Module: Emfsvg::Svg::PathData::Parser
- Defined in:
- lib/emfsvg/svg/path_data.rb
Overview
Stateful parser walks the string once, emitting Commands as enough args accumulate for the current letter. Implicit repeats: subsequent arg groups after M/m are treated as L/l.
Class Method Summary collapse
- .emit_command(commands, letter, args) ⇒ Object
- .flush_command(_commands, letter, args) ⇒ Object
-
.implicit_repeat_letter(letter) ⇒ Object
M/m repeats as L/l per SVG spec; all other commands repeat as themselves.
- .parse(string) ⇒ Object
Class Method Details
.emit_command(commands, letter, args) ⇒ Object
58 59 60 61 62 |
# File 'lib/emfsvg/svg/path_data.rb', line 58 def emit_command(commands, letter, args) raise FormatError, "unknown path command: #{letter}" unless ARG_COUNTS.key?(letter.upcase) commands << Command.new(letter: letter, args: args.dup) end |
.flush_command(_commands, letter, args) ⇒ Object
64 65 66 67 68 69 70 71 72 |
# File 'lib/emfsvg/svg/path_data.rb', line 64 def flush_command(_commands, letter, args) return unless letter return if args.empty? expected = ARG_COUNTS.fetch(letter.upcase, 0) return if args.size == expected raise FormatError, "path command #{letter} expected #{expected} args, got #{args.size}" end |
.implicit_repeat_letter(letter) ⇒ Object
M/m repeats as L/l per SVG spec; all other commands repeat as themselves.
76 77 78 79 80 81 82 |
# File 'lib/emfsvg/svg/path_data.rb', line 76 def implicit_repeat_letter(letter) case letter when "M" then "L" when "m" then "l" else letter end end |
.parse(string) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/emfsvg/svg/path_data.rb', line 23 def parse(string) return [] if string.nil? || string.empty? commands = [] scanner = Scanner.new(string) current_letter = nil args = [] while (token = scanner.next_token) case token when Symbol # command letter flush_command(commands, current_letter, args) if current_letter && args.any? current_letter = token.to_s args = [] # Zero-arg commands (Z/z) emit immediately. if ARG_COUNTS.fetch(current_letter.upcase, 1).zero? emit_command(commands, current_letter, []) current_letter = nil end when Numeric raise FormatError, "path data begins with a number: #{string.inspect}" if current_letter.nil? args << token if args.size == ARG_COUNTS.fetch(current_letter.upcase) emit_command(commands, current_letter, args) args = [] current_letter = implicit_repeat_letter(current_letter) end end end flush_command(commands, current_letter, args) if current_letter && args.any? commands end |