-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Copy pathbytes.sw
1076 lines (988 loc) · 28.4 KB
/
bytes.sw
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
//! The `Bytes` type is used when a collection of tightly-packed arbitrary bytes is needed.
library;
use ::{alloc::{alloc_bytes, realloc_bytes}, vec::Vec};
use ::assert::{assert, assert_eq};
use ::intrinsics::size_of_val;
use ::option::Option::{self, *};
use ::convert::{From, Into, *};
use ::clone::Clone;
struct RawBytes {
ptr: raw_ptr,
cap: u64,
}
impl RawBytes {
/// Create a new `RawBytes` with zero capacity.
pub fn new() -> Self {
Self {
ptr: alloc_bytes(0),
cap: 0,
}
}
/// Creates a `RawBytes` (on the heap) with exactly the capacity (in bytes) specified.
/// This is equivalent to calling `RawBytes::new` when `capacity` is zero.
pub fn with_capacity(capacity: u64) -> Self {
Self {
ptr: alloc_bytes(capacity),
cap: capacity,
}
}
/// Gets the pointer of the allocation.
pub fn ptr(self) -> raw_ptr {
self.ptr
}
/// Gets the capacity of the allocation.
pub fn capacity(self) -> u64 {
self.cap
}
/// Grow the capacity of `Bytes` by doubling its current capacity. The
/// `realloc_bytes` function allocates memory on the heap and copies
/// the data from the old allocation to the new allocation.
pub fn grow(ref mut self) {
let new_cap = if self.cap == 0 { 1 } else { 2 * self.cap };
self.ptr = realloc_bytes(self.ptr, self.cap, new_cap);
self.cap = new_cap;
}
}
impl From<raw_slice> for RawBytes {
/// Creates a `RawBytes` from a `raw_slice`.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::RawBytes;
///
/// let mut vec = Vec::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8
///
/// vec.push(a);
/// vec.push(b);
/// vec.push(c);
///
/// let vec_as_raw_slice = vec.as_raw_slice();
/// let raw_bytes = RawBytes::from(vec_as_raw_slice);
///
/// assert(raw_bytes.capacity == 3);
/// ```
fn from(slice: raw_slice) -> Self {
let cap = slice.number_of_bytes();
let ptr = alloc_bytes(cap);
if cap > 0 {
slice.ptr().copy_to::<u8>(ptr, cap);
}
Self { ptr, cap }
}
}
/// A type used to represent raw bytes. It has ownership over its buffer.
pub struct Bytes {
/// A barebones struct for the bytes.
buf: RawBytes,
/// The number of bytes being stored.
len: u64,
}
impl Bytes {
/// Constructs a new, empty `Bytes`.
///
/// # Additional Information
///
/// The struct will not allocate until elements are pushed onto it.
///
/// # Returns
///
/// * [Bytes] - A new, empty `Bytes`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let bytes = Bytes::new();
/// assert(bytes.len() == 0);
/// assert(bytes.capacity() == 0);
/// }
/// ```
pub fn new() -> Self {
Self {
buf: RawBytes::new(),
len: 0,
}
}
/// Constructs a new, empty `Bytes` with the specified capacity.
///
/// # Additional Information
///
/// The `Bytes` will be able to hold exactly `capacity` bytes without
/// reallocating. If `capacity` is zero, the `Bytes` will not allocate.
///
/// It is important to note that although the returned `Bytes` has the
/// capacity specified, the type will have a zero length.
///
/// # Arguments
///
/// * `capacity`: [u64] - The capacity with which to initialize the `Bytes`.
///
/// # Returns
///
/// * [Bytes] - A new, empty `Bytes` with the specified capacity.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::with_capacity(2);
/// // does not allocate
/// bytes.push(5);
/// // does not re-allocate
/// bytes.push(10);
/// }
/// ```
pub fn with_capacity(capacity: u64) -> Self {
Self {
buf: RawBytes::with_capacity(capacity),
len: 0,
}
}
/// Appends an element to the back of a `Bytes` collection.
///
/// # Arguments
///
/// * `byte`: [u8] - The element to be pushed onto the `Bytes`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// let a = 5u8;
/// let b = 7u8;
/// bytes.push(a);
/// bytes.push(b);
/// assert(bytes.len() == 2);
/// }
/// ```
pub fn push(ref mut self, byte: u8) {
// If there is insufficient capacity, grow the buffer.
if self.len == self.buf.capacity() {
self.buf.grow();
};
// Get a pointer to the end of the buffer, where the new element will
// be inserted.
let end = self.buf.ptr().add_uint_offset(self.len);
// Write `byte` at pointer `end`
end.write_byte(byte);
// Increment length.
self.len += 1;
}
/// Removes the last element from a `Bytes` and returns it, or `None` if it
/// is empty.
///
/// # Returns
///
/// * [Option<u8>] - The last element of the `Bytes`, or `None` if it is empty.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
///
/// let res = bytes.pop();
/// assert(res.is_none());
///
/// bytes.push(5);
/// let res = bytes.pop();
/// assert(res.unwrap() == 5);
/// assert(bytes.is_empty());
/// }
/// ```
pub fn pop(ref mut self) -> Option<u8> {
if self.len == 0 {
return None;
};
// Decrement length.
self.len -= 1;
let target = self.buf.ptr().add_uint_offset(self.len);
Some(target.read_byte())
}
/// Returns `Some(byte)` at `index`, or `None` if `index` is out of
/// bounds.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the element to be returned.
///
/// # Returns
///
/// * [Option<u8>] - The element at the specified index, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Byte;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// bytes.push(5u8);
/// bytes.push(10u8);
/// bytes.push(15u8);
/// let item = bytes.get(1).unwrap();
/// assert(item == 10u8);
/// let opt = bytes.get(10);
/// assert(opt.is_none()); // index out of bounds
/// }
/// ```
pub fn get(self, index: u64) -> Option<u8> {
// First check that index is within bounds.
if self.len <= index {
return None;
};
let item_ptr = self.buf.ptr().add_uint_offset(index);
Some(item_ptr.read_byte())
}
/// Updates an element at position `index` with a new element `value`.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the element to be set.
/// * `value`: [u8] - The value of the element to be set.
///
/// # Reverts
///
/// * When `index` is greater than or equal to the length of Bytes.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8;
/// bytes.push(a);
/// bytes.push(b);
/// bytes.push(c);
///
/// let d = 11u8;
///
/// bytes.set(1, d);
///
/// assert(bytes.len() == 3);
/// assert(bytes.get(0).unwrap() == a);
/// assert(bytes.get(1).unwrap() == d);
/// assert(bytes.get(2).unwrap() == c);
/// }
/// ```
pub fn set(ref mut self, index: u64, value: u8) {
assert(index < self.len);
let index_ptr = self.buf.ptr().add_uint_offset(index);
index_ptr.write_byte(value);
}
/// Inserts an element at position `index` within the Bytes, shifting all
/// elements after it to the right.
///
/// # Arguments
///
/// * `index`: [u64] - The index at which to insert the element.
/// * `element`: [u8] - The element to be inserted.
///
/// # Reverts
///
/// * When `index > len`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Byte;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// let a = 11u8;
/// let b = 11u8;
/// let c = 11u8;
/// let d = 11u8;
/// bytes.push(a);
/// bytes.push(b);
/// bytes.push(c);
/// bytes.insert(1, d);
///
/// assert(bytes.get(0).unwrap() == a);
/// assert(bytes.get(1).unwrap() == d);
/// assert(bytes.get(2).unwrap() == b);
/// assert(bytes.get(3).unwrap() == c);
/// }
/// ```
pub fn insert(ref mut self, index: u64, element: u8) {
assert(index <= self.len);
// If there is insufficient capacity, grow the buffer.
if self.len == self.buf.capacity() {
self.buf.grow();
}
let start = self.buf.ptr();
// The spot to put the new value.
let index_ptr = start.add_uint_offset(index);
// Shift everything over to make space.
let mut i = self.len;
while i > index {
let idx_ptr = start.add_uint_offset(i);
let previous = idx_ptr.sub_uint_offset(1);
previous.copy_bytes_to(idx_ptr, 1);
i -= 1;
}
// Write `element` at pointer `index`.
index_ptr.write_byte(element);
// Increment length.
self.len += 1;
}
/// Removes and returns the element at position `index` within the Bytes,
/// shifting all elements after it to the left.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the element to be removed.
///
/// # Returns
///
/// * [u8] - The element at the specified index.
///
/// # Reverts
///
/// * When `index >= self.len`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Byte;
///
/// fn foo() {
/// let mut bytes = Byte::new();
/// bytes.push(5);
/// bytes.push(10);
/// bytes.push(15);
/// let item = bytes.remove(1);
/// assert(item == 10);
/// assert(bytes.get(0).unwrap() == 5);
/// assert(bytes.get(1).unwrap() == 15);
/// assert(bytes.get(2).is_none());
/// }
/// ```
pub fn remove(ref mut self, index: u64) -> u8 {
// Panic if index >= length.
assert(index < self.len);
let start = self.buf.ptr();
let item_ptr = start.add_uint_offset(index);
// Read the value at `index`
let ret = item_ptr.read_byte();
// Shift everything down to fill in that spot.
let mut i = index;
while i < self.len - 1 {
let idx_ptr = start.add_uint_offset(i);
let next = idx_ptr.add_uint_offset(1);
next.copy_bytes_to(idx_ptr, 1);
i += 1;
}
// Decrease length.
self.len -= 1;
ret
}
/// Swaps two elements.
///
/// # Arguments
///
/// * `element1_index`: [u64] - The index of the first element.
/// * `element2_index`: [u64] - The index of the second element.
///
/// # Reverts
///
/// * When `element1_index` or `element2_index` is greater than or equal to the length of `Bytes`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8;
/// bytes.push(a);
/// bytes.push(b);
/// bytes.push(c);
///
/// bytes.swap(0, 1);
///
/// assert(bytes.get(0).unwrap() == b);
/// assert(bytes.get(1).unwrap() == a);
/// assert(bytes.get(2).unwrap() == c);
/// }
/// ```
pub fn swap(ref mut self, element1_index: u64, element2_index: u64) {
assert(element1_index < self.len);
assert(element2_index < self.len);
if element1_index == element2_index {
return;
}
let start = self.buf.ptr();
let element1_ptr = start.add_uint_offset(element1_index);
let element2_ptr = start.add_uint_offset(element2_index);
let element1_val = element1_ptr.read_byte();
element2_ptr.copy_bytes_to(element1_ptr, 1);
element2_ptr.write_byte(element1_val);
}
/// Gets the capacity of the allocation.
///
/// # Returns
///
/// * [u64] - The capacity of the allocation.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let bytes = Bytes::with_capacity(5);
/// let cap = bytes.capacity();
/// assert(cap == 5);
/// }
/// ```
pub fn capacity(self) -> u64 {
self.buf.capacity()
}
/// Gets the length of the `Bytes`.
///
/// # Returns
///
/// * [u64] - The length of the `Bytes`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// assert(bytes.len() == 0);
/// bytes.push(5);
/// assert(bytes.len() == 1);
/// }
/// ```
pub fn len(self) -> u64 {
self.len
}
/// Clears the `Bytes`, removing all values.
///
/// # Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// bytes.push(5);
/// bytes.clear()
/// assert(bytes.is_empty());
/// }
/// ```
pub fn clear(ref mut self) {
self.buf = RawBytes::new();
self.len = 0;
}
/// Returns `true` if the type contains no elements.
///
/// # Returns
///
/// * [bool] - `true` if the type contains no elements, `false` otherwise.
///
/// # Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// assert(bytes.is_empty());
/// bytes.push(5);
/// assert(!bytes.is_empty());
/// bytes.clear()
/// assert(bytes.is_empty());
/// }
/// ```
pub fn is_empty(self) -> bool {
self.len == 0
}
/// Gets the pointer of the allocation.
///
/// # Returns
///
/// [raw_ptr] - The location in memory that the allocated bytes live.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let bytes = Bytes::new();
/// assert(!bytes.ptr().is_null());
/// }
/// ```
pub fn ptr(self) -> raw_ptr {
self.buf.ptr()
}
/// Divides one Bytes into two at an index.
///
/// # Additional Information
///
/// The first will contain all indices from `[0, mid)` (excluding the index
/// `mid` itself) and the second will contain all indices from `[mid, len)`
/// (excluding the index `len` itself).
///
/// # Arguments
///
/// * `mid`: [u64] - Index at which the Bytes is to be split.
///
/// # Reverts
///
/// * When `mid > self.len`.
///
/// # Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// bytes.push(5u8);
/// bytes.push(7u8);
/// bytes.push(9u8);
/// assert(bytes.len() == 3);
/// let mid = 1;
/// let (left, right) = bytes.split_at(mid);
/// assert(left.capacity() == mid);
/// assert(right.capacity() == bytes.len() - mid);
/// assert(left.len() == 1);
/// assert(right.len() == 2);
/// }
/// ```
pub fn split_at(self, mid: u64) -> (Self, Self) {
assert(self.len >= mid);
let left_len = mid;
let right_len = self.len - mid;
let mut left_bytes = Self {
buf: RawBytes::with_capacity(left_len),
len: left_len,
};
let mut right_bytes = Self {
buf: RawBytes::with_capacity(right_len),
len: right_len,
};
if mid > 0 {
self.buf.ptr().copy_bytes_to(left_bytes.ptr(), left_len);
};
if mid != self.len {
self.buf
.ptr()
.add_uint_offset(mid)
.copy_bytes_to(right_bytes.ptr(), right_len);
};
left_bytes.len = left_len;
right_bytes.len = right_len;
(left_bytes, right_bytes)
}
/// Copies all elements of `other` into `self`
///
/// # Additional Information
///
/// NOTE: Appending `self` to itself will duplicate the `Bytes`. i.e. [0, 1, 2] => [0, 1, 2, 0, 1, 2]
/// This function differs from the rust `append` function in that it does not clear the `other` `Bytes`
///
/// # Arguments
///
/// * `other`: [Bytes] - The Bytes to append to self.
///
/// # Examples
///
/// ```sway
///
/// use std:bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// bytes.push(5u8);
/// bytes.push(7u8);
/// bytes.push(9u8);
/// assert(bytes.len() == 3);
///
/// let mut bytes2 = Bytes::new();
/// bytes2.push(5u8);
/// bytes2.push(7u8);
/// bytes2.push(9u8);
/// assert(bytes2.len() == 3);
///
/// let first_length = bytes.len();
/// let second_length = bytes2.len();
/// let first_cap = bytes.capacity();
/// let second_cap = bytes2.capacity();
/// bytes.append(bytes2);
/// assert(bytes.len() == first_length + second_length);
/// assert(bytes.capacity() == first_cap + second_cap);
/// }
/// ```
pub fn append(ref mut self, ref mut other: Self) {
let other_len = other.len();
if other_len == 0 {
return
};
// optimization for when starting with empty bytes and appending to it
if self.len == 0 {
self = other;
return;
};
let both_len = self.len + other_len;
let other_start = self.len;
// reallocate with combined capacity, write `other`, set buffer capacity
if self.buf.capacity() < both_len {
let new_slice = raw_slice::from_parts::<u8>(
realloc_bytes(self.buf.ptr(), self.buf.capacity(), both_len),
both_len,
);
self.buf = RawBytes::from(new_slice);
}
let new_ptr = self.buf.ptr().add_uint_offset(other_start);
other.ptr().copy_bytes_to(new_ptr, other_len);
// set capacity and length
self.len = both_len;
}
/// Removes and returns a range of elements from the `Bytes` (i.e. indices `[start, end)`),
/// then replaces that range with the contents of `replace_with`.
///
/// # Arguments
///
/// * `start`: [u64] - The starting index for the splice (inclusive).
/// * `end`: [u64] - The ending index for the splice (exclusive).
/// * `replace_with`: [Bytes] - The elements to insert in place of the removed range.
///
/// # Returns
///
/// * [Bytes] - A new `Bytes` containing all of the elements from `start` up to (but not including) `end`.
///
/// # Reverts
///
/// * When `start > end`.
/// * When `end > self.len`.
///
/// # Examples
///
/// ```sway
/// use std::bytes::Bytes;
///
/// fn foo() {
/// let mut bytes = Bytes::new();
/// bytes.push(5u8); // index 0
/// bytes.push(7u8); // index 1
/// bytes.push(9u8); // index 2
///
/// // Replace the middle item (index 1) with two new items
/// let mut replacement = Bytes::new();
/// replacement.push(42u8);
/// replacement.push(100u8);
///
/// // Splice out range [1..2) => removes the single element 7u8,
/// // then inserts [42, 100] there
/// let spliced = bytes.splice(1, 2, replacement);
///
/// // `spliced` has the element [7u8]
/// assert(spliced.len() == 1);
/// assert(spliced.get(0).unwrap() == 7u8);
///
/// // `bytes` is now [5u8, 42u8, 100u8, 9u8]
/// assert(bytes.len() == 4);
/// assert(bytes.get(0).unwrap() == 5u8);
/// assert(bytes.get(1).unwrap() == 42u8);
/// assert(bytes.get(2).unwrap() == 100u8);
/// assert(bytes.get(3).unwrap() == 9u8);
/// }
/// ```
pub fn splice(ref mut self, start: u64, end: u64, replace_with: Bytes) -> Bytes {
assert(start <= end);
assert(end <= self.len);
let splice_len = end - start;
let replace_len = replace_with.len();
// Build the Bytes to return
let mut spliced = Bytes::with_capacity(splice_len);
if splice_len > 0 {
let old_ptr = self.buf.ptr().add_uint_offset(start);
old_ptr.copy_bytes_to(spliced.buf.ptr(), splice_len);
spliced.len = splice_len;
}
// New self
let new_len = self.len - splice_len + replace_len;
let mut new_buf = Bytes::with_capacity(new_len);
// Move head
if start > 0 {
let old_ptr = self.buf.ptr();
old_ptr.copy_bytes_to(new_buf.buf.ptr(), start);
}
// Move middle
if replace_len > 0 {
replace_with
.buf
.ptr()
.copy_bytes_to(new_buf.buf.ptr().add_uint_offset(start), replace_len);
}
// Move tail
let tail_len = self.len - end;
if tail_len > 0 {
let old_tail = self.buf.ptr().add_uint_offset(end);
let new_tail = new_buf.buf.ptr().add_uint_offset(start + replace_len);
old_tail.copy_bytes_to(new_tail, tail_len);
}
self.buf = new_buf.buf;
self.len = new_len;
spliced
}
}
impl core::ops::Eq for Bytes {
fn eq(self, other: Self) -> bool {
if self.len != other.len {
return false;
}
asm(result, r2: self.buf.ptr, r3: other.buf.ptr, r4: self.len) {
meq result r2 r3 r4;
result: bool
}
}
}
impl AsRawSlice for Bytes {
/// Returns a raw slice of all of the elements in the type.
fn as_raw_slice(self) -> raw_slice {
asm(ptr: (self.buf.ptr, self.len)) {
ptr: raw_slice
}
}
}
/// Methods for converting between the `Bytes` and the `b256` types.
impl From<b256> for Bytes {
fn from(b: b256) -> Self {
// Artificially create bytes with capacity and len
let mut bytes = Self::with_capacity(32);
bytes.len = 32;
// Copy bytes from contract_id into the buffer of the target bytes
__addr_of(b).copy_bytes_to(bytes.buf.ptr, 32);
bytes
}
}
impl From<Bytes> for b256 {
// NOTE: this cas be lossy! Added here as the From trait currently requires it,
// but the conversion from `Bytes` ->`b256` should be implemented as
// `impl TryFrom<Bytes> for b256` when the `TryFrom` trait lands:
// https://github.com/FuelLabs/sway/pull/3881
fn from(bytes: Bytes) -> b256 {
let mut value = 0x0000000000000000000000000000000000000000000000000000000000000000;
let ptr = __addr_of(value);
bytes.buf.ptr().copy_to::<b256>(ptr, 1);
value
}
}
impl From<raw_slice> for Bytes {
/// Creates a `Bytes` from a `raw_slice`.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let mut vec = Vec::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8
///
/// vec.push(a);
/// vec.push(b);
/// vec.push(c);
///
/// let vec_as_raw_slice = vec.as_raw_slice();
/// let bytes = Bytes::from(vec_as_raw_slice);
///
/// assert(bytes.len == 3);
/// assert(bytes.get(0).unwrap() == a);
/// assert(bytes.get(1).unwrap() == b);
/// assert(bytes.get(2).unwrap() == c);
/// ```
fn from(slice: raw_slice) -> Self {
Self {
buf: RawBytes::from(slice),
len: slice.number_of_bytes(),
}
}
}
impl From<Bytes> for raw_slice {
/// Creates a `raw_slice` from a `Bytes`.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let mut bytes = Bytes::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8
/// bytes.push(a);
/// bytes.push(b);
/// bytes.push(c);
///
/// assert(bytes.len() == 3);
///
/// let slice: raw_slice = bytes.into();
///
/// assert(slice.number_of_bytes() == 3);
/// ```
fn from(bytes: Bytes) -> raw_slice {
bytes.as_raw_slice()
}
}
impl From<Vec<u8>> for Bytes {
/// Creates a `Bytes` from a `Vec<u8>`.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let mut vec = Vec::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8
///
/// vec.push(a);
/// vec.push(b);
/// vec.push(c);
///
/// let bytes = Bytes::from(vec);
///
/// assert(bytes.len == 3);
/// assert(bytes.get(0).unwrap() == a);
/// assert(bytes.get(1).unwrap() == b);
/// assert(bytes.get(2).unwrap() == c);
/// ```
fn from(vec: Vec<u8>) -> Self {
let mut bytes = Self::with_capacity(vec.len());
let mut i = 0;
while i < vec.len() {
bytes.push(vec.get(i).unwrap());
i += 1;
};
bytes
}
}
impl From<Bytes> for Vec<u8> {
/// Creates a `Vec<u8>` from a `Bytes`.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let mut bytes = Bytes::new();
/// let a = 5u8;
/// let b = 7u8;
/// let c = 9u8
/// bytes.push(a);
/// bytes.push(b);
/// bytes.push(c);
///
/// assert(bytes.len() == 3);
///
/// let vec: Vec<u8> = bytes.into();
///
/// assert(vec.len() == 3);
/// assert(vec.get(0).unwrap() == a);
/// assert(vec.get(1).unwrap() == b);
/// assert(vec.get(2).unwrap() == c);
/// ```
fn from(bytes: Bytes) -> Vec<u8> {
let mut vec = Vec::with_capacity(bytes.len);
let mut i = 0;
while i < bytes.len {
vec.push(bytes.get(i).unwrap());
i += 1;
};
vec
}
}