Skip to content

Commit 2929a9c

Browse files
refactor: use uninitialized array to avoid initialization
1 parent bf3d0fc commit 2929a9c

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

bytes/bytes.mbt

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,17 @@ pub fn from_array(arr : Array[Byte]) -> Bytes {
6969
/// ),
7070
/// )
7171
/// ```
72+
///
73+
/// Panics if the length is invalid
7274
pub fn Bytes::from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytes {
7375
let len = match len {
7476
None => arr.length()
75-
Some(x) => x
77+
Some(x) => {
78+
guard 0 <= x && x <= arr.length()
79+
x
80+
}
7681
}
77-
let result = FixedArray::make(len, Byte::default())
82+
let result = unsafe_to_fixedarray(UninitializedArray::make(len))
7883
arr.blit_to(result, len~)
7984
result.unsafe_reinterpret_as_bytes()
8085
}
@@ -108,15 +113,18 @@ pub fn from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytes {
108113
/// let arr2 = bytes.to_fixedarray(len=3)
109114
/// inspect(arr2, content="[b'\\x68', b'\\x65', b'\\x6C']")
110115
/// ```
116+
///
117+
/// Panics if the length is invalid
111118
pub fn to_fixedarray(self : Bytes, len? : Int) -> FixedArray[Byte] {
112119
let len = match len {
113120
None => self.length()
114-
Some(x) => x
115-
}
116-
let arr = FixedArray::make(len, Byte::default())
117-
for i in 0..<len {
118-
arr[i] = self[i]
121+
Some(x) => {
122+
guard 0 <= x && x <= self.length()
123+
x
124+
}
119125
}
126+
let arr = unsafe_to_fixedarray(UninitializedArray::make(len))
127+
arr.blit_from_bytes(0, self, 0, len)
120128
arr
121129
}
122130
@@ -176,7 +184,7 @@ pub fn from_iter(iter : Iter[Byte]) -> Bytes {
176184
/// TODO: marked as intrinsic, inline if it is constant
177185
pub fn Bytes::of(arr : FixedArray[Byte]) -> Bytes {
178186
let len = arr.length()
179-
let result = FixedArray::make(len, Byte::default())
187+
let result = unsafe_to_fixedarray(UninitializedArray::make(len))
180188
arr.blit_to(result, len~)
181189
result.unsafe_reinterpret_as_bytes()
182190
}
@@ -313,6 +321,9 @@ pub fn default() -> Bytes {
313321
/// Reinterpret the byte sequence as Bytes.
314322
fn unsafe_to_bytes(array : FixedArray[Byte]) -> Bytes = "%identity"
315323
324+
///|
325+
fn unsafe_to_fixedarray(array : UninitializedArray[Byte]) -> FixedArray[Byte] = "%identity"
326+
316327
///|
317328
/// Concatenates two bytes sequences.
318329
///

0 commit comments

Comments
 (0)