Skip to content

Commit

Permalink
add overload add(a: var string, b: openArray[char])
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Nov 13, 2020
1 parent d0c4c73 commit 47773e9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

- `doAssertRaises` now correctly handles foreign exceptions.

- Added overload `ssytem.add(a: var string, b: openArray[char])`

## Language changes

- `nimscript` now handles `except Exception as e`
Expand Down
12 changes: 12 additions & 0 deletions lib/system.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,18 @@ proc add*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
## tmp.add("cd")
## assert(tmp == "abcd")

proc add*(x: var string, y: openArray[char]) =
## Concatenates `x` and `y` in place. `y` must not overlap with `x` to
## allow future memcpy optimizations.
let n = x.len
x.setLen n + y.len
# pending https://github.com/nim-lang/Nim/issues/14655#issuecomment-643671397
# use x.setLen(n + y.len, isInit = false)
var i=0
while i<y.len:
x[n + i] = y[i]
i.inc
# xxx use `nimCopyMem(x[n].addr, y[0].addr, y.len)` after some refactoring

type
Endianness* = enum ## Type describing the endianness of a processor.
Expand Down
15 changes: 14 additions & 1 deletion tests/vm/tstring_openarray.nim
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ proc set_all[T](s: var openArray[T]; val: T) =
s[i] = val

proc test() =
block:
var a0 = "hello_world"
var a1 = [1,2,3,4,5,6,7,8,9]
var a2 = @[1,2,3,4,5,6,7,8,9]
Expand All @@ -22,6 +23,18 @@ proc test() =
doAssert a0 == "iiiiiiiiiii"
doAssert a1 == [4,4,4,4,4,4,4,4,4]
doAssert a2 == @[4,4,4,4,4,4,4,4,4]
block:
var a0 = "hi"
var b0 = "foobar"
when nimvm:
discard # otherwise hits: bug #15952
else:
a0.add b0.toOpenArray(1,3)
doAssert a0 == "hioob"
proc fn(c: openArray[char]): string =
result.add c
doAssert fn("def") == "def"
doAssert fn(['d','\0', 'f'])[2] == 'f'

const constval0 = "hello".map(proc(x: char): char = x)
const constval1 = [1,2,3,4].map(proc(x: int): int = x)
Expand All @@ -31,4 +44,4 @@ doAssert([1,2,3,4].map(proc(x: int): int = x) == constval1)

test()
static:
test()
test()

0 comments on commit 47773e9

Please sign in to comment.