Merge pull request #9 from jangko/concat_operation

fixes #8, add concat operation
This commit is contained in:
Yuriy Glukhov 2018-06-12 12:19:33 +03:00 committed by GitHub
commit 3435dc1155
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 1 deletions

View File

@ -1,4 +1,4 @@
import ./ptr_arith
import ./ptr_arith, typetraits
const rangesGCHoldEnabled = not defined(rangesDisableGCHold)
const unsafeAPIEnabled = defined(rangesEnableUnsafeAPI)
@ -145,3 +145,32 @@ proc `[]=`*[T, U, V](r: MutRange[T], s: HSlice[U, V], v: Range[T]) {.inline.} =
r[s] = toOpenArray(v)
proc baseAddr*[T](r: Range[T]): ptr T {.inline.} = r.start
template toRange*[T](a: Range[T]): Range[T] = a
# this preferred syntax doesn't work
# see https://github.com/nim-lang/Nim/issues/7995
#template copyRange[T](dest: seq[T], destOffset: int, src: Range[T]) =
# when supportsCopyMem(T):
template copyRange[T](E: typedesc, dest: seq[T], destOffset: int, src: Range[T]) =
when supportsCopyMem(E):
if dest.len != 0 and src.len != 0:
copyMem(dest[destOffset].unsafeAddr, src.start, sizeof(T) * src.len)
else:
for i in 0..<src.len:
dest[i + destOffset] = src[i]
proc concat*[T](v: varargs[Range[T], toRange]): seq[T] =
var len = 0
for c in v: inc(len, c.len)
result = newSeq[T](len)
len = 0
for c in v:
copyRange(T, result, len, c)
inc(len, c.len)
proc `&`*[T](a, b: Range[T]): seq[T] =
result = newSeq[T](a.len + b.len)
copyRange(T, result, 0, a)
copyRange(T, result, a.len, b)

View File

@ -26,3 +26,40 @@ suite "Typed ranges":
var z = toRange(@[1, 2, 3, 4])
check y == z
check x != z
test "concat operation":
var a = toRange(@[1,2,3])
var b = toRange(@[4,5,6])
var c = toRange(@[7,8,9])
var d = @[1,2,3,4,5,6,7,8,9]
var e = @[1,2,3,4,5,6]
var f = @[4,5,6,7,8,9]
var x = concat(a, b, c)
var y = a & b
check x == d
check y == e
var z = concat(b, @[7,8,9])
check z == f
let u = toRange(newSeq[int](0))
let v = toRange(@[3])
check concat(u, v) == @[3]
check (v & u) == @[3]
test "complex types concat operation":
type
Jaeger = object
name: string
weight: int
var A = Jaeger(name: "Gipsy Avenger", weight: 2004)
var B = Jaeger(name: "Striker Eureka", weight: 1850)
var C = Jaeger(name: "Saber Athena", weight: 1628)
var D = Jaeger(name: "Cherno Alpha", weight: 2412)
var k = toRange(@[A, B])
var m = toRange(@[C, D])
var n = concat(k, m)
check n == @[A, B, C ,D]
check n != @[A, B, C ,C]