Skip to main content

rustapi_toon/
lib.rs

1//! # TOON Format Support for RustAPI
2//!
3//! This crate provides [TOON (Token-Oriented Object Notation)](https://toonformat.dev/)
4//! support for the RustAPI framework. TOON is a compact, human-readable format
5//! designed for passing structured data to Large Language Models (LLMs) with
6//! significantly reduced token usage (typically 20-40% savings).
7//!
8//! ## Quick Example
9//!
10//! **JSON (16 tokens, 40 bytes):**
11//! ```json
12//! {
13//!   "users": [
14//!     { "id": 1, "name": "Alice" },
15//!     { "id": 2, "name": "Bob" }
16//!   ]
17//! }
18//! ```
19//!
20//! **TOON (13 tokens, 28 bytes) - 18.75% token savings:**
21//! ```text
22//! users[2]{id,name}:
23//!   1,Alice
24//!   2,Bob
25//! ```
26//!
27//! ## Usage
28//!
29//! Add to your `Cargo.toml`:
30//!
31//! ```toml
32//! [dependencies]
33//! rustapi-rs = { version = "0.1", features = ["toon"] }
34//! ```
35//!
36//! ### Toon Extractor
37//!
38//! Parse TOON request bodies:
39//!
40//! ```rust,ignore
41//! use rustapi_rs::prelude::*;
42//! use rustapi_rs::toon::Toon;
43//!
44//! #[derive(Deserialize)]
45//! struct CreateUser {
46//!     name: String,
47//!     email: String,
48//! }
49//!
50//! async fn create_user(Toon(user): Toon<CreateUser>) -> impl IntoResponse {
51//!     Json(user)
52//! }
53//! ```
54//!
55//! ### Toon Response
56//!
57//! Return TOON formatted responses:
58//!
59//! ```rust,ignore
60//! use rustapi_rs::prelude::*;
61//! use rustapi_rs::toon::Toon;
62//!
63//! #[derive(Serialize)]
64//! struct User {
65//!     id: u64,
66//!     name: String,
67//! }
68//!
69//! async fn get_user() -> Toon<User> {
70//!     Toon(User {
71//!         id: 1,
72//!         name: "Alice".to_string(),
73//!     })
74//! }
75//! ```
76//!
77//! ## Content Types
78//!
79//! - Request: `application/toon` or `text/toon`
80//! - Response: `application/toon`
81
82mod error;
83mod extractor;
84mod llm_response;
85mod negotiate;
86mod openapi;
87
88pub use error::ToonError;
89pub use extractor::Toon;
90pub use llm_response::{
91    LlmResponse, X_FORMAT_USED, X_TOKEN_COUNT_JSON, X_TOKEN_COUNT_TOON, X_TOKEN_SAVINGS,
92};
93pub use negotiate::{AcceptHeader, MediaTypeEntry, Negotiate, OutputFormat, JSON_CONTENT_TYPE};
94pub use openapi::{
95    api_description_with_toon, format_comparison_example, token_headers_schema, toon_extension,
96    toon_schema, TOON_FORMAT_DESCRIPTION,
97};
98
99// Re-export toon-format types for advanced usage
100pub use toon_format::{
101    decode, decode_default, encode, encode_default, DecodeOptions, EncodeOptions,
102};
103
104/// TOON Content-Type header value
105pub const TOON_CONTENT_TYPE: &str = "application/toon";
106
107/// Alternative TOON Content-Type (text-based)
108pub const TOON_CONTENT_TYPE_TEXT: &str = "text/toon";