Skip to content

Commit

Permalink
Implement string escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
tomascco committed Dec 1, 2023
1 parent 11ce9fa commit fb1fdc1
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 6 deletions.
20 changes: 19 additions & 1 deletion lib/rubrik/document/serialize_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def [](obj)
when PDF::Reader::Reference
"#{obj.id} #{obj.gen} R"
when String
"(#{obj})"
serialize_string(obj)
when TrueClass
"true"
when FalseClass
Expand All @@ -48,6 +48,24 @@ def [](obj)
end

alias call []

private

ESCAPE_MAP = {
"\n" => "\\\n",
"\r" => "\\\r",
"\t" => "\\\t",
"\b" => "\\\b",
"\f" => "\\\f",
"\\" => "\\\\",
"(" => "\\(",
")" => "\\)"
}.freeze

sig {params(string: String).returns(String)}
def serialize_string(string)
"(#{string.gsub(/[\n\r\t\b\f\\()]/n, ESCAPE_MAP)})"
end
end
end
end
16 changes: 11 additions & 5 deletions test/rubrik/document/serialize_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,17 @@ def test_reference_serialization
end

def test_string_serialization
# Act
result = SerializeObject["Test"]

# Assert
assert_equal("(Test)", result)
# Act + Assert
[
["(Test)", "Test"],
["(Test\\))", "Test)"],
["(Test\\\n)", "Test\n"],
["(hello \\\f\\\b hi)", "hello \f\b hi"],
["(This is \\(\\)n inverted backslash \\\\)", "This is ()n inverted backslash \\"],
["(Really \\(\\) \\\r\\\n complicated\\\ttest)", "Really () \r\n complicated\ttest"]
].each do |(expected, subject)|
assert_equal(expected, SerializeObject[subject])
end
end

def test_booleans_serialization
Expand Down
Binary file modified test/support/indirect_annots.expected.pdf
Binary file not shown.
Binary file modified test/support/indirect_annots.pdf
Binary file not shown.

0 comments on commit fb1fdc1

Please sign in to comment.