rtf-parser
A safe Rust RTF parser & lexer library designed for speed and memory efficiency, with no external dependencies.
It implements the last version of the RTF specification (1.9), with modern UTF-16 unicode support.
The official documentation is available at docs.rs/rtf-parser.
Installation
This library can be installed using cargo with the CLI :
Or adding rtf-parser = "<last-version>"
under [dependencies] in your Cargo.toml
.
Design
The library is split into 2 main components:
- The lexer
- The parser
The lexer scans the document and returns a Vec<Token>
which represent the RTF file in a code-understandable manner.
These tokens can then be passed to the parser to transcript it to a real document : RtfDocument
.
use Lexer;
use Token;
use Parser;
use RtfDocument;
or in a more concise way :
use RtfDocument;
The RtfDocument
struct implement the TryFrom
trait for :
&str
String
&mut std::fs::File
and a from_filepath
constructor that handle the i/o internally.
The error returned can be a LexerError
or a ParserError
depending on the phase wich failed.
An RtfDocument
is composed with :
- the header, containing among others the font table, the color table and the encoding.
- the body, which is a
Vec<StyledBlock>
A StyledBlock
contains all the information about the formatting of a specific block of text.
It contains a Painter
for the text style, a Paragraph
for the layout, and the text (String
).
The Painter
is defined below, and the rendering implementation depends on the user.
The layout information are exposed in the paragraph
property :
It defined the way a block is aligned, what spacing it uses, etc...
You also can extract the text without any formatting information, with the to_text()
method of the RtfDocument
struct.
Examples
A complete example of rtf parsing is presented below :
use Lexer;
use Parser;
Known limitations
For now, the \bin
keyword is not taken into account. As its content is text in binary format, it can mess with the lexing algorithm, and crash the program.
Future support for the binary will soon come.
The base64 images are not supported as well, but can safely be parsed.
Benchmark
For now, there is no comparable crates to rtf-parser
.
However, the rtf-grimoire
crate provide a similar Lexer. Here is a quick benchmark of the lexing and parsing of a 500kB rtf document.
Crate | Version | Duration |
---|---|---|
rtf-parser |
v0.3.0 | 7 ms |
rtf-grimoire (only lexing) |
v0.2.1 | 13 ms |
This benchmark has been run on an Intel MacBook Pro, with the release build.
For the rtf-parser
, most of the compute time (65 %) is spent by the lexing process. There is still lot of room for improvement.