Skip to content

Commit

Permalink
added tohexstring() builtin
Browse files Browse the repository at this point in the history
  • Loading branch information
Ladislav Slezak committed May 6, 2013
1 parent b178ba8 commit 20ce36c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/ruby/ycp/builtins.rb
Original file line number Diff line number Diff line change
Expand Up @@ -837,8 +837,30 @@ def self.toascii
# Converts an integer to a hexadecimal string.
# - tohexstring(<int>)
# - tohexstring(<int>, <int>width)
def self.tohexstring
raise "Builtin tohexstring() is not implemented yet"
def self.tohexstring int, width = 0
return nil if int.nil? || width.nil?

if int >= 0
sprintf("0x%0#{width}x", int)
else
# compatibility for negative numbers
# Ruby: -3 => '0x..fd'
# YCP: -3 => '0xfffffffffffffffd' (64bit integer)

# this has '..fff' prefix
ret = sprintf("%018x", int)

# pad with zeroes or spaces if needed
if width > 16
ret.insert(2, "0" * (width - 16))
elsif width < -16
ret << (" " * (-width - 16))
end

# replace the ".." prefix by "0x"
ret[0..1] = "0x"
ret
end
end

# tolower() YCP built-in
Expand Down
26 changes: 26 additions & 0 deletions tests/ruby/builtins_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,32 @@ def test_regexptokenize
assert_equal nil, YCP::Builtins.regexptokenize("aaabbb", "(.*ba).*(");
end

def test_tohexstring
assert_equal nil, YCP::Builtins.tohexstring(nil)
assert_equal nil, YCP::Builtins.tohexstring(nil, nil)
assert_equal "0x0", YCP::Builtins.tohexstring(0)
assert_equal "0xa", YCP::Builtins.tohexstring(10)
assert_equal "0xff", YCP::Builtins.tohexstring(255)
assert_equal "0x3640e", YCP::Builtins.tohexstring(222222)

assert_equal "0x1f", YCP::Builtins.tohexstring(31, 0)
assert_equal "0x1f", YCP::Builtins.tohexstring(31, 1)
assert_equal "0x001f", YCP::Builtins.tohexstring(31, 4)
assert_equal "0x00001f", YCP::Builtins.tohexstring(31, 6)

assert_equal "0x1f", YCP::Builtins.tohexstring(31, -1)
assert_equal "0x1f ", YCP::Builtins.tohexstring(31, -3)

assert_equal "0xfffffffffffffffd", YCP::Builtins.tohexstring(-3)
assert_equal "0xfffffffffffffffd", YCP::Builtins.tohexstring(-3, 5)
assert_equal "0x00fffffffffffffffd", YCP::Builtins.tohexstring(-3, 18)
assert_equal "0x000000fffffffffffffffd", YCP::Builtins.tohexstring(-3, 22)

assert_equal "0xfffffffffffffffd", YCP::Builtins.tohexstring(-3, -16)
assert_equal "0xfffffffffffffffd ", YCP::Builtins.tohexstring(-3, -17)
assert_equal "0xfffffffffffffffd ", YCP::Builtins.tohexstring(-3, -22)
end

def test_tolower
assert_equal nil, YCP::Builtins.tolower(nil)
assert_equal "", YCP::Builtins.tolower("")
Expand Down

0 comments on commit 20ce36c

Please sign in to comment.