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
405
406
407
408
409
410
411
412
413
414
use std::io;
use std::ops::Range;

use delegate::delegate;

use crate::constants::v1_0::system_symbol_ids;
use crate::raw_reader::{RawReader, RawStreamItem};
use crate::raw_symbol_token::RawSymbolToken;
use crate::result::{decoding_error, decoding_error_raw, IonResult};
use crate::stream_reader::StreamReader;
use crate::symbol_table::{Symbol, SymbolTable};
use crate::types::decimal::Decimal;
use crate::types::timestamp::Timestamp;
use crate::{IonType, RawBinaryReader};

/// A streaming Ion reader that resolves symbol IDs into their corresponding text.
///
/// Reader itself is format-agnostic; all format-specific logic is handled by the
/// wrapped [RawReader] implementation.
pub struct Reader<R: RawReader> {
    raw_reader: R,
    symbol_table: SymbolTable,
}

/// Stream components that an application-level [Reader] implementation may encounter.
#[derive(Eq, PartialEq, Debug)]
pub enum StreamItem {
    /// A non-null Ion value and its corresponding Ion data type.
    Value(IonType),
    /// A null Ion value and its corresponding Ion data type.
    Null(IonType),
    /// Indicates that the reader is not positioned over anything. This can happen:
    /// * before the reader has begun processing the stream.
    /// * after the reader has stepped into a container, but before the reader has called next()
    /// * after the reader has stepped out of a container, but before the reader has called next()
    /// * after the reader has read the last item in a container
    Nothing,
}

impl<R: RawReader> Reader<R> {
    pub fn new(raw_reader: R) -> Reader<R> {
        Reader {
            raw_reader,
            symbol_table: SymbolTable::new(),
        }
    }

    pub fn read_raw_symbol(&mut self) -> IonResult<RawSymbolToken> {
        self.raw_reader.read_symbol()
    }

    pub fn raw_field_name_token(&mut self) -> IonResult<RawSymbolToken> {
        self.raw_reader.field_name()
    }

    fn read_symbol_table(&mut self) -> IonResult<()> {
        self.raw_reader.step_in()?;

        let mut is_append = false;
        let mut new_symbols = vec![];

        loop {
            let ion_type = match self.raw_reader.next()? {
                RawStreamItem::Value(ion_type) => ion_type,
                RawStreamItem::Null(_) => continue,
                RawStreamItem::Nothing => break,
                RawStreamItem::VersionMarker(major, minor) => {
                    return decoding_error(format!(
                        "encountered Ion version marker for v{}.{} in symbol table",
                        major, minor
                    ))
                }
            };

            let field_id = self
                .raw_reader
                .field_name()
                .expect("No field ID found inside $ion_symbol_table struct.");
            match (field_id, ion_type) {
                // The field name is either SID 6 or the text 'imports' and the
                // field value is a non-null symbol
                (symbol, IonType::Symbol)
                    if symbol.matches(system_symbol_ids::IMPORTS, "imports") =>
                {
                    // TODO: SST imports. This implementation only supports local symbol
                    //       table imports and appends.
                    let import_symbol = self.raw_reader.read_symbol()?;
                    if !import_symbol.matches(3, "$ion_symbol_table") {
                        unimplemented!("Can't handle non-$ion_symbol_table imports value.");
                    }
                    is_append = true;
                }
                // The field name is either SID 7 or the text 'imports' and the
                // field value is a non-null list
                (symbol, IonType::List)
                    if symbol.matches(system_symbol_ids::SYMBOLS, "symbols") =>
                {
                    self.raw_reader.step_in()?;
                    loop {
                        use RawStreamItem::*;
                        match self.raw_reader.next()? {
                            Value(IonType::String) => {
                                new_symbols.push(Some(self.raw_reader.read_string()?));
                            }
                            Value(_) | Null(_) => {
                                // If we encounter a non-string or null, add a placeholder
                                new_symbols.push(None);
                            }
                            VersionMarker(_, _) => {
                                return decoding_error("Found IVM in symbol table.")
                            }
                            Nothing => break,
                        }
                    }
                    self.raw_reader.step_out()?;
                }
                something_else => {
                    unimplemented!("No support for {:?}", something_else);
                }
            }
        }

        if is_append {
            // We're adding new symbols to the end of the symbol table.
            for maybe_text in new_symbols.drain(..) {
                let _sid = self.symbol_table.intern_or_add_placeholder(maybe_text);
            }
        } else {
            // The symbol table has been set by defining new symbols without importing the current
            // symbol table.
            self.symbol_table.reset();
            for maybe_text in new_symbols.drain(..) {
                let _sid = self.symbol_table.intern_or_add_placeholder(maybe_text);
            }
        }

        self.raw_reader.step_out()?;
        Ok(())
    }

    fn raw_annotations(&mut self) -> impl Iterator<Item = RawSymbolToken> + '_ {
        // RawReader implementations do not attempt to resolve each annotation into text.
        // Additionally, they perform all I/O related to annotations in their implementations
        // of Reader::next. As such, it's safe to call `unwrap()` on each raw annotation.
        self.raw_reader.annotations().map(|a| a.unwrap())
    }

    pub fn symbol_table(&self) -> &SymbolTable {
        &self.symbol_table
    }
}

impl<R: RawReader> StreamReader for Reader<R> {
    type Item = StreamItem;
    type Symbol = Symbol;

    fn current(&self) -> Self::Item {
        if let Some(ion_type) = self.ion_type() {
            return if self.is_null() {
                StreamItem::Null(ion_type)
            } else {
                StreamItem::Value(ion_type)
            };
        }
        StreamItem::Nothing
    }

    /// Advances the raw reader to the next user-level Ion value, processing any system-level directives
    /// encountered along the way.
    // v-- Clippy complains that `next` resembles `Iterator::next()`
    #[allow(clippy::should_implement_trait)]
    fn next(&mut self) -> IonResult<Self::Item> {
        use RawStreamItem::*;
        loop {
            match self.raw_reader.next()? {
                VersionMarker(1, 0) => {
                    self.symbol_table.reset();
                }
                VersionMarker(major, minor) => {
                    return decoding_error(format!(
                        "Encountered a version marker for v{}.{}, but only v1.0 is supported.",
                        major, minor
                    ));
                }
                Value(IonType::Struct) => {
                    // Top-level structs whose _first_ annotation is $ion_symbol_table are
                    // interpreted as local symbol tables. Other trailing annotations (if any) are
                    // ignored. If the first annotation is something other than `$ion_symbol_table`,
                    // the struct is considered user data even if one of the trailing annotations
                    // is `$ion_symbol_table`. For more information, see this section of the spec:
                    // https://amzn.github.io/ion-docs/docs/symbols.html#local-symbol-tables
                    if self.raw_reader.depth() == 0 {
                        let is_symtab = match self.raw_reader.annotations().next() {
                            Some(Err(error)) => return Err(error),
                            Some(Ok(symbol))
                                if symbol.matches(
                                    system_symbol_ids::ION_SYMBOL_TABLE,
                                    "$ion_symbol_table",
                                ) =>
                            {
                                true
                            }
                            _ => false,
                        };
                        // This logic cannot be merged into the `match` statement above because
                        // `self.read_symbol_table()` requires a mutable borrow which is not
                        // possible while iterating over the reader's annotations.
                        if is_symtab {
                            self.read_symbol_table()?;
                            continue;
                        }
                    }
                    return Ok(StreamItem::Value(IonType::Struct));
                }
                Value(ion_type) => return Ok(StreamItem::Value(ion_type)),
                Null(ion_type) => return Ok(StreamItem::Null(ion_type)),
                Nothing => return Ok(StreamItem::Nothing),
            }
        }
    }

    fn field_name(&self) -> IonResult<Self::Symbol> {
        match self.raw_reader.field_name()? {
            RawSymbolToken::SymbolId(sid) => {
                self.symbol_table.symbol_for(sid).cloned().ok_or_else(|| {
                    decoding_error_raw(format!("encountered field ID with unknown text: ${}", sid))
                })
            }
            RawSymbolToken::Text(text) => Ok(Symbol::owned(text)),
        }
    }

    fn annotations<'a>(&'a self) -> Box<dyn Iterator<Item = IonResult<Self::Symbol>> + 'a> {
        let iterator = self
            .raw_reader
            .annotations()
            .map(move |raw_token| match raw_token? {
                RawSymbolToken::SymbolId(sid) => {
                    self.symbol_table.symbol_for(sid).cloned().ok_or_else(|| {
                        decoding_error_raw(format!(
                            "found annotation ID with unknown text: ${}",
                            sid
                        ))
                    })
                }
                RawSymbolToken::Text(text) => Ok(Symbol::owned(text)),
            });
        Box::new(iterator)
    }

    fn read_symbol(&mut self) -> IonResult<Self::Symbol> {
        match self.raw_reader.read_symbol()? {
            RawSymbolToken::SymbolId(symbol_id) => {
                if let Some(symbol) = self.symbol_table.symbol_for(symbol_id) {
                    Ok(symbol.clone())
                } else {
                    return decoding_error(format!(
                        "Found symbol ID ${}, which is not defined.",
                        symbol_id
                    ));
                }
            }
            RawSymbolToken::Text(text) => Ok(Symbol::owned(text)),
        }
    }

    // The Reader needs to expose many of the same functions as the Cursor, but only some of those
    // need to be re-defined to allow for system value processing. Any method listed here will be
    // delegated to self.raw_reader directly.
    delegate! {
        to self.raw_reader {
            fn is_null(&self) -> bool;
            fn ion_version(&self) -> (u8, u8);
            fn ion_type(&self) -> Option<IonType>;
            fn read_null(&mut self) -> IonResult<IonType>;
            fn read_bool(&mut self) -> IonResult<bool>;
            fn read_i64(&mut self) -> IonResult<i64>;
            fn read_f32(&mut self) -> IonResult<f32>;
            fn read_f64(&mut self) -> IonResult<f64>;
            fn read_decimal(&mut self) -> IonResult<Decimal>;
            fn read_string(&mut self) -> IonResult<String>;
            fn map_string<F, U>(&mut self, f: F) -> IonResult<U> where F: FnOnce(&str) -> U;
            fn map_string_bytes<F, U>(&mut self, f: F) -> IonResult<U> where F: FnOnce(&[u8]) -> U;
            fn read_blob(&mut self) -> IonResult<Vec<u8>>;
            fn map_blob<F, U>(&mut self, f: F) -> IonResult<U> where F: FnOnce(&[u8]) -> U;
            fn read_clob(&mut self) -> IonResult<Vec<u8>>;
            fn map_clob<F, U>(&mut self, f: F) -> IonResult<U> where F: FnOnce(&[u8]) -> U;
            fn read_timestamp(&mut self) -> IonResult<Timestamp>;
            fn step_in(&mut self) -> IonResult<()>;
            fn step_out(&mut self) -> IonResult<()>;
            fn parent_type(&self) -> Option<IonType>;
            fn depth(&self) -> usize;
        }
    }
}

/// Functionality that is only available if the data source we're reading from is in-memory, like
/// a Vec<u8> or &[u8].
impl<T: AsRef<[u8]>> Reader<RawBinaryReader<io::Cursor<T>>> {
    delegate! {
        to self.raw_reader {
            pub fn raw_bytes(&self) -> Option<&[u8]>;
            pub fn raw_field_id_bytes(&self) -> Option<&[u8]>;
            pub fn raw_header_bytes(&self) -> Option<&[u8]>;
            pub fn raw_value_bytes(&self) -> Option<&[u8]>;
            pub fn raw_annotations_bytes(&self) -> Option<&[u8]>;

            pub fn field_id_length(&self) -> Option<usize>;
            pub fn field_id_offset(&self) -> Option<usize>;
            pub fn field_id_range(&self) -> Option<Range<usize>>;

            pub fn annotations_length(&self) -> Option<usize>;
            pub fn annotations_offset(&self) -> Option<usize>;
            pub fn annotations_range(&self) -> Option<Range<usize>>;

            pub fn header_length(&self) -> usize;
            pub fn header_offset(&self) -> usize;
            pub fn header_range(&self) -> Range<usize>;

            pub fn value_length(&self) -> usize;
            pub fn value_offset(&self) -> usize;
            pub fn value_range(&self) -> Range<usize>;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io;

    use super::*;
    use crate::binary::constants::v1_0::IVM;
    use crate::binary::raw_binary_reader::RawBinaryReader;

    use crate::result::IonResult;
    use crate::types::IonType;
    use crate::Reader;
    use crate::StreamItem::Value;

    type TestDataSource = io::Cursor<Vec<u8>>;

    // Create a growable byte vector that starts with the Ion 1.0 version marker
    fn ion_data(bytes: &[u8]) -> Vec<u8> {
        let mut data = Vec::new();
        data.extend_from_slice(&IVM);
        data.extend_from_slice(bytes);
        data
    }

    // Creates an io::Cursor over the provided data
    fn data_source_for(bytes: &[u8]) -> TestDataSource {
        let data = ion_data(bytes);
        io::Cursor::new(data)
    }

    // Prepends an Ion 1.0 IVM to the provided data and then creates a BinaryIonCursor over it
    fn raw_binary_reader_for(bytes: &[u8]) -> RawBinaryReader<TestDataSource> {
        use RawStreamItem::*;
        let mut raw_reader = RawBinaryReader::new(data_source_for(bytes));
        assert_eq!(raw_reader.ion_type(), None);
        assert_eq!(raw_reader.next(), Ok(VersionMarker(1, 0)));
        assert_eq!(raw_reader.ion_version(), (1u8, 0u8));
        raw_reader
    }

    fn ion_reader_for(bytes: &[u8]) -> Reader<RawBinaryReader<TestDataSource>> {
        Reader::new(raw_binary_reader_for(bytes))
    }

    const EXAMPLE_STREAM: &[u8] = &[
        // $ion_symbol_table::{imports: $ion_symbol_table, symbols: ["foo", "bar", "baz"]}
        0xEE, // Var len annotations
        0x94, // Annotations + Value length: 20 bytes
        0x81, // Annotations length: 1
        0x83, // Annotation 3 ('$ion_symbol_table')
        0xDE, // Var len struct
        0x91, // Length: 17 bytes
        0x86, // Field ID 6 ('imports')
        0x71, 0x03, // Symbol 3 ('$ion_symbol_table')
        0x87, // Field ID 7 ('symbols')
        0xBC, // 12-byte List
        0x83, 0x66, 0x6f, 0x6f, // "foo"
        0x83, 0x62, 0x61, 0x72, // "bar"
        0x83, 0x62, 0x61, 0x7a, // "baz"
        // System: {$10: 1, $11: 2, $12: 3}
        // User: {foo: 1, bar: 1, baz: 1}
        0xD9, // 9-byte struct
        0x8A, // Field ID 10
        0x21, 0x01, // Integer 1
        0x8B, // Field ID 11
        0x21, 0x02, // Integer 2
        0x8C, // Field ID 12
        0x21, 0x03, // Integer 3
    ];

    #[test]
    fn test_read_struct() -> IonResult<()> {
        let mut reader = ion_reader_for(EXAMPLE_STREAM);

        assert_eq!(Value(IonType::Struct), reader.next()?);
        reader.step_in()?;

        assert_eq!(reader.next()?, Value(IonType::Integer));
        assert_eq!(reader.field_name()?, "foo");

        assert_eq!(reader.next()?, Value(IonType::Integer));
        assert_eq!(reader.field_name()?, "bar");

        assert_eq!(reader.next()?, Value(IonType::Integer));
        assert_eq!(reader.field_name()?, "baz");

        Ok(())
    }
}