User-defined primitive types -- how to access?


#1

The documentation explains how to declare a primitive type, but seems silent on how to set the bits or read them.

For example, given:

primitive type Foo 8 end

how would I construct a Foo holding 42, or given a Foo, how do I read the bits?


#2

reinterpret


#3

A real-world example may be helpful: https://github.com/BioJulia/BioSymbols.jl/blob/9680751fabdb26ddc7a841c2115c149ec78e7617/src/nucleicacid.jl#L29-L47.

"""
An abstract nucleic acid type.
"""
@compat abstract type NucleicAcid end

"""
A deoxyribonucleic acid type.
"""
@compat primitive type DNA <: NucleicAcid 8 end

"""
A ribonucleic acid type.
"""
@compat primitive type RNA <: NucleicAcid 8 end

# Conversion from/to integers
# ---------------------------

Base.convert{T<:NucleicAcid}(::Type{T}, nt::UInt8) = reinterpret(T, nt)
Base.convert{T<:NucleicAcid}(::Type{UInt8}, nt::T) = reinterpret(UInt8, nt)
Base.convert{T<:Number,S<:NucleicAcid}(::Type{T}, nt::S) = convert(T, UInt8(nt))
Base.convert{T<:Number,S<:NucleicAcid}(::Type{S}, nt::T) = convert(S, UInt8(nt))