1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

string(buffer, len) cast

This commit is contained in:
Alexander Medvednikov 2019-07-18 04:42:00 +02:00
parent 92fbe56276
commit f5c8ee4742
2 changed files with 21 additions and 2 deletions

View File

@ -2647,11 +2647,18 @@ 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') {
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' {
p.error('cannot cast `$expr_typ` to `$typ`, use `str()` method instead')
@ -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
}

View File

@ -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'
}