1 31 package org.pdfbox.filter; 32 33 import java.io.ByteArrayOutputStream ; 34 import java.io.IOException ; 35 36 import java.util.HashMap ; 37 import java.util.Map ; 38 39 46 class LZWDictionary 47 { 48 private Map codeToData = new HashMap (); 49 private LZWNode root = new LZWNode(); 50 51 private ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 52 private long nextCode = 258; 53 private int codeSize = 9; 54 55 58 public LZWDictionary() 59 { 60 for( long i=0; i<256; i++ ) 61 { 62 LZWNode node = new LZWNode(); 63 node.setCode( i ); 64 root.setNode( (byte)i, node ); 65 codeToData.put( new Long ( i ), new byte[]{ (byte)i } ); 66 } 67 } 68 69 77 public byte[] getData( long code ) 78 { 79 return (byte[])codeToData.get( new Long ( code ) ); 80 } 81 82 90 public void visit( byte[] data ) throws IOException 91 { 92 for( int i=0; i<data.length; i++ ) 93 { 94 visit( data[i] ); 95 } 96 } 97 98 106 public void visit( byte data ) throws IOException 107 { 108 buffer.write( data ); 109 byte[] curBuffer = buffer.toByteArray(); 110 LZWNode previous = null; 111 LZWNode current = root; 112 boolean createNewCode = false; 113 for( int i=0; i<curBuffer.length && current != null; i++ ) 114 { 115 previous = current; 116 current = current.getNode( curBuffer[i] ); 117 if( current == null ) 118 { 119 createNewCode = true; 120 current = new LZWNode(); 121 previous.setNode( curBuffer[i], current ); 122 } 123 } 124 if( createNewCode ) 125 { 126 long code = nextCode++; 127 current.setCode( code ); 128 codeToData.put( new Long ( code ), curBuffer ); 129 130 147 buffer.reset(); 148 buffer.write( data ); 149 resetCodeSize(); 150 } 151 } 152 153 158 public long getNextCode() 159 { 160 return nextCode; 161 } 162 163 168 public int getCodeSize() 169 { 170 return codeSize; 171 } 172 173 176 private void resetCodeSize() 177 { 178 if( nextCode >= 2048 ) 179 { 180 codeSize = 12; 181 } 182 else if( nextCode >= 1024 ) 183 { 184 codeSize = 11; 185 } 186 else if( nextCode >= 512 ) 187 { 188 codeSize = 10; 189 } 190 else 191 { 192 codeSize = 9; 193 } 194 } 195 196 199 public void clear() 200 { 201 buffer.reset(); 202 } 203 204 211 public LZWNode getNode( byte[] data ) 212 { 213 return root.getNode( data ); 214 } 215 } | Popular Tags |