1use core::convert::Infallible;
16use core::iter::Peekable;
17use core::marker::PhantomData;
18use std::borrow::Cow;
19use std::collections::HashSet;
20
21#[cfg(feature = "proc_macro")]
22use quote::{quote, ToTokens};
23
24mod float;
25mod integer;
26mod padding;
27mod platform;
28mod text;
29
30use self::float::format_float;
31use self::integer::{format_int, format_ptr, format_uint};
32pub use self::platform::{
33 Ilp32Platform, Llp64Platform, Lp64Platform, PlatformTypes, PointerInt, SignedInt, UnsignedInt,
34};
35use self::text::{format_char, format_str};
36use crate::{core_fmt, printf};
37
38pub const MAX_FIELD_LEN: u32 = 0x0001_0000;
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum Primitive {
49 Integer,
51
52 Unsigned,
54
55 Float,
57
58 String,
60
61 Character,
63
64 Pointer,
66
67 Dynamic,
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73pub enum Style {
74 None,
76
77 Octal,
79
80 Hex,
82
83 UpperHex,
85
86 Exponential,
88
89 UpperExponential,
91
92 General,
94
95 UpperGeneral,
97
98 HexFloat,
100
101 UpperHexFloat,
103
104 Upper,
106
107 Pointer,
109
110 Debug,
112
113 HexDebug,
115
116 UpperHexDebug,
118
119 Binary,
124}
125
126#[cfg(feature = "proc_macro")]
128impl ToTokens for Style {
129 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
130 let new_tokens = match self {
131 Style::None => quote!(pw_format::Style::None),
132 Style::Octal => quote!(pw_format::Style::Octal),
133 Style::Hex => quote!(pw_format::Style::Hex),
134 Style::UpperHex => quote!(pw_format::Style::UpperHex),
135 Style::Exponential => quote!(pw_format::Style::Exponential),
136 Style::UpperExponential => quote!(pw_format::Style::UpperExponential),
137 Style::General => quote!(pw_format::Style::General),
138 Style::UpperGeneral => quote!(pw_format::Style::UpperGeneral),
139 Style::HexFloat => quote!(pw_format::Style::HexFloat),
140 Style::UpperHexFloat => quote!(pw_format::Style::UpperHexFloat),
141 Style::Upper => quote!(pw_format::Style::Upper),
142 Style::Debug => quote!(pw_format::Style::Debug),
143 Style::HexDebug => quote!(pw_format::Style::HexDebug),
144 Style::UpperHexDebug => quote!(pw_format::Style::UpperHexDebug),
145 Style::Pointer => quote!(pw_format::Style::Pointer),
146 Style::Binary => quote!(pw_format::Style::Binary),
147 };
148 new_tokens.to_tokens(tokens);
149 }
150}
151
152#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
154pub enum Flag {
155 LeftJustify,
157
158 ForceSign,
160
161 SpaceSign,
163
164 AlternateSyntax,
166
167 LeadingZeros,
169}
170
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum MinFieldWidth {
174 None,
176
177 Fixed(u32),
179
180 Variable,
182}
183
184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub enum Precision {
190 None,
192
193 Fixed(u32),
195
196 Variable,
198}
199
200impl Precision {
201 #[must_use]
203 pub const fn to_fixed(self) -> Option<u32> {
204 match self {
205 Self::Fixed(p) => Some(p),
206 _ => None,
207 }
208 }
209}
210
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub enum Length {
214 Char,
216
217 Short,
219
220 Long,
222
223 LongLong,
225
226 LongDouble,
228
229 IntMax,
231
232 Size,
234
235 PointerDiff,
237}
238
239impl Length {
240 #[must_use]
242 pub const fn as_str(&self) -> &'static str {
243 match self {
244 Self::Char => "hh",
245 Self::Short => "h",
246 Self::Long => "l",
247 Self::LongLong => "ll",
248 Self::LongDouble => "L",
249 Self::IntMax => "j",
250 Self::Size => "z",
251 Self::PointerDiff => "t",
252 }
253 }
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258pub enum Alignment {
259 None,
261
262 Left,
264
265 Center,
267
268 Right,
270}
271
272#[derive(Clone, Debug, PartialEq, Eq)]
276pub enum Argument {
277 None,
279
280 Positional(usize),
282
283 Named(String),
285}
286
287#[derive(Clone, Debug, PartialEq, Eq)]
289pub struct ConversionSpec {
290 pub argument: Argument,
292 pub fill: char,
294 pub alignment: Alignment,
296 pub flags: HashSet<Flag>,
298 pub min_field_width: MinFieldWidth,
300 pub precision: Precision,
302 pub length: Option<Length>,
304 pub primitive: Primitive,
306 pub style: Style,
308}
309
310impl Default for ConversionSpec {
311 fn default() -> Self {
312 Self {
313 argument: Argument::None,
314 fill: ' ',
315 alignment: Alignment::None,
316 flags: HashSet::new(),
317 min_field_width: MinFieldWidth::None,
318 precision: Precision::None,
319 length: None,
320 primitive: Primitive::Dynamic,
321 style: Style::None,
322 }
323 }
324}
325
326impl ConversionSpec {
327 #[must_use]
330 pub const fn has_valid_field_lengths(&self) -> bool {
331 !matches!(self.min_field_width, MinFieldWidth::Fixed(w) if w > MAX_FIELD_LEN)
332 && !matches!(self.precision, Precision::Fixed(p) if p > MAX_FIELD_LEN)
333 }
334
335 #[must_use]
337 pub fn to_printf(&self) -> String {
338 let mut s = String::from("%");
339 if self.flags.contains(&Flag::LeftJustify) {
340 s.push('-');
341 }
342 if self.flags.contains(&Flag::ForceSign) {
343 s.push('+');
344 }
345 if self.flags.contains(&Flag::SpaceSign) {
346 s.push(' ');
347 }
348 if self.flags.contains(&Flag::AlternateSyntax) {
349 s.push('#');
350 }
351 if self.flags.contains(&Flag::LeadingZeros) {
352 s.push('0');
353 }
354
355 match self.min_field_width {
356 MinFieldWidth::None => {}
357 MinFieldWidth::Fixed(w) => s.push_str(&w.to_string()),
358 MinFieldWidth::Variable => s.push('*'),
359 }
360
361 match self.precision {
362 Precision::None => {}
363 Precision::Fixed(p) => s.push_str(&format!(".{p}")),
364 Precision::Variable => s.push_str(".*"),
365 }
366
367 if let Some(length) = self.length {
368 s.push_str(length.as_str());
369 }
370
371 let type_char = match (self.primitive, self.style) {
372 (Primitive::Integer, _) => 'd',
373 (Primitive::Unsigned, Style::Octal) => 'o',
374 (Primitive::Unsigned, Style::Hex) => 'x',
375 (Primitive::Unsigned, Style::UpperHex) => 'X',
376 (Primitive::Unsigned, _) => 'u',
377 (Primitive::Float, Style::Exponential) => 'e',
378 (Primitive::Float, Style::UpperExponential) => 'E',
379 (Primitive::Float, Style::General) => 'g',
380 (Primitive::Float, Style::UpperGeneral) => 'G',
381 (Primitive::Float, Style::HexFloat) => 'a',
382 (Primitive::Float, Style::UpperHexFloat) => 'A',
383 (Primitive::Float, Style::Upper) => 'F',
384 (Primitive::Float, _) => 'f',
385 (Primitive::Character, _) => 'c',
386 (Primitive::String, _) => 's',
387 (Primitive::Pointer, _) => 'p',
388 (Primitive::Dynamic, _) => 'v',
389 };
390 s.push(type_char);
391 s
392 }
393}
394
395#[derive(Clone, Debug, Default, PartialEq, Eq)]
397pub enum SimpleNestedDomain {
398 #[default]
400 Default,
401
402 Literal(String),
404
405 LiteralToken {
407 domain: String,
409 token: u32,
411 },
412
413 VariableToken {
415 domain: String,
417 },
418}
419
420#[derive(Clone, Debug, Default, PartialEq, Eq)]
422pub enum NestedDomain {
423 #[default]
425 Default,
426
427 Literal(String),
429
430 LiteralToken {
432 domain: String,
434 token: u32,
436 },
437
438 VariableToken {
440 domain: String,
442 },
443
444 BitField {
447 low: SimpleNestedDomain,
449 low_bits: u8,
451 high: SimpleNestedDomain,
453 },
454}
455
456impl NestedDomain {
457 #[must_use]
459 pub const fn has_variable_token(&self) -> bool {
460 match self {
461 Self::VariableToken { .. } => true,
462 Self::BitField { low, high, .. } => {
463 matches!(low, SimpleNestedDomain::VariableToken { .. })
464 || matches!(high, SimpleNestedDomain::VariableToken { .. })
465 }
466 Self::Default | Self::Literal(_) | Self::LiteralToken { .. } => false,
467 }
468 }
469
470 #[must_use]
472 pub const fn has_literal_token(&self) -> bool {
473 match self {
474 Self::LiteralToken { .. } => true,
475 Self::BitField { low, high, .. } => {
476 matches!(low, SimpleNestedDomain::LiteralToken { .. })
477 || matches!(high, SimpleNestedDomain::LiteralToken { .. })
478 }
479 Self::Default | Self::Literal(_) | Self::VariableToken { .. } => false,
480 }
481 }
482}
483
484impl From<SimpleNestedDomain> for NestedDomain {
485 fn from(domain: SimpleNestedDomain) -> Self {
486 match domain {
487 SimpleNestedDomain::Default => Self::Default,
488 SimpleNestedDomain::Literal(name) => Self::Literal(name),
489 SimpleNestedDomain::LiteralToken { domain, token } => {
490 Self::LiteralToken { domain, token }
491 }
492 SimpleNestedDomain::VariableToken { domain } => Self::VariableToken { domain },
493 }
494 }
495}
496
497#[derive(Clone, Copy, Debug, PartialEq, Eq)]
499pub enum NestedTokenValue {
500 Literal(u32),
502
503 Variable,
505}
506
507#[derive(Clone, Debug, PartialEq, Eq)]
509pub struct NestedTokenSpec {
510 pub prefix: char,
512
513 pub domain: NestedDomain,
515
516 pub token: NestedTokenValue,
518
519 pub token_data: Option<Vec<u8>>,
521
522 pub raw: String,
535}
536
537impl Default for NestedTokenSpec {
538 fn default() -> Self {
539 Self {
540 prefix: FormatString::DEFAULT_NESTED_PREFIX,
541 domain: NestedDomain::Default,
542 token: NestedTokenValue::Variable,
543 token_data: None,
544 raw: String::new(),
545 }
546 }
547}
548
549impl NestedTokenSpec {
550 #[must_use]
552 pub fn token_data(&self) -> Option<&[u8]> {
553 self.token_data.as_deref()
554 }
555
556 #[must_use]
558 pub fn raw(&self) -> &str {
559 &self.raw
560 }
561
562 #[must_use]
564 pub fn to_printf(&self) -> String {
565 self.raw.clone()
566 }
567}
568
569#[derive(Clone, Debug, PartialEq, Eq)]
571pub enum FormatFragment {
572 Literal(String),
574
575 Conversion(ConversionSpec),
577
578 NestedToken(NestedTokenSpec),
580}
581
582impl FormatFragment {
583 fn try_append<'a>(&mut self, fragment: &'a FormatFragment) -> Option<&'a FormatFragment> {
587 let Self::Literal(literal_fragment) = &fragment else {
588 return Some(fragment);
589 };
590
591 let Self::Literal(literal_self) = self else {
592 return Some(fragment);
593 };
594
595 literal_self.push_str(literal_fragment);
596
597 None
598 }
599}
600
601#[derive(Debug, Clone, PartialEq)]
603pub enum Arg {
604 Int(i64),
606 Uint(u64),
608 Float(f64),
610 Str(String),
612 Char(char),
614 Ptr(usize),
616}
617
618#[derive(Debug, Clone, Copy, PartialEq, Eq)]
620pub enum FormatStyle {
621 Printf,
623 CoreFmt,
625}
626
627pub trait FormatError {
629 type Error;
631
632 fn format_error(&self, spec: &ConversionSpec, error: &Self::Error) -> String;
634
635 fn format_missing(&self, spec: &ConversionSpec) -> String;
637
638 fn format_type_error(&self, spec: &ConversionSpec, arg: &Arg) -> String;
640
641 fn format_nested_token_error(&self, spec: &NestedTokenSpec, _error: &Self::Error) -> String {
643 spec.to_printf()
644 }
645
646 fn format_nested_token_missing(&self, spec: &NestedTokenSpec) -> String {
648 spec.to_printf()
649 }
650
651 fn format_nested_token_type_error(&self, spec: &NestedTokenSpec, _arg: &Arg) -> String {
653 spec.to_printf()
654 }
655}
656
657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660struct DefaultFormatter;
661
662impl FormatError for DefaultFormatter {
663 type Error = core::convert::Infallible;
664
665 fn format_error(&self, spec: &ConversionSpec, _error: &core::convert::Infallible) -> String {
666 spec.to_printf()
667 }
668 fn format_missing(&self, spec: &ConversionSpec) -> String {
669 spec.to_printf()
670 }
671 fn format_type_error(&self, spec: &ConversionSpec, _arg: &Arg) -> String {
672 spec.to_printf()
673 }
674}
675
676#[derive(Clone, Debug, PartialEq, Eq)]
678pub struct FormatString {
679 pub fragments: Vec<FormatFragment>,
681}
682
683impl FormatString {
684 #[must_use]
687 pub fn format_for_platform<P: PlatformTypes>(
688 &self,
689 args: &[Arg],
690 style: FormatStyle,
691 ) -> String {
692 let result_args: Vec<Result<Arg, Infallible>> =
693 args.iter().map(|arg| Ok(arg.clone())).collect();
694 self.format_with_errors_for_platform::<P, _>(&result_args, style, &DefaultFormatter)
695 }
696
697 #[must_use]
699 pub fn format(&self, args: &[Arg], style: FormatStyle) -> String {
700 self.format_for_platform::<Ilp32Platform>(args, style)
701 }
702
703 pub fn format_with_errors<FE: FormatError>(
707 &self,
708 args: &[Result<Arg, FE::Error>],
709 style: FormatStyle,
710 error_formatter: &FE,
711 ) -> String {
712 self.format_with_errors_for_platform::<Ilp32Platform, FE>(args, style, error_formatter)
713 }
714
715 pub fn format_with_errors_for_platform<P: PlatformTypes, FE: FormatError>(
718 &self,
719 args: &[Result<Arg, FE::Error>],
720 style: FormatStyle,
721 error_formatter: &FE,
722 ) -> String {
723 let mut output = String::new();
724 let mut session =
725 FormatSession::<_, _, P>::new(args.iter(), style, error_formatter, &mut output);
726
727 for fragment in &self.fragments {
728 session.format_fragment(fragment);
729 }
730
731 output
732 }
733
734 pub const DEFAULT_NESTED_PREFIX: char = '$';
736
737 pub fn parse_printf(s: &str) -> Result<Self, String> {
739 Self::parse_printf_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
740 }
741
742 pub fn parse_printf_with_prefix(s: &str, prefix: char) -> Result<Self, String> {
744 Self::parse_printf_opt_prefix(s, Some(prefix))
745 }
746
747 pub fn parse_pure_printf(s: &str) -> Result<Self, String> {
749 Self::parse_printf_opt_prefix(s, None)
750 }
751
752 fn parse_printf_opt_prefix(s: &str, prefix: Option<char>) -> Result<Self, String> {
753 let (rest, result) = printf::format_string(s, prefix)
755 .map_err(|e| format!("Failed to parse format string \"{s}\": {e}"))?;
756
757 if !rest.is_empty() {
759 return Err(format!(
760 "Failed to parse format string fragment \"{rest}\" in \"{s}\""
761 ));
762 }
763
764 Ok(result)
765 }
766
767 #[must_use]
772 pub fn parse_printf_lossy(s: &str) -> Self {
773 Self::parse_printf_lossy_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
774 }
775
776 #[must_use]
781 pub fn parse_printf_lossy_with_prefix(s: &str, prefix: char) -> Self {
782 printf::format_string_lossy(s, Some(prefix))
783 }
784
785 #[must_use]
788 pub fn parse_nested_tokens(s: &str) -> Self {
789 Self::parse_nested_tokens_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
790 }
791
792 #[must_use]
795 pub fn parse_nested_tokens_with_prefix(s: &str, prefix: char) -> Self {
796 let (_, result) = printf::nested_tokens_string(s, prefix)
797 .expect("nested_tokens_string is infallible on all UTF-8 inputs");
798 result
799 }
800
801 pub fn parse_core_fmt(s: &str) -> Result<Self, String> {
803 let (rest, result) = core_fmt::format_string(s)
805 .map_err(|e| format!("Failed to parse format string \"{s}\": {e}"))?;
806
807 if !rest.is_empty() {
809 return Err(format!(
810 "Failed to parse format string fragment \"{rest}\" in \"{s}\""
811 ));
812 }
813
814 Ok(result)
815 }
816
817 pub(crate) fn from_fragments(fragments: &[FormatFragment]) -> Self {
824 Self {
825 fragments: fragments
826 .iter()
827 .fold(Vec::<_>::new(), |mut fragments, fragment| {
828 let Some(last) = fragments.last_mut() else {
830 fragments.push((*fragment).clone());
832 return fragments;
833 };
834 if let Some(fragment) = last.try_append(fragment) {
835 fragments.push((*fragment).clone());
837 };
838 fragments
839 }),
840 }
841 }
842}
843
844struct FormatSession<'a, 'b, I, FE, P: PlatformTypes>
854where
855 I: Iterator<Item = &'a Result<Arg, FE::Error>>,
856 FE: FormatError,
857 FE::Error: 'a,
858{
859 args: Peekable<I>,
861 style: FormatStyle,
863 error_formatter: &'b FE,
866 output: &'b mut String,
868 _platform: PhantomData<P>,
870}
871
872impl<'a, 'b, I, FE, P: PlatformTypes> FormatSession<'a, 'b, I, FE, P>
873where
874 I: Iterator<Item = &'a Result<Arg, FE::Error>>,
875 FE: FormatError,
876 FE::Error: 'a,
877{
878 fn new(args: I, style: FormatStyle, error_formatter: &'b FE, output: &'b mut String) -> Self {
879 Self {
880 args: args.peekable(),
881 style,
882 error_formatter,
883 output,
884 _platform: PhantomData,
885 }
886 }
887
888 fn push_missing(&mut self, spec: &ConversionSpec) {
889 self.output
890 .push_str(&self.error_formatter.format_missing(spec));
891 }
892
893 fn push_error(&mut self, spec: &ConversionSpec, err: &FE::Error) {
894 self.output
895 .push_str(&self.error_formatter.format_error(spec, err));
896 }
897
898 fn push_type_error(&mut self, spec: &ConversionSpec, arg: &Arg) {
899 self.output
900 .push_str(&self.error_formatter.format_type_error(spec, arg));
901 }
902
903 fn drain_remaining_ok_args(&mut self, count: usize) {
906 for _ in 0..count {
907 if matches!(self.args.peek(), Some(Ok(_))) {
908 self.args.next();
909 } else {
910 break;
911 }
912 }
913 }
914
915 fn fail_dynamic_arg(&mut self, spec: &ConversionSpec, arg: &Arg, remaining_ok_slots: usize) {
916 self.push_type_error(spec, arg);
917 self.drain_remaining_ok_args(remaining_ok_slots);
918 }
919
920 fn next_arg(&mut self, spec: &ConversionSpec, remaining_ok_slots: usize) -> Option<&'a Arg> {
921 let Some(decoded) = self.args.next() else {
922 self.push_missing(spec);
923 return None;
924 };
925 match decoded {
926 Ok(arg) => Some(arg),
927 Err(err) => {
928 self.push_error(spec, err);
929 self.drain_remaining_ok_args(remaining_ok_slots);
930 None
931 }
932 }
933 }
934
935 fn format_fragment(&mut self, fragment: &FormatFragment) {
936 match fragment {
937 FormatFragment::Literal(s) => self.output.push_str(s),
938 FormatFragment::NestedToken(token_spec) => self.format_nested_token(token_spec),
939 FormatFragment::Conversion(spec) => self.format_conversion(spec),
940 }
941 }
942
943 fn format_nested_token(&mut self, token_spec: &NestedTokenSpec) {
944 let Some(decoded) = self.args.next() else {
945 self.output
946 .push_str(&self.error_formatter.format_nested_token_missing(token_spec));
947 return;
948 };
949
950 let arg = match decoded {
951 Ok(arg) => arg,
952 Err(err) => {
953 self.output.push_str(
954 &self
955 .error_formatter
956 .format_nested_token_error(token_spec, err),
957 );
958 return;
959 }
960 };
961
962 if let Arg::Str(s) = arg {
963 self.output.push_str(s);
964 } else {
965 self.output.push_str(
966 &self
967 .error_formatter
968 .format_nested_token_type_error(token_spec, arg),
969 );
970 }
971 }
972
973 fn format_conversion(&mut self, spec: &ConversionSpec) {
974 let Some(effective_spec) = self.resolve_dynamic_spec(spec) else {
975 return;
976 };
977
978 let Some(arg) = self.next_arg(spec, 0) else {
979 return;
980 };
981
982 let initial_len = self.output.len();
983 if format_value::<P>(&effective_spec, arg, self.style, self.output).is_err() {
984 self.output.truncate(initial_len);
985 self.push_type_error(spec, arg);
986 }
987 }
988
989 fn resolve_dynamic_spec<'s>(
990 &mut self,
991 spec: &'s ConversionSpec,
992 ) -> Option<Cow<'s, ConversionSpec>> {
993 if spec.min_field_width != MinFieldWidth::Variable && spec.precision != Precision::Variable
994 {
995 return Some(Cow::Borrowed(spec));
996 }
997
998 let mut resolved = spec.clone();
999 resolved.min_field_width = self.resolve_dynamic_width(spec, &mut resolved.flags)?;
1000 if resolved.flags.contains(&Flag::LeftJustify) {
1001 resolved.alignment = Alignment::Left;
1002 }
1003 resolved.precision = self.resolve_dynamic_precision(spec)?;
1004 Some(Cow::Owned(resolved))
1005 }
1006
1007 fn resolve_dynamic_width(
1008 &mut self,
1009 spec: &ConversionSpec,
1010 flags: &mut HashSet<Flag>,
1011 ) -> Option<MinFieldWidth> {
1012 let MinFieldWidth::Variable = spec.min_field_width else {
1013 return Some(spec.min_field_width);
1014 };
1015 let remaining_slots = usize::from(spec.precision == Precision::Variable) + 1;
1016 let arg = self.next_arg(spec, remaining_slots)?;
1017 let (width, is_negative) = match arg {
1018 Arg::Int(val) => (validate_field_len(val.unsigned_abs()), *val < 0),
1019 Arg::Uint(val) => (validate_field_len(*val), false),
1020 _ => (None, false),
1021 };
1022 let Some(w) = width else {
1023 self.fail_dynamic_arg(spec, arg, remaining_slots);
1024 return None;
1025 };
1026 if is_negative {
1027 flags.insert(Flag::LeftJustify);
1028 }
1029 Some(MinFieldWidth::Fixed(w))
1030 }
1031
1032 fn resolve_dynamic_precision(&mut self, spec: &ConversionSpec) -> Option<Precision> {
1033 let Precision::Variable = spec.precision else {
1034 return Some(spec.precision);
1035 };
1036 let arg = self.next_arg(spec, 1)?;
1037 let resolved = match arg {
1038 Arg::Int(val) if *val < 0 => i32::try_from(*val).ok().map(|_| Precision::None),
1041 Arg::Int(val) => validate_field_len(val.cast_unsigned()).map(Precision::Fixed),
1042 Arg::Uint(val) => validate_field_len(*val).map(Precision::Fixed),
1043 _ => None,
1044 };
1045 let Some(precision) = resolved else {
1046 self.fail_dynamic_arg(spec, arg, 1);
1047 return None;
1048 };
1049 Some(precision)
1050 }
1051}
1052
1053fn validate_field_len(val: u64) -> Option<u32> {
1054 u32::try_from(val).ok().filter(|&v| v <= MAX_FIELD_LEN)
1055}
1056
1057#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1059pub enum FormatValueError {
1060 MismatchedType,
1062
1063 ValueOutOfRange,
1066}
1067
1068fn format_value<P: PlatformTypes>(
1069 spec: &ConversionSpec,
1070 arg: &Arg,
1071 style: FormatStyle,
1072 output: &mut String,
1073) -> Result<(), FormatValueError> {
1074 if !spec.has_valid_field_lengths() {
1075 return Err(FormatValueError::ValueOutOfRange);
1076 }
1077
1078 match (spec.primitive, arg) {
1079 (Primitive::Integer, Arg::Int(v)) => format_int::<P>(*v, spec, style, output),
1080 (Primitive::Integer, Arg::Uint(v)) => format_int::<P>(v.cast_signed(), spec, style, output),
1081 (Primitive::Unsigned, Arg::Uint(v)) => format_uint::<P>(*v, spec, style, output),
1082 (Primitive::Unsigned, Arg::Int(v)) => {
1083 format_uint::<P>(v.cast_unsigned(), spec, style, output)
1084 }
1085 (Primitive::Float, Arg::Float(v)) => format_float(*v, spec, style, output),
1086 (Primitive::String, Arg::Str(v)) => format_str(v, spec, output),
1087 (Primitive::Character, Arg::Char(v)) => format_char(*v, spec, output),
1088
1089 (Primitive::Character, Arg::Int(v)) => {
1093 let c = u8::try_from(*v).map_err(|_| FormatValueError::ValueOutOfRange)? as char;
1094 format_char(c, spec, output);
1095 }
1096 (Primitive::Character, Arg::Uint(v)) => {
1097 let c = u8::try_from(*v).map_err(|_| FormatValueError::ValueOutOfRange)? as char;
1098 format_char(c, spec, output);
1099 }
1100 (Primitive::Pointer, Arg::Ptr(v)) => {
1101 format_ptr(P::Pointer::ptr_from_usize(*v)?, spec, output)
1102 }
1103 (Primitive::Pointer, Arg::Uint(v)) => {
1104 format_ptr(P::Pointer::ptr_from_u64(*v), spec, output)
1105 }
1106 (Primitive::Pointer, Arg::Int(v)) => {
1107 format_ptr(P::Pointer::ptr_from_u64(v.cast_unsigned()), spec, output)
1108 }
1109 (Primitive::Dynamic, _) => format_dynamic::<P>(spec, arg, style, output)?,
1110 _ => return Err(FormatValueError::MismatchedType),
1111 }
1112 Ok(())
1113}
1114
1115fn format_dynamic<P: PlatformTypes>(
1116 spec: &ConversionSpec,
1117 arg: &Arg,
1118 style: FormatStyle,
1119 output: &mut String,
1120) -> Result<(), FormatValueError> {
1121 match arg {
1122 Arg::Int(v) => format_int::<P>(*v, spec, style, output),
1123 Arg::Uint(v) => format_uint::<P>(*v, spec, style, output),
1124 Arg::Float(v) => format_float(*v, spec, style, output),
1125 Arg::Str(v) => format_str(v, spec, output),
1126 Arg::Char(v) => format_char(*v, spec, output),
1127 Arg::Ptr(v) => format_ptr(P::Pointer::ptr_from_usize(*v)?, spec, output),
1128 }
1129 Ok(())
1130}