fmt

A simple and efficient string formatting library for MoonBit.

fmt
formatting
string
moon add BigOrangeQWQ/fmt@0.2.0
Download zip
Version
0.2.0
License
Apache-2.0
Last updated
last year
Downloads
1K

Dependencies

README

#BigOrangeQWQ/fmt

This library provides powerful formatting capabilities similar to Python's str.format, supporting multi-type and multi-style string formatting. The underlying float-to-string algorithm is based on Moonbit Core Ryu.

#Struct to Json automatically

struct TestObj {
name : String
age : Int
} derive(ToJson)

jprintln("Hello {:05} {}", [1, { name: "Alice", age: 30 }])
// Output: Hello 00001 {"name": String("Alice"), "age": Number(30)}

#Multiple arguments and brace escaping

let parts = "{0} {1} {{not things}} {1} {2:.2f}"
fprintln(parts, ["hello", "world", 42])
// Output: hello world {not things} world 42.00

#Positional arguments

fprintln("{} {} {}", ["hello", "world", 42])
// Output: hello world 42

#Radix and prefix formatting

fstring("{:o}", [8]) // "10"
fstring("{:#o}", [8]) // "0o10"
fstring("{:b}", [16]) // "10000"

#Alignment and padding

fstring("{:>>30}", ["test"]) // ">>>>>>>>>>>>>>>>>>>>>>test"
fstring("{:<<30}", ["test"]) // "test<<<<<<<<<<<<<<<<<<<<<<"
fstring("{:^^30}", ["test"]) // "^^^^^^^^^^^test^^^^^^^^^^^"

#Grouping separators

fstring("{:_d}", [4285565, 59]) // "428_556_5"
fstring("{:,d}", [4285565, 3]) // "428,556,5"
fstring("{:#_b}", [4285565, 3]) // "0b1000_0010_1100_1000_1111_101"

#Precision

fstring("{:.5E}", [42.5]) // 4.25000E+01
fstring("{:.10e}", [4464252.51334]) // 4.4642525133e+06
fstring("{:.17e}", [4464252.51334]) // 4.46425251334000006e+06

  • For decimal types, a separator is added every 3 digits; for other bases, every 4 digits. Comma (,) is only supported for decimal types.

#Formatting Syntax Reference

Syntax ExampleDescriptionOutput Example
{}Automatic sequential argumenthello (argument: "hello")
{0}Positional argumentworld (argument: ["hello", "world"])
{{ / }}Output a single { or }{ or }
{:05}Width 5, left pad with 000042
{:>10}Width 10, right align test
{:<10}Width 10, left aligntest
{:^10}Width 10, center aligntest
{:*^10}Center align, fill with ****test***
{:b} / {:#b}Binary / with prefix10000 / 0b10000
{:o} / {:#o}Octal / with prefix10 / 0o10
{:x} / {:#x}Hex lower / with prefixff / 0xff
{:X} / {:#X}Hex upper / with prefixFF / 0XFF
{:d}Decimal integer42
{:05d}Width 5, left pad 0 decimal00042
{:e} / {:E}Scientific notation (lower/upper E)4.25e+1 / 4.25E+1 (argument: 42.5)
{:.2f}Float with 2 decimal places3.14 (argument: 3.1415)
{:%}Percent format, auto multiply by 1004250.00% (argument: 42.5)
{:>>10}Width 10, right align, fill >>>>>>>>test
{:_d}Decimal grouped with underscore428_556_5
{:,d}Decimal grouped with comma428,556,5
{:#_b}Base grouped with underscore & prefix0b1000_0010_1100_1000_1111_101

Note: Comma (,) as a grouping separator is only supported for decimal types; binary, octal, and hexadecimal only support underscore (_) as a separator.

#Thanks

The float-to-string conversion code is from the standard library Core

#
Formatter

pub(open) trait Formatter : Show {
format(Self, FormatSpec) -> String = _
display(Self, FormatSpec, Logger) -> Unit = _
}

impl Formatter for Bool
impl Formatter for Char
impl Formatter for Int
impl Formatter for Int16
impl Formatter for Int64
impl Formatter for UInt
impl Formatter for UInt16
impl Formatter for UInt64
impl Formatter for Float
impl Formatter for Double
impl Formatter for String
impl Formatter for BigInt
impl Formatter for Json

#
Align

pub enum Align {
Left
Right
Center
}

impl Eq for Align
impl Show for Align

#
FormatSpec

pub struct FormatSpec {
options : Options
width : Int?
grouping : Grouping
precision : Int?
typ : SpecType
}

impl Show for FormatSpec

#
Grouping

pub enum Grouping {
Comma
Underscore
Default
}

impl Show for Grouping

#
Options

pub struct Options {
fill : Char?
align : Align
sharp : Bool
zero : Bool
}

impl Show for Options

#
SpecType

pub enum SpecType {
Binary
Digit
ExponentLower
ExponentUpper
Float
Octal
HexLower
HexUpper
Percent
Default
}

impl Show for SpecType

#
fprintln

fn fprintln(parts : String, values : Array[Formatter]) -> Unit

Formats a string with placeholders using the provided formatter values and prints it to standard output followed by a newline.

This function combines string formatting and output in a single operation. It parses the format string, applies the formatter values to fill placeholders, and outputs the result.

Parameters:

  • parts : The format string containing placeholders and literal text to be formatted.
  • values : An array of formatter objects that implement the Formatter trait, used to fill the placeholders in the format string.

Example:

let name = "Alice"
let age = 30
@fmt.fprintln("Hello, {0}! You are {1} years old.", [name, age])
// Outputs: Hello, Alice! You are 30 years old.

#
fstring

fn fstring(parts : String, values : Array[Formatter]) -> String

Formats a string with placeholders using the provided formatter values.

Parses the format string to identify placeholders and literal text, then applies the formatter values to fill the placeholders according to their specifications. This function provides a flexible way to create formatted strings with type-safe value insertion.

Parameters:

  • parts : The format string containing placeholders (e.g., {0}, {1:x}) and literal text to be formatted.
  • values : An array of formatter objects that implement the Formatter trait, used to fill the placeholders in the format string.

Returns the formatted string with all placeholders replaced by their corresponding formatted values.

Example:

let name = "Alice"
let age = 30
let formatted = @fmt.fstring("Hello, {0}! You are {1} years old.", [name, age])
inspect(formatted, content="Hello, Alice! You are 30 years old.")

#
jprintln

fn jprintln(parts : String, values : Json) -> Unit

Formats a string with placeholders using the provided JSON values and prints it to standard output followed by a newline.

This function combines string formatting and output in a single operation. It parses the format string, applies the JSON values to fill placeholders according to their specifications, and outputs the result to the console.

Parameters:

  • parts : The format string containing placeholders (e.g., {0}, {1:x}) and literal text to be formatted.
  • values : A JSON array containing the values used to fill the placeholders in the format string. Each element corresponds to a placeholder position.

Panics if values is not a JSON array.

Example:

let data = @json.parse("[\"Alice\", 30]")
@fmt.jprintln("Hello, {0}! You are {1} years old.", data)
// Outputs: Hello, Alice! You are 30 years old.

#
jstring

fn jstring(parts : String, values : Json) -> String

Formats a string with placeholders using the provided JSON values.

Parses the format string to identify placeholders and literal text, then applies the JSON values to fill the placeholders according to their specifications. This function provides a flexible way to create formatted strings using JSON data as input.

Parameters:

  • parts : The format string containing placeholders (e.g., {0}, {1:x}) and literal text to be formatted.
  • values : A JSON array containing the values used to fill the placeholders in the format string. Each element corresponds to a placeholder position.

Returns the formatted string with all placeholders replaced by their corresponding formatted values from the JSON array.

Panics if values is not a JSON array.

Example:

let data = @json.parse("[\"Alice\", 30]")
let formatted = @fmt.jstring("Hello, {0}! You are {1} years old.", data)
inspect(formatted, content="Hello, Alice! You are 30 years old.")