Standard Library Tour
You have spent the last twenty chapters learning Auto's core language: types, functions, pattern matching, generics, error handling, concurrency, and metaprogramming. But a language is only as useful as the tools it gives you out of the box. Auto comes with a comprehensive standard library -- a toolkit of ready-made modules for the things every program needs: strings, math, file I/O, collections, time, and JSON.
This chapter is a tour. We will walk through the most useful parts of the standard library, one domain at a time, with practical examples. Think of it as a guided walk through a well-organized workshop: you will not memorize every tool on the shelf, but you will know where to find them when you need them.
String Utilities
Strings are everywhere. Parsing user input, formatting log messages, building file paths -- most programs spend a significant fraction of their time working with text. Auto's std::string module provides a rich set of methods on the String type.
The key functions are: trim() to remove whitespace, format!() for interpolation, split() to break a string into parts, join() to combine them, and query methods like contains(), starts_with(), ends_with(), to_upper(), to_lower(), and replace().
Notice how each language approaches the same operations:
| Operation | Auto | Rust | Python | C | TypeScript |
|---|---|---|---|---|---|
| Trim whitespace | .trim() | .trim() | .strip() | manual loop | .trim() |
| Format string | format!() | format!() | .format() | sprintf | template literal |
| Split | .split(",") | .split(",") | .split(",") | strtok | .split(",") |
| Join | .join(" ") | .join(" ") | " ".join() | manual loop | .join(" ") |
| Contains | .contains() | .contains() | in operator | strstr | .includes() |
The Auto versions mirror Rust closely, which is intentional. If you know Rust's standard library, you already know most of Auto's.
Math & Numbers
The std::math module provides common mathematical functions. Most are top-level functions you can call directly: min, max, abs, round, floor, ceil, clamp, pow, and sqrt.
These are the functions you reach for when doing calculations -- from scoring algorithms to physics simulations to financial computations.
A few things to note:
clamp(value, lo, hi)constrains a value to a range.clamp(15, 0, 10)returns10because 15 exceeds the upper bound. This is surprisingly useful in UI code (keeping a slider within bounds), game physics (clamping velocity), and data validation.round,floor,ceildiffer in how they handle the fractional part.round(3.7)gives4(nearest integer).floor(3.9)gives3(toward negative infinity).ceil(3.1)gives4(toward positive infinity).In Rust and C,
minandmaxlive in different places. Rust puts them instd::cmp, while C uses the ternary operator or macros. Python and TypeScript have them as built-in functions andMathmethods respectively. Auto provides them as top-level functions for convenience.
IO & File Operations
Reading and writing files is one of the most common things programs do. Auto's std::fs module provides functions for file I/O, path manipulation, and directory operations. These functions use the !T (result) type for error handling, so you never forget to handle a failure.
The key functions are: read_file, write_file, path_join, exists, mkdir, list_dir, copy, and remove.
Key observations:
path_join("data", "output.txt")constructs a path using the correct separator for the current platform (/on Unix,\on Windows). You should always usepath_joininstead of concatenating strings with/-- it prevents bugs when your code runs on different operating systems.read_fileandwrite_filehandle the entire file content as a string. In Rust, these arefs::read_to_stringandfs::write. In C, you work withfopen/fread/fwriteand manage buffers manually. Auto abstracts away the buffer management.existsreturns abool-- it does not error if the file is missing, it simply returnsfalse. This makes it easy to check before operations.mkdircreates nested directories (likemkdir -p). If the directory already exists, it is a no-op rather than an error.
Collection Helpers
You met iterators and their chainable methods in Chapter 19. The std::collections module adds more operations on List<T>, Map<K,V>, and Set<T>: sort, reverse, unique, flatten, zip, chunk, take, and skip.
These helpers are the kind of thing you reach for constantly in data processing, and having them built into the standard library saves you from reinventing the wheel.
The operations here deserve a closer look:
.sort()returns a new sorted list, leaving the original unchanged. The default sort order is ascending. You can pass a comparator closure for custom ordering:nums.sort(fn(a, b) int { b - a })for descending..unique()removes duplicates while preserving insertion order. The first occurrence of each element is kept. This is more useful than aSetwhen you need to maintain order..flatten()turns a list of lists into a single list.[[1, 2], [3, 4], [5, 6]].flatten()becomes[1, 2, 3, 4, 5, 6]. This is the inverse of.chunk()..zip()combines two lists into a list of pairs.names.zip(scores)produces[("Alice", 95), ("Bob", 87), ("Carol", 92)]. If the lists have different lengths, zipping stops at the shorter one..chunk(3)splits a list into chunks of at most 3 elements. The last chunk may be smaller if the list length is not a multiple of 3.
Time & Date
Working with dates and times is notoriously tricky. Time zones, leap years, daylight saving time -- there are many edge cases. Auto's std::time module provides a solid foundation: getting the current time, formatting dates, parsing date strings, and computing durations.
The key types are Time (a point in time) and Duration (a span of time). The key functions are Time.now(), .format(), Time.parse(), Duration.hours(), Duration.minutes(), and Duration.seconds().
A few things worth noting:
Format specifiers -- Auto uses the same
%Y-%m-%d %H:%M:%Sformat strings as C'sstrftimeand Rust'schrono.%Yis the four-digit year,%mis the zero-padded month,%dis the zero-padded day,%His the 24-hour,%Mis the minute, and%Sis the second.Duration arithmetic --
Duration.hours(2) + Duration.minutes(30)creates a 2.5-hour duration. You can add durations to times (now + duration) and subtract times to get durations (later - now).total_minutes()converts a duration to its total value in minutes, regardless of how it was constructed. Similarly,total_seconds()gives the total in seconds.Time.parse()is the inverse of.format(). It takes a string and a format specifier and returns aTime. If the string does not match the format, it returns an error (!Time).
JSON Serialization
JSON is the lingua franca of the web. APIs send it, configuration files store it, logs write it. Auto's std::json module provides to_json and from_json functions that work with any type that implements the Serialize and Deserialize specs.
Let us break down what is happening:
to_json(alice)serializes theUservalue to a JSON string:{"name":"Alice","age":30,"email":"alice@example.com"}. Theto_jsonfunction works with any type that implements theSerializespec.from_json!(json, User)deserializes a JSON string back into aUservalue. The!infrom_json!indicates this can fail -- if the JSON is malformed or missing required fields, it returns an error. In practice, you would handle this with?or amatch.to_json_pretty(alice)produces the same JSON but with indentation for human readability. This is useful for config files and debugging.Collections serialize naturally -- a
List<User>becomes a JSON array of objects, aMap<String, Int>becomes a JSON object, and so on. The serialization is recursive and handles nesting to arbitrary depth.
In Rust, this is powered by serde and serde_json, the de facto standard for serialization. In Python, it is the built-in json module. In TypeScript, it is JSON.stringify and JSON.parse. In C, you typically need a third-party library like cJSON, though here we show manual sprintf for simplicity.
TOML Configuration
TOML is a popular configuration format, especially in the Rust ecosystem (it is the format used by Cargo.toml). Auto's std::config module provides parse_toml for reading TOML configuration files into structured data.
TOML parsing returns a nested map structure. In Auto, you access values using index syntax: config["server"]["host"]. In Rust, this maps to nested HashMaps. Python 3.11+ provides tomllib in the standard library. C has no built-in TOML support; you would need a library like tomlc99.
Data Encoding
Encoding binary data as text is essential for network protocols, file formats, and data storage. Auto provides base64_encode/base64_decode and hex/unhex for the two most common binary-to-text encodings.
Key points about data encoding:
Base64 encodes 3 bytes into 4 ASCII characters. It is used in email attachments, data URLs, and JWT tokens. Every language has a base64 library in its standard library or a popular crate.
Hex encoding converts each byte into two hex characters (
0x00-0xFF). It is human-readable and used for hash digests, network addresses, and debug output. Thehexfunction works on both byte arrays and integers.Auto's encoding functions handle both strings and byte arrays.
b"..."is a byte literal in Auto (equivalent to Rust'sb"...").
Elapsed Time
Measuring how long an operation takes is fundamental for performance testing and profiling. Auto provides now() for getting the current timestamp and sleep() for pausing execution.
Note how each platform measures time differently:
Auto uses
now()returning a timestamp andsleep(ms)for delays. Subtracting two timestamps gives elapsed milliseconds.Rust uses
Instant::now()with.elapsed().as_millis()for precise measurement, andthread::sleep()for delays.C uses
clock()from<time.h>withCLOCKS_PER_SECconversion.TypeScript/JavaScript uses
Date.now()returning milliseconds since epoch.
Regular Expressions
Regular expressions are powerful for text search and replacement. Auto integrates with Rust's regex crate through the use.rust FFI mechanism, giving you access to a fast, safe regex engine.
The regex example demonstrates Auto's FFI to Rust crates:
use.rust regex::Regeximports theRegextype from Rust'sregexcrate. The.rustqualifier tells Auto to use a native Rust dependency.c"\\d+"is a raw string literal in Auto (equivalent to Rust'sr"\d+"). The backslash is not treated as an escape character..unwrap()handles the case where the regex pattern might be invalid. In production code, you would use?ormatchfor proper error handling..replace_all()replaces every match, not just the first one. For single-replacement, use.replace().
Cryptography
Auto provides access to cryptographic primitives through Rust's crate ecosystem. The sha2 crate gives you SHA-256 and other hash functions.
The dep sha2 declaration tells Auto's package manager to include the sha2 crate as a dependency. Combined with use.rust sha2::Sha256, this gives you direct access to a production-grade cryptographic library.
Advanced Math
Beyond the basic min, max, and sqrt functions, Auto supports advanced mathematical operations through methods on numeric types: .powf(), .abs(), .sin(), .cos(), and more.
The numeric methods in Auto mirror Rust's f64 methods closely:
.powf(y)raises a number to a power:2.0.powf(3.0)= 8.0..sqrt()computes the square root:2.0.sqrt()≈ 1.4142..abs()returns the absolute value:(-5.0).abs()= 5.0..sin()and.cos()compute trigonometric functions in radians.
Summary
This chapter toured the most useful parts of Auto's standard library:
| Domain | Module | Key Functions |
|---|---|---|
| Strings | std::string | trim, format!, split, join, contains, replace |
| Math | std::math | min, max, abs, round, floor, ceil, clamp, pow, sqrt, powf, sin, cos |
| File I/O | std::fs | read_file, write_file, path_join, exists, mkdir, list_dir |
| Collections | std::collections | sort, reverse, unique, flatten, zip, chunk |
| Time | std::time | Time.now, .format, Time.parse, Duration.hours, Duration.minutes, now, sleep |
| JSON | std::json | to_json, from_json, to_json_pretty |
| TOML | std::config | parse_toml |
| Encoding | std::encoding | base64_encode, base64_decode, hex, unhex |
| Regex | regex crate | Regex.new, .replace_all, .replace |
| Crypto | sha2 crate | Sha256.new, .update, .finalize, .hex |
Key takeaways:
Auto comes with batteries included -- The standard library covers the most common programming tasks. You rarely need to reach for external packages for basic operations.
The API is consistent -- Methods like
.sort(),.trim(), and.format()follow predictable naming conventions. If you can guess the name of a function, it probably exists.Error handling is built in -- File I/O and JSON parsing use the
!Tresult type, so errors are explicit and handled at the call site. You never silently ignore a failure.The same concepts exist across all target languages -- Auto's standard library maps naturally to Rust's
std+serde, Python's built-in modules, C'sstdlib+ POSIX, and TypeScript'sfs/path/JSON. Learning Auto's stdlib also teaches you the idioms of every target platform.This tour is just the beginning -- The full standard library includes networking, cryptography, regular expressions, concurrency primitives, and more. Explore the complete documentation at
docs.auto.dev.
This is the last regular chapter before the capstone project. You now have a complete toolkit: a type system, pattern matching, generics, error handling, closures, iterators, concurrency, metaprogramming, and a comprehensive standard library. In the next chapter, you will put it all together to build something real.