Skip to content

Commit

Permalink
perf(buffer): skip unnecessary capacity check
Browse files Browse the repository at this point in the history
  • Loading branch information
jetjinser committed Jan 28, 2025
1 parent 04776c4 commit 45b0b9a
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions buffer/buffer.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -163,27 +163,40 @@ pub fn new(size_hint~ : Int = 0) -> T {
}

///| Create a buffer from a bytes.
pub fn T::from_bytes(bytes : Bytes) -> T {
let buf = T::new(size_hint=bytes.length())
buf.write_bytes(bytes)
pub fn from_bytes(bytes : Bytes) -> T {
let val_len = bytes.length()
let buf = new(size_hint=val_len)
// inline write_bytes, skip grow_if_necessary check
// SAFETY: known bytes size
buf.data.blit_from_bytes(0, bytes, 0, val_len)
buf.len = val_len
buf
}

///|
/// Create a buffer from an array.
pub fn T::from_array(arr : Array[Byte]) -> T {
let buf = T::new(size_hint=arr.length())
pub fn from_array(arr : Array[Byte]) -> T {
let buf = new(size_hint=arr.length())
for byte in arr {
buf.write_byte(byte)
// inline write_byte, skip grow_if_necessary check
// SAFETY: known array size
buf.data[buf.len] = byte
buf.len += 1
}
buf
}

///|
/// Create a buffer from an array.
pub fn T::from_iter(iter : Iter[Byte]) -> T {
let arr = iter.collect()
T::from_array(arr)
/// Create a buffer from an iterator.
pub fn from_iter(iter : Iter[Byte]) -> T {
let buf = new(size_hint=iter.count())
for byte in iter {
// inline write_byte, skip grow_if_necessary check
// SAFETY: known iter size
buf.data[buf.len] = byte
buf.len += 1
}
buf
}

///|
Expand Down

0 comments on commit 45b0b9a

Please sign in to comment.