Skip to content

Commit

Permalink
Fixed YCP compatibility in Builtins.tointeger()
Browse files Browse the repository at this point in the history
tointeger("") or tointeger("foo") should return nil, Ruby returns 0,
handle also the weird YCP cases like " 0x20" (-> 0) or " 020" (-> 20)
  • Loading branch information
Ladislav Slezak committed Jun 13, 2013
1 parent 161af1b commit 7534c6f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/ruby/ycp/builtins.rb
@@ -1,4 +1,5 @@
require "set"
require "scanf"

require "ycp/ycp"
require "ycp/path"
Expand Down Expand Up @@ -297,8 +298,16 @@ def self.tointeger object
return nil if object.nil?

case object
when ::String
# ideally this should be enought: object.scanf("%i").first
# but to be 100% YCP compatible we need to do this,
# see https://github.com/yast/yast-core/blob/master/libycp/src/YCPInteger.cc#L39
if object[0] == "0"
return object.scanf((object[1] == "x") ? "%x" : "%o").first
end
object.scanf("%d").first
# use full qualified ::Float to avoid clash with YCP::Builtins::Float
when ::String, ::Float, ::Fixnum, ::Bignum
when ::Float, ::Fixnum, ::Bignum
object.to_i
else
nil
Expand Down
15 changes: 15 additions & 0 deletions tests/ruby/builtins_test.rb
Expand Up @@ -347,9 +347,24 @@ def test_srandom

def test_tointeger()
assert_equal nil, YCP::Builtins.tointeger(nil)
assert_equal nil, YCP::Builtins.tointeger("")
assert_equal nil, YCP::Builtins.tointeger("foo")
assert_equal 120, YCP::Builtins.tointeger(120)
assert_equal 120, YCP::Builtins.tointeger("120")
assert_equal 120, YCP::Builtins.tointeger(" 120asdf")
assert_equal 120, YCP::Builtins.tointeger(120.0)
assert_equal 32, YCP::Builtins.tointeger("0x20")
assert_equal 0, YCP::Builtins.tointeger(" 0x20")
assert_equal 32, YCP::Builtins.tointeger("0x20Z")
assert_equal 8, YCP::Builtins.tointeger("010")
assert_equal -10, YCP::Builtins.tointeger("-10")

# weird YCP cases
assert_equal 0, YCP::Builtins.tointeger("-0x20")
assert_equal 0, YCP::Builtins.tointeger(" 0x20")
assert_equal 20, YCP::Builtins.tointeger(" 020")
assert_equal -20, YCP::Builtins.tointeger("-020")
assert_equal -20, YCP::Builtins.tointeger("-0020")
end

def test_search
Expand Down

0 comments on commit 7534c6f

Please sign in to comment.