Skip to content

Instantly share code, notes, and snippets.

@SimonDanisch
Created November 2, 2017 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimonDanisch/02e74622e0577f199c1b1a8a65390c24 to your computer and use it in GitHub Desktop.
Save SimonDanisch/02e74622e0577f199c1b1a8a65390c24 to your computer and use it in GitHub Desktop.
struct FixedString{N} # Size is a static type parameter
length::UInt32
data::NTuple{N, UInt8} # Immutable statically sized tuple
end
function Base.:(==)(a::FixedString, b::FixedString)
a.length == b.length || return false
for i in 1:a.length
a.data[i] == b.data[i] || return false
end
return true
end
# some constructors
function Base.convert(::Type{FixedString{N}}, x::String) where N
FixedString(
length(x),
ntuple(Val{N}) do i
UInt8(i <= length(x) ? x[i] : 0)
end
)
end
Base.convert(::Type{String}, x::FixedString) =
String([x.data[1:x.length]...])
Base.show(io::IO, x::FixedString) = show(io, String(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment