cheatah
Module

io

Python-like input/output, surfaced as free functions plus a Python-style File object.

Usage

import io

io.print("meow", 42, "purr")               # -> meow 42 purr
let s = io.format("{} ate {} fish", "cat", 3)  # -> "cat ate 3 fish"

let f = io.open("notes.txt", "w")
f.write("hello\n")
f.close()

import io includes io.hpp and links libcheatah_io; a program that doesn't import it neither sees nor links it.

Functions

Rendering

  • str(x) — stringify any Printable value (bool → True/False; lists → [1, 2, 3]; dicts → {'k': 1}; an object with a str() method → its str()).

  • repr(x) — like str, but strings are single-quoted (incl. inside lists/dicts).

  • format(fmt, ...) — sequential {} substitution (str.format / f-string style).

Console

  • print(*args) — space-separated, newline-terminated, to stdout. Accepts any Printable arg, not just streamable scalars.

The

print/str require Printable, not raw streamability: a value is printable if it streams directly (numbers, strings, bool), exposes a str() method (a struct that implements fn str(self), or a built-in object like an ndarray), or is a list/dict whose elements are themselves printable (checked recursively). So you can io.print([1, 2, 3]), io.print(myStruct), and io.print(someNdarray) — and a non-printable type fails with a clear "does not satisfy `Printable`" error.

  • input(prompt="") — write the prompt, read one line from stdin.

Files

  • read_file(path) — read a whole file into a string in one call (binary-safe; "" if it can't be opened).

  • open(path, mode="r") — returns a File (Python modes r/w/a, +/b).

  • File::read() — the whole remaining file.

  • File::readline() — the next line (newline stripped; "" at EOF).

  • File::readlines() — all remaining lines as a vector.

  • File::write(value) — write a streamable value.

  • File::is_open() / File::close() — handle state; RAII closes on scope exit.

Per-function docs (parameters, complexity, heap behavior) are in io.hpp. Tested in ../tests/io_test.cpp; ASan + Valgrind clean via the QA gate (security/run-valgrind.sh).

Classes

Functions

fn str · 8 overloads
std::string str(const std::string &value)source#
std::string str(bool b)source#
std::string str(signed char v)source#
std::string str(unsigned char v)source#
std::string str(const T &value)source#
std::string str(const std::complex< T > &z)source#
std::string str(const std::vector< T > &v)source#
std::string str(const std::unordered_map< K, V, H, E, A > &m)source#

str() for a std::string — identity overload.

Parameters
value

the string.

Returns

a copy of value.

Complexity

O(n).

Allocation

allocates the result copy.

Compile-run testIoCompileRun.Str
Performance81.17 ns/call in cheatah · 100 ns/call in CPython 3.12.3 · ≈1.2× faster
fn std::string fixed(double value, long long places) source#

Fixed-point float formatting — Python's f"{x:.2f}" / "%.2f" % x as a function.

Renders value with exactly places digits after the decimal point, correctly rounded (the C printf("%.*f") semantics, which match Python's fixed-point format of the same double). Negative places is treated as 0; places is capped at 17 (beyond a double's meaningful precision).

Parameters
value

the number to format.

places

digits after the decimal point (clamped to [0, 17]).

Returns

the fixed-point text (e.g. fixed(2.675, 2) -> "2.67").

Complexity

O(places) plus the integer-digit count.

Allocation

allocates the result string.

Compile-run testIoCompileRun.Fixed
System testStdlibE2E.Io
fn repr · 6 overloads
std::string repr(const std::string &value)source#
std::string repr(const char *value)source#
std::string repr(const T &value)source#
std::string repr(const std::complex< T > &z)source#
std::string repr(const std::vector< T > &v)source#
std::string repr(const std::unordered_map< K, V, H, E, A > &m)source#

repr() for a std::string — quoted (Python repr).

Wraps the text in single quotes but does not escape embedded quotes, backslashes, or control characters, so the result is not a faithful round-trip of Python's repr.

Parameters
value

the string.

Returns

value wrapped in single quotes.

Complexity

O(n).

Allocation

allocates the result string.

Compile-run testIoCompileRun.Repr
System testStdlibE2E.Io
Performance241 ns/call in cheatah · 180 ns/call in CPython 3.12.3 · ≈1.4× slower
fn std::string input(std::string_view prompt="") source#

Python input(prompt=""): write prompt, read one line from stdin.

Writes (and flushes) prompt only when non-empty, then reads one line via getline; at EOF or on a blank line it returns an empty string rather than signaling end-of-input.

Parameters
prompt

text shown before reading (no newline added).

Returns

the line read, with the trailing newline stripped.

Complexity

O(line length).

Allocation

allocates the returned string.

Concurrency

blocks the calling thread until a full line (or EOF) arrives on stdin.

Note

No compile-run test: io.input reads stdin, which the e2e harness does not feed, so it is intentionally skipped in tests/purrc/io_cr_test.cpp.

System testStdlibE2E.Io
PerformanceI/O-bound — dominated by the OS, not micro-benchmarked
fn File open(const std::string &path, std::string_view mode="r") source#

Python open(path, mode="r") — construct and return a File.

Constructs a File on path (defaulting to read mode) and returns it by move; as with the File constructor a failed open does not throw, so check is_open() on the result.

Parameters
path

filesystem path.

mode

Python-style mode string.

Returns

an open File (move-returned).

Complexity

O(1) plus the OS open.

Allocation

constructs a File; no heap of our own.

PerformanceI/O-bound — dominated by the OS, not micro-benchmarked
fn std::string read_file(const std::string &path) source#

Read a whole file into a string in one call (binary-safe — preserves every byte, including NULs).

Opens path in binary mode and slurps the entire buffer in one read; an empty return is ambiguous between a missing/unopenable file and a genuinely empty file.

Parameters
path

filesystem path.

Returns

the file's contents, or "" if it cannot be opened.

Complexity

O(file size).

Allocation

allocates the returned string.

Compile-run testIoCompileRun.ReadFile
PerformanceI/O-bound — dominated by the OS, not micro-benchmarked
fn void print(const Args &... args) source#

Python print(*args): space-separated, newline-terminated, to stdout (sep=' ', end='
').

Inserts a single space between consecutive arguments (none before the first) and always ends with a trailing \n; with no arguments it writes just that newline (blank line). Output is meant to be NICE AND READABLE by default: a struct (which the compiler gives a cheatah_pretty_print member) is rendered over multiple indented lines, e.g. Point(\n x = 1,\n y = 2\n). Use rprint to print a struct in its compact form.

Parameters
args

zero or more printable values.

Complexity

O(total output length).

Allocation

allocates a temporary string per str()-routed arg; a struct's pretty-printer streams straight to stdout instead.

Concurrency

writes to the shared std::cout; concurrent prints from several threads do not race but may interleave their characters.

Compile-run testIoCompileRun.Print
PerformanceI/O-bound — dominated by the OS, not micro-benchmarked
fn void rprint(const Args &... args) source#

Python print but RAW: a struct prints in its COMPACT Name(field=value, …) form (exactly as stored) instead of the pretty multi-line layout print uses; otherwise identical (space-separated, newline-terminated).

Reach for it when you want a struct exactly as it is rather than the default human-readable formatting.

Parameters
args

zero or more printable values.

Complexity

O(total output length).

Allocation

each arg is routed through str(), allocating temporary strings.

Concurrency

writes to the shared std::cout; concurrent prints from several threads do not race but may interleave their characters.

Compile-run testIoCompileRun.Rprint
System testStdlibE2E.Io
fn std::string format(std::string_view fmt, const Args &... args) source#

Sequential {} substitution — the common case of Python's str.format() / f-strings.

Replaces each {} left-to-right with the corresponding argument (streamed via its operator<<); surplus arguments are silently dropped, and any {} left without an argument is emitted literally rather than raising. Does not support indexed or named fields ({0}, {name}) or escaped braces ({{).

Parameters
fmt

format string with {} placeholders.

args

values substituted left-to-right (extras dropped, missing placeholders left as-is).

Returns

the formatted string.

Complexity

O(len(fmt) + total arg output).

Allocation

allocates the result string (via an ostringstream).

Compile-run testIoCompileRun.Format
Performancestring templating — closest CPython twin (f-strings) isn't a function call