Created
August 12, 2021 22:12
-
-
Save iamed2/7800a9b391d9e11f0f2b7fbbfbb84c32 to your computer and use it in GitHub Desktop.
A custom Julia serialization method that works for any primitive type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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