Skip to content

Commit

Permalink
Add DriverIterator to iterate though the registered drivers (#513)
Browse files Browse the repository at this point in the history
* Add `DriverIterator` to iterate though the registered drivers

* Apply suggestions from code review

Co-authored-by: Laurențiu Nicola <[email protected]>

---------

Co-authored-by: Laurențiu Nicola <[email protected]>
  • Loading branch information
Atreyagaurav and lnicola committed Jan 5, 2024
1 parent 924bdbf commit 82db2fe
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changes

## Unreleased
- Add `DriverIterator` format to iterate through drivers, as well as `DriverManager::all()` method that provides the iterator.

- **Breaking**: `Feature::set_field_xxx` now take `&mut self`
- <https://github.com/georust/gdal/pull/505>

Expand Down
39 changes: 39 additions & 0 deletions src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,10 +451,39 @@ impl DriverManager {
gdal_sys::GDALDestroyDriverManager();
}
}

/// Get an `Iterator` over for all the loaded drivers.
///
/// Warning: Adding or removing drivers while consuming the
/// iterator is safe, but can produce less useful results.
pub fn all() -> DriverIterator {
DriverIterator { current: 0 }
}
}

/// Iterator for the registered [`Driver`]s in [`DriverManager`]
pub struct DriverIterator {
current: usize,
}

impl Iterator for DriverIterator {
type Item = Driver;

fn next(&mut self) -> Option<Self::Item> {
match DriverManager::get_driver(self.current) {
Ok(d) => {
self.current += 1;
Some(d)
}
Err(_) => None,
}
}
}

#[cfg(test)]
mod tests {
use std::collections::HashSet;

use super::*;

#[test]
Expand All @@ -466,4 +495,14 @@ mod tests {
assert!(DriverManager::count() > 0);
assert!(DriverManager::get_driver(0).is_ok());
}

#[test]
fn test_driver_iterator() {
assert_eq!(DriverManager::count(), DriverManager::all().count());

let drivers: HashSet<String> = DriverManager::all().map(|d| d.short_name()).collect();
for i in 0..DriverManager::count() {
assert!(drivers.contains(&DriverManager::get_driver(i).unwrap().short_name()))
}
}
}

0 comments on commit 82db2fe

Please sign in to comment.