From: Funtowicz Morgan Date: Mon, 22 May 2023 13:26:06 +0000 (+0200) Subject: Added method `len` on `SafeTensors` (#252) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=a03528d558d4df92fc0ce65693f44efd07767152;p=safetensors.git Added method `len` on `SafeTensors` (#252) * Added method `len` on `SafeTensors` in order to avoid allocating a new tensor through `names()` or `tensors()` * Make clippy happy with `is_empty() -> bool` * Apply @Narsil suggestion regarding is_empty Co-authored-by: Nicolas Patry * Fix format. --------- Co-authored-by: Nicolas Patry --- diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index ad97280..5afbdd2 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -380,6 +380,18 @@ impl<'data> SafeTensors<'data> { pub fn names(&self) -> Vec<&'_ String> { self.metadata.index_map.keys().collect() } + + /// Return how many tensors are currently stored within the SafeTensors. + #[inline] + pub fn len(&self) -> usize { + self.metadata.tensors.len() + } + + /// Indicate if the SafeTensors contains or not any tensor. + #[inline] + pub fn is_empty(&self) -> bool { + self.metadata.tensors.is_empty() + } } /// The stuct representing the header of safetensor files which allow @@ -945,6 +957,7 @@ mod tests { let loaded = SafeTensors::deserialize(serialized).unwrap(); + assert_eq!(loaded.len(), 1); assert_eq!(loaded.names(), vec!["test"]); let tensor = loaded.tensor("test").unwrap(); assert_eq!(tensor.shape(), vec![2, 2]);