gd_host ======= .. rust:crate:: gd_host :synopsis: gd-host: where the Guidedoc engine meets the operating system. gd-host: where the Guidedoc engine meets the operating system. Sessions that convert with Ctrl+C cancellation; sources read within limits (UTF-8 checked, byte order mark dropped); included files confined to approved roots; atomic publication; engine diagnostics as ``gd_report::Report``\ s; a coarse memory budget; worker threads with known stacks; a crash reporter; and ``convert_artifact``, the route ``guidedog convert`` takes from a file to a published HTML or PDF artifact. .. code-block:: rust use gd_host::{Session, describe_all}; let registry = guidedoc::Registry::default(); // guidedoc_defaults::registry() in a program let mut session = Session::new(); let request = guidedoc::default_request("hello.rst", "Hello *world*.\n", "rst", "html"); let result = session.run(®istry, &request).map(str::to_owned); for report in session.reports() { eprint!("{}", gd_report::render_text(&report, &gd_report::Style::default())); } if let Ok(html) = result { println!("{html}"); } Failures are ``Problem``\ s (code, title, message, hint, exit status) or engine ``Fail``\ s described as reports; nothing here prints except ``catch_crash``, the last resort. .. rubric:: Structs .. rust:struct:: pub struct ArtifactRequest<'a> One conversion of ``guidedog convert``. Everything is borrowed for the call; fill it with struct-update syntax from ``Default``. .. rubric:: Fields .. rust:field:: pub input: &'a str The input path, or ``"-"`` for standard input. .. rust:field:: pub from: Format The markup of the input. .. rust:field:: pub to: Target The artifact to publish. .. rust:field:: pub output: &'a str The output path, or ``"-"`` for standard output. .. rust:field:: pub emit_typst: Option<&'a Path> Where to publish the intermediate Typst source too, if anywhere. .. rust:field:: pub force: bool Replace existing outputs. .. rust:field:: pub policy: Policy The conversion's trust decisions. .. rust:field:: pub limits: Limits The conversion's bounds; their byte bounds are lowered to the budget. .. rust:field:: pub read: ReadOptions<'a> Read options. .. rust:field:: pub render: RenderOptions<'a> Render options. .. rust:field:: pub typst_program: &'a str The Typst program name or path; ``""`` or ``"typst"`` uses the embedded compiler. .. rust:field:: pub typst_options: gd_typst::Options<'a> Typst packages and fonts; ``reserve`` is set by the route (it charges the budget). .. rust:field:: pub passes: &'a [Pass<'a>] Transforms run between reading and rendering (embedded pictures, typeset math). .. rust:field:: pub roots: &'a [PathBuf] Approved roots for included files; the input's folder when empty. .. rust:field:: pub budget: usize Memory budget in bytes for what the route holds; 0 is ``DEFAULT_BUDGET``. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for ArtifactRequest<'_> :noindex: :for: ArtifactRequest<'_> :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:struct:: pub struct ArtifactResult What ``convert_artifact`` did. Reports are kept whatever the outcome; ``exit`` is 0 on success, else the status the command ends with, explained by ``problem`` or by the error reports. .. rubric:: Fields .. rust:field:: pub exit: i32 The process exit status. .. rust:field:: pub reports: Vec The conversion's and Typst's diagnostics, ready to render. .. rust:field:: pub problem: Option The host failure, if one stopped the route. .. rust:field:: pub delivered: Delivered Where the artifact went. .. rust:struct:: pub struct Budget Bounds the bytes a build holds at once, shared by its threads (``Budget`` is ``Sync``). Units of work that run at once (``join``) wait for each other: a reservation the budget cannot hold now waits while another joined unit runs, since that one releases what it holds when it ends. When every other unit waits too, nothing would be released, and the reservation is refused instead, so the budget never deadlocks. A reservation larger than the whole limit goes to the policy at once. .. rubric:: Implementations .. rust:impl:: impl Budget :noindex: :for: Budget .. rust:method:: pub fn new(limit: usize) -> Budget Makes a budget of ``limit`` bytes that refuses what it cannot hold. .. rust:method:: pub fn with_policy(limit: usize, on_refusal: impl Fn(&Refusal) -> RefusalChoice + Send + Sync + 'static) -> Budget Makes a budget of ``limit`` bytes that asks ``on_refusal`` what to do with a reservation it cannot hold (a terminal build asks the user whether to raise it). .. rust:method:: pub fn limit(&self) -> usize The limit now; a policy may have raised it. .. rust:method:: pub fn set_limit(&self, limit: usize) Sets the limit; reservations waiting are woken to try again. .. rust:method:: pub fn used(&self) -> usize The bytes held now. .. rust:method:: pub fn peak(&self) -> usize The most bytes held at once. .. rust:method:: pub fn last_refusal(&self) -> Option What the budget held and was asked for when it last refused, if it has. .. rust:method:: pub fn join(&self) -> Unit<'_> Counts a unit of work that runs at once with others until the returned guard drops (see :rust:struct:`Budget `). Borrows the budget for the guard's life. .. rubric:: Trait Implementations .. rust:impl:: impl std::fmt::Debug for Budget :noindex: :for: Budget :trait: std::fmt::Debug .. rust:method:: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result :noindex: .. rust:struct:: pub struct Ledger<'b> Counts what one unit of work (a document's read, a page, a conversion) holds of a budget: the files it reads, the outputs it keeps. Each charge is made before the memory is allocated; dropping the ledger (or ``settle``) releases them all. A ledger without a budget accepts every charge. Its methods take ``&self``, so a resource provider can charge through a shared reference, from several threads. .. rubric:: Implementations .. rust:impl:: impl<'b> Ledger<'b> :noindex: :for: Ledger<'b> .. rust:method:: pub fn new(budget: &'b Budget) -> Ledger<'b> Makes a ledger charging ``budget``, which it borrows. .. rust:method:: pub fn unbounded() -> Ledger<'static> Makes a ledger that counts nothing and refuses nothing. .. rust:method:: pub fn budget(&self) -> Option<&'b Budget> The budget it charges, if any. .. rust:method:: pub fn charge(&self, bytes: usize) -> bool Reserves ``bytes``, waiting as :rust:struct:`Budget ` describes. Returns false, reserving nothing, when the budget refuses; ``refused`` then tells the bytes asked for. .. rust:method:: pub fn discharge(&self, bytes: usize) Returns ``bytes`` the unit has freed before it ends (at most what it holds). .. rust:method:: pub fn settle(&self) Releases everything the ledger holds. .. rust:method:: pub fn held(&self) -> usize The bytes held now. .. rust:method:: pub fn refused(&self) -> usize The bytes the last refused charge asked for, or 0. .. rubric:: Trait Implementations .. rust:impl:: impl Drop for Ledger<'_> :noindex: :for: Ledger<'_> :trait: Drop .. rust:method:: fn drop(&mut self) :noindex: .. rust:struct:: pub struct Refusal What a budget tells its policy when it cannot hold a reservation. .. rubric:: Fields .. rust:field:: pub need: usize The bytes asked for. .. rust:field:: pub used: usize What the budget holds. .. rust:field:: pub limit: usize Its limit. .. rust:struct:: pub struct Unit<'b> A unit of work counted by :rust:fn:`Budget::join `; dropping it ends the unit. .. rubric:: Trait Implementations .. rust:impl:: impl Drop for Unit<'_> :noindex: :for: Unit<'_> :trait: Drop .. rust:method:: fn drop(&mut self) :noindex: .. rust:struct:: pub struct Files<'l> Provides included files from approved roots. It refuses Docutils' ```` includes, names that leave the roots, and names that pass through a symbolic link: links are checked on the path as written, component by component, before it is resolved; then the resolved path must still lie in a root. .. code-block:: rust let ledger = gd_host::Ledger::unbounded(); let files = gd_host::Files::new(&["docs"]).with_ledger(&ledger); let request = guidedoc::Request { resources: Some(&files), ..Default::default() }; .. rubric:: Fields .. rust:field:: pub max_bytes: usize The largest file served, in bytes. .. rust:field:: pub project: Option When set, a name starting with ``/`` is relative to this folder, as Sphinx reads ``/path`` in ``include`` and ``literalinclude``; otherwise such a name is absolute. .. rust:field:: pub ledger: Option<&'l Ledger<'l>> When set, each file's size is charged here before it is read; a file the budget cannot hold is ``ResourceStatus::Limit``. The charges last as long as the ledger. .. rubric:: Implementations .. rust:impl:: impl Files<'static> :noindex: :for: Files<'static> .. rust:method:: pub fn new>(roots: &[P]) -> Files<'static> Serves files below ``roots``, resolved now (``canonical_roots``), up to ``MAX_SOURCE_BYTES`` each, charging nothing. .. rust:impl:: impl<'l> Files<'l> :noindex: :for: Files<'l> .. rust:method:: pub fn with_ledger<'m>(self, ledger: &'m Ledger<'m>) -> Files<'m> where 'l: 'm The same provider, charging each file to ``ledger``, which it borrows. .. rust:method:: pub fn with_project(self, project: impl Into) -> Files<'l> The same provider, reading names that start with ``/`` below ``project``. .. rust:method:: pub fn roots(&self) -> &[PathBuf] The resolved roots. .. rust:method:: pub fn missing(&self) -> Vec The files asked for so far that did not exist, absolute and sorted, each once. A reader records them as dependencies, so a document that includes a file that is created later is read again. .. rubric:: Trait Implementations .. rust:impl:: impl ResourceProvider for Files<'_> :noindex: :for: Files<'_> :trait: ResourceProvider .. rust:method:: fn provide(&self, from: &str, name: &str) -> Result :noindex: .. rust:struct:: pub struct SourceFile An input read by :rust:fn:`read_source `: its text and the name the conversion knows it by. .. rubric:: Fields .. rust:field:: pub text: String The text, UTF-8 checked, without a byte order mark. .. rust:field:: pub canonical: String The absolute, resolved path, or ``"-"`` for standard input. .. rust:struct:: pub struct FolderEntry A name in a folder, what it names, and its inode as the listing gives it (0 where the system gives none). .. rubric:: Fields .. rust:field:: pub name: OsString The entry's name. .. rust:field:: pub kind: PathKind What it names; a symbolic link is ``PathKind::Link``. .. rust:field:: pub inode: u64 The inode, or 0. .. rust:struct:: pub struct Identity A file's or a folder's device and inode, which a rename keeps: two paths with the same identity name the same file. .. rubric:: Fields .. rust:field:: pub device: u64 The device. .. rust:field:: pub inode: u64 The inode. .. rust:struct:: pub struct Problem A host failure: a file that cannot be read, an output that exists, a budget reached, a Typst program that is missing. It carries the exit status the command ends with. Turn it into a report with :rust:fn:`Problem::report ` to render it. .. rubric:: Fields .. rust:field:: pub code: &'static str A stable code such as ``"host.io"``. .. rust:field:: pub title: &'static str A short upper-case title such as ``"CANNOT ACCESS THIS PATH"``. .. rust:field:: pub path: String The path the problem concerns, as given; may be empty. .. rust:field:: pub message: String The plain explanation. .. rust:field:: pub hint: String How to fix it. .. rust:field:: pub exit: i32 The process exit status: 2 usage or file type, 3 limits and memory, 4 I/O and Typst, 130 cancelled. .. rubric:: Implementations .. rust:impl:: impl Problem :noindex: :for: Problem .. rust:method:: pub fn new(code: &'static str, title: &'static str, path: &str, message: impl Into, hint: impl Into, exit: i32) -> Problem Makes a problem from its parts; ``path`` is copied. .. rust:method:: pub fn report(&self) -> Report The problem as an error report without a position, for ``gd_report::render_text`` and ``render_json``. Copies the problem's text. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Display for Problem :noindex: :for: Problem :trait: fmt::Display .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl std::error::Error for Problem :noindex: :for: Problem :trait: std::error::Error .. rust:struct:: pub struct Stage A staging file beside a destination, for output written in place by another producer (Typst) or by ``publish``. Dropping it removes the file unless it was committed, so an abandoned stage leaves nothing behind. .. rubric:: Implementations .. rust:impl:: impl Stage :noindex: :for: Stage .. rust:method:: pub fn beside(destination: &Path) -> Result Creates an empty staging file in the folder of ``destination``, making the folders on its way. Fails with ``host.io``. .. rust:method:: pub fn path(&self) -> &Path The staging file's path, for a producer to write to. .. rust:method:: pub fn commit(mut self, destination: &Path, force: bool) -> Result<(), Problem> Flushes the staging file and renames it over ``destination``, then flushes the folder so the name is durable. An existing destination is refused (``host.output.exists``) unless ``force`` is set; on any failure the destination is unchanged and the stage removed. .. rubric:: Trait Implementations .. rust:impl:: impl Drop for Stage :noindex: :for: Stage :trait: Drop .. rust:method:: fn drop(&mut self) :noindex: .. rust:struct:: pub struct Schedule The jobs of a parallel run, numbered in the order a sequential run takes them, and the memory they may reserve together. Plain data; one schedule per run. .. rubric:: Implementations .. rust:impl:: impl Schedule :noindex: :for: Schedule .. rust:method:: pub fn new(weights: Vec, capacity: u64, slots: usize) -> Schedule A schedule of ``weights.len()`` waiting jobs, which may reserve ``capacity`` bytes together and run at most ``slots`` at once (0 counts as 1). .. rust:method:: pub fn job_count(&self) -> usize The number of jobs. .. rust:method:: pub fn phase(&self, job: usize) -> JobPhase Where ``job`` is. Panics when ``job`` is not a job of the schedule. .. rust:method:: pub fn load(&self) -> u64 The memory the running jobs reserve. .. rust:method:: pub fn running_count(&self) -> usize How many jobs run. .. rust:method:: pub fn may_start(&self, job: usize, room: impl Fn(u64) -> bool) -> bool Whether ``job`` may start now: the guard of ``start``. ``room`` is asked about the job's weight only when other jobs run. .. rust:method:: pub fn next(&self, room: impl Fn(u64) -> bool) -> Option The job to start next, if one may start: the heaviest, and of equal weights the earliest, so that light jobs fill the gaps at the end. .. rust:method:: pub fn start(&mut self, job: usize) Marks ``job`` as running. Panics when it may not start, whatever ``room`` says: the caller asks :rust:fn:`Schedule::next ` or :rust:fn:`Schedule::may_start ` first. .. rust:method:: pub fn finish(&mut self, job: usize, succeeded: bool) Marks the running ``job`` as ended. Panics when it does not run. .. rust:method:: pub fn is_ended(&self) -> bool Whether no job runs and none may start: the run has ended. A sequential run would have ended in the same outcome (GDS 0020, Theorems 4 and 5). .. rust:method:: pub fn first_failure(&self) -> Option The first job that failed, in plan order. .. rust:struct:: pub struct Session One thread's conversions. Reuse it: its workspace keeps its buffers between runs. What a run returns (output, document) and ``reports`` describe the last run only. .. rubric:: Implementations .. rust:impl:: impl Session :noindex: :for: Session .. rust:method:: pub fn new() -> Session Makes a session with an empty workspace; it allocates nothing until used. .. rust:method:: pub fn run(&mut self, registry: &Registry, request: &Request<'_>) -> Result<&str, Fail> Converts ``request`` with ``registry``: read, passes, render. A request without a cancel probe gets the Ctrl+C one (``cancel_probe``). The output borrows the session until the next run; on failure, ``reports`` explains it. .. rust:method:: pub fn read(&mut self, reader: &Reader, request: &Request<'_>) -> Result, Fail> Reads ``request``'s source with ``reader`` without rendering, then runs ``request.passes`` over the document (a translation, for example). The document borrows the session until the next run. .. rust:method:: pub fn document(&self) -> Option> The current document: the last successful read or run. .. rust:method:: pub fn reports(&self) -> Vec Describes what the last run reported (``describe_all``); the reports are owned. .. rust:method:: pub fn workspace(&self) -> &Workspace The workspace, for the source table, source map, and raw diagnostics. .. rust:method:: pub fn workspace_mut(&mut self) -> &mut Workspace The workspace, for the engine's staged calls (``check_render``, ``load_object``). .. rubric:: Enums .. rust:enum:: pub enum Delivered Where a successful conversion's artifact went. .. rubric:: Variants .. rust:variant:: Nothing Nothing was delivered (the conversion failed). .. rust:variant:: File(PathBuf) Published at this path. .. rust:variant:: Stdout(Vec) The bytes to print, for output ``"-"``. .. rust:enum:: pub enum Format The markup ``convert_artifact`` reads. .. rubric:: Variants .. rust:variant:: Rst reStructuredText (reader ``rst``). .. rust:variant:: Commonmark CommonMark (reader ``commonmark``). .. rust:variant:: Myst MyST Markdown (reader ``myst``; the read options carry the Sphinx layer). .. rust:variant:: Sphinx reStructuredText with the Sphinx layer (reader ``sphinx``). .. rust:variant:: Typst Native Typst, compiled as it is. .. rubric:: Implementations .. rust:impl:: impl Format :noindex: :for: Format .. rust:method:: pub fn reader(self) -> Option<&'static str> The id of the reader of the format; ``None`` for native Typst, which is compiled. .. rust:enum:: pub enum Target The artifact ``convert_artifact`` publishes. .. rubric:: Variants .. rust:variant:: Html An HTML page (renderer ``html``; Typst's HTML export for Typst input). .. rust:variant:: Pdf A PDF document (renderer ``typst``, then the Typst compiler). .. rust:variant:: Rst reStructuredText source (renderer ``rst``), written as text like HTML. .. rubric:: Implementations .. rust:impl:: impl Target :noindex: :for: Target .. rust:method:: pub fn renderer(self) -> &'static str The id of the renderer that writes the target (PDF goes through Typst). .. rust:enum:: pub enum RefusalChoice What a budget's policy decides about a reservation it cannot hold. .. rubric:: Variants .. rust:variant:: Stop Refuse it, and every later one without asking again. .. rust:variant:: Raise(usize) Raise the limit to this many bytes (more than ``Refusal::limit``) and try again. .. rust:enum:: pub enum Confinement Where a path lies with respect to the roots a project reads from. .. rubric:: Variants .. rust:variant:: Inside Confined: below a root once every link is followed. .. rust:variant:: Outside The path as written is below no root. .. rust:variant:: ThroughLink Written below a readable folder, but a link on the way leads out of the roots. .. rust:enum:: pub enum PathKind What a path names, never following a symbolic link. .. rubric:: Variants .. rust:variant:: File A regular file. .. rust:variant:: Folder A folder. .. rust:variant:: Link A symbolic link, whatever it leads to. .. rust:variant:: Other Anything else (a device, a socket, a pipe). .. rust:enum:: pub enum JobPhase Where a job is. .. rubric:: Variants .. rust:variant:: Waiting Not started. .. rust:variant:: Running Started and not ended. .. rust:variant:: Succeeded Ended with success. .. rust:variant:: Failed Ended with failure. .. rubric:: Functions .. rust:function:: pub fn backend_problem(program: &str) -> Problem The problem of a Typst program that cannot be found (``typst.missing``, exit 4). .. rust:function:: pub fn convert_artifact(registry: &Registry, req: &ArtifactRequest<'_>) -> ArtifactResult Converts one file to a published HTML, PDF, or reStructuredText artifact: reads the input within ``MAX_SOURCE_BYTES``, converts it with ``registry`` (the readers and renderers ``Format::reader`` and ``Target::renderer`` name) and includes confined to the roots, runs Typst for PDF, and publishes atomically, or returns the bytes for ``"-"``. The budget bounds what the route holds: the source, its includes, and the PDF the embedded compiler returns. A failure leaves any existing output unchanged. .. rust:function:: pub fn available_memory() -> Option The memory this machine has free, in bytes: the value of :rust:const:`AVAILABLE_OVERRIDE ` in MiB when set, else what the system reports (GDS 0020). On Linux that is ``MemAvailable`` from ``/proc/meminfo``, lowered to what the process's control group may still use (``cgroup_room``); on macOS, the free, speculative and inactive pages that ``vm_stat`` counts; on Windows, ``ullAvailPhys`` of ``GlobalMemoryStatusEx``. ``None`` when the system does not say. .. rust:function:: pub fn budget_advice(used: usize, need: usize, limit: usize, available: Option, other: &str) -> String The text of ``budget_hint``, for a step that asked for ``need`` bytes while the budget held ``used`` of ``limit``, on a machine with ``available`` bytes free (``None``: unknown). .. rust:function:: pub fn budget_hint(budget: Option<&Budget>, need: usize, other: &str) -> String The hint of a budget's problem: the budget the refused step fits in, from what ``budget`` held and was asked for when it last refused (``need`` when it refused nothing itself), capped by the machine's free memory, and the other way out the caller names (``other``, lower case, without a full stop). .. rust:function:: pub fn budget_problem(what: &str, path: &str, bytes: usize, budget: Option<&Budget>) -> Problem Explains a charge ``budget`` refused (``host.budget``, exit 3): what needed ``bytes``, and where. The hint names a budget that fits (``budget_hint``). .. rust:function:: pub fn fitting_budget(available: usize) -> usize A budget that fits in ``available`` free bytes: nine tenths of it, in steps of 16 MiB; 0 when there is no room for even one step (never offer 0 to the CLI, where it means the default). .. rust:function:: pub fn limits_within(limits: Limits, budget: usize) -> Limits ``limits`` with the byte bounds of one conversion (text pool, output, included sources) lowered to ``budget`` bytes, so no single conversion is allowed more than the whole budget. A ``budget`` of 0 leaves the limits as they are. .. rust:function:: pub fn peak_memory() -> Option The peak resident memory of this process so far, in bytes: ``VmHWM`` from ``/proc/self/status`` on Linux, ``ru_maxrss`` of ``getrusage`` on macOS, and the peak working set on Windows; ``None`` elsewhere or when the system does not say. .. rust:function:: pub fn suggest_budget(used: usize, need: usize, limit: usize, available: Option) -> (usize, bool) The budget in bytes to suggest so that one change is enough: what is held plus the request four times over (a step also holds its output and the copy it writes), or twice the old limit, whichever is larger, in steps of 64 MiB. With ``available`` known and smaller, the budget is capped to ``fitting_budget``, or is what is needed in steps of 16 MiB when even that does not fit; ``fits`` is then false. .. rust:function:: pub fn canonical_roots>(roots: &[P]) -> Vec Resolves ``roots`` to absolute paths with every link followed, as ``confined`` compares paths with them; a root that cannot be resolved is made absolute as written (it then matches nothing that exists through a link, so it never widens what is allowed). .. rust:function:: pub fn confined(roots: &[PathBuf], path: &Path) -> bool Reports whether ``path`` (a document, an image, a template a project reads) lies in one of the canonical ``roots``: written below a root with no link on the way, or below a root once every link is resolved. .. rust:function:: pub fn confinement(roots: &[PathBuf], path: &Path) -> Confinement Tells whether ``confined`` accepts ``path``, and when it does not, whether the path itself or a link on its way leads outside, so a refusal can say which. .. rust:function:: pub fn containing_root<'r>(roots: &'r [PathBuf], path: &Path) -> Option<&'r Path> The root of ``roots`` that ``path`` is written below (or is), comparing whole components and following no link; ``confined`` is the check that follows them. .. rust:function:: pub fn catch_crash(command: impl FnOnce() -> i32) -> i32 Runs ``command`` and returns its exit status; a panic that unwinds out of it prints the crash report to standard error and returns ``CRASH_EXIT``. .. rust:function:: pub fn crash_report(cause: &str) -> String The whole report for ``cause``, from the parts ``install_crash_reporter`` prepared. .. rust:function:: pub fn install_crash_reporter(args: &[String], version: &str) Prepares the crash report for the command line ``args`` (the program name first) and ``version`` (what ``guidedog --version`` prints), and installs a panic hook that records each panic's message and location without printing it. .. rust:function:: pub fn describe(ws: &Workspace, d: &Diagnostic) -> Report Turns a diagnostic of the conversion ``ws`` holds into a report: its message and hint with ``{0}``/``{1}`` filled (span arguments quoted from the sources, cut at 60 characters), the source's path as ``display_path`` shows it, and the line, columns, and excerpt of its span. The report copies what it needs and outlives ``ws``. .. rust:function:: pub fn describe_all(ws: &Workspace) -> Vec Describes every diagnostic the last conversion in ``ws`` reported, in order; the primary error too when the store was full before it, and a note counting the diagnostics the store had no room for. .. rust:function:: pub fn display_path(name: &str) -> String ``name`` relative to the working directory when that reads shorter (not three or more folders above it), and ``name`` itself otherwise, for "" and "-", and for names that are not absolute paths. .. rust:function:: pub fn exit_code(status: Status) -> i32 Maps a conversion status to the exit status Guidedog's commands use: 0 ok, 1 invalid input, unsupported or policy, 3 capacity or limits, 5 internal, 130 cancelled. .. rust:function:: pub fn each_chunk(path: &Path, mut each: impl FnMut(&[u8]) -> bool) -> bool Reads a file through a stack buffer, giving each chunk to ``each`` until it returns false. Returns whether the whole file was read and accepted. .. rust:function:: pub fn read_file(path: &Path, ledger: Option<&Ledger<'_>>, limit: usize) -> Result, Problem> Reads a regular file of at most ``limit`` bytes whole, charging its size to ``ledger`` before allocating; the ledger keeps the charge until the caller discharges or drops it. A file that grows while it is read is refused; one that shrinks keeps its full charge (fewer bytes read do not mean fewer bytes held). .. rust:function:: pub fn read_source(path: &str, limit: usize) -> Result Reads a named input, or standard input for ``"-"``, of at most ``limit`` bytes, checks that it is UTF-8 and drops a leading byte order mark. Fails with ``host.io``, ``host.file-type``, ``host.limit.source``, or ``host.utf8`` (with the line and column of the first bad byte). .. rust:function:: pub fn read_stream(stream: &mut impl Read, name: &str, limit: usize) -> Result, Problem> Reads a stream of unknown length (a pipe, standard input) within ``limit`` bytes, probing one byte past the limit: neither an endless pipe nor a growing file can force an unbounded allocation. ``name`` names the stream in problems. .. rust:function:: pub fn same_contents(path: &Path, data: &[u8]) -> bool Reports whether the file at ``path`` holds exactly ``data``, reading it in chunks and stopping at the first difference; false when it cannot be read. .. rust:function:: pub fn exchange(a: &Path, b: &Path) -> io::Result Swaps the names of two existing paths in one step where the system can (Linux's ``renameat2`` with ``RENAME_EXCHANGE``, macOS's ``renamex_np`` with ``RENAME_SWAP``), so a reader sees one folder or the other, never neither. ``Ok(false)``, changing nothing, where the system or the file system cannot: the caller then renames in two steps. .. rust:function:: pub fn identity(path: &Path) -> io::Result> The identity of what is at ``path`` (not following a link); ``None`` when nothing is, or where the system gives no inode (Windows). .. rust:function:: pub fn link_file(from: &Path, to: &Path, kind: PathKind) -> io::Result Makes ``to`` name the same file as ``from``: a hard link, or a copy where the file system cannot link (FAT, some network shares), which ``Ok(true)`` reports and the caller must flush. A symbolic link (``kind`` is ``PathKind::Link``) is made again, to the same target. An existing ``to`` is an error, never replaced. .. rust:function:: pub fn list_folder(dir: &Path) -> io::Result> Lists a folder's entries in the order the system gives them, each with its kind from the listing itself (no entry is opened, which matters for thousands of files). .. rust:function:: pub fn path_type(path: &Path) -> io::Result> What is at ``path``, not following a symbolic link; ``None`` when nothing is. .. rust:function:: pub fn remove_path(path: &Path) -> io::Result<()> Removes a file, a link, or an empty folder. .. rust:function:: pub fn remove_tree(path: &Path) -> io::Result<()> Removes what is at ``path``, a whole folder tree included, without following a symbolic link: a link is removed, never what it leads to. A work list replaces recursion, so deep folders cannot exhaust the stack. Nothing at ``path`` is nothing to remove; the first entry that cannot be removed ends it with its error. .. rust:function:: pub fn cancel_probe() -> &'static (dyn Fn() -> bool + Sync) The probe a ``guidedoc::Request`` polls (``request.cancel``) to stop at Ctrl+C; it holds no state of its own. .. rust:function:: pub fn catch_interrupts() -> bool Makes Ctrl+C (SIGINT) set the interrupt flag instead of ending the process, for the whole process. A program calls it once, at the start; false when the system refused. .. rust:function:: pub fn clear_interrupt() Clears the interrupt flag, for a long-running embedder that goes on after a cancel. .. rust:function:: pub fn request_interrupt() Sets the interrupt flag as Ctrl+C does, for an embedder that cancels by other means (a server's stop button, a test). .. rust:function:: pub fn was_interrupted() -> bool Reports whether Ctrl+C was pressed (or ``request_interrupt`` called) since the start. .. rust:function:: pub fn interrupted_problem() -> Problem The problem, with exit status 130, of a command stopped by Ctrl+C. .. rust:function:: pub fn io_problem(path: &Path, error: &std::io::Error) -> Problem Explains an operating-system error on ``path`` (``host.io``, exit 4). .. rust:function:: pub fn folders_of(paths: &[PathBuf], top: &Path) -> Vec Lists, once each and sorted, the folders that hold ``paths`` and those between them and ``top`` (included): the folders whose names a publication adds or changes. A path not below ``top`` gives only its own folder. .. rust:function:: pub fn is_stage_name(name: &str) -> bool Reports whether ``name`` is one ``Stage`` gives a staging file: ``STAGE_PREFIX``, ten digits, then nothing or one extension. Any other name, however close, is not ours. .. rust:function:: pub fn publish(path: &Path, data: &[u8], force: bool) -> Result<(), Problem> Writes ``data`` to ``path`` through a flushed staging file renamed over it, making the folders on its way. An existing ``path`` is refused (``host.output.exists``) unless ``force`` is set; any failure leaves ``path`` unchanged. .. rust:function:: pub fn remove_stages(dir: &Path) Removes, in ``dir`` and every folder below it, the staging files a stopped process (killed, or the machine lost power) left behind: regular files whose names ``is_stage_name`` accepts. Everything else stays; a folder that cannot be listed is left as it is. The caller makes sure no stage below ``dir`` is still in use. .. rust:function:: pub fn sync_all(paths: &[PathBuf]) -> Result<(), Problem> Flushes files and folders to storage, several at once, and returns the first that failed. A folder is flushed so the names in it are durable (skipped on Windows, which keeps them durable itself); a path that is gone or a link has nothing to flush. .. rust:function:: pub fn sync_each(paths: &[PathBuf]) -> Result<(), Problem> Flushes each path in turn on the calling thread, as ``sync_all`` does with threads. .. rust:function:: pub fn write_unsynced(path: &Path, data: &[u8]) -> Result<(), Problem> Writes ``data`` as ``publish`` does (replacing ``path``), but flushes nothing: a publication of many files writes them all, then makes them durable in one pass (``sync_all`` of the files and their ``folders_of``). .. rust:function:: pub fn default_stack_budget(stack: usize) -> usize The budget to use when none is asked for: ``guidedoc::DEFAULT_STACK_BYTES``, or less on a thread too small for it. .. rust:function:: pub fn map_ordered(threads: usize, items: I, init: impl Fn() -> S + Sync, work: impl Fn(&mut S, I::Item) -> R + Sync) -> Vec where I: IntoIterator, I::IntoIter: Send, R: Send Runs ``work`` on every item of ``items`` on ``threads`` workers (through ``run_workers``) and returns the results in the order of ``items``, however the threads interleave. Each worker first makes its own state with ``init`` (a workspace, a highlighter) and passes it to ``work`` for every item it takes; the state is dropped when the worker ends. A panic in ``init`` or ``work`` is raised again on the caller, as ``run_workers`` does. .. rust:function:: pub fn run_with_stack(bytes: usize, work: impl FnOnce() -> R + Send) -> R Runs ``work`` on a thread with a stack of ``bytes`` and returns its result, so a command knows the stack its conversions run on; on the calling thread when no thread can be started. A panic in ``work`` is raised again on the caller. .. rust:function:: pub fn run_workers(count: usize, work: F) where F: Fn(usize) + Sync Runs ``work(i)`` on ``count`` threads at once (``i`` from 0), each with a stack of ``WORKER_STACK_BYTES``, and returns when all have ended; ``work`` takes its share itself (an index taken atomically, for one). A thread that cannot start is left out; when none can, ``work(0)`` runs on the calling thread, so the work is always done. A panic in a worker is raised again on the caller, once every worker has ended, with its original payload. .. rust:function:: pub fn stack_budget_limit(stack: usize) -> usize The largest stack budget a thread with ``stack`` bytes can hold: all but 2 MiB of headroom, and never less than half the stack. An 8 MiB thread holds 6 MiB. .. rubric:: Type Aliases .. rust:type:: pub type OnRefusal = dyn Fn(&Refusal) -> RefusalChoice + Send + Sync The policy a budget asks (at most one call at a time, while its other reservations wait). It must not reserve from the budget it is asked about. .. rubric:: Constants .. rust:const:: pub const AVAILABLE_OVERRIDE: &str = "GUIDEDOG_AVAILABLE_MIB" The environment variable that states the machine's free memory in MiB, for machines whose own report misleads (``available_memory``). .. rust:const:: pub const DEFAULT_BUDGET: usize = 256 << 20 The budget ``guidedog convert`` uses when none is given (256 MiB). .. rust:const:: pub const CRASH_EXIT: i32 = 70 The exit status of a command that crashed: EX_SOFTWARE, which no other failure uses. .. rust:const:: pub const ISSUE_TRACKER: &str Where a crash is to be reported: the issue tracker of whoever distributes the build, set when it is built (``GUIDEDOG_ISSUE_TRACKER=https://...``); "" names none. .. rust:const:: pub const MAX_SOURCE_BYTES: usize = 32 << 20 The default size limit of one input file (32 MiB). .. rust:const:: pub const STAGE_PREFIX: &str = ".guidedog-stage-" Begins the name of every staging file: then ten digits, then the destination's extension (``.guidedog-stage-0123456789.html``). .. rust:const:: pub const WORKER_STACK_BYTES: usize = 8 << 20 The stack of every thread ``run_workers`` and ``run_with_stack`` start (8 MiB, the main thread's usual stack on Linux and macOS).