-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvec_copy.rs
1549 lines (1388 loc) · 52.8 KB
/
vec_copy.rs
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module defines a typeless homogeneous vector data structure optimized to be written to and
//! read from standard `Vec`s. It is not unlike `Vec<dyn Trait>` but stores only a single vtable
//! for all the values in the vector producing better data locality.
//!
//! [`VecCopy`] is particularly useful when dealing with plain data whose type is determined at
//! run time. Note that data is stored in the underlying byte vectors in native endian form,
//! endianness is not handled by this type.
//!
//! # Caveats
//!
//! [`VecCopy`] doesn't support zero-sized types.
//!
//! [`VecCopy`]: struct.VecCopy
use std::{
any::{Any, TypeId},
mem::{size_of, MaybeUninit},
slice,
};
// At the time of this writing, there is no evidence that there is a significant benefit in sharing
// vtables via Rc or Arc, but to make potential future refactoring easier we use the Ptr alias.
use std::boxed::Box as Ptr;
#[cfg(feature = "numeric")]
use std::fmt;
#[cfg(feature = "numeric")]
use num_traits::{cast, NumCast, Zero};
use crate::bytes::Bytes;
use crate::copy_value::*;
use crate::slice_copy::*;
use crate::vtable::*;
use crate::{ElementBytes, ElementBytesMut};
pub trait CopyElem: Any + Copy {}
impl<T> CopyElem for T where T: Any + Copy {}
/// Buffer of plain old data. The data is stored as an array of bytes (`Vec<MaybeUninit<u8>>`).
///
/// `VecCopy` keeps track of the type stored within via an explicit `TypeId` member. This allows
/// one to hide the type from the compiler and check it only when necessary. It is particularly
/// useful when the type of data is determined at runtime (e.g. when parsing numeric data).
///
/// # Safety
///
/// It is assumed that any Rust type has a valid representation in bytes. This library has an
/// inherently more relaxed requirement than crates like [`zerocopy`] or [`bytemuck`] since the
/// representative bytes cannot be modified or inspected by the safe API exposed by this library,
/// they can only be copied.
///
/// Further, the bytes representing a type are never interpreted as
/// anything other than a type with an identical `TypeId`, which are assumed to have an identical
/// memory layout throughout the execution of the program.
///
/// [`bytemuck`]: https://crates.io/crates/bytemuck
/// [`zerocopy`]: https://crates.io/crates/zerocopy
#[derive(Clone)]
pub struct VecCopy<V = ()>
where
V: ?Sized,
{
/// Raw data stored as bytes.
pub(crate) data: Vec<MaybeUninit<u8>>,
/// Number of bytes occupied by an element of this buffer.
///
/// Note: We store this instead of length because it gives us the ability to get the type size
/// when the buffer is empty.
pub(crate) element_size: usize,
/// Type encoding for hiding the type of data from the compiler.
pub(crate) element_type_id: TypeId,
pub(crate) vtable: Ptr<V>,
}
impl<V> VecCopy<V> {
/// Construct an empty `VecCopy` with a specific type.
#[inline]
pub fn with_type<T: CopyElem>() -> Self
where
V: VTable<T>,
{
// This is safe because `T` is a `CopyElem`.
unsafe { VecCopy::with_type_non_copy::<T>() }
}
/// It is unsafe to construct a `VecCopy` if `T` is not a `CopyElem`.
#[inline]
pub(crate) unsafe fn with_type_non_copy<T: Any>() -> Self
where
V: VTable<T>,
{
let element_size = size_of::<T>();
assert_ne!(element_size, 0, "VecCopy doesn't support zero sized types.");
VecCopy {
data: Vec::new(),
element_size,
element_type_id: TypeId::of::<T>(),
vtable: Ptr::new(V::build_vtable()),
}
}
/// Construct an empty `VecCopy` with a capacity for a given number of typed elements. For
/// setting byte capacity use `with_byte_capacity`.
#[inline]
pub fn with_capacity<T: CopyElem>(n: usize) -> Self
where
V: VTable<T>,
{
// This is safe because `T` is a `CopyElem`.
unsafe { VecCopy::with_capacity_non_copy::<T>(n) }
}
/// It is unsafe to construct a `VecCopy` if `T` is not `Copy`.
#[inline]
pub(crate) unsafe fn with_capacity_non_copy<T: Any>(n: usize) -> Self
where
V: VTable<T>,
{
let element_size = size_of::<T>();
assert_ne!(element_size, 0, "VecCopy doesn't support zero sized types.");
VecCopy {
data: Vec::with_capacity(n * element_size),
element_size,
element_type_id: TypeId::of::<T>(),
vtable: Ptr::new(V::build_vtable()),
}
}
/// Construct a typed `VecCopy` with a given size and filled with the specified default
/// value.
///
/// # Examples
/// ```
/// use dync::VecCopy;
/// let buf: VecCopy = VecCopy::with_size(8, 42usize); // Create buffer
/// let buf_vec: Vec<usize> = buf.into_vec().unwrap(); // Convert into `Vec`
/// assert_eq!(buf_vec, vec![42usize; 8]);
/// ```
#[inline]
pub fn with_size<T: CopyElem>(n: usize, def: T) -> Self
where
V: VTable<T>,
{
Self::from_vec(vec![def; n])
}
/// Construct a `VecCopy` from a given `Vec<T>` reusing the space already allocated by the
/// given vector.
///
/// # Examples
/// ```
/// use dync::VecCopy;
/// let vec = vec![1u8, 3, 4, 1, 2];
/// let buf: VecCopy = VecCopy::from_vec(vec.clone()); // Convert into buffer
/// let nu_vec: Vec<u8> = buf.into_vec().unwrap(); // Convert back into `Vec`
/// assert_eq!(vec, nu_vec);
/// ```
pub fn from_vec<T: CopyElem>(vec: Vec<T>) -> Self
where
V: VTable<T>,
{
// This is safe because `T` is a `CopyElem`.
unsafe { Self::from_vec_non_copy(vec) }
}
/// It is unsafe to call this for `T` that is not a `CopyElem`.
pub(crate) unsafe fn from_vec_non_copy<T: Any>(vec: Vec<T>) -> Self
where
V: VTable<T>,
{
let element_size = size_of::<T>();
assert_ne!(element_size, 0, "VecCopy doesn't support zero sized types.");
let data = {
// Replace with into_raw_parts when that stabilizes.
let mut md = std::mem::ManuallyDrop::new(vec);
let len_in_bytes = md.len() * element_size;
let capacity_in_bytes = md.capacity() * element_size;
let vec_ptr = md.as_mut_ptr() as *mut MaybeUninit<u8>;
Vec::from_raw_parts(vec_ptr, len_in_bytes, capacity_in_bytes)
};
VecCopy {
data,
element_size,
element_type_id: TypeId::of::<T>(),
vtable: Ptr::new(V::build_vtable()),
}
}
/// Construct a `VecCopy` from a given slice by copying the data.
#[inline]
pub fn from_slice<T: CopyElem>(slice: &[T]) -> Self
where
V: VTable<T>,
{
let mut vec = Vec::with_capacity(slice.len());
vec.extend_from_slice(slice);
Self::from_vec(vec)
}
/// It is unsafe to call this for `T` that is not a `CopyElem`.
#[cfg(feature = "traits")]
#[inline]
pub(crate) unsafe fn from_slice_non_copy<T: Any + Clone>(slice: &[T]) -> Self
where
V: VTable<T>,
{
let mut vec = Vec::with_capacity(slice.len());
vec.extend_from_slice(slice);
Self::from_vec_non_copy(vec)
}
}
impl<V: ?Sized> VecCopy<V> {
/// Construct a `VecCopy` with the same type as the given buffer without copying its data.
#[cfg(feature = "traits")]
#[inline]
pub fn with_type_from(other: impl Into<crate::meta::Meta<Ptr<V>>>) -> Self {
let other = other.into();
VecCopy {
data: Vec::new(),
element_size: other.element_size,
element_type_id: other.element_type_id,
vtable: other.vtable,
}
}
/// Construct a `SliceCopy` from raw bytes and type metadata.
///
/// # Safety
///
/// Almost exclusively the only inputs that are safe here are the ones returned by
/// `into_raw_parts`.
///
/// This function should not be used other than in internal APIs. It exists to enable the
/// `into_dyn` macro until `CoerceUsize` is stabilized.
#[inline]
pub unsafe fn from_raw_parts(
data: Vec<MaybeUninit<u8>>,
element_size: usize,
element_type_id: TypeId,
vtable: Ptr<V>,
) -> VecCopy<V> {
VecCopy {
data,
element_size,
element_type_id,
vtable,
}
}
/// Convert this collection into its raw components.
///
/// This function exists mainly to enable the `into_dyn` macro until `CoerceUnsized` is
/// stabilized.
#[inline]
pub fn into_raw_parts(self) -> (Vec<MaybeUninit<u8>>, usize, TypeId, Ptr<V>) {
let VecCopy {
data,
element_size,
element_type_id,
vtable,
} = self;
(data, element_size, element_type_id, vtable)
}
/// Upcast the `VecCopy` into a more general base `VecCopy`.
///
/// This function converts the underlying virtual function table into a subset of the existing
#[inline]
pub fn upcast<U: From<V>>(self) -> VecCopy<U>
where
V: Clone,
{
self.upcast_with(U::from)
}
// Helper for upcasts
#[inline]
pub fn upcast_with<U>(self, f: impl FnOnce(V) -> U) -> VecCopy<U>
where
V: Clone,
{
VecCopy {
data: self.data,
element_size: self.element_size,
element_type_id: self.element_type_id,
vtable: Ptr::new(f((*self.vtable).clone())),
}
}
/// Resizes the buffer in-place to store `new_len` elements and returns an optional
/// mutable reference to `Self`.
///
/// If `T` does not correspond to the underlying element type, then `None` is returned and the
/// `VecCopy` is left unchanged.
///
/// This function has the similar properties to `Vec::resize`.
#[inline]
pub fn resize<T: CopyElem>(&mut self, new_len: usize, value: T) -> Option<&mut Self> {
self.check_ref::<T>()?;
let size_t = size_of::<T>();
if new_len >= self.len() {
let diff = new_len - self.len();
self.reserve_bytes(diff * size_t);
for _ in 0..diff {
self.push_as(value.clone());
}
} else {
// Truncate
self.data
.resize(new_len * size_t, MaybeUninit::<u8>::uninit());
}
Some(self)
}
/// Copy data from a given slice into the current buffer.
///
/// The `VecCopy` is extended if the given slice is larger than the number of elements
/// already stored in this `VecCopy`.
#[inline]
pub fn copy_from_slice<T: CopyElem>(&mut self, slice: &[T]) -> &mut Self {
let element_size = size_of::<T>();
assert_ne!(element_size, 0, "VecCopy doesn't support zero sized types.");
let bins = slice.len() * element_size;
let byte_slice =
unsafe { slice::from_raw_parts(slice.as_ptr() as *const MaybeUninit<u8>, bins) };
self.data.resize(bins, MaybeUninit::<u8>::uninit());
self.data.copy_from_slice(byte_slice);
self.element_size = element_size;
self.element_type_id = TypeId::of::<T>();
self
}
/// Clear the data buffer without destroying its type information.
#[inline]
pub fn clear(&mut self) {
self.data.clear();
}
/// Fill the current buffer with copies of the given value. The size of the buffer is left
/// unchanged. If the given type doesn't patch the internal type, `None` is returned, otherwise
/// a mut reference to the modified buffer is returned.
///
/// # Examples
/// ```
/// use dync::VecCopy;
/// let vec = vec![1u8, 3, 4, 1, 2];
/// let mut buf: VecCopy = VecCopy::from_vec(vec.clone()); // Convert into buffer
/// buf.fill(0u8);
/// assert_eq!(buf.into_vec::<u8>().unwrap(), vec![0u8, 0, 0, 0, 0]);
/// ```
#[inline]
pub fn fill<T: CopyElem>(&mut self, def: T) -> Option<&mut Self> {
for v in self.iter_mut_as::<T>()? {
*v = def;
}
Some(self)
}
/// Add an element to this buffer.
///
/// If the type of the given element coincides with the type
/// stored by this buffer, then the modified buffer is returned via a mutable reference.
/// Otherwise, `None` is returned.
#[inline]
pub fn push_as<T: Any>(&mut self, element: T) -> Option<&mut Self> {
self.check_ref::<T>()?;
let bytes = element.as_bytes();
let result = unsafe { self.push_bytes(bytes) };
std::mem::forget(element);
result
}
/// Check if the current buffer contains elements of the specified type. Returns `Some(self)`
/// if the type matches and `None` otherwise.
#[inline]
pub fn check<T: Any>(self) -> Option<Self> {
if TypeId::of::<T>() != self.element_type_id() {
None
} else {
Some(self)
}
}
/// Check if the current buffer contains elements of the specified type. Returns `None` if the
/// check fails, otherwise a reference to self is returned.
#[inline]
pub fn check_ref<T: Any>(&self) -> Option<&Self> {
if TypeId::of::<T>() != self.element_type_id() {
None
} else {
Some(self)
}
}
/// Check if the current buffer contains elements of the specified type. Same as `check_ref`
/// but consumes and produces a mut reference to self.
#[inline]
pub fn check_mut<T: Any>(&mut self) -> Option<&mut Self> {
if TypeId::of::<T>() != self.element_type_id() {
None
} else {
Some(self)
}
}
/*
* Accessors
*/
/// Get the `TypeId` of data stored within this buffer.
#[inline]
pub fn element_type_id(&self) -> TypeId {
self.element_type_id
}
/// Get the number of elements stored in this buffer.
#[inline]
pub fn len(&self) -> usize {
debug_assert_eq!(self.data.len() % self.element_size, 0);
self.data.len() / self.element_size // element_size is guaranteed to be strictly positive
}
/// Check if there are any elements stored in this buffer.
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Get the byte capacity of this buffer.
#[inline]
pub fn byte_capacity(&self) -> usize {
self.data.capacity()
}
/// Return an iterator to a slice representing typed data.
/// Returs `None` if the given type `T` doesn't match the internal.
///
/// # Examples
/// ```
/// use dync::VecCopy;
/// let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
/// let buf: VecCopy = VecCopy::from(vec.clone()); // Convert into buffer
/// for (i, &val) in buf.iter_as::<f32>().unwrap().enumerate() {
/// assert_eq!(val, vec[i]);
/// }
/// ```
#[inline]
pub fn iter_as<T: Any>(&self) -> Option<slice::Iter<T>> {
self.as_slice_as::<T>().map(|x| x.iter())
}
/// Return an iterator to a mutable slice representing typed data.
/// Returns `None` if the given type `T` doesn't match the internal.
#[inline]
pub fn iter_mut_as<T: Any>(&mut self) -> Option<slice::IterMut<T>> {
self.as_mut_slice_as::<T>().map(|x| x.iter_mut())
}
/// Append copied items from this buffer to a given `Vec<T>`. Return the mutable reference
/// `Some(vec)` if type matched the internal type and `None` otherwise.
#[inline]
pub fn append_copy_to_vec<'a, T: CopyElem>(
&self,
vec: &'a mut Vec<T>,
) -> Option<&'a mut Vec<T>> {
let iter = self.iter_as()?;
// Allocate only after we know the type is right to prevent unnecessary allocations.
vec.reserve(self.len());
vec.extend(iter);
Some(vec)
}
/// Copies contents of `self` into the given `Vec`.
#[inline]
pub fn copy_into_vec<T: CopyElem>(&self) -> Option<Vec<T>> {
let mut vec = Vec::new();
match self.append_copy_to_vec(&mut vec) {
Some(_) => Some(vec),
None => None,
}
}
/// An alternative to using the `Into` trait. This function helps the compiler
/// determine the type `T` automatically.
#[inline]
pub fn into_vec<T: Any>(self) -> Option<Vec<T>> {
// This is safe since `T` is `CopyElem` guaranteed at construction.
unsafe { self.check::<T>().map(|x| x.reinterpret_into_vec()) }
}
/// Convert this buffer into a typed slice.
/// Returs `None` if the given type `T` doesn't match the internal.
#[inline]
pub fn as_slice_as<T: Any>(&self) -> Option<&[T]> {
let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
Some(unsafe { slice::from_raw_parts(ptr, self.len()) })
}
/// Convert this buffer into a typed mutable slice.
/// Returs `None` if the given type `T` doesn't match the internal.
#[inline]
pub fn as_mut_slice_as<T: Any>(&mut self) -> Option<&mut [T]> {
let ptr = self.check_mut::<T>()?.data.as_mut_ptr() as *mut T;
Some(unsafe { slice::from_raw_parts_mut(ptr, self.len()) })
}
/// Get `i`'th element of the buffer by value.
#[inline]
pub fn get_as<T: CopyElem>(&self, i: usize) -> Option<T> {
assert!(i < self.len());
let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
Some(unsafe { *ptr.add(i) })
}
/// Get a `const` reference to the `i`'th element of the buffer.
#[inline]
pub fn get_ref_as<T: Any>(&self, i: usize) -> Option<&T> {
assert!(i < self.len());
let ptr = self.check_ref::<T>()?.data.as_ptr() as *const T;
Some(unsafe { &*ptr.add(i) })
}
/// Get a mutable reference to the `i`'th element of the buffer.
#[inline]
pub fn get_mut_as<T: Any>(&mut self, i: usize) -> Option<&mut T> {
assert!(i < self.len());
let ptr = self.check_mut::<T>()?.data.as_mut_ptr() as *mut T;
Some(unsafe { &mut *ptr.add(i) })
}
/// Move elements from `buf` to this buffer.
///
/// The given buffer must have the same underlying type as `self`.
#[inline]
pub fn append(&mut self, buf: &mut VecCopy<V>) -> Option<&mut Self> {
if buf.element_type_id() == self.element_type_id() {
self.data.append(&mut buf.data);
Some(self)
} else {
None
}
}
/// Rotates the slice in-place such that the first `mid` elements of the slice move to the end
/// while the last `self.len() - mid` elements move to the front. After calling `rotate_left`,
/// the element previously at index `mid` will become the first element in the slice.
///
/// # Example
///
/// ```
/// use dync::*;
/// let mut buf: VecCopy = VecCopy::from_vec(vec![1u32,2,3,4,5]);
/// buf.rotate_left(3);
/// assert_eq!(buf.as_slice_as::<u32>().unwrap(), &[4,5,1,2,3]);
/// ```
#[inline]
pub fn rotate_left(&mut self, mid: usize) {
self.data.rotate_left(mid * self.element_size);
}
/// Rotates the slice in-place such that the first `self.len() - k` elements of the slice move
/// to the end while the last `k` elements move to the front. After calling `rotate_right`, the
/// element previously at index `k` will become the first element in the slice.
///
/// # Example
///
/// ```
/// use dync::*;
/// let mut buf: VecCopy = VecCopy::from_vec(vec![1u32,2,3,4,5]);
/// buf.rotate_right(3);
/// assert_eq!(buf.as_slice_as::<u32>().unwrap(), &[3,4,5,1,2]);
/// ```
#[inline]
pub fn rotate_right(&mut self, k: usize) {
self.data.rotate_right(k * self.element_size);
}
/*
* Value API. This allows users to manipulate contained data without knowing the element type.
*/
/// Get a reference to a value stored in this container at index `i`.
#[inline]
pub fn get_ref(&self, i: usize) -> CopyValueRef<V> {
debug_assert!(i < self.len());
// This call is safe since our buffer guarantees that the given bytes have the
// corresponding TypeId.
unsafe {
CopyValueRef::from_raw_parts(
self.get_bytes(i),
self.element_type_id(),
self.vtable.as_ref(),
)
}
}
/// Get a mutable reference to a value stored in this container at index `i`.
#[inline]
pub fn get_mut(&mut self, i: usize) -> CopyValueMut<V> {
debug_assert!(i < self.len());
let type_id = self.element_type_id();
let element_bytes = self.index_byte_range(i);
unsafe {
CopyValueMut::from_raw_parts(
&mut self.data[element_bytes],
type_id,
self.vtable.as_ref(),
)
}
}
/// Return an iterator over untyped value references stored in this buffer.
///
/// In contrast to `iter`, this function defers downcasting on a per element basis.
/// As a result, this type of iteration is typically less efficient if a typed value is needed
/// for each element.
///
/// # Examples
/// ```
/// use dync::VecCopy;
/// let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
/// let buf: VecCopy = VecCopy::from(vec.clone()); // Convert into buffer
/// for (i, val) in buf.iter().enumerate() {
/// assert_eq!(val.downcast::<f32>().unwrap(), &vec[i]);
/// }
/// ```
#[inline]
pub fn iter<'a>(&'a self) -> impl Iterator<Item = CopyValueRef<'a, V>> + 'a {
self.byte_chunks().map(move |bytes| unsafe {
CopyValueRef::from_raw_parts(bytes, self.element_type_id(), &*self.vtable)
})
}
/// Return an iterator over untyped value references stored in this buffer.
///
/// In contrast to `iter`, this function defers downcasting on a per element basis.
/// As a result, this type of iteration is typically less efficient if a typed value is needed
/// for each element.
///
/// # Examples
/// ```
/// use dync::*;
/// let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
/// let mut buf: VecCopy = VecCopy::from(vec.clone()); // Convert into buffer
/// for (i, val) in buf.iter_mut().enumerate() {
/// val.copy(CopyValueRef::new(&100.0f32));
/// }
/// assert_eq!(buf.into_vec::<f32>().unwrap(), vec![100.0f32; 5]);
/// ```
#[inline]
pub fn iter_mut(&mut self) -> impl Iterator<Item = CopyValueMut<V>> {
let &mut VecCopy {
ref mut data,
element_size,
element_type_id,
ref vtable,
} = self;
let vtable = vtable.as_ref();
data.chunks_exact_mut(element_size)
.map(move |bytes| unsafe {
CopyValueMut::from_raw_parts(bytes, element_type_id, vtable)
})
}
/// Push a value to this `VecCopy` by reference and return a mutable reference to `Self`.
///
/// If the type of the value doesn't match the internal element type, return `None`.
///
/// Note that it is not necessary for vtables of the value and this vector to match. IF the
/// types coincide, we know that either of the vtables is valid, so we just stick with the one
/// we already have in the container.
///
/// # Panics
///
/// This function panics if the size of the given value doesn't match the size of the stored
/// value.
#[inline]
pub fn push<U>(&mut self, value: CopyValueRef<U>) -> Option<&mut Self> {
assert_eq!(value.size(), self.element_size());
if value.value_type_id() == self.element_type_id() {
self.data.extend_from_slice(value.bytes);
Some(self)
} else {
None
}
}
#[inline]
pub fn as_slice(&self) -> SliceCopy<V> {
let &VecCopy {
ref data,
element_size,
element_type_id,
ref vtable,
} = self;
unsafe { SliceCopy::from_raw_parts(data, element_size, element_type_id, vtable.as_ref()) }
}
#[inline]
pub fn as_mut_slice(&mut self) -> SliceCopyMut<V> {
let &mut VecCopy {
ref mut data,
element_size,
element_type_id,
ref vtable,
} = self;
unsafe {
SliceCopyMut::from_raw_parts(data, element_size, element_type_id, vtable.as_ref())
}
}
}
impl<V> VecCopy<V> {
/*
* Methods specific to buffers storing numeric data
*/
#[cfg(feature = "numeric")]
/// Cast a numeric `VecCopy` into the given output `Vec` type.
pub fn cast_into_vec<T>(self) -> Vec<T>
where
T: CopyElem + NumCast + Zero,
{
// Helper function (generic on the input) to convert the given VecCopy into Vec.
unsafe fn convert_into_vec<I, O, V>(buf: VecCopy<V>) -> Vec<O>
where
I: CopyElem + Any + NumCast,
O: CopyElem + NumCast + Zero,
{
debug_assert_eq!(buf.element_type_id(), TypeId::of::<I>()); // Check invariant.
buf.reinterpret_into_vec()
.into_iter()
.map(|elem: I| cast(elem).unwrap_or_else(O::zero))
.collect()
}
call_numeric_buffer_fn!( convert_into_vec::<_, T, V>(self) or { Vec::new() } )
}
#[cfg(feature = "numeric")]
/// Display the contents of this buffer reinterpreted in the given type.
unsafe fn reinterpret_display<T: CopyElem + fmt::Display>(&self, f: &mut fmt::Formatter) {
debug_assert_eq!(self.element_type_id(), TypeId::of::<T>()); // Check invariant.
for item in self.reinterpret_iter::<T>() {
write!(f, "{} ", item).expect("Error occurred while writing an VecCopy.");
}
}
}
impl<'a, V: Clone + ?Sized + 'a> std::iter::FromIterator<CopyValueRef<'a, V>> for VecCopy<V> {
#[inline]
fn from_iter<T: IntoIterator<Item = CopyValueRef<'a, V>>>(iter: T) -> Self {
let mut iter = iter.into_iter();
let next = iter
.next()
.expect("VecCopy cannot be built from an empty untyped iterator.");
let mut data = Vec::with_capacity(next.size() * iter.size_hint().0);
data.extend_from_slice(next.bytes);
let mut buf = VecCopy {
data,
element_size: next.size(),
element_type_id: next.value_type_id(),
vtable: Ptr::new(next.vtable.take()),
};
buf.extend(iter);
buf
}
}
impl<'a, V: ?Sized + 'a> Extend<CopyValueRef<'a, V>> for VecCopy<V> {
#[inline]
fn extend<T: IntoIterator<Item = CopyValueRef<'a, V>>>(&mut self, iter: T) {
for value in iter {
assert_eq!(value.size(), self.element_size());
assert_eq!(value.value_type_id(), self.element_type_id());
self.data.extend_from_slice(value.bytes);
}
}
}
/*
* Advanced methods to probe buffer internals.
*/
impl<V: ?Sized + Clone> VecCopy<V> {
/// Clones this `VecCopy` using the given function.
#[cfg(feature = "traits")]
pub(crate) fn clone_with(
&self,
clone: impl FnOnce(&[MaybeUninit<u8>]) -> Vec<MaybeUninit<u8>>,
) -> Self {
VecCopy {
data: clone(&self.data),
element_size: self.element_size,
element_type_id: self.element_type_id,
vtable: Ptr::clone(&self.vtable),
}
}
}
impl<V: ?Sized> VecCopy<V> {
/// Reserves capacity for at least `additional` more bytes to be inserted in this buffer.
#[inline]
pub fn reserve_bytes(&mut self, additional: usize) {
self.data.reserve(additional);
}
/// Get `i`'th element of the buffer by value without checking type.
///
/// This can be used to reinterpret the internal data as a different type. Note that if the
/// size of the given type `T` doesn't match the size of the internal type, `i` will really
/// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
///
/// # Safety
///
/// It is assumed that that the buffer contains elements of type `T` and that `i` is strictly
/// less than the length of this vector, otherwise this function will cause undefined behavior.
#[inline]
pub unsafe fn get_unchecked<T: CopyElem>(&self, i: usize) -> T {
let ptr = self.data.as_ptr() as *const T;
*ptr.add(i)
}
/// Get a `const` reference to the `i`'th element of the buffer.
///
/// This can be used to reinterpret the internal data as a different type. Note that if the
/// size of the given type `T` doesn't match the size of the internal type, `i` will really
/// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
///
/// # Safety
///
/// It is assumed that that the buffer contains elements of type `T` and that `i` is strictly
/// less than the length of this vector, otherwise this function will cause undefined behavior.
#[inline]
pub unsafe fn get_unchecked_ref<T: CopyElem>(&self, i: usize) -> &T {
let ptr = self.data.as_ptr() as *const T;
&*ptr.add(i)
}
/// Get a mutable reference to the `i`'th element of the buffer.
///
/// This can be used to reinterpret the internal data as a different type. Note that if the
/// size of the given type `T` doesn't match the size of the internal type, `i` will really
/// index the `i`th `T` sized chunk in the current buffer. See the implementation for details.
///
/// # Safety
///
/// It is assumed that that the buffer contains elements of type `T` and that `i` is strictly
/// less than the length of this vector, otherwise this function will cause undefined behavior.
#[inline]
pub unsafe fn get_unchecked_mut<T: CopyElem>(&mut self, i: usize) -> &mut T {
let ptr = self.data.as_mut_ptr() as *mut T;
&mut *ptr.add(i)
}
/// Get a `const` reference to the byte slice of the `i`'th element of the buffer.
#[inline]
pub fn get_bytes(&self, i: usize) -> &[MaybeUninit<u8>] {
debug_assert!(i < self.len());
let element_size = self.element_size();
&self.data[i * element_size..(i + 1) * element_size]
}
/// Get a mutable reference to the byte slice of the `i`'th element of the buffer.
///
/// # Safety
///
/// This function is marked as unsafe since the returned bytes may be modified
/// arbitrarily, which may potentially produce malformed values.
#[inline]
pub unsafe fn get_bytes_mut(&mut self, i: usize) -> &mut [MaybeUninit<u8>] {
debug_assert!(i < self.len());
self.index_byte_slice_mut(i)
}
/// Move buffer data to a vector with a given type, reinterpreting the data type as
/// required.
///
/// # Safety
///
/// The underlying data must be correctly represented by a `Vec<T>`.
#[inline]
pub unsafe fn reinterpret_into_vec<T>(self) -> Vec<T> {
reinterpret::reinterpret_vec(self.data)
}
/// Borrow buffer data and reinterpret it as a slice of a given type.
///
/// # Safety
///
/// The underlying data must be correctly represented by a `&[T]` when borrowed as
/// `&[MaybeUninit<u8>]`.
#[inline]
pub unsafe fn reinterpret_as_slice<T>(&self) -> &[T] {
reinterpret::reinterpret_slice(self.data.as_slice())
}
/// Mutably borrow buffer data and reinterpret it as a mutable slice of a given type.
///
/// # Safety
///
/// The underlying data must be correctly represented by a `&mut [T]` when borrowed as`&mut
/// [MaybeUninit<u8>]`.
#[inline]
pub unsafe fn reinterpret_as_mut_slice<T>(&mut self) -> &mut [T] {
reinterpret::reinterpret_mut_slice(self.data.as_mut_slice())
}
/// Borrow buffer data and iterate over reinterpreted underlying data.
///
/// # Safety
///
/// Each underlying element must be correctly represented by a `&T` when borrowed as
/// `&[MaybeUninit<u8>]`.
#[inline]
pub unsafe fn reinterpret_iter<T>(&self) -> slice::Iter<T> {
self.reinterpret_as_slice().iter()
}
/// Mutably borrow buffer data and mutably iterate over reinterpreted underlying data.
///
/// # Safety
///
/// Each underlying element must be correctly represented by a `&mut T` when borrowed as `&mut
/// [MaybeUninit<u8>]`.
#[inline]
pub unsafe fn reinterpret_iter_mut<T>(&mut self) -> slice::IterMut<T> {
self.reinterpret_as_mut_slice().iter_mut()
}
/// Peek at the internal representation of the data.
#[inline]
pub fn as_bytes(&self) -> &[MaybeUninit<u8>] {
self.data.as_slice()
}
/// Get a mutable reference to the internal data representation.
///
/// # Safety
///
/// This function is marked as unsafe since the returned bytes may be modified
/// arbitrarily, which may potentially produce malformed values.
#[inline]
pub unsafe fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
self.data.as_mut_slice()
}
/// Iterate over chunks type sized chunks of bytes without interpreting them.
///
/// This avoids needing to know what type data you're dealing with. This type of iterator is
/// useful for transferring data from one place to another for a generic buffer.
#[inline]
pub fn byte_chunks<'a>(&'a self) -> impl Iterator<Item = &'a [MaybeUninit<u8>]> + 'a {
let chunk_size = self.element_size();
self.data.chunks_exact(chunk_size)
}
/// Mutably iterate over chunks type sized chunks of bytes without interpreting them. This
/// avoids needing to know what type data you're dealing with. This type of iterator is useful
/// for transferring data from one place to another for a generic buffer, or modifying the
/// underlying untyped bytes (e.g. bit twiddling).
///
/// # Safety
///
/// This function is marked as unsafe since the returned bytes may be modified
/// arbitrarily, which may potentially produce malformed values.
#[inline]
pub unsafe fn byte_chunks_mut<'a>(
&'a mut self,
) -> impl Iterator<Item = &'a mut [MaybeUninit<u8>]> + 'a {
let chunk_size = self.element_size();
self.data.chunks_exact_mut(chunk_size)
}
/// Add bytes to this buffer.
///
/// If the size of the given slice coincides with the number of bytes occupied by the
/// underlying element type, then these bytes are added to the underlying data buffer and a
/// mutable reference to the buffer is returned.
/// Otherwise, `None` is returned, and the buffer remains unmodified.
///
/// # Safety
///
/// It is assumed that that the given `bytes` slice is a valid representation of the element
/// types stored in this buffer. Otherwise this function will cause undefined behavior.
#[inline]
pub unsafe fn push_bytes(&mut self, bytes: &[MaybeUninit<u8>]) -> Option<&mut Self> {
if bytes.len() == self.element_size() {
self.data.extend_from_slice(bytes);
Some(self)
} else {
None
}
}