Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Libc s(n)printf clone written in Rust, so you can use printf-style
2 //! formatting without a libc (e.g. in WebAssembly).
3 //!
4 //! **Note:** *You're probably better off using standard Rust string formatting
5 //! instead of thie crate unless you specificaly need printf compatibility.*
6 //!
7 //! It follows the standard C semantics, except:
8 //!
9 //! * Locale-aware UNIX extensions (`'` and GNU’s `I`) are not supported.
10 //! * `%a`/`%A` (hexadecimal floating point) are currently not implemented.
11 //! * Length modifiers (`h`, `l`, etc.) are checked, but ignored. The passed
12 //! type is used instead.
13 //!
14 //! Usage example:
15 //!
16 //! use sprintf::sprintf;
17 //! let s = sprintf!("%d + %d = %d\n", 3, 9, 3+9).unwrap();
18 //! assert_eq!(s, "3 + 9 = 12\n");
19 //!
20 //! The types of the arguments are checked at runtime.
21 //!
22
23 use thiserrorrust-analyzer cargo thiserror 2.0.12 crate/::Errorrust-analyzer cargo thiserror-impl 2.0.12 Error:;
24
25 mod formatrust-analyzer cargo sprintf 0.4.2 format/;
26 pub mod parserrust-analyzer cargo sprintf 0.4.2 parser/;
27
28 pub use formatrust-analyzer cargo sprintf 0.4.2 format/::Printfrust-analyzer cargo sprintf 0.4.2 format/Printf#;
29 use parserrust-analyzer cargo sprintf 0.4.2 parser/::{parse_format_stringrust-analyzer cargo sprintf 0.4.2 parser/parse_format_string()., FormatElementrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#};
30 #[doc(hidden)]
31 pub use parserrust-analyzer cargo sprintf 0.4.2 parser/::{ConversionSpecifierrust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#, ConversionTyperust-analyzer cargo sprintf 0.4.2 parser/ConversionType#, NumericParamrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#};
32
33 /// Error type
34 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/macros/Debug:, Clonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core clone/Clone:, Copyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Copy:, Errorrust-analyzer cargo thiserror-impl 2.0.12 Error:, PartialEqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/PartialEq:, Eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/Eq:)]
35 pub enum PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError# {
36 /// Error parsing the format string
37 #[errorrust-analyzer cargo thiserror-impl 2.0.12 error:("Error parsing the format string")]
38 ParseErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#ParseError#,
39 /// Incorrect type passed as an argument
40 #[errorrust-analyzer cargo thiserror-impl 2.0.12 error:("Incorrect type passed as an argument")]
41 WrongTyperust-analyzer cargo sprintf 0.4.2 PrintfError#WrongType#,
42 /// Too many arguments passed
43 #[errorrust-analyzer cargo thiserror-impl 2.0.12 error:("Too many arguments passed")]
44 TooManyArgsrust-analyzer cargo sprintf 0.4.2 PrintfError#TooManyArgs#,
45 /// Too few arguments passed
46 #[errorrust-analyzer cargo thiserror-impl 2.0.12 error:("Too few arguments passed")]
47 NotEnoughArgsrust-analyzer cargo sprintf 0.4.2 PrintfError#NotEnoughArgs#,
48 /// Other error (should never happen)
49 #[errorrust-analyzer cargo thiserror-impl 2.0.12 error:("Other error (should never happen)")]
50 Unknownrust-analyzer cargo sprintf 0.4.2 PrintfError#Unknown#,
51 }
52
53 pub type Resultrust-analyzer cargo sprintf 0.4.2 Result#<T> = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/::Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<T, PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#>;
54
55 /// Format a string. (Roughly equivalent to `vsnprintf` or `vasprintf` in C)
56 ///
57 /// Takes a printf-style format string `format` and a slice of dynamically
58 /// typed arguments, `args`.
59 ///
60 /// use sprintf::{vsprintf, Printf};
61 /// let n = 16;
62 /// let args: Vec<&dyn Printf> = vec![&n];
63 /// let s = vsprintf("%#06x", &args).unwrap();
64 /// assert_eq!(s, "0x0010");
65 ///
66 /// See also: [sprintf]
67 pub fn vsprintfrust-analyzer cargo sprintf 0.4.2 vsprintf().(format: &str, args: &[&dyn Printfrust-analyzer cargo sprintf 0.4.2 format/Printf#]) -> Resultrust-analyzer cargo sprintf 0.4.2 Result#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#> {
68 vsprintfprust-analyzer cargo sprintf 0.4.2 vsprintfp().(&parse_format_stringrust-analyzer cargo sprintf 0.4.2 parser/parse_format_string().(format)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()., args)
69 }
70
71 /// Format a string using [`parser::FormatElement`]s
72 ///
73 /// Like [vsprintf], except that it doesn't parse the format string.
74 pub fn vsprintfprust-analyzer cargo sprintf 0.4.2 vsprintfp().(format: &[FormatElementrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#], args: &[&dyn Printfrust-analyzer cargo sprintf 0.4.2 format/Printf#]) -> Resultrust-analyzer cargo sprintf 0.4.2 Result#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#> {
75 let mut res = Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]new().();
76
77 let mut args = args;
78 let mut pop_arg = || {
79 if args.is_emptyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/impl#[`[T]`]is_empty().() {
80 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#::NotEnoughArgsrust-analyzer cargo sprintf 0.4.2 PrintfError#NotEnoughArgs#)
81 } else {
82 let a = args[rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/Index#index().0]rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/Index#index().;
83 args = &args[rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/Index#index().1..rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeFrom#]rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/Index#index().;
84 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(a)
85 }
86 };
87
88 for elem in format {
89 match elem {
90 FormatElementrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#::Verbatimrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#Verbatim#(s) => {
91 res.push_strrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]push_str().(s);
92 }
93 FormatElementrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#::Formatrust-analyzer cargo sprintf 0.4.2 parser/FormatElement#Format#(spec) => {
94 if spec.conversion_typerust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#conversion_type. rust-analyzer cargo sprintf 0.4.2 parser/impl#[ConversionType][`PartialEq<Self>`]eq().==rust-analyzer cargo sprintf 0.4.2 parser/impl#[ConversionType][`PartialEq<Self>`]eq(). rust-analyzer cargo sprintf 0.4.2 parser/impl#[ConversionType][`PartialEq<Self>`]eq().ConversionTyperust-analyzer cargo sprintf 0.4.2 parser/ConversionType#::PercentSignrust-analyzer cargo sprintf 0.4.2 parser/ConversionType#PercentSign# {
95 res.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]push().('%');
96 } else {
97 let mut completed_spec = *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&T`][Deref]deref().spec;
98 if spec.widthrust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#width. rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq().==rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq(). rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq().NumericParamrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#::FromArgumentrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#FromArgument# {
99 completed_spec.widthrust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#width. = NumericParamrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#::Literalrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#Literal#(
100 pop_arg()?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()..as_intrust-analyzer cargo sprintf 0.4.2 format/Printf#as_int().().ok_orrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]ok_or().(PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#::WrongTyperust-analyzer cargo sprintf 0.4.2 PrintfError#WrongType#)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().,
101 )
102 }
103 if spec.precisionrust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#precision. rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq().==rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq(). rust-analyzer cargo sprintf 0.4.2 parser/impl#[NumericParam][`PartialEq<Self>`]eq().NumericParamrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#::FromArgumentrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#FromArgument# {
104 completed_spec.precisionrust-analyzer cargo sprintf 0.4.2 parser/ConversionSpecifier#precision. = NumericParamrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#::Literalrust-analyzer cargo sprintf 0.4.2 parser/NumericParam#Literal#(
105 pop_arg()?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()..as_intrust-analyzer cargo sprintf 0.4.2 format/Printf#as_int().().ok_orrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]ok_or().(PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#::WrongTyperust-analyzer cargo sprintf 0.4.2 PrintfError#WrongType#)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().,
106 )
107 }
108 res.push_strrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[String]push_str().(&pop_arg()?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch()..formatrust-analyzer cargo sprintf 0.4.2 format/Printf#format().(&completed_spec)?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().);
109 }
110 }
111 }
112 }
113
114 if args.is_emptyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/impl#[`[T]`]is_empty().() {
115 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(res)
116 } else {
117 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(PrintfErrorrust-analyzer cargo sprintf 0.4.2 PrintfError#::TooManyArgsrust-analyzer cargo sprintf 0.4.2 PrintfError#TooManyArgs#)
118 }
119 }
120
121 /// Format a string. (Roughly equivalent to `snprintf` or `asprintf` in C)
122 ///
123 /// Takes a printf-style format string `format` and a variable number of
124 /// additional arguments.
125 ///
126 /// use sprintf::sprintf;
127 /// let s = sprintf!("%s = %*d", "forty-two", 4, 42).unwrap();
128 /// assert_eq!(s, "forty-two = 42");
129 ///
130 /// Wrapper around [vsprintf].
131 #[macro_export]
132 macro_rules! sprintfrust-analyzer cargo sprintf 0.4.2 sprintf! {
133 ($fmt:expr, $($arg:expr),*) => {
134 sprintf::vsprintf($fmt, &[$( &($arg) as &dyn sprintf::Printf),* ][..])
135 };
136 }