light-zero-copy 0.7.0

Zero copy vector and utils for Solana programs.
Documentation
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
#![cfg(all(feature = "std", feature = "derive"))]

use std::{ops::Deref, vec};

use borsh::{BorshDeserialize, BorshSerialize};
use light_zero_copy::{
    errors::ZeroCopyError,
    slice::ZeroCopySliceBorsh,
    traits::{ZeroCopyAt, ZeroCopyStructInner},
};
use zerocopy::{
    little_endian::{U16, U64},
    FromBytes, Immutable, IntoBytes, KnownLayout, Ref, Unaligned,
};

// Rules:
// 1. create ZStruct for the struct
//      1.1. the first fields are extracted into a meta struct until we reach a Vec, Option or type that does not implement Copy, and we implement deref for the meta struct
//      1.2. represent vectors to ZeroCopySlice & don't include these into the meta struct
//      1.3. replace u16 with U16, u32 with U32, etc
//      1.4. every field after the first vector is directly included in the ZStruct and deserialized 1 by 1
//      1.5. If a vector contains a nested vector (does not implement Copy) it  must implement Deserialize
//      1.6. Elements in an Option must implement Deserialize
//      1.7. a type that does not implement Copy must implement Deserialize, and is deserialized 1 by 1

// Derive Macro needs to derive:
//  1. ZeroCopyStructInner
// 2. Deserialize
// 3. PartialEq<Struct> for ZStruct<'_>
//
// For every struct1 - struct7 create struct_derived1 - struct_derived7 and replicate the tests for the new structs.

// Tests for manually implemented structures (without derive macro)

#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct1 {
    pub a: u8,
    pub b: u16,
}

// pub fn data_hash_struct_1(a: u8, b: u16) -> [u8; 32] {

// }

#[repr(C)]
#[derive(Debug, PartialEq, KnownLayout, Immutable, Unaligned, FromBytes)]
pub struct ZStruct1Meta {
    pub a: u8,
    pub b: U16,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct1<'a> {
    meta: Ref<&'a [u8], ZStruct1Meta>,
}
impl<'a> Deref for ZStruct1<'a> {
    type Target = Ref<&'a [u8], ZStruct1Meta>;

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

impl<'a> ZeroCopyAt<'a> for Struct1 {
    type ZeroCopyAt = ZStruct1<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (meta, bytes) = Ref::<&[u8], ZStruct1Meta>::from_prefix(bytes)?;
        Ok((ZStruct1 { meta }, bytes))
    }
}

#[test]
fn test_struct_1() {
    let bytes = Struct1 { a: 1, b: 2 }.try_to_vec().unwrap();
    let (struct1, remaining) = Struct1::zero_copy_at(&bytes).unwrap();
    assert_eq!(struct1.a, 1u8);
    assert_eq!(struct1.b, 2u16);
    assert_eq!(remaining, &[]);
}

#[repr(C)]
#[derive(Debug, PartialEq, Clone, BorshSerialize, BorshDeserialize)]
pub struct Struct2 {
    pub a: u8,
    pub b: u16,
    pub vec: Vec<u8>,
}

#[repr(C)]
#[derive(Debug, PartialEq, KnownLayout, Immutable, Unaligned, FromBytes)]
pub struct ZStruct2Meta {
    pub a: u8,
    pub b: U16,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct2<'a> {
    meta: Ref<&'a [u8], ZStruct2Meta>,
    pub vec: <Vec<u8> as ZeroCopyStructInner>::ZeroCopyInner,
}

impl PartialEq<Struct2> for ZStruct2<'_> {
    fn eq(&self, other: &Struct2) -> bool {
        let meta: &ZStruct2Meta = &self.meta;
        if meta.a != other.a || other.b != meta.b.into() {
            return false;
        }
        self.vec.as_slice() == other.vec.as_slice()
    }
}

impl<'a> Deref for ZStruct2<'a> {
    type Target = Ref<&'a [u8], ZStruct2Meta>;

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

impl<'a> ZeroCopyAt<'a> for Struct2 {
    type ZeroCopyAt = ZStruct2<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (meta, bytes) = Ref::<&[u8], ZStruct2Meta>::from_prefix(bytes)?;
        let (vec, bytes) = <Vec<u8> as ZeroCopyAt>::zero_copy_at(bytes)?;
        Ok((ZStruct2 { meta, vec }, bytes))
    }
}

#[test]
fn test_struct_2() {
    let bytes = Struct2 {
        a: 1,
        b: 2,
        vec: vec![1u8; 32],
    }
    .try_to_vec()
    .unwrap();
    let (struct2, remaining) = Struct2::zero_copy_at(&bytes).unwrap();
    assert_eq!(struct2.a, 1u8);
    assert_eq!(struct2.b, 2u16);
    assert_eq!(struct2.vec.to_vec(), vec![1u8; 32]);
    assert_eq!(remaining, &[]);
}

#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct3 {
    pub a: u8,
    pub b: u16,
    pub vec: Vec<u8>,
    pub c: u64,
}

#[repr(C)]
#[derive(Debug, PartialEq, KnownLayout, Immutable, Unaligned, FromBytes)]
pub struct ZStruct3Meta {
    pub a: u8,
    pub b: U16,
}

#[derive(Debug, PartialEq)]
pub struct ZStruct3<'a> {
    meta: Ref<&'a [u8], ZStruct3Meta>,
    pub vec: ZeroCopySliceBorsh<'a, u8>,
    pub c: Ref<&'a [u8], U64>,
}

impl<'a> Deref for ZStruct3<'a> {
    type Target = Ref<&'a [u8], ZStruct3Meta>;

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

impl<'a> ZeroCopyAt<'a> for Struct3 {
    type ZeroCopyAt = ZStruct3<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (meta, bytes) = Ref::<&[u8], ZStruct3Meta>::from_prefix(bytes)?;
        let (vec, bytes) = ZeroCopySliceBorsh::zero_copy_at(bytes)?;
        let (c, bytes) = Ref::<&[u8], U64>::from_prefix(bytes)?;
        Ok((ZStruct3 { meta, vec, c }, bytes))
    }
}

#[test]
fn test_struct_3() {
    let bytes = Struct3 {
        a: 1,
        b: 2,
        vec: vec![1u8; 32],
        c: 3,
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct3::zero_copy_at(&bytes).unwrap();
    assert_eq!(zero_copy.a, 1u8);
    assert_eq!(zero_copy.b, 2u16);
    assert_eq!(zero_copy.vec.to_vec(), vec![1u8; 32]);
    assert_eq!(u64::from(*zero_copy.c), 3);
    assert_eq!(remaining, &[]);
}

#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize, Clone)]
pub struct Struct4Nested {
    a: u8,
    b: u16,
}

#[repr(C)]
#[derive(
    Debug, PartialEq, Copy, Clone, KnownLayout, Immutable, IntoBytes, Unaligned, FromBytes,
)]
pub struct ZStruct4Nested {
    pub a: u8,
    pub b: U16,
}

impl ZeroCopyStructInner for Struct4Nested {
    type ZeroCopyInner = ZStruct4Nested;
}

#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct4 {
    pub a: u8,
    pub b: u16,
    pub vec: Vec<u8>,
    pub c: u64,
    pub vec_2: Vec<Struct4Nested>,
}

#[repr(C)]
#[derive(Debug, PartialEq, KnownLayout, Immutable, Unaligned, IntoBytes, FromBytes)]
pub struct ZStruct4Meta {
    pub a: <u8 as ZeroCopyStructInner>::ZeroCopyInner,
    pub b: <u16 as ZeroCopyStructInner>::ZeroCopyInner,
}

#[derive(Debug, PartialEq)]
pub struct ZStruct4<'a> {
    meta: Ref<&'a [u8], ZStruct4Meta>,
    pub vec: ZeroCopySliceBorsh<'a, <u8 as ZeroCopyStructInner>::ZeroCopyInner>,
    pub c: Ref<&'a [u8], <u64 as ZeroCopyStructInner>::ZeroCopyInner>,
    pub vec_2: ZeroCopySliceBorsh<'a, <Struct4Nested as ZeroCopyStructInner>::ZeroCopyInner>,
}

impl<'a> Deref for ZStruct4<'a> {
    type Target = Ref<&'a [u8], ZStruct4Meta>;

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

impl<'a> ZeroCopyAt<'a> for Struct4 {
    type ZeroCopyAt = ZStruct4<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (meta, bytes) = Ref::<&[u8], ZStruct4Meta>::from_prefix(bytes)?;
        let (vec, bytes) = ZeroCopySliceBorsh::from_bytes_at(bytes)?;
        let (c, bytes) =
            Ref::<&[u8], <u64 as ZeroCopyStructInner>::ZeroCopyInner>::from_prefix(bytes)?;
        let (vec_2, bytes) = ZeroCopySliceBorsh::from_bytes_at(bytes)?;
        Ok((
            ZStruct4 {
                meta,
                vec,
                c,
                vec_2,
            },
            bytes,
        ))
    }
}

#[test]
fn test_struct_4() {
    let bytes = Struct4 {
        a: 1,
        b: 2,
        vec: vec![1u8; 32],
        c: 3,
        vec_2: vec![Struct4Nested { a: 1, b: 2 }; 32],
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct4::zero_copy_at(&bytes).unwrap();
    assert_eq!(zero_copy.a, 1u8);
    assert_eq!(zero_copy.b, 2u16);
    assert_eq!(zero_copy.vec.to_vec(), vec![1u8; 32]);
    assert_eq!(u64::from(*zero_copy.c), 3);
    assert_eq!(
        zero_copy.vec_2.to_vec(),
        vec![ZStruct4Nested { a: 1, b: 2.into() }; 32]
    );
    assert_eq!(remaining, &[]);
}

#[repr(C)]
#[derive(Debug, Clone, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct5 {
    pub a: Vec<Vec<u8>>,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct5<'a> {
    pub a: Vec<ZeroCopySliceBorsh<'a, <u8 as ZeroCopyStructInner>::ZeroCopyInner>>,
}

impl<'a> ZeroCopyAt<'a> for Struct5 {
    type ZeroCopyAt = ZStruct5<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (a, bytes) =
            Vec::<ZeroCopySliceBorsh<<u8 as ZeroCopyStructInner>::ZeroCopyInner>>::zero_copy_at(
                bytes,
            )?;
        Ok((ZStruct5 { a }, bytes))
    }
}

#[test]
fn test_struct_5() {
    let bytes = Struct5 {
        a: vec![vec![1u8; 32]; 32],
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct5::zero_copy_at(&bytes).unwrap();
    assert_eq!(
        zero_copy.a.iter().map(|x| x.to_vec()).collect::<Vec<_>>(),
        vec![vec![1u8; 32]; 32]
    );
    assert_eq!(remaining, &[]);
}

// If a struct inside a vector contains a vector it must implement Deserialize.
#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct6 {
    pub a: Vec<Struct2>,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct6<'a> {
    pub a: Vec<<Struct2 as ZeroCopyAt<'a>>::ZeroCopyAt>,
}

impl<'a> ZeroCopyAt<'a> for Struct6 {
    type ZeroCopyAt = ZStruct6<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (a, bytes) = Vec::<Struct2>::zero_copy_at(bytes)?;
        Ok((ZStruct6 { a }, bytes))
    }
}

#[test]
fn test_struct_6() {
    let bytes = Struct6 {
        a: vec![
            Struct2 {
                a: 1,
                b: 2,
                vec: vec![1u8; 32],
            };
            32
        ],
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct6::zero_copy_at(&bytes).unwrap();
    assert_eq!(
        zero_copy.a.iter().collect::<Vec<_>>(),
        vec![
            &Struct2 {
                a: 1,
                b: 2,
                vec: vec![1u8; 32],
            };
            32
        ]
    );
    assert_eq!(remaining, &[]);
}

#[repr(C)]
#[derive(Debug, PartialEq, Clone, BorshSerialize, BorshDeserialize)]
pub struct Struct7 {
    pub a: u8,
    pub b: u16,
    pub option: Option<u8>,
}

#[repr(C)]
#[derive(Debug, PartialEq, KnownLayout, Immutable, Unaligned, FromBytes)]
pub struct ZStruct7Meta {
    pub a: u8,
    pub b: U16,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct7<'a> {
    meta: Ref<&'a [u8], ZStruct7Meta>,
    pub option: <Option<u8> as ZeroCopyStructInner>::ZeroCopyInner,
}

impl PartialEq<Struct7> for ZStruct7<'_> {
    fn eq(&self, other: &Struct7) -> bool {
        let meta: &ZStruct7Meta = &self.meta;
        if meta.a != other.a || other.b != meta.b.into() {
            return false;
        }
        self.option == other.option
    }
}

impl<'a> Deref for ZStruct7<'a> {
    type Target = Ref<&'a [u8], ZStruct7Meta>;

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

impl<'a> ZeroCopyAt<'a> for Struct7 {
    type ZeroCopyAt = ZStruct7<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (meta, bytes) = Ref::<&[u8], ZStruct7Meta>::from_prefix(bytes)?;
        let (option, bytes) = <Option<u8> as ZeroCopyAt>::zero_copy_at(bytes)?;
        Ok((ZStruct7 { meta, option }, bytes))
    }
}

#[test]
fn test_struct_7() {
    let bytes = Struct7 {
        a: 1,
        b: 2,
        option: Some(3),
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct7::zero_copy_at(&bytes).unwrap();
    assert_eq!(zero_copy.a, 1u8);
    assert_eq!(zero_copy.b, 2u16);
    assert_eq!(zero_copy.option, Some(3));
    assert_eq!(remaining, &[]);

    let bytes = Struct7 {
        a: 1,
        b: 2,
        option: None,
    }
    .try_to_vec()
    .unwrap();
    let (zero_copy, remaining) = Struct7::zero_copy_at(&bytes).unwrap();
    assert_eq!(zero_copy.a, 1u8);
    assert_eq!(zero_copy.b, 2u16);
    assert_eq!(zero_copy.option, None);
    assert_eq!(remaining, &[]);
}

// If a struct inside a vector contains a vector it must implement Deserialize.
#[repr(C)]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct Struct8 {
    pub a: Vec<NestedStruct>,
}

#[derive(Debug, Clone, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct NestedStruct {
    pub a: u8,
    pub b: Struct2,
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZNestedStruct<'a> {
    pub a: <u8 as ZeroCopyStructInner>::ZeroCopyInner,
    pub b: <Struct2 as ZeroCopyAt<'a>>::ZeroCopyAt,
}

impl<'a> ZeroCopyAt<'a> for NestedStruct {
    type ZeroCopyAt = ZNestedStruct<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (a, bytes) = <u8 as ZeroCopyStructInner>::ZeroCopyInner::zero_copy_at(bytes)?;
        let (b, bytes) = <Struct2 as ZeroCopyAt>::zero_copy_at(bytes)?;
        Ok((ZNestedStruct { a, b }, bytes))
    }
}

impl PartialEq<NestedStruct> for ZNestedStruct<'_> {
    fn eq(&self, other: &NestedStruct) -> bool {
        self.a == other.a && self.b == other.b
    }
}

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct ZStruct8<'a> {
    pub a: Vec<<NestedStruct as ZeroCopyAt<'a>>::ZeroCopyAt>,
}

impl<'a> ZeroCopyAt<'a> for Struct8 {
    type ZeroCopyAt = ZStruct8<'a>;

    fn zero_copy_at(
        bytes: &'a [u8],
    ) -> Result<(<Self as ZeroCopyAt<'a>>::ZeroCopyAt, &'a [u8]), ZeroCopyError> {
        let (a, bytes) = Vec::<NestedStruct>::zero_copy_at(bytes)?;
        Ok((ZStruct8 { a }, bytes))
    }
}

#[test]
fn test_struct_8() {
    let bytes = Struct8 {
        a: vec![
            NestedStruct {
                a: 1,
                b: Struct2 {
                    a: 1,
                    b: 2,
                    vec: vec![1u8; 32],
                },
            };
            32
        ],
    }
    .try_to_vec()
    .unwrap();

    let (zero_copy, remaining) = Struct8::zero_copy_at(&bytes).unwrap();
    assert_eq!(
        zero_copy.a.iter().collect::<Vec<_>>(),
        vec![
            &NestedStruct {
                a: 1,
                b: Struct2 {
                    a: 1,
                    b: 2,
                    vec: vec![1u8; 32],
                },
            };
            32
        ]
    );
    assert_eq!(remaining, &[]);
}