Module: Postsvg::Svg::PathData::Parser
- Defined in:
- lib/postsvg/svg/path_data/parser.rb
Overview
Tokenizer + parser for SVG path data. Handles the standard grammar from SVG 1.1 ยง8.3. Output is a list of Command value objects with normalized argument counts.
Constant Summary collapse
- COMMAND_RE =
/([MmLlHhVvCcSsQqTtAaZz])/- ARG_RE =
/(-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)/.freeze
- NUMBER_ONLY_RE =
/\A-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?\z/.freeze
Class Method Summary collapse
- .arity_for(opcode) ⇒ Object
- .parse(text) ⇒ Object
- .take_args(tokens, start, count) ⇒ Object
- .tokenize(text) ⇒ Object
Class Method Details
.arity_for(opcode) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/postsvg/svg/path_data/parser.rb', line 47 def arity_for(opcode) case opcode.upcase when "M", "L", "T" then 2 when "H", "V" then 1 when "C" then 6 when "S", "Q" then 4 when "A" then 7 when "Z" then 0 else 0 end end |
.parse(text) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/postsvg/svg/path_data/parser.rb', line 15 def parse(text) return [] if text.nil? || text.empty? commands = [] tokens = tokenize(text) i = 0 while i < tokens.length opcode = tokens[i] i += 1 arity = arity_for(opcode) if arity.zero? commands << Command.new(opcode: opcode, args: []) next end # Repeat: M / L / C etc. can have multiple coordinate # tuples after a single opcode. Consume in groups of arity. loop do args, consumed = take_args(tokens, i, arity) break unless consumed == arity commands << Command.new(opcode: opcode, args: args) i += consumed # After moveto, implicit lineto for subsequent tuples. opcode = (opcode == "M") ? "L" : (opcode == "m" ? "l" : opcode) # For H/V/Z, no implicit repetition. break if %w[H V Z h v z].include?(opcode) end end commands end |
.take_args(tokens, start, count) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/postsvg/svg/path_data/parser.rb', line 67 def take_args(tokens, start, count) args = [] consumed = 0 while consumed < count && start + consumed < tokens.length tok = tokens[start + consumed] break unless NUMBER_ONLY_RE.match?(tok.to_s) args << tok.to_f consumed += 1 end [args, consumed] end |
.tokenize(text) ⇒ Object
59 60 61 62 63 |
# File 'lib/postsvg/svg/path_data/parser.rb', line 59 def tokenize(text) text.to_s.gsub(/-/, " -") .scan(/([MmLlHhVvCcSsQqTtAaZz])|(-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)/) .flatten.compact end |