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

Proposal: Pointer::Appender#to_slice #14797

Open
straight-shoota opened this issue Jul 7, 2024 · 0 comments
Open

Proposal: Pointer::Appender#to_slice #14797

straight-shoota opened this issue Jul 7, 2024 · 0 comments

Comments

@straight-shoota
Copy link
Member

When using a Pointer::Appender, somteimes you do not know how much data you're going to append beforehand (only an upper limit). But to continue, you need a slice of the appended data.

I'm proposing to add a method Pointer::Appender#to_slice for that. It returns a slice from the appender start and of the size of appended data. The implementation is trivial:

struct Pointer::Appender
    def to_slice : Slice(T)
      @start.to_slice(size)
    end
end

There are some use cases in stdlib, where such a method could replace the manual slice creation:

appender = utf8.to_unsafe.appender
String.each_utf16_char(bytes) do |char|
if appender.size > utf8.size - char.bytesize
# buffer is full (char won't fit)
print_error utf8.to_slice[0...appender.size]
appender = utf8.to_unsafe.appender
end
char.each_byte do |byte|
appender << byte
end
end
if appender.size > 0
print_error utf8.to_slice[0...appender.size]
end

appender = @@utf8_buffer.to_unsafe.appender
String.each_utf16_char(utf16_buffer.to_slice[..index]) do |char|
char.each_byte do |byte|
appender << byte
end
end
@@buffer = @@utf8_buffer[0, appender.size]

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

1 participant