|
42 | 42 | //! assert!(first_byte == 0x41);
|
43 | 43 | //! ```
|
44 | 44 |
|
45 |
| -use crate::array::{ArrayTrait, SpanTrait}; |
| 45 | +use crate::array::{ArrayTrait, Span, SpanTrait}; |
46 | 46 | #[allow(unused_imports)]
|
47 | 47 | use crate::bytes_31::{
|
48 | 48 | BYTES_IN_BYTES31, Bytes31Trait, POW_2_128, POW_2_8, U128IntoBytes31, U8IntoBytes31,
|
@@ -585,3 +585,49 @@ impl ByteArrayFromIterator of crate::iter::FromIterator<ByteArray, u8> {
|
585 | 585 | ba
|
586 | 586 | }
|
587 | 587 | }
|
| 588 | + |
| 589 | +/// A view into a contiguous collection of a string type. |
| 590 | +/// Currently implemented only for `ByteArray`, but will soon be implemented for other string types. |
| 591 | +/// `Span` implements the `Copy` and the `Drop` traits. |
| 592 | +#[derive(Copy, Drop)] |
| 593 | +pub struct ByteSpan { |
| 594 | + pub(crate) raw_data: Span<bytes31>, |
| 595 | + /// The offset of the first character in the first entry of [Self::raw_data], for use in span |
| 596 | + /// slices. |
| 597 | + /// Value should be in the range [0, 30]. |
| 598 | + pub(crate) first_char_start_offset: usize, |
| 599 | + /// The last word in the span will always be located in this field, to account for bytearrays |
| 600 | + /// which don't include the pending bytes31 word in the array itself. |
| 601 | + pub(crate) last_word: felt252, |
| 602 | + /// The offset of the last character in the last entry of span, located in [Self::last_word]. |
| 603 | + /// Value should be in the range [0, 30]. |
| 604 | + pub(crate) last_char_end_offset: usize, |
| 605 | +} |
| 606 | + |
| 607 | +#[generate_trait] |
| 608 | +pub impl ByteArraySpanImpl of ByteSpanTrait { |
| 609 | + fn len(self: @ByteSpan) -> usize { |
| 610 | + let raw_data_bytes = self.raw_data.len() * BYTES_IN_BYTES31; |
| 611 | + raw_data_bytes - *self.first_char_start_offset + *self.last_char_end_offset |
| 612 | + } |
| 613 | + |
| 614 | + fn is_empty(self: @ByteSpan) -> bool { |
| 615 | + self.len() == 0 |
| 616 | + } |
| 617 | +} |
| 618 | + |
| 619 | +pub trait ToByteSpanTrait<C> { |
| 620 | + #[must_use] |
| 621 | + fn span(self: @C) -> ByteSpan; |
| 622 | +} |
| 623 | + |
| 624 | +impl ByteArrayToByteSpan of ToByteSpanTrait<ByteArray> { |
| 625 | + fn span(self: @ByteArray) -> ByteSpan { |
| 626 | + ByteSpan { |
| 627 | + raw_data: self.data.span(), |
| 628 | + first_char_start_offset: 0, |
| 629 | + last_word: *self.pending_word, |
| 630 | + last_char_end_offset: *self.pending_word_len, |
| 631 | + } |
| 632 | + } |
| 633 | +} |
0 commit comments