* [PATCH proxmox] schema: api_string_type: add from_str method to validate before allocating
@ 2026-03-20 13:19 Gabriel Goller
0 siblings, 0 replies; only message in thread
From: Gabriel Goller @ 2026-03-20 13:19 UTC (permalink / raw)
To: pve-devel; +Cc: Wolfgang Bumiller
The existing from_string takes ownership of a String, meaning callers
with a &str had to heap-allocate first and discard the allocation on
validation failure. The new from_str validates the &str against the
schema's check_constraints before calling to_string(), so no allocation
happens on the error path.
Suggested-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Gabriel Goller <g.goller@proxmox.com>
---
Motivation:
This is used quite a lot in proxmox-ve-rs, where we often do e.g.
NetAfi::from_str(afi.to_string()), where from_str is the implementation provided
by the api_string_type macro.
proxmox-schema/src/api_type_macros.rs | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
diff --git a/proxmox-schema/src/api_type_macros.rs b/proxmox-schema/src/api_type_macros.rs
index f3740d14fd35..dd83f684baba 100644
--- a/proxmox-schema/src/api_type_macros.rs
+++ b/proxmox-schema/src/api_type_macros.rs
@@ -27,6 +27,8 @@
/// * `fn as_str(&self) -> &str`
/// * `fn from_string(inner: String) -> Result<Self, anyhow::Error>` using
/// `StringSchema::check_constraints`.
+/// * `fn from_str(inner: &str) -> Result<Self, anyhow::Error>` using
+/// `StringSchema::check_constraints`.
/// * `unsafe fn from_string_unchecked(inner: String) -> Self`
#[macro_export]
macro_rules! api_string_type {
@@ -101,6 +103,21 @@ macro_rules! api_string_type {
}
Ok(Self(inner))
}
+
+ /// Create an instance from a `&str`, validating it using the API schema's
+ /// [`check_constraints`](::proxmox_schema::StringSchema::check_constraints())
+ /// method.
+ ///
+ /// Validates the string *before* allocating, so no heap allocation occurs on
+ /// failure. Only allocates when the value is guaranteed to be valid.
+ pub fn from_str(inner: &str) -> Result<Self, ::anyhow::Error> {
+ use $crate::ApiType;
+ match &Self::API_SCHEMA {
+ $crate::Schema::String(s) => s.check_constraints(inner)?,
+ _ => unreachable!(),
+ }
+ Ok(Self(inner.to_string()))
+ }
}
impl ::std::fmt::Display for $name {
--
2.47.3
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2026-03-20 13:19 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-03-20 13:19 [PATCH proxmox] schema: api_string_type: add from_str method to validate before allocating Gabriel Goller
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.