Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions stack_strings.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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.}
Expand Down Expand Up @@ -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].} =
Expand Down Expand Up @@ -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.} =
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.} =
Expand Down