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
208 changes: 208 additions & 0 deletions internal/vm/range_bsearch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import (
"math"

"github.com/go-embedded-ruby/ruby/internal/object"
)

// bsearchProbe evaluates a bsearch block for one candidate value and reports how
// the search should proceed: smaller narrows to the lower half, exact is a
// find-any hit (the block returned 0), and satisfied marks a find-minimum match
// (the block returned true). A block result that is neither numeric, true, false
// nor nil is a TypeError. Shared by Array#bsearch and Range#bsearch.
func (vm *VM) bsearchProbe(blk *Proc, val object.Value) (smaller, exact, satisfied bool) {
switch v := vm.callBlock(blk, []object.Value{val}).(type) {
case object.Bool:
if bool(v) {
return true, false, true
}
return false, false, false
case object.Nil:
return false, false, false
default:
rv := object.Value(v)
if !isNumericValue(rv) {
raise("TypeError", "wrong argument type %s (must be numeric, true, false or nil)", vm.classOf(rv).name)
}
switch c := vm.spaceship(rv, object.IntValue(0)); {
case c == 0:
return false, true, false
case c < 0:
return true, false, false
default:
return false, false, false
}
}
}

// bsearchMid returns ⌊(low+high)/2⌋ without overflowing when the two ends span
// more than half the int64 range — as the ordered-bits domain of a float bsearch
// crossing zero does. It computes the distance in unsigned arithmetic.
func bsearchMid(low, high int64) int64 {
return int64(uint64(low) + (uint64(high)-uint64(low))>>1)
}

// bsearchNumeric reports whether v is a valid Range#bsearch bound: an Integer,
// Bignum or Float. nil (a beginless/endless bound) is handled separately.
func bsearchNumeric(v object.Value) bool {
switch v.(type) {
case object.Integer, *object.Bignum, object.Float:
return true
}
return false
}

// rangeBsearch implements Range#bsearch. An all-integer range searches the
// integer domain directly; a range with any Float bound searches the IEEE-754
// bit domain (which orders ±Infinity and Float::MAX correctly). Beginless and
// endless ranges probe outward for a finite bracket first.
func (vm *VM) rangeBsearch(r *object.Range, blk *Proc) object.Value {
// The bounds were validated as numeric by the Range#bsearch entry point; a
// Float bound selects the bit-domain search, anything else the integer one.
_, loFloat := r.Lo.(object.Float)
_, hiFloat := r.Hi.(object.Float)
if loFloat || hiFloat {
return vm.rangeBsearchFloat(r, blk)
}
return vm.rangeBsearchInt(r, blk)
}

// bsearchInt64 narrows an integer (Integer or Bignum) bound to an int64 for the
// integer bsearch domain.
func bsearchInt64(v object.Value) int64 {
b, _ := object.BigOf(v)
return b.Int64()
}

// rangeBsearchInt searches an integer range (both bounds Integer or nil).
func (vm *VM) rangeBsearchInt(r *object.Range, blk *Proc) object.Value {
// Resolve the [low, high) half-open integer interval, growing an unbounded
// end (or beginning) outward until the predicate brackets a finite range.
var low, high int64
if object.IsNil(r.Lo) {
// Beginless: walk the lower bound down (geometrically) until the target is
// no longer at/below it, i.e. the block stops narrowing to the left.
high = intBoundInclusiveEnd(r) + 1
low = high - 1
for diff := int64(1); ; diff *= 2 {
if s, x, _ := vm.bsearchProbe(blk, object.IntValue(low)); x {
return object.IntValue(low)
} else if !s {
break // the target, if any, is above low
}
low -= diff
}
} else {
low = bsearchInt64(r.Lo)
if object.IsNil(r.Hi) {
// Endless: grow the upper bound (geometrically) until the target is
// bracketed (the block narrows to the left) or found exactly.
high = low
for diff := int64(1); ; diff *= 2 {
if s, x, _ := vm.bsearchProbe(blk, object.IntValue(high)); x {
return object.IntValue(high)
} else if s {
break
}
high += diff
}
high++ // make the bracket half-open
} else {
high = intBoundInclusiveEnd(r) + 1
}
}
satisfied := false
for low < high {
mid := bsearchMid(low, high)
smaller, exact, sat := vm.bsearchProbe(blk, object.IntValue(mid))
if exact {
return object.IntValue(mid)
}
if sat {
satisfied = true
}
if smaller {
high = mid
} else {
low = mid + 1
}
}
if satisfied {
return object.IntValue(low)
}
return object.NilV
}

// intBoundInclusiveEnd returns the last integer contained in an integer range
// (r.Hi adjusted for an exclusive end).
func intBoundInclusiveEnd(r *object.Range) int64 {
end := bsearchInt64(r.Hi)
if r.Exclusive {
end--
}
return end
}

// rangeBsearchFloat searches a range with a Float bound over the IEEE-754 bit
// domain, mapping doubles to a monotonic int64 so binary search works across the
// sign boundary and out to ±Infinity.
func (vm *VM) rangeBsearchFloat(r *object.Range, blk *Proc) object.Value {
lo := math.Inf(-1)
if !object.IsNil(r.Lo) {
lo, _ = toFloat(r.Lo)
}
hi := math.Inf(1)
if !object.IsNil(r.Hi) {
hi, _ = toFloat(r.Hi)
}
low := floatToOrderedInt(lo)
high := floatToOrderedInt(hi)
if !r.Exclusive {
high++ // include the endpoint: search the half-open [low, high)
}
satisfied := false
for low < high {
mid := bsearchMid(low, high)
smaller, exact, sat := vm.bsearchProbe(blk, object.Float(orderedIntToFloat(mid)))
if exact {
return object.Float(orderedIntToFloat(mid))
}
if sat {
satisfied = true
}
if smaller {
high = mid
} else {
low = mid + 1
}
}
if satisfied {
return object.Float(orderedIntToFloat(low))
}
return object.NilV
}

// floatToOrderedInt maps a float64 to an int64 whose natural ordering matches the
// float ordering (so a binary search over the int64s walks the doubles in
// order), as MRI's double_as_int64 does.
func floatToOrderedInt(d float64) int64 {
i := int64(math.Float64bits(d))
if i < 0 {
return math.MinInt64 - i
}
return i
}

// orderedIntToFloat is the inverse of floatToOrderedInt (the transform is its own
// inverse).
func orderedIntToFloat(i int64) float64 {
if i < 0 {
i = math.MinInt64 - i
}
return math.Float64frombits(uint64(i))
}
68 changes: 68 additions & 0 deletions internal/vm/range_bsearch_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright (c) the go-embedded-ruby/ruby authors
//
// SPDX-License-Identifier: BSD-3-Clause

package vm

import "testing"

// TestRangeBsearch covers Range#bsearch: the find-minimum (true/false block) and
// find-any (numeric block) modes over integer and float ranges, inclusive vs
// exclusive endpoints, empty and reversed ranges, endless and beginless ranges,
// infinity bounds, the no-block Enumerator (with a nil #size), and the
// TypeErrors for a non-numeric bound or block result. Verified against ruby
// 4.0.6.
func TestRangeBsearch(t *testing.T) {
cases := []struct{ src, want string }{
// Integer, find-minimum.
{`p (0..10).bsearch { |x| x >= 5 }`, `5`},
{`p (0..10).bsearch { |x| x >= 100 }`, `nil`},
{`p (0..10).bsearch { |x| true }`, `0`},
{`p (0..10).bsearch { |x| false }`, `nil`},
// Integer, find-any.
{`p (0..10).bsearch { |x| 5 - x }`, `5`},
{`p (0..10).bsearch { |x| 1 }`, `nil`},
{`p (0..10).bsearch { |x| -1 }`, `nil`},
// A nil block result behaves like false.
{`p (0..10).bsearch { |x| nil }`, `nil`},
// find-any exact hit while probing an endless / beginless bound, and a float.
{`p (5..).bsearch { |x| 5 - x }`, `5`},
{`p (..10).bsearch { |x| 10 - x }`, `10`},
{`p (2.0..2.0).bsearch { |x| 0 }`, `2.0`},
// A Bignum bound does not crash.
{`p (0..10**20).bsearch { |x| x >= 5 }`, `5`},
// Empty / reversed ranges.
{`p (0...0).bsearch { true }`, `nil`},
{`p (4..2).bsearch { true }`, `nil`},
// Exclusive end.
{`p (0...5).bsearch { |x| x >= 4 }`, `4`},
// Float, find-minimum, inclusive/exclusive endpoints.
{`p (1.0..3.0).bsearch { |x| x >= 3.0 }`, `3.0`},
{`p (0..4.2).bsearch { |x| x >= 2 }`, `2.0`},
{`p (-1.2..4.3).bsearch { |x| x >= 1 }`, `1.0`},
{`p (0.1...2.3).bsearch { |x| x > 3 }`, `nil`},
// Endless ranges.
{`p (1..).bsearch { |x| x >= 5 }`, `5`},
{`p (1.0..).bsearch { |x| x >= 5.5 }`, `5.5`},
// Beginless ranges.
{`p (..10).bsearch { |x| x >= 5 }`, `5`},
{`p (..5.0).bsearch { |x| x >= 2 }`, `2.0`},
// Infinity bounds.
{`p (0..Float::INFINITY).bsearch { |x| x >= 3 }`, `3.0`},
{`p (0..Float::INFINITY).bsearch { |x| x == Float::INFINITY }`, `Infinity`},
{`p (0...Float::INFINITY).bsearch { |x| x == Float::INFINITY }`, `nil`},
{`p (-Float::INFINITY..0).bsearch { |x| x >= -3 }`, `-3.0`},
// No-block Enumerator with a nil size.
{`p (0..1).bsearch.class`, `Enumerator`},
{`p (0..1).bsearch.size`, `nil`},
// TypeErrors.
{`begin; (0..1).bsearch { Object.new }; rescue TypeError => e; p e.class; end`, `TypeError`},
{`begin; ("a".."e").bsearch { true }; rescue TypeError => e; p e.message; end`, `"can't do binary search for String"`},
{`begin; ("a".."e").bsearch; 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")
}
}
}
17 changes: 17 additions & 0 deletions internal/vm/range_edges.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@ import (
// range-in-range variant) and Range#size (the endless/beginless/Float edges) are
// wired in the bootstrap itself and delegate to helpers defined here.
func (vm *VM) registerRangeEdges() {
// bsearch finds an element by binary search over the range's numeric domain
// (see rangeBsearch); without a block it returns an Enumerator.
vm.cRange.define("bsearch", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value {
r := self.(*object.Range)
// A non-numeric bound cannot be searched — MRI reports this even without a
// block, before returning the Enumerator.
for _, b := range []object.Value{r.Lo, r.Hi} {
if !object.IsNil(b) && !bsearchNumeric(b) {
raise("TypeError", "can't do binary search for %s", vm.classOf(b).name)
}
}
if blk == nil {
// bsearch has no meaningful element count, so its Enumerator #size is nil.
return enumForSized(self, "bsearch", func(*VM) object.Value { return object.NilV })
}
return vm.rangeBsearch(r, blk)
})
// reverse_each yields the elements from end down to begin. rbgo materialises
// the range forward (via rangeElems) and walks the slice backwards, so it
// requires a range that can be enumerated: an endless range (nil end) or a
Expand Down