Crate xmlsafe[][src]

Expand description

An XML writer that protects you from XML injections through type safety. If you forget to escape a string, your code just doesn’t compile. Contrary to other XML writing libraries xmlsafe doesn’t require you to escape everything: you get to choose. Furthermore xmlsafe never panics and avoids allocations by just writing to a std::fmt::Write.

xmlsafe introduces three marker traits to mark the XML safety of Display implementations. Please keep two things in mind:

  1. Whenever you supply a string literal (&'static str), take care that it is syntactically valid for the respective context.

  2. Whenever you implement one of the marker traits, take care that you fulfill its requirements.

Example

use std::fmt::{Error, Write};
use xmlsafe::{XmlWriter, format_text, escape_text};

fn write_greeting(w: XmlWriter, name: &str) -> Result<(), Error> {
    let mut w = w.open_start_tag("greeting")?.attr("id", 42)?.close()?;
    w.write(format_text!("Hello {}!", escape_text(name)))?;
    w.write_end_tag("greeting")?;
    Ok(())
}

fn main() {
    let mut out = String::new();
    write_greeting(XmlWriter::new(&mut out), "Ferris").unwrap();
    assert_eq!(out, "<greeting id=\"42\">Hello Ferris!</greeting>");
}

Note how the XmlWriter acts as a protective layer between the actual write target (the String in our example) and the XML generation code. Also note that if we forgot the escape_text call, the example would not compile.

Macros

Wraps format_args casting all arguments to AttValueSafe. The return value is wrapped to also implement AttValueSafe. Literal " and & characters in the format string must be escaped as &quot; and &amp;.

Wraps format_args casting all arguments to PcdataSafe. The return value is wrapped to also implement PcdataSafe. Literal < and & characters in the format string must be escaped as &lt; and &amp; respectively. Do NOT use this to build tags (instead use the secure methods from XmlWriter).

Structs

An XML attribute writer returned by XmlWriter::open_start_tag.

An XML writer that helps to prevent XML injections.

Traits

Types whose Display implementation can be safely embedded in double-quoted XML attribute values. Literal " and & characters must be escaped as &quot; and &amp; respectively.

Types whose Display implementation can be safely used as an XML name.

Types whose Display implementation can be safely embedded between XML tags. Literal < and & characters must be escaped as &lt; and &amp; respectively.

Functions

XML escape an untrusted string to make it AttValueSafe.

XML escape an untrusted string to make it PcdataSafe.