From 5ba19c15e522d48ac4a2a712ea270995b92c396e Mon Sep 17 00:00:00 2001 From: Timothy Date: Mon, 22 Jul 2024 18:54:37 +0800 Subject: [PATCH] Fix potential underrun with annotation merging (#54917) Fixes #54860, see the commit message for more details. The added test serves as a MWE of the original bug report. (cherry picked from commit e621c74d52e095d740cede89e4e9da82d4f737a9) --- base/strings/annotated.jl | 1 + test/strings/annotated.jl | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/base/strings/annotated.jl b/base/strings/annotated.jl index 4f2caa107b5f1..69b04202edbf6 100644 --- a/base/strings/annotated.jl +++ b/base/strings/annotated.jl @@ -593,6 +593,7 @@ function _insert_annotations!(io::AnnotatedIOBuffer, annotations::Vector{Tuple{U for i in reverse(axes(annotations, 1)) annot = annotations[i] first(first(annot)) == 1 || continue + i <= length(io.annotations) || continue if last(annot) == last(last(io.annotations)) valid_run = true for runlen in 1:i diff --git a/test/strings/annotated.jl b/test/strings/annotated.jl index 222d9addc910c..944608fa8c4a9 100644 --- a/test/strings/annotated.jl +++ b/test/strings/annotated.jl @@ -215,6 +215,12 @@ end @test write(aio2, Base.AnnotatedChar('c', [:b => 2, :c => 3, :d => 4])) == 1 @test Base.annotations(aio2) == [(1:2, :a => 1), (1:3, :b => 2), (3:3, :c => 3), (3:3, :d => 4)] end + let aio2 = Base.AnnotatedIOBuffer() + @test write(aio2, Base.AnnotatedChar('a', [:b => 1])) == 1 + @test write(aio2, Base.AnnotatedChar('b', [:a => 1, :b => 1])) == 1 + @test read(seekstart(aio2), Base.AnnotatedString) == + Base.AnnotatedString("ab", [(1:1, :b => 1), (2:2, :a => 1), (2:2, :b => 1)]) + end # Working through an IOContext aio = Base.AnnotatedIOBuffer() wrapio = IOContext(aio)