diff --git a/builtin/bytesview.mbt b/builtin/bytesview.mbt index 8eb76622a7..a8a96f2def 100644 --- a/builtin/bytesview.mbt +++ b/builtin/bytesview.mbt @@ -625,6 +625,31 @@ pub fn BytesView::lexical_compare(self : BytesView, other : BytesView) -> Int { self_len.compare(other_len) } +///| +/// Creates a new bytes view from a byte array. +/// +/// Parameters: +/// +/// * `array` : An array of bytes to be converted. +/// +/// Returns a bytes view containing the same bytes as the input array. +pub fn BytesView::from_array(arr : ArrayView[Byte]) -> BytesView { + Bytes::from_array(arr)[:] +} + +///| +/// Creates a new bytes view from an iterator of bytes. +/// +/// Parameters: +/// +/// * `iterator` : An iterator that yields bytes. +/// +/// Returns a bytes view containing all the bytes from the iterator. +#alias(from_iterator, deprecated) +pub fn BytesView::from_iter(iter : Iter[Byte]) -> BytesView { + Bytes::from_iter(iter)[:] +} + ///| /// Retrieves the underlying `Bytes` from a `View`. pub fn BytesView::data(self : BytesView) -> Bytes { @@ -648,6 +673,24 @@ pub fn BytesView::to_bytes(self : BytesView) -> Bytes { unsafe_to_bytes(bytes) } +///| +/// Return an unchecked string, containing the subsequence of `self` that starts at +/// `offset` and has length `length`. Both `offset` and `length` +/// are indexed by byte. +/// +/// Note this function does not validate the encoding of the byte sequence, +/// it simply copy the bytes into a new String. +pub fn BytesView::to_unchecked_string( + self : BytesView, + offset? : Int = 0, + length? : Int, +) -> String { + let len = self.length() + let length = if length is Some(l) { l } else { len - offset } + guard offset >= 0 && length >= 0 && offset + length <= len + self.data().to_unchecked_string(offset=self.start_offset() + offset, length~) +} + ///| pub impl ToJson for BytesView with to_json(self) -> Json { let sb = StringBuilder::new() diff --git a/builtin/pkg.generated.mbti b/builtin/pkg.generated.mbti index 00531b8dc6..c8a5cc24ae 100644 --- a/builtin/pkg.generated.mbti +++ b/builtin/pkg.generated.mbti @@ -944,6 +944,9 @@ pub fn BytesView::chop_prefix(Self, Self) -> Self? pub fn BytesView::chop_suffix(Self, Self) -> Self? pub fn BytesView::data(Self) -> Bytes pub fn BytesView::find(Self, Self) -> Int? +pub fn BytesView::from_array(ArrayView[Byte]) -> Self +#alias(from_iterator, deprecated) +pub fn BytesView::from_iter(Iter[Byte]) -> Self pub fn BytesView::get(Self, Int) -> Byte? pub fn BytesView::has_prefix(Self, Self) -> Bool pub fn BytesView::has_suffix(Self, Self) -> Bool @@ -959,6 +962,7 @@ pub fn BytesView::start_offset(Self) -> Int pub fn BytesView::to_array(Self) -> Array[Byte] pub fn BytesView::to_bytes(Self) -> Bytes pub fn BytesView::to_fixedarray(Self) -> FixedArray[Byte] +pub fn BytesView::to_unchecked_string(Self, offset? : Int, length? : Int) -> String #alias("_[_:_]") #alias(sub, deprecated) pub fn BytesView::view(Self, start? : Int, end? : Int) -> Self