Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StringPool as a collection #14507

Open
HertzDevil opened this issue Apr 18, 2024 · 3 comments
Open

StringPool as a collection #14507

HertzDevil opened this issue Apr 18, 2024 · 3 comments

Comments

@HertzDevil
Copy link
Contributor

StringPool is often used to reduce string memory consumption when one has a byte buffer to begin with, but conceptually it is quite similar to a Set(String). That means operations on collections like #count and #join should also make sense on a StringPool. So I wonder if it would be a good idea for StringPool to include Enumerable:

class StringPool
  include Enumerable(String)

  def each(& : String ->) : Nil
    @capacity.times do |i|
      unless @hashes[i] == 0
        yield @values[i]
      end
    end
  end

  # array-like literal support
  def <<(str : String | Bytes | IO::Memory) : self
    get(str)
    self
  end
end

StringPool{"foo", "bar", "baz"}.count(&.starts_with?("ba")) # => 2
@straight-shoota
Copy link
Member

What would be a use case for this though? I don't think it's really necessary for the purpose of deduplication.

@ysbaddaden
Copy link
Contributor

With #get? it will be useful to create a StringPool with a set of known keys, and doing so in idiomatic crystal sounds good.

known_keys = StringPool{"foo", "bar"}
known_keys << "baz"

@HertzDevil
Copy link
Contributor Author

I don't think that depends on #get?; it works directly with #get (otherwise nothing gets inserted), and doesn't even require StringPool to be an Enumerable, as long as a compatible #<< exists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants