Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Created November 3, 2015 22:57
Show Gist options
  • Select an option

  • Save ityonemo/fd72b2f632500bf77a3d to your computer and use it in GitHub Desktop.

Select an option

Save ityonemo/fd72b2f632500bf77a3d to your computer and use it in GitHub Desktop.
squaring the circle to make variadic unums have both sane construction and high performance
abstract Unum{ESS, FSS}
#define an outer constructor on this type.
type Unum_Small{ESS, FSS} <: Unum{ESS, FSS}
fsize::UInt16
esize::UInt16
flags::UInt16
fraction::UInt64
exponent::UInt64
end
type Unum_Variable{ESS, FSS} <: Unum{ESS, FSS}
fsize::UInt16
esize::UInt16
flags::UInt16
fraction::Array{UInt64}
exponent::UInt64
end
#override call to allow direct instantiation as a unum.
function call{ESS, FSS}(::Type{Unum{ESS,FSS}}, fsize::UInt16, esize::UInt16, flags::UInt16, fraction::UInt64, exponent::UInt64)
(FSS > 6) && throw(ArgumentError("FSS = $FSS > 6 requires an UInt64 array"))
(ESS > 6) && throw(ArgumentError("ESS = $ESS > 6 currently not allowed."))
Unum_Small{ESS,FSS}(fsize, esize, flags, fraction, exponent)
end
function call{ESS,FSS}(::Type{Unum{ESS, FSS}}, fsize::UInt16, esize::UInt16, flags::UInt16, fraction::Array{UInt64}, exponent::UInt64)
(ESS > 6) && throw(ArgumentError("ESS = $ESS > 6 currently not allowed."))
(FSS > 11) && throw(ArgumentError("FSS = $FSS > 11 currently not allowed"))
#calculate the number of cells that fraction will have.
min_frac_length = max(1 << (FSS - 6), 0)
l = length(fraction)
(l < min_frac_length) && throw(ArgumentError("insufficient array elements to create unum with desired FSS ($FSS requires $min_frac_length > $l)"))
if (FSS < 7)
Unum_Small{ESS,FSS}(fsize, esize, flags, fraction[1], exponent)
else
Unum_Variable{ESS,FSS}(fsize, esize, flags, fraction[1:min_frac_length], exponent)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment