Module: T::Types::Union::Private::Pool

Defined in:
lib/types/types/union.rb

Class Method Summary collapse

Class Method Details

.union_of_types(type_a, type_b, types = EMPTY_ARRAY) ⇒ Object

Try to use ‘to_nilable` on a type to get memoization, or failing that try to at least use SimplePairUnion to get faster init and typechecking.

We aren’t guaranteed to detect a simple ‘T.nilable(<Module>)` type here in cases where there are duplicate types, nested unions, etc.

That’s ok, because returning is SimplePairUnion an optimization which isn’t necessary for correctness.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/types/types/union.rb', line 95

def self.union_of_types(type_a, type_b, types=EMPTY_ARRAY)
  if !types.empty?
    # Slow path
    return Union.new([type_a, type_b] + types)
  elsif !type_a.is_a?(T::Types::Simple) || !type_b.is_a?(T::Types::Simple)
    # Slow path
    return Union.new([type_a, type_b])
  end

  begin
    if type_b == T::Utils::Nilable::NIL_TYPE
      type_a.to_nilable
    elsif type_a == T::Utils::Nilable::NIL_TYPE
      type_b.to_nilable
    else
      T::Private::Types::SimplePairUnion.new(type_a, type_b)
    end
  rescue T::Private::Types::SimplePairUnion::DuplicateType
    # Slow path
    #
    # This shouldn't normally be possible due to static checks,
    # but we can get here if we're constructing a type dynamically.
    #
    # Relying on the duplicate check in the constructor has the
    # advantage that we avoid it when we hit the memoized case
    # of `to_nilable`.
    type_a
  end
end