@@ -69,12 +69,17 @@ pub fn from_array(arr : Array[Byte]) -> Bytes {
69
69
/// ),
70
70
/// )
71
71
/// ```
72
+ ///
73
+ /// Panics if the length is invalid
72
74
pub fn Bytes ::from_fixedarray (arr : FixedArray [Byte ], len ? : Int ) -> Bytes {
73
75
let len = match len {
74
76
None => arr .length ()
75
- Some (x ) => x
77
+ Some (x ) => {
78
+ guard 0 <= x && x <= arr .length ()
79
+ x
80
+ }
76
81
}
77
- let result = FixedArray ::make (len , Byte :: default ( ))
82
+ let result = unsafe_to_fixedarray ( UninitializedArray ::make (len ))
78
83
arr .blit_to (result , len ~)
79
84
result .unsafe_reinterpret_as_bytes ()
80
85
}
@@ -108,15 +113,18 @@ pub fn from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytes {
108
113
/// let arr2 = bytes.to_fixedarray(len=3)
109
114
/// inspect(arr2, content="[b'\\x68', b'\\x65', b'\\x6C']")
110
115
/// ```
116
+ ///
117
+ /// Panics if the length is invalid
111
118
pub fn to_fixedarray (self : Bytes , len ? : Int ) -> FixedArray [Byte ] {
112
119
let len = match len {
113
120
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
+ }
119
125
}
126
+ let arr = unsafe_to_fixedarray (UninitializedArray ::make (len ))
127
+ arr .blit_from_bytes (0 , self , 0 , len )
120
128
arr
121
129
}
122
130
@@ -176,7 +184,7 @@ pub fn from_iter(iter : Iter[Byte]) -> Bytes {
176
184
/// TODO: marked as intrinsic, inline if it is constant
177
185
pub fn Bytes ::of (arr : FixedArray [Byte ]) -> Bytes {
178
186
let len = arr .length ()
179
- let result = FixedArray ::make (len , Byte :: default ( ))
187
+ let result = unsafe_to_fixedarray ( UninitializedArray ::make (len ))
180
188
arr .blit_to (result , len ~)
181
189
result .unsafe_reinterpret_as_bytes ()
182
190
}
@@ -313,6 +321,9 @@ pub fn default() -> Bytes {
313
321
/// Reinterpret the byte sequence as Bytes.
314
322
fn unsafe_to_bytes (array : FixedArray [Byte ]) -> Bytes = "%identity"
315
323
324
+ ///|
325
+ fn unsafe_to_fixedarray (array : UninitializedArray [Byte ]) -> FixedArray [Byte ] = "%identity"
326
+
316
327
///|
317
328
/// Concatenates two bytes sequences.
318
329
///
0 commit comments