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
use crate::binary_encoder::{
    encode_blob, encode_bool, encode_datetime, encode_decimal, encode_float64, encode_integer,
    encode_null, encode_uint, encode_varuint, ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED,
};
use crate::binary_parser_types::{SystemSymbolIds, SYSTEM_SYMBOL_TABLE};
use crate::symbol_table::SymbolContext;
use crate::IonValue;
use num_bigint::{BigInt, BigUint};
use std::collections::HashMap;
use std::convert::TryFrom;

/// Allows to binary encode one or multiple IonValue.
///
/// Given how Ion format works there are two methods in order to use
/// this utility.
///
/// - `add` allows to add IonValue to the buffer to later encoding.
/// - `encode` takes all biffered values and encodes them, generating
/// the symbol's table and the ion header. It returns a Vec<u8>.
///
/// ```rust,no_run
///
/// use ion_binary_rs::{IonEncoder, IonParser, IonValue};
/// use std::collections::HashMap;
///
/// let mut ion_struct = HashMap::new();
///
/// ion_struct.insert("Model".to_string(), IonValue::String("CLK 350".to_string()));
/// ion_struct.insert("Type".to_string(), IonValue::String("Sedan".to_string()));
/// ion_struct.insert("Color".to_string(), IonValue::String("White".to_string()));
/// ion_struct.insert(
///     "VIN".to_string(),
///     IonValue::String("1C4RJFAG0FC625797".to_string()),
/// );
/// ion_struct.insert("Make".to_string(), IonValue::String("Mercedes".to_string()));
/// ion_struct.insert("Year".to_string(), IonValue::Integer(2019));
///
/// let ion_value = IonValue::Struct(ion_struct);
///
/// let mut encoder = IonEncoder::new();
///
/// encoder.add(ion_value.clone());
/// let bytes = encoder.encode();
///
/// let resulting_ion_value = IonParser::new(&bytes[..]).consume_value().unwrap().0;
///
/// assert_eq!(ion_value, resulting_ion_value);
/// ```
#[derive(Debug)]
pub struct IonEncoder {
    current_buffer: Vec<IonValue>,
    symbol_table: SymbolContext,
}

impl Default for IonEncoder {
    fn default() -> Self {
        Self::new()
    }
}

impl IonEncoder {
    pub fn new() -> IonEncoder {
        IonEncoder {
            current_buffer: vec![],
            symbol_table: SymbolContext::new(),
        }
    }

    pub fn add(&mut self, value: IonValue) {
        self.current_buffer.push(value);
    }

    pub fn encode(&mut self) -> Vec<u8> {
        let mut values = vec![];

        values.append(&mut self.current_buffer);

        let mut values_buffer: Vec<u8> = values
            .into_iter()
            .flat_map(|value| self.encode_value(&value))
            .collect();

        let mut symbol_table = self.encode_current_symbol_table();

        let mut buffer = IonEncoder::get_ion_1_0_header();

        buffer.append(&mut symbol_table);
        buffer.append(&mut values_buffer);

        buffer
    }

    fn get_ion_1_0_header() -> Vec<u8> {
        vec![0xE0, 0x01, 0x00, 0xEA]
    }

    pub(crate) fn encode_value(&mut self, value: &IonValue) -> Vec<u8> {
        match value {
            IonValue::Null(value) => encode_null(value),
            IonValue::Bool(value) => encode_bool(value),
            IonValue::Integer(value) => encode_integer(&BigInt::from(*value)),
            IonValue::BigInteger(value) => encode_integer(value),
            IonValue::Float(value) => encode_float64(value),
            IonValue::Decimal(value) => encode_decimal(value),
            IonValue::String(value) => encode_blob(8, value.as_bytes()),
            IonValue::Clob(value) => encode_blob(9, value),
            IonValue::Blob(value) => encode_blob(10, value),
            IonValue::DateTime(value) => encode_datetime(value),
            IonValue::List(value) => self.encode_list(value, false),
            IonValue::SExpr(value) => self.encode_list(value, true),
            IonValue::Symbol(symbol) => self.encode_symbol(symbol),
            IonValue::Struct(value) => self.encode_struct(value),
            IonValue::Annotation(annotations, value) => self.encode_annotation(annotations, value),
        }
    }

    pub(crate) fn encode_symbol(&mut self, symbol: &str) -> Vec<u8> {
        let mut buffer: Vec<u8> = vec![];

        let mut header: u8 = 0x70;

        let id = self.symbol_table.insert_symbol(symbol);

        let mut id_bytes = encode_uint(&BigUint::from(id));
        let id_bytes_len = id_bytes.len();
        let has_len_field = id_bytes_len >= ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED.into();

        if has_len_field {
            header += ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED;
            buffer.push(header);
            let mut id_bytes_len_bytes = encode_varuint(&id_bytes_len.to_be_bytes());
            buffer.append(&mut id_bytes_len_bytes);
        } else {
            header += u8::try_from(id_bytes_len).unwrap();
            buffer.push(header);
        };

        buffer.append(&mut id_bytes);

        buffer
    }

    pub(crate) fn encode_list(&mut self, values: &[IonValue], is_sexp: bool) -> Vec<u8> {
        let mut buffer: Vec<u8> = vec![];

        for value in values {
            let mut bytes = self.encode_value(value);

            buffer.append(&mut bytes);
        }

        let buffer_len = buffer.len();
        let has_len_field = buffer_len >= ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED.into();

        let mut header: u8 = if is_sexp { 0xC0 } else { 0xB0 };

        if has_len_field {
            header += ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED;
        } else {
            header += u8::try_from(buffer_len).unwrap();
        }

        let mut buffer = if has_len_field {
            let mut buffer_len_bytes = encode_varuint(&buffer_len.to_be_bytes());
            buffer_len_bytes.append(&mut buffer);
            buffer_len_bytes
        } else {
            buffer
        };

        buffer.insert(0, header);

        buffer
    }

    pub(crate) fn encode_annotation(
        &mut self,
        annotations: &[String],
        value: &IonValue,
    ) -> Vec<u8> {
        let mut annot_buffer: Vec<u8> = vec![];

        for annot in annotations {
            let annot_symbol = self.symbol_table.insert_symbol(annot);
            let mut annot_symbol_bytes = encode_varuint(&annot_symbol.to_be_bytes());
            annot_buffer.append(&mut annot_symbol_bytes);
        }

        let mut annot_len_bytes = encode_varuint(&annot_buffer.len().to_be_bytes());

        let mut value_bytes = self.encode_value(value);

        annot_len_bytes.append(&mut annot_buffer);

        let mut buffer = annot_len_bytes;

        buffer.append(&mut value_bytes);

        let len = buffer.len();
        let has_len_field = len >= ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED.into();

        let mut header = 0xE0;

        let mut final_buffer: Vec<u8> = vec![];

        if has_len_field {
            header += ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED;
            final_buffer.push(header);
            let mut len_bytes = encode_varuint(&len.to_be_bytes());
            final_buffer.append(&mut len_bytes);
        } else {
            header += u8::try_from(len).unwrap();
            final_buffer.push(header);
        }

        final_buffer.append(&mut buffer);

        final_buffer
    }

    pub(crate) fn encode_struct(&mut self, value: &HashMap<String, IonValue>) -> Vec<u8> {
        let mut content_buffer: Vec<u8> = vec![];

        for (key, value) in value {
            let symbol = self.symbol_table.insert_symbol(key);
            let mut symbol_bytes = encode_varuint(&symbol.to_be_bytes());
            let mut value_bytes = self.encode_value(value);
            content_buffer.append(&mut symbol_bytes);
            content_buffer.append(&mut value_bytes);
        }

        let content_len = content_buffer.len();
        let has_len_field = content_len >= ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED.into();

        let mut header = 0xD0;

        let mut buffer: Vec<u8> = vec![];

        if has_len_field {
            header += ION_LEN_ON_HEADER_WHEN_EXTRA_LEN_FIELD_REQUIRED;
            buffer.push(header);
            let mut content_len_bytes = encode_varuint(&content_len.to_be_bytes());
            buffer.append(&mut content_len_bytes);
        } else {
            header += u8::try_from(content_len).unwrap();
            buffer.push(header);
        }

        buffer.append(&mut content_buffer);

        buffer
    }

    pub(crate) fn encode_current_symbol_table(&mut self) -> Vec<u8> {
        let symbols = self.symbol_table.dump_all_local_symbols();

        let symbols = IonValue::List(symbols.into_iter().map(IonValue::String).collect());

        let mut annotation_struct = HashMap::new();

        let symbols_symbol = SYSTEM_SYMBOL_TABLE[SystemSymbolIds::Symbols as usize].to_string();
        let local_table_annotation_symbol =
            SYSTEM_SYMBOL_TABLE[SystemSymbolIds::IonSymbolTable as usize].to_string();

        annotation_struct.insert(symbols_symbol, symbols);

        let annotation_struct = IonValue::Struct(annotation_struct);

        let annotation = IonValue::Annotation(
            vec![local_table_annotation_symbol],
            Box::new(annotation_struct),
        );

        self.encode_value(&annotation)
    }
}