File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -116,6 +116,7 @@ def normalize_data(value)
116116
117117 def datatype_id_for ( values )
118118 if values . all? { |item | item . is_a? ( Integer ) }
119+ validate_native_int_range! ( values )
119120 HDF5 ::FFI . H5T_NATIVE_INT
120121 elsif values . all? { |item | item . is_a? ( Numeric ) }
121122 HDF5 ::FFI . H5T_NATIVE_DOUBLE
@@ -135,5 +136,21 @@ def buffer_for(values)
135136
136137 buffer
137138 end
139+
140+ def native_int_bounds
141+ bits = ::FFI . type_size ( :int ) * 8
142+ max = ( 1 << ( bits - 1 ) ) - 1
143+ min = -( 1 << ( bits - 1 ) )
144+ [ min , max ]
145+ end
146+
147+ def validate_native_int_range! ( values )
148+ min , max = native_int_bounds
149+ out_of_range = values . find { |value | value < min || value > max }
150+ return unless out_of_range
151+
152+ raise HDF5 ::Error ,
153+ "Integer value #{ out_of_range } is outside native int range (#{ min } ..#{ max } ). Use a smaller value."
154+ end
138155 end
139156end
Original file line number Diff line number Diff line change @@ -154,6 +154,23 @@ class HDF5Test < Test::Unit::TestCase
154154 end
155155 end
156156
157+ test 'rejects integer values outside native int range on attribute write' do
158+ min = -( 1 << ( ::FFI . type_size ( :int ) * 8 - 1 ) )
159+ max = ( 1 << ( ::FFI . type_size ( :int ) * 8 - 1 ) ) - 1
160+
161+ Dir . mktmpdir do |dir |
162+ path = File . join ( dir , 'attribute-overflow.h5' )
163+
164+ HDF5 ::File . create ( path ) do |file |
165+ dataset = file . create_dataset ( 'values' , [ 1 , 2 , 3 ] )
166+ error = assert_raise ( HDF5 ::Error ) do
167+ dataset . attrs [ 'scale' ] = [ max + 1 ]
168+ end
169+ assert_include ( error . message , "#{ min } ..#{ max } " )
170+ end
171+ end
172+ end
173+
157174 test 'group list_datasets returns only datasets' do
158175 Dir . mktmpdir do |dir |
159176 path = File . join ( dir , 'group-list.h5' )
You can’t perform that action at this time.
0 commit comments