aboutsummaryrefslogtreecommitdiff
path: root/tools/Mach5/bit-struct/yaml.rb
blob: f298ab2b9789f42ca8af08258e703b9ed162fc52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require 'bit-struct/bit-struct'
require 'yaml'

class BitStruct
  if RUBY_VERSION == "1.8.2"
    def is_complex_yaml? # :nodoc:
      true
    end

    YAML.add_ruby_type(/^bitstruct/) do |type, val|
      subtype, subclass = YAML.read_type_class(type, Object)
      subclass.new(val)
    end

    def to_yaml_type # :nodoc:
      "!ruby/bitstruct:#{self.class}"
    end

    def to_yaml( opts = {} ) # :nodoc:
      opts[:DocType] = self.class if Hash === opts
      YAML.quick_emit(self.object_id, opts) do |out|
        out.map(to_yaml_type) do |map|
          fields.each do |field|
            fn = field.name
            map.add(fn, send(fn))
          end
        end
      end
    end

  else
    yaml_as "tag:path.berkeley.edu,2006:bitstruct"

    def to_yaml_properties # :nodoc:
      yaml_fields = fields.select {|field| field.inspectable?}
      props = yaml_fields.map {|f| f.name.to_s}
      if (rest_field = self.class.rest_field)
        props << rest_field.name.to_s
      end
      props
    end

    # Return YAML representation of the BitStruct.
    def to_yaml( opts = {} )
      YAML::quick_emit( object_id, opts ) do |out|
        out.map( taguri, to_yaml_style ) do |map|
          to_yaml_properties.each do |m|
            map.add( m, send( m ) )
          end
        end
      end
    end

    def self.yaml_new( klass, tag, val ) # :nodoc:
      unless Hash === val
        raise YAML::TypeError, "Invalid BitStruct: " + val.inspect
      end

      bitstruct_name, bitstruct_type = YAML.read_type_class( tag, BitStruct )

      st = bitstruct_type.new

      val.each do |k,v|
        st.send( "#{k}=", v )
      end

      st
    end
  end
end