1 6 21 22 package de.schlichtherle.nio.charset; 23 24 import java.nio.ByteBuffer ; 25 import java.nio.CharBuffer ; 26 import java.nio.charset.Charset ; 27 import java.nio.charset.CharsetDecoder ; 28 import java.nio.charset.CharsetEncoder ; 29 import java.nio.charset.CoderResult ; 30 import java.util.Arrays ; 31 32 38 public abstract class OctetCharset extends Charset { 39 40 44 protected static final char REPLACEMENT = '\uFFFD'; 45 46 private final char[] byte2char; 47 private final char[][] char2byte; 48 49 protected OctetCharset(String cname, String [] aliases, char[] byte2char) { 50 super(cname, aliases); 51 52 final char[][] char2byte = new char[256][]; 54 for (char i = 0; i < 256; i++) { 55 final char c = byte2char[i]; 56 if (c == REPLACEMENT) 57 continue; 58 59 final int high = c >> 8; char[] table = char2byte[high]; 61 if (table == null) { 62 table = new char[256]; 63 Arrays.fill(table, REPLACEMENT); 64 char2byte[high] = table; 65 } 66 table[c & 0xFF] = i; 67 } 68 69 this.byte2char = byte2char; 70 this.char2byte = char2byte; 71 } 72 73 public boolean contains(Charset cs) { 74 return this.getClass().isInstance(cs); 75 } 76 77 public CharsetEncoder newEncoder() { 78 return new Encoder (); 79 } 80 81 protected class Encoder extends CharsetEncoder { 82 83 protected Encoder() { 84 super(OctetCharset.this, 1, 1); 85 } 86 87 protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { 88 final char[][] c2b = char2byte; 89 while (in.hasRemaining()) { 90 if (!out.hasRemaining()) 91 return CoderResult.OVERFLOW; 92 final char c = in.get(); 93 final char[] table = c2b[c >> 8]; final char b; 95 if (table == null || (b = table[c & 0xFF]) == REPLACEMENT) { 96 in.position(in.position() - 1); return CoderResult.unmappableForLength(1); 98 } 99 out.put((byte)(b & 0xFF)); 100 } 101 return CoderResult.UNDERFLOW; 102 } 103 } 104 105 public CharsetDecoder newDecoder() { 106 return new Decoder (); 107 } 108 109 protected class Decoder extends CharsetDecoder { 110 111 protected Decoder() { 112 super(OctetCharset.this, 1, 1); 113 } 114 115 protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { 116 final char[] b2c = byte2char; 117 while (in.hasRemaining()) { 118 if (!out.hasRemaining()) 119 return CoderResult.OVERFLOW; 120 final char c = b2c[in.get() & 0xFF]; 121 if (c == REPLACEMENT) { 122 in.position(in.position() - 1); return CoderResult.unmappableForLength(1); 124 } 125 out.put(c); 126 } 127 return CoderResult.UNDERFLOW; 128 } 129 } 130 } 131 | Popular Tags |