1 5 package org.h2.test.unit; 6 7 import java.io.ByteArrayInputStream ; 8 import java.io.ByteArrayOutputStream ; 9 import java.util.Random ; 10 11 import org.h2.compress.LZFInputStream; 12 import org.h2.compress.LZFOutputStream; 13 import org.h2.test.TestBase; 14 15 public class TestStreams extends TestBase { 16 17 public void test() throws Exception { 18 testLZFStreams(); 19 } 20 21 byte[] getRandomBytes(Random random) { 22 int[] sizes = new int[]{0, 1, random.nextInt(1000), random.nextInt(100000), random.nextInt(1000000)}; 23 int size = sizes[random.nextInt(sizes.length)]; 24 byte[] buffer = new byte[size]; 25 if(random.nextInt(5) == 1) { 26 random.nextBytes(buffer); 27 } else if(random.nextBoolean()) { 28 int patternLen = random.nextInt(100)+1; 29 for(int j=0; j<size; j++) { 30 buffer[j] = (byte)(j % patternLen); 31 } 32 } 33 return buffer; 34 } 35 36 private void testLZFStreams() throws Exception { 37 Random random = new Random (1); 38 int max = getSize(100, 1000); 39 for(int i=0; i<max; i+=3) { 40 byte[] buffer = getRandomBytes(random); 41 ByteArrayOutputStream out = new ByteArrayOutputStream (); 42 LZFOutputStream comp = new LZFOutputStream(out); 43 if(random.nextInt(10) == 1) { 44 comp.write(buffer); 45 } else { 46 for(int j=0; j<buffer.length;) { 47 int[] sizes = new int[]{0, 1, random.nextInt(100), random.nextInt(100000)}; 48 int size = sizes[random.nextInt(sizes.length)]; 49 size = Math.min(size, buffer.length - j); 50 if(size == 1) { 51 comp.write(buffer[j]); 52 } else { 53 comp.write(buffer, j, size); 54 } 55 j+=size; 56 } 57 } 58 comp.close(); 59 byte[] compressed = out.toByteArray(); 60 ByteArrayInputStream in = new ByteArrayInputStream (compressed); 61 LZFInputStream decomp = new LZFInputStream(in); 62 byte[] test = new byte[buffer.length]; 63 for(int j=0; j<buffer.length;) { 64 int[] sizes = new int[]{0, 1, random.nextInt(100), random.nextInt(100000)}; 65 int size = sizes[random.nextInt(sizes.length)]; 66 if(size == 1) { 67 int x = decomp.read(); 68 if(x < 0) { 69 break; 70 } 71 test[j++] = (byte)x; 72 } else { 73 size = Math.min(size, test.length-j); 74 int l = decomp.read(test, j, size); 75 if(l < 0) { 76 break; 77 } else { 78 j += l; 79 } 80 } 81 } 82 check(buffer, test); 83 } 84 } 85 86 } 87 | Popular Tags |