Skip to content

Instantly share code, notes, and snippets.

@iamed2
Created August 12, 2021 22:12
Show Gist options
  • Save iamed2/7800a9b391d9e11f0f2b7fbbfbb84c32 to your computer and use it in GitHub Desktop.
Save iamed2/7800a9b391d9e11f0f2b7fbbfbb84c32 to your computer and use it in GitHub Desktop.
A custom Julia serialization method that works for any primitive type
# Originally written to work with InlineString in WeakRefStrings, this should work for any primitive type
# In most cases, the built-in defaults provided by Julia work fine, using `read` and `write`.
# However, if your `read` and `write` methods are not round-trippable, or they convert your data into a
# less-efficient representation before writing, then you might want to additionally define a custom
# serialization method, using this code.
# It should only be necessary to substitute your type for `Primitive`.
using Serialization
abstract type Primitive end
primitive type Primitive128 <: Primitive 128 end
primitive type Primitive256 <: Primitive 256 end
function Serialization.serialize(s::AbstractSerializer, x::T) where {T<:Primitive}
Serialization.serialize_type(s, T)
unsafe_write(s.io, Ref{T}(x), sizeof(T))
return nothing
end
function Serialization.deserialize(s::AbstractSerializer, ::Type{T}) where {T<:Primitive}
ref = Ref{T}()
unsafe_read(s.io, ref, sizeof(T))
return ref[]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment