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
//! Newtypes for `&[u8]`, `[u8;N]` and `Vec<u8>`.
//!
//! To support specialised encoding and decoding of byte slices, byte arrays,
//! and vectors which are represented as CBOR bytes instead of arrays of `u8`s,
//! the types `ByteSlice`, `ByteArray` and `ByteVec` (requires feature "alloc")
//! are provided. These implement [`Encode`] and [`Decode`] by translating to
//! and from CBOR bytes.
//!
//! If the feature "derive" is present, specialised traits `EncodeBytes` and
//! `DecodeBytes` are also provided. These are implemented for the
//! aforementioned newtypes as well as for their `Option` variations and
//! regular `&[u8]`, `[u8; N]` and `Vec<u8>`. They enable the direct use of
//! `&[u8]`, `[u8; N]` and `Vec<u8>` in types deriving `Encode` and `Decode`
//! if used with a `#[cbor(with = "minicbor::bytes")]` annotation.

use crate::decode::{self, Decode, Decoder};
use crate::encode::{self, Encode, Encoder, Write};
use core::ops::{Deref, DerefMut};

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

/// Re-export of `alloc::borrow::Cow`.
#[cfg(feature = "alloc")]
pub use alloc::borrow::Cow;

/// Newtype for `[u8]`.
///
/// Used to implement `Encode` and `Decode` which translate to
/// CBOR bytes instead of arrays for `u8`s.
#[repr(transparent)]
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ByteSlice([u8]);

impl<'a> From<&'a [u8]> for &'a ByteSlice {
    fn from(xs: &'a [u8]) -> Self {
        unsafe {
            &*(xs as *const [u8] as *const ByteSlice)
        }
    }
}

impl<'a> From<&'a mut [u8]> for &'a mut ByteSlice {
    fn from(xs: &'a mut [u8]) -> Self {
        unsafe {
            &mut *(xs as *mut [u8] as *mut ByteSlice)
        }
    }
}

impl Deref for ByteSlice {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for ByteSlice {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl AsRef<[u8]> for ByteSlice {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl AsMut<[u8]> for ByteSlice {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

impl<'a, 'b: 'a> Decode<'b> for &'a ByteSlice {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        d.bytes().map(<&ByteSlice>::from)
    }
}

impl Encode for ByteSlice {
    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(self)?.ok()
    }
}

#[cfg(feature = "alloc")]
impl core::borrow::Borrow<ByteSlice> for Vec<u8> {
    fn borrow(&self) -> &ByteSlice {
        self.as_slice().into()
    }
}

#[cfg(feature = "alloc")]
impl core::borrow::BorrowMut<ByteSlice> for Vec<u8> {
    fn borrow_mut(&mut self) -> &mut ByteSlice {
        self.as_mut_slice().into()
    }
}

#[cfg(feature = "alloc")]
impl core::borrow::Borrow<ByteSlice> for ByteVec {
    fn borrow(&self) -> &ByteSlice {
        self.as_slice().into()
    }
}

#[cfg(feature = "alloc")]
impl core::borrow::BorrowMut<ByteSlice> for ByteVec {
    fn borrow_mut(&mut self) -> &mut ByteSlice {
        self.as_mut_slice().into()
    }
}

impl<const N: usize> core::borrow::Borrow<ByteSlice> for ByteArray<N> {
    fn borrow(&self) -> &ByteSlice {
        self.0[..].into()
    }
}

impl<const N: usize> core::borrow::BorrowMut<ByteSlice> for ByteArray<N> {
    fn borrow_mut(&mut self) -> &mut ByteSlice {
        (&mut self.0[..]).into()
    }
}

#[cfg(feature = "alloc")]
impl alloc::borrow::ToOwned for ByteSlice {
    type Owned = ByteVec;

    fn to_owned(&self) -> Self::Owned {
        ByteVec::from(self.to_vec())
    }
}

/// Newtype for `[u8; N]`.
///
/// Used to implement `Encode` and `Decode` which translate to
/// CBOR bytes instead of arrays for `u8`s.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ByteArray<const N: usize>([u8; N]);

impl<const N: usize> From<[u8; N]> for ByteArray<N> {
    fn from(a: [u8; N]) -> Self {
        ByteArray(a)
    }
}

impl<const N: usize> From<ByteArray<N>> for [u8; N] {
    fn from(a: ByteArray<N>) -> Self {
        a.0
    }
}

impl<const N: usize> Deref for ByteArray<N> {
    type Target = [u8; N];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const N: usize> DerefMut for ByteArray<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const N: usize> AsRef<[u8; N]> for ByteArray<N> {
    fn as_ref(&self) -> &[u8; N] {
        &self.0
    }
}

impl<const N: usize> AsMut<[u8; N]> for ByteArray<N> {
    fn as_mut(&mut self) -> &mut [u8; N] {
        &mut self.0
    }
}

impl<'b, const N: usize> Decode<'b> for ByteArray<N> {
    fn decode(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        let slice = d.bytes()?;
        let array = <[u8; N]>::try_from(slice).map_err(|_| {
            decode::Error::Message("byte slice length does not match expected array length")
        })?;
        Ok(ByteArray(array))
    }
}

impl<const N: usize> Encode for ByteArray<N> {
    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(&self.0[..])?.ok()
    }
}

/// Newtype for `Vec<u8>`.
///
/// Used to implement `Encode` and `Decode` which translate to
/// CBOR bytes instead of arrays for `u8`s.
#[cfg(feature = "alloc")]
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ByteVec(Vec<u8>);

#[cfg(feature = "alloc")]
impl From<Vec<u8>> for ByteVec {
    fn from(xs: Vec<u8>) -> Self {
        ByteVec(xs)
    }
}

#[cfg(feature = "alloc")]
impl From<ByteVec> for Vec<u8> {
    fn from(b: ByteVec) -> Self {
        b.0
    }
}

#[cfg(feature = "alloc")]
impl Deref for ByteVec {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(feature = "alloc")]
impl DerefMut for ByteVec {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[cfg(feature = "alloc")]
impl Decode<'_> for ByteVec {
    fn decode(d: &mut Decoder<'_>) -> Result<Self, decode::Error> {
        d.bytes().map(|xs| xs.to_vec().into())
    }
}

#[cfg(feature = "alloc")]
impl Encode for ByteVec {
    fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(self)?.ok()
    }
}

// Traits /////////////////////////////////////////////////////////////////////

/// Like [`Encode`] but specific for encoding of byte slices.
#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub trait EncodeBytes {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>>;

    fn is_nil(&self) -> bool {
        false
    }
}

/// Like [`Decode`] but specific for decoding from byte slices.
#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub trait DecodeBytes<'b>: Sized {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error>;

    fn nil() -> Option<Self> {
        None
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'a, T: EncodeBytes + ?Sized> EncodeBytes for &'a T {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        (**self).encode_bytes(e)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl EncodeBytes for [u8] {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(self)?.ok()
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'a, 'b: 'a> DecodeBytes<'b> for &'a [u8] {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        d.bytes()
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<const N: usize> EncodeBytes for [u8; N] {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(&self[..])?.ok()
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'b, const N: usize> DecodeBytes<'b> for [u8; N] {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        ByteArray::decode(d).map(ByteArray::into)
    }
}

#[cfg(all(feature = "alloc", any(feature = "derive", feature = "partial-derive-support")))]
impl EncodeBytes for Vec<u8> {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        e.bytes(self.as_slice())?.ok()
    }
}

#[cfg(all(feature = "alloc", any(feature = "derive", feature = "partial-derive-support")))]
impl<'b> DecodeBytes<'b> for Vec<u8> {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        d.bytes().map(Vec::from)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl EncodeBytes for ByteSlice {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        Self::encode(self, e)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'a, 'b: 'a> DecodeBytes<'b> for &'a ByteSlice {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        Self::decode(d)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<const N: usize> EncodeBytes for ByteArray<N> {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        Self::encode(self, e)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'b, const N: usize> DecodeBytes<'b> for ByteArray<N> {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        Self::decode(d)
    }
}

#[cfg(all(feature = "alloc", any(feature = "derive", feature = "partial-derive-support")))]
impl EncodeBytes for ByteVec {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        Self::encode(self, e)
    }
}

#[cfg(all(feature = "alloc", any(feature = "derive", feature = "partial-derive-support")))]
impl<'b> DecodeBytes<'b> for ByteVec {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        Self::decode(d)
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<T: EncodeBytes> EncodeBytes for Option<T> {
    fn encode_bytes<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
        if let Some(x) = self {
            x.encode_bytes(e)
        } else {
            e.null()?.ok()
        }
    }

    fn is_nil(&self) -> bool {
        self.is_none()
    }
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
impl<'b, T: DecodeBytes<'b>> DecodeBytes<'b> for Option<T> {
    fn decode_bytes(d: &mut Decoder<'b>) -> Result<Self, decode::Error> {
        if crate::data::Type::Null == d.datatype()? {
            d.skip()?;
            return Ok(None)
        }
        T::decode_bytes(d).map(Some)
    }

    fn nil() -> Option<Self> {
        Some(None)
    }
}

/// Freestanding function calling `DecodeBytes::decode_bytes`.
///
/// For use in `#[cbor(with = "minicbor::bytes")]` or `#[cbor(decode_with =
/// "minicbor::bytes::decode")]`.
#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub fn decode<'b, T>(d: &mut Decoder<'b>) -> Result<T, decode::Error>
where
    T: DecodeBytes<'b>
{
    T::decode_bytes(d)
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub fn nil<'b, T>() -> Option<T>
where
    T: DecodeBytes<'b>
{
    T::nil()
}

/// Freestanding function calling `EncodeBytes::encode_bytes`.
///
/// For use in `#[cbor(with = "minicbor::bytes")]` or `#[cbor(encode_with =
/// "minicbor::bytes::encode")]`.
#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub fn encode<T, W>(xs: &T, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>>
where
    T: EncodeBytes,
    W: Write
{
    T::encode_bytes(xs, e)
}

#[cfg(any(feature = "derive", feature = "partial-derive-support"))]
pub fn is_nil<T>(xs: &T) -> bool
where
    T: EncodeBytes
{
    T::is_nil(xs)
}