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

Refactor String header layout reflection #13335

Merged
Show file tree
Hide file tree
Changes from 2 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
19 changes: 15 additions & 4 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ class String
TYPE_ID = "".crystal_type_id

# :nodoc:
HEADER_SIZE = sizeof({Int32, Int32, Int32})
#
# Holds the offset to the first character byte.
HEADER_SIZE = offsetof(String, @c)

include Comparable(self)

Expand Down Expand Up @@ -266,9 +268,18 @@ class String
str = GC.realloc(str, bytesize.to_u32 + HEADER_SIZE + 1)
end

str_header = str.as({Int32, Int32, Int32}*)
str_header.value = {TYPE_ID, bytesize.to_i, size.to_i}
str.as(String)
str.as(Pointer(typeof(TYPE_ID))).value = TYPE_ID
str = str.as(String)
str.initialize_header(bytesize.to_i, size.to_i)
str
end

# :nodoc:
#
# Initializes the header information of a `String` instance.
# The actual character content at `@c` is expected to be already filled and is
# unaffected by this method.
def initialize_header(@bytesize : Int32, @length : Int32 = 0)
end

# Builds a `String` by creating a `String::Builder` with the given initial capacity, yielding
Expand Down
8 changes: 4 additions & 4 deletions src/string/builder.cr
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ class String::Builder < IO
# Make sure to also be able to hold
# the header size plus the trailing zero byte
capacity += String::HEADER_SIZE + 1
String.check_capacity_in_bounds(capacity)

@buffer = GC.malloc_atomic(capacity.to_u32).as(UInt8*)
@bytesize = 0
Expand Down Expand Up @@ -117,9 +116,10 @@ class String::Builder < IO
resize_to_capacity(real_bytesize)
end

header = @buffer.as({Int32, Int32, Int32}*)
header.value = {String::TYPE_ID, @bytesize - 1, 0}
@buffer.as(String)
@buffer.as(Pointer(typeof(String::TYPE_ID))).value = String::TYPE_ID
str = @buffer.as(String)
str.initialize_header((bytesize - 1).to_i)
str
end

private def real_bytesize
Expand Down