vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.76k stars 2.16k forks source link

str.bytes() bug #18243

Open Vsirer opened 1 year ago

Vsirer commented 1 year ago

Describe the bug

I use str.bytes() to create a byte array and the result of a manually created byte array is different

Expected Behavior

  func TestName(t *testing.T) {
      b1 := []byte{0x59, 0x3c, 0x5c, 0x52, 0x18}
      b2 := []byte("\x59\x3c\x5c\x52\x18")

      for i := 0; i < len(b2); i++ {
          fmt.Printf("num:%d, byte1:%x, byte2:%x\n", i, b1[i], b2[i])
      }
  }
result: 
num:0, byte1:59, byte2:59
num:1, byte1:3c, byte2:3c
num:2, byte1:5c, byte2:5c
num:3, byte1:52, byte2:52
num:4, byte1:18, byte2:18

I use golang to test, the results are the same in both ways

Current Behavior

module main

fn main(){
    b1 := [u8(0x59),0x3c,0x5c,0x52,0x18]
    b2 := '\x59\x3c\x5c\x52\x18'.bytes()

    for i := 0; i < b2.len; i++ {
        println('num:${i}, byte1:${b1[i].hex()}, byte2:${b2[i].hex()}')
    }
}
result: 
num:0, byte1:59, byte2:59
num:1, byte1:3c, byte2:3c
num:2, byte1:5c, byte2:52
num:3, byte1:52, byte2:18

In vlang, the results of the two methods are different. In str.bytes(), 5c is missing

Reproduction Steps

module main

fn main(){
    b1 := [u8(0x59),0x3c,0x5c,0x52,0x18]
    b2 := '\x59\x3c\x5c\x52\x18'.bytes()

    for i := 0; i < b2.len; i++ {
        println('num:${i}, byte1:${b1[i].hex()}, byte2:${b2[i].hex()}')
    }
}

Possible Solution

No response

Additional Information/Context

result: 
num:0, byte1:59, byte2:59
num:1, byte1:3c, byte2:3c
num:2, byte1:5c, byte2:52
num:3, byte1:52, byte2:18

V version

V 0.3.4 6698fe4

Environment details (OS name and version, etc.)

V full version: V 0.3.4 c4b34c9.6698fe4 OS: windows, Microsoft Windows 11 Home China v22621 64-bit Processor: 16 cpus, 64bit, little endian,

getwd: C:\Users\V vexe: C:\Software\v\v.exe vexe mtime: 2023-05-23 13:49:56

vroot: OK, value: C:\Software\v VMODULES: OK, value: C:\Users\V.vmodules VTMP: OK, value: C:\Users\V\AppData\Local\Temp\v_0

Git version: git version 2.33.0.windows.2 Git vroot status: weekly.2023.15-174-g6698fe4f .git/config present: true

CC version: Error: exec failed (CreateProcess) with code 2: 系统找不到指定的文件。 cmd: cc --version thirdparty/tcc status: thirdparty-windows-amd64 e90c2620

kbkpbot commented 1 year ago

'\x59\x3c\x5c\x52\x18' was transferred to "Y<\R\030" in C , so the \x5c => \ in the string. It is treated as a escape control char.

Vsirer commented 1 year ago

'\x59\x3c\x5c\x52\x18' was transferred to "Y<\R\030" in C , so the \x5c => \ in the string. It is treated as a escape control char.

So is this a normal result?

kbkpbot commented 1 year ago

My suggestion is not to use string store binary data.