Skip to content

Commit

Permalink
Regex support
Browse files Browse the repository at this point in the history
  • Loading branch information
ancapdev committed Jul 10, 2024
1 parent fe7d01b commit b6175d2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/representations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 12 additions & 0 deletions test/representation_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit b6175d2

Please sign in to comment.