From 4038ac463cf899a234a19789471c3e51962f868a Mon Sep 17 00:00:00 2001 From: Henrixounez <30901439+Henrixounez@users.noreply.github.com> Date: Fri, 18 Sep 2020 01:12:32 +0200 Subject: [PATCH] gen: bytes array print not ending prematurely when null byte (#6401) --- vlib/builtin/int.v | 16 ++++++++++++++++ vlib/v/gen/auto_str_methods.v | 3 +++ vlib/v/tests/array_to_string_test.v | 3 +++ 3 files changed, 22 insertions(+) diff --git a/vlib/builtin/int.v b/vlib/builtin/int.v index e7ff07c278..1dcbb21658 100644 --- a/vlib/builtin/int.v +++ b/vlib/builtin/int.v @@ -383,6 +383,22 @@ pub fn (b byte) str() string { return str } +pub fn (b byte) str_escaped() string { + str := match b { + 0 { '`\\' + '0`' } // Bug is preventing \\0 in a literal + 7 { '`\\a`' } + 8 { '`\\b`' } + 9 { '`\\t`' } + 10 { '`\\n`' } + 11 { '`\\v`' } + 12 { '`\\f`' } + 13 { '`\\r`' } + 32...126 { b.str() } + else { '0x' + b.hex() } + } + return str +} + // TODO generic pub fn (a []byte) contains(val byte) bool { for aa in a { diff --git a/vlib/v/gen/auto_str_methods.v b/vlib/v/gen/auto_str_methods.v index 62aedb6a51..b5edd9085f 100644 --- a/vlib/v/gen/auto_str_methods.v +++ b/vlib/v/gen/auto_str_methods.v @@ -74,6 +74,9 @@ fn (mut g Gen) gen_str_for_array(info table.Array, styp, str_fn_name string) { if sym_has_str_method { elem_str_fn_name = if is_elem_ptr { field_styp.replace('*', '') + '_str' } else { field_styp + '_str' } + if sym.kind == .byte { + elem_str_fn_name = elem_str_fn_name + '_escaped' + } } else { elem_str_fn_name = styp_to_str_fn_name(field_styp) } diff --git a/vlib/v/tests/array_to_string_test.v b/vlib/v/tests/array_to_string_test.v index 9adae05a9f..004272861a 100644 --- a/vlib/v/tests/array_to_string_test.v +++ b/vlib/v/tests/array_to_string_test.v @@ -13,6 +13,9 @@ fn test_array_to_string_conversion() { e := [i64(1), 2, 3] assert e.str() == '[1, 2, 3]' + + f := [byte(66), 32, 126, 10, 13, 5, 18, 127, 255] + assert f.str() == '[B, , ~, `\\n`, `\\r`, 0x05, 0x12, 0x7f, 0xff]' } fn test_interpolation_array_to_string() {