Module: Carbon::Core::Integer::Ship Private

Included in:
Carbon::Core::Integer
Defined in:
lib/carbon/core/integer/ship.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Defines the "spaceship" function on all integers except booleans. The spaceship operator compares two integers, and returns three possible values depending on the order of the integers: 1 if the receiver (this) is greater than the right (other), 0 if this is equal to other, and -1 if this is less than other. This is useful for determining the order of things. This module defines a single function on all integers except boolean:

  • .<=><T: Carbon::Numeric>(self, other: T): Carbon::Int8

The function returns Carbon::Int8 because it is the smallest possible integer type that retains sign information.

Instance Method Summary collapse

Instance Method Details

#define_ship_function(left, right) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Defines the spaceship function (:<=>). The left and right integer types are given. The spaceship function works the same as the one in Ruby:

  • If the left value is less than the right value, return -1; otherwise,
  • If the left value is equal to the right value, return 0; otherwise,
  • The left value is greater than the right value, return 1.

Parameters:



33
34
35
36
37
38
39
40
# File 'lib/carbon/core/integer/ship.rb', line 33

def define_ship_function(left, right)
  return if left.size == 1 || right.size == 1
  function_name = left.name.call(:<=>, [left.name, right.name])
  Core.define(function: function_name) do |function|
    function[:return] = Carbon::Type("Carbon::Int8")
    define_ship_definition(left, right, function[:definition])
  end
end