• Stars
    star
    143
  • Rank 250,992 (Top 6 %)
  • Language
    Rust
  • License
    MIT License
  • Created about 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

rust library for formatting dynamic strings

strfmt: rust library for formatting dynamic strings

This library is for rust developers who want to bring rust-like formatting to non-static strings.

Basic use of formatting Display types

extern crate strfmt;
use strfmt::strfmt;
use std::collections::HashMap;

#[test]
fn it_works() {
    let mut vars = HashMap::new();
    vars.insert("name".to_string(), "bob");
    vars.insert("job".to_string(), "python developer");

    let fmt = "hi, my name is {name} and I am a {job}!".to_string();
    assert_eq!(
      strfmt(&fmt, &vars).unwrap(),
      "hi, my name is bob and I am a python developer!")
}

In addition to the strfmt function, this library has the Format trait which adds the format method to str and String types.

assert_eq!("hi, my name is {name}".format(&vars), "hi, my name is bob")

You can use this library any time you have dynamic strings you want to format, such as if you are providing your users a ui or are reading configuration files.

strfmt does not support empty identifiers (i.e. {} or {:<10}. Integer identifiers will be read as str keys to the hashmap (i.e. {1:<10} will have key == "1")

Legacy

In the 0.2.0 update, the signature of strfmt and Format::format changed to fix a bug with numeric formatting. For easy migration the strfmt_display and Format::format_display function provide the old behaviour.

BETA: Formatting numeric types

This feature is in Beta and may change. I expect it to be fairly stable at this point but would appreciate feedback on development.

In addition, "signed 0 padding" (i.e. +000042) is not yet supported for numeric types

Using strfmt_map it is also possible to format integers and floats:

let mut vars: HashMap<String, f64> = HashMap::new();
vars.insert("x".to_string(), 42.4242);
vars.insert("y".to_string(), -100.11111);
vars.insert("z".to_string(), 0.);

let f = |mut fmt: Formatter| {
    fmt.f64(*vars.get(fmt.key).unwrap())
};
assert_eq!(strfmt_map("{x:<7.2}", f).unwrap(), "42.42  ");
assert_eq!(strfmt_map("{y:+.2E}", f).unwrap(), "-1.00E2");
assert_eq!(strfmt_map("{z:+.2E}", f).unwrap(), "+0.00E0");

Status and Goals

strfmt aims to support all of the formatting options defined in std::fmt. Currently it officially only supports the format options for strings (beta support for i64 and f64)

See the syntax for how to create a formatted string

Current Status (in order of priority)

  • get strfmt_map out of Beta and create Format.format_map method
  • handle sign aware zero padding for numeric types
  • format any Display type
  • stabilize strfmt_map and add format_map to the Format trait.
  • add f64 method to Formatter allowing those using strfmt_map to format f64s according to the spec
  • add i64 method to Formatter allowing those using strfmt_map to format i64s according to the spec
  • use DisplayStr trait for formatting, permitting proper formatting of integer types.
  • look for a rust library has "unbounded float" (like python) and add that to the formatter
  • look for a rust library has "unbounded integer" (like python) and add that to the formatter
  • Implement vec method to Formatter allowing those usin strfmt_map to format types of Vec<Display> in a way that uses precision and width (precision will limit the number of elements displayed, width the width of each element)
  • special suppport to format HashMap<String, String> for improved speed
  • special suppport to format HashMap<String, &str> for improved speed
  • special suppport to format HashMap<&str, &str> for improved speed

HELP

I (@vitiral) am no longer an active maintainer of this library or any rust code, but I accept pull requests that fix bugs or implement the above features. All pull requests must be tested appropriately.

Adding functionality should be fairly easy, the main piece of work is checking and handling the flags correctly and creating comprehensive tests. Hopefully I will be creating the f64 method soon to show how it can be done, but I could really use all the help I can get on making this libray complete.

More Repositories

1

artifact

The open source design documentation tool for everybody
Rust
559
star
2

gpio

python gpio module for linux using the sysfs file access (/sys/class/gpio). Mimics similar Raspberry Pi IO libraries
Python
69
star
3

novault

ultra simple and secure vaultless password manager (beta)
Nix
56
star
4

path_abs

ergonomic paths and files in rust
Rust
49
star
5

defrag-rs

safe and efficient memory manager for microcontrollers
Rust
34
star
6

litevault

litevault provides an ultra lightweight command line password manager written in a single python file
Python
28
star
7

usertools

Arduino Library to offer debugging, errorhandling, simple threading and user interface, logging and many other tools
C++
26
star
8

stfu8

Sorta Text Format in UTF-8
Rust
25
star
9

stdcli

(pre-alpha) rust meta library for cli applications
Rust
18
star
10

termstyle

create and test the style and formatting of text in your terminal applications
Rust
18
star
11

yew_simple

Router for yew
Rust
13
star
12

Airbeam

C++
12
star
13

jrpc

ultra simple crate for types from the jsonrpc specification, for rust
Rust
10
star
14

dotfiles

vitiral's dotfiles
Shell
10
star
15

i2cdev

access to /dev/i2c* for linux devices
Python
8
star
16

taken

macros for taking ownership
Rust
7
star
17

tinymem

(ALPHA) tiny memory manager including ability to defragment memory pool. For use in uC and Linux
C
7
star
18

triforth

A typeforth implementation in tutorial-style assembly and forth (WIP)
Assembly
7
star
19

artifact_py

artifact re-imagined in python
Python
6
star
20

expect_macro

The expect! macro
Rust
5
star
21

diagnose

single tested python script for fast linux diagnostics
Python
5
star
22

notes

vitiral's notes
C
5
star
23

cloudtb

General "ToolBox" for programs developed by cloudformdesign.com
Python
4
star
24

zoa

serialized structured data and it's textual representation
Python
4
star
25

fiction-civboot

Civboot related fiction
3
star
26

wheat

wheat: a macro+const first low-level language
Rust
3
star
27

trfl

filesystem for fngi kernel
3
star
28

simple-quality

A short guide to quality best practices for developers
HTML
3
star
29

py3-smbus

python3 port of smbus
C
2
star
30

build_const

library for creating importable constants from build.rs or a script
Rust
2
star
31

bridge-rpc

bridged RPC protocol for microcontrollers
Rust
2
star
32

tmq

(pre-Alpha) Token Message Queue Library, written to be easily embedded
Python
2
star
33

nixos-configuration

My configurationf files for nixos
Nix
1
star
34

dungeon_game

A dungeon game for learning C++
C
1
star
35

typeforth.vim

vim syntax for typeforth
Vim Script
1
star
36

creative-commons-music

just some creative commons music I've found that I like for vidoes
1
star
37

DHT

DHT library that is compatible with Spark and non blocking (not interrupt driven)
C++
1
star
38

oserial

Object based serial port for python
Python
1
star
39

artifact-design

static web page for the design of artifact: the design doc tool made for developers
HTML
1
star
40

rag

rust documentation search engine [Alpha]
Rust
1
star
41

SearchTheSky

Search the Sky is a powerful a code re-factoring in a single tool for multiple programming languages.
Python
1
star
42

cfd_arduino_software

A mirror of my arduino install, with extra libraries added.
C
1
star
43

artifact-example

hello world example with rendered design docs
HTML
1
star
44

GaryDB

alpha single file NoSQLish database
Rust
1
star
45

ArduinoISP

Modifies the ArduinoISP library to allow talking through a serial port.
Arduino
1
star
46

spor_alloc

Small Allocator written in C for the spor/fngi kernel
C
1
star
47

wake

⏾🌊🛠 wake software's true potential
Python
1
star
48

adxl345-python3

fork of adxl345 library
Python
1
star
49

jsh

JSON-RPC standards for the shell
Python
1
star
50

pastebin

A place for me to paste stuff
1
star
51

HabitatMap

Arduino
1
star
52

pymakec

Create makefiles using python (2 or 3)
Python
1
star
53

replace.rs

cmdline utility to find and replace text using regular expression groups
Rust
1
star
54

vitiral.github.io

blog about life and computers
SCSS
1
star
55

fencsv

convert a chess fen string into human readable csv and back
Python
1
star
56

sparklibs

General libraries for the spark core
C++
1
star
57

raspi_i2c

very simple i2c module for the raspberry pi
Python
1
star
58

dataloss

short python script that can help detect data loss
Python
1
star
59

embedded_sensors

Based off of keiichishima RPiSensors. Designed for python3
Python
1
star
60

microtb

Shell
1
star
61

spidev

spidev for python3
C
1
star
62

El14_AudioServo

Audioservo from http://www.scary-terry.com/audioservo/audioservo.htm to demonstrate Beta of Eagle v7
1
star
63

jsoncmd

json rpc specification for the command line
1
star
64

anchor_txt

assign attributes to your markdown sections
Python
1
star
65

rust-embedded-design

design documents for the embedded rust ecosystem
1
star