From 79a265d3bf7d2728ed4f70f02e48b9d246d03f0c Mon Sep 17 00:00:00 2001 From: Rene Donner Date: Sun, 10 May 2015 21:49:04 +0200 Subject: [PATCH] add tryparse --- src/Compat.jl | 13 +++++++++++++ test/runtests.jl | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/src/Compat.jl b/src/Compat.jl index 43e681149630b..f2cac919b2943 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -290,6 +290,19 @@ if VERSION < v"0.4.0-dev+656" include("nullable.jl") end +if VERSION < v"0.4.0-dev+3864" + function tryparse(T::Type{Float32}, s) + r = Array(T,1) + float32_isvalid(s, r) ? Nullable(r[1]) : Nullable{Float32}() + end + + function tryparse(T::Type{Float64}, s) + r = Array(T,1) + float64_isvalid(s, r) ? Nullable(r[1]) : Nullable{Float64}() + end + export tryparse +end + if VERSION < v"0.4.0-dev+3844" @eval module Libc const FILE = Base.CFILE diff --git a/test/runtests.jl b/test/runtests.jl index ac7bf73e62869..21497bab0ee42 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -192,6 +192,12 @@ end @test parse(Float64, "222") == 222.0 @test parse(Float32, "1.1") == convert(Float32, 1.1) @test parse(BigFloat, "1.125") == convert(BigFloat, 1.125) +@test isa(tryparse(Float32, "1.1"), Nullable) +@test get(tryparse(Float32, "1.1")) == 1.1f0 +@test isa(tryparse(Float32, "a"), Nullable{Float32}) +@test isa(tryparse(Float64, "1.1"), Nullable) +@test get(tryparse(Float64, "1.1")) == 1.1 +@test isa(tryparse(Float64, "a"), Nullable{Float64}) # Make sure exports from Libc and Libdl are defined for x in [:strftime,:systemsleep,:getpid,:FILE,:malloc,:MS_SYNC,:munmap,:flush_cstdio,:realloc,:strptime,:Libc,:errno,:msync,:TmStruct,:calloc,:MS_INVALIDATE,:MS_ASYNC,:time,:strerror,:gethostname,:free,:mmap]