01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.test.unit;
07:
08: import java.io.ByteArrayInputStream;
09: import java.io.ByteArrayOutputStream;
10: import java.util.Random;
11:
12: import org.h2.compress.LZFInputStream;
13: import org.h2.compress.LZFOutputStream;
14: import org.h2.test.TestBase;
15:
16: /**
17: * Tests the LZF stream.
18: */
19: public class TestStreams extends TestBase {
20:
21: public void test() throws Exception {
22: testLZFStreams();
23: }
24:
25: byte[] getRandomBytes(Random random) {
26: int[] sizes = new int[] { 0, 1, random.nextInt(1000),
27: random.nextInt(100000), random.nextInt(1000000) };
28: int size = sizes[random.nextInt(sizes.length)];
29: byte[] buffer = new byte[size];
30: if (random.nextInt(5) == 1) {
31: random.nextBytes(buffer);
32: } else if (random.nextBoolean()) {
33: int patternLen = random.nextInt(100) + 1;
34: for (int j = 0; j < size; j++) {
35: buffer[j] = (byte) (j % patternLen);
36: }
37: }
38: return buffer;
39: }
40:
41: private void testLZFStreams() throws Exception {
42: Random random = new Random(1);
43: int max = getSize(100, 1000);
44: for (int i = 0; i < max; i += 3) {
45: byte[] buffer = getRandomBytes(random);
46: ByteArrayOutputStream out = new ByteArrayOutputStream();
47: LZFOutputStream comp = new LZFOutputStream(out);
48: if (random.nextInt(10) == 1) {
49: comp.write(buffer);
50: } else {
51: for (int j = 0; j < buffer.length;) {
52: int[] sizes = new int[] { 0, 1,
53: random.nextInt(100), random.nextInt(100000) };
54: int size = sizes[random.nextInt(sizes.length)];
55: size = Math.min(size, buffer.length - j);
56: if (size == 1) {
57: comp.write(buffer[j]);
58: } else {
59: comp.write(buffer, j, size);
60: }
61: j += size;
62: }
63: }
64: comp.close();
65: byte[] compressed = out.toByteArray();
66: ByteArrayInputStream in = new ByteArrayInputStream(
67: compressed);
68: LZFInputStream decompress = new LZFInputStream(in);
69: byte[] test = new byte[buffer.length];
70: for (int j = 0; j < buffer.length;) {
71: int[] sizes = new int[] { 0, 1, random.nextInt(100),
72: random.nextInt(100000) };
73: int size = sizes[random.nextInt(sizes.length)];
74: if (size == 1) {
75: int x = decompress.read();
76: if (x < 0) {
77: break;
78: }
79: test[j++] = (byte) x;
80: } else {
81: size = Math.min(size, test.length - j);
82: int l = decompress.read(test, j, size);
83: if (l < 0) {
84: break;
85: } else {
86: j += l;
87: }
88: }
89: }
90: check(buffer, test);
91: }
92: }
93:
94: }
|