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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use std::marker::PhantomData;

use crate::{canonical::canonicalise, constants::*, reader::Literal, Cbor, CborOwned};

enum Bytes<'a> {
    Owned(Vec<u8>),
    Borrowed(&'a mut Vec<u8>),
}

impl<'a> Bytes<'a> {
    pub fn copy(&mut self) -> Bytes {
        Bytes::Borrowed(self.as_mut())
    }

    pub fn as_slice(&self) -> &[u8] {
        match self {
            Bytes::Owned(b) => b.as_slice(),
            Bytes::Borrowed(b) => b.as_slice(),
        }
    }

    pub fn as_mut(&mut self) -> &mut Vec<u8> {
        match self {
            Bytes::Owned(b) => b,
            Bytes::Borrowed(b) => *b,
        }
    }
}

/// High-level encoding functions to write values in their canonical format.
///
/// ```
/// use cbor_data::{CborBuilder, Encoder, Writer};
///
/// let cbor = CborBuilder::default().encode_u64(12);
///
/// let array = CborBuilder::default().encode_array(|builder| {
///     builder
///         .encode_u64(18)
///         .encode_i64(-12);
/// });
///
/// let array2 = CborBuilder::default().with_max_definite_size(Some(1)).write_array(None, |builder| {
///     builder
///         .encode_u64(18)
///         .encode_i64(-12);
/// });
///
/// let dict = CborBuilder::default().encode_dict(|builder| {
///     builder
///         .with_key("a", |b| b.encode_u64(14))
///         .with_key("b", |b| b.encode_i64(-1));
/// });
///
/// let (dict2, ret) = CborBuilder::default().write_dict_ret(None, |builder| {
///     builder
///         .with_key("a", |b| b.encode_u64(14))
///         .with_key("b", |b| b.encode_i64(-1));
///     "hello"
/// });
/// assert_eq!(ret, "hello");
///
/// # assert_eq!(cbor.as_slice(), vec![0x0cu8]);
/// # assert_eq!(array.as_slice(), vec![0x82u8, 0x12, 0x2b]);
/// # assert_eq!(array2.as_slice(), vec![0x9fu8, 0x12, 0x2b, 0xff]);
/// # assert_eq!(dict.as_slice(), vec![0xa2u8, 0x61, b'a', 0x0e, 0x61, b'b', 0x20]);
/// # assert_eq!(dict2.as_slice(), vec![0xa2u8, 0x61, b'a', 0x0e, 0x61, b'b', 0x20]);
/// ```
pub trait Encoder: Writer {
    fn encode_bool(self, value: bool) -> Self::Output {
        self.write_bool(value, None)
    }

    /// Encode an unsigned integer of at most 64 bit.
    ///
    /// Also to be used for smaller unsigned integers:
    ///
    /// ```
    /// use cbor_data::{CborBuilder, Encoder};
    ///
    /// let short = 12345u16;
    /// let cbor = CborBuilder::default().encode_u64(short.into());
    ///
    /// # assert_eq!(cbor.as_slice(), vec![0x19u8, 48, 57]);
    /// ```
    fn encode_u64(self, value: u64) -> Self::Output {
        self.write_pos(value, None)
    }

    /// Encode a signed integer of at most 64 bit.
    ///
    /// Also to be used for smaller signed integers:
    ///
    /// ```
    /// use cbor_data::{CborBuilder, Encoder};
    ///
    /// let short = -12345i16;
    /// let cbor = CborBuilder::default().encode_i64(short.into());
    ///
    /// # assert_eq!(cbor.as_slice(), vec![0x39u8, 48, 56]);
    /// ```
    fn encode_i64(self, value: i64) -> Self::Output {
        if value < 0 {
            self.write_neg((-1 - value) as u64, None)
        } else {
            self.write_pos(value as u64, None)
        }
    }

    /// Encode a floating-point number of at most 64 bit.
    ///
    /// Also to be used for smaller formats:
    ///
    /// ```
    /// use cbor_data::{CborBuilder, Encoder};
    ///
    /// let single = -3.14f32;
    /// let cbor = CborBuilder::default().encode_f64(single.into());
    ///
    /// # assert_eq!(cbor.as_slice(), vec![0xfbu8, 192, 9, 30, 184, 96, 0, 0, 0]);
    /// ```
    fn encode_f64(self, value: f64) -> Self::Output {
        self.write_lit(Literal::L8(value.to_bits()), None)
    }

    /// Encode a string.
    ///
    /// ```
    /// use cbor_data::{CborBuilder, Encoder};
    ///
    /// let cbor = CborBuilder::default().encode_array(|builder| {
    ///     builder.encode_str("hello");
    ///     builder.encode_str(String::new());
    /// });
    ///
    /// # assert_eq!(cbor.as_slice(), vec![0x82, 0x65, b'h', b'e', b'l', b'l', b'o', 0x60]);
    /// ```
    fn encode_str(self, value: impl AsRef<str>) -> Self::Output {
        self.write_str(value.as_ref(), None)
    }

    /// Write an array that is then filled by the provided closure using the passed builder.
    ///
    /// see [`trait Encoder`](trait.Encoder.html) for usage examples
    fn encode_array<F>(self, mut f: F) -> Self::Output
    where
        F: FnMut(&mut ArrayWriter<'_>),
    {
        self.write_array(None, |builder| f(builder))
    }

    /// Write a dict that is then filled by the provided closure using the passed builder.
    ///
    /// see [`trait Encoder`](trait.Encoder.html) for usage examples
    fn encode_dict<F>(self, mut f: F) -> Self::Output
    where
        F: FnMut(&mut DictWriter<'_>),
    {
        self.write_dict(None, |builder| f(builder))
    }
}

impl<T: Writer> Encoder for T {}

/// Low-level primitives for emitting CBOR items.
///
/// The methods of this trait give you full control over the encoding of values according to the
/// CBOR specification (apart from the technically allowed non-optimal integer encodings). It
/// allows you to emit any item tagged with any number you desire.
///
/// If you are looking for convenient methods of writing end-user data types please refer to
/// the [`Encoder`](trait.Encoder.html) trait.
pub trait Writer: Sized {
    type Output;
    #[doc(hidden)]
    // internal helper method — do not use!
    /// contract: each call to this method MUST corresopnd to a single CBOR item being written!
    fn bytes<T>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> T) -> T;
    #[doc(hidden)]
    // internal helper method — do not use!
    fn into_output(self) -> Self::Output;

    /// Configured maximum array or dict length up to which definite size encoding is used.
    fn max_definite(&self) -> Option<u64>;

    /// Write a unsigned value of up to 64 bits.
    /// Tags are from outer to inner.
    fn write_pos(mut self, value: u64, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_positive(b, value, tags));
        self.into_output()
    }

    /// Write a negative value of up to 64 bits — the represented number is `-1 - value`.
    /// Tags are from outer to inner.
    fn write_neg(mut self, value: u64, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_neg(b, value, tags));
        self.into_output()
    }

    /// Write the given slice as a definite size byte string.
    /// Tags are from outer to inner.
    fn write_bytes(mut self, value: &[u8], tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_bytes(b, value, tags));
        self.into_output()
    }

    /// Write the given slice as a definite size string.
    /// Tags are from outer to inner.
    fn write_str(mut self, value: &str, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_str(b, value, tags));
        self.into_output()
    }

    /// Tags are from outer to inner.
    fn write_bool(mut self, value: bool, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_bool(b, value, tags));
        self.into_output()
    }

    /// Tags are from outer to inner.
    fn write_null(mut self, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_null(b, tags));
        self.into_output()
    }

    /// Tags are from outer to inner.
    fn write_undefined(mut self, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| write_undefined(b, tags));
        self.into_output()
    }

    /// Write custom literal value — [RFC 7049 §2.3](https://tools.ietf.org/html/rfc7049#section-2.3) is required reading.
    /// Tags are from outer to inner.
    fn write_lit(mut self, value: Literal, tags: impl IntoIterator<Item = u64>) -> Self::Output {
        self.bytes(|b| {
            write_tags(b, tags);
            write_lit(b, value)
        });
        self.into_output()
    }

    /// Write a nested array using the given closure that receives an array builder.
    /// Tags are from outer to inner.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer};
    /// let cbor = CborBuilder::default().write_array(None, |builder| {
    ///     builder.write_array_ret(None, |builder| {
    ///         builder.write_pos(42, None);
    ///     });
    /// });
    /// # assert_eq!(cbor.as_slice(), vec![0x81u8, 0x81, 0x18, 42]);
    /// ```
    fn write_array<F>(self, tags: impl IntoIterator<Item = u64>, f: F) -> Self::Output
    where
        F: FnOnce(&mut ArrayWriter<'_>),
    {
        self.write_array_ret(tags, f).0
    }

    /// Write a nested array using the given closure that receives an array builder.
    /// Tags are from outer to inner.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer};
    /// let (cbor, ret) = CborBuilder::default().write_array_ret(None, |builder| {
    ///     builder.write_array_ret(None, |builder| {
    ///         builder.write_pos(42, None);
    ///     });
    ///     42
    /// });
    /// assert_eq!(ret, 42);
    /// # assert_eq!(cbor.as_slice(), vec![0x81u8, 0x81, 0x18, 42]);
    /// ```
    fn write_array_ret<T, F>(
        mut self,
        tags: impl IntoIterator<Item = u64>,
        f: F,
    ) -> (Self::Output, T)
    where
        F: FnOnce(&mut ArrayWriter<'_>) -> T,
    {
        let max_definite = self.max_definite();
        let ret = self.bytes(|b| {
            write_tags(b, tags);
            let pos = b.len();
            write_indefinite(b, MAJOR_ARRAY);
            let mut writer = ArrayWriter::new(b, max_definite);
            let ret = f(&mut writer);
            let max_definite = writer.max_definite;
            finish_array(writer.count, b, pos, MAJOR_ARRAY, max_definite);
            ret
        });
        (self.into_output(), ret)
    }

    /// Write a nested dict using the given closure that receives a dict builder.
    /// Tags are from outer to inner.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer};
    /// let cbor = CborBuilder::default().write_array(None, |builder | {
    ///     builder.write_dict_ret(None, |builder| {
    ///         builder.with_key("y", |b| b.write_pos(42, None));
    ///     });
    /// });
    /// # assert_eq!(cbor.as_slice(), vec![0x81u8, 0xa1, 0x61, b'y', 0x18, 42]);
    /// ```
    fn write_dict<F>(self, tags: impl IntoIterator<Item = u64>, f: F) -> Self::Output
    where
        F: FnOnce(&mut DictWriter<'_>),
    {
        self.write_dict_ret(tags, f).0
    }

    /// Write a nested dict using the given closure that receives a dict builder.
    /// Tags are from outer to inner.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer};
    /// let (cbor, ret) = CborBuilder::default().write_array_ret(None, |builder | {
    ///     builder.write_dict_ret(None, |builder| {
    ///         builder.with_key("y", |b| b.write_pos(42, None));
    ///     });
    ///     42
    /// });
    /// assert_eq!(ret, 42);
    /// # assert_eq!(cbor.as_slice(), vec![0x81u8, 0xa1, 0x61, b'y', 0x18, 42]);
    /// ```
    fn write_dict_ret<T, F>(
        mut self,
        tags: impl IntoIterator<Item = u64>,
        f: F,
    ) -> (Self::Output, T)
    where
        F: FnOnce(&mut DictWriter<'_>) -> T,
    {
        let max_definite = self.max_definite();
        let ret = self.bytes(|b| {
            write_tags(b, tags);
            let pos = b.len();
            write_indefinite(b, MAJOR_DICT);
            let mut writer = DictWriter::new(b, max_definite);
            let ret = f(&mut writer);
            let max_definite = writer.0.max_definite;
            finish_array(writer.0.count, b, pos, MAJOR_DICT, max_definite);
            ret
        });
        (self.into_output(), ret)
    }

    /// Interpret the given bytes as a single CBOR item and write it to this builder,
    /// canonicalising its contents like [`CborOwned::canonical()`](struct.CborOwned.html#method.canonical)
    fn write_canonical(mut self, bytes: &[u8]) -> Option<Self::Output> {
        let max_definite = self.max_definite();
        let c = self.bytes(|b| {
            canonicalise(
                bytes,
                CborBuilder::append_to(b).with_max_definite_size(max_definite),
            )
        });
        if c.is_some() {
            Some(self.into_output())
        } else {
            None
        }
    }

    /// Assume that the given bytes are a well-formed single CBOR item and write it to this builder.
    ///
    /// If those bytes are not valid CBOR you get to keep the pieces!
    fn write_trusting(mut self, bytes: &[u8]) -> Self::Output {
        self.bytes(|b| b.extend_from_slice(bytes));
        self.into_output()
    }

    /// Write the given CBOR item
    fn write_item(self, item: Cbor) -> Self::Output {
        self.write_trusting(item.as_slice())
    }
}

/// Marker trait to distinguish a builder that emits an owned value from one that appends to a vector
pub trait CborOutput {
    type Output;
    fn output(bytes: &[u8]) -> Self::Output;
}
/// Marker type for builders that emit an owned value
pub struct WithOutput;
impl CborOutput for WithOutput {
    type Output = CborOwned;
    fn output(bytes: &[u8]) -> Self::Output {
        CborOwned::trusting(bytes)
    }
}
/// Marker type for builders that only append to a provided vector
pub struct NoOutput;
impl CborOutput for NoOutput {
    type Output = ();
    fn output(_bytes: &[u8]) -> Self::Output {}
}

/// Builder for a single CBOR value.
pub struct CborBuilder<'a, O: CborOutput> {
    bytes: Bytes<'a>,
    max_definite: Option<u64>,
    ph: PhantomData<O>,
}

impl Default for CborBuilder<'static, WithOutput> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> CborBuilder<'a, WithOutput> {
    /// Create a builder that writes into its own fresh vector.
    pub fn new() -> Self {
        Self {
            bytes: Bytes::Owned(Vec::new()),
            max_definite: Some(255),
            ph: PhantomData,
        }
    }

    /// Create a builder that clears the given vector and writes into it.
    ///
    /// You can use this to reuse a scratch space across multiple values being built, e.g. by
    /// keeping the same vector in a thread-local variable.
    pub fn with_scratch_space(v: &'a mut Vec<u8>) -> Self {
        v.clear();
        Self {
            bytes: Bytes::Borrowed(v),
            max_definite: Some(255),
            ph: PhantomData,
        }
    }
}

impl<'a> CborBuilder<'a, NoOutput> {
    /// Append the CBOR bytes to the given vector and do not return a separate output value.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer};
    /// let mut v = Vec::new();
    /// let result: () = CborBuilder::append_to(&mut v).write_pos(12, None);
    ///
    /// assert_eq!(v, vec![12u8])
    /// ```
    pub fn append_to(v: &'a mut Vec<u8>) -> Self {
        Self {
            bytes: Bytes::Borrowed(v),
            max_definite: Some(255),
            ph: PhantomData,
        }
    }
}

impl<'a, O: CborOutput> CborBuilder<'a, O> {
    /// Configure the limit above which indefinite size encoding will be used.
    ///
    /// The default is 255, which is the largest size up to which definite size is at least as
    /// compact as indefinite size. Set to 23 to avoid moving bytes around when finishing the array.
    /// Set to `None` to always use indefinite size encoding.
    pub fn with_max_definite_size(self, max_definite: Option<u64>) -> Self {
        Self {
            bytes: self.bytes,
            max_definite,
            ph: PhantomData,
        }
    }
}

impl<'a, O: CborOutput> Writer for CborBuilder<'a, O> {
    type Output = O::Output;

    fn bytes<T>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
        f(self.bytes.as_mut())
    }

    fn into_output(self) -> Self::Output {
        O::output(self.bytes.as_slice())
    }

    fn max_definite(&self) -> Option<u64> {
        self.max_definite
    }
}

/// Builder for an array value, used by `write_array_ret()`.
///
/// see [`trait Encoder`](trait.Encoder.html) for usage examples
pub struct ArrayWriter<'a> {
    bytes: Bytes<'a>,
    count: u64,
    max_definite: Option<u64>,
}

impl<'a> ArrayWriter<'a> {
    fn new(bytes: &'a mut Vec<u8>, max_definite: Option<u64>) -> Self {
        Self {
            bytes: Bytes::Borrowed(bytes),
            count: 0,
            max_definite,
        }
    }
    fn non_tracking(&mut self, max_definite: Option<u64>) -> ArrayWriter {
        ArrayWriter {
            bytes: self.bytes.copy(),
            count: 0,
            max_definite,
        }
    }
    /// Configure the limit above which indefinite size encoding will be used.
    ///
    /// The default is 255, which is the largest size up to which definite size is at least as
    /// compact as indefinite size. Set to 23 to avoid moving bytes around when finishing the array.
    /// Set to `None` to always use indefinite size encoding.
    pub fn set_max_definite_size(&mut self, size: Option<u64>) {
        self.max_definite = size;
    }
}

impl<'a> Writer for ArrayWriter<'a> {
    type Output = Self;

    fn bytes<T>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
        self.count += 1;
        f(self.bytes.as_mut())
    }

    fn into_output(self) -> Self::Output {
        self
    }

    fn max_definite(&self) -> Option<u64> {
        self.max_definite
    }
}

/// Builder for a dict value, used by `write_dict_rec()`.
///
/// see [`trait Encoder`](trait.Encoder.html) for usage examples
pub struct DictWriter<'a>(ArrayWriter<'a>);

impl<'a> DictWriter<'a> {
    fn new(bytes: &'a mut Vec<u8>, max_definite: Option<u64>) -> Self {
        Self(ArrayWriter::new(bytes, max_definite))
    }

    /// Configure the limit above which indefinite size encoding will be used.
    ///
    /// The default is 255, which is the largest size up to which definite size is at least as
    /// compact as indefinite size. Set to 23 to avoid moving bytes around when finishing the array.
    /// Set to `None` to always use indefinite size encoding.
    pub fn set_max_definite_size(&mut self, size: Option<u64>) {
        self.0.max_definite = size;
    }

    /// Add one key–value pair to the dict.
    ///
    /// ```
    /// # use cbor_data::{CborBuilder, Writer, Encoder};
    /// let cbor = CborBuilder::new().encode_dict(|builder| {
    ///     builder.with_key("the answer", |b| b.encode_u64(42));
    /// });
    /// ```
    pub fn with_key(
        &mut self,
        key: &str,
        f: impl FnOnce(SingleBuilder<'_, '_>) -> SingleResult,
    ) -> &mut Self {
        self.with_cbor_key(|b| b.write_str(key, None), f)
    }

    pub fn with_cbor_key(
        &mut self,
        k: impl FnOnce(SingleBuilder<'_, '_>) -> SingleResult,
        v: impl FnOnce(SingleBuilder<'_, '_>) -> SingleResult,
    ) -> &mut Self {
        k(SingleBuilder(&mut self.0.non_tracking(self.0.max_definite)));
        v(SingleBuilder(&mut self.0));
        self
    }
}

/// Builder for the single value of a dict key.
///
/// This builder can be used for exactly one item (which may be a complex one, like an array)
/// and returns a [`SingleResult`](struct.SingleResult.html) to prove to its
/// [`DictWriter`](struct.DictWriter.html) that it has been used.
pub struct SingleBuilder<'a, 'b>(&'b mut ArrayWriter<'a>);

/// Result value of using a [`SingleBuilder`](struct.SingleBuilder.html) proving that it has been used.
///
/// This value needs to be returned to [`DictWriter.with_key()`](struct.DictWriter.html#method.with_key).
/// You can only obtain it by using the `SingleBuilder`.
pub struct SingleResult {
    ph: PhantomData<u8>,
}

impl<'a, 'b> Writer for SingleBuilder<'a, 'b> {
    type Output = SingleResult;

    fn bytes<T>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
        self.0.bytes(f)
    }

    fn into_output(self) -> Self::Output {
        SingleResult { ph: PhantomData }
    }

    fn max_definite(&self) -> Option<u64> {
        self.0.max_definite
    }
}

impl<T> Writer for &mut T
where
    T: Writer<Output = T>,
{
    type Output = Self;

    fn bytes<U>(&mut self, f: impl FnOnce(&mut Vec<u8>) -> U) -> U {
        (*self).bytes(f)
    }

    fn into_output(self) -> Self::Output {
        self
    }

    fn max_definite(&self) -> Option<u64> {
        (**self).max_definite()
    }
}

/// Tags are from outer to inner.
fn write_positive(bytes: &mut Vec<u8>, value: u64, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_POS, value);
}

/// Tags are from outer to inner.
fn write_neg(bytes: &mut Vec<u8>, value: u64, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_NEG, value);
}

/// Tags are from outer to inner.
fn write_str(bytes: &mut Vec<u8>, value: &str, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_STR, value.len() as u64);
    bytes.extend_from_slice(value.as_bytes());
}

/// Tags are from outer to inner.
fn write_bytes(bytes: &mut Vec<u8>, value: &[u8], tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_BYTES, value.len() as u64);
    bytes.extend_from_slice(value);
}

/// Tags are from outer to inner.
fn write_bool(bytes: &mut Vec<u8>, value: bool, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(
        bytes,
        MAJOR_LIT,
        if value {
            LIT_TRUE.into()
        } else {
            LIT_FALSE.into()
        },
    );
}

/// Tags are from outer to inner.
fn write_null(bytes: &mut Vec<u8>, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_LIT, LIT_NULL.into());
}

/// Tags are from outer to inner.
fn write_undefined(bytes: &mut Vec<u8>, tags: impl IntoIterator<Item = u64>) {
    write_tags(bytes, tags);
    write_info(bytes, MAJOR_LIT, LIT_UNDEFINED.into());
}

/// Tags are from outer to inner.
pub(crate) fn write_tags(bytes: &mut Vec<u8>, tags: impl IntoIterator<Item = u64>) {
    for tag in tags {
        write_info(bytes, MAJOR_TAG, tag);
    }
}

fn write_info(bytes: &mut Vec<u8>, major: u8, value: u64) -> usize {
    if value < 24 {
        bytes.push(major << 5 | (value as u8));
        1
    } else if value < 0x100 {
        bytes.push(major << 5 | 24);
        bytes.push(value as u8);
        2
    } else if value < 0x1_0000 {
        bytes.push(major << 5 | 25);
        bytes.push((value >> 8) as u8);
        bytes.push(value as u8);
        3
    } else if value < 0x1_0000_0000 {
        bytes.push(major << 5 | 26);
        bytes.push((value >> 24) as u8);
        bytes.push((value >> 16) as u8);
        bytes.push((value >> 8) as u8);
        bytes.push(value as u8);
        5
    } else {
        bytes.push(major << 5 | 27);
        bytes.push((value >> 56) as u8);
        bytes.push((value >> 48) as u8);
        bytes.push((value >> 40) as u8);
        bytes.push((value >> 32) as u8);
        bytes.push((value >> 24) as u8);
        bytes.push((value >> 16) as u8);
        bytes.push((value >> 8) as u8);
        bytes.push(value as u8);
        9
    }
}

fn write_lit(bytes: &mut Vec<u8>, value: Literal) {
    match value {
        Literal::L0(v) => bytes.push(MAJOR_LIT << 5 | v),
        Literal::L1(v) => {
            bytes.push(MAJOR_LIT << 5 | 24);
            bytes.push(v);
        }
        Literal::L2(v) => {
            bytes.push(MAJOR_LIT << 5 | 25);
            bytes.push((v >> 8) as u8);
            bytes.push(v as u8);
        }
        Literal::L4(v) => {
            bytes.push(MAJOR_LIT << 5 | 26);
            bytes.push((v >> 24) as u8);
            bytes.push((v >> 16) as u8);
            bytes.push((v >> 8) as u8);
            bytes.push(v as u8);
        }
        Literal::L8(v) => {
            bytes.push(MAJOR_LIT << 5 | 27);
            bytes.push((v >> 56) as u8);
            bytes.push((v >> 48) as u8);
            bytes.push((v >> 40) as u8);
            bytes.push((v >> 32) as u8);
            bytes.push((v >> 24) as u8);
            bytes.push((v >> 16) as u8);
            bytes.push((v >> 8) as u8);
            bytes.push(v as u8);
        }
    }
}

fn write_indefinite(bytes: &mut Vec<u8>, major: u8) {
    bytes.push(major << 5 | INDEFINITE_SIZE);
}

fn finish_array(count: u64, b: &mut Vec<u8>, pos: usize, major: u8, max_definite: Option<u64>) {
    if Some(count) > max_definite {
        // indefinite encoding saves bytes here
        b.push(STOP_BYTE);
    } else {
        // otherwise prefer definite encoding
        let end = b.len();
        // use main vector as scratch space, will clean up below
        let head_len = write_info(b, major, count);
        if head_len > 1 {
            // save header bytes onto stack
            let mut buf = [0u8; 9];
            let buf = &mut buf[0..head_len];
            buf.copy_from_slice(&b[end..]);
            // need to shift back the array contents to make room for longer header
            let to_move = pos + 1..end;
            let new_start = pos + head_len;
            b.copy_within(to_move, new_start);
            // now put the new header in place
            b[pos..new_start].copy_from_slice(buf);
        } else {
            b[pos] = b[end];
        }
        // written header included the `pos` byte, so clean up
        b.pop();
    }
}