Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
RECIPE 08 / 8

A library someone else can use.

Package a small text-analysis API with unit tests, integration tests, and rustdoc examples.

BY NAVAN SAMI~25 MIN BUILDLOCAL PROJECT
Download this project ↓
Standard libraryCargorustdoc

01 The shape of the build

A library is a public contract, not just code without a main function. This project defines named statistics and a deterministic word-frequency function, documents its tokenization policy, and exercises its API from a separate integration-test crate. Unit tests cover implementation behavior, while a documentation test shows the smallest useful call. The example binary demonstrates consumption without coupling the library to a UI or server. Keep publishing as a separate action: cargo package can inspect a distributable package without uploading it.

  1. 1

    Expose a Stats type with named byte, scalar, and word counts.

  2. 2

    Document that whitespace tokenization retains punctuation.

  3. 3

    Test the public API from tests/public_api.rs.

  4. 4

    Run the bundled example and generate local API documentation.

02 Get it running

Install Rust stable and extract this project’s ZIP. Run these commands from the extracted reusable-library folder. The full workbench keeps it under cookbook/reusable-library.

terminal
cargo test
cargo run --example report
cargo doc --no-deps
cargo package --allow-dirty
WHAT YOU SHOULD SEE

Tests include unit, integration, and documentation checks. The report prints bytes=9 scalars=9 words=2 for Rust Rust, followed by {"rust": 2}. cargo package creates a local archive without publishing it.

First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.

03 The complete source

Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.

Cargo.toml9 lines +
Cargo.toml
[package]
name = "build-lab-text"
version = "0.1.0"
edition = "2024"

[dependencies]


[workspace]
src/lib.rs44 lines +
src/lib.rs
use std::collections::BTreeMap;
#[derive(Debug, PartialEq, Eq)]
pub struct Stats {
    pub bytes: usize,
    pub scalars: usize,
    pub words: usize,
}
/// Count bytes, Unicode scalar values, and whitespace-separated words.
///
/// ```
/// let stats=build_lab_text::analyze("Rust Rust");
/// assert_eq!(stats.words,2);
/// ```
pub fn analyze(text: &str) -> Stats {
    Stats {
        bytes: text.len(),
        scalars: text.chars().count(),
        words: text.split_whitespace().count(),
    }
}
/// Lowercase whitespace-separated tokens. Punctuation is retained.
pub fn frequencies(text: &str) -> BTreeMap<String, usize> {
    let mut result = BTreeMap::new();
    for word in text.split_whitespace() {
        *result.entry(word.to_lowercase()).or_insert(0) += 1;
    }
    result
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn empty() {
        assert_eq!(
            analyze(""),
            Stats {
                bytes: 0,
                scalars: 0,
                words: 0
            }
        );
        assert!(frequencies("").is_empty());
    }
}
examples/report.rs8 lines +
examples/report.rs
fn main() {
    let stats = build_lab_text::analyze("Rust Rust");
    println!(
        "bytes={} scalars={} words={}",
        stats.bytes, stats.scalars, stats.words
    );
    println!("{:?}", build_lab_text::frequencies("Rust Rust"));
}
tests/public_api.rs9 lines +
tests/public_api.rs
use build_lab_text::{analyze, frequencies};
#[test]
fn public_contract() {
    let s = analyze("café");
    assert_eq!(s.bytes, 5);
    assert_eq!(s.scalars, 4);
    assert_eq!(s.words, 1);
    assert_eq!(frequencies("Rust RUST")["rust"], 2);
}

04 Check the behavior

  • □cargo test runs all three test styles.
  • □Empty text yields zero counts and no words.
  • □Accented text demonstrates the difference between bytes and scalars.
  • □The library can be imported by its package name from an integration test.

05 Know what you are building on

Word splitting is whitespace-only; punctuation stays attached and Unicode lowercase is not full case-folding.

This package is a learning artifact and is not published to crates.io.

Changing public types or semantics later needs an API compatibility decision.

MAKE IT YOUR OWN

Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.