repeated_field.rb 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. require 'forwardable'
  31. #
  32. # This class makes RepeatedField act (almost-) like a Ruby Array.
  33. # It has convenience methods that extend the core C or Java based
  34. # methods.
  35. #
  36. # This is a best-effort to mirror Array behavior. Two comments:
  37. # 1) patches always welcome :)
  38. # 2) if performance is an issue, feel free to rewrite the method
  39. # in jruby and C. The source code has plenty of examples
  40. #
  41. # KNOWN ISSUES
  42. # - #[]= doesn't allow less used approaches such as `arr[1, 2] = 'fizz'`
  43. # - #concat should return the orig array
  44. # - #push should accept multiple arguments and push them all at the same time
  45. #
  46. module Google
  47. module Protobuf
  48. class RepeatedField
  49. extend Forwardable
  50. # methods defined in C or Java:
  51. # +
  52. # [], at
  53. # []=
  54. # concat
  55. # clear
  56. # dup, clone
  57. # each
  58. # push, <<
  59. # replace
  60. # length, size
  61. # ==
  62. # to_ary, to_a
  63. # also all enumerable
  64. #
  65. # NOTE: using delegators rather than method_missing to make the
  66. # relationship explicit instead of implicit
  67. def_delegators :to_ary,
  68. :&, :*, :-, :'<=>',
  69. :assoc, :bsearch, :combination, :compact, :count, :cycle,
  70. :drop, :drop_while, :eql?, :fetch, :find_index, :flatten,
  71. :include?, :index, :inspect, :join,
  72. :pack, :permutation, :product, :pretty_print, :pretty_print_cycle,
  73. :rassoc, :repeated_combination, :repeated_permutation, :reverse,
  74. :rindex, :rotate, :sample, :shuffle, :shelljoin, :slice,
  75. :to_s, :transpose, :uniq, :|
  76. def first(n=nil)
  77. n ? self[0..n] : self[0]
  78. end
  79. def last(n=nil)
  80. n ? self[(self.size-n-1)..-1] : self[-1]
  81. end
  82. def pop(n=nil)
  83. if n
  84. results = []
  85. n.times{ results << pop_one }
  86. return results
  87. else
  88. return pop_one
  89. end
  90. end
  91. def empty?
  92. self.size == 0
  93. end
  94. # array aliases into enumerable
  95. alias_method :each_index, :each_with_index
  96. alias_method :slice, :[]
  97. alias_method :values_at, :select
  98. alias_method :map, :collect
  99. class << self
  100. def define_array_wrapper_method(method_name)
  101. define_method(method_name) do |*args, &block|
  102. arr = self.to_a
  103. result = arr.send(method_name, *args)
  104. self.replace(arr)
  105. return result if result
  106. return block ? block.call : result
  107. end
  108. end
  109. private :define_array_wrapper_method
  110. def define_array_wrapper_with_result_method(method_name)
  111. define_method(method_name) do |*args, &block|
  112. # result can be an Enumerator, Array, or nil
  113. # Enumerator can sometimes be returned if a block is an optional argument and it is not passed in
  114. # nil usually specifies that no change was made
  115. result = self.to_a.send(method_name, *args, &block)
  116. if result
  117. new_arr = result.to_a
  118. self.replace(new_arr)
  119. if result.is_a?(Enumerator)
  120. # generate a fresh enum; rewinding the exiting one, in Ruby 2.2, will
  121. # reset the enum with the same length, but all the #next calls will
  122. # return nil
  123. result = new_arr.to_enum
  124. # generate a wrapper enum so any changes which occur by a chained
  125. # enum can be captured
  126. ie = ProxyingEnumerator.new(self, result)
  127. result = ie.to_enum
  128. end
  129. end
  130. result
  131. end
  132. end
  133. private :define_array_wrapper_with_result_method
  134. end
  135. %w(delete delete_at delete_if shift slice! unshift).each do |method_name|
  136. define_array_wrapper_method(method_name)
  137. end
  138. %w(collect! compact! fill flatten! insert reverse!
  139. rotate! select! shuffle! sort! sort_by! uniq!).each do |method_name|
  140. define_array_wrapper_with_result_method(method_name)
  141. end
  142. alias_method :keep_if, :select!
  143. alias_method :map!, :collect!
  144. alias_method :reject!, :delete_if
  145. # propagates changes made by user of enumerator back to the original repeated field.
  146. # This only applies in cases where the calling function which created the enumerator,
  147. # such as #sort!, modifies itself rather than a new array, such as #sort
  148. class ProxyingEnumerator < Struct.new(:repeated_field, :external_enumerator)
  149. def each(*args, &block)
  150. results = []
  151. external_enumerator.each_with_index do |val, i|
  152. result = yield(val)
  153. results << result
  154. #nil means no change occured from yield; usually occurs when #to_a is called
  155. if result
  156. repeated_field[i] = result if result != val
  157. end
  158. end
  159. results
  160. end
  161. end
  162. end
  163. end
  164. end