Skip to content
📖 The Auto Programming LanguageBook contents

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().

String processing pipeline: trim, format, split, join, and query

Notice how each language approaches the same operations:

OperationAutoRustPythonCTypeScript
Trim whitespace.trim().trim().strip()manual loop.trim()
Format stringformat!()format!().format()sprintftemplate literal
Split.split(",").split(",").split(",")strtok.split(",")
Join.join(" ").join(" ")" ".join()manual loop.join(" ")
Contains.contains().contains()in operatorstrstr.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.

Mathematical operations: min, max, abs, round, clamp, pow, sqrt

A few things to note:

  1. clamp(value, lo, hi) constrains a value to a range. clamp(15, 0, 10) returns 10 because 15 exceeds the upper bound. This is surprisingly useful in UI code (keeping a slider within bounds), game physics (clamping velocity), and data validation.

  2. round, floor, ceil differ in how they handle the fractional part. round(3.7) gives 4 (nearest integer). floor(3.9) gives 3 (toward negative infinity). ceil(3.1) gives 4 (toward positive infinity).

  3. In Rust and C, min and max live in different places. Rust puts them in std::cmp, while C uses the ternary operator or macros. Python and TypeScript have them as built-in functions and Math methods 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.

File I/O: reading, writing, path manipulation, and directory listing

Key observations:

  1. path_join("data", "output.txt") constructs a path using the correct separator for the current platform (/ on Unix, \ on Windows). You should always use path_join instead of concatenating strings with / -- it prevents bugs when your code runs on different operating systems.

  2. read_file and write_file handle the entire file content as a string. In Rust, these are fs::read_to_string and fs::write. In C, you work with fopen/fread/fwrite and manage buffers manually. Auto abstracts away the buffer management.

  3. exists returns a bool -- it does not error if the file is missing, it simply returns false. This makes it easy to check before operations.

  4. mkdir creates nested directories (like mkdir -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.

Collection operations: sort, reverse, unique, flatten, zip, and chunk

The operations here deserve a closer look:

  1. .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.

  2. .unique() removes duplicates while preserving insertion order. The first occurrence of each element is kept. This is more useful than a Set when you need to maintain order.

  3. .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().

  4. .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.

  5. .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().

Time operations: current time, formatting, parsing, and duration arithmetic

A few things worth noting:

  1. Format specifiers -- Auto uses the same %Y-%m-%d %H:%M:%S format strings as C's strftime and Rust's chrono. %Y is the four-digit year, %m is the zero-padded month, %d is the zero-padded day, %H is the 24-hour, %M is the minute, and %S is the second.

  2. 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).

  3. 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.

  4. Time.parse() is the inverse of .format(). It takes a string and a format specifier and returns a Time. 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.

JSON serialization: converting types to and from JSON

Let us break down what is happening:

  1. to_json(alice) serializes the User value to a JSON string: {"name":"Alice","age":30,"email":"alice@example.com"}. The to_json function works with any type that implements the Serialize spec.

  2. from_json!(json, User) deserializes a JSON string back into a User value. The ! in from_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 a match.

  3. to_json_pretty(alice) produces the same JSON but with indentation for human readability. This is useful for config files and debugging.

  4. Collections serialize naturally -- a List<User> becomes a JSON array of objects, a Map<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.

JSON serialization with external dependencies

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 configuration parsing

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.

Base64 encoding and decoding
Hexadecimal encoding and decoding

Key points about data encoding:

  1. 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.

  2. 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. The hex function works on both byte arrays and integers.

  3. Auto's encoding functions handle both strings and byte arrays. b"..." is a byte literal in Auto (equivalent to Rust's b"...").

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.

Measuring elapsed time

Note how each platform measures time differently:

  1. Auto uses now() returning a timestamp and sleep(ms) for delays. Subtracting two timestamps gives elapsed milliseconds.

  2. Rust uses Instant::now() with .elapsed().as_millis() for precise measurement, and thread::sleep() for delays.

  3. C uses clock() from <time.h> with CLOCKS_PER_SEC conversion.

  4. 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.

Regex search and replace

The regex example demonstrates Auto's FFI to Rust crates:

  1. use.rust regex::Regex imports the Regex type from Rust's regex crate. The .rust qualifier tells Auto to use a native Rust dependency.

  2. c"\\d+" is a raw string literal in Auto (equivalent to Rust's r"\d+"). The backslash is not treated as an escape character.

  3. .unwrap() handles the case where the regex pattern might be invalid. In production code, you would use ? or match for proper error handling.

  4. .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.

SHA-256 hash digest

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.

Advanced math: power, trigonometry, and absolute value

The numeric methods in Auto mirror Rust's f64 methods closely:

  1. .powf(y) raises a number to a power: 2.0.powf(3.0) = 8.0.
  2. .sqrt() computes the square root: 2.0.sqrt() ≈ 1.4142.
  3. .abs() returns the absolute value: (-5.0).abs() = 5.0.
  4. .sin() and .cos() compute trigonometric functions in radians.

Summary ​

This chapter toured the most useful parts of Auto's standard library:

DomainModuleKey Functions
Stringsstd::stringtrim, format!, split, join, contains, replace
Mathstd::mathmin, max, abs, round, floor, ceil, clamp, pow, sqrt, powf, sin, cos
File I/Ostd::fsread_file, write_file, path_join, exists, mkdir, list_dir
Collectionsstd::collectionssort, reverse, unique, flatten, zip, chunk
Timestd::timeTime.now, .format, Time.parse, Duration.hours, Duration.minutes, now, sleep
JSONstd::jsonto_json, from_json, to_json_pretty
TOMLstd::configparse_toml
Encodingstd::encodingbase64_encode, base64_decode, hex, unhex
Regexregex crateRegex.new, .replace_all, .replace
Cryptosha2 crateSha256.new, .update, .finalize, .hex

Key takeaways:

  1. 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.

  2. 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.

  3. Error handling is built in -- File I/O and JSON parsing use the !T result type, so errors are explicit and handled at the call site. You never silently ignore a failure.

  4. 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's stdlib + POSIX, and TypeScript's fs/path/JSON. Learning Auto's stdlib also teaches you the idioms of every target platform.

  5. 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.

Released under the MIT License.