Skip to content

Commit 04776c4

Browse files
committed
feat(buffer): new api from_{bytes, array, iter}
1 parent 133e21a commit 04776c4

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

buffer/buffer.mbt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,30 @@ pub fn new(size_hint~ : Int = 0) -> T {
162162
{ data, len: 0, initial_data: data }
163163
}
164164
165+
///| Create a buffer from a bytes.
166+
pub fn T::from_bytes(bytes : Bytes) -> T {
167+
let buf = T::new(size_hint=bytes.length())
168+
buf.write_bytes(bytes)
169+
buf
170+
}
171+
172+
///|
173+
/// Create a buffer from an array.
174+
pub fn T::from_array(arr : Array[Byte]) -> T {
175+
let buf = T::new(size_hint=arr.length())
176+
for byte in arr {
177+
buf.write_byte(byte)
178+
}
179+
buf
180+
}
181+
182+
///|
183+
/// Create a buffer from an array.
184+
pub fn T::from_iter(iter : Iter[Byte]) -> T {
185+
let arr = iter.collect()
186+
T::from_array(arr)
187+
}
188+
165189
///|
166190
/// Writes a UTF-16LE encoded string into the buffer. The buffer will
167191
/// automatically grow if needed to accommodate the string.

buffer/buffer.mbti

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ fn new(size_hint~ : Int = ..) -> T
77
type T
88
impl T {
99
contents(Self) -> Bytes
10+
from_array(Array[Byte]) -> Self
11+
from_bytes(Bytes) -> Self
12+
from_iter(Iter[Byte]) -> Self
1013
is_empty(Self) -> Bool
1114
length(Self) -> Int
1215
new(size_hint~ : Int = ..) -> Self //deprecated

buffer/buffer_test.mbt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,24 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
test "create buffer from bytes" {
16+
let bytes = b"1\x002\x003\x00"
17+
let buf = @buffer.from_bytes(bytes)
18+
inspect!(buf, content="123")
19+
}
20+
21+
test "create buffer from array" {
22+
let arr = [b'4', b'\x00', b'5', b'\x00', b'6', b'\x00']
23+
let buf = @buffer.from_array(arr)
24+
inspect!(buf, content="456")
25+
}
26+
27+
test "create buffer from iterator" {
28+
let iter = [b'5', b'\x00', b'6', b'\x00', b'7', b'\x00'].iter()
29+
let buf = @buffer.from_iter(iter)
30+
inspect!(buf, content="567")
31+
}
32+
1533
test "length method" {
1634
let buf = @buffer.new(size_hint=100)
1735
inspect!(buf.length(), content="0")

0 commit comments

Comments
 (0)