Skip to content

Commit

Permalink
AnnotatedString support
Browse files Browse the repository at this point in the history
  • Loading branch information
aplavin committed Dec 5, 2024
1 parent 171d06a commit c0c33ff
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/functionlenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,12 @@ function set(s::AbstractString, o::Base.Fix2{typeof(split), <:Union{AbstractChar
any(c -> occursin(o.x, c), v) && throw(ArgumentError("split components cannot contain the delimiter $(repr(o.x))"))
join(v, o.x)
end

if isdefined(Base, :AnnotatedString)
# 1.11+
using Base: AnnotatedString, annotations
set(s::AbstractString, ::typeof(annotations), anns) = AnnotatedString(s, anns)
set(s::AnnotatedString, ::typeof(annotations), anns) = AnnotatedString(s.string, anns)
delete(s::AnnotatedString, ::typeof(annotations)) = s.string
insert(s::AbstractString, ::typeof(annotations), anns) = AnnotatedString(s, anns)
end
21 changes: 21 additions & 0 deletions test/test_functionlenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,27 @@ end
@test_throws ArgumentError set(" abc def ", @optic(split(_, ' ')), [" ", "y"])
end

VERSION v"1.11" && @testset "AnnotatedStrings" begin
using Base: AnnotatedChar, AnnotatedString, annotations

s = Base.AnnotatedString("good bad", [(region=1:4, label=:sentiment, value=+1), (region=6:8, label=:sentiment, value=-1)])

@test (@delete annotations(s))::String == "good bad"

snew = @delete annotations(s)[2]
@test String(snew) == "good bad"
@test annotations(snew) == [(region=1:4, label=:sentiment, value=+1)]

snew = (@set Base.annotations(s)[1].region = 2:6)
@test String(snew) == "good bad"
@test annotations(snew) == [(region=2:6, label=:sentiment, value=+1), (region=6:8, label=:sentiment, value=-1)]

test_getset_laws((@o annotations(_)[2].region), s, 5:5, 1:3)
test_getset_laws((@o annotations(_)[2].label), s, :abc, :def)
test_getset_laws((@o annotations(_)[2].value), s, "sad", +2)
test_insertdelete_laws((@o annotations(_)[2]), s, (region=2:2, label=:mylabel, value=+1))
end

@testset "custom binary function" begin
(x, y) = x - y
Accessors.set(x, f::Base.Fix1{typeof(↑)}, y) = f.x - y
Expand Down

0 comments on commit c0c33ff

Please sign in to comment.