Crate json_escape

Crate json_escape 

Source
Expand description

§Streaming JSON String Escape/Unescape

Welcome to a highly efficient, no_std compatible library for handling JSON string escaping and unescaping. This crate provides iterator-based tools that process strings on the fly, avoiding heap allocations for the entire result. It’s designed for performance-critical applications, such as parsing large JSON files or working in memory-constrained environments. ⚡

The core of the library is two iterator structs:

  • Escape: Takes a string slice (&str) and yields escaped string slices ready for JSON serialization.
  • Unescape: Takes a byte slice (&[u8]) representing the content of a JSON string and yields the decoded byte slices.

§Key Features

  • Zero-Copy Slicing: For sequences of characters that don’t need modification, the iterators yield slices that borrow directly from the input, avoiding unnecessary data copying.
  • Comprehensive JSON Support: Correctly handles all standard JSON escapes: \", \\, \/, \b, \f, \n, \r, \t.
  • Full Unicode Handling: Correctly decodes \uXXXX sequences, including full support for UTF-16 surrogate pairs (e.g., \uD83D\uDE00 for 😀).
  • Robust Error Handling: The Unescape iterator returns descriptive errors (UnescapeError) for invalid or truncated escape sequences, making debugging straightforward.
  • Allocation Control (with alloc feature): Provides convenient methods to collect the iterator’s output into owned types like String or Cow<str>.
  • std::io Integration (with std feature): The Unescape iterator implements std::io::Read, allowing it to be used as an efficient reader for I/O streams.

§Quick Start: Escaping a String

use json_escape::escape_str;

let input = "Hello, \"world\"!\nThis contains a \\ backslash.";
let expected = r#"Hello, \"world\"!\nThis contains a \\ backslash."#;

// The `escape_str` function returns an iterator.
let mut escaper = escape_str(input);

// You can iterate over the chunks:
assert_eq!(escaper.next(), Some("Hello, "));
assert_eq!(escaper.next(), Some(r#"\""#));
assert_eq!(escaper.next(), Some("world"));
// ...and so on.

// Or, collect it into a String (requires the "alloc" feature).
// let escaped_string: String = escape_str(input).collect();
// assert_eq!(escaped_string, expected);

§Quick Start: Unescaping a String

use json_escape::unescape;

let input = r#"A 😀 emoji: \uD83D\uDE00 and a tab\t!"#;

// The unescape iterator yields `Result<&[u8], _>`.
let unescaper = unescape(input);

// With the "alloc" feature, you can decode it directly into a string.
let decoded_cow = unescaper.decode_utf8().unwrap();
assert_eq!(decoded_cow, "A 😀 emoji: 😀 and a tab\t!");

§Performance and the explicit Module

This crate is designed for high-performance, zero-allocation escaping and unescaping. For most use cases, the functions in this root module provide the best balance of ergonomics and speed.

However, for users with extreme performance requirements, the explicit module is provided. Its iterators yield structured Chunk data instead of simple slices. As shown by benchmarks, this approach can be slightly faster, especially on inputs with a high density of escape sequences. If you are processing a very large volume of JSON strings in a tight loop, consider using the explicit module for a potential performance boost.

Modules§

explicit
More explicit and fine-grained iterators for JSON escaping and unescaping.

Structs§

DisplayUnescape
A wrapper for an Unescape iterator that implements fmt::Display.
DisplayUnescapeLossy
A wrapper for an Unescape iterator that implements fmt::Display lossily.
Escape
A streaming JSON string escaper that yields &'a str slices.
InvalidEscapeError
Details of an invalid escape sequence error.
InvalidHexError
Details of an invalid hex digit error within a \uXXXX sequence.
LoneSurrogateError
Details of a lone UTF-16 surrogate error.
Unescape
A streaming JSON string unescaper.
UnescapeError
An error that can occur during the JSON string unescaping process.

Enums§

DecodeUtf8Error
An error that can occur when decoding the final byte stream to a UTF-8 string.
UnescapeErrorKind
The specific kind of error that can occur during JSON string unescaping.

Functions§

escape_str
Creates a streaming JSON string escaper from a string slice.
unescape
Creates a streaming JSON string unescaper from a byte slice.
unescape_quoted
Creates a streaming JSON string unescaper, trimming enclosing quotes.