Class: Odin::Serialization::Canonicalize

Inherits:
Object
  • Object
show all
Defined in:
lib/odin/serialization/canonicalize.rb

Constant Summary collapse

RE_PATH_SPLIT =

Pre-compiled regex for splitting paths into segments

/(\[[^\]]*\])|\./.freeze
RE_ARRAY_INDEX =

Matches a pure-integer bracket segment like [0], [12]

/\A\[(\d+)\]\z/.freeze

Instance Method Summary collapse

Instance Method Details

#canonicalize(doc) ⇒ Object



11
12
13
14
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
# File 'lib/odin/serialization/canonicalize.rb', line 11

def canonicalize(doc)
  entries = []

  # Collect metadata as $.key entries
  doc. do |key, value|
    entries << ["$.#{key}", value, nil]
  end

  # Collect all assignments (skip $.xxx already added from metadata)
  doc.each_assignment do |path, value|
    next if path.start_with?("$.")

    mods = doc.modifiers_for(path)
    entries << [path, value, mods]
  end

  return "" if entries.empty?

  # Pre-compute sort keys once, then sort by key (avoids repeated parsing)
  keyed = entries.map { |e| [canonical_sort_key(e[0]), e] }
  keyed.sort_by! { |k, _| k }

  # Build output
  output = +""
  keyed.each do |_, (path, value, mods)|
    output << path
    output << " = "
    output << Utils::FormatUtils.format_modifier_prefix(mods) if mods
    output << Utils::FormatUtils.format_canonical_value(value)
    output << "\n"
  end

  output
end