@@ -41,6 +41,7 @@ pub struct YamlEmitter<'a> {
4141 writer : & ' a mut fmt:: Write ,
4242 best_indent : usize ,
4343 compact : bool ,
44+ escape_all_strings : bool ,
4445
4546 level : isize ,
4647}
@@ -117,6 +118,7 @@ impl<'a> YamlEmitter<'a> {
117118 best_indent : 2 ,
118119 compact : true ,
119120 level : -1 ,
121+ escape_all_strings : false ,
120122 }
121123 }
122124
@@ -137,6 +139,19 @@ impl<'a> YamlEmitter<'a> {
137139 self . compact
138140 }
139141
142+ /// Wrap all `YAML::String` nodes in double-quotes and escape special characters (if any),
143+ /// regardless of whether or not they contain special characters.
144+ ///
145+ /// This maintains typing, ensuring that `example: "0x00"` is not emitted as `example: 0x00`.
146+ pub fn escape_all_strings ( & mut self , escape_all_strings : bool ) {
147+ self . escape_all_strings = escape_all_strings
148+ }
149+
150+ /// Determine if this emitter will wrap all strings in double-quotes.
151+ pub fn is_escape_all_strings ( & self ) -> bool {
152+ self . escape_all_strings
153+ }
154+
140155 pub fn dump ( & mut self , doc : & Yaml ) -> EmitResult {
141156 // write DocumentStart
142157 writeln ! ( self . writer, "---" ) ?;
@@ -161,7 +176,7 @@ impl<'a> YamlEmitter<'a> {
161176 Yaml :: Array ( ref v) => self . emit_array ( v) ,
162177 Yaml :: Hash ( ref h) => self . emit_hash ( h) ,
163178 Yaml :: String ( ref v) => {
164- if need_quotes ( v) {
179+ if need_quotes ( v) | self . escape_all_strings {
165180 escape_str ( self . writer , v) ?;
166181 } else {
167182 write ! ( self . writer, "{}" , v) ?;
638653 assert_eq ! ( s, writer) ;
639654 }
640655
656+ #[ test]
657+ fn test_escape_all_strings ( ) {
658+ let s = r#"---
659+ example: "0x00""# ;
660+
661+ let docs = YamlLoader :: load_from_str ( & s) . unwrap ( ) ;
662+ let doc = & docs[ 0 ] ;
663+
664+ let mut wr = String :: new ( ) ;
665+ {
666+ let mut emitter = YamlEmitter :: new ( & mut wr) ;
667+ assert_eq ! ( emitter. is_escape_all_strings( ) , false ) ;
668+ emitter. dump ( doc) . unwrap ( ) ;
669+ }
670+
671+ assert_eq ! (
672+ wr,
673+ r#"---
674+ example: 0x00"#
675+ ) ;
676+
677+ let mut wr = String :: new ( ) ;
678+ {
679+ let mut emitter = YamlEmitter :: new ( & mut wr) ;
680+ emitter. escape_all_strings ( true ) ;
681+ assert_eq ! ( emitter. is_escape_all_strings( ) , true ) ;
682+ emitter. dump ( doc) . unwrap ( ) ;
683+ }
684+
685+ assert_eq ! (
686+ wr,
687+ r#"---
688+ "example": "0x00""#
689+ ) ;
690+ }
691+
641692}
0 commit comments