Skip to content
Open
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
29 changes: 19 additions & 10 deletions lib/psych/scalar_scanner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,9 @@ def tokenize string
@symbol_cache[string] = class_loader.symbolize(string.sub(/^:/, ''))
end
elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$/)
i = 0
string.split(':').each_with_index do |n,e|
i += (n.to_i * 60 ** (e - 2).abs)
end
i
parse_sexagesimal(string, &:to_i)
elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$/)
i = 0
string.split(':').each_with_index do |n,e|
i += (n.to_f * 60 ** (e - 2).abs)
end
i
parse_sexagesimal(string, &:to_f)
elsif string.match?(FLOAT)
if string.match?(/\A[-+]?\.\Z/)
string
Expand All @@ -116,6 +108,23 @@ def tokenize string
end
end

###
# Parse and return a base 60 number from +string+, converting each
# component with the given block.
#
# The components are written most significant first, so a component's
# weight depends on how many follow it rather than on a fixed width, and
# the sign belongs to the value as a whole rather than to the first
# component alone.
def parse_sexagesimal string
components = string.split(':')
total = 0
components.each_with_index do |component, index|
total += yield(component).abs * 60 ** (components.length - 1 - index)
end
components.first.start_with?('-') ? -total : total
end

###
# Parse and return an int from +string+
def parse_int string
Expand Down
18 changes: 18 additions & 0 deletions test/psych/test_scalar_scanner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,24 @@ def test_scan_sexagesimal_int
assert_equal 685230, ss.tokenize('190:20:30')
end

def test_scan_sexagesimal_two_components
assert_equal 750, ss.tokenize('12:30')
assert_equal 750.5, ss.tokenize('12:30.5')
assert_equal 6000, ss.tokenize('100:00')
end

def test_scan_sexagesimal_negative
assert_equal(-750, ss.tokenize('-12:30'))
assert_equal(-45000, ss.tokenize('-12:30:00'))
assert_equal(-750.5, ss.tokenize('-12:30.5'))
end

def test_scan_sexagesimal_distinguishes_component_counts
# Different documents, so they must not resolve to the same value.
assert_equal 750, ss.tokenize('12:30')
assert_equal 45000, ss.tokenize('12:30:00')
end

def test_scan_float
assert_equal 1.2, ss.tokenize('1.2')
end
Expand Down