Skip to content

Commit

Permalink
Introduce AnnotatedIOBuffer
Browse files Browse the repository at this point in the history
This allows for styled content to be constructed incrementally, without
resorting to repeated concatenation. It operates very similarly to
IOContext, just with a special `write` method and specifically wrapping
an IOBuffer.
  • Loading branch information
tecosaur committed Oct 26, 2023
1 parent b5a531a commit 75f4654
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions base/strings/annotated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,47 @@ annotations(s::SubString{<:AnnotatedString}, pos::UnitRange{<:Integer}) =
Get all annotations of `chr`.
"""
annotations(c::AnnotatedChar) = c.annotations

## AnnotatedIOBuffer

struct AnnotatedIOBuffer <: IO
io::IOBuffer
annotations::Vector{Tuple{UnitRange{Int}, Pair{Symbol, Any}}}
end

AnnotatedIOBuffer(io::IOBuffer) = AnnotatedIOBuffer(io, Vector{Tuple{UnitRange{Int}, Pair{Symbol, Any}}}())
AnnotatedIOBuffer() = AnnotatedIOBuffer(IOBuffer())

function show(io::IO, annio::AnnotatedIOBuffer)
show(io, AnnotatedIOBuffer)
print(io, '(', annio.io.size, " bytes)")
end

position(io::AnnotatedIOBuffer) = position(io.io)
lock(io::AnnotatedIOBuffer) = lock(io.io)
unlock(io::AnnotatedIOBuffer) = unlock(io.io)

function write(io::AnnotatedIOBuffer, astr::Union{AnnotatedString, SubString{<:AnnotatedString}})
astr = AnnotatedString(astr)
offset = position(io.io)
for (region, annot) in astr.annotations
start, stop = first(region), last(region)
push!(io.annotations, (start+offset:stop+offset, annot))
end
write(io.io, astr)
end
write(io::AnnotatedIOBuffer, achr::AnnotatedChar) = write(io, AnnotatedString(achr))
write(io::AnnotatedIOBuffer, x::AbstractString) = write(io.io, x)
write(io::AnnotatedIOBuffer, s::Union{SubString{String}, String}) = write(io.io, x)
write(io::AnnotatedIOBuffer, x::UInt8) = write(io.io, x)

function take!(aiob::AnnotatedIOBuffer)
str = String(take!(aiob.io))
annot = copy(aiob.annotations)
empty!(aiob.annotations)
seekstart(aiob.io)
str, annot
end

AnnotatedString((str, annots)::Tuple{<:AbstractString, Vector{Tuple{UnitRange{Int}, Pair{Symbol, Any}}}}) =
AnnotatedString(str, annots)

0 comments on commit 75f4654

Please sign in to comment.