From b6175d2a8b49a8d4c79d24143b3040736b63e571 Mon Sep 17 00:00:00 2001 From: Christian Rorvik Date: Wed, 10 Jul 2024 11:21:41 +0200 Subject: [PATCH] Regex support --- src/representations.jl | 19 +++++++++++++++++++ test/representation_tests.jl | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/representations.jl b/src/representations.jl index a1934bf..8a4d772 100644 --- a/src/representations.jl +++ b/src/representations.jl @@ -20,6 +20,25 @@ struct DefaultBSONConversions <: BSONConversionRules end @inline bson_representation_convert(::Type{Vector{UInt8}}, x::BSONBinary) = x.data @inline bson_representation_convert(::Type{BSONBinary}, x::Vector{UInt8}) = BSONBinary(x) +# NOTE: no public API for this, hopefully this doesn't break too often +function regex_opts_str_(x::Regex) + o1 = Base.regex_opts_str(x.compile_options & ~Base.DEFAULT_COMPILER_OPTS) + o2 = Base.regex_opts_str(x.match_options & ~Base.DEFAULT_MATCH_OPTS) + o1 * o2 +end +# Alternative implementation should the former start breaking +# function regex_opts_str_(r::Regex) +# s = string(r) +# s[findlast(x -> x == '"', s)+1:end] +# end + +@inline bson_representation_type(::Type{Regex}) = BSONRegex +@inline bson_representation_convert(::Type{Regex}, x::BSONRegex) = Regex(x.pattern, x.options) +@inline bson_representation_convert(::Type{BSONRegex}, x::Regex) = BSONRegex( + x.pattern, + regex_opts_str_(x) +) + @inline bson_representation_type(::Type{<:IPAddr}) = String @inline bson_representation_type(::Type{<:Sockets.InetAddr}) = String diff --git a/test/representation_tests.jl b/test/representation_tests.jl index 930d7ee..04e0226 100644 --- a/test/representation_tests.jl +++ b/test/representation_tests.jl @@ -96,4 +96,16 @@ end @test BSONReader(buf, StrictBSONValidator(), NumericBSONConversions())["x"][Float32] == x end +@testset "Regex" for x in [ + r"test", + r"test"i, + r"^foo$", +] + buf = empty!(fill(0xff, 1000)) + writer = BSONWriter(buf) + writer["x"] = x + close(writer) + @test BSONReader(buf, StrictBSONValidator())["x"][Regex] == x +end + end