lib/bindata/single.rb in bindata-0.8.1 vs lib/bindata/single.rb in bindata-0.9.0

- old
+ new

@@ -4,10 +4,30 @@ # A BinData::Single object is a container for a value that has a particular # binary representation. A value corresponds to a primitive type such as # as integer, float or string. Only one value can be contained by this # object. This value can be read from or written to an IO stream. # + # require 'bindata' + # + # obj = BinData::Uint8.new(:initial_value => 42) + # obj.value #=> 42 + # obj.value = 5 + # obj.value #=> 5 + # obj.clear + # obj.value #=> 42 + # + # obj = BinData::Uint8.new(:value => 42) + # obj.value #=> 42 + # obj.value = 5 + # obj.value #=> 42 + # + # obj = BinData::Uint8.new(:check_value => 3) + # obj.read("\005") #=> BinData::ValidityError: value is '5' but expected '3' + # + # obj = BinData::Uint8.new(:check_value => lambda { value < 5 }) + # obj.read("\007") #=> BinData::ValidityError: value not as expected + # # == Parameters # # Parameters may be provided at initialisation to control the behaviour of # an object. These params include those for BinData::Base as well as: # @@ -26,19 +46,19 @@ # or failure. Any other return is compared to # the value just read in. class Single < Base # These are the parameters used by this class. optional_parameters :initial_value, :value, :check_value + mutually_exclusive_parameters :initial_value, :value - # Register the names of all subclasses of this class. - def self.inherited(subclass) #:nodoc: - register(subclass.name, subclass) + # Single objects don't contain fields so this returns an empty list. + def self.all_possible_field_names(sanitized_params) + [] end def initialize(params = {}, env = nil) super(params, env) - ensure_mutual_exclusion(:initial_value, :value) clear end # Resets the internal state to that of a newly created object. def clear @@ -88,10 +108,15 @@ # Returns a snapshot of this data object. def snapshot value end + # Single objects are single_values + def single_value? + true + end + # Single objects don't contain fields so this returns an empty list. def field_names [] end @@ -147,11 +172,11 @@ raise EOFError, "End of file reached" if str == nil raise IOError, "data truncated" if str.size < n str end -=begin + ########################################################################### # To be implemented by subclasses # Return the string representation that +val+ will take when written. def val_to_str(val) raise NotImplementedError @@ -166,8 +191,8 @@ def sensible_default raise NotImplementedError end # To be implemented by subclasses -=end + ########################################################################### end end