@@ -68,8 +68,10 @@ pub fn writeString(w: *Writer, s: []const u8, o: Options) Writer.Error!void {
6868 try w .print ("\\ u{x:0>4}" , .{c });
6969 i += 1 ;
7070 } else {
71- const n = std .unicode .utf8ByteSequenceLength (c ) catch 1 ;
72- const code = decodeWtf8 (s [i .. @min (s .len , i + n )]);
71+ // a sequence cut short at the string's end is U+FFFD and consumes only the bytes that are there
72+ const full = std .unicode .utf8ByteSequenceLength (c ) catch 1 ;
73+ const n = @min (full , s .len - i );
74+ const code = if (n < full ) 0xfffd else decodeWtf8 (s [i .. i + n ]);
7375 if (code >= 0x10000 ) {
7476 const v = code - 0x10000 ;
7577 try w .print ("\\ u{x:0>4}\\ u{x:0>4}" , .{ 0xd800 + (v >> 10 ), 0xdc00 + (v & 0x3ff ) });
@@ -171,3 +173,14 @@ test "dumps" {
171173 try std .testing .expectEqualStrings ("{\" a\" : [1, 2.5, \" \\ u00e9\\ n\\ ud83d\\ ude00\\ u007f\" ], \" b\" : {}, \" c\" : 0}" , try json .stringify (a , r .ok , .{}));
172174 try std .testing .expectEqualStrings ("{\" a\" :[1,2.5,\" \xc3\xa9 \\ n\xf0\x9f\x98\x80\x7f \" ],\" b\" :{},\" c\" :0}" , try json .stringify (a , r .ok , .{ .ascii = false , .compact = true }));
173175}
176+
177+ test "a UTF-8 sequence cut short at the string's end is U+FFFD, not a slice past it" {
178+ var buf : [64 ]u8 = undefined ;
179+ for ([_ ]struct { []const u8 , []const u8 }{
180+ .{ "ab\xE2 " , "\" ab\\ ufffd\" " }, .{ "ab\xE2\x82 " , "\" ab\\ ufffd\" " }, .{ "\xF0\x9F\x98 " , "\" \\ ufffd\" " }, .{ "x\xE2\x82\xAC " , "\" x\\ u20ac\" " },
181+ }) | c | {
182+ var w : Writer = .fixed (& buf );
183+ try writeString (& w , c [0 ], .{});
184+ try std .testing .expectEqualStrings (c [1 ], w .buffered ());
185+ }
186+ }
0 commit comments