How to dispatch this serializer function?

Here would be my start. (there might be some typos, but I think you’ll get the gist).

# Encode number types
classToByte(::Float64) = Int8(0)
classToByte(::Union{Float32, Float16}) = Int8(1)
classToByte(::Bool) = Int8(2)
classToByte(::Char) = Int8(3)
classToByte(::Int8) = Int8(4)
classToByte(::UInt8) = Int8(5)
classToByte(::Int16) = Int8(6)
classToByte(::UInt16) = Int8(7)
classToByte(::Int32) = Int8(8)
classToByte(::UInt32) = Int8(9)
classToByte(::Int64) = Int8(10)
classToByte(::UInt64) = Int8(11)
classToByte(x) = error("Unknown number type: $cls")

function serializej2m(v)
    
    ```
    io = serializej2m(v)
    reinterprets a Julia object into a Matlab object's series of bytes.
    
    Based on
    https://de.mathworks.com/matlabcentral/fileexchange/29457-serialize-deserialize
    
    ```
    io = IOBuffer(UInt8[]; append = true)
    serializej2m(v,io)
    return take!(io)
end

function serializej2m(io, v::T) where {T<:Real}
    # Data type.
    write(io, classToByte(T))
    # Number of dimensions.
    write(io, UInt8(2))
    # Dimensions.
    write(io, UInt32(1))
    write(io, UInt32(1))
    # Data.
    write(io, v)
end

function serializej2m(io, v::Union{Char,String})
    # Data type.
    write(io, classToByte(Char)
    # Number of dimensions.
    write(io, UInt8(2))
    # Dimensions.
    write(io, UInt32(1))
    write(io, UInt32(length(v)))
    # Data.
    write(io, v)
end
# Matlab matrix. Numeric (n-dim) or character (vector).
function serializej2m(io, v::AbstractArray{T<:Real})
    iss = false
    # Data type.
    write(io, classToByte(eltype(v)))
    # Number of dimensions.
    nd = max(2, ndims(v))
    write(io, UInt8(nd))
    # Dimensions.
    for ii = 1:nd
        write(io, UInt32(size(v, ii)))
    end
    # Data.
    write(io, v)
end

# Matlab cell array. Any content not fitting into a Matlab matrix.
function serializej2m(io, v::AbstractArray)
    # Data type.
    write(io, UInt8(254)) # 254 = cell.
    # Number of dimensions.
    nd = max(2, ndims(v))
    write(io, UInt8(nd))
    # Dimensions.
    for ii = 1:nd
        write(io, UInt32.(size(v)))
    end
    # Just serialize each member.
    for ii = 1:numel(v)
        write(io, serializej2m(v[ii]))
    end
end
2 Likes