pub struct TextChunk<'i> { /* private fields */ }
Expand description

An HTML text node chunk.

Since the rewriter operates on a streaming input with minimal internal buffering, HTML text node can be represented by multiple text chunks. The size of a chunk depends on multiple parameters, such as decoding buffer size and input chunk size.

It is up to a user of the rewriter to buffer content of chunks to get the whole text node content where desired. The last chunk in a text node can be determined by calling last_in_text_node method of the chunk.

Note that in the sequence "<span>red-<b>or</b>-blue</span>" the span element contains three text nodes: "red-", "or", and "-blue". Each of these can produce multiple text chunks and each will produce one text chunk where last_in_text_node returns true. The last chunk in a text node can have empty textual content. To perform an action once on the text contents of an element, see Element::end_tag_handlers.

§Example

use lol_html::{HtmlRewriter, Settings, text};

let mut greeting = String::new();

{
    let mut rewriter = HtmlRewriter::new(
        Settings {
           element_content_handlers: vec![
               text!("div", |t| {
                 greeting += t.as_str();

                 if t.last_in_text_node() {
                        greeting += "!";
                    }

                    Ok(())
                })
            ],
            ..Settings::default()
        },
        |_:&[u8]| {}
    );

    rewriter.write(b"<div>He").unwrap();
    rewriter.write(b"llo w").unwrap();
    rewriter.write(b"orld</div>").unwrap();
    rewriter.end().unwrap();
}

assert_eq!(greeting, "Hello world!");

Implementations§

source§

impl<'i> TextChunk<'i>

source

pub fn as_str(&self) -> &str

Returns the textual content of the chunk.

source

pub fn as_mut_str(&mut self) -> &mut String

Returns the textual content of the chunk that the caller can modify. Note that this can cause the string to be allocated.

source

pub fn set_str(&mut self, text: String)

Sets the textual content of the chunk.

source

pub fn text_type(&self) -> TextType

Returns the type of the text in the chunk.

The type of the text depends on the surrounding context of the text. E.g. regular visible text and text inside a <script> element will have different types. Refer to TextType for more information about possible text types.

§Example
use lol_html::{rewrite_str, text, RewriteStrSettings};
use lol_html::html_content::TextType;

let html = rewrite_str(
    r#"<div>Hello</div><script>"use strict";</script>"#,
    RewriteStrSettings {
        element_content_handlers: vec![
            text!("div", |t| {
                assert_eq!(t.text_type(), TextType::Data);

                Ok(())
            }),
            text!("script", |t| {
                assert_eq!(t.text_type(), TextType::ScriptData);

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();
source

pub fn last_in_text_node(&self) -> bool

Returns true if the chunk is last in a HTML text node.

Note that last chunk can have empty textual content.

source

pub fn before(&mut self, content: &str, content_type: ContentType)

Inserts content before the text chunk.

Consequent calls to the method append content to the previously inserted content.

§Example
use lol_html::{rewrite_str, text, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div>world</div>"#,
    RewriteStrSettings {
        element_content_handlers: vec![
            text!("div", |t| {
                if !t.last_in_text_node(){
                    t.before("<!-- 42 -->", ContentType::Html);
                    t.before("Hello ", ContentType::Text);
                }

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div><!-- 42 -->Hello world</div>"#);
source

pub fn after(&mut self, content: &str, content_type: ContentType)

Inserts content after the text chunk.

Consequent calls to the method prepend content to the previously inserted content.

§Example
use lol_html::{rewrite_str, text, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div>Foo</div>"#,
    RewriteStrSettings {
        element_content_handlers: vec![
            text!("div", |t| {
                if t.last_in_text_node(){
                    t.after("Bar", ContentType::Text);
                    t.after("Qux", ContentType::Text);
                }

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div>FooQuxBar</div>"#);
source

pub fn replace(&mut self, content: &str, content_type: ContentType)

Replaces the text chunk with the content.

Consequent calls to the method overwrite previous replacement content.

§Example
use lol_html::{rewrite_str, text, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div>Foo</div>"#,
    RewriteStrSettings {
        element_content_handlers: vec![
            text!("div", |t| {
                if !t.last_in_text_node(){
                    t.replace("Bar", ContentType::Text);
                    t.replace("Qux", ContentType::Text);
                }

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div>Qux</div>"#);
source

pub fn remove(&mut self)

Removes the text chunk.

source

pub fn removed(&self) -> bool

Returns true if the text chunk has been replaced or removed.

Trait Implementations§

source§

impl Debug for TextChunk<'_>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl UserData for TextChunk<'_>

source§

fn user_data(&self) -> &dyn Any

Returns a reference to the attached user data.
source§

fn user_data_mut(&mut self) -> &mut dyn Any

Returns a mutable reference to the attached user data.
source§

fn set_user_data(&mut self, data: impl Any)

Attaches user data to a rewritable unit.

Auto Trait Implementations§

§

impl<'i> !RefUnwindSafe for TextChunk<'i>

§

impl<'i> !Send for TextChunk<'i>

§

impl<'i> !Sync for TextChunk<'i>

§

impl<'i> Unpin for TextChunk<'i>

§

impl<'i> !UnwindSafe for TextChunk<'i>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.