package ch.tkuhn.memetools;

import java.util.ArrayList;
import java.util.List;

public class IntStringMap {

	private static final int MAX_POS = 2000000000;

	private List<String> data = new ArrayList<String>();
	private long[] startPos;
	private int[] length;

	private StringBuilder sb = new StringBuilder();

	private boolean frozen = false;

	public IntStringMap(int size) {
		startPos = new long[size];
		length = new int[size];
		sb.append(" ");
	}

	public void put(int key, String value) {
		if (frozen) {
			throw new RuntimeException("Frozen");
		}
		int l = value.length();
		if (sb.length() + l >= MAX_POS) {
			data.add(sb.toString());
			sb = new StringBuilder();
		}
		long s = MAX_POS*data.size() + sb.length();
		sb.append(value);
		startPos[key] = s;
		length[key] = l;
	}

	public String get(int key) {
		if (!frozen) {
			throw new RuntimeException("Not yet frozen");
		}
		long s = startPos[key];
		if (s == 0) return null;
		int l = length[key];
		int subpos = (int) (s % MAX_POS);
		return data.get((int) (s / MAX_POS)).substring(subpos, subpos + l);
	}

	public void freeze() {
		frozen = true;
		data.add(sb.toString());
		sb = null;
	}

}

@@ -742,16 +742,162 @@
 value);%0A
+%09%09if (s %3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative start position%22);%0A%09%09%7D%0A%09%09if (l %3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative length%22);%0A%09%09%7D%0A
 %09%09startP
@@ -1070,85 +1070,434 @@
  (s 
-== 0) return null;%0A%09%09int l = length%5Bkey%5D;%0A%09%09int subpos = (int) (s %25 MAX_POS);
+%3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative start position%22);%0A%09%09%7D%0A%09%09if (s == 0) return null;%0A%09%09int l = length%5Bkey%5D;%0A%09%09if (l %3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative length%22);%0A%09%09%7D%0A%09%09int subpos = (int) (s %25 MAX_POS);%0A%09%09int subposEnd = subpos + l;%0A%09%09if (subpos %3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative sub-position start%22);%0A%09%09%7D%0A%09%09if (subposEnd %3C 0) %7B%0A%09%09%09throw new RuntimeException(%22Negative sub-position end%22);%0A%09%09%7D
 %0A%09%09r
@@ -1556,20 +1556,19 @@
 , subpos
- + l
+End
 );%0A%09%7D%0A%0A%09

Throw exceptions for debugging