]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Added method `len` on `SafeTensors` (#252)
authorFuntowicz Morgan <mfuntowicz@users.noreply.github.com>
Mon, 22 May 2023 13:26:06 +0000 (15:26 +0200)
committerGitHub <noreply@github.com>
Mon, 22 May 2023 13:26:06 +0000 (15:26 +0200)
* 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 <patry.nicolas@protonmail.com>
* Fix format.

---------

Co-authored-by: Nicolas Patry <patry.nicolas@protonmail.com>
safetensors/src/tensor.rs

index ad97280c944a9812e52625f8535c443dbb5ad2c6..5afbdd265087680e6eb29ee3d74585f26438e1d3 100644 (file)
@@ -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]);