OLD | NEW |
| (Empty) |
1 // Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE.md file. | |
4 | |
5 package dartino; | |
6 | |
7 import java.nio.ByteBuffer; | |
8 import java.nio.charset.Charset; | |
9 | |
10 class Reader { | |
11 public Reader() { } | |
12 | |
13 public Reader(byte[] memory, int offset) { | |
14 segment = new Segment(memory); | |
15 base = offset; | |
16 } | |
17 | |
18 public Reader(Segment segment, int offset) { | |
19 this.segment = segment; | |
20 base = offset; | |
21 } | |
22 | |
23 public Reader(byte[][] segments, int offset) { | |
24 MessageReader reader = new MessageReader(segments); | |
25 segment = reader.getSegment(0); | |
26 base = offset; | |
27 } | |
28 | |
29 public Reader readStruct(Reader reader, int offset) { | |
30 Segment s = segment; | |
31 offset += base; | |
32 while (true) { | |
33 ByteBuffer buffer = s.buffer(); | |
34 int lo = buffer.getInt(offset + 0); | |
35 int hi = buffer.getInt(offset + 4); | |
36 int tag = lo & 3; | |
37 if (tag == 0) { | |
38 // Cannot read uninitialized structs. | |
39 System.exit(1); | |
40 } else if (tag == 1) { | |
41 reader.segment = s; | |
42 reader.base = lo >> 2; | |
43 return reader; | |
44 } else { | |
45 s = s.reader().getSegment(hi); | |
46 offset = lo >> 2; | |
47 } | |
48 } | |
49 } | |
50 | |
51 public ListReader readList(ListReader reader, int offset) { | |
52 Segment s = segment; | |
53 offset += base; | |
54 while (true) { | |
55 ByteBuffer buffer = s.buffer(); | |
56 int lo = buffer.getInt(offset + 0); | |
57 int hi = buffer.getInt(offset + 4); | |
58 int tag = lo & 3; | |
59 if (tag == 0) { | |
60 // If the list hasn't been initialized we return an empty | |
61 // list. | |
62 reader.length = 0; | |
63 return reader; | |
64 } else if (tag == 1) { | |
65 reader.segment = s; | |
66 reader.base = lo >> 2; | |
67 reader.length = hi; | |
68 return reader; | |
69 } else { | |
70 s = s.reader().getSegment(hi); | |
71 offset = lo >> 2; | |
72 } | |
73 } | |
74 } | |
75 | |
76 public String readString(int offset) { | |
77 ListReader reader = new ListReader(); | |
78 readList(reader, offset); | |
79 byte[] data = reader.segment.buffer().array(); | |
80 int byteLength = reader.length * 2; | |
81 return new String( | |
82 data, reader.base, byteLength, Charset.forName("UTF_16LE")); | |
83 } | |
84 | |
85 public int computeUsed() { | |
86 MessageReader reader = segment.reader(); | |
87 int used = 0; | |
88 for (int i = 0; i < reader.segmentCount(); i++) { | |
89 used += reader.getSegment(i).buffer().capacity(); | |
90 } | |
91 return used; | |
92 } | |
93 | |
94 protected Segment segment; | |
95 protected int base; | |
96 } | |
OLD | NEW |