3 unstable releases
new 0.1.0 | Apr 4, 2025 |
---|---|
0.0.3 |
|
0.0.2 | Mar 30, 2025 |
0.0.1 | Mar 28, 2025 |
#701 in Encoding
433 downloads per month
8KB
87 lines
formattable
Make it easy and ergonomic to provide formatted output.
Usage
Make sure you enable/disable the appropriate <#features> for the functionality you want.
Basic
use formattable::Format;
use serde::Serialize;
// Have some data structure that can be serialized.
#[derive(Serialize)]
struct Foo;
// Instantiate a Format variant. Format is Copy, so it's easy to use and pass
// around.
let fmt = Format::Json;
// Write your data structure to a JSON string.
let foo = Foo;
fmt.to_string(&foo).unwrap();
clap
Integration
use clap::Parser;
use formattable::Format;
use serde::Serialize;
/// Demonstrate how to use `formattable` in a `clap`-based CLI.
///
/// This example just dumps the CLI arguments themselves as the selected format.
#[derive(Debug, Parser, Serialize)]
struct Cli {
/// Select a format for output.
#[clap(short, long, value_enum, default_value_t = Format::Json)]
format: Format,
}
fn main() {
let cli = Cli::parse();
dbg!(&cli);
println!("{}", cli.format.to_string(&cli).unwrap());
}
Features
Unfortunately, not all the various serialization libraries used by formattable
support the same serialization capabilities. Therefore, depending on the enabled
features you may or may not have certain methods available on Format
. When in
doubt, consult the docs.
- default [toml, json, yaml]
- clap - enables the
clap
CLI integration - json - default; enables serialization to JSON
- yaml - default; enables serialization to YAML; disables
to_string_pretty
- toml - default; enables serialization to TOML; disables
to_writer
Dependencies
~0.5–1.7MB
~36K SLoC