package me.akuz.core;

/**
 * Circular character buffer.
 * @author andrey
 *
 */
public final class CharBuffer {
	
	private final byte[] _tmp;
	private final byte[] _data;
	private int _cursor;
	
	public CharBuffer(int size) {
		if (size < 3) {
			throw new IllegalArgumentException("Size must >= 3");
		}
		_tmp = new byte[3];
		_data = new byte[size];
		_cursor = -1;
	}
	
	public void add(char ch) {
		byte[] bytes = getBytes(ch);
		for (int i=bytes.length-1; i>=0; i--) {
			_cursor = (_cursor + 1) % _data.length;
			_data[_cursor] = bytes[i];
		}
	}
	
	public String get() {
		
		if (_cursor < 0) {
			return "";
		}
		
		int cursor = _cursor;
		int startCursor = cursor;
		StringBuffer sb = new StringBuffer();
		
		while (true) {
			
			int len = ((_data[cursor] >> 6) & 3);
			
			if (len == 0) {
				break; // nothing more in buffer
			}

			for (int i=0; i<len; i--) {
				
				// copy byte for char creation
				_tmp[i] = _data[cursor];
				
				if (i<len-1) {
					
					cursor--;
					if (cursor < 0) {
						cursor = _data.length-1;
					}
					
					// check if reached start cursor
					if (cursor == startCursor) {
						break;
					}
				}
			}
			
			// check if reached start cursor
			if (cursor == startCursor) {
				break;
			}
			
			// convert to char from bytes
			char ch = getChar(_tmp, len);
			sb.append(ch);
		}
		
		// reverse and to string
		return sb.reverse().toString();
	}
	
	/**
	 * Return bytes array from char.
	 * @param ch - character
	 * @return
	 */
	private static final byte[] getBytes(char ch) {
		return null; // TODO
	}
	
	/**
	 * Return char from bytes, given the length (bytes array can be longer than length).
	 * @param bs - bytes array
	 * @param len - number of bytes to convert to char
	 * @return
	 */
	private static final char getChar(byte[] bs, int len) {
		return 0; // TODO
	}

}

@@ -626,17 +626,20 @@
 %09%0A%09%09int 
-c
+tmpC
 ursor = 
@@ -649,16 +649,22 @@
 rsor;%0A%09%09
+final 
 int star
@@ -673,17 +673,20 @@
 ursor = 
-c
+tmpC
 ursor;%0A%09
@@ -686,16 +686,22 @@
 rsor;%0A%09%09
+final 
 StringBu
@@ -757,16 +757,22 @@
 %0A%09%09%09%0A%09%09%09
+final 
 int len 
@@ -777,25 +777,28 @@
 n = ((_data%5B
-c
+tmpC
 ursor%5D %3E%3E 6)
@@ -961,17 +961,20 @@
 = _data%5B
-c
+tmpC
 ursor%5D;%0A
@@ -974,24 +974,58 @@
 rsor%5D;%0A%09%09%09%09%0A
+%09%09%09%09// if more bytes in this char%0A
 %09%09%09%09if (i%3Cle
@@ -1038,25 +1038,41 @@
 %0A%09%09%09%09%09%0A%09%09%09%09%09
-c
+// move%0A%09%09%09%09%09tmpC
 ursor--;%0A%09%09%09
@@ -1073,25 +1073,28 @@
 -;%0A%09%09%09%09%09if (
-c
+tmpC
 ursor %3C 0) %7B
@@ -1100,17 +1100,20 @@
 %7B%0A%09%09%09%09%09%09
-c
+tmpC
 ursor = 
@@ -1184,25 +1184,28 @@
 or%0A%09%09%09%09%09if (
-c
+tmpC
 ursor == sta
@@ -1294,17 +1294,20 @@
 %0A%09%09%09if (
-c
+tmpC
 ursor ==

Update CharBuffer