Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: read (some) v4 format files #164

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/MAT.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ using HDF5, SparseArrays

include("MAT_HDF5.jl")
include("MAT_v5.jl")
include("MAT_v4.jl")

using .MAT_HDF5, .MAT_v5

Expand All @@ -54,8 +55,10 @@ function matopen(filename::AbstractString, rd::Bool, wr::Bool, cr::Bool, tr::Boo
magic = read!(rawfid, Vector{UInt8}(undef, 4))
for i = 1:length(magic)
if magic[i] == 0
close(rawfid)
error("\"$filename\" is not a MAT file, or is an unsupported (v4) MAT file")
if wr || cr || tr || ff
error("creating or appending to MATLAB v4 files is not supported")
end
return MAT_v4.matopen(rawfid)
end
end

Expand Down
59 changes: 59 additions & 0 deletions src/MAT_v4.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
module MAT_v4

import Base: read, write, close

mutable struct Matlabv4File
ios::IOStream
varnames::Dict{String, Int64}

Matlabv4File(ios) = new(ios)
end

const V4_ELTYPE = [Float64, Float32, Int32, Int16, UInt16, UInt8]

matopen(ios::IOStream) = Matlabv4File(ios)

function unpack_header_type(type::Int32)
T, P, O, M = digits(type; pad=4)
iszero(O) || error("file is not a v4 MAT file (magic digit not 0)")
iszero(M) || error("only little endian v4 MAT currently supported")
iszero(T) || error("only full numeric matrices supported for v4 MAT files")

P in 0:5 || error("invalid eltype digit in v4 MAT file: $P")
eltype = V4_ELTYPE[P+1]

return eltype
end

function read_one_mat!(mat::Matlabv4File)
type, mrows, ncols, imagf, namlen = read!(mat.ios, Vector{Int32}(undef, 5))
eltype = unpack_header_type(type)

iszero(imagf) || error("no imaginary matrix support")

name = String(read!(mat.ios, Vector{UInt8}(undef, namlen-1)))

# one null byte before start of matrix data
Base.read(mat.ios, UInt8)

@show mrows, ncols
value = read!(mat.ios, Matrix{eltype}(undef, mrows, ncols))

return name => value
end

function read(mat::Matlabv4File)
seekstart(mat.ios)

results = Dict{String,Any}()
while !eof(mat.ios)
name, value = read_one_mat!(mat)
results[name] = value
end

return results
end

close(mat::Matlabv4File) = close(mat.ios)

end # module