|
| 1 | +# https://github.com/mkitti/StaticStrings.jl |
| 2 | +# https://github.com/JuliaPy/PythonCall.jl/blob/main/src/Utils/Utils.jl |
| 3 | + |
| 4 | +struct StaticString{N, T} <: AbstractString |
| 5 | + codeunits::NTuple{N, T} |
| 6 | + StaticString{N, T}(codeunits::NTuple{N, T}) where {N, T} = new{N, T}(codeunits) |
| 7 | +end |
| 8 | + |
| 9 | +function Base.iterate(x::StaticString{N, UInt8}, i::Int = 1) where {N} |
| 10 | + i > N && return |
| 11 | + cs = x.codeunits |
| 12 | + c = @inbounds cs[i] |
| 13 | + if all(iszero, (cs[j] for j in i:N)) |
| 14 | + return |
| 15 | + elseif (c & 0x80) == 0x00 |
| 16 | + return (reinterpret(Char, UInt32(c) << 24), i + 1) |
| 17 | + elseif (c & 0x40) == 0x00 |
| 18 | + nothing |
| 19 | + elseif (c & 0x20) == 0x00 |
| 20 | + if @inbounds (i ≤ N - 1) && ((cs[i + 1] & 0xC0) == 0x80) |
| 21 | + return ( |
| 22 | + reinterpret(Char, (UInt32(cs[i]) << 24) | (UInt32(cs[i + 1]) << 16)), |
| 23 | + i + 2, |
| 24 | + ) |
| 25 | + end |
| 26 | + elseif (c & 0x10) == 0x00 |
| 27 | + if @inbounds (i ≤ N - 2) && ((cs[i + 1] & 0xC0) == 0x80) && ((cs[i + 2] & 0xC0) == 0x80) |
| 28 | + return ( |
| 29 | + reinterpret( |
| 30 | + Char, |
| 31 | + (UInt32(cs[i]) << 24) | |
| 32 | + (UInt32(cs[i + 1]) << 16) | |
| 33 | + (UInt32(cs[i + 2]) << 8), |
| 34 | + ), |
| 35 | + i + 3, |
| 36 | + ) |
| 37 | + end |
| 38 | + elseif (c & 0x08) == 0x00 |
| 39 | + if @inbounds (i ≤ N - 3) && |
| 40 | + ((cs[i + 1] & 0xC0) == 0x80) && |
| 41 | + ((cs[i + 2] & 0xC0) == 0x80) && |
| 42 | + ((cs[i + 3] & 0xC0) == 0x80) |
| 43 | + return ( |
| 44 | + reinterpret( |
| 45 | + Char, |
| 46 | + (UInt32(cs[i]) << 24) | |
| 47 | + (UInt32(cs[i + 1]) << 16) | |
| 48 | + (UInt32(cs[i + 2]) << 8) | |
| 49 | + UInt32(cs[i + 3]), |
| 50 | + ), |
| 51 | + i + 4, |
| 52 | + ) |
| 53 | + end |
| 54 | + end |
| 55 | + throw(StringIndexError(x, i)) |
| 56 | +end |
| 57 | + |
| 58 | +function Base.String(x::StaticString{N, T}) where {N, T} |
| 59 | + b = Base.StringVector(N) |
| 60 | + return String(b .= x.codeunits) |
| 61 | +end |
0 commit comments