diff --git a/compiler/parser.v b/compiler/parser.v index dd8f9205f6..da46bb564e 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -2647,10 +2647,17 @@ fn (p mut Parser) cast(typ string) string { p.expected_type = typ expr_typ := p.bool_expression() p.expected_type = '' - p.check(.rpar) // `string(buffer)` => `tos2(buffer)` + // `string(buffer, len)` => `tos(buffer, len)` if typ == 'string' && (expr_typ == 'byte*' || expr_typ == 'byteptr') { - p.cgen.set_placeholder(pos, 'tos2(') + if p.tok == .comma { + p.check(.comma) + p.cgen.set_placeholder(pos, 'tos(') + p.gen(', ') + p.check_types(p.expression(), 'int') + } else { + p.cgen.set_placeholder(pos, 'tos2(') + } } // `string(234)` => error else if typ == 'string' && expr_typ == 'int' { @@ -2659,6 +2666,7 @@ fn (p mut Parser) cast(typ string) string { else { p.cgen.set_placeholder(pos, '($typ)(') } + p.check(.rpar) p.gen(')') return typ } diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 6d80ec6b37..5808ed4abe 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -318,3 +318,14 @@ fn test_interpolation() { assert s == 'baz=baz' } + +fn test_bytes_to_string() { + mut buf := malloc(10) + buf[0] = `h` + buf[1] = `e` + buf[2] = `l` + buf[3] = `l` + buf[4] = `o` + assert string(buf) == 'hello' + assert string(buf, 2) == 'he' +}