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 super::low_level::*;
use crate::{
    canonical::canonicalise, constants::*, ArrayWriter, Cbor, CborBuilder, DictWriter, Literal,
    ParseError,
};

/// 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.len(), [value], tags));
        self.into_output()
    }

    /// Write the given slices as a definite size byte string.
    /// Tags are from outer to inner.
    ///
    /// Example:
    /// ```rust
    /// # use cbor_data::{CborBuilder, Writer};
    /// let cbor = CborBuilder::default().write_bytes_chunked([&[0][..], &[1, 2][..]], [12]);
    /// # assert_eq!(cbor.as_slice(), vec![0xccu8, 0x43, 0, 1, 2]);
    /// ```
    fn write_bytes_chunked(
        mut self,
        value: impl IntoIterator<Item = impl AsRef<[u8]>> + Copy,
        tags: impl IntoIterator<Item = u64>,
    ) -> Self::Output {
        let len = value.into_iter().map(|x| x.as_ref().len()).sum();
        self.bytes(|b| write_bytes(b, len, 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.len(), [value], tags));
        self.into_output()
    }

    /// Write the given slice as a definite size string.
    /// Tags are from outer to inner.
    ///
    /// Example:
    /// ```rust
    /// # use cbor_data::{CborBuilder, Writer};
    /// let cbor = CborBuilder::default().write_str_chunked(["a", "b"], [12]);
    /// # assert_eq!(cbor.as_slice(), vec![0xccu8, 0x62, 0x61, 0x62]);
    /// ```
    fn write_str_chunked(
        mut self,
        value: impl IntoIterator<Item = impl AsRef<str>> + Copy,
        tags: impl IntoIterator<Item = u64>,
    ) -> Self::Output {
        let len = value.into_iter().map(|x| x.as_ref().len()).sum();
        self.bytes(|b| write_str(b, len, 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 8949 §3.3](https://www.rfc-editor.org/rfc/rfc8949#section-3.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.max_definite();
            finish_array(writer.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]) -> Result<Self::Output, ParseError> {
        let max_definite = self.max_definite();
        self.bytes(|b| {
            canonicalise(
                bytes,
                CborBuilder::append_to(b).with_max_definite_size(max_definite),
            )
        })
        .map(|_| self.into_output())
    }

    /// 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())
    }
}

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()
    }
}