]> git.mikk.net Git - mtbl-rs/commitdiff
Implement dyn-compatible source variant.
authorChris Mikkelson <chris@mikk.net>
Tue, 8 Apr 2025 20:48:07 +0000 (15:48 -0500)
committerChris Mikkelson <chris@mikk.net>
Tue, 8 Apr 2025 20:48:07 +0000 (15:48 -0500)
With appropriate boxing, allows creation of dynamically-dispatched
sources for heterogeneous collections of sources.

src/merger.rs
src/source.rs

index 5d9e371b7e43d1edc01df193fd22792d1528e10f..5abf0a9dfc565e568de3bbc582ebfd1876b69d4c 100644 (file)
@@ -167,7 +167,7 @@ mod test {
         let iters: Vec<_> = range
             .clone()
             .map(test_source)
-            //.map(|s| s.into_boxed())
+            .map(|s| s.into_boxed())
             .collect();
         let s = Merger::from(iters);
         let mut v = Vec::<u8>::new();
index adefa73b33506a26f71470d4a69e2398c76d84c3..04d9dd3b06da243f88831c00b3db09049d64b9e2 100644 (file)
@@ -50,15 +50,39 @@ pub trait Source {
     {
         FilterSource::new(self, filter_func)
     }
+
+    fn into_boxed(self) -> Box<dyn DynSource<Item = Self::Item>>
+    where
+        Self: Sized + 'static,
+    {
+        // Inner Box satisfied DynSource, outer Box required for an owned DynSource trait object.
+        Box::new(Box::new(self))
+    }
+}
+
+// A dyn-compatible variant of Source generating boxed SeekableIters. Necessary to create
+// heterogeneous collections of sources.
+pub trait DynSource {
+    type Item;
+
+    fn iter(&self) -> Box<dyn SeekableIter<Item = Self::Item> + '_>;
 }
 
-impl<S: Source + ?Sized> Source for Box<S> {
+impl<S: Source + ?Sized> DynSource for Box<S> {
     type Item = S::Item;
-    fn iter(&self) -> impl SeekableIter<Item = Self::Item> {
+
+    fn iter(&self) -> Box<dyn SeekableIter<Item = Self::Item> + '_> {
         Box::new(self.as_ref().iter())
     }
 }
 
+impl<D: DynSource + ?Sized> Source for D {
+    type Item = D::Item;
+    fn iter(&self) -> impl SeekableIter<Item = Self::Item> {
+        DynSource::iter(self)
+    }
+}
+
 pub struct VecIter<'a> {
     index: usize,
     vec: &'a Vec<Entry>,