Standard library reference
The Salam libraries
Salam ships with its whole library built in, from text, numbers, files, networking and SQL to database drivers, machine learning, audio, gRPC and OpenSearch: there is nothing to install or add before you import a package. Every package has a page here, and every function, struct and constant comes with a plain explanation and a complete example. Every example is run before the site is published, so the output you see is the output you will get.
Basics
coreStopping a program with a clear message, and Option for a value that may or may not be there.ioReading from the keyboard, reading and writing files, and writing to standard error.fmtTurning numbers and booleans into text, aligning text, and building a string from a template.convConverting numbers and booleans to text and back, including Persian digits, with errors for text that is not a number.text.diffComparing two texts line by line, printing the difference as a unified diff and measuring how alike they are.textConverting a string to UTF-16 and back, for Windows and libraries that want that format.
Text
strEverything to do with text: searching, slicing, replacing, digits, case, and building long strings.unicodeWhat Unicode knows about a character: category, script, writing direction, case, decomposition and composition.arabicNormalising Arabic-script text: Arabic yeh and kaf, vowel marks, tatweel, the zero width non-joiner and digits, for search and comparison.bidiThe Unicode bidirectional algorithm: the right display order when right to left and left to right text are mixed.regexSearching and replacing with a pattern: finding a number, an email address or a date in text and pulling it apart.templateFilling text and HTML templates with values, with automatic escaping for safety.i18nA multilingual program: translating messages, placing values into them and choosing singular or plural.
Numbers and collections
mathThe basic mathematics: powers and roots, logarithms, trigonometry, rounding, minimum and maximum, and the greatest common divisor.randRandom numbers, text and choices: dice, one-time codes, unique identifiers and shuffling a list.statsDescriptive statistics over a list of numbers: mean, median, variance, standard deviation and percentiles.typesRecognising the type of a value from its text: a whole number, a decimal, a boolean or ordinary text?bigintWhole numbers of unlimited size: large factorials, cryptography, and any arithmetic that will not fit in 64 bits.decimalExact decimal numbers for money and accounting, with none of the rounding error of floating point.sortSorting vectors with the default or your own comparison, binary search, and a dozen sorting algorithms to learn from.collectionsData structures: vector and map, stack, queue, deque, set, linked list, priority queue and counter.matrixLinear algebra: matrices, systems of equations, decompositions, eigenvalues and statistics.graphGraph theory: traversal, shortest paths, spanning trees, flow, coloring, communities and centrality.
System and tools
osFiles, directories, system commands, program arguments and environment variables.os.errorThe last error from a file or process operation: its code, its message and the path that failed.os.platformIdentifying the system the program is running on: the operating system, the processor, the core count and the memory.os.dlLoading shared libraries at run time, looking up their functions and calling a function pointer with up to eight integer or pointer arguments.os.mmapMemory pages with read, write and execute permissions: map, change the permissions of and release them.os.processRunning other programs, talking to them through pipes, reading with a time limit, telling an exit code from a signal, and stopping them.os.shellRunning a command and getting its exit code, its output and its errors together.os.tempMaking a temporary file or directory under a unique name.os.userWho is running the program, and the standard directories that belong to them.fsReading, writing, copying and moving files, file information, times and permissions, and MD5 and SHA digests.fs.dirCreating, listing, copying, moving and removing directories.fs.fileDeprecated: every function forwards to fs. Write import fs instead of import fs.file.fs.pathWorking with file paths: joining them, separating the name and the extension, absolute and relative paths, and a safety check.filepathPath functions that never touch the file system; the same work as the fs.path package.envEnvironment variables: reading them with the right type, .env files, the run profile, and masking sensitive values.flagReading command line options such as--port 8080and-vwith the right type, and generating the help text.cliCommand line programs with several commands, likegit commit, and asking the user questions.configReading and writing INI, env and YAML settings files with dotted keys.logRecording what a program does, with levels, a prefix, structured fields, JSON output and writing to a file.debugTools for finding a bug: assertions, a hand-kept call stack, tracing and timing.runtimeFacts about the running program: the system, the memory, the uptime and the build options.testingWriting tests for your code: equality assertions, a pass and fail count, and a summary at the end.errorThe one Error type behind throw, try and catch: a kind, a message, where it happened, and a retry policy.memWorking with memory directly: allocating and freeing, copying, arenas and pools, and leak checking.termText colour and style, cursor movement, progress bars, reading keys and the mouse, and the terminal size.cpuUse the processor's AES and carry-less multiply instructions, and ask what the processor offers.os.ptyRunning a program on a pseudo terminal: waiting for its prompt, typing keys, and changing the window size.os.signalWaiting for operating system signals: stopping cleanly on Ctrl+C or SIGTERM, noticing terminal resizes, and controlling which thread receives a signal.tuiFull-screen terminal programs: widgets, layout, focus, keys, mouse and resizing, drawn into a buffer and repainted only where something changed.
Time and concurrency
timeThe current time, durations, formatting and parsing dates, the monotonic clock, timers and tickers.calendarThe Jalali, Hijri and Gregorian calendars: conversion, day arithmetic, month names and time zones.threadHolding and waiting for the threads thatspawncreates.syncMutexes, condition variables, wait groups, read-write locks, semaphores and once, for coordinating threads.atomicA counter and a flag that several threads can change safely without taking a lock by hand.chanA channel for passing values from one thread to another, with a buffer, timeouts and closing.poolParallel loops, a bounded worker pool, goroutine-style tasks, error groups and futures.ctxA context for cancellation and deadlines, passed from the main piece of work down to the smaller ones.cronCron expressions with optional seconds, interval, daily, weekly, monthly and one-time jobs, tags, limits and hooks, each job on its own thread.eventsAn in-process event emitter: dotted topics with wildcards, one-shot handlers, and an optional worker thread.
Encoding and data
encodingTurning text and data into Base64, hexadecimal and URL encoding.encoding.jsonBuilding and reading JSON: from a plain string through automatic struct conversion to streaming.encoding.yamlReading YAML by path, building and writing it, and converting it to JSON.encoding.csvReading and writing CSV files, with correct quoting and conversion to a dynamic value.encoding.tomlReading and writing TOML configuration files.encoding.htmlTurning HTML entities, named and numeric, into text, and text into safe HTML.encoding.urlTaking a web address apart, building and editing its parameters, and resolving relative addresses.encoding.queryReading and building the query string of a web address, such asq=hello&page=2.encoding.envfileReading and writing.envfiles, with variable substitution.encoding.valueA dynamic value for data whose shape you do not know in advance; the shared language of every format in this group.encoding.serdeDetecting the format of a piece of text and converting JSON, YAML, TOML, XML and CSV into one another.encoding.msgpackThe compact binary MessagePack format for dynamic values.encoding.binaryWriting and reading numbers as bytes, big-endian or little-endian.encoding.xmlReading, building and writing XML, with XPath, DTD validation, namespaces and a light simple interface.encoding.protobufReading.protofiles, the Protocol Buffers wire encoding, and generating Salam code from them.compressByte buffers, compression methods from RLE through DEFLATE, gzip, bzip2, zstd and checksums.archiveMaking, listing, checking and extracting zip, tar, tar.gz, tar.zst, gzip, zstd and RAR files, with passwords and multi-volume RAR.npyReading and writing NumPy.npyand.npzfiles.excelReading and writing Excel (xlsx), OpenDocument (ods) and CSV spreadsheets: sheets, cells, styles, formulas and dates.dataReading data for machine learning: CSV tables, batching samples, MNIST and images, and synthetic data.
Network
net.tcpTCP servers and clients: listening, connecting, reading and writing, TLS and a connection pool.net.udpSending and receiving UDP packets, with broadcast and multicast.net.dnsFinding the address of a name and asking for any kind of DNS record.net.mimeThe media type of a file, the Content-Type header, and multipart form bodies.net.proxyConnecting through an HTTP or SOCKS5 proxy, alone or in a chain.net.routerRouting HTTP requests, with parameters, groups and static files.net.emailSending email over SMTP and reading it over IMAP and POP3.net.websocketA two way connection that stays open between browser and server, with rooms for broadcasting.net.httpHTTP servers and clients: handlers, text and JSON responses, cookies and sending requests.net.http.middlewareThe usual security, cache and CORS headers, and request logging, in one call.net.http.validateChecking form input and answering with a 400.net.http.sessionUser sessions over a cookie: keeping data between requests, and a CSRF token.net.http.swaggerWriting OpenAPI documentation for an API and serving the documentation page.net.http2The HTTP/2 protocol from the ground up: frames, HPACK header compression and streams.net.socketioA Socket.IO client: events, acknowledgements, namespaces and automatic reconnection.sshSSH connections, running a command on a server, and working with files over SFTP.ftpAn FTP and FTPS client: listing a directory, uploading and downloading files.rpcJSON-RPC 2.0 and MessagePack-RPC: a server, a client and registering methods.grpcA gRPC server and client over HTTP/2: unary and streaming calls, metadata and status codes.net.httpdA web server driven by a config file: several sites on one port, locations, redirects, caching, static files and FastCGI backends such as PHP.net.httpd.confThe reader of the web server config: blocks, settings and values in Salam block syntax, with positions for errors.net.fastcgiA FastCGI client: run PHP or any FastCGI program behind a Salam server.net.natsA NATS client: publish and subscribe, request and reply, queue groups, automatic reconnection, JetStream and a key value helper.net.tunnelThe shared core for proxy and VPN style tools: streams, addresses, dialers and proxy chains, a mixed inbound, routing rules with an Iran preset, share links and v2ray style configs.net.socksSOCKS4, SOCKS4a and SOCKS5: a client with login, BIND and UDP associate, a server with users, access rules and a pluggable way to reach targets, and a connector for proxy chains.net.httpproxyAn HTTP and HTTPS proxy: a client with Basic login and CONNECT tunnels, a server that forwards plain requests and opens tunnels, with access rules, TLS and a connector for proxy chains.net.trojanThe Trojan protocol: a TLS client and server that look like an ordinary HTTPS site, a fallback website for everyone who is not a client, WebSocket mode, UDP and a connector for proxy chains.net.dohEncrypted DNS: a resolver over DNS over HTTPS and DNS over TLS with server failover and a TTL cache, plain UDP DNS as a fallback, presets, and a local stub server for other programs.net.censorHelpers for networks that interfere with traffic: protocol sniffing and TLS server name reading, ClientHello fragmentation, padding, domain rule sets with Iran lists, a probe guard and a replay cache.net.shadowsocksA Shadowsocks client and server: AEAD and Shadowsocks 2022 ciphers, ss:// links, simple-obfs, a UDP relay, and a stream that runs over any tunnel.Stream.net.transportThe byte stream under the VPN protocols: TCP, TLS, WebSocket and HTTP upgrade connections with SNI, ALPN and ClientHello fragmentation, plus byte buffers and addresses.net.vlessThe VLESS proxy protocol: client and server, TCP and UDP, vless:// share links, over TCP, TLS, WebSocket or any tunnel stream.net.vmessThe VMess proxy protocol, AEAD form only: encrypted client and server, TCP and UDP, over TCP, TLS, WebSocket or any tunnel stream, with the cryptographic building blocks exposed.net.realityThe REALITY security layer of Xray: a client that proves itself inside a TLS 1.3 handshake, a server that shows everyone else the real website, key and short id helpers, and link parameters.net.vpnOne call that registers every proxy protocol with net.tunnel, so a v2ray style JSON config runs both sides, with a ready to use runner.net.utlsTLS ClientHello fingerprints: build the first message of a TLS 1.3 handshake in the byte layout of Chrome, Firefox or Safari, compute JA3 strings, and run a handshake from it.
Web and services
domWorking with a web page in the browser: elements, events, timers and JavaScript objects.web.canvasDrawing shapes, text and images on a browser canvas element.web.keysKeyboard state for browser games.webpushSending notifications to browsers from a server, with VAPID keys and the standard encryption.graphqlA GraphQL server: schemas, resolvers, query execution and HTTP handling.googleGoogle service account authentication for the Google APIs.telegram.botBuilding a bot with the Bot API: messages, buttons, webhooks and a polling loop.nodeA Salam program under Node.js: modules, files, processes and JavaScript objects.awsAmazon S3, SQS and STS, and any S3 compatible service, with Signature Version 4.
Security and cryptography
cryptoSHA and MD5 digests, HMAC signatures, secure random numbers and password hashing.jwtMaking and checking JWT tokens, and guarding API routes.tlsSecure TLS 1.3 and 1.2 connections and public key cryptography tools, with no OpenSSL needed.sslA familiar OpenSSL style interface for secure connections, on top of Salam's own TLS.
Database
db.sqlRead, check and type SQL without a database: a dialect-aware parser, a schema catalog and typed placeholders.dbOne interface shared by the database engines, schema migrations and a connection pool.db.sqliteAn SQLite database in one file or in memory.db.mysqlConnecting to MySQL and MariaDB.db.postgresA PostgreSQL client written in Salam: connection strings and URIs, TLS, queries, transactions, pools and migrations.db.redisA Redis client: keys and values, hashes, lists, sets and publishing.db.typesenseA Typesense client: collections, documents, typo tolerant, faceted, grouped, vector and union search, synonyms, curation, API keys, analytics and clusters.db.elasticsearchAn Elasticsearch and OpenSearch client: documents, search, aggregations, bulk, SQL and index management.db.meilisearchA Meilisearch client: indexes, documents, full text, faceted, hybrid and federated search, settings, tasks and API keys.db.opensearchAn OpenSearch client: documents, bulk, the query DSL, aggregations, scroll and point in time, index admin, SQL and PPL, k-NN vector search, ISM, security and AWS signing.db.clickhouseA ClickHouse client over the HTTP interface: statements, typed rows, batch inserts and the shared db interface.
Compiler and tools
AI
ai.optimNeural network optimisers: SGD, Adam, RMSProp and learning rate schedules.ai.onnxReading and running ONNX models with no outside dependency.ai.ggufReading GGUF model files, the llama.cpp format.ai.tensorMulti dimensional arrays and numeric operations for machine learning.ai.autogradReverse mode automatic differentiation for training models.ai.nnNeural network layers: linear, convolutional, recurrent, transformer, and checkpoints.ai.llmRunning Llama and Qwen language models from a GGUF file.imageReading, editing and saving images, and writing text on them.ai.mlClassic machine learning: preprocessing, regression, classification, trees, clustering and evaluation.opencvComputer vision with OpenCV: image processing, features, face detection, neural networks and video.
Graphics and games
gui.webviewA native window around HTML, and a whole desktop application layer on top of it.gui.raylibGames and graphics with raylib: windows, 2D and 3D drawing, textures, text, input and audio.gui.webview.packThe file format that holds an application's web files.gui.webview.bundleWhatsalam bundleruns to make installers.colorColours for the Salam UI standard: every colour syntax in English and Persian, checked with clear errors, conversion between colour spaces, mixing in oklab, light and dark pairs, contrast and the CSS the web target emits.gui.colorColours for the Salam UI standard: every colour syntax in English and Persian, checked with clear errors, conversion between colour spaces, mixing in oklab, light and dark pairs, contrast and the CSS the web target emits.gui.flowThe layout engine of the Salam style standard: column, row, grid, stack and flow layouts, positioning, scrolling and right to left, with incremental relayout.gui.styleThe Salam UI style standard: every property with its English and Persian name, value syntax, validation with clear errors, defaults per element, inheritance, interpolation for transitions and the CSS the web target writes.
Audio
audioSound as a clip of samples: cutting, mixing, measuring and converting it.audio.wavReading and writing WAVE files: PCM, floating point, A-law and mu-law.audio.dspA Fourier transform, windows, filters and resampling for sound.audio.codecOpen and save a sound file without naming its format.audio.aiffReading and writing AIFF and AIFF-C files.audio.auReading and writing the Sun and NeXT au format.audio.flacLossless compression: reading and writing FLAC.audio.tagReading and writing the tags on a song: title, artist, album and cover art.audio.musicNotes, scales, chords and tunings, Persian dastgah among them.audio.synthMaking sound from nothing: oscillators, envelopes and voices.audio.midiReading, writing and playing standard MIDI files.audio.mp3Reading the frames, headers and VBR tags of an mp3 file.
Trading
Language and runtime
Every package ships with its own API: salam doc str generates the full reference of one from the source. If the language itself is new to you, start with the course.