Skip to content

StringLiteral#to_i with a number kind #16469

@HertzDevil

Description

@HertzDevil

StringLiteral#to_i converts its receiver using String#to_i64? (due to #16467 the effective range is currently even smaller), yet number literals can certainly go over Int64's range. I propose adding a separate overload that accepts a number kind, i.e. the symbol that would be returned by NumberLiteral#kind:

module Crystal::Macros
  class StringLiteral
    # Similar to `String#to_i`.
    #
    # *kind* is the returned literal's type as returned by `NumberLiteral#kind`.
    # This type is always used, even if the numeric value of the string fits into
    # a smaller integer type's range.
    def to_i(kind : SymbolLiteral, base : NumberLiteral = 0) : NumberLiteral
    end
  end
end

{{ "123".to_i(:u64) }}                           # => 123_u64
{{ UInt64::MAX.to_number.stringify.to_i(:u64) }} # okay
{{ ("1" * 30).to_i(:i128) }}                     # okay
{{ "130".to_i(:i8) }}                            # error

Add a 👍 reaction to issues you find important.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions