Skip to content

Commit 4d68d93

Browse files
committed
Make LazyString mutably cache its printed value
and implement more of the string interface.
1 parent 1da5d4e commit 4d68d93

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

base/strings/lazy.jl

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ of functions).
99
This type is designed to be cheap to construct at runtime, trying to offload
1010
as much work as possible to either the macro or later printing operations.
1111
"""
12-
struct LazyString <: AbstractString
12+
mutable struct LazyString <: AbstractString
1313
parts::Tuple
14+
# Created on first access
15+
str::String
1416
LazyString(args...) = new(args)
1517
end
1618

@@ -28,8 +30,21 @@ macro lazy_str(text)
2830
:(LazyString($(parts...)))
2931
end
3032

31-
function print(io::IO, s::LazyString)
32-
for part in s.parts
33-
print(io, part)
33+
function String(l::LazyString)
34+
if !isdefined(l, :str)
35+
l.str = sprint() do io
36+
for p in l.parts
37+
print(io, p)
38+
end
39+
end
3440
end
41+
return l.str
3542
end
43+
44+
hash(s::LazyString, args...) = hash(String(s), args...)
45+
lastindex(s::LazyString) = lastindex(String(s))
46+
iterate(s::LazyString) = iterate(String(s))
47+
iterate(s::LazyString, i::Integer) = iterate(String(s), i)
48+
isequal(a::LazyString, b::LazyString) = isequal(String(a), String(b))
49+
==(a::LazyString, b::LazyString) = (String(a) == String(b))
50+
ncodeunits(s::LazyString) = ncodeunits(String(s))

0 commit comments

Comments
 (0)