Skip to content

Add truncate_at_null parameter to String.new(Bytes) and .from_utf16#15887

Merged
straight-shoota merged 2 commits intocrystal-lang:masterfrom
HertzDevil:feature/string-slice-null-terminated
Jun 11, 2025
Merged

Add truncate_at_null parameter to String.new(Bytes) and .from_utf16#15887
straight-shoota merged 2 commits intocrystal-lang:masterfrom
HertzDevil:feature/string-slice-null-terminated

Conversation

@HertzDevil
Copy link
Contributor

It is common to find C strings in StaticArrays or Slices that are null-terminated, but may also take up the entire slice if its size is equal to the slice's size. In this case String.new(UInt8*) is unsafe, whereas String.new(Bytes) followed by rstrip('\0') is not very efficient. This PR allows the Bytes constructor to stop as soon as it encounters a null character.

LibC::SockaddrUn#sun_path is not necessarily null-terminated in practice, according to https://man7.org/linux/man-pages/man7/unix.7.html. LibC::Dirent#d_name is always null-terminated (in fact, it is declared as a variable-length array on Solaris).

There are probably more places where this is applicable to Win32 code than the ones included here.

@straight-shoota
Copy link
Member

This looks good, but I'm wondering about naming. Intuitively, I'd understand null_terminated : Bool to indicate whether the source is null delimited or not. But that's not exactly what it does.
Perhaps truncate_at_null would be a bit more clear about the intention?

@HertzDevil HertzDevil changed the title Add null_terminated parameter to String.new(Bytes) and .from_utf16 Add truncate_at_null parameter to String.new(Bytes) and .from_utf16 Jun 10, 2025
@straight-shoota straight-shoota added this to the 1.17.0 milestone Jun 10, 2025
@straight-shoota straight-shoota merged commit bff5068 into crystal-lang:master Jun 11, 2025
37 checks passed
@HertzDevil HertzDevil deleted the feature/string-slice-null-terminated branch June 12, 2025 16:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants