Skip to content

Commit

Permalink
Very ad hoc Attribute implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
kojix2 committed Sep 12, 2024
1 parent 9ba1d6b commit 0f6629c
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/hdf5.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ def search_hdf5lib
require_relative 'hdf5/file'
require_relative 'hdf5/group'
require_relative 'hdf5/dataset'
require_relative 'hdf5/attribute'
60 changes: 60 additions & 0 deletions lib/hdf5/attribute.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
module HDF5
class Attribute
def initialize(dataset_id, attr_name)
@dataset_id = dataset_id
@attr_name = attr_name
@attr_id = FFI.H5Aopen(@dataset_id, @attr_name, 0)
raise 'Failed to open attribute' if @attr_id < 0
end

def read
type_id = FFI.H5Aget_type(@attr_id)
space_id = FFI.H5Aget_space(@attr_id)

size = FFI.H5Sget_simple_extent_npoints(space_id)

buffer = \
case FFI.H5Tget_class(type_id)
when :H5T_INTEGER
::FFI::MemoryPointer.new(:int, size)
when :H5T_FLOAT
::FFI::MemoryPointer.new(:double, size)
when :H5T_STRING
::FFI::MemoryPointer.new(:pointer, size)
else
raise 'Unsupported data type'
end

status = FFI.H5Aread(@attr_id, type_id, buffer)
raise 'Failed to read attribute' if status < 0

case FFI.H5Tget_class(type_id)
when :H5T_INTEGER
buffer.read_array_of_int(size)
when :H5T_FLOAT
buffer.read_array_of_double(size)
when :H5T_STRING
buffer.read_pointer.read_string
else
raise 'Unsupported data type'
end
end

def close
FFI.H5Aclose(@attr_id)
end
end

class AttributeManager
def initialize(dataset_id)
@dataset_id = dataset_id
end

def [](attr_name)
attr = Attribute.new(@dataset_id, attr_name)
attr.read
ensure
attr.close if attr
end
end
end
4 changes: 4 additions & 0 deletions lib/hdf5/dataset.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ def initialize(parent_id, name)
@dataset_id = HDF5::FFI.H5Dopen1(parent_id, name)
end

def attrs
@attrs ||= AttributeManager.new(@dataset_id)
end

def write(data)
HDF5::FFI.H5Dwrite(@dataset_id, data)
end
Expand Down
4 changes: 4 additions & 0 deletions lib/hdf5/file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ def [](name)
end
end

def attrs
@attrs ||= AttributeManager.new(@file_id)
end

private

def group?(name)
Expand Down
4 changes: 4 additions & 0 deletions lib/hdf5/group.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ def [](name)
end
end

def attrs
@attrs ||= AttributeManager.new(@group_id)
end

private

def group?(name)
Expand Down

0 comments on commit 0f6629c

Please sign in to comment.