diff --git a/stew/arrayops.nim b/stew/arrayops.nim index 94b78c0..0b6b4fb 100644 --- a/stew/arrayops.nim +++ b/stew/arrayops.nim @@ -46,7 +46,7 @@ func mnot*[N: static int; T](x: var array[N, T], y: array[N, T]) = eachElement(x, x, `not`) func copyFrom*[T]( - v: var openArray[T], src: openArray[T]): Natural {.raises: [Defect].} = + v: var openArray[T], src: openArray[T]): Natural = ## Copy `src` contents into `v` - this is a permissive assignment where `src` ## may contain both fewer and more elements than `v`. Returns the number of ## elements copied which may be less than N when `src` is shorter than v @@ -54,6 +54,13 @@ func copyFrom*[T]( assign(v.toOpenArray(0, elems - 1), src.toOpenArray(0, elems - 1)) elems +func initCopyFrom*[N: static[int], T]( + A: type array[N, T], src: openArray[T]): A = + ## Copy `src` contents into an array - this is a permissive copy where `src` + ## may contain both fewer and more elements than `N`. + let elems = min(N, src.len) + assign(result.toOpenArray(0, elems - 1), src.toOpenArray(0, elems - 1)) + func initArrayWith*[N: static[int], T](value: T): array[N, T] {.noinit, inline.}= result.fill(value) diff --git a/stew/endians2.nim b/stew/endians2.nim index d57b2bc..c9a3914 100644 --- a/stew/endians2.nim +++ b/stew/endians2.nim @@ -98,9 +98,11 @@ func toBytes*(x: SomeEndianInt, endian: Endianness = system.cpuEndian): if endian == system.cpuEndian: x else: swapBytes(x) - # Loop since vm can't copymem - let's hope optimizer is smart here :) - for i in 0..= sizeof(T), "Not enough bytes for endian conversion" -func fromBytesBE*( - T: typedesc[SomeEndianInt], - x: array[sizeof(T), byte]): T {.inline.} = - ## Read big endian bytes and convert to an integer. By default, native - ## endianness is used which is not portable! - fromBytes(T, x, bigEndian) + when nimvm: # No copyMem in vm + for i in 0..