Skip to content

Commit

Permalink
Add string macros (#47)
Browse files Browse the repository at this point in the history
* Add string macros

* Lower case the macros, do construction during parsing

* Create individual macros for each size

* Reduce code, string macro suffix
  • Loading branch information
mkitti committed Oct 18, 2022
1 parent 788df4d commit b9c58bb
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/InlineStrings.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Base: ==
using Parsers

export InlineString, InlineStringType, inlinestrings
export @inline_str

"""
InlineString
Expand All @@ -23,6 +24,8 @@ abstract type InlineString <: AbstractString end
for sz in (1, 4, 8, 16, 32, 64, 128, 256)
nm = Symbol(:String, max(1, sz - 1))
nma = Symbol(:InlineString, max(1, sz - 1))
macro_nm = Symbol(:inline, max(1, sz - 1), :_str)
at_macro_nm = Symbol("@", macro_nm)
@eval begin
"""
$($nm)(str::AbstractString)
Expand Down Expand Up @@ -55,6 +58,18 @@ for sz in (1, 4, 8, 16, 32, 64, 128, 256)
const $nma = $nm
export $nm
export $nma

"""
inline$($(max(1, sz - 1)))"string"
Macro to create a [`$($nm)`](@ref) with a fixed size of $($sz) bytes.
"""
macro $macro_nm(ex)
T = InlineStringType($(max(1,sz - 1)))
T(unescape_string(ex))
end

export $at_macro_nm
end
end

Expand Down Expand Up @@ -277,6 +292,16 @@ end
InlineString(x::InlineString) = x
InlineString(x::AbstractString)::InlineStringTypes = (InlineStringType(ncodeunits(x)))(x)

"""
inline"string"
Macro to create an [`InlineString`](@ref).
"""
macro inline_str(ex)
InlineString(unescape_string(ex))
end


(==)(x::T, y::T) where {T <: InlineString} = Base.eq_int(x, y)
function ==(x::String, y::T) where {T <: InlineString}
sizeof(x) == sizeof(y) || return false
Expand Down
14 changes: 14 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,17 @@ end
@test InlineString(x) == String(x)
end
end

@testset "macros" begin
x = inline"This is a macro test"
@test String(x) == "This is a macro test"
@test typeof(x) == String31
@test typeof(inline1"a") == String1
@test typeof(inline3"a") == String3
@test typeof(inline7"a") == String7
@test typeof(inline15"a") == String15
@test typeof(inline31"a") == String31
@test typeof(inline63"a") == String63
@test typeof(inline127"a") == String127
@test typeof(inline255"a") == String255
end

0 comments on commit b9c58bb

Please sign in to comment.