rust-ammonia / ammonia

Repair and secure untrusted HTML
Apache License 2.0
524 stars 43 forks source link

Do not require `'static` to `UrlRelativeEvaluate` #176

Closed rhysd closed 1 year ago

rhysd commented 1 year ago

Fixes #175

With this patch, UrlRelative knows the outer lifetime 'a and is bound by it.

I confirmed that the following code works.

use ammonia::*;
use std::borrow::Cow;

struct Eval<'a>(&'a str);

impl<'a> UrlRelativeEvaluate<'a> for Eval<'a> {
    fn evaluate<'u>(&self, url: &'u str) -> Option<Cow<'u, str>> {
        let mut s = self.0.to_string();
        s.push_str(url);
        Some(Cow::Owned(s))
    }
}

fn main() {
    let prefix = "/prefix/".to_string();
    let eval = Eval(&prefix);

    let mut sanitizer = Builder::default();
    sanitizer.url_relative(UrlRelative::Custom(Box::new(eval)));
    let s = "<a href=\"foo\">link</a>".to_string();
    let s = sanitizer.clean(&s).to_string();
    println!("{}", s)
}

Output:

> cargo run
    Blocking waiting for file lock on build directory
   Compiling ammonia v3.3.0 (/Users/rhysd/Develop/github.com/rust-ammonia/ammonia)
    Finished dev [unoptimized + debuginfo] target(s) in 0.79s
     Running `target/debug/ammonia`
<a href="/prefix/foo" rel="noopener noreferrer">link</a>

Comparing with the code in #175, please notice UrlRelativeEvaluate is now bound as UrlRelativeEvaluate<'a>.

notriddle commented 1 year ago

bors r+

bors[bot] commented 1 year ago

Build succeeded: