1
0

pool.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //! # pool of databases
  2. //!
  3. //! Redis and microredis support multiple databases.
  4. //!
  5. //! Each database is completely independent from each other. There are a few
  6. //! commands that allows multiple databases to interact with each other (to move
  7. //! or copy entires atomically).
  8. //!
  9. //! This struct will hold an Arc for each database to share databases between
  10. //! connections.
  11. use super::Db;
  12. use crate::error::Error;
  13. use std::sync::Arc;
  14. /// Databases
  15. #[derive(Debug)]
  16. pub struct Databases {
  17. databases: Vec<Arc<Db>>,
  18. }
  19. impl Databases {
  20. /// Creates new pool of databases.
  21. ///
  22. /// The default database is returned along side the pool
  23. pub fn new(databases: usize, number_of_slots: usize) -> (Arc<Db>, Arc<Self>) {
  24. let databases = (0..databases)
  25. .map(|_| Arc::new(Db::new(number_of_slots)))
  26. .collect::<Vec<Arc<Db>>>();
  27. (databases[0].clone(), Arc::new(Self { databases }))
  28. }
  29. /// Returns a single database or None
  30. pub fn get(&self, db: usize) -> Result<Arc<Db>, Error> {
  31. self.databases
  32. .get(db)
  33. .map(|db| db.clone())
  34. .ok_or(Error::NotSuchDatabase)
  35. }
  36. }
  37. /// Database iterator
  38. pub struct DatabasesIterator<'a> {
  39. databases: &'a Databases,
  40. index: usize,
  41. }
  42. impl<'a> IntoIterator for &'a Databases {
  43. type Item = Arc<Db>;
  44. type IntoIter = DatabasesIterator<'a>;
  45. fn into_iter(self) -> Self::IntoIter {
  46. DatabasesIterator {
  47. databases: self,
  48. index: 0,
  49. }
  50. }
  51. }
  52. impl<'a> Iterator for DatabasesIterator<'a> {
  53. type Item = Arc<Db>;
  54. fn next(&mut self) -> Option<Self::Item> {
  55. self.index += 1;
  56. self.databases.get(self.index - 1).ok()
  57. }
  58. }