Debian Codegraph @

src/test/java/com/fasterxml/jackson/dataformat/smile/TestGeneratorLongStrings.java

raw
1 package com.fasterxml.jackson.dataformat.smile;
2
3 import java.io.*;
4 import java.util.*;
5
6 import com.fasterxml.jackson.core.*;
7
8 import com.fasterxml.jackson.dataformat.smile.SmileFactory;
9 import com.fasterxml.jackson.dataformat.smile.SmileGenerator;
10
11 public class TestGeneratorLongStrings extends SmileTestBase
12 {
13 final static int DOC_LEN = 2000000; // 2 meg test doc
14
15 public void testLongWithMultiBytes() throws Exception
16 {
17 SmileFactory f = new SmileFactory();
18 ArrayList<String> strings = new ArrayList<String>();
19 Random rnd = new Random(123);
20
21 ByteArrayOutputStream out = new ByteArrayOutputStream(DOC_LEN);
22 SmileGenerator gen = f.createGenerator(out);
23 gen.writeStartArray();
24
25 // Let's create 1M doc, first using Strings
26 while (out.size() < (DOC_LEN - 10000)) {
27 String str = generateString(5000, rnd);
28 strings.add(str);
29 gen.writeString(str);
30 }
31 gen.writeEndArray();
32 gen.close();
33 // Written ok; let's try parsing then
34 _verifyStrings(f, out.toByteArray(), strings);
35
36 // Then same with char[]
37 out = new ByteArrayOutputStream(DOC_LEN);
38 gen = f.createGenerator(out);
39 gen.writeStartArray();
40
41 // Let's create 1M doc, first using Strings
42 for (int i = 0, len = strings.size(); i < len; ++i) {
43 char[] ch = strings.get(i).toCharArray();
44 gen.writeString(ch, 0, ch.length);
45 }
46 gen.writeEndArray();
47 gen.close();
48 _verifyStrings(f, out.toByteArray(), strings);
49 }
50
51 /*
52 /**********************************************************
53 /* Helper methods
54 /**********************************************************
55 */
56
57 protected String generateString(int length, Random rnd) throws Exception
58 {
59 StringBuilder sw = new StringBuilder(length+10);
60 do {
61 // First, add 7 ascii characters
62 int num = 4 + (rnd.nextInt() & 7);
63 while (--num >= 0) {
64 sw.append((char) ('A' + num));
65 }
66 // Then a unicode char of 2, 3 or 4 bytes long
67 switch (rnd.nextInt() % 3) {
68 case 0:
69 sw.append((char) (256 + rnd.nextInt() & 511));
70 break;
71 case 1:
72 sw.append((char) (2048 + rnd.nextInt() & 4095));
73 break;
74 default:
75 sw.append((char) (65536 + rnd.nextInt() & 0x3FFF));
76 break;
77 }
78 } while (sw.length() < length);
79 return sw.toString();
80 }
81
82 private void _verifyStrings(JsonFactory f, byte[] input, List<String> strings)
83 throws IOException
84 {
85 JsonParser jp = f.createParser(input);
86 assertToken(JsonToken.START_ARRAY, jp.nextToken());
87 for (int i = 0, len = strings.size(); i < len; ++i) {
88 assertToken(JsonToken.VALUE_STRING, jp.nextToken());
89 assertEquals(strings.get(i), jp.getText());
90 }
91 assertToken(JsonToken.END_ARRAY, jp.nextToken());
92 jp.close();
93 }
94 }