Grav v1.14.0

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

ImportBrings 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 aliasthe 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

ModuleContents
exceptionException and the standard exception classes
mathMath: roots, powers, trigonometry, rounding, gcd, isPrime, constants; Stats: mean, median, standard deviation, percentiles
randomRandom and Rng: random numbers, shuffling, choosing
resultResult<T, E> and Option<T> data enums
optionalOptional<T>: a value or nothing, as a class
sortSort: sorting and binary search
timsortTimSorter: the sorting algorithm underneath
panicPanic: recovering from panics
gcGC: the cycle collector
reflectClassInfo, FieldInfo, MethodInfo, Decorator: classes, fields and decorators at run time
memMem: how much memory a value uses at run time (sizeOf, deepSizeOf, describe)
iterIterator<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.

ModuleContents
integerInteger: limits, parsing in any base, text (hex, grouped, ordinal), gcd and powers, digits, checked arithmetic, bits, comparators
floatFloat: limits, NaN and Infinity, parsing, rounding, tests, text, comparators
stringString: Str's text functions as methods, plus conversions, characters, natural order
boolBool: parsing ("yes", "on", ...), conversions, comparators
byteByte: ASCII tests and case for the bytes of text (s[i])
decimalDecimal: exact decimal numbers, for money and DECIMAL/NUMERIC columns
nullNull: defaults and checks for T? values (port.orElse(8080))
objectObject: any value's type, text, equality, hash and fields
bigintBigInt: whole numbers of any size, modular arithmetic and primes

collections

ModuleContents
arrayArray<T>: the growable list
listList<T>: a list with collection-style names
dequeDeque<T>: add and remove at both ends
stackStack<T> (last in, first out) and Queue<T> (first in, first out)
hashmapHashMap<K, V>: fast key-value lookup; mapOf
hashsetHashSet<T>: fast membership
mapMap<K, V>: a small map in insertion order
setSet<T>: a small set in insertion order
sortedmapSortedMap<K, V>: keys kept in order
heapPriorityQueue<T>: always the best element next
linkedlistLinkedList<T>: a doubly linked list
bitsetBitSet: a compact set of small integers
bloomBloomFilter: "certainly not seen" or "probably seen", in a little memory
tuplePair<A, B>, Triple<A, B, C> and Quad<A, B, C, D>: what (a, b) builds

text

ModuleContents
stringStr: searching, splitting, trimming, case, padding
strbufStringBuilder: building long strings efficiently
convertFormat: text to numbers and numbers to formatted text
regexRegex: regular expressions: find, match, replace, split
markdownMarkdown: Markdown to HTML (with a safe mode for users' text) and to plain text
unicodeUnicode: normalization (NFC, NFD, NFKC, NFKD) and accents stripped
htmlHtml, HtmlSanitizer: escaping, entities, tags stripped, and an allow-list sanitizer for HTML from users
templateTemplate: Mustache templates over JSON, HTML-escaped by default
diffDiff: line, word and character diffs; unified output and HTML
localeLocale: numbers, money (KES 1,234.50), dates and plural rules by country

data

ModuleContents
jsonJson and JsonValue: parsing, building, writing JSON
json_mapJsonMap: JSON read straight into objects and written back
json_schemaJsonSchema: checking JSON against a schema, and a schema from a class
msgpackMsgPack: MessagePack read into and written from JsonValue
otpTotp and Hotp: two-factor one-time passwords
tarTarWriter and TarReader: tar archives, streamed (with gzip: .tar.gz)
bytesBytes: a buffer of raw bytes
encodingBase64, Hex, Utf8
hashHash (SHA-256, SHA-1, MD5, CRC-32, FNV-1a, random tokens), Uuid (v4, v7) and Ulid
csvCsv: reading and writing comma-separated values
compressCompress: gzip, zlib and raw deflate (system zlib); GzipWriter and GzipReader streams
cryptoCrypto (SHA-2 digests, HMAC, random bytes), AesGcm, CryptoKey (RSA, ECDSA, Ed25519: sign, verify, PEM, JWK), PasswordHash (scrypt)
jwtJwt, JwtKey, Jwks, JwtOptions: JSON Web Tokens (HS, RS, ES, EdDSA) and key sets
tomlToml: TOML 1.0 read into and written from JsonValue
yamlYaml: YAML 1.2 read into and written from JsonValue
zipZipWriter, ZipReader: ZIP archives (stored or deflated), safe extraction
xmlXml, XmlNode: XML parsed, queried by path, written; DTDs refused
mimeMimeType: media types by extension and back
imageImage: PNG and JPEG read and written, resized, cropped, rotated; thumbnails
qrcodeQrCode: QR codes as SVG, PNG, an Image or terminal text
pdfPdfDocument, PdfPage, PdfTable: PDFs with text, fonts, tables, images, QR codes and links
protobufProtoSchema, ProtoWriter, ProtoReader: Protocol Buffers from a .proto schema, as JSON
semverSemver: semantic versions, ordering and npm-style ranges

io

ModuleContents
ioIO: console input and output, printRaw, eprint, readLine
fsFile, Dir, FileReader, FileWriter: files and folders, walking and globbing
pathPath: building and splitting paths
termTerm: colours and cursor control in the terminal
watchFileWatcher: files created, changed or deleted under some paths

sys

ModuleContents
osOS: platform, user, environment variables
commandCommand: running programs without a shell
processProcess: running shell command lines
timeTime, Stopwatch and Duration: clocks, measuring, lengths of time
datetimeDateTime: calendar dates and times, parsing and arithmetic
cronCron: cron expressions, when they are next or last due
logLog and Logger: leveled logging to standard error or a file
argsArgs: command-line options, flags and --help
metricsMetricsRegistry: counters, gauges, histograms and process metrics in the Prometheus format

concurrency

ModuleContents
asyncAsync, Mutex, AtomicInt, AtomicLong, AtomicBool, Channel<T>, awaitAll
threadThread, WaitGroup, CountDownLatch, Semaphore, RWLock, Once
sharedThreadLocal<T>, ConcurrentMap<K, V>, LruCache<K, V>: per-thread values, a sharded map, a bounded cache
retryRetry: trying again with exponential backoff and jitter, within a deadline
ratelimitTokenBucket, TokenBuckets, SlidingWindow: rate limits in memory
poolPool<T>: reusable connections and buffers, capped, health-checked, shared by threads
generatorGenerator<T>: what a function that yields becomes

net (import "std/net")

ModuleContents
tcpTcpStream, TcpListener, Net: TCP clients and servers
tlsTls, TlsContext: encrypted connections (OpenSSL), certificates
udpUdpSocket, UdpPacket: datagrams
unixUnixSocket: local connections through a file path
ipIpAddress, Cidr: IPv4/IPv6 addresses and ranges
urlUrl: parsing, building, resolving links, percent-encoding
httpHttpRequest, HttpResponse, Headers, Cookie, FormData, streaming and server-sent events
http_serverHttpServer, Cors: routing, CORS, HTTPS, conditional and range requests
http_clientHttpClient: pooled keep-alive, HTTPS, redirects, auth, cookies
http2Http2Client: HTTP/2 requests, many at once on one connection
websocketWebSocket: two-way connections over HTTP (ws://, wss://)
smtpSmtpClient, EmailMessage: sending email with STARTTLS and login
dnsDns, 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:

MemberMeaning
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) -> boolwhether 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