package org.capnproto;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public final class Text {

    public static final class Reader {
        public final ByteBuffer buffer;
        public final int offset; // in bytes
        public final int size; // in bytes, not including NUL terminator

        public Reader(ByteBuffer buffer, int offset, int size) {
            this.buffer = buffer;
            this.offset = offset * 8;
            this.size = size;
        }

        public Reader(String value) {
            try {
                byte[] bytes = value.getBytes(StandardCharsets.UTF_8.name());
                this.buffer = ByteBuffer.wrap(bytes);
                this.offset = 0;
                this.size = bytes.length;
            } catch (java.io.UnsupportedEncodingException e) {
                throw new Error("UTF-8 is unsupported");
            }
        }

        @Override
        public final String toString() {
            byte[] bytes = new byte[this.size];

            this.buffer.position(this.offset);
            this.buffer.get(bytes, 0, this.size);

            try {
                return new String(bytes, StandardCharsets.UTF_8.name());
            } catch (java.io.UnsupportedEncodingException e) {
                return "unsupported encoding"; // XXX
            }
        }

    }

    public static final class Builder {
        public final ByteBuffer buffer;
        public final int offset;

        // size not including the NUL terminator
        public final int size;

        public Builder(ByteBuffer buffer, int offset, int size) {
            this.buffer = buffer;
            this.offset = offset;
            this.size = size;
        }

        @Override
        public final String toString() {
            byte[] bytes = new byte[this.size];

            this.buffer.position(this.offset);
            this.buffer.get(bytes, 0, this.size);

            try {
                return new String(bytes, StandardCharsets.UTF_8.name());
            } catch (java.io.UnsupportedEncodingException e) {
                return "unsupported encoding"; // XXX
            }
        }

    }

}

@@ -48,50 +48,8 @@
 fer;
-%0Aimport java.nio.charset.StandardCharsets;
 %0A%0Apu
@@ -555,37 +555,15 @@
 tes(
-StandardCharsets.UTF_8.name()
+%22UTF-8%22
 );%0A 
@@ -1104,37 +1104,15 @@
 es, 
-StandardCharsets.UTF_8.name()
+%22UTF-8%22
 );%0A 
@@ -1898,37 +1898,15 @@
 es, 
-StandardCharsets.UTF_8.name()
+%22UTF-8%22
 );%0A 

make compatible with java 6 once again