Skip to content

Commit

Permalink
Add Pointer::Appender#to_slice (#14874)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Aug 19, 2024
1 parent a9e0457 commit 7427990
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 4 deletions.
14 changes: 14 additions & 0 deletions spec/std/pointer/appender_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,18 @@ describe Pointer::Appender do
end
appender.size.should eq 4
end

it "#to_slice" do
data = Slice(Int32).new(5)
appender = data.to_unsafe.appender
appender.to_slice.should eq Slice(Int32).new(0)
appender.to_slice.to_unsafe.should eq data.to_unsafe

4.times do |i|
appender << (i + 1) * 2
appender.to_slice.should eq data[0, i + 1]
end
appender.to_slice.should eq Slice[2, 4, 6, 8]
appender.to_slice.to_unsafe.should eq data.to_unsafe
end
end
2 changes: 1 addition & 1 deletion src/base64.cr
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ module Base64
buf = Pointer(UInt8).malloc(decode_size(slice.size))
appender = buf.appender
from_base64(slice) { |byte| appender << byte }
Slice.new(buf, appender.size.to_i32)
appender.to_slice
end

# Writes the base64-decoded version of *data* to *io*.
Expand Down
4 changes: 2 additions & 2 deletions src/crystal/system/print_error.cr
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ module Crystal::System
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]
print_error appender.to_slice
appender = utf8.to_unsafe.appender
end

Expand All @@ -33,7 +33,7 @@ module Crystal::System
end

if appender.size > 0
print_error utf8.to_slice[0...appender.size]
print_error appender.to_slice
end
end

Expand Down
2 changes: 1 addition & 1 deletion src/crystal/system/win32/file_descriptor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ private module ConsoleUtils
appender << byte
end
end
@@buffer = @@utf8_buffer[0, appender.size]
@@buffer = appender.to_slice
end

private def self.read_console(handle : LibC::HANDLE, slice : Slice(UInt16)) : Int32
Expand Down
14 changes: 14 additions & 0 deletions src/pointer.cr
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ struct Pointer(T)
def pointer
@pointer
end

# Creates a slice pointing at the values appended by this instance.
#
# ```
# slice = Slice(Int32).new(5)
# appender = slice.to_unsafe.appender
# appender << 1
# appender << 2
# appender << 3
# appender.to_slice # => Slice[1, 2, 3]
# ```
def to_slice : Slice(T)
@start.to_slice(size)
end
end

include Comparable(self)
Expand Down

0 comments on commit 7427990

Please sign in to comment.