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 delegate::delegate;

use ion_rs::{IonError, IonType, IonWriter};
use ordered_float::OrderedFloat;
use partiql_value::{Bag, DateTime, List, Tuple, Value};
use rust_decimal::Decimal;

use crate::common::{
    BAG_ANNOT, DATE_ANNOT, MISSING_ANNOT, TIME_ANNOT, TIME_PART_HOUR_KEY, TIME_PART_MINUTE_KEY,
    TIME_PART_SECOND_KEY, TIME_PART_TZ_HOUR_KEY, TIME_PART_TZ_MINUTE_KEY,
};
use crate::Encoding;
use thiserror::Error;
use time::{Date, Duration, Time, UtcOffset};

/// Errors in ion encoding.
///
/// ### Notes
/// This is marked `#[non_exhaustive]`, to reserve the right to add more variants in the future.
#[derive(Error, Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum IonEncodeError {
    /// Ion Writer error.
    #[error("Ion write error: `{}`", .0)]
    IonWriterError(IonError),

    /// Unsupported type error.
    #[error("Ion write error: unsupported value of type `{}`", .0)]
    UnsupportedType(&'static str),
}

impl From<IonError> for IonEncodeError {
    fn from(value: IonError) -> Self {
        IonEncodeError::IonWriterError(value)
    }
}

/// Result of attempts to encode a [`Value`] to Ion.
pub type IonEncodeResult = Result<(), IonEncodeError>;

/// Config for construction an Ion encoder.
pub struct IonEncoderConfig {
    mode: Encoding,
}

impl IonEncoderConfig {
    /// Set the mode to `mode`
    pub fn with_mode(mut self, mode: crate::Encoding) -> Self {
        self.mode = mode;
        self
    }
}

impl Default for IonEncoderConfig {
    fn default() -> Self {
        IonEncoderConfig {
            mode: crate::Encoding::Ion,
        }
    }
}

/// Builder for creating an encoder.
pub struct IonEncoderBuilder {
    config: IonEncoderConfig,
}

impl IonEncoderBuilder {
    /// Create the builder from 'config'
    pub fn new(config: IonEncoderConfig) -> Self {
        Self { config }
    }

    /// Create a encoder given the previously specified config and an ion [`IonWriter`].
    pub fn build<'a, W, I>(
        self,
        writer: &'a mut I,
    ) -> Result<Box<dyn ValueEncoder<W, I> + 'a>, IonEncodeError>
    where
        W: 'a,
        I: IonWriter<Output = W> + 'a,
    {
        let encoder = SimpleIonValueEncoder { writer };
        let encoder: Box<dyn ValueEncoder<W, I>> = match self.config.mode {
            crate::Encoding::Ion => Box::new(encoder),
            crate::Encoding::PartiqlEncodedAsIon => {
                Box::new(PartiqlEncodedIonValueEncoder { inner: encoder })
            }
        };

        Ok(encoder)
    }
}

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

/// An encoder which will write [`Value`]s as Ion stream values.
pub trait ValueEncoder<W, I>
where
    I: IonWriter<Output = W>,
{
    /// A reference to the writer used by this encoder.
    fn writer(&mut self) -> &mut I;

    /// Write an Ion stream value from the given [`Value`]
    fn write_value(&mut self, value: &Value) -> IonEncodeResult;
}

trait IonValueEncoder<W, I>: ValueEncoder<W, I>
where
    I: IonWriter<Output = W>,
{
    fn get_writer(&mut self) -> &mut I;

    #[inline]
    fn encode_value(&mut self, value: &Value) -> IonEncodeResult {
        match value {
            Value::Null => self.encode_null(),
            Value::Missing => self.encode_missing(),
            Value::Boolean(b) => self.encode_bool(b),
            Value::Integer(i) => self.encode_int(i),
            Value::Real(r) => self.encode_real(r),
            Value::Decimal(d) => self.encode_decimal(d),
            Value::String(s) => self.encode_string(s.as_ref()),
            Value::Blob(b) => self.encode_blob(b.as_ref()),
            Value::DateTime(dt) => self.encode_datetime(dt.as_ref()),
            Value::List(l) => self.encode_list(l.as_ref()),
            Value::Bag(b) => self.encode_bag(b.as_ref()),
            Value::Tuple(t) => self.encode_tuple(t.as_ref()),
        }
    }

    fn encode_null(&mut self) -> IonEncodeResult;
    fn encode_missing(&mut self) -> IonEncodeResult;
    fn encode_bool(&mut self, val: &bool) -> IonEncodeResult;
    fn encode_int(&mut self, val: &i64) -> IonEncodeResult;
    fn encode_real(&mut self, val: &OrderedFloat<f64>) -> IonEncodeResult;
    fn encode_decimal(&mut self, val: &Decimal) -> IonEncodeResult;
    fn encode_string(&mut self, val: &str) -> IonEncodeResult;
    fn encode_blob(&mut self, val: &[u8]) -> IonEncodeResult;
    fn encode_datetime(&mut self, val: &DateTime) -> IonEncodeResult;
    fn encode_list(&mut self, val: &List) -> IonEncodeResult;
    fn encode_bag(&mut self, val: &Bag) -> IonEncodeResult;
    fn encode_tuple(&mut self, val: &Tuple) -> IonEncodeResult;
}

impl<'a, W, I> ValueEncoder<W, I> for SimpleIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    fn writer(&mut self) -> &mut I {
        self.get_writer()
    }

    #[inline]
    fn write_value(&mut self, value: &Value) -> IonEncodeResult {
        self.encode_value(value)
    }
}

impl<'a, W, I> ValueEncoder<W, I> for PartiqlEncodedIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    fn writer(&mut self) -> &mut I {
        self.get_writer()
    }

    #[inline]
    fn write_value(&mut self, value: &Value) -> IonEncodeResult {
        self.encode_value(value)
    }
}

struct SimpleIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    pub(crate) writer: &'a mut I,
}

impl<'a, W, I> IonValueEncoder<W, I> for SimpleIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    fn get_writer(&mut self) -> &mut I {
        self.writer
    }

    fn encode_null(&mut self) -> IonEncodeResult {
        Ok(self.writer.write_null(IonType::Null)?)
    }

    fn encode_missing(&mut self) -> IonEncodeResult {
        Err(IonEncodeError::UnsupportedType("missing"))
    }

    fn encode_bool(&mut self, val: &bool) -> IonEncodeResult {
        Ok(self.writer.write_bool(*val)?)
    }

    fn encode_int(&mut self, val: &i64) -> IonEncodeResult {
        Ok(self.writer.write_i64(*val)?)
    }

    fn encode_real(&mut self, val: &OrderedFloat<f64>) -> IonEncodeResult {
        Ok(self.writer.write_f64(val.0)?)
    }

    fn encode_decimal(&mut self, val: &Decimal) -> IonEncodeResult {
        let scale = val.scale() as i64;
        let mantissa = val.mantissa();
        let dec = ion_rs::Decimal::new(mantissa, -scale);
        Ok(self.writer.write_decimal(&dec)?)
    }

    fn encode_string(&mut self, val: &str) -> IonEncodeResult {
        Ok(self.writer.write_string(val)?)
    }

    fn encode_blob(&mut self, val: &[u8]) -> IonEncodeResult {
        Ok(self.writer.write_blob(val)?)
    }

    fn encode_datetime(&mut self, val: &DateTime) -> IonEncodeResult {
        match val {
            DateTime::Timestamp(ts) => {
                let ts = ion_rs::Timestamp::with_ymd(
                    ts.year() as u32,
                    ts.month() as u32,
                    ts.day() as u32,
                )
                .with_hms(ts.hour() as u32, ts.minute() as u32, ts.second() as u32)
                .with_nanoseconds(ts.nanosecond())
                .build_at_unknown_offset()?;

                Ok(self.writer.write_timestamp(&ts)?)
            }
            DateTime::TimestampWithTz(ts) => {
                let ts = ion_rs::Timestamp::with_ymd(
                    ts.year() as u32,
                    ts.month() as u32,
                    ts.day() as u32,
                )
                .with_hms(ts.hour() as u32, ts.minute() as u32, ts.second() as u32)
                .with_nanoseconds(ts.nanosecond())
                .build_at_offset(ts.offset().whole_minutes() as i32)?;

                Ok(self.writer.write_timestamp(&ts)?)
            }
            _ => Err(IonEncodeError::UnsupportedType(
                "unsupported date time variant",
            )),
        }
    }

    fn encode_list(&mut self, val: &List) -> IonEncodeResult {
        encode_list(self, val.iter())
    }

    fn encode_bag(&mut self, _val: &Bag) -> IonEncodeResult {
        Err(IonEncodeError::UnsupportedType("bag"))
    }

    fn encode_tuple(&mut self, val: &Tuple) -> IonEncodeResult {
        encode_tuple(self, val)
    }
}

#[inline]
fn encode_list<'a, W, I, V>(encoder: &'a mut impl IonValueEncoder<W, I>, vals: V) -> IonEncodeResult
where
    W: 'a,
    I: IonWriter<Output = W> + 'a,
    V: Iterator<Item = &'a Value> + 'a,
{
    encoder.writer().step_in(IonType::List)?;
    for v in vals {
        encoder.encode_value(v)?;
    }
    encoder.writer().step_out()?;

    Ok(())
}

#[inline]
fn encode_tuple<'a, W, I>(
    encoder: &'a mut impl IonValueEncoder<W, I>,
    val: &'a Tuple,
) -> IonEncodeResult
where
    W: 'a,
    I: IonWriter<Output = W> + 'a,
{
    encoder.writer().step_in(IonType::Struct)?;
    for (k, v) in val.pairs() {
        encoder.writer().set_field_name(k);
        encoder.encode_value(v)?;
    }
    encoder.writer().step_out()?;

    Ok(())
}

struct PartiqlEncodedIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    inner: SimpleIonValueEncoder<'a, W, I>,
}

impl<'a, W, I> PartiqlEncodedIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    fn write_date(&mut self, date: &Date) -> IonEncodeResult {
        self.inner
            .writer
            .set_annotations(std::iter::once(DATE_ANNOT));
        let ts =
            ion_rs::Timestamp::with_ymd(date.year() as u32, date.month() as u32, date.day() as u32)
                .build()?;

        Ok(self.inner.writer.write_timestamp(&ts)?)
    }

    fn write_timestamp(&mut self, time: &Time, offset: Option<&UtcOffset>) -> IonEncodeResult {
        let writer = &mut self.inner.writer;
        writer.set_annotations(std::iter::once(TIME_ANNOT));
        writer.step_in(IonType::Struct)?;
        writer.set_field_name(TIME_PART_HOUR_KEY);
        writer.write_i64(time.hour() as i64)?;
        writer.set_field_name(TIME_PART_MINUTE_KEY);
        writer.write_i64(time.minute() as i64)?;
        writer.set_field_name(TIME_PART_SECOND_KEY);

        let seconds = Duration::new(time.second() as i64, time.nanosecond() as i32);
        writer.write_f64(seconds.as_seconds_f64())?;

        if let Some(offset) = offset {
            writer.set_field_name(TIME_PART_TZ_HOUR_KEY);
            writer.write_i64(offset.whole_hours() as i64)?;
            writer.set_field_name(TIME_PART_TZ_MINUTE_KEY);
            writer.write_i64(offset.minutes_past_hour() as i64)?;
        }

        writer.step_out()?;

        Ok(())
    }
}

impl<'a, W, I> IonValueEncoder<W, I> for PartiqlEncodedIonValueEncoder<'a, W, I>
where
    W: 'a,
    I: IonWriter<Output = W>,
{
    fn get_writer(&mut self) -> &mut I {
        self.inner.writer
    }

    fn encode_missing(&mut self) -> IonEncodeResult {
        self.inner
            .writer
            .set_annotations(std::iter::once(MISSING_ANNOT));
        self.inner.writer.write_null(IonType::Null)?;
        Ok(())
    }

    fn encode_datetime(&mut self, val: &DateTime) -> IonEncodeResult {
        match val {
            DateTime::Date(date) => self.write_date(date),
            DateTime::Time(time) => self.write_timestamp(time, None),
            DateTime::TimeWithTz(time, offset) => self.write_timestamp(time, Some(offset)),
            _ => self.inner.encode_datetime(val),
        }
    }

    fn encode_list(&mut self, val: &List) -> IonEncodeResult {
        encode_list(self, val.iter())
    }

    fn encode_bag(&mut self, val: &Bag) -> IonEncodeResult {
        self.inner
            .writer
            .set_annotations(std::iter::once(BAG_ANNOT));
        encode_list(self, val.iter())
    }

    fn encode_tuple(&mut self, val: &Tuple) -> IonEncodeResult {
        encode_tuple(self, val)
    }

    delegate! {
        to self.inner {
            fn encode_null(& mut self) -> IonEncodeResult;
            fn encode_bool(& mut self, val: & bool) -> IonEncodeResult;
            fn encode_int(& mut self, val: & i64) -> IonEncodeResult;
            fn encode_real(& mut self, val: & OrderedFloat<f64>) -> IonEncodeResult;
            fn encode_decimal(& mut self, val: & Decimal) -> IonEncodeResult;
            fn encode_string(& mut self, val: & str) -> IonEncodeResult;
            fn encode_blob(& mut self, val: & [u8]) -> IonEncodeResult;
        }
    }
}