nim-stack-strings icon indicating copy to clipboard operation
nim-stack-strings copied to clipboard

Customizable `lenInternal`?

Open elcritch opened this issue 8 months ago • 5 comments

Thanks for the library! What do you think about making lenInternal customizable to different int types? Alternatively the smallest lenInternal size could be figured out at compile time.

I've been using it more lately for UI and CSS libraries only need ~60 letters for strings. That means Natural is as large as the text itself on a 64bit platform. :/

One way to do it automatically might be like:

type StackString*[Size: static Natural] = object
  ## A stack-allocated string with a fixed capacity
  when Size <= uint8.high():
    lenInternal: uint8
  elif Size <= uint16.high():
    lenInternal: uint16
  elif Size <= uint32.high():
    lenInternal: uint32
  elif Size <= uint64.high():
    lenInternal: uint64
  else:
    {.error: "size is too large to be stored: " & $Size.}

elcritch avatar Apr 13 '25 07:04 elcritch

I'm glad my library has been useful to you.

I'd rather make the type of Size a generic parameter itself if possible as opposed to the code snippet, since platform ints tend to be faster and easier to work with. If you'd like to take a crack at it and open a PR, I'd be willing to merge it if it passes tests.

We'd probably need tests to handle cases where the string is longer than what Size can represent as well.

termermc avatar Apr 14 '25 09:04 termermc

I'd rather make the type of Size a generic parameter itself if possible as opposed to the code snippet, since platform ints tend to be faster and easier to work with.

That'd work for me as well. Actually it was my first though but it's more intrusive to the APIs.

If you'd like to take a crack at it and open a PR, I'd be willing to merge it if it passes tests.

Great, I'll take a crack at it.

We'd probably need tests to handle cases where the string is longer than what Size can represent as well.

It could be a compile time error, then you don't have to worry about runtime detection. Then the test would just be "can't compile".

elcritch avatar Apr 17 '25 06:04 elcritch

Sounds good. I like the idea of it being completely compile time.

termermc avatar Apr 17 '25 17:04 termermc

I made a PR where the lenInternal type is a generic parameter: https://github.com/termermc/nim-stack-strings/pull/10

Since it's easy I also made a PR that uses the minimum int size possible with an optional override flag: https://github.com/termermc/nim-stack-strings/pull/11

elcritch avatar May 03 '25 03:05 elcritch

It turns out my time is way more divided than I thought it was. Would you be interested in becoming a maintainer?

termermc avatar Jul 23 '25 00:07 termermc