Skip to content

Commit

Permalink
Make LazyString mutably cache its printed value
Browse files Browse the repository at this point in the history
and implement more of the string interface.
  • Loading branch information
Keno committed Jan 20, 2022
1 parent 1da5d4e commit 4d68d93
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions base/strings/lazy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ of functions).
This type is designed to be cheap to construct at runtime, trying to offload
as much work as possible to either the macro or later printing operations.
"""
struct LazyString <: AbstractString
mutable struct LazyString <: AbstractString
parts::Tuple
# Created on first access
str::String
LazyString(args...) = new(args)
end

Expand All @@ -28,8 +30,21 @@ macro lazy_str(text)
:(LazyString($(parts...)))
end

function print(io::IO, s::LazyString)
for part in s.parts
print(io, part)
function String(l::LazyString)
if !isdefined(l, :str)
l.str = sprint() do io
for p in l.parts
print(io, p)
end
end
end
return l.str
end

hash(s::LazyString, args...) = hash(String(s), args...)
lastindex(s::LazyString) = lastindex(String(s))
iterate(s::LazyString) = iterate(String(s))
iterate(s::LazyString, i::Integer) = iterate(String(s), i)
isequal(a::LazyString, b::LazyString) = isequal(String(a), String(b))
==(a::LazyString, b::LazyString) = (String(a) == String(b))
ncodeunits(s::LazyString) = ncodeunits(String(s))

0 comments on commit 4d68d93

Please sign in to comment.