TExcelTAD
Home › Cargo in Depth › Mini Project: Workspace, C Library & Private Registry

Mini Project: Workspace, C Library & Private Registry

Time to put the course together. You'll build fastsum, a tiny checksum toolkit, as a real-world-shaped Cargo workspace:

Package Kind What it shows
fastsum library, published C code compiled by build.rs with the cc crate, a safe Rust API over it, unit and doc tests, packaging metadata
sumcli binary, never published a CLI built with clap's derive API, depending on the library through the workspace
consumer a separate project uses fastsum from the private registry, like any third-party crate

The layout

text
fastsum-ws/
├── Cargo.toml              [workspace], [workspace.package], [workspace.dependencies], [profile.release]
├── Cargo.lock              committed
└── crates/
    ├── fastsum/
    │   ├── Cargo.toml      links = "fastsum", include = [...], publish = ["local"]
    │   ├── build.rs        cc::Build → libfastsum.a
    │   ├── csrc/fastsum.c  Adler-32 and FNV-1a in C
    │   └── src/lib.rs      safe wrappers, tests, doc tests
    └── sumcli/
        ├── Cargo.toml      publish = false
        └── src/main.rs     clap CLI

The design follows the course's rules:

  • One place for shared facts: version, edition, license and MSRV in [workspace.package]; clap, cc and the internal fastsum dependency in [workspace.dependencies] (Workspace Inheritance). fastsum is declared with both path and version, so the CLI could be published later.
  • The C code stays behind a safe API. Only src/lib.rs contains unsafe; the CLI and every consumer call ordinary Rust functions (Compiling C with the cc Crate).
  • links = "fastsum" guarantees that only one copy of the C library can ever be linked into a build.
  • include keeps the published crate to exactly what it needs to build: Rust sources, the C source and build.rs (cargo package).
  • publish fields make accidents impossible: the library may only go to local; the CLI nowhere.
  • Release profile in the root manifest: thin LTO, one codegen unit, stripped (Profiles).

Part 1: build, test and run the workspace

bash · try it yourself
mkdir -p fastsum-ws/crates/fastsum/src fastsum-ws/crates/fastsum/csrc fastsum-ws/crates/sumcli/src
cd fastsum-ws
cat > Cargo.toml <<'T'
[workspace]
members = ["crates/*"]
resolver = "3"

[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
rust-version = "1.85"
repository = "https://example.com/fastsum"

[workspace.dependencies]
cc = "1.2"
clap = { version = "4.6", features = ["derive"] }
fastsum = { path = "crates/fastsum", version = "0.1.0" }

[profile.release]
lto = "thin"
codegen-units = 1
strip = true
T
cat > crates/fastsum/Cargo.toml <<'T'
[package]
name = "fastsum"
description = "Adler-32 and FNV-1a checksums, implemented in C"
links = "fastsum"
include = ["src/**/*.rs", "csrc/*", "build.rs"]
publish = ["local"]
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true

[build-dependencies]
cc.workspace = true
T
cat > crates/fastsum/csrc/fastsum.c <<'C'
#include <stddef.h>
#include <stdint.h>

uint32_t fs_adler32(const uint8_t *data, size_t len) {
    uint32_t a = 1, b = 0;
    for (size_t i = 0; i < len; i++) {
        a = (a + data[i]) % 65521;
        b = (b + a) % 65521;
    }
    return (b << 16) | a;
}

uint32_t fs_fnv1a(const uint8_t *data, size_t len) {
    uint32_t h = 2166136261u;
    for (size_t i = 0; i < len; i++) {
        h ^= data[i];
        h *= 16777619u;
    }
    return h;
}
C
cat > crates/fastsum/build.rs <<'RS'
fn main() {
    println!("cargo::rerun-if-changed=csrc/fastsum.c");
    cc::Build::new().file("csrc/fastsum.c").warnings(true).compile("fastsum");
}
RS
cat > crates/fastsum/src/lib.rs <<'RS'
//! Fast checksums. The algorithms are implemented in C and wrapped in a safe API.

mod ffi {
    unsafe extern "C" {
        pub fn fs_adler32(data: *const u8, len: usize) -> u32;
        pub fn fs_fnv1a(data: *const u8, len: usize) -> u32;
    }
}

/// Adler-32 checksum of `data`.
///
/// ```
/// assert_eq!(fastsum::adler32(b"Wikipedia"), 0x11e6_0398);
/// ```
pub fn adler32(data: &[u8]) -> u32 {
    // SAFETY: the C function reads exactly `len` bytes from a valid slice.
    unsafe { ffi::fs_adler32(data.as_ptr(), data.len()) }
}

/// 32-bit FNV-1a hash of `data`.
///
/// ```
/// assert_eq!(fastsum::fnv1a(b"hello"), 0x4f9f_2cab);
/// ```
pub fn fnv1a(data: &[u8]) -> u32 {
    // SAFETY: as above.
    unsafe { ffi::fs_fnv1a(data.as_ptr(), data.len()) }
}

#[cfg(test)]
mod tests {
    #[test]
    fn empty_inputs() {
        assert_eq!(super::adler32(b""), 1);
        assert_eq!(super::fnv1a(b""), 0x811c_9dc5);
    }
}
RS
cat > crates/sumcli/Cargo.toml <<'T'
[package]
name = "sumcli"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true

[dependencies]
clap.workspace = true
fastsum.workspace = true
T
cat > crates/sumcli/src/main.rs <<'RS'
use clap::{Parser, ValueEnum};

#[derive(Clone, Copy, ValueEnum)]
enum Algo {
    Adler32,
    Fnv1a,
}

/// Print checksums of strings, computed by a C library.
#[derive(Parser)]
#[command(name = "sumcli", version)]
struct Args {
    /// Checksum algorithm
    #[arg(short, long, value_enum, default_value_t = Algo::Adler32)]
    algo: Algo,
    /// Strings to checksum
    #[arg(required = true)]
    inputs: Vec<String>,
}

fn main() {
    let args = Args::parse();
    for s in &args.inputs {
        let sum = match args.algo {
            Algo::Adler32 => fastsum::adler32(s.as_bytes()),
            Algo::Fnv1a => fastsum::fnv1a(s.as_bytes()),
        };
        println!("{sum:08x}  {s}");
    }
}
RS
echo "=== build"
cargo build --workspace 2>&1 | grep -v Unpacking | grep -E 'Locking|Compiling (fastsum|sumcli)|Finished'
echo "=== test"
cargo test --workspace --locked -- --test-threads=1 2>&1 | grep -E '^test |Doc-tests'
echo "=== run"
cargo run -q -p sumcli -- Wikipedia hello
cargo run -q -p sumcli -- --algo fnv1a hello
cargo run -q -p sumcli -- --version
cargo run -q -p sumcli -- --help
cargo run -q -p sumcli 2>&1; echo "exit code: $?"
echo "=== lint and release build"
cargo clippy --workspace --all-targets --locked -q -- -D warnings && echo "clippy: clean"
cargo build -q --release --locked -p sumcli
file target/release/sumcli | cut -d, -f1-2
cargo tree -p sumcli --depth 1 -e normal
=== build
     Locking 24 packages to highest Rust 1.85 compatible versions
   Compiling fastsum v0.1.0 (/home/learner/fastsum-ws/crates/fastsum)
   Compiling sumcli v0.1.0 (/home/learner/fastsum-ws/crates/sumcli)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 9.49s
=== test
test tests::empty_inputs ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
   Doc-tests fastsum
test crates/fastsum/src/lib.rs - adler32 (line 12) ... ok
test crates/fastsum/src/lib.rs - fnv1a (line 22) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
=== run
11e60398  Wikipedia
062c0215  hello
4f9f2cab  hello
sumcli 0.1.0
Print checksums of strings, computed by a C library

Usage: sumcli [OPTIONS] <INPUTS>...

Arguments:
  <INPUTS>...  Strings to checksum

Options:
  -a, --algo <ALGO>  Checksum algorithm [default: adler32] [possible values: adler32, fnv1a]
  -h, --help         Print help
  -V, --version      Print version
error: the following required arguments were not provided:
  <INPUTS>...

Usage: sumcli <INPUTS>...

For more information, try '--help'.
exit code: 2
=== lint and release build
clippy: clean
target/release/sumcli: ELF 64-bit LSB pie executable, x86-64
sumcli v0.1.0 (/home/learner/fastsum-ws/crates/sumcli)
├── clap v4.6.7
└── fastsum v0.1.0 (/home/learner/fastsum-ws/crates/fastsum)

Check the results against the plan:

  • 0x11e60398 and 0x4f9f2cab are the published reference values of Adler-32("Wikipedia") and FNV-1a("hello"), so the C code, the FFI declarations and the linking all work. The unit test also checks the empty-input initial values.
  • The doc tests ran against the library from the outside, including the C code, through the public API.
  • clap generated --help and --version (from CARGO_PKG_VERSION, inherited from the workspace) and rejected a missing argument with exit code 2.
  • Clippy is clean with -D warnings, and --locked proves the committed lockfile matches the manifests.

Part 2: publish the library and use it from another project

The library goes to the private registry; then a completely separate project depends on it by version, exactly as it would on a crates.io crate. (Each session starts from an empty machine, so this one recreates the workspace with just the library.)

bash · try it yourself
crate-registry start
mkdir -p fastsum-ws/crates/fastsum/src fastsum-ws/crates/fastsum/csrc && cd fastsum-ws
cat > Cargo.toml <<'T'
[workspace]
members = ["crates/*"]
resolver = "3"

[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
rust-version = "1.85"
repository = "https://example.com/fastsum"

[workspace.dependencies]
cc = "1.2"
T
cat > crates/fastsum/Cargo.toml <<'T'
[package]
name = "fastsum"
description = "Adler-32 and FNV-1a checksums, implemented in C"
links = "fastsum"
include = ["src/**/*.rs", "csrc/*", "build.rs"]
publish = ["local"]
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true

[build-dependencies]
cc.workspace = true
T
cat > crates/fastsum/csrc/fastsum.c <<'C'
#include <stddef.h>
#include <stdint.h>
uint32_t fs_adler32(const uint8_t *d, size_t n) {
    uint32_t a = 1, b = 0;
    for (size_t i = 0; i < n; i++) { a = (a + d[i]) % 65521; b = (b + a) % 65521; }
    return (b << 16) | a;
}
uint32_t fs_fnv1a(const uint8_t *d, size_t n) {
    uint32_t h = 2166136261u;
    for (size_t i = 0; i < n; i++) { h ^= d[i]; h *= 16777619u; }
    return h;
}
C
cat > crates/fastsum/build.rs <<'RS'
fn main() {
    println!("cargo::rerun-if-changed=csrc/fastsum.c");
    cc::Build::new().file("csrc/fastsum.c").compile("fastsum");
}
RS
cat > crates/fastsum/src/lib.rs <<'RS'
//! Fast checksums implemented in C.
mod ffi {
    unsafe extern "C" {
        pub fn fs_adler32(data: *const u8, len: usize) -> u32;
        pub fn fs_fnv1a(data: *const u8, len: usize) -> u32;
    }
}
/// Adler-32 checksum.
pub fn adler32(data: &[u8]) -> u32 { unsafe { ffi::fs_adler32(data.as_ptr(), data.len()) } }
/// 32-bit FNV-1a hash.
pub fn fnv1a(data: &[u8]) -> u32 { unsafe { ffi::fs_fnv1a(data.as_ptr(), data.len()) } }
RS
cargo generate-lockfile -q
echo "=== what will be published"
cargo package -p fastsum --list
echo "=== publish"
cargo publish -p fastsum 2>&1 | grep -v -e Unpacking -e '^ *Compiling'
echo "=== a separate project, outside the workspace"
cd ~
cargo new consumer --vcs none -q
cd consumer
cargo add fastsum --registry local 2>&1 | grep Adding
cat > src/main.rs <<'RS'
fn main() {
    let data = b"shipped through a private registry";
    println!("adler32 = {:08x}", fastsum::adler32(data));
    println!("fnv1a   = {:08x}", fastsum::fnv1a(data));
}
RS
cargo run 2>&1 | grep -v -e Unpacking -e Downloading -e Downloaded -e Updating
cargo tree 2>&1 | grep -v Updating
grep -A2 'name = "fastsum"' Cargo.lock
=== what will be published
Cargo.lock
Cargo.toml
Cargo.toml.orig
build.rs
csrc/fastsum.c
src/lib.rs
=== publish
note: found `local` as only allowed registry. Publishing to it automatically.
    Updating `local` index
   Packaging fastsum v0.1.0 (/home/learner/fastsum-ws/crates/fastsum)
    Packaged 6 files, 3.0KiB (1.5KiB compressed)
   Verifying fastsum v0.1.0 (/home/learner/fastsum-ws/crates/fastsum)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.64s
   Uploading fastsum v0.1.0 (/home/learner/fastsum-ws/crates/fastsum)
    Uploaded fastsum v0.1.0 to registry `local`
note: waiting for fastsum v0.1.0 to be available at registry `local`
help: you may press ctrl-c to skip waiting; the crate should be available shortly
   Published fastsum v0.1.0 at registry `local`
=== a separate project, outside the workspace
      Adding fastsum v0.1.0 to dependencies
   Compiling shlex v2.0.1
   Compiling find-msvc-tools v0.1.15
   Compiling cc v1.10.0
   Compiling fastsum v0.1.0 (registry `local`)
   Compiling consumer v0.1.0 (/home/learner/consumer)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.80s
     Running `target/debug/consumer`
adler32 = e6400d44
fnv1a   = df6789b8
consumer v0.1.0 (/home/learner/consumer)
└── fastsum v0.1.0 (registry `local`)
    [build-dependencies]
    └── cc v1.10.0
        ├── find-msvc-tools v0.1.15
        └── shlex v2.0.1
name = "fastsum"
version = "0.1.0"
source = "sparse+http://127.0.0.1:8282/index/"

What happened:

  • cargo package --list shows the effect of include: sources, the C file and build.rs, plus the files Cargo adds itself (the normalised Cargo.toml, Cargo.toml.orig, Cargo.lock). No target/, no workspace files.
  • cargo publish -p fastsum packaged, verified (the unpacked crate, C code and all, built on its own), uploaded and waited for the index. The normalised manifest inside the crate carries the inherited version, license and MSRV.
  • In consumer, fastsum came from the registry (registry = "local" in Cargo.toml, the sparse index as source in Cargo.lock), its build.rs compiled the C code again on the consumer's machine with the consumer's compiler, and the program printed the checksums.

Extend it

  1. Release 0.2.0 with a new crc32 function: add it to the C file and the Rust API, bump [workspace.package] version, publish, then cargo update -p fastsum in consumer. Why doesn't a plain cargo update pick up 0.2.0 when the requirement is "0.1.0"? (Version Requirements)
  2. Add a serde feature to fastsum that derives Serialize for a Checksum { algo, value } struct, using dep:serde. Check with cargo tree -e features that consumers who don't enable it don't compile serde.
  3. Cross-compile sumcli for aarch64-unknown-linux-gnu and confirm with file that both the Rust code and the C object are ARM64 (Cross-Compiling).
  4. Vendor the consumer's dependencies with cargo vendor --respect-source-config and build it with an empty CARGO_HOME. What has to change in .cargo/config.toml for a crate from a non-crates.io registry? (Vendoring)
  5. Write the CI script from Field Notes: CI for the workspace, including an MSRV job for Rust 1.85.

Test yourself

Why does fastsum set include = ["src/**/*.rs", "csrc/*", "build.rs"]?

  1. To speed up compilation
  2. So the published crate contains exactly what's needed to build it, including the C source the build script compiles
  3. Because workspaces require it
  4. To exclude Cargo.toml

Where is the C code of fastsum compiled when consumer builds?

  1. Nowhere: the registry stores a prebuilt libfastsum.a
  2. On the consumer's machine, by fastsum's build.rs, with the consumer's C compiler
  3. On the registry server
  4. In the publisher's target/ directory

Why does [workspace.dependencies] declare fastsum = { path = ..., version = "0.1.0" } and not just a path?

  1. Paths are deprecated
  2. Members build from the path, but a published dependent needs a registry version
  3. The version is ignored
  4. It makes the build faster