@@ -68,13 +68,18 @@ pub fn Bytes::from_array(arr : Array[Byte]) -> Bytes {
6868/// ),
6969/// )
7070/// ```
71+ ///
72+ /// Panics if the length is invalid
7173#as_free_fn
7274pub 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}
@@ -102,15 +107,18 @@ pub fn Bytes::from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytes {
102107/// let arr2 = bytes.to_fixedarray(len=3)
103108/// inspect(arr2, content="[b'\\x68', b'\\x65', b'\\x6C']")
104109/// ```
110+ ///
111+ /// Panics if the length is invalid
105112pub fn to_fixedarray (self : Bytes , len ? : Int ) -> FixedArray [Byte ] {
106113 let len = match len {
107114 None => self .length ()
108- Some (x ) => x
109- }
110- let arr = FixedArray ::make (len , Byte ::default ())
111- for i in 0 ..< len {
112- arr [i ] = self [i ]
115+ Some (x ) => {
116+ guard 0 <= x && x <= self .length ()
117+ x
118+ }
113119 }
120+ let arr = unsafe_to_fixedarray (UninitializedArray ::make (len ))
121+ arr .blit_from_bytes (0 , self , 0 , len )
114122 arr
115123}
116124
@@ -170,7 +178,7 @@ pub fn Bytes::from_iter(iter : Iter[Byte]) -> Bytes {
170178#as_free_fn
171179pub fn Bytes ::of (arr : FixedArray [Byte ]) -> Bytes {
172180 let len = arr .length ()
173- let result = FixedArray ::make (len , Byte :: default ( ))
181+ let result = unsafe_to_fixedarray ( UninitializedArray ::make (len ))
174182 arr .blit_to (result , len ~)
175183 result .unsafe_reinterpret_as_bytes ()
176184}
@@ -301,6 +309,9 @@ pub fn get(self : Bytes, index : Int) -> Byte? {
301309/// Reinterpret the byte sequence as Bytes.
302310fn unsafe_to_bytes (array : FixedArray [Byte ]) -> Bytes = "%identity"
303311
312+ ///|
313+ fn unsafe_to_fixedarray (array : UninitializedArray [Byte ]) -> FixedArray [Byte ] = "%identity"
314+
304315///|
305316/// Concatenates two bytes sequences.
306317///
0 commit comments