Skip to content

Commit

Permalink
Strings tagged binary will be emitted as binary. Fixes #27
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Sep 1, 2011
1 parent a7534c2 commit c9cd187
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.rdoc
@@ -1,3 +1,9 @@
Fri Sep 2 04:05:25 2011 Aaron Patterson <aaron@tenderlovemaking.com>

* ext/psych/lib/psych/visitors/yaml_tree.rb: emit strings tagged as
ascii-8bit as binary in YAML.
* test/psych/test_string.rb: corresponding test.

Thu Aug 25 06:11:35 2011 Aaron Patterson <aaron@tenderlovemaking.com>

* ext/psych/lib/psych/nodes/node.rb: default `to_yaml` encoding to be
Expand Down
9 changes: 8 additions & 1 deletion lib/psych/visitors/yaml_tree.rb
Expand Up @@ -214,12 +214,19 @@ def visit_Float o
end
end

def binary? string
string.encoding == Encoding::ASCII_8BIT ||
string.index("\x00") ||
string.count("\x00-\x7F", "^ -~\t\r\n").fdiv(string.length) > 0.3
end
private :binary?

def visit_String o
plain = false
quote = false
style = Nodes::Scalar::ANY

if o.index("\x00") || o.count("\x00-\x7F", "^ -~\t\r\n").fdiv(o.length) > 0.3
if binary?(o)
str = [o].pack('m').chomp
tag = '!binary' # FIXME: change to below when syck is removed
#tag = 'tag:yaml.org,2002:binary'
Expand Down
8 changes: 8 additions & 0 deletions test/psych/test_string.rb
Expand Up @@ -2,6 +2,14 @@

module Psych
class TestString < TestCase
def test_tagged_binary_should_be_dumped_as_binary
string = "hello world!"
string.force_encoding 'ascii-8bit'
yml = Psych.dump string
assert_match(/binary/, yml)
assert_equal string, Psych.load(yml)
end

def test_binary_string_null
string = "\x00"
yml = Psych.dump string
Expand Down

0 comments on commit c9cd187

Please sign in to comment.