module Anthropic::Internal::Type::Union

def coerce(value, state:)

Returns:
  • (Object) -

Options Hash: (**state)
  • :branched (Integer) --
  • :exactness (Hash{Symbol=>Object}) --
  • :strictness (Boolean, :strong) --

Parameters:
  • state (Hash{Symbol=>Object}) -- .
  • value (Object) --

Other tags:
    Api: - private
def coerce(value, state:)
  if (target = resolve_variant(value))
    return Anthropic::Internal::Type::Converter.coerce(target, value, state: state)
  end
  strictness = state.fetch(:strictness)
  exactness = state.fetch(:exactness)
  state[:strictness] = strictness == :strong ? true : strictness
  alternatives = []
  known_variants.each do |_, variant_fn|
    target = variant_fn.call
    exact = state[:exactness] = {yes: 0, no: 0, maybe: 0}
    state[:branched] += 1
    coerced = Anthropic::Internal::Type::Converter.coerce(target, value, state: state)
    yes, no, maybe = exact.values
    if (no + maybe).zero? || (!strictness && yes.positive?)
      exact.each { exactness[_1] += _2 }
      state[:exactness] = exactness
      return coerced
    elsif maybe.positive?
      alternatives << [[-yes, -maybe, no], exact, coerced]
    end
  end
  case alternatives.sort_by(&:first)
  in []
    exactness[:no] += 1
    if strictness == :strong
      message = "no possible conversion of #{value.class} into a variant of #{target.inspect}"
      raise ArgumentError.new(message)
    end
    value
  in [[_, exact, coerced], *]
    exact.each { exactness[_1] += _2 }
    coerced
  end
    .tap { state[:exactness] = exactness }
ensure
  state[:strictness] = strictness
end