Skip to content
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
115 changes: 115 additions & 0 deletions argv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,121 @@ pub fn invalid_os_value<'t, 'v>(name: &'t str, bytes: Vec<u8>) -> Error<'t, 'v>
)
}

/// Convert every repeated value of one text field, reporting `name` for the
/// first that is not UTF-8.
///
/// The shared body of what a generated `build` does per collecting text field:
/// one loop in the binary rather than one per field. Converts element by
/// element rather than with `collect` so the error can carry the value that
/// failed rather than only that one did.
///
/// The empty case is answered here rather than in the shared loop, and this is
/// what keeps sharing the loop free: a command at mise's scale declares dozens
/// of collecting fields and a command line names one or two of them, so most of
/// these calls have nothing to convert. Testing that at the field costs a branch;
/// reaching the loop to learn it costs the call.
#[inline]
pub fn utf8_values<'t, 'v>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<String>, Error<'t, 'v>> {
if values.is_empty() {
return Ok(Vec::new());
}
utf8_values_given(values, name)
}

#[inline(never)]
fn utf8_values_given<'t, 'v>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<String>, Error<'t, 'v>> {
let mut out = Vec::with_capacity(values.len());
for value in values {
match String::from_utf8(value) {
Ok(text) => out.push(text),
Err(bad) => return Err(invalid_utf8_value(name, bad)),
}
}
Ok(out)
}

/// Convert every repeated value of one field through
/// [`FromStr`](std::str::FromStr), reporting `name` for the first that fails.
///
/// Monomorphized once per target type rather than expanded once per field, and
/// the empty case is answered at the field for the reason [`utf8_values`] gives.
#[inline]
pub fn parsed_values<'t, 'v, T>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, Error<'t, 'v>>
where
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
if values.is_empty() {
return Ok(Vec::new());
}
parsed_values_given(values, name)
}

#[inline(never)]
fn parsed_values_given<'t, 'v, T>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, Error<'t, 'v>>
where
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
let mut out = Vec::with_capacity(values.len());
for value in values {
let text = match String::from_utf8(value) {
Ok(text) => text,
Err(bad) => return Err(invalid_utf8_value(name, bad)),
};
match text.parse() {
Ok(parsed) => out.push(parsed),
Err(reason) => return Err(invalid_parsed_value(name, text, &reason)),
}
}
Ok(out)
}

/// Convert every repeated value of one path-like field, reporting `name` for
/// the first the platform cannot hold.
///
/// `T` is what the field collects — [`PathBuf`](std::path::PathBuf) or
/// [`OsString`] — so one body serves both. The same platform note as
/// [`os_string_from_bytes`] applies: lossless on Unix, partial on Windows. The
/// empty case is answered at the field for the reason [`utf8_values`] gives.
#[inline]
pub fn os_values<'t, 'v, T: From<OsString>>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, Error<'t, 'v>> {
if values.is_empty() {
return Ok(Vec::new());
}
os_values_given(values, name)
}

#[inline(never)]
fn os_values_given<'t, 'v, T: From<OsString>>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, Error<'t, 'v>> {
let mut out = Vec::with_capacity(values.len());
for value in values {
match os_string_from_bytes(value) {
Ok(os) => out.push(T::from(os)),
Err(bytes) => return Err(invalid_os_value(name, bytes)),
}
}
Ok(out)
}

/// A single-pass parse over `argv`.
///
/// Created with [`Parser::new`] and driven with [`Parser::next_event`].
Expand Down
36 changes: 36 additions & 0 deletions argv/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2946,6 +2946,42 @@ pub trait ValueEnum: Sized {
fn from_choice(value: &str) -> Option<Self>;
}

/// Convert every repeated value of one [`ValueEnum`] field, reporting `name`
/// for the first word that is not one of the declared values.
///
/// The shared body of what a generated `build` does per collecting enum field —
/// monomorphized once per enum type rather than expanded once per field. The
/// empty case is answered at the field for the reason [`crate::utf8_values`] gives.
#[inline]
pub fn choice_values<'t, 'v, T: ValueEnum>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, crate::Error<'t, 'v>> {
if values.is_empty() {
return Ok(Vec::new());
}
choice_values_given(values, name)
}

#[inline(never)]
fn choice_values_given<'t, 'v, T: ValueEnum>(
values: Vec<Vec<u8>>,
name: &'t str,
) -> Result<Vec<T>, crate::Error<'t, 'v>> {
let mut out = Vec::with_capacity(values.len());
for value in values {
let text = match String::from_utf8(value) {
Ok(text) => text,
Err(bad) => return Err(crate::invalid_utf8_value(name, bad)),
};
match T::from_choice(&text) {
Some(parsed) => out.push(parsed),
None => return Err(crate::invalid_choice_value(name, text)),
}
}
Ok(out)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChoiceMeta<'a> {
pub value: &'a str,
Expand Down
39 changes: 15 additions & 24 deletions derive/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4763,15 +4763,11 @@ fn field_value(field: &Field, omitter: Option<&TokenStream>) -> TokenStream {
})
}
Shape::Many => {
let value = converted(quote!(__usage_value));
let collected = quote! {{
let mut __usage_values =
::std::vec::Vec::with_capacity(partial.#ident.len());
for __usage_value in partial.#ident {
__usage_values.push(#value);
}
__usage_values
}};
// One shared loop in the runtime rather than one per field — the
// collecting fields were most of what a large `build` still held.
let collected = quote! {
usage_argv::os_values(partial.#ident, #name)?
};
if field.optional_collection {
let given = format_ident!("__given_{}", ident);
let defaulted = !field.default.is_empty();
Expand Down Expand Up @@ -4864,21 +4860,16 @@ fn field_value(field: &Field, omitter: Option<&TokenStream>) -> TokenStream {
})
}
Shape::Many => {
let one = converted(quote!(__usage_value));
// Built by hand rather than with `collect`, so the error can carry the value
// that failed rather than only that one did.
// A `Vec<String>` is moved whole. Rebuilding it element by element allocated a
// second `Vec` to hold what the first already held, which is one allocation per
// collecting field — and mise's commands collect a lot.
// Built by hand rather than with `collect`, so the error can carry the value
// that failed rather than only that one did.
let collected = quote! {{
let mut __usage_values = ::std::vec::Vec::with_capacity(partial.#ident.len());
for __usage_value in partial.#ident {
__usage_values.push(#one);
}
__usage_values
}};
// One shared loop in the runtime rather than one per field — the collecting
// fields were most of what a large `build` still held. Each helper converts
// element by element so the error carries the value that failed.
let collected = if field.value_enum {
quote!(usage_argv::spec::choice_values::<#ty>(partial.#ident, #name)?)
} else if is_std_string {
quote!(usage_argv::utf8_values(partial.#ident, #name)?)
} else {
quote!(usage_argv::parsed_values::<#ty>(partial.#ident, #name)?)
};
if field.optional_collection {
let given = format_ident!("__given_{}", ident);
// A declared default is a value, so a field that has one is never `None`. It
Expand Down
Loading