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
//! A fixed-capacity octets sequence.

use core::{cmp, fmt};
use core::ops::RangeBounds;
use crate::builder::{
    EmptyBuilder, FreezeBuilder, FromBuilder, IntoBuilder, OctetsBuilder,
    ShortBuf, Truncate,
};
use crate::octets::{Octets, OctetsFrom};


//------------ Array ---------------------------------------------------------

#[derive(Clone)]
pub struct Array<const N: usize> {
    octets: [u8; N],
    len: usize
}

impl<const N: usize> Array<N> {
    /// Creates a new empty value.
    pub fn new() -> Self {
        Default::default()
    }

    /// Returns an octets slice with the content of the array.
    pub fn as_slice(&self) -> &[u8] {
        &self.octets[..self.len]
    }

    /// Returns a mutable octets slice with the content of the array.
    pub fn as_slice_mut(&mut self) -> &mut [u8] {
        &mut self.octets[..self.len]
    }

    /// Resizes the array in place updating additional octets.
    ///
    /// The method only changes the length of the contained octets
    /// sequence. If `new_len` is greater than the current length, the
    /// content of the additional octets will be left at whatever they
    /// were.
    ///
    /// Returns an error if `new_len` is larger than the array size.
    pub fn resize_raw(&mut self, new_len: usize) -> Result<(), ShortBuf> {
        if new_len >= N {
            Err(ShortBuf)
        }
        else {
            self.len = new_len;
            Ok(())
        }
    }
}


//--- Default

impl<const N: usize> Default for Array<N> {
    fn default() -> Self {
        Array {
            octets: [0; N],
            len: 0
        }
    }
}


//--- TryFrom

impl<'a, const N: usize> TryFrom<&'a [u8]> for Array<N> {
    type Error = ShortBuf;

    fn try_from(src: &'a [u8]) -> Result<Self, ShortBuf> {
        let len = src.len();
        if len > N {
            Err(ShortBuf)
        }
        else {
            let mut res = Self::default();
            res.octets[..len].copy_from_slice(src);
            res.len = len;
            Ok(res)
        }
    }
}


//--- Deref, AsRef, Borrow, and Mut versions

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

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

impl<const N: usize> core::ops::DerefMut for Array<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_slice_mut()
    }
}

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

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

impl<const N: usize> core::borrow::Borrow<[u8]> for Array<N> {
    fn borrow(&self) -> &[u8] {
        self.as_slice()
    }
}

impl<const N: usize> core::borrow::BorrowMut<[u8]> for Array<N> {
    fn borrow_mut(&mut self) -> &mut [u8] {
        self.as_slice_mut()
    }
}

//--- Truncate

impl<const N: usize> Octets for Array<N> {
    type Range<'a> = &'a [u8];

    fn range(&self, range: impl RangeBounds<usize>) -> Self::Range<'_> {
        self.as_slice().range(range)
    }
}


//--- Truncate

impl<const N: usize> Truncate for Array<N> {
    fn truncate(&mut self, len: usize) {
        self.len = cmp::min(self.len, len)
    }
}


//--- OctetsBuilder, EmptyBuilder, and FreezeBuilder

impl<const N: usize> OctetsBuilder for Array<N> {
    type AppendError = ShortBuf;

    fn append_slice(
        &mut self, slice: &[u8]
    ) -> Result<(), Self::AppendError> {
        let end = self.len + slice.len();
        if end > N {
            return Err(ShortBuf)
        }
        self.octets[self.len..end].copy_from_slice(slice);
        self.len = end;
        Ok(())
    }
}

impl<const N: usize> EmptyBuilder for Array<N> {
    fn empty() -> Self {
        Default::default()
    }

    fn with_capacity(_capacity: usize) -> Self {
        Self::empty()
    }
}

impl<const N: usize> FreezeBuilder for Array<N> {
    type Octets = Self;

    fn freeze(self) -> Self::Octets {
        self
    }
}


//--- IntoBuilder, FromBuilder

impl<const N: usize> IntoBuilder for Array<N> {
    type Builder = Self;

    fn into_builder(self) -> Self::Builder {
        self
    }
}

impl<const N: usize> FromBuilder for Array<N> {
    type Builder = Self;

    fn from_builder(builder: Self::Builder) -> Self {
        builder
    }
}


//--- OctetsFrom

impl<Source: AsRef<[u8]>, const N: usize> OctetsFrom<Source> for Array<N> {
    type Error = ShortBuf;

    fn try_octets_from(source: Source) -> Result<Self, Self::Error> {
        Self::try_from(source.as_ref())
    }
}


//--- PartialEq and Eq

impl<T: AsRef<[u8]>, const N: usize> PartialEq<T> for Array<N> {
    fn eq(&self, other: &T) -> bool {
        self.as_slice().eq(other.as_ref())
    }
}

impl<const N: usize> Eq for Array<N> { }


//--- PartialOrd and Ord

impl<T: AsRef<[u8]>, const N: usize> PartialOrd<T> for Array<N> {
    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
        self.as_slice().partial_cmp(other.as_ref())
    }
}

impl<const N: usize> Ord for Array<N> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.as_slice().cmp(other)
    }
}


//--- Hash

impl<const N: usize> core::hash::Hash for Array<N> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state)
    }
}


//--- Debug

impl<const N: usize> fmt::Debug for Array<N> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("octets::Array")
            .field(&self.as_slice())
            .finish()
    }
}


//--- SerializeOctets and DeserializeOctets

#[cfg(feature = "serde")]
impl<const N: usize> crate::serde::SerializeOctets for Array<N> {
    fn serialize_octets<S: serde::Serializer>(
        &self, serializer: S
    ) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(self.as_ref())
    }
}

#[cfg(feature = "serde")]
impl<'de, const N: usize> crate::serde::DeserializeOctets<'de> for Array<N> {
    type Visitor = ArrayVisitor<N>;

    fn deserialize_octets<D: serde::Deserializer<'de>>(
        deserializer: D
    ) -> Result<Self, D::Error> {
        Self::visitor().deserialize(deserializer)
    }

    fn deserialize_with_visitor<D, V>(
        deserializer: D,
        visitor: V,
    ) -> Result<V::Value, D::Error>
    where
        D: serde::Deserializer<'de>,
        V: serde::de::Visitor<'de>,
    {
        deserializer.deserialize_byte_buf(visitor)
    }

    fn visitor() -> Self::Visitor {
        ArrayVisitor
    }
}


//------------ ArrayVisitor ----------------------------------------------

#[cfg(feature = "serde")]
pub struct ArrayVisitor<const N: usize>;

#[cfg(feature = "serde")]
impl<const N: usize> ArrayVisitor<N> {
    pub fn deserialize<'de, D: serde::Deserializer<'de>>(
        self,
        deserializer: D,
    ) -> Result<Array<N>, D::Error> {
        deserializer.deserialize_byte_buf(self)
    }
}

#[cfg(feature = "serde")]
impl<'de, const N: usize> serde::de::Visitor<'de> for ArrayVisitor<N> {
    type Value = Array<N>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("an octet sequence")
    }

    fn visit_bytes<E: serde::de::Error>(
        self, value: &[u8]
    ) -> Result<Self::Value, E> {
        Array::try_from(value).map_err(E::custom)
    }
}