Gleam Standard Library

repository·main·Indexed 20 days ago

https://github.com/gleam-lang/stdlib

The official standard library for the Gleam programming language. It provides essential modules and functions for common tasks, including string manipulation, Unicode grapheme handling, BitArray operations, base conversion, and bitwise operations for large integers. It is designed for compatibility with Erlang (OTP 26+) and JavaScript runtimes including NodeJS, Deno, Bun, and major web browsers.

Tokens
1.4K
Snippets
4
Records
10
Agent score
22%

What's inside gleam_stdlib

  1. Check Gleam standard library target and compatibility

    main

    The Gleam standard library is designed to work across different runtimes.

    Supported Targets:

    • Erlang
    • JavaScript

    Compatibility Requirements:

    • Erlang: Erlang/OTP 26 and higher.
    • JavaScript: All currently supported versions of NodeJS, Deno, Bun, and major web browsers.
  2. Perform bitwise operations on large integers

    main

    The library implements bitwise operations that work correctly even for integers outside the standard JavaScript 32-bit signed integer range. It automatically switches between standard bitwise operators, manual high/low word splitting, or BigInt arithmetic to maintain precision.

    Supported operations:

    • bitwise_and(x, y)
    • bitwise_or(x, y)
    • bitwise_exclusive_or(x, y)
    • bitwise_not(x)
    • bitwise_shift_right(x, y)
    • bitwise_shift_left(x, y)
  3. Use the Gleam standard library in your code

    main

    Once installed, you can import modules from the standard library, such as gleam/io, to perform tasks like printing to the console.

    import gleam/io
    
    pub fn greet(name: String) -> Nil {
      io.println("Hello " <> name <> "!")
    }
  4. Parse integers and floats from strings

    main

    Use parse_int and parse_float to convert string values into numeric types. Both functions return a Result type to handle invalid input safely.

    • parse_int(value): Returns Result$Ok(int) if the string is a valid integer, otherwise Result$Error(Nil).
    • parse_float(value): Returns Result$Ok(float) if the string is a valid float, otherwise Result$Error(Nil).
    // Example usage (conceptual)
    parse_int("123"); // Result$Ok(123)
    parse_int("abc"); // Result$Error(Nil)
    
    parse_float("123.45"); // Result$Ok(123.45)
  5. Convert integers to and from base strings

    main

    The library provides utilities for base conversion, supporting bases from 2 up to 36.

    • int_to_base_string(int, base): Converts an integer to a string representation in the specified base. The output is always uppercase.
    • int_from_base_string(string, base): Parses a string in a given base back into an integer. Returns Result$Ok(int) on success or Result$Error(Nil) if the string contains invalid characters for that base or is not a valid number.
    int_to_base_string(255, 16); // "FF"
    int_from_base_string("ff", 16); // Result$Ok(255)
  6. Inspect values for debugging

    main

    The inspect(v) function provides a string representation of a value, useful for debugging. It handles various types including List, Dict, BitArray, CustomType, and circular references (returning "//js(circular reference)").

    It also provides specialized formatting for:

    • true/false $\rightarrow$ "True"/"False"
    • null/undefined $\rightarrow$ "//js(null)"/"Nil"
    • Date $\rightarrow$ "//js(Date(...))"
    • Error $\rightarrow$ "//js(...)"
  7. Perform string manipulations

    main

    A variety of string utility functions are available for common tasks:

    • string_replace(string, target, substitute): Replaces all occurrences of target with substitute.
    • string_reverse(string): Returns the reversed string.
    • string_length(string): Returns the number of graphemes in the string (handling Unicode correctly).
    • string_remove_prefix(string, prefix): Removes the prefix if the string starts with it.
    • string_remove_suffix(string, suffix): Removes the suffix if the string ends with it.
    • string_byte_slice(string, index, length): Returns a slice of the string based on byte indices.
    • string_grapheme_slice(string, idx, len): Returns a slice of the string based on grapheme indices.
    • string_codeunit_slice(str, from, length): Returns a slice based on UTF-16 code units.
    • split_once(haystack, needle): Splits a string into two parts at the first occurrence of needle. Returns Result$Ok([before, after]) or Result$Error(Nil).
  8. Work with BitArrays

    main

    The library provides low-level bit manipulation via the BitArray type.

    • bit_array_from_string(string): Creates a BitArray from a string.
    • bit_array_bit_size(bit_array): Returns the total number of bits.
    • bit_array_byte_size(bit_array): Returns the total number of bytes.
    • bit_array_pad_to_bytes(bit_array): Pads the bit array so its size is a multiple of 8 bytes.
    • bit_array_concat(bit_arrays): Concatenates multiple BitArray instances.
    • bit_array_to_string(bit_array): Decodes a BitArray into a UTF-8 string. Returns Result$Error(Nil) if the bit size is not a multiple of 8 or if decoding fails.
    • base64_encode(bit_array, padding): Encodes a BitArray to a Base64 string. Use padding: true to include = padding.
    • base64_decode(sBase64): Decodes a Base64 string into a BitArray. Returns Result$Ok(BitArray) or Result$Error(Nil).
  9. Handle Unicode graphemes and codepoints

    main

    For advanced text processing, use grapheme-aware functions to avoid breaking multi-byte characters or emoji.

    • graphemes(string): Returns a list of all graphemes in the string.
    • pop_grapheme(string): Returns the first grapheme and the remainder of the string as Result$Ok([first, rest]).
    • string_to_codepoint_integer_list(string): Converts a string into a list of its Unicode codepoint integers.
    • utf_codepoint_list_to_string(list): Converts a list of Unicode codepoint integers back into a string.