Runtime assertions for Ruby literal.fun
ruby
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

Optimise primitive unions (#280)

authored by

Joel Drapper and committed by
GitHub
a8a0be45 bd242e05

+41 -14
+2
allocations_test.rb
··· 90 90 91 91 assert_allocations(_Union(String, Integer), 42) => 0 92 92 93 + assert_allocations(_Union(String, "Hello", "World"), "World") => 0 94 + 93 95 assert_allocations(_Void, nil) => 0
+26 -14
lib/literal/types/union_type.rb
··· 3 3 class Literal::Types::UnionType 4 4 include Enumerable 5 5 6 - def initialize(*types) 7 - raise Literal::ArgumentError.new("_Union type must have at least one type.") if types.size < 1 6 + def initialize(*queue) 7 + raise Literal::ArgumentError.new("_Union type must have at least one type.") if queue.size < 1 8 + types = [] 9 + primitives = Set[] 8 10 9 - @types = [] 10 - load_types(types) 11 - @types.uniq! 11 + while queue.length > 0 12 + type = queue.shift 13 + case type 14 + when Literal::Types::UnionType 15 + queue.concat(type.types, type.primitives.to_a) 16 + when Array, Hash, String, Symbol, Integer, Float, Complex, Rational, true, false, nil 17 + primitives << type 18 + else 19 + types << type 20 + end 21 + end 22 + 23 + types.uniq! 24 + @types = types 25 + @primitives = primitives 26 + 12 27 @types.freeze 28 + @primitives.freeze 29 + freeze 13 30 end 14 31 15 - attr_reader :types 32 + attr_reader :types, :primitives 16 33 17 34 def inspect 18 35 "_Union(#{@types.inspect})" 19 36 end 20 37 21 38 def ===(value) 39 + return true if @primitives.include?(value) 40 + 22 41 types = @types 42 + 23 43 i, len = 0, types.size 24 44 while i < len 25 45 return true if types[i] === value ··· 62 82 @types.any? do |type| 63 83 Literal.subtype?(other, of: type) 64 84 end 65 - end 66 - end 67 - 68 - private 69 - 70 - def load_types(types) 71 - types.each do |type| 72 - (Literal::Types::UnionType === type) ? load_types(type.types) : @types << type 73 85 end 74 86 end 75 87
+13
test/types.test.rb
··· 755 755 assert_equal type.inspect, "_Union([String, Integer, Symbol, Float])" 756 756 end 757 757 758 + test "_Union with primitives" do 759 + position = _Union(:top, :right, :bottom, :left, Integer) 760 + 761 + assert position === :top 762 + assert position === :right 763 + assert position === :bottom 764 + assert position === :left 765 + assert position === 42 766 + 767 + refute position === :center 768 + refute position === "top" 769 + end 770 + 758 771 test "_Void" do 759 772 Fixtures::Objects.each do |object| 760 773 assert _Void === object