Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose parse_format_string to external users to allow for attempting to typecast raw data #5

Merged
merged 6 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod format;
mod parser;

pub use format::Printf;
use parser::{parse_format_string, FormatElement};
pub use parser::{parse_format_string, FormatElement};
pub use parser::{ConversionSpecifier, ConversionType, NumericParam};

/// Error type
Expand Down
27 changes: 23 additions & 4 deletions src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::{PrintfError, Result};

#[derive(Debug, Clone)]
pub(crate) enum FormatElement {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormatElement {
Verbatim(String),
Format(ConversionSpecifier),
}

/// Parsed printf conversion specifier
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConversionSpecifier {
/// flag `#`: use `0x`, etc?
pub alt_form: bool,
Expand Down Expand Up @@ -69,7 +69,26 @@ pub enum ConversionType {
PercentSign,
}

pub(crate) fn parse_format_string(fmt: &str) -> Result<Vec<FormatElement>> {
/// Parses a string to a vector of [FormatElement]
///
/// Takes a printf-style format string `fmt`
///
/// use sprintf::{parse_format_string, FormatElement, ConversionType, ConversionSpecifier, NumericParam};
/// let fmt = "Hello %#06x";
/// let parsed = parse_format_string(fmt).unwrap();
/// assert_eq!(parsed[0], FormatElement::Verbatim("Hello ".to_owned()));
/// assert_eq!(parsed[1], FormatElement::Format(ConversionSpecifier {
/// alt_form: true,
/// zero_pad: true,
/// left_adj: false,
/// space_sign: false,
/// force_sign: false,
/// width: NumericParam::Literal(6),
/// precision: NumericParam::Literal(6),
/// conversion_type: ConversionType::HexIntLower,
/// }));
///
pub fn parse_format_string(fmt: &str) -> Result<Vec<FormatElement>> {
// find the first %
let mut res = Vec::new();
let parts: Vec<&str> = fmt.splitn(2, '%').collect();
Expand Down
Loading