Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
47 changes: 37 additions & 10 deletions core/functions/printf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,50 @@ pub fn exec_printf(values: &[Register]) -> crate::Result<Value> {
continue;
}

match chars.next() {
Some('%') => {
result.push('%');
continue;
// Check for %% escape
if let Some(&'%') = chars.peek() {
chars.next(); // consume the second %
result.push('%');
continue;
}

// Parse width (if present)
let mut width = None;
let mut width_str = String::new();
while let Some(&c) = chars.peek() {
if c.is_ascii_digit() {
width_str.push(c);
chars.next();
} else {
break;
}
}
if !width_str.is_empty() {
width = width_str.parse().ok();
}

// Get format type and handle
match chars.next() {
Some('d') | Some('i') => {
if args_index >= values.len() {
return Err(LimboError::InvalidArgument("not enough arguments".into()));
}
let value = &values[args_index].get_value();
match value {
Value::Integer(i) => result.push_str(&i.to_string()),
Value::Float(f) => {
let truncated_val = *f as i64;
result.push_str(&truncated_val.to_string());
let int_str = match value {
Value::Integer(i) => i.to_string(),
Value::Float(f) => (*f as i64).to_string(),
_ => "0".to_string(),
};

// Apply width formatting if specified
if let Some(w) = width {
if w > int_str.len() {
result.push_str(&format!("{int_str:>w$}"));
} else {
result.push_str(&int_str);
}
_ => result.push('0'),
} else {
result.push_str(&int_str);
}
args_index += 1;
}
Expand Down
14 changes: 14 additions & 0 deletions testing/scalar-functions-printf.test
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,17 @@ do_execsql_test printf-mixed-exponential-integer {
do_execsql_test printf-mixed-octal-hex {
SELECT printf('Octal %o is hex %x', 255, 255);
} {{Octal 377 is hex ff}}

# width formatting for integers

do_execsql_test printf-width-integer-basic {
SELECT printf('Number: %5d', 42);
} {{Number: 42}}

do_execsql_test printf-width-integer-exact {
SELECT printf('Number: %3d', 123);
} {{Number: 123}}

do_execsql_test printf-width-integer-smaller {
SELECT printf('Number: %2d', 12345);
} {{Number: 12345}}
Loading