tcstring.nim 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. discard """
  2. targets: "c cpp js"
  3. matrix: "--gc:refc; --gc:arc"
  4. """
  5. from std/sugar import collect
  6. from stdtest/testutils import whenRuntimeJs, whenVMorJs
  7. import std/assertions
  8. template testMitems() =
  9. block:
  10. var a = "abc"
  11. var b = a.cstring
  12. let s = collect:
  13. for bi in mitems(b):
  14. if bi == 'b': bi = 'B'
  15. bi
  16. whenRuntimeJs:
  17. discard # xxx mitems should give CT error instead of @['\x00', '\x00', '\x00']
  18. do:
  19. doAssert s == @['a', 'B', 'c']
  20. block:
  21. var a = "abc\0def"
  22. var b = a.cstring
  23. let s = collect:
  24. for bi in mitems(b):
  25. if bi == 'b': bi = 'B'
  26. bi
  27. whenRuntimeJs:
  28. discard # ditto
  29. do:
  30. doAssert s == @['a', 'B', 'c']
  31. proc mainProc() =
  32. testMitems()
  33. template main() =
  34. block: # bug #13859
  35. let str = "abc".cstring
  36. doAssert len(str).int8 == 3
  37. doAssert len(str).int16 == 3
  38. doAssert len(str).int32 == 3
  39. var str2 = "cde".cstring
  40. doAssert len(str2).int8 == 3
  41. doAssert len(str2).int16 == 3
  42. doAssert len(str2).int32 == 3
  43. const str3 = "abc".cstring
  44. doAssert len(str3).int32 == 3
  45. doAssert len("abc".cstring).int16 == 3
  46. doAssert len("abc".cstring).float32 == 3.0
  47. block: # bug #17159
  48. block:
  49. var a = "abc"
  50. var b = a.cstring
  51. doAssert $(b, ) == """("abc",)"""
  52. let s = collect:
  53. for bi in b: bi
  54. doAssert s == @['a', 'b', 'c']
  55. block:
  56. var a = "abc\0def"
  57. var b = a.cstring
  58. let s = collect:
  59. for bi in b: bi
  60. whenRuntimeJs:
  61. doAssert $(b, ) == """("abc\x00def",)"""
  62. doAssert s == @['a', 'b', 'c', '\x00', 'd', 'e', 'f']
  63. do:
  64. doAssert $(b, ) == """("abc",)"""
  65. doAssert s == @['a', 'b', 'c']
  66. block:
  67. when defined(gcArc): # xxx SIGBUS
  68. discard
  69. else:
  70. mainProc()
  71. when false: # xxx bug vm: Error: unhandled exception: 'node' is not accessible using discriminant 'kind' of type 'TFullReg' [FieldDefect]
  72. testMitems()
  73. block: # bug #13321: [codegen] --gc:arc does not properly emit cstring, results in SIGSEGV
  74. let a = "hello".cstring
  75. doAssert $a == "hello"
  76. doAssert $a[0] == "h"
  77. doAssert $a[4] == "o"
  78. whenVMorJs: discard # xxx this should work in vm, refs https://github.com/timotheecour/Nim/issues/619
  79. do:
  80. doAssert a[a.len] == '\0'
  81. static: main()
  82. main()