From fb1fdc1c100f4a7e7c89e6118c02440f3b9ad6af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Co=C3=AAlho?= Date: Fri, 1 Dec 2023 01:56:53 +0000 Subject: [PATCH] Implement string escaping --- lib/rubrik/document/serialize_object.rb | 20 +++++++++++++++++- test/rubrik/document/serialize_object_test.rb | 16 +++++++++----- test/support/indirect_annots.expected.pdf | Bin 9347 -> 9383 bytes test/support/indirect_annots.pdf | Bin 619 -> 636 bytes 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/lib/rubrik/document/serialize_object.rb b/lib/rubrik/document/serialize_object.rb index 2219e9c..4d7a4aa 100644 --- a/lib/rubrik/document/serialize_object.rb +++ b/lib/rubrik/document/serialize_object.rb @@ -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 @@ -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 diff --git a/test/rubrik/document/serialize_object_test.rb b/test/rubrik/document/serialize_object_test.rb index 92f9de9..e8bd523 100644 --- a/test/rubrik/document/serialize_object_test.rb +++ b/test/rubrik/document/serialize_object_test.rb @@ -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 diff --git a/test/support/indirect_annots.expected.pdf b/test/support/indirect_annots.expected.pdf index a4deb76536e81b266803fc8a65d00bef461708f2..2873a8cdf2cb02f56c80b2cfd0cdf9853d223e21 100644 GIT binary patch delta 179 zcmZqnT<*D{jZsiRKP0udL_s6Cq$o2lT|-lIavS4PCPVYdx=f}_#-@`~n4E=C)x>DT zXlia=&QzqpVPR;bU}<1rHd#^mwwHEb9OO delta 137 zcmZ4P+3dNYjdAjH#-&UK29xcWOqmQVCYLffZ$8abq`+ZrZl+*iX>KstRr$7^k%58% z2q@$!aDf>HmWC$g=wb$DmYC`cj4UU|spv}?TG-if6_+Fyl~fd^rg2#snj3Pds=E5S GaRC6IQz3=` diff --git a/test/support/indirect_annots.pdf b/test/support/indirect_annots.pdf index 924186e66778161b905542a0fdba30100b8e0fb9..5026e4a3974f3c73d70dc8026b99b3c80cbdbf16 100644 GIT binary patch delta 46 zcmaFO@`q(Z8>66ten@I@iGoIONl|8Ax`w9a