Skip to content

Commit

Permalink
Merge pull request #13 from tomascco:support-name-escaping
Browse files Browse the repository at this point in the history
Handle name escaping
  • Loading branch information
tomascco authored Dec 1, 2023
2 parents 88d68f2 + 35bd6bd commit 9cec203
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 8 deletions.
25 changes: 22 additions & 3 deletions lib/rubrik/document/serialize_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def [](obj)
serialized_objs = obj.flatten.map { |e| SerializeObject[e] }
"<<#{serialized_objs.join(" ")}>>"
when Symbol
"/#{obj}"
serialize_symbol(obj)
when Array
serialized_objs = obj.map { |e| SerializeObject[e] }
"[#{serialized_objs.join(" ")}]"
Expand Down Expand Up @@ -51,7 +51,7 @@ def [](obj)

private

ESCAPE_MAP = {
STRING_ESCAPE_MAP = {
"\n" => "\\\n",
"\r" => "\\\r",
"\t" => "\\\t",
Expand All @@ -64,7 +64,26 @@ def [](obj)

sig {params(string: String).returns(String)}
def serialize_string(string)
"(#{string.gsub(/[\n\r\t\b\f\\()]/n, ESCAPE_MAP)})"
"(#{string.gsub(/[\n\r\t\b\f\\()]/n, STRING_ESCAPE_MAP)})"
end

DELIMITERS = "()<>[]{}/%".bytes.freeze
REGULAR_CHARACTERS =
"!\"\#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".bytes.freeze


NAME_ESCAPE_CHARACTERS = (0..255).to_a - REGULAR_CHARACTERS + DELIMITERS + "#".bytes
NAME_ESCAPE_CHARACTERS.freeze

NAME_ESCAPE_MAP = NAME_ESCAPE_CHARACTERS.each_with_object({}) do |char, escape_map|
escape_map[char.chr] = "##{char.to_s(16).rjust(2, "0")}"
end.freeze

NAME_ESCAPE_REGEX = /[#{Regexp.escape(NAME_ESCAPE_CHARACTERS.map(&:chr).join)}]/

sig {params(symbol: Symbol).returns(String)}
def serialize_symbol(symbol)
"/#{symbol.to_s.b.gsub(NAME_ESCAPE_REGEX, NAME_ESCAPE_MAP)}"
end
end
end
Expand Down
22 changes: 17 additions & 5 deletions test/rubrik/document/serialize_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,23 @@ def test_hash_serialization
end

def test_symbol_serialization
# Act
result = SerializeObject[:Test]

# Assert
assert_equal("/Test", result)
# Act + Assert
[
["/Name1", :"Name1"],
["/ASomewhatLongerName", :"ASomewhatLongerName"],
["/A;Name_With-Various***Characters?", :"A;Name_With-Various***Characters?"],
["/1.2", :"1.2"],
["/$$", :"$$"],
["/@pattern", :"@pattern"],
["/.notdef", :".notdef"],
["/Lime#20Green", :"Lime Green"],
["/paired#28#29parentheses", :"paired()parentheses"],
["/The_Key_of_F#23_Minor", :"The_Key_of_F#_Minor"],
["/AB", :"AB"],
["/H#c3#b6#c3#9fgang", :"Hößgang"],
].each do |(expected, subject)|
assert_equal(expected, SerializeObject[subject])
end
end

def test_array_serialization
Expand Down
Binary file modified test/support/inline_interactive_form.expected.pdf
Binary file not shown.
Binary file modified test/support/inline_interactive_form.pdf
Binary file not shown.

0 comments on commit 9cec203

Please sign in to comment.