[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / lib / ostruct.rb
blobc762baa5a593060c3e43ad6b41edcc58fa82dc93
1 # frozen_string_literal: true
3 # = ostruct.rb: OpenStruct implementation
5 # Author:: Yukihiro Matsumoto
6 # Documentation:: Gavin Sinclair
8 # OpenStruct allows the creation of data objects with arbitrary attributes.
9 # See OpenStruct for an example.
13 # An OpenStruct is a data structure, similar to a Hash, that allows the
14 # definition of arbitrary attributes with their accompanying values. This is
15 # accomplished by using Ruby's metaprogramming to define methods on the class
16 # itself.
18 # == Examples
20 #   require "ostruct"
22 #   person = OpenStruct.new
23 #   person.name = "John Smith"
24 #   person.age  = 70
26 #   person.name      # => "John Smith"
27 #   person.age       # => 70
28 #   person.address   # => nil
30 # An OpenStruct employs a Hash internally to store the attributes and values
31 # and can even be initialized with one:
33 #   australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
34 #     # => #<OpenStruct country="Australia", capital="Canberra">
36 # Hash keys with spaces or characters that could normally not be used for
37 # method calls (e.g. <code>()[]*</code>) will not be immediately available
38 # on the OpenStruct object as a method for retrieval or assignment, but can
39 # still be reached through the Object#send method or using [].
41 #   measurements = OpenStruct.new("length (in inches)" => 24)
42 #   measurements[:"length (in inches)"]       # => 24
43 #   measurements.send("length (in inches)")   # => 24
45 #   message = OpenStruct.new(:queued? => true)
46 #   message.queued?                           # => true
47 #   message.send("queued?=", false)
48 #   message.queued?                           # => false
50 # Removing the presence of an attribute requires the execution of the
51 # delete_field method as setting the property value to +nil+ will not
52 # remove the attribute.
54 #   first_pet  = OpenStruct.new(:name => "Rowdy", :owner => "John Smith")
55 #   second_pet = OpenStruct.new(:name => "Rowdy")
57 #   first_pet.owner = nil
58 #   first_pet                 # => #<OpenStruct name="Rowdy", owner=nil>
59 #   first_pet == second_pet   # => false
61 #   first_pet.delete_field(:owner)
62 #   first_pet                 # => #<OpenStruct name="Rowdy">
63 #   first_pet == second_pet   # => true
65 # Ractor compatibility: A frozen OpenStruct with shareable values is itself shareable.
67 # == Caveats
69 # An OpenStruct utilizes Ruby's method lookup structure to find and define the
70 # necessary methods for properties. This is accomplished through the methods
71 # method_missing and define_singleton_method.
73 # This should be a consideration if there is a concern about the performance of
74 # the objects that are created, as there is much more overhead in the setting
75 # of these properties compared to using a Hash or a Struct.
76 # Creating an open struct from a small Hash and accessing a few of the
77 # entries can be 200 times slower than accessing the hash directly.
79 # This is a potential security issue; building OpenStruct from untrusted user data
80 # (e.g. JSON web request) may be susceptible to a "symbol denial of service" attack
81 # since the keys create methods and names of methods are never garbage collected.
83 # This may also be the source of incompatibilities between Ruby versions:
85 #   o = OpenStruct.new
86 #   o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6
88 # Builtin methods may be overwritten this way, which may be a source of bugs
89 # or security issues:
91 #   o = OpenStruct.new
92 #   o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, ...
93 #   o.methods = [:foo, :bar]
94 #   o.methods # => [:foo, :bar]
96 # To help remedy clashes, OpenStruct uses only protected/private methods ending with <code>!</code>
97 # and defines aliases for builtin public methods by adding a <code>!</code>:
99 #   o = OpenStruct.new(make: 'Bentley', class: :luxury)
100 #   o.class # => :luxury
101 #   o.class! # => OpenStruct
103 # It is recommended (but not enforced) to not use fields ending in <code>!</code>;
104 # Note that a subclass' methods may not be overwritten, nor can OpenStruct's own methods
105 # ending with <code>!</code>.
107 # For all these reasons, consider not using OpenStruct at all.
109 class OpenStruct
110   VERSION = "0.6.0"
112   HAS_PERFORMANCE_WARNINGS = begin
113     Warning[:performance]
114     true
115   rescue NoMethodError, ArgumentError
116     false
117   end
118   private_constant :HAS_PERFORMANCE_WARNINGS
120   #
121   # Creates a new OpenStruct object.  By default, the resulting OpenStruct
122   # object will have no attributes.
123   #
124   # The optional +hash+, if given, will generate attributes and values
125   # (can be a Hash, an OpenStruct or a Struct).
126   # For example:
127   #
128   #   require "ostruct"
129   #   hash = { "country" => "Australia", :capital => "Canberra" }
130   #   data = OpenStruct.new(hash)
131   #
132   #   data   # => #<OpenStruct country="Australia", capital="Canberra">
133   #
134   def initialize(hash=nil)
135     if HAS_PERFORMANCE_WARNINGS && Warning[:performance]
136        warn "OpenStruct use is discouraged for performance reasons", uplevel: 1, category: :performance
137     end
139     if hash
140       update_to_values!(hash)
141     else
142       @table = {}
143     end
144   end
146   # Duplicates an OpenStruct object's Hash table.
147   private def initialize_clone(orig) # :nodoc:
148     super # clones the singleton class for us
149     @table = @table.dup unless @table.frozen?
150   end
152   private def initialize_dup(orig) # :nodoc:
153     super
154     update_to_values!(@table)
155   end
157   private def update_to_values!(hash) # :nodoc:
158     @table = {}
159     hash.each_pair do |k, v|
160       set_ostruct_member_value!(k, v)
161     end
162   end
164   #
165   # call-seq:
166   #   ostruct.to_h                        -> hash
167   #   ostruct.to_h {|name, value| block } -> hash
168   #
169   # Converts the OpenStruct to a hash with keys representing
170   # each attribute (as symbols) and their corresponding values.
171   #
172   # If a block is given, the results of the block on each pair of
173   # the receiver will be used as pairs.
174   #
175   #   require "ostruct"
176   #   data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
177   #   data.to_h   # => {:country => "Australia", :capital => "Canberra" }
178   #   data.to_h {|name, value| [name.to_s, value.upcase] }
179   #               # => {"country" => "AUSTRALIA", "capital" => "CANBERRA" }
180   #
181   if {test: :to_h}.to_h{ [:works, true] }[:works] # RUBY_VERSION < 2.6 compatibility
182     def to_h(&block)
183       if block
184         @table.to_h(&block)
185       else
186         @table.dup
187       end
188     end
189   else
190     def to_h(&block)
191       if block
192         @table.map(&block).to_h
193       else
194         @table.dup
195       end
196     end
197   end
199   #
200   # :call-seq:
201   #   ostruct.each_pair {|name, value| block }  -> ostruct
202   #   ostruct.each_pair                         -> Enumerator
203   #
204   # Yields all attributes (as symbols) along with the corresponding values
205   # or returns an enumerator if no block is given.
206   #
207   #   require "ostruct"
208   #   data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
209   #   data.each_pair.to_a   # => [[:country, "Australia"], [:capital, "Canberra"]]
210   #
211   def each_pair
212     return to_enum(__method__) { @table.size } unless defined?(yield)
213     @table.each_pair{|p| yield p}
214     self
215   end
217   #
218   # Provides marshalling support for use by the Marshal library.
219   #
220   def marshal_dump # :nodoc:
221     @table
222   end
224   #
225   # Provides marshalling support for use by the Marshal library.
226   #
227   alias_method :marshal_load, :update_to_values! # :nodoc:
229   #
230   # Used internally to defined properties on the
231   # OpenStruct. It does this by using the metaprogramming function
232   # define_singleton_method for both the getter method and the setter method.
233   #
234   def new_ostruct_member!(name) # :nodoc:
235     unless @table.key?(name) || is_method_protected!(name)
236       if defined?(::Ractor)
237         getter_proc = nil.instance_eval{ Proc.new { @table[name] } }
238         setter_proc = nil.instance_eval{ Proc.new {|x| @table[name] = x} }
239         ::Ractor.make_shareable(getter_proc)
240         ::Ractor.make_shareable(setter_proc)
241       else
242         getter_proc = Proc.new { @table[name] }
243         setter_proc = Proc.new {|x| @table[name] = x}
244       end
245       define_singleton_method!(name, &getter_proc)
246       define_singleton_method!("#{name}=", &setter_proc)
247     end
248   end
249   private :new_ostruct_member!
251   private def is_method_protected!(name) # :nodoc:
252     if !respond_to?(name, true)
253       false
254     elsif name.match?(/!$/)
255       true
256     else
257       owner = method!(name).owner
258       if owner.class == ::Class
259         owner < ::OpenStruct
260       else
261         self.class!.ancestors.any? do |mod|
262           return false if mod == ::OpenStruct
263           mod == owner
264         end
265       end
266     end
267   end
269   def freeze
270     @table.freeze
271     super
272   end
274   private def method_missing(mid, *args) # :nodoc:
275     len = args.length
276     if mname = mid[/.*(?==\z)/m]
277       if len != 1
278         raise! ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1)
279       end
280       set_ostruct_member_value!(mname, args[0])
281     elsif len == 0
282       @table[mid]
283     else
284       begin
285         super
286       rescue NoMethodError => err
287         err.backtrace.shift
288         raise!
289       end
290     end
291   end
293   #
294   # :call-seq:
295   #   ostruct[name]  -> object
296   #
297   # Returns the value of an attribute, or +nil+ if there is no such attribute.
298   #
299   #   require "ostruct"
300   #   person = OpenStruct.new("name" => "John Smith", "age" => 70)
301   #   person[:age]   # => 70, same as person.age
302   #
303   def [](name)
304     @table[name.to_sym]
305   end
307   #
308   # :call-seq:
309   #   ostruct[name] = obj  -> obj
310   #
311   # Sets the value of an attribute.
312   #
313   #   require "ostruct"
314   #   person = OpenStruct.new("name" => "John Smith", "age" => 70)
315   #   person[:age] = 42   # equivalent to person.age = 42
316   #   person.age          # => 42
317   #
318   def []=(name, value)
319     name = name.to_sym
320     new_ostruct_member!(name)
321     @table[name] = value
322   end
323   alias_method :set_ostruct_member_value!, :[]=
324   private :set_ostruct_member_value!
326   # :call-seq:
327   #   ostruct.dig(name, *identifiers) -> object
328   #
329   # Finds and returns the object in nested objects
330   # that is specified by +name+ and +identifiers+.
331   # The nested objects may be instances of various classes.
332   # See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
333   #
334   # Examples:
335   #   require "ostruct"
336   #   address = OpenStruct.new("city" => "Anytown NC", "zip" => 12345)
337   #   person  = OpenStruct.new("name" => "John Smith", "address" => address)
338   #   person.dig(:address, "zip") # => 12345
339   #   person.dig(:business_address, "zip") # => nil
340   def dig(name, *names)
341     begin
342       name = name.to_sym
343     rescue NoMethodError
344       raise! TypeError, "#{name} is not a symbol nor a string"
345     end
346     @table.dig(name, *names)
347   end
349   #
350   # Removes the named field from the object and returns the value the field
351   # contained if it was defined. You may optionally provide a block.
352   # If the field is not defined, the result of the block is returned,
353   # or a NameError is raised if no block was given.
354   #
355   #   require "ostruct"
356   #
357   #   person = OpenStruct.new(name: "John", age: 70, pension: 300)
358   #
359   #   person.delete_field!("age")  # => 70
360   #   person                       # => #<OpenStruct name="John", pension=300>
361   #
362   # Setting the value to +nil+ will not remove the attribute:
363   #
364   #   person.pension = nil
365   #   person                 # => #<OpenStruct name="John", pension=nil>
366   #
367   #   person.delete_field('number')  # => NameError
368   #
369   #   person.delete_field('number') { 8675_309 } # => 8675309
370   #
371   def delete_field(name, &block)
372     sym = name.to_sym
373     begin
374       singleton_class.remove_method(sym, "#{sym}=")
375     rescue NameError
376     end
377     @table.delete(sym) do
378       return yield if block
379       raise! NameError.new("no field '#{sym}' in #{self}", sym)
380     end
381   end
383   InspectKey = :__inspect_key__ # :nodoc:
385   #
386   # Returns a string containing a detailed summary of the keys and values.
387   #
388   def inspect
389     ids = (Thread.current[InspectKey] ||= [])
390     if ids.include?(object_id)
391       detail = ' ...'
392     else
393       ids << object_id
394       begin
395         detail = @table.map do |key, value|
396           " #{key}=#{value.inspect}"
397         end.join(',')
398       ensure
399         ids.pop
400       end
401     end
402     ['#<', self.class!, detail, '>'].join
403   end
404   alias :to_s :inspect
406   attr_reader :table # :nodoc:
407   alias table! table
408   protected :table!
410   #
411   # Compares this object and +other+ for equality.  An OpenStruct is equal to
412   # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
413   # equal.
414   #
415   #   require "ostruct"
416   #   first_pet  = OpenStruct.new("name" => "Rowdy")
417   #   second_pet = OpenStruct.new(:name  => "Rowdy")
418   #   third_pet  = OpenStruct.new("name" => "Rowdy", :age => nil)
419   #
420   #   first_pet == second_pet   # => true
421   #   first_pet == third_pet    # => false
422   #
423   def ==(other)
424     return false unless other.kind_of?(OpenStruct)
425     @table == other.table!
426   end
428   #
429   # Compares this object and +other+ for equality.  An OpenStruct is eql? to
430   # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
431   # eql?.
432   #
433   def eql?(other)
434     return false unless other.kind_of?(OpenStruct)
435     @table.eql?(other.table!)
436   end
438   # Computes a hash code for this OpenStruct.
439   def hash # :nodoc:
440     @table.hash
441   end
443   #
444   # Provides marshalling support for use by the YAML library.
445   #
446   def encode_with(coder) # :nodoc:
447     @table.each_pair do |key, value|
448       coder[key.to_s] = value
449     end
450     if @table.size == 1 && @table.key?(:table) # support for legacy format
451       # in the very unlikely case of a single entry called 'table'
452       coder['legacy_support!'] = true # add a bogus second entry
453     end
454   end
456   #
457   # Provides marshalling support for use by the YAML library.
458   #
459   def init_with(coder) # :nodoc:
460     h = coder.map
461     if h.size == 1 # support for legacy format
462       key, val = h.first
463       if key == 'table'
464         h = val
465       end
466     end
467     update_to_values!(h)
468   end
470   # Make all public methods (builtin or our own) accessible with <code>!</code>:
471   give_access = instance_methods
472   # See https://github.com/ruby/ostruct/issues/30
473   give_access -= %i[instance_exec instance_eval eval] if RUBY_ENGINE == 'jruby'
474   give_access.each do |method|
475     next if method.match(/\W$/)
477     new_name = "#{method}!"
478     alias_method new_name, method
479   end
480   # Other builtin private methods we use:
481   alias_method :raise!, :raise
482   private :raise!
484   # See https://github.com/ruby/ostruct/issues/40
485   if RUBY_ENGINE != 'jruby'
486     alias_method :block_given!, :block_given?
487     private :block_given!
488   end