summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorTimothee Cour <timothee.cour2@gmail.com>2021-01-11 01:16:20 -0800
committerGitHub <noreply@github.com>2021-01-11 10:16:20 +0100
commitf6c2450cdb7e24b5dbd118494560cc8452dd3688 (patch)
tree9c4f53378d6f32eb7e7485d3772ad21262144f1a /lib
parent0286a0879bc44e5267a5fd36e6f4aac8f78713ea (diff)
downloadNim-f6c2450cdb7e24b5dbd118494560cc8452dd3688.tar.gz
fix #16555, fixes #16405: len, high honors '\0' for cstring in vm (#16610)
Diffstat (limited to 'lib')
-rw-r--r--lib/system.nim20
1 files changed, 13 insertions, 7 deletions
diff --git a/lib/system.nim b/lib/system.nim
index e220ba7a3..25184eb15 100644
--- a/lib/system.nim
+++ b/lib/system.nim
@@ -701,18 +701,24 @@ proc len*(x: string): int {.magic: "LengthStr", noSideEffect.}
   ##   var str = "Hello world!"
   ##   echo len(str) # => 12
 
-proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.}
-  ## Returns the length of a compatible string. This is sometimes
-  ## an O(n) operation.
+proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.} =
+  ## Returns the length of a compatible string. This is an O(n) operation except
+  ## in js at runtime.
   ##
   ## **Note:** On the JS backend this currently counts UTF-16 code points
   ## instead of bytes at runtime (not at compile time). For now, if you
   ## need the byte length of the UTF-8 encoding, convert to string with
   ## `$` first then call `len`.
-  ##
-  ## .. code-block:: Nim
-  ##   var str: cstring = "Hello world!"
-  ##   len(str) # => 12
+  runnableExamples:
+    doAssert len(cstring"abc") == 3
+    doAssert len(cstring r"ab\0c") == 5 # \0 is escaped
+    doAssert len(cstring"ab\0c") == 5 # ditto
+    var a: cstring = "ab\0c"
+    when defined(js): doAssert a.len == 4 # len ignores \0 for js
+    else: doAssert a.len == 2 # \0 is a null terminator
+    static:
+      var a2: cstring = "ab\0c"
+      doAssert a2.len == 2 # \0 is a null terminator, even in js vm
 
 proc len*(x: (type array)|array): int {.magic: "LengthArray", noSideEffect.}
   ## Returns the length of an array or an array type.