Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refine behavior of Show::to_string(Bytes) #384

Merged
merged 2 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion builtin/show.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,29 @@ pub impl Show for Byte with output(self, logger) {
}

pub impl Show for Bytes with output(self, logger) {
logger.write_string(self.to_string())
fn to_hex_digit(i : Int) -> Char {
if i < 10 {
Char::from_int('0'.to_int() + i)
} else {
Char::from_int('a'.to_int() + (i - 10))
}
}

logger.write_string("b\"")
for i = 0; i < self.length(); i = i + 1 {
let byte = self[i].to_int()
logger
..write_string("\\x")
..write_char(to_hex_digit(byte / 16))
.write_char(to_hex_digit(byte % 16))
}
logger.write_string("\"")
}

pub impl Show for Bytes with to_string(self) {
let buf = Buffer::new()
Show::output(self, buf)
buf.to_string()
}

pub impl Show for String with output(self, logger) {
Expand Down
22 changes: 21 additions & 1 deletion bytes/bytes_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,29 @@
// See the License for the specific language governing permissions and
// limitations under the License.

test "bytes literal" {
inspect!(
b"ABC",
content=
#|b"\x41\x42\x43"
,
)
inspect!(
b"\x41\x42\x43",
content=
#|b"\x41\x42\x43"
,
)
}

test "from_array" {
let b = @bytes.of([b'\x41', b'\x00', b'\x42', b'\x00', b'\x43', b'\x00'])
inspect!(b, content="ABC")
inspect!(
b,
content=
#|b"\x41\x00\x42\x00\x43\x00"
,
)
}

test "hash" {
Expand Down