File: nullable.jl

package info (click to toggle)
julia 0.4.7-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,128 kB
  • ctags: 15,440
  • sloc: lisp: 146,606; ansic: 96,638; sh: 12,615; cpp: 11,846; makefile: 3,431; python: 1,005; pascal: 856; xml: 585; f90: 415; java: 343; asm: 86; perl: 77
file content (64 lines) | stat: -rw-r--r-- 1,704 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# This file is a part of Julia. License is MIT: http://julialang.org/license

immutable NullException <: Exception
end

Nullable{T}(value::T, isnull::Bool=false) = Nullable{T}(value, isnull)
Nullable() = Nullable{Union{}}()

eltype{T}(::Type{Nullable{T}}) = T

convert{T}(::Type{Nullable{T}}, x::Nullable{T}) = x
convert(   ::Type{Nullable   }, x::Nullable   ) = x

function convert{T}(::Type{Nullable{T}}, x::Nullable)
    return isnull(x) ? Nullable{T}() : Nullable{T}(convert(T, get(x)))
end

convert{T}(::Type{Nullable{T}}, x::T) = Nullable{T}(x)
convert{T}(::Type{Nullable   }, x::T) = Nullable{T}(x)

convert{T}(::Type{Nullable{T}}, ::Void) = Nullable{T}()
convert(   ::Type{Nullable   }, ::Void) = Nullable{Union{}}()

function show{T}(io::IO, x::Nullable{T})
    if x.isnull
        print(io, "Nullable{"); show(io, T); print(io, "}()")
    else
        print(io, "Nullable("); show(io, x.value); print(io, ")")
    end
end

get(x::Nullable) = x.isnull ? throw(NullException()) : x.value

@inline function get{T}(x::Nullable{T}, y)
    if isbits(T)
        ifelse(x.isnull, convert(T, y), x.value)
    else
        x.isnull ? convert(T, y) : x.value
    end
end

isnull(x::Nullable) = x.isnull

function isequal(x::Nullable, y::Nullable)
    if x.isnull && y.isnull
        return true
    elseif x.isnull || y.isnull
        return false
    else
        return isequal(x.value, y.value)
    end
end

==(x::Nullable, y::Nullable) = throw(NullException())

const nullablehash_seed = UInt === UInt64 ? 0x932e0143e51d0171 : 0xe51d0171

function hash(x::Nullable, h::UInt)
    if x.isnull
        return h + nullablehash_seed
    else
        return hash(x.value, h + nullablehash_seed)
    end
end