diff --git a/stack_strings.nim b/stack_strings.nim index 6fbd511..3b8efbd 100644 --- a/stack_strings.nim +++ b/stack_strings.nim @@ -151,10 +151,22 @@ template raiseInsufficientCapacityDefect(msg: string, capacity: Natural, request raise newInsufficientCapacityDefect(msg, capacity, requestedCapacity) +template minLenInternal(size: static Natural): auto = + when defined(stackStringsUseInt): + int + elif size < 127: + int8 + elif size < 32767: + int16 + elif size < 2147483647: + int32 + else: + int64 + type StackString*[Size: static Natural] = object ## A stack-allocated string with a fixed capacity - lenInternal: Natural + lenInternal: minLenInternal(Size) ## The current string length data*: array[Size + 1, char] @@ -557,7 +569,7 @@ proc unsafeAdd*(this: var StackString, strOrChar: auto) {.inline.} = for i in this.len ..< newLen: this.data[i] = strOrChar[i - this.len] - this.lenInternal = newLen + this.lenInternal = typeof(this.lenInternal)(newLen) {.boundChecks: on.} {.boundChecks: off.} @@ -636,7 +648,7 @@ proc addTruncate*(this: var StackString, strOrChar: auto): bool {.inline, discar for i in this.len ..< newLen: this.data[i] = strOrChar[i - this.len] - this.lenInternal = newLen + this.lenInternal = typeof(this.lenInternal)(newLen) {.boundChecks: on.} proc add*(this: var StackString, strOrChar: auto) {.inline, raises: [InsufficientCapacityDefect].} = @@ -692,7 +704,7 @@ proc unsafeSetLen*(this: var StackString, newLen: Natural | BackwardsIndex, writ for i in lenRes ..< this.len: this.data[i] = '\x00' - this.lenInternal = lenRes + this.lenInternal = typeof(this.lenInternal)(lenRes) {.boundChecks: on.} proc trySetLen*(this: var StackString, newLen: Natural | BackwardsIndex, writeZerosOnTruncate: bool = true): bool {.inline.} = @@ -852,7 +864,7 @@ template toCstring*(this: StackString): cstring = when NimMajor > 1: ## Nim 2.0 no longer requires `unsafeaddr` cast[cstring](addr this.data[0]) else: - cast[cstring](unsafeaddr this.data[0]) + cast[cstring](unsafeAddr this.data[0]) proc toHeapCstring*(this: StackString): cstring {.inline.} = ## Allocates a `cstring` on the heap and copies the contents of the [StackString] into it. @@ -881,7 +893,7 @@ proc toHeapCstring*(this: StackString): cstring {.inline.} = when NimMajor > 1: ## Nim 2.0 no longer requires `unsafeaddr` moveMem(result, addr this.data[0], len) else: - moveMem(result, unsafeaddr this.data[0], len) + moveMem(result, unsafeAddr this.data[0], len) result[len] = '\x00' proc unsafeToStackString*(content: IndexableChars, size: static Natural): StackString[size] {.inline.} =