Skip to content

Commit 1b6ec98

Browse files
committed
Don't add null bytes in serialize::json::Encoder::write_char
This fixes rust-lang#19514 using a two-line patch suggested by @lifthrasiir. The code snippet: ```rust extern crate serialize; fn main() { let s = serialize::json::encode(&'c'); println!("Encoded: {}, bytes: {}", s, s.as_bytes()); } ``` ...serialized 'c' as `[34, 99, 0, 0, 0, 34]` when it should have used `[34, 99, 34]`. A test case is included.
1 parent da83ad8 commit 1b6ec98

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/libserialize/json.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -367,8 +367,8 @@ fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
367367

368368
fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
369369
let mut buf = [0, .. 4];
370-
v.encode_utf8(&mut buf);
371-
escape_bytes(writer, &mut buf)
370+
let sz = v.encode_utf8(&mut buf).unwrap();
371+
escape_bytes(writer, buf[mut ..sz])
372372
}
373373

374374
fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
@@ -2413,7 +2413,7 @@ mod tests {
24132413
use super::StackElement::*;
24142414
use super::InternalStackElement::*;
24152415
use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2416-
StackElement, Stack, Encoder, Decoder};
2416+
StackElement, Stack, Encoder, Decoder, encode};
24172417
use std::{i64, u64, f32, f64, io};
24182418
use std::collections::TreeMap;
24192419
use std::num::Float;
@@ -2536,6 +2536,12 @@ mod tests {
25362536
assert_eq!(String("madoka".into_string()).to_pretty_str(), "\"madoka\"");
25372537
}
25382538

2539+
#[test]
2540+
fn test_write_char() {
2541+
// We don't have a corresponding Json type, so test this with 'encode'.
2542+
assert_eq!(encode(&'c'), "\"c\"");
2543+
}
2544+
25392545
#[test]
25402546
fn test_write_bool() {
25412547
assert_eq!(Boolean(true).to_string(), "true");

0 commit comments

Comments
 (0)