1///|
2struct Buffer {
3  mut 
Slice[Byte]
b
:
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
[
Byte
Byte
]
4 // off represent the current read/write position in the buffer. 5 // It is recommended to use the buffer as a reader or writer 6 // but not both at the same time. 7 mut
Int
off
:
Int
Int
8} 9 10///| 11/// Buffer::new creates a new empty Buffer with an optional size hint. 12/// The size hint is used to preallocate memory for the buffer, which can 13/// improve performance when the size of the data to be written is known in advance. 14pub fn
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(size_hint~ : Int = ..) -> Buffer

Buffer::new creates a new empty Buffer with an optional size hint. The size hint is used to preallocate memory for the buffer, which can improve performance when the size of the data to be written is known in advance.

new
(
Int
size_hint
~ :
Int
Int
= 0) ->
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
{
15 let
Slice[Byte]
b
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int, end~ : Int) -> Slice[Byte]
new
(
type Array[T]

An Array is a collection of values that supports random access and can grow in size.

Array
::
(Int, Byte) -> Array[Byte]

Creates a new array with a specified length and initializes all elements with the given value.

Parameters:

  • length : The length of the array to create. Must be a non-negative integer.
  • initial_value : The value used to initialize all elements in the array.

Returns a new array of type Array[T] with length elements, where each element is initialized to initial_value.

Throws an error if length is negative.

Example:

test "Array::make" {
  let arr = Array::make(3, 42)
  inspect(arr, content="[42, 42, 42]")
}

test "panic Array::make/negative_length" {
  ignore(Array::make(-1, 0))
}

WARNING: A common pitfall is creating with the same initial value, for example:

test {
  let two_dimension_array = Array::make(10, Array::make(10, 0))
  two_dimension_array[0][5] = 10
  assert_eq(two_dimension_array[5][5], 10)
}

This is because all the cells reference to the same object (the Array[Int] in this case). One should use makei() instead which creates an object for each index.

make
(
Int
size_hint
, b'\x00'),
Int
start
=0,
Int
end
=0)
16 {
Slice[Byte]
b
,
Int
off
: 0 }
17} 18 19///| 20let
&Reader
_trait4
: &
trait Reader {
  read(Self, Slice[Byte]) -> (Int, IOError?)
}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-None) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == eof or err == None. The next Read should return 0, eof.

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed eof behaviors.

If len(p) == 0, Read should always return n == 0. It may return a non-None error if some error condition is known, such as eof.

Implementations of Read are discouraged from returning a zero byte count with a None error, except when len(p) == 0. Callers should treat a return of 0 and None as indicating that nothing happened; in particular it does not indicate eof.

Implementations must not retain p.

Reader
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(size_hint~ : Int = ..) -> Buffer

Buffer::new creates a new empty Buffer with an optional size hint. The size hint is used to preallocate memory for the buffer, which can improve performance when the size of the data to be written is known in advance.

new
()
21 22///| 23let
&Writer
_trait5
: &
trait Writer {
  write(Self, Slice[Byte]) -> (Int, IOError?)
}

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-None error if it returns n < len(p). Write must not modify the slice data, even temporarily.

Implementations must not retain p.

Writer
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(size_hint~ : Int = ..) -> Buffer

Buffer::new creates a new empty Buffer with an optional size hint. The size hint is used to preallocate memory for the buffer, which can improve performance when the size of the data to be written is known in advance.

new
()
24 25///| 26pub fn
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : Slice[Byte]) -> Buffer
from_slice
(
Slice[Byte]
s
:
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
[
Byte
Byte
]) ->
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
{
27 let
Slice[Byte]
b
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
Slice[Byte]
s
.
(self : Slice[Byte]) -> Bytes

to_bytes returns slice as Bytes.

to_bytes
().
(self : Bytes) -> Array[Byte]

Converts a bytes sequence into an array of bytes.

Parameters:

  • bytes : A sequence of bytes to be converted into an array.

Returns an array containing the same bytes as the input sequence.

Example:

test "Bytes::to_array" {
  let bytes = b"hello"
  let arr = bytes.to_array()
  inspect(arr, content="[b'\\x68', b'\\x65', b'\\x6C', b'\\x6C', b'\\x6F']")
}
to_array
())
28 {
Slice[Byte]
b
,
Int
off
: 0 }
29} 30 31///| 32pub fn
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(b : Bytes) -> Buffer
from_bytes
(
Bytes
b
:
Bytes
Bytes
) ->
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
{
33 let
Slice[Byte]
buf
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
Bytes
b
.
(self : Bytes) -> Array[Byte]

Converts a bytes sequence into an array of bytes.

Parameters:

  • bytes : A sequence of bytes to be converted into an array.

Returns an array containing the same bytes as the input sequence.

Example:

test "Bytes::to_array" {
  let bytes = b"hello"
  let arr = bytes.to_array()
  inspect(arr, content="[b'\\x68', b'\\x65', b'\\x6C', b'\\x6C', b'\\x6F']")
}
to_array
())
34 {
Slice[Byte]
b
:
Slice[Byte]
buf
,
Int
off
: 0 }
35} 36 37///| 38/// `Buffer::from_string` converts the MoonBit UTF-16 String to UTF-8 39/// and creates a Buffer from the bytes. 40pub fn
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : String) -> Buffer

Buffer::from_string converts the MoonBit UTF-16 String to UTF-8 and creates a Buffer from the bytes.

from_string
(
String
s
:
String
String
) ->
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
{
41 let
Bytes
b
=
(s : String) -> Bytes

str2bytes encodes a UTF-16 String as a UTF-8 Bytes.

Examples:

inspect!(str2bytes("+/ Hello, 世界! 🌍"), content=
  #|b"\x2b\x2f\x20\x48\x65\x6c\x6c\x6f\x2c\x20\xe4\xb8\x96\xe7\x95\x8c\x21\x20\xf0\x9f\x8c\x8d"
)
@base64.str2bytes
(
String
s
)
42 let
Slice[Byte]
buf
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
Bytes
b
.
(self : Bytes) -> Array[Byte]

Converts a bytes sequence into an array of bytes.

Parameters:

  • bytes : A sequence of bytes to be converted into an array.

Returns an array containing the same bytes as the input sequence.

Example:

test "Bytes::to_array" {
  let bytes = b"hello"
  let arr = bytes.to_array()
  inspect(arr, content="[b'\\x68', b'\\x65', b'\\x6C', b'\\x6C', b'\\x6F']")
}
to_array
())
43 {
Slice[Byte]
b
:
Slice[Byte]
buf
,
Int
off
: 0 }
44} 45 46///| 47pub fn
(self : Buffer, size_hint~ : Int = ..) -> Unit
reset
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
Int
size_hint
~ :
Int
Int
= 0) ->
Unit
Unit
{
48
Buffer
self
.
Slice[Byte]
b
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int, end~ : Int) -> Slice[Byte]
new
(
type Array[T]

An Array is a collection of values that supports random access and can grow in size.

Array
::
(Int, Byte) -> Array[Byte]

Creates a new array with a specified length and initializes all elements with the given value.

Parameters:

  • length : The length of the array to create. Must be a non-negative integer.
  • initial_value : The value used to initialize all elements in the array.

Returns a new array of type Array[T] with length elements, where each element is initialized to initial_value.

Throws an error if length is negative.

Example:

test "Array::make" {
  let arr = Array::make(3, 42)
  inspect(arr, content="[42, 42, 42]")
}

test "panic Array::make/negative_length" {
  ignore(Array::make(-1, 0))
}

WARNING: A common pitfall is creating with the same initial value, for example:

test {
  let two_dimension_array = Array::make(10, Array::make(10, 0))
  two_dimension_array[0][5] = 10
  assert_eq(two_dimension_array[5][5], 10)
}

This is because all the cells reference to the same object (the Array[Int] in this case). One should use makei() instead which creates an object for each index.

make
(
Int
size_hint
, b'\x00'),
Int
start
=0,
Int
end
=0)
49
Buffer
self
.
Int
off
= 0
50} 51 52///| 53pub impl
trait Writer {
  write(Self, Slice[Byte]) -> (Int, IOError?)
}

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-None error if it returns n < len(p). Write must not modify the slice data, even temporarily.

Implementations must not retain p.

Writer
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer, buf : Slice[Byte]) -> (Int, IOError?)
write
(
Buffer
self
,
Slice[Byte]
buf
) {
54 let
Int
blen
=
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
55 let
Int
buflen
=
Slice[Byte]
buf
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
56
Buffer
self
.
Slice[Byte]
b
=
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
57
type Array[T]

An Array is a collection of values that supports random access and can grow in size.

Array
::
(Int, (Int) -> Byte) -> Array[Byte]

Creates a new array of the specified length, where each element is initialized using an index-based initialization function.

Parameters:

  • length : The length of the new array. If length is less than or equal to 0, returns an empty array.
  • initializer : A function that takes an index (starting from 0) and returns a value of type T. This function is called for each index to initialize the corresponding element.

Returns a new array of type Array[T] with the specified length, where each element is initialized using the provided function.

Example:

test "Array::makei" {
  let arr = Array::makei(3, fn(i) { i * 2 })
  inspect(arr, content="[0, 2, 4]")
}
makei
(
Int
blen
(self : Int, other : Int) -> Int

Adds two 32-bit signed integers. Performs two's complement arithmetic, which means the operation will wrap around if the result exceeds the range of a 32-bit integer.

Parameters:

  • self : The first integer operand.
  • other : The second integer operand.

Returns a new integer that is the sum of the two operands. If the mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to 2,147,483,647), the result wraps around according to two's complement rules.

Example:

test "Int::op_add" {
  inspect(42 + 1, content="43")
  inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
}
+
Int
buflen
, fn(
Int
i
) {
58 if
Int
i
(self_ : Int, other : Int) -> Bool
<
Int
blen
{
59
Buffer
self
.
Slice[Byte]
b
(Slice[Byte], Int) -> Byte
[
i]
60 } else { 61
Slice[Byte]
buf
.
Array[Byte]
buf
(Array[Byte], Int) -> Byte

Retrieves an element from the array at the specified index.

Parameters:

  • array : The array to get the element from.
  • index : The position in the array from which to retrieve the element.

Returns the element at the specified index.

Throws a panic if the index is negative or greater than or equal to the length of the array.

Example:

test "Array::op_get" {
  let arr = [1, 2, 3]
  inspect(arr[1], content="2")
}

test "panic Array::op_get/out_of_bounds" {
  let arr = [1, 2, 3]
  ignore(arr[3]) // Index out of bounds
}
[
buf.
Int
start
(self : Int, other : Int) -> Int

Adds two 32-bit signed integers. Performs two's complement arithmetic, which means the operation will wrap around if the result exceeds the range of a 32-bit integer.

Parameters:

  • self : The first integer operand.
  • other : The second integer operand.

Returns a new integer that is the sum of the two operands. If the mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to 2,147,483,647), the result wraps around according to two's complement rules.

Example:

test "Int::op_add" {
  inspect(42 + 1, content="43")
  inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
}
+
Int
i
(self : Int, other : Int) -> Int

Performs subtraction between two 32-bit integers, following standard two's complement arithmetic rules. When the result overflows or underflows, it wraps around within the 32-bit integer range.

Parameters:

  • self : The minuend (the number being subtracted from).
  • other : The subtrahend (the number to subtract).

Returns the difference between self and other.

Example:

test "Int::op_sub" {
  let a = 42
  let b = 10
  inspect(a - b, content="32")
  let max = 2147483647 // Int maximum value
  inspect(max - -1, content="-2147483648") // Overflow case
}
-
Int
blen
]
62 } 63 }), 64 ) 65 (
Int
buflen
,
IOError?
None
)
66} 67 68///| 69pub fn
(self : Buffer, buf : Bytes) -> (Int, IOError?)
write_bytes
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
Bytes
buf
:
Bytes
Bytes
) -> (
Int
Int
,
type! IOError String

An IOError can be tested with equality checks.

IOError
?) {
70
Buffer
self
.
(self : Buffer, buf : Slice[Byte]) -> (Int, IOError?)
write
(
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
Bytes
buf
.
(self : Bytes) -> Array[Byte]

Converts a bytes sequence into an array of bytes.

Parameters:

  • bytes : A sequence of bytes to be converted into an array.

Returns an array containing the same bytes as the input sequence.

Example:

test "Bytes::to_array" {
  let bytes = b"hello"
  let arr = bytes.to_array()
  inspect(arr, content="[b'\\x68', b'\\x65', b'\\x6C', b'\\x6C', b'\\x6F']")
}
to_array
()))
71} 72 73///| 74pub fn
(self : Buffer, b : Byte) -> (Int, IOError?)
write_byte
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
Byte
b
:
Byte
Byte
) -> (
Int
Int
,
type! IOError String

An IOError can be tested with equality checks.

IOError
?) {
75
Buffer
self
.
(self : Buffer, buf : Slice[Byte]) -> (Int, IOError?)
write
(
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
([
Byte
b
]))
76} 77 78///| 79/// `write_string` converts the MoonBit UTF-16 String to UTF-8 and 80/// writes the bytes to the buffer. 81pub fn
(self : Buffer, s : String) -> (Int, IOError?)

write_string converts the MoonBit UTF-16 String to UTF-8 and writes the bytes to the buffer.

write_string
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
String
s
:
String
String
) -> (
Int
Int
,
type! IOError String

An IOError can be tested with equality checks.

IOError
?) {
82 let
Bytes
b
=
(s : String) -> Bytes

str2bytes encodes a UTF-16 String as a UTF-8 Bytes.

Examples:

inspect!(str2bytes("+/ Hello, 世界! 🌍"), content=
  #|b"\x2b\x2f\x20\x48\x65\x6c\x6c\x6f\x2c\x20\xe4\xb8\x96\xe7\x95\x8c\x21\x20\xf0\x9f\x8c\x8d"
)
@base64.str2bytes
(
String
s
)
83
Buffer
self
.
(self : Buffer, buf : Bytes) -> (Int, IOError?)
write_bytes
(
Bytes
b
)
84} 85 86///| 87pub impl
trait Reader {
  read(Self, Slice[Byte]) -> (Int, IOError?)
}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-None) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == eof or err == None. The next Read should return 0, eof.

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed eof behaviors.

If len(p) == 0, Read should always return n == 0. It may return a non-None error if some error condition is known, such as eof.

Implementations of Read are discouraged from returning a zero byte count with a None error, except when len(p) == 0. Callers should treat a return of 0 and None as indicating that nothing happened; in particular it does not indicate eof.

Implementations must not retain p.

Reader
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer, buf : Slice[Byte]) -> (Int, IOError?)
read
(
Buffer
self
,
Slice[Byte]
buf
) {
88 let
Int
remaining
=
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
(self : Int, other : Int) -> Int

Performs subtraction between two 32-bit integers, following standard two's complement arithmetic rules. When the result overflows or underflows, it wraps around within the 32-bit integer range.

Parameters:

  • self : The minuend (the number being subtracted from).
  • other : The subtrahend (the number to subtract).

Returns the difference between self and other.

Example:

test "Int::op_sub" {
  let a = 42
  let b = 10
  inspect(a - b, content="32")
  let max = 2147483647 // Int maximum value
  inspect(max - -1, content="-2147483648") // Overflow case
}
-
Buffer
self
.
Int
off
89 if
Int
remaining
(self_ : Int, other : Int) -> Bool
<=
0
(Bool, Bool) -> Bool
||
Slice[Byte]
buf
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
(self : Int, other : Int) -> Bool

Compares two integers for equality.

Parameters:

  • self : The first integer to compare.
  • other : The second integer to compare.

Returns true if both integers have the same value, false otherwise.

Example:

test "Int::op_equal" {
  inspect(42 == 42, content="true")
  inspect(42 == -42, content="false")
}
==
0 {
90 return (0,
(IOError) -> IOError?
Some
(
IOError

eof is the error returned by Read when no more input is available. (Read must return eof itself, not an error wrapping eof, because callers will test for eof using ==.) Functions should return eof only to signal a graceful end of input. If the eof occurs unexpectedly in a structured data stream, the appropriate error is either [err_unexpected_eof] or some other error giving more detail.

eof
))
91 } 92 let
Int
n
=
(a : Int, b : Int) -> Int
minimum
(
Int
remaining
,
Slice[Byte]
buf
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
())
93
type Array[T]

An Array is a collection of values that supports random access and can grow in size.

Array
::
(Array[Byte], Int, Array[Byte], Int, Int) -> Unit

Copies elements from one array to another array. Works correctly even when the source and destination arrays overlap.

Parameters:

  • dst : The destination array where elements will be copied to.
  • dst_offset : The starting index in the destination array where elements should be copied.
  • src : The source array from which elements will be copied.
  • src_offset : The starting index in the source array from which elements should be copied.
  • len : The number of elements to copy.

The behavior is undefined if any of the following conditions are met:

  • len is negative
  • dst_offset is negative
  • src_offset is negative
  • dst_offset + len exceeds the length of destination array
  • src_offset + len exceeds the length of source array

Example:

test "Array::unsafe_blit" {
  let src = [1, 2, 3, 4, 5]
  let dst = [0, 0, 0, 0, 0]
  Array::unsafe_blit(dst, 1, src, 2, 2)
  inspect(dst, content="[0, 3, 4, 0, 0]")
}
unsafe_blit
(
Slice[Byte]
buf
.
Array[Byte]
buf
,
Slice[Byte]
buf
.
Int
start
,
Buffer
self
.
Slice[Byte]
b
.
Array[Byte]
buf
,
Buffer
self
.
Int
off
,
Int
n
)
94
Buffer
self
.
Int
off
(self : Int, other : Int) -> Int

Adds two 32-bit signed integers. Performs two's complement arithmetic, which means the operation will wrap around if the result exceeds the range of a 32-bit integer.

Parameters:

  • self : The first integer operand.
  • other : The second integer operand.

Returns a new integer that is the sum of the two operands. If the mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to 2,147,483,647), the result wraps around according to two's complement rules.

Example:

test "Int::op_add" {
  inspect(42 + 1, content="43")
  inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
}
+=
Int
n
95 (
Int
n
,
IOError?
None
)
96} 97 98///| 99pub impl
trait ByteReader {
  read_byte(Self) -> (Byte, IOError?)
}

ByteReader is the interface that wraps the read_byte method.

read_byte reads and returns the next byte from the input or any error encountered. If read_byte returns an error, no input byte was consumed, and the returned byte value is undefined.

read_byte provides an efficient interface for byte-at-time processing. A [Reader] that does not implement ByteReader can be wrapped using bufio.NewReader to add this method.

ByteReader
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer) -> (Byte, IOError?)
read_byte
(
Buffer
self
) {
100 let
Int
remaining
=
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
(self : Int, other : Int) -> Int

Performs subtraction between two 32-bit integers, following standard two's complement arithmetic rules. When the result overflows or underflows, it wraps around within the 32-bit integer range.

Parameters:

  • self : The minuend (the number being subtracted from).
  • other : The subtrahend (the number to subtract).

Returns the difference between self and other.

Example:

test "Int::op_sub" {
  let a = 42
  let b = 10
  inspect(a - b, content="32")
  let max = 2147483647 // Int maximum value
  inspect(max - -1, content="-2147483648") // Overflow case
}
-
Buffer
self
.
Int
off
101 if
Int
remaining
(self_ : Int, other : Int) -> Bool
<=
0 {
102 return (0,
(IOError) -> IOError?
Some
(
IOError

eof is the error returned by Read when no more input is available. (Read must return eof itself, not an error wrapping eof, because callers will test for eof using ==.) Functions should return eof only to signal a graceful end of input. If the eof occurs unexpectedly in a structured data stream, the appropriate error is either [err_unexpected_eof] or some other error giving more detail.

eof
))
103 } 104 let
Byte
b
=
Buffer
self
.
Slice[Byte]
b
(Slice[Byte], Int) -> Byte
[
self.
Int
off
]
105
Buffer
self
.
Int
off
(self : Int, other : Int) -> Int

Adds two 32-bit signed integers. Performs two's complement arithmetic, which means the operation will wrap around if the result exceeds the range of a 32-bit integer.

Parameters:

  • self : The first integer operand.
  • other : The second integer operand.

Returns a new integer that is the sum of the two operands. If the mathematical sum exceeds the range of a 32-bit integer (-2,147,483,648 to 2,147,483,647), the result wraps around according to two's complement rules.

Example:

test "Int::op_add" {
  inspect(42 + 1, content="43")
  inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
}
+=
1
106 (
Byte
b
,
IOError?
None
)
107} 108 109///| 110pub fn
(self : Buffer, r : &Reader) -> (Int64, IOError?)
read_from
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
&Reader
r
: &
trait Reader {
  read(Self, Slice[Byte]) -> (Int, IOError?)
}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-None) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == eof or err == None. The next Read should return 0, eof.

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed eof behaviors.

If len(p) == 0, Read should always return n == 0. It may return a non-None error if some error condition is known, such as eof.

Implementations of Read are discouraged from returning a zero byte count with a None error, except when len(p) == 0. Callers should treat a return of 0 and None as indicating that nothing happened; in particular it does not indicate eof.

Implementations must not retain p.

Reader
) -> (
Int64
Int64
,
type! IOError String

An IOError can be tested with equality checks.

IOError
?) {
111
(dst : &Writer, src : &Reader) -> (Int64, IOError?)

copy copies from src to dst until either eof is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.

A successful copy returns err == None, not err == eof. Because copy is defined to read from src until eof, it does not treat an eof from Read as an error to be reported.

If src implements [WriterTo], the copy is implemented by calling src.write_to(dst). Otherwise, if dst implements [ReaderFrom], the copy is implemented by calling dst.read_from(src).

copy
(
Buffer
self
,
&Reader
r
)
112} 113 114///| 115fn
(a : Int, b : Int) -> Int
minimum
(
Int
a
:
Int
Int
,
Int
b
:
Int
Int
) ->
Int
Int
{
116 if
Int
a
(self_ : Int, other : Int) -> Bool
<
Int
b
{
117
Int
a
118 } else { 119
Int
b
120 } 121} 122 123///| 124pub fn
(self : Buffer) -> Bytes
to_bytes
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
) ->
Bytes
Bytes
{
125
(Array[Byte]) -> Bytes
Bytes::
(arr : Array[Byte]) -> Bytes

Creates a new bytes sequence from a byte array.

Parameters:

  • array : An array of bytes to be converted.

Returns a new bytes sequence containing the same bytes as the input array.

Example:

test "Bytes::from_array" {
  let arr = [b'h', b'i']
  let bytes = @bytes.from_array(arr)
  inspect(bytes, content=
    #|b"\x68\x69"
  )
}
from_array
(
Buffer
self
.
Slice[Byte]
b
.
Array[Byte]
buf
)
126} 127 128///| 129pub impl
trait Show {
  output(Self, &Logger) -> Unit
  to_string(Self) -> String
}

Trait for types that can be converted to String

Show
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer) -> String
to_string
(
Buffer
self
) {
130
(b : Bytes) -> String

bytes2str decodes a UTF-8 Bytes to a UTF-16 String.

Examples:

inspect!(bytes2str("+/ Hello, 世界! 🌍"), content="+/ Hello, 世界! 🌍")
@base64.bytes2str
(
(Array[Byte]) -> Bytes
Bytes::
(arr : Array[Byte]) -> Bytes

Creates a new bytes sequence from a byte array.

Parameters:

  • array : An array of bytes to be converted.

Returns a new bytes sequence containing the same bytes as the input array.

Example:

test "Bytes::from_array" {
  let arr = [b'h', b'i']
  let bytes = @bytes.from_array(arr)
  inspect(bytes, content=
    #|b"\x68\x69"
  )
}
from_array
(
Buffer
self
.
Slice[Byte]
b
.
Array[Byte]
buf
))
131} 132 133///| 134pub impl
trait Show {
  output(Self, &Logger) -> Unit
  to_string(Self) -> String
}

Trait for types that can be converted to String

Show
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer, logger : &Logger) -> Unit
output
(
Buffer
self
,
&Logger
logger
) {
135
&Logger
logger
.
(&Logger, String) -> Unit
write_string
(
Buffer
self
.
(self : Buffer) -> String
to_string
())
136} 137 138///| 139pub impl
trait Eq {
  op_equal(Self, Self) -> Bool
}

Trait for types whose elements can test for equality

Eq
for
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
with
(self : Buffer, other : Buffer) -> Bool
op_equal
(
Buffer
self
,
Buffer
other
) {
140 if
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
(x : Int, y : Int) -> Bool
!=
Buffer
other
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
() {
141 return false 142 } 143 for
Int
i
in
Int
0
..<
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
() {
144 if
Buffer
self
.
Slice[Byte]
b
(Slice[Byte], Int) -> Byte
[
i]
(x : Byte, y : Byte) -> Bool
!=
Buffer
other
.
Slice[Byte]
b
(Slice[Byte], Int) -> Byte
[
i] {
145 return false 146 } 147 } 148 true 149} 150 151///| 152pub fn
(self : Buffer) -> Slice[Byte]
to_slice
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
) ->
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
[
Byte
Byte
] {
153
struct Slice[T] {
  buf: Array[T]
  start: Int
  len: Int
}

A Slice is a slice of an Array.

A separate Slice type was needed because of this issue: https://github.com/moonbitlang/core/issues/1063

This struct is based on MoonBit's "ArrayView" implementation here: https://github.com/moonbitlang/core/blob/main/builtin/arrayview.mbt which has the following copyright:

Copyright 2024 International Digital Economy Academy

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Slice
::
(buf : Array[Byte], start~ : Int = .., end? : Int) -> Slice[Byte]
new
(
Buffer
self
.
Slice[Byte]
b
.
Array[Byte]
buf
)
154} 155 156///| 157pub fn
(self : Buffer) -> Int
length
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
) ->
Int
Int
{
158
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
159} 160 161///| 162pub fn
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(self : Buffer, index : Int) -> Byte
op_get
(
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
Int
index
:
Int
Int
) ->
Byte
Byte
{
163
Buffer
self
.
Slice[Byte]
b
(Slice[Byte], Int) -> Byte
[
index]
164} 165 166///| 167pub fn
(self : Buffer, start~ : Int = .., end~ : Int = ..) -> String
substring
(
168
Buffer
self
:
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
,
169
Int
start
~ :
Int
Int
= 0,
170
Int
end
~ :
Int
Int
=
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()
171) ->
String
String
{
172 guard
Int
start
(self_ : Int, other : Int) -> Bool
>=
0
(Bool, Bool) -> Bool
&&
Int
start
(self_ : Int, other : Int) -> Bool
<=
Int
end
(Bool, Bool) -> Bool
&&
Int
end
(self_ : Int, other : Int) -> Bool
<=
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
() else {
173
(msg : String) -> String

Aborts the program with an error message. Always causes a panic, regardless of the message provided.

Parameters:

  • message : A string containing the error message to be displayed when aborting.

Returns a value of type T. However, this function never actually returns a value as it always causes a panic.

abort
(
174 "Buffer::substring(start=\{
Int
start
}, end=\{
Int
end
}) out of bounds for length=\{
Buffer
self
.
Slice[Byte]
b
.
(self : Slice[Byte]) -> Int

length returns the length of the slice.

length
()})",
175 ) 176 } 177 let
Bytes
bytes
=
(Iter[Byte]) -> Bytes
Bytes::
(iter : Iter[Byte]) -> Bytes

Creates a new bytes sequence from an iterator of bytes.

Parameters:

  • iterator : An iterator that yields bytes.

Returns a new bytes sequence containing all the bytes from the iterator.

Example:

test "from_iter" {
  let iter = Iter::singleton(b'h')
  let bytes = @bytes.from_iter(iter)
  inspect(bytes, content=
    #|b"\x68"
  )
}
from_iter
(
Buffer
self
.
Slice[Byte]
b
[
Int
start
:
Int
end
].
(self : Slice[Byte]) -> Iter[Byte]
iter
())
178
(b : Bytes) -> String

bytes2str decodes a UTF-8 Bytes to a UTF-16 String.

Examples:

inspect!(bytes2str("+/ Hello, 世界! 🌍"), content="+/ Hello, 世界! 🌍")
@base64.bytes2str
(
Bytes
bytes
)
179} 180 181///| 182test "Buffer::substring" { 183 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(size_hint~ : Int = ..) -> Buffer

Buffer::new creates a new empty Buffer with an optional size hint. The size hint is used to preallocate memory for the buffer, which can improve performance when the size of the data to be written is known in advance.

new
()
184
Buffer
buf
.
(self : Buffer, s : String) -> (Int, IOError?)

write_string converts the MoonBit UTF-16 String to UTF-8 and writes the bytes to the buffer.

write_string
("hello world") |>
(t : (Int, IOError?)) -> Unit

Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

Parameters:

  • value : The value to be ignored. Can be of any type.

Example:

test "ignore" {
  let x = 42
  ignore(x) // Explicitly ignore the value
  let mut sum = 0
  ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
}
ignore
()
185
(obj : &Show, content~ : String, loc~ : SourceLoc = _, args_loc~ : ArgsLoc = _) -> Unit!InspectError

Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

Parameters:

  • object : The object to be inspected. Must implement the Show trait.
  • content : The expected string representation of the object. Defaults to an empty string.
  • location : Source code location information for error reporting. Automatically provided by the compiler.
  • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

Example:

test "inspect/basic" {
  inspect(42, content="42")
  inspect("hello", content="hello")
  inspect([1, 2, 3], content="[1, 2, 3]")
}
inspect
!(
Buffer
buf
.
(self : Buffer, start~ : Int = .., end~ : Int = ..) -> String
substring
(),
String
content
="hello world")
186
(obj : &Show, content~ : String, loc~ : SourceLoc = _, args_loc~ : ArgsLoc = _) -> Unit!InspectError

Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

Parameters:

  • object : The object to be inspected. Must implement the Show trait.
  • content : The expected string representation of the object. Defaults to an empty string.
  • location : Source code location information for error reporting. Automatically provided by the compiler.
  • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

Example:

test "inspect/basic" {
  inspect(42, content="42")
  inspect("hello", content="hello")
  inspect([1, 2, 3], content="[1, 2, 3]")
}
inspect
!(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int = ..) -> String
substring
(
Int
start
=6),
String
content
="world")
187
(obj : &Show, content~ : String, loc~ : SourceLoc = _, args_loc~ : ArgsLoc = _) -> Unit!InspectError

Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

Parameters:

  • object : The object to be inspected. Must implement the Show trait.
  • content : The expected string representation of the object. Defaults to an empty string.
  • location : Source code location information for error reporting. Automatically provided by the compiler.
  • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

Example:

test "inspect/basic" {
  inspect(42, content="42")
  inspect("hello", content="hello")
  inspect([1, 2, 3], content="[1, 2, 3]")
}
inspect
!(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int) -> String
substring
(
Int
start
=0,
Int
end
=5),
String
content
="hello")
188} 189 190///| 191test "panic Buffer::substring/out-of-bounds 1" { 192 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : String) -> Buffer

Buffer::from_string converts the MoonBit UTF-16 String to UTF-8 and creates a Buffer from the bytes.

from_string
("hello world")
193
(t : String) -> Unit

Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

Parameters:

  • value : The value to be ignored. Can be of any type.

Example:

test "ignore" {
  let x = 42
  ignore(x) // Explicitly ignore the value
  let mut sum = 0
  ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
}
ignore
(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int = ..) -> String
substring
(
Int
start
=-1))
194} 195 196///| 197test "panic Buffer::substring/out-of-bounds 2" { 198 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : String) -> Buffer

Buffer::from_string converts the MoonBit UTF-16 String to UTF-8 and creates a Buffer from the bytes.

from_string
("hello world")
199
(t : String) -> Unit

Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

Parameters:

  • value : The value to be ignored. Can be of any type.

Example:

test "ignore" {
  let x = 42
  ignore(x) // Explicitly ignore the value
  let mut sum = 0
  ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
}
ignore
(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int = ..) -> String
substring
(
Int
start
=12))
200} 201 202///| 203test "panic Buffer::substring/out-of-bounds 3" { 204 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : String) -> Buffer

Buffer::from_string converts the MoonBit UTF-16 String to UTF-8 and creates a Buffer from the bytes.

from_string
("hello world")
205
(t : String) -> Unit

Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

Parameters:

  • value : The value to be ignored. Can be of any type.

Example:

test "ignore" {
  let x = 42
  ignore(x) // Explicitly ignore the value
  let mut sum = 0
  ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
}
ignore
(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int) -> String
substring
(
Int
start
=0,
Int
end
=12))
206} 207 208///| 209test "panic Buffer::substring/out-of-bounds 4" { 210 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(s : String) -> Buffer

Buffer::from_string converts the MoonBit UTF-16 String to UTF-8 and creates a Buffer from the bytes.

from_string
("hello world")
211
(t : String) -> Unit

Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

Parameters:

  • value : The value to be ignored. Can be of any type.

Example:

test "ignore" {
  let x = 42
  ignore(x) // Explicitly ignore the value
  let mut sum = 0
  ignore([1, 2, 3].iter().each(fn(x) { sum = sum + x })) // Ignore the Unit return value of each()
}
ignore
(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int) -> String
substring
(
Int
start
=6,
Int
end
=5))
212} 213 214///| 215test "Buffer::substring/empty" { 216 let
Buffer
buf
=
struct Buffer {
  mut b: Slice[Byte]
  mut off: Int
}
Buffer
::
(size_hint~ : Int = ..) -> Buffer

Buffer::new creates a new empty Buffer with an optional size hint. The size hint is used to preallocate memory for the buffer, which can improve performance when the size of the data to be written is known in advance.

new
()
217
(obj : &Show, content~ : String, loc~ : SourceLoc = _, args_loc~ : ArgsLoc = _) -> Unit!InspectError

Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

Parameters:

  • object : The object to be inspected. Must implement the Show trait.
  • content : The expected string representation of the object. Defaults to an empty string.
  • location : Source code location information for error reporting. Automatically provided by the compiler.
  • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

Example:

test "inspect/basic" {
  inspect(42, content="42")
  inspect("hello", content="hello")
  inspect([1, 2, 3], content="[1, 2, 3]")
}
inspect
!(
Buffer
buf
.
(self : Buffer, start~ : Int = .., end~ : Int = ..) -> String
substring
(),
String
content
="")
218
(obj : &Show, content~ : String, loc~ : SourceLoc = _, args_loc~ : ArgsLoc = _) -> Unit!InspectError

Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

Parameters:

  • object : The object to be inspected. Must implement the Show trait.
  • content : The expected string representation of the object. Defaults to an empty string.
  • location : Source code location information for error reporting. Automatically provided by the compiler.
  • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

Example:

test "inspect/basic" {
  inspect(42, content="42")
  inspect("hello", content="hello")
  inspect([1, 2, 3], content="[1, 2, 3]")
}
inspect
!(
Buffer
buf
.
(self : Buffer, start~ : Int, end~ : Int) -> String
substring
(
Int
start
=0,
Int
end
=0),
String
content
="")
219} 220