The standard library
The standard library is written in Grav itself (with inline C where it talks to the operating system) and ships with the compiler. Its source is in lib/; every public function there has a doc comment, which editors show on hover and these pages list.
#Importing
| Import | Brings in |
import "std" | every category below except net |
import "std/<category>" | one category, e.g. import "std/collections" |
import "std/<category>/<module>" | one module, e.g. import "std/collections/hashmap" |
import { A, B as C } from "std/<category>" | only the names listed |
import "std/<category>" as alias | the names behind a prefix: alias.Json |
Each category is a namespace (std.core, std.collections, ...). Importing makes its names usable without the prefix, and your own declarations take priority over the library's. See Modules and packages.
#Modules
#core
| Module | Contents |
| exception | Exception and the standard exception classes |
| math | Math: roots, powers, trigonometry, rounding, gcd, isPrime, constants; Stats: mean, median, standard deviation, percentiles |
| random | Random and Rng: random numbers, shuffling, choosing |
| result | Result<T, E> and Option<T> data enums |
| optional | Optional<T>: a value or nothing, as a class |
| sort | Sort: sorting and binary search |
| timsort | TimSorter: the sorting algorithm underneath |
| panic | Panic: recovering from panics |
| gc | GC: the cycle collector |
| reflect | ClassInfo, FieldInfo, MethodInfo, Decorator: classes, fields and decorators at run time |
| mem | Mem: how much memory a value uses at run time (sizeOf, deepSizeOf, describe) |
| iter | Iterator<T> and Iterable<T>: what for (x in v) walks besides positions |
#types
Each class's static methods whose first parameter is the value are also methods of the value itself: n.toHex() is Integer.toHex(n), s.trim() is String.trim(s), one direct call with nothing boxed. A cast converts through them too: "42" as int, price as float, 19.99 as Decimal.
| Module | Contents |
| integer | Integer: limits, parsing in any base, text (hex, grouped, ordinal), gcd and powers, digits, checked arithmetic, bits, comparators |
| float | Float: limits, NaN and Infinity, parsing, rounding, tests, text, comparators |
| string | String: Str's text functions as methods, plus conversions, characters, natural order |
| bool | Bool: parsing ("yes", "on", ...), conversions, comparators |
| byte | Byte: ASCII tests and case for the bytes of text (s[i]) |
| decimal | Decimal: exact decimal numbers, for money and DECIMAL/NUMERIC columns |
| null | Null: defaults and checks for T? values (port.orElse(8080)) |
| object | Object: any value's type, text, equality, hash and fields |
| bigint | BigInt: whole numbers of any size, modular arithmetic and primes |
#collections
| Module | Contents |
| array | Array<T>: the growable list |
| list | List<T>: a list with collection-style names |
| deque | Deque<T>: add and remove at both ends |
| stack | Stack<T> (last in, first out) and Queue<T> (first in, first out) |
| hashmap | HashMap<K, V>: fast key-value lookup; mapOf |
| hashset | HashSet<T>: fast membership |
| map | Map<K, V>: a small map in insertion order |
| set | Set<T>: a small set in insertion order |
| sortedmap | SortedMap<K, V>: keys kept in order |
| heap | PriorityQueue<T>: always the best element next |
| linkedlist | LinkedList<T>: a doubly linked list |
| bitset | BitSet: a compact set of small integers |
| bloom | BloomFilter: "certainly not seen" or "probably seen", in a little memory |
| tuple | Pair<A, B>, Triple<A, B, C> and Quad<A, B, C, D>: what (a, b) builds |
#text
| Module | Contents |
| string | Str: searching, splitting, trimming, case, padding |
| strbuf | StringBuilder: building long strings efficiently |
| convert | Format: text to numbers and numbers to formatted text |
| regex | Regex: regular expressions: find, match, replace, split |
| markdown | Markdown: Markdown to HTML (with a safe mode for users' text) and to plain text |
| unicode | Unicode: normalization (NFC, NFD, NFKC, NFKD) and accents stripped |
| html | Html, HtmlSanitizer: escaping, entities, tags stripped, and an allow-list sanitizer for HTML from users |
| template | Template: Mustache templates over JSON, HTML-escaped by default |
| diff | Diff: line, word and character diffs; unified output and HTML |
| locale | Locale: numbers, money (KES 1,234.50), dates and plural rules by country |
#data
| Module | Contents |
| json | Json and JsonValue: parsing, building, writing JSON |
| json_map | JsonMap: JSON read straight into objects and written back |
| json_schema | JsonSchema: checking JSON against a schema, and a schema from a class |
| msgpack | MsgPack: MessagePack read into and written from JsonValue |
| otp | Totp and Hotp: two-factor one-time passwords |
| tar | TarWriter and TarReader: tar archives, streamed (with gzip: .tar.gz) |
| bytes | Bytes: a buffer of raw bytes |
| encoding | Base64, Hex, Utf8 |
| hash | Hash (SHA-256, SHA-1, MD5, CRC-32, FNV-1a, random tokens), Uuid (v4, v7) and Ulid |
| csv | Csv: reading and writing comma-separated values |
| compress | Compress: gzip, zlib and raw deflate (system zlib); GzipWriter and GzipReader streams |
| crypto | Crypto (SHA-2 digests, HMAC, random bytes), AesGcm, CryptoKey (RSA, ECDSA, Ed25519: sign, verify, PEM, JWK), PasswordHash (scrypt) |
| jwt | Jwt, JwtKey, Jwks, JwtOptions: JSON Web Tokens (HS, RS, ES, EdDSA) and key sets |
| toml | Toml: TOML 1.0 read into and written from JsonValue |
| yaml | Yaml: YAML 1.2 read into and written from JsonValue |
| zip | ZipWriter, ZipReader: ZIP archives (stored or deflated), safe extraction |
| xml | Xml, XmlNode: XML parsed, queried by path, written; DTDs refused |
| mime | MimeType: media types by extension and back |
| image | Image: PNG and JPEG read and written, resized, cropped, rotated; thumbnails |
| qrcode | QrCode: QR codes as SVG, PNG, an Image or terminal text |
| pdf | PdfDocument, PdfPage, PdfTable: PDFs with text, fonts, tables, images, QR codes and links |
| protobuf | ProtoSchema, ProtoWriter, ProtoReader: Protocol Buffers from a .proto schema, as JSON |
| semver | Semver: semantic versions, ordering and npm-style ranges |
| Module | Contents |
| io | IO: console input and output, printRaw, eprint, readLine |
| fs | File, Dir, FileReader, FileWriter: files and folders, walking and globbing |
| path | Path: building and splitting paths |
| term | Term: colours and cursor control in the terminal |
| watch | FileWatcher: files created, changed or deleted under some paths |
#sys
| Module | Contents |
| os | OS: platform, user, environment variables |
| command | Command: running programs without a shell |
| process | Process: running shell command lines |
| time | Time, Stopwatch and Duration: clocks, measuring, lengths of time |
| datetime | DateTime: calendar dates and times, parsing and arithmetic |
| cron | Cron: cron expressions, when they are next or last due |
| log | Log and Logger: leveled logging to standard error or a file |
| args | Args: command-line options, flags and --help |
| metrics | MetricsRegistry: counters, gauges, histograms and process metrics in the Prometheus format |
#concurrency
| Module | Contents |
| async | Async, Mutex, AtomicInt, AtomicLong, AtomicBool, Channel<T>, awaitAll |
| thread | Thread, WaitGroup, CountDownLatch, Semaphore, RWLock, Once |
| shared | ThreadLocal<T>, ConcurrentMap<K, V>, LruCache<K, V>: per-thread values, a sharded map, a bounded cache |
| retry | Retry: trying again with exponential backoff and jitter, within a deadline |
| ratelimit | TokenBucket, TokenBuckets, SlidingWindow: rate limits in memory |
| pool | Pool<T>: reusable connections and buffers, capped, health-checked, shared by threads |
| generator | Generator<T>: what a function that yields becomes |
#net (import "std/net")
| Module | Contents |
| tcp | TcpStream, TcpListener, Net: TCP clients and servers |
| tls | Tls, TlsContext: encrypted connections (OpenSSL), certificates |
| udp | UdpSocket, UdpPacket: datagrams |
| unix | UnixSocket: local connections through a file path |
| ip | IpAddress, Cidr: IPv4/IPv6 addresses and ranges |
| url | Url: parsing, building, resolving links, percent-encoding |
| http | HttpRequest, HttpResponse, Headers, Cookie, FormData, streaming and server-sent events |
| http_server | HttpServer, Cors: routing, CORS, HTTPS, conditional and range requests |
| http_client | HttpClient: pooled keep-alive, HTTPS, redirects, auth, cookies |
| http2 | Http2Client: HTTP/2 requests, many at once on one connection |
| websocket | WebSocket: two-way connections over HTTP (ws://, wss://) |
| smtp | SmtpClient, EmailMessage: sending email with STARTTLS and login |
| dns | Dns, DnsResolver: SRV, TXT, MX, A/AAAA and other records from the name servers, cached |
#Conventions
The collections share one shape, so moving from one to another is easy:
| Member | Meaning |
size() (also length()) | the number of elements |
isEmpty(), clear() | emptiness, removing everything |
contains(x) | membership |
forEach(f), toArray() | visiting every element, copying into an Array |
get(i), c[i] | indexed access, where it makes sense; always bounds-checked |
getOr(k, fallback), peekOr(fallback) | lookups that never fail |
remove(x) -> bool | whether something was removed |
for (x in c) | works on every collection with indexed access |
toString() | the contents as text: [1, 2] for sequences, {1, 2} for sets, {"a": 1} for maps, ("a", 1) for pairs; strings in quotes |
Across the library:
- Misuse throws an exception from
exception: IndexError for bad positions, StateError for taking from something empty, NotFound for missing keys in strict lookups, ValueError for bad arguments, IOError for the outside world (file writes instead return false when they fail).
- Methods that build a collection return a new one (
keys(), toArray(), filter, map), so changing the result never changes the source.
- Most builder-style methods return the object, so calls chain:
sb.append("a").append("b"), new Command("ls").arg("-l").run().
- Static-function classes (
Str, Math, Path, Format, OS, Time) group related functions; you never create them.
#Built-in functions
print, str, input, argv, assert, panic and the other functions that need no import are described in the built-ins reference.
#About the API sections
Each page has a hand-written introduction and examples, followed by an API section generated from the library source by gen-api.js. Run node docs/std/gen-api.js after changing the library; the test suite checks that the pages are up to date.
Edit this page on GitHub