Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -2186,6 +2186,17 @@ func (vm *VM) bootstrap() {
return vm.tryConvert(args[0], cls, meth)
}}
}
// Integer.sqrt(n) returns the integer square root ⌊√n⌋; the argument is
// coerced via #to_int (so a Float or #to_int object works) and a negative
// value raises Math::DomainError.
vm.cInteger.smethods["sqrt"] = &Method{name: "sqrt", owner: vm.cInteger,
native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
n := vm.integerArg(args[0])
if n.Sign() < 0 {
raise("Math::DomainError", "Numerical argument is out of domain - \"isqrt\"")
}
return object.NormInt(new(big.Int).Sqrt(n))
}}
vm.cArray.define("first", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
a := self.(*object.Array)
if len(args) == 0 {
Expand Down Expand Up @@ -6520,6 +6531,26 @@ func (vm *VM) arrayAssoc(a *object.Array, key object.Value, idx int) object.Valu
return object.NilV
}

// integerArg coerces v to a big.Int for Integer.sqrt: an Integer or Bignum is
// used directly, any other value is converted via #to_int (so a Float or a
// user #to_int object works), and a value with no (Integer-returning) #to_int
// raises TypeError.
func (vm *VM) integerArg(v object.Value) *big.Int {
if b, ok := object.BigOf(v); ok {
return b
}
if vm.respondsToDynamic(v, "to_int") {
r := vm.send(v, "to_int", nil, nil)
if b, ok := object.BigOf(r); ok {
return b
}
raise("TypeError", "can't convert %s to Integer (%s#to_int gives %s)",
vm.classOf(v).name, vm.classOf(v).name, vm.classOf(r).name)
}
raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(v))
return nil
}

// tryConvert backs Array/Hash/String/Integer.try_convert: an object that is
// already a kind of target is returned unchanged; otherwise, if it responds to
// the named conversion method (#to_ary/#to_hash/#to_str/#to_int), that is called
Expand Down
42 changes: 42 additions & 0 deletions internal/vm/integer_sqrt_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import "testing"

// TestIntegerSqrt covers Integer.sqrt: the floored integer square root, exact
// squares, a Bignum argument and result, #to_int coercion of a Float and of a
// user object, the Math::DomainError for a negative argument, and the TypeError
// for a non-coercible argument (and a #to_int returning a non-Integer). Verified
// against ruby 4.0.6.
func TestIntegerSqrt(t *testing.T) {
cases := []struct{ src, want string }{
{`p Integer.sqrt(0)`, `0`},
{`p Integer.sqrt(1)`, `1`},
{`p Integer.sqrt(24)`, `4`},
{`p Integer.sqrt(25)`, `5`},
{`p Integer.sqrt(10)`, `3`},
{`p Integer.sqrt(10).is_a?(Integer)`, `true`},
// Bignum argument and result.
{`p Integer.sqrt(10**400) == 10**200`, `true`},
{`p Integer.sqrt(2**128).class`, `Integer`},
// #to_int coercion: a Float (truncated) and a user object.
{`p Integer.sqrt(10.0)`, `3`},
{`p Integer.sqrt(10.9)`, `3`},
{`class K; def to_int; 25; end; end; p Integer.sqrt(K.new)`, `5`},
// A negative argument raises Math::DomainError.
{`begin; Integer.sqrt(-4); rescue Math::DomainError => e; p e.message; end`,
`"Numerical argument is out of domain - \"isqrt\""`},
// A non-coercible argument, and a #to_int returning a non-Integer, raise TypeError.
{`begin; Integer.sqrt("test"); rescue TypeError => e; p e.class; end`, `TypeError`},
{`class Bad; def to_int; "x"; end; end
begin; Integer.sqrt(Bad.new); rescue TypeError => e; p e.class; end`, `TypeError`},
}
for _, c := range cases {
if got := eval(t, c.src); got != c.want+"\n" {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want+"\n")
}
}
}