Skip to content

Commit 0f6629c

Browse files
committed
Very ad hoc Attribute implementation
1 parent 9ba1d6b commit 0f6629c

5 files changed

Lines changed: 73 additions & 0 deletions

File tree

lib/hdf5.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ def search_hdf5lib
3636
require_relative 'hdf5/file'
3737
require_relative 'hdf5/group'
3838
require_relative 'hdf5/dataset'
39+
require_relative 'hdf5/attribute'

lib/hdf5/attribute.rb

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
module HDF5
2+
class Attribute
3+
def initialize(dataset_id, attr_name)
4+
@dataset_id = dataset_id
5+
@attr_name = attr_name
6+
@attr_id = FFI.H5Aopen(@dataset_id, @attr_name, 0)
7+
raise 'Failed to open attribute' if @attr_id < 0
8+
end
9+
10+
def read
11+
type_id = FFI.H5Aget_type(@attr_id)
12+
space_id = FFI.H5Aget_space(@attr_id)
13+
14+
size = FFI.H5Sget_simple_extent_npoints(space_id)
15+
16+
buffer = \
17+
case FFI.H5Tget_class(type_id)
18+
when :H5T_INTEGER
19+
::FFI::MemoryPointer.new(:int, size)
20+
when :H5T_FLOAT
21+
::FFI::MemoryPointer.new(:double, size)
22+
when :H5T_STRING
23+
::FFI::MemoryPointer.new(:pointer, size)
24+
else
25+
raise 'Unsupported data type'
26+
end
27+
28+
status = FFI.H5Aread(@attr_id, type_id, buffer)
29+
raise 'Failed to read attribute' if status < 0
30+
31+
case FFI.H5Tget_class(type_id)
32+
when :H5T_INTEGER
33+
buffer.read_array_of_int(size)
34+
when :H5T_FLOAT
35+
buffer.read_array_of_double(size)
36+
when :H5T_STRING
37+
buffer.read_pointer.read_string
38+
else
39+
raise 'Unsupported data type'
40+
end
41+
end
42+
43+
def close
44+
FFI.H5Aclose(@attr_id)
45+
end
46+
end
47+
48+
class AttributeManager
49+
def initialize(dataset_id)
50+
@dataset_id = dataset_id
51+
end
52+
53+
def [](attr_name)
54+
attr = Attribute.new(@dataset_id, attr_name)
55+
attr.read
56+
ensure
57+
attr.close if attr
58+
end
59+
end
60+
end

lib/hdf5/dataset.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ def initialize(parent_id, name)
44
@dataset_id = HDF5::FFI.H5Dopen1(parent_id, name)
55
end
66

7+
def attrs
8+
@attrs ||= AttributeManager.new(@dataset_id)
9+
end
10+
711
def write(data)
812
HDF5::FFI.H5Dwrite(@dataset_id, data)
913
end

lib/hdf5/file.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ def [](name)
4343
end
4444
end
4545

46+
def attrs
47+
@attrs ||= AttributeManager.new(@file_id)
48+
end
49+
4650
private
4751

4852
def group?(name)

lib/hdf5/group.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ def [](name)
3434
end
3535
end
3636

37+
def attrs
38+
@attrs ||= AttributeManager.new(@group_id)
39+
end
40+
3741
private
3842

3943
def group?(name)

0 commit comments

Comments
 (0)