| 765 | } |
| 766 | |
| 767 | pub fn format_int(&self, num: &BigInt) -> Result<String, FormatSpecError> { |
| 768 | self.validate_format(FormatType::Decimal)?; |
| 769 | let magnitude = num.abs(); |
| 770 | let prefix = if self.alternate_form { |
| 771 | match self.format_type { |
| 772 | Some(FormatType::Binary) => "0b", |
| 773 | Some(FormatType::Octal) => "0o", |
| 774 | Some(FormatType::Hex(Case::Lower)) => "0x", |
| 775 | Some(FormatType::Hex(Case::Upper)) => "0X", |
| 776 | _ => "", |
| 777 | } |
| 778 | } else { |
| 779 | "" |
| 780 | }; |
| 781 | let raw_magnitude_str = match self.format_type { |
| 782 | Some(FormatType::Binary) => self.format_int_radix(magnitude, 2), |
| 783 | Some(FormatType::Decimal) => self.format_int_radix(magnitude, 10), |
| 784 | Some(FormatType::Octal) => self.format_int_radix(magnitude, 8), |
| 785 | Some(FormatType::Hex(Case::Lower)) => self.format_int_radix(magnitude, 16), |
| 786 | Some(FormatType::Hex(Case::Upper)) => match self.precision { |
| 787 | Some(_) => Err(FormatSpecError::PrecisionNotAllowed), |
| 788 | None => { |
| 789 | let mut result = magnitude.to_str_radix(16); |
| 790 | result.make_ascii_uppercase(); |
| 791 | Ok(result) |
| 792 | } |
| 793 | }, |
| 794 | Some(FormatType::Number(Case::Lower)) => self.format_int_radix(magnitude, 10), |
| 795 | Some(FormatType::Number(Case::Upper)) => { |
| 796 | Err(FormatSpecError::UnknownFormatCode('N', "int")) |
| 797 | } |
| 798 | Some(FormatType::String) => Err(FormatSpecError::UnknownFormatCode('s', "int")), |
| 799 | Some(FormatType::Character) => match (self.sign, self.alternate_form) { |
| 800 | (Some(_), _) => Err(FormatSpecError::NotAllowed("Sign")), |
| 801 | (_, true) => Err(FormatSpecError::NotAllowed("Alternate form (#)")), |
| 802 | (_, _) => match num.to_u32() { |
| 803 | Some(n) if n <= 0x10ffff => Ok(core::char::from_u32(n).unwrap().to_string()), |
| 804 | Some(_) | None => Err(FormatSpecError::CodeNotInRange), |
| 805 | }, |
| 806 | }, |
| 807 | Some(FormatType::GeneralFormat(_)) |
| 808 | | Some(FormatType::FixedPoint(_)) |
| 809 | | Some(FormatType::Exponent(_)) |
| 810 | | Some(FormatType::Percentage) => match num.to_f64() { |
| 811 | Some(float) => return self.format_float(float), |
| 812 | _ => Err(FormatSpecError::UnableToConvert), |
| 813 | }, |
| 814 | Some(FormatType::Unknown(c)) => Err(FormatSpecError::UnknownFormatCode(c, "int")), |
| 815 | None => self.format_int_radix(magnitude, 10), |
| 816 | }?; |
| 817 | let format_sign = self.sign.unwrap_or(FormatSign::Minus); |
| 818 | let sign_str = match num.sign() { |
| 819 | Sign::Minus => "-", |
| 820 | _ => match format_sign { |
| 821 | FormatSign::Plus => "+", |
| 822 | FormatSign::Minus => "", |
| 823 | FormatSign::MinusOrSpace => " ", |
| 824 | }, |