Skip to content

Commit c79947c

Browse files
authored
Extend Base.tryparse (#112)
1 parent b7b7c8d commit c79947c

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

NEWS.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
# History of Measurements.jl
22

3-
## v2.7.0 (2021-??-??)
3+
## v2.7.0 (2021-12-28)
44

55
### New features
66

77
* Support hashing of `Measurement` objects
88
([#103](https://github.com/JuliaPhysics/Measurements.jl/issues/103),
99
[#104](https://github.com/JuliaPhysics/Measurements.jl/pull/104)).
10+
* New method `Base.tryparse(::Type{Measurement}, ::AbstractString)`
11+
([#110](https://github.com/JuliaPhysics/Measurements.jl/issues/110),
12+
[#112](https://github.com/JuliaPhysics/Measurements.jl/pull/112)).
1013

1114
### Deprecations
1215

src/parsing.jl

+8-2
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ julia> measurement("-1234e-1")
8383
"""
8484
measurement(str::AbstractString) = parse(Measurement{Float64}, str)
8585

86-
function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString}
86+
function Base.tryparse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString}
8787
m = match(rxp_error_with_parentheses, str)
8888
if m !== nothing # "123(45)e6"
8989
val_str::S, val_dec, err_str::S, err_dec_str, expn = m.captures
@@ -105,7 +105,7 @@ function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:
105105
val_str, err_str, val_dec, expn =
106106
m.captures[1], "0", nothing, nothing
107107
else
108-
throw(ArgumentError("cannot parse $(repr(str)) as Measurement{$T}"))
108+
return nothing
109109
end
110110
end
111111
end
@@ -127,3 +127,9 @@ function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:
127127
end
128128
return measurement(val, err)
129129
end
130+
131+
function Base.parse(::Type{Measurement{T}}, str::S) where {T<:AbstractFloat, S<:AbstractString}
132+
out = tryparse(Measurement{T}, str)
133+
out === nothing && throw(ArgumentError("cannot parse $(repr(str)) as Measurement{$T}"))
134+
return out
135+
end

0 commit comments

Comments
 (0)