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
use core::fmt::Debug;
use core::ops::{Bound, Deref, DerefMut, Range, RangeBounds};

/// An instance of data owns a block of data. It implements `AsRef<[u8]>` and `AsMut<[u8]>` to allow
/// borrowing that data, and it has a [Data::into_subregion] function that cuts away bytes at either
/// end of the block and returns a [Data] instance that (semantically) owns a subrange of the original
/// [Data] instance. This works without copying. Implementation wise, the new instance still owns and
/// holds all of the data, just the accessors got limited to a smaller subrange.
///
/// That means this struct is great if you need to handle data blocks, cut away headers and pass ownership
/// of the remaining data on to something else without having to copy it. The downside is that the
/// header data isn't freed up - as long as any subregion of the original data exists somewhere,
/// the whole data has to be kept in memory.
#[derive(Clone)]
pub struct Data<S> {
    storage: S,
    // region stores the subregion in the vector that we care for.
    // TODO We're probably safer with an invariant that 0 <= range.start <= range.end <= storage.len(). Otherwise we'd have to think about the other case everywhere.
    region: Range<usize>,
}

// TODO region should be a type parameter so that binary-layout can guarantee it's evaluated at compile time

impl<S> Data<S> {
    /// Return the length of the [Data] instance (or if it is a subregion, length of the subregion)
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.region.len()
    }

    /// Returns true if the [Data] instance contains data and false if it has a zero length.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.region.is_empty()
    }

    /// Return a [Data] instance that semantically only represents a subregion of the original instance.
    /// Using any data accessors like `AsRef<[u8]>` or `AsMut<[u8]>` on the new instance will behave
    /// as if the instance only owned the subregion.
    ///
    /// Creating subregions is super fast and does not incur a copy.
    /// Note, however, that this is implemented by keeping all of the original data in memory and just
    /// changing the behavior of the accessors. The memory will only be freed once the subregion instance
    /// gets dropped.
    #[inline]
    pub fn into_subregion(self, range: impl RangeBounds<usize> + Debug) -> Self {
        let start_bound_diff = match range.start_bound() {
            Bound::Unbounded => 0,
            Bound::Included(&x) => x,
            Bound::Excluded(&x) => x + 1,
        };
        let panic_end_out_of_bounds = || {
            panic!(
                "Range end out of bounds. Tried to access subregion {:?} for a Data instance of length {}",
                range,
                self.region.len(),
            );
        };
        let end_bound_diff = match range.end_bound() {
            Bound::Unbounded => 0,
            Bound::Included(&x) => self
                .region
                .len()
                .checked_sub(x + 1)
                .unwrap_or_else(panic_end_out_of_bounds),
            Bound::Excluded(&x) => self
                .region
                .len()
                .checked_sub(x)
                .unwrap_or_else(panic_end_out_of_bounds),
        };
        Self {
            storage: self.storage,
            region: Range {
                start: self.region.start + start_bound_diff,
                end: self.region.end - end_bound_diff,
            },
        }
    }
}

impl<S> From<S> for Data<S>
where
    S: AsRef<[u8]>,
{
    /// Create a new [Data] object from a given `Vec<[u8]>` allocation.
    #[inline(always)]
    fn from(data: S) -> Data<S> {
        let len = data.as_ref().len();
        Self {
            storage: data,
            region: 0..len,
        }
    }
}

impl<S> AsRef<[u8]> for Data<S>
where
    S: AsRef<[u8]>,
{
    #[inline(always)]
    fn as_ref(&self) -> &[u8] {
        &self.storage.as_ref()[self.region.clone()]
    }
}

impl<S> AsMut<[u8]> for Data<S>
where
    S: AsMut<[u8]>,
{
    #[inline(always)]
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.storage.as_mut()[self.region.clone()]
    }
}

// TODO Test
impl<S> Deref for Data<S>
where
    S: AsRef<[u8]>,
{
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &[u8] {
        self.as_ref()
    }
}

// TODO Test
impl<S> DerefMut for Data<S>
where
    S: AsRef<[u8]> + AsMut<[u8]>,
{
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut [u8] {
        self.as_mut()
    }
}

impl<'a> Data<&'a [u8]> {
    /// Transform the [Data] object into a slice for the data pointed to.
    /// This also extracts the lifetime and can be useful to get an object
    /// whose lifetime isn't bound to the view or any local object anymore,
    /// but instead bound to the original storage of the View.
    ///
    /// Example:
    /// ---------------
    /// ```
    /// use binary_layout::define_layout;
    ///
    /// define_layout!(my_layout, LittleEndian, {
    ///   field: u16,
    ///   data: [u8],
    /// });
    ///
    /// fn func(input: &[u8]) -> &[u8] {
    ///   let view = my_layout::View::new(input);
    ///   // Returning `view.data_mut()` doesn't work because its lifetime is bound to the local `view` object.
    ///   // But we can return the following
    ///   view.into_data().into_slice()
    /// }
    ///
    /// let data = vec![0; 1024];
    /// assert_eq!(0, func(&data)[0]);
    /// ```
    pub fn into_slice(self) -> &'a [u8] {
        &self.storage[self.region]
    }
}

impl<'a> Data<&'a mut [u8]> {
    /// Transform the [Data] object into a slice for the data pointed to.
    /// This also extracts the lifetime and can be useful to get an object
    /// whose lifetime isn't bound to the view or any local object anymore,
    /// but instead bound to the original storage of the View.
    ///
    /// Example:
    /// ---------------
    /// ```
    /// use binary_layout::define_layout;
    ///
    /// define_layout!(my_layout, LittleEndian, {
    ///   field: u16,
    ///   data: [u8],
    /// });
    ///
    /// fn func(input: &mut [u8]) -> &mut [u8] {
    ///   let view = my_layout::View::new(input);
    ///   // Returning `view.data_mut()` doesn't work because its lifetime is bound to the local `view` object.
    ///   // But we can return the following
    ///   view.into_data().into_slice()
    /// }
    ///
    /// let mut data = vec![0; 1024];
    /// func(&mut data)[0] = 5;
    /// ```
    pub fn into_slice(self) -> &'a mut [u8] {
        &mut self.storage[self.region]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::{rngs::StdRng, RngCore, SeedableRng};

    fn data_region(size: usize, seed: u64) -> Vec<u8> {
        let mut rng = StdRng::seed_from_u64(seed);
        let mut res = vec![0; size];
        rng.fill_bytes(&mut res);
        res
    }

    #[test]
    fn given_fullrangedata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        assert_eq!(data.as_ref(), &data_region(1024, 0));
    }

    #[test]
    fn given_fullrangedata_when_callingasmut() {
        let mut data: Data<_> = data_region(1024, 0).into();
        assert_eq!(data.as_mut(), &data_region(1024, 0));
    }

    #[test]
    fn given_fullsubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(..);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0));
    }

    #[test]
    fn given_fullsubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(..);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0));
    }

    #[test]
    fn given_openendsubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(5..);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0)[5..]);
    }

    #[test]
    fn given_openendsubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(5..);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0)[5..]);
    }

    #[test]
    fn given_openbeginningexclusivesubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(..1000);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0)[..1000]);
    }

    #[test]
    fn given_openbeginningexclusivesubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(..1000);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0)[..1000]);
    }

    #[test]
    fn given_openbeginninginclusivesubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(..=1000);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0)[..=1000]);
    }

    #[test]
    fn given_openbeginninginclusivesubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(..=1000);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0)[..=1000]);
    }

    #[test]
    fn given_exclusivesubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(5..1000);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0)[5..1000]);
    }

    #[test]
    fn given_exclusivesubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(5..1000);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0)[5..1000]);
    }

    #[test]
    fn given_inclusivesubregiondata_when_callingasref() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data.into_subregion(5..=1000);
        assert_eq!(subdata.as_ref(), &data_region(1024, 0)[5..=1000]);
    }

    #[test]
    fn given_inclusivesubregiondata_when_callingasmut() {
        let data: Data<_> = data_region(1024, 0).into();
        let mut subdata = data.into_subregion(5..=1000);
        assert_eq!(subdata.as_mut(), &data_region(1024, 0)[5..=1000]);
    }

    #[test]
    fn nested_subregions_still_do_the_right_thing() {
        let data: Data<_> = data_region(1024, 0).into();
        let subdata = data
            .into_subregion(..)
            .into_subregion(5..)
            .into_subregion(..1000)
            .into_subregion(..=950)
            .into_subregion(10..900)
            .into_subregion(3..=800)
            // and all types of ranges again, just in case they don't work if a certain other range happens beforehand
            .into_subregion(..)
            .into_subregion(5..)
            .into_subregion(..700)
            .into_subregion(..=650)
            .into_subregion(10..600)
            .into_subregion(3..=500);
        assert_eq!(
            subdata.as_ref(),
            &data_region(1024, 0)[..][5..][..1000][..=950][10..900][3..=800][..][5..][..700]
                [..=650][10..600][3..=500]
        );
    }

    #[test]
    #[should_panic(
        expected = "Range end out of bounds. Tried to access subregion ..=1024 for a Data instance of length 1024"
    )]
    fn given_fullrangedata_when_tryingtogrowendbeyondlength_with_inclusiverange_then_panics() {
        let data: Data<_> = data_region(1024, 0).into();
        data.into_subregion(..=1024);
    }

    #[test]
    #[should_panic(
        expected = "Range end out of bounds. Tried to access subregion ..=100 for a Data instance of length 100"
    )]
    fn given_subrangedata_when_tryingtogrowendbeyondlength_with_inclusiverange_then_panics() {
        let data: Data<_> = data_region(1024, 0).into();
        let data = data.into_subregion(0..100);
        data.into_subregion(..=100);
    }

    #[test]
    #[should_panic(
        expected = "Range end out of bounds. Tried to access subregion ..1025 for a Data instance of length 1024"
    )]
    fn given_fullrangedata_when_tryingtogrowendbeyondlength_with_exclusiverange_then_panics() {
        let data: Data<_> = data_region(1024, 0).into();
        data.into_subregion(..1025);
    }

    #[test]
    #[should_panic(
        expected = "Range end out of bounds. Tried to access subregion ..101 for a Data instance of length 100"
    )]
    fn given_subrangedata_when_tryingtogrowendbeyondlength_with_exclusiverange_then_panics() {
        let data: Data<_> = data_region(1024, 0).into();
        let data = data.into_subregion(0..100);
        data.into_subregion(..101);
    }

    #[test]
    fn given_fullrangedata_when_tryingtogrowstartbeyondend_then_returnszerolengthrange() {
        let data: Data<_> = data_region(1024, 0).into();
        #[allow(clippy::reversed_empty_ranges)]
        let data = data.into_subregion(5000..400);
        assert_eq!(0, data.len());
    }
}