summaryrefslogtreecommitdiff
path: root/src/ion.rs
blob: cbfae2495e3aaa5f50fc9a0f443e8c8f1c207b44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::{iter::Copied, cmp::Ordering};

pub enum IonType {
    Null = 0x00,
    Bool = 0x01,
    IntPos = 0x02,
    IntNeg= 0x03,
    Float = 0x04,
    Decimal = 0x05,
    Timestamp = 0x06,
    Symbol = 0x07,
    String = 0x08,
    Clob = 0x09,
    Blob = 0x0a,
    List = 0x0b,
    Sexp = 0x0c,
    Struct = 0x0d,
    Annotations = 0x0e,
}

#[derive(PartialOrd, PartialEq)]
pub struct IonValue(Vec<u8>);

impl IonValue {
    pub fn new_null() -> IonValue {
        IonValue(vec![0x0F])
    }

    pub fn new_symbol(value: usize) -> IonValue {
        let mut buf = Vec::new();
        if value == 0 {
            buf.push(0x70);
        } else {
            let octets = ((usize::BITS - value.leading_zeros() + 7) >> 3) as usize;
            let tl = 0x70 | octets as u8;
            buf.push(tl);
            let be = value.to_be_bytes();
            let start = be.len() - octets;
            for b in &be[start..] {
                buf.push(*b);
            }
        }
        IonValue(buf)
    }

    pub fn new_f64(value: f64) -> IonValue {
        let b = value.to_be_bytes();
        IonValue(vec![0x48, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
    }

    pub fn new_i32(value: i32) -> IonValue {
        IonValue::from(value as i64)
    }

    pub fn new_bool(value: bool) -> IonValue {
        if value {
            IonValue(vec![0x11])
        } else {
            IonValue(vec![0x10])
        }
    }

    pub fn new_string<S>(value: S) -> IonValue
    where S: AsRef<str> 
    {
        let bytes = value.as_ref().as_bytes();
        let mut v = Vec::with_capacity(2 + bytes.len());
        if bytes.len() < 14 {
            v.push(0x80 | (bytes.len() as u8));
        } else {
            v.push(0x8E);
            push_varuint(&mut v, bytes.len());
        }
        v.extend(bytes);
        IonValue(v)
    }


    pub fn ion_type(&self) -> u8 {
        self.0[0] >> 4
    }

    pub fn len(&self) -> usize {
        // TODO: Should this read the type length?
        self.0.len()
    }

    pub fn repr_offset(&self) -> usize {
        let mut reader = self.reader();
        let tl = reader.next_byte();
        let _len = reader.extract_length(tl);
        reader.offset()
    }

    pub fn bytes(&self) -> impl DoubleEndedIterator<Item = u8> + '_ {
        self.0.iter().copied()
    }

    pub fn reader(&self) -> IonReader<impl DoubleEndedIterator<Item = u8> + '_> {
        IonReader::new(self.0.iter().copied(), 0)
    }

    pub fn reader_at(&self, offset: usize) -> IonReader<Copied<std::slice::Iter<'_, u8>>> {
        IonReader::new(self.0[offset..].iter().copied(), offset)
    }

    pub fn struct_reader_at(&self, offset: usize) -> IonReader<Copied<std::slice::Iter<'_, u8>>> {
        IonReader::new_struct(self.0[offset..].iter().copied(), offset)
    }

    pub fn to_usize(&self) -> usize {
        self.reader().next_usize()
    }

    pub fn to_symbol_id(&self) -> usize {
        self.reader().next_symbol_id()
    }

}

impl From<Vec<u8>> for IonValue {
    fn from(value: Vec<u8>) -> Self {
        if value.len() > 0 {
            IonValue(value)
        } else {
            IonValue(vec![0x0F])
        }
    }
}

impl From<usize> for IonValue {
    fn from(value: usize) -> Self {
        let mut buf = Vec::new();
        if value == 0 {
            buf.push(0x20);
        } else {
            let v = value;
            let octets = ((usize::BITS - v.leading_zeros() + 7) >> 3) as usize;
            let tl = 0x20 | octets as u8;
            buf.push(tl);
            let be = v.to_be_bytes();
            let start = be.len() - octets;
            for b in &be[start..] {
                buf.push(*b);
            }
        }
        IonValue(buf)
    }
}

impl From<i64> for IonValue {
    fn from(value: i64) -> Self {
        let mut buf = Vec::new();
        let (mut tl, v) = match value.cmp(&0) {
            Ordering::Equal => return IonValue(vec![0x20]),
            Ordering::Greater => (0x20, value),
            Ordering::Less => (0x30, -value),
        };

        let octets = ((usize::BITS - v.leading_zeros() + 7) >> 3) as usize;
        tl |= octets as u8;
        buf.push(tl);
        let be = v.to_be_bytes();
        let start = be.len() - octets;
        for b in &be[start..] {
            buf.push(*b);
        }
        IonValue(buf)
    }
}


pub struct IonReader<T> {
    iter: T,
    offset: usize,
    is_struct: bool,
    field_name: Option<usize>,
}

impl <T> IonReader<T>
    where T: Iterator<Item = u8>
{
    pub fn new(iter: T, offset: usize) -> IonReader<T> {
        IonReader {
            iter,
            offset,
            is_struct: false,
            field_name: None,
        }
    }

    pub fn new_struct(iter: T, offset: usize) -> IonReader<T> {
        IonReader {
            iter,
            offset,
            is_struct: true,
            field_name: None,
        }
    }

    pub fn offset(&self) -> usize {
        self.offset
    }

    pub fn field_id(&self) -> Option<usize> {
        self.field_name
    }

    /// Move the iterator to the first nested value.
    pub fn step_in(&mut self) -> (u8, usize) {
        self.prepare_next();
        let tl = self.next_byte();
        let len = self.extract_length(tl);
        if (tl & 0xF0) == 0xD0 {
            self.is_struct = true;
        }
        (tl >> 4, self.offset + len)
    }

    fn prepare_next(&mut self) {
        if self.is_struct {
            // TODO: symbol length can be greater than max usize.
            self.field_name = Some(self.next_varuint());
        }
    }

    pub fn skip_value(&mut self) {
        self.prepare_next();
        let tl = self.next_byte();
        let len = self.extract_length(tl);
        for _ in 0..len {
            self.next_byte();
        }
    }

    pub fn next_value(&mut self) -> IonValue {
        self.prepare_next();
        let tl = self.next_byte();
        let (mut buf, len) = match tl & 0xF0 {
            0x10 => (vec![tl], 0), // bool
            0xD0 => { // struct
                match tl & 0x0F {
                    0 | 15 => (vec![tl], 0),
                    1 | 14 => {
                        let l = self.next_varuint();
                        let mut v = Vec::with_capacity(5 + l);
                        v.push(tl);
                        push_varuint(&mut v, l);
                        (v, l)
                    },
                    len => {
                        let l = len.into();
                        let mut v = Vec::with_capacity(5 + l);
                        v.push(tl);
                        (v, l)
                    }
                }
            },
            0x00 | 0x20 | 0x30 | 0x40 |
                0x50 | 0x60 | 0x70 | 0x80 |
                0x90 | 0xA0 | 0xB0 | 0xC0 |
                0xE0 =>
            {
                match tl & 0x0F {
                    0 | 15 => (vec![tl], 0),
                    14 => {
                        let l = self.next_varuint();
                        let mut v = Vec::with_capacity(5 + l);
                        v.push(tl);
                        push_varuint(&mut v, l);
                        (v, l)
                    },
                    len => {
                        let l = len.into();
                        let mut v = Vec::with_capacity(5 + l);
                        v.push(tl);
                        (v, l)
                    }
                }
            },
            _ => panic!("unsupported ion type"),
        };
        for _ in 0..len {
            let b = self.next_byte();
            buf.push(b);
        }
        buf.into()
    }

    pub fn next_usize(&mut self) -> usize {
        self.prepare_next();
        let tl = self.next_byte();
        if tl & 0xF0 != 0x20 {
            panic!("Not a positive integer");
        }

        let len = self.extract_length(tl);
        if len * 8 > usize::BITS as usize {
            panic!("Integer too large for usize");
        }

        let mut value = 0;
        for _ in 0..len {
            let b = self.next_byte();
            value <<= 8;
            value |= b as usize;
        }
        value
    }

    pub fn next_symbol_id(&mut self) -> usize {
        self.prepare_next();
        let tl = self.next_byte();
        if tl & 0xF0 != 0x70 {
            panic!("Not a symbol");
        }

        let len = self.extract_length(tl);
        if len * 8 > usize::BITS as usize {
            panic!("Symbol id too large for usize");
        }

        let mut value = 0;
        for _ in 0..len {
            let b = self.next_byte();
            value <<= 8;
            value |= b as usize;
        }
        value
    }


    fn next_byte(&mut self) -> u8 {
        self.offset += 1;
        self.iter.next().expect("Missing data")
    }

    fn extract_length(&mut self, tl: u8) -> usize {
        match tl & 0xF0 {
            0x10 => 0, // bool
            0xD0 => { // struct
                match tl & 0x0F {
                    0 | 15 => 0,
                    1 | 14 => self.next_varuint(),
                    len => len.into(),
                }
            },
            0x00 | 0x20 | 0x30 | 0x40 |
                0x50 | 0x60 | 0x70 | 0x80 |
                0x90 | 0xA0 | 0xB0 | 0xC0 |
                0xE0 =>
            {
                match tl & 0x0F {
                    0 | 15 => 0,
                    14 => self.next_varuint(),
                    len => len.into(),
                }
            }
            _ => panic!("Unsupported Ion type"),
        }
    }

    fn next_varuint(&mut self) -> usize {
        let mut v: usize = 0;
        while let Some(b) = self.iter.next() {
            self.offset += 1;
            v <<= 7;
            v |= (b & 0x7f) as usize;
            if b & 0x80 != 0 {
                return v;
            }
        }
        panic!("Truncated varuint");
    }
}

fn push_varuint(v: &mut Vec<u8>, mut value: usize) {
    let mut buf = [0; (usize::BITS / 7 + 1) as usize];
    let mut pos = 0;
    while value != 0 {
        buf[pos] = (value & 0x7F) as u8;
        value >>= 7;
        pos += 1;
    }
    buf[0] |= 0x80;
    pos = pos.max(1);

    for i in (0..pos).rev() {
        v.push(buf[i]);
    }
}

fn parse_varuint(buf: &[u8]) -> usize {
    let mut value: usize = 0;
    for b in buf {
        value <<= 7;
        value |= (b & 0x7F) as usize;
        if b & 0x80 != 0 {
            break;
        }
    }
    value
}