| 1 | use crate::provider_kind::ProviderKind; |
| 2 | |
| 3 | /// Ordered primary-plus-fallback provider list for future provider routing. |
| 4 | /// |
| 5 | /// The helper is intentionally dormant: constructing or parsing a chain does |
| 6 | /// not change `ConfigToml::resolve_runtime_options`. |
| 7 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8 | pub struct ProviderChain { |
| 9 | providers: Vec<ProviderKind>, |
| 10 | position: usize, |
| 11 | } |
| 12 | |
| 13 | impl ProviderChain { |
| 14 | #[must_use] |
| 15 | pub fn new(active: ProviderKind, fallbacks: &[ProviderKind]) -> Self { |
| 16 | let mut providers = vec![active]; |
| 17 | for fallback in fallbacks { |
| 18 | if *fallback != active && !providers.contains(fallback) { |
| 19 | providers.push(*fallback); |
| 20 | } |
| 21 | } |
| 22 | Self { |
| 23 | providers, |
| 24 | position: 0, |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | #[must_use] |
| 29 | pub fn providers(&self) -> &[ProviderKind] { |
| 30 | &self.providers |
| 31 | } |
| 32 | |
| 33 | #[must_use] |
| 34 | pub fn position(&self) -> usize { |
| 35 | self.position |
| 36 | } |
| 37 | |
| 38 | #[must_use] |
| 39 | pub fn current(&self) -> ProviderKind { |
| 40 | self.providers |
| 41 | .get(self.position) |
| 42 | .copied() |
| 43 | .or_else(|| self.providers.first().copied()) |
| 44 | .unwrap_or_default() |
| 45 | } |
| 46 | |
| 47 | #[must_use] |
| 48 | pub fn has_next(&self) -> bool { |
| 49 | self.position + 1 < self.providers.len() |
| 50 | } |
| 51 | |
| 52 | pub fn advance(&mut self) -> Option<ProviderKind> { |
| 53 | if !self.has_next() { |
| 54 | return None; |
| 55 | } |
| 56 | self.position += 1; |
| 57 | Some(self.current()) |
| 58 | } |
| 59 | |
| 60 | pub fn reset(&mut self) { |
| 61 | self.position = 0; |
| 62 | } |
| 63 | |
| 64 | #[must_use] |
| 65 | pub fn is_fallback_active(&self) -> bool { |
| 66 | self.position > 0 |
| 67 | } |
| 68 | |
| 69 | /// Count the current provider plus untried chain entries. |
| 70 | #[must_use] |
| 71 | pub fn remaining(&self) -> usize { |
| 72 | self.providers.len() - self.position |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | #[cfg(test)] |
| 77 | mod provider_chain_tests { |
| 78 | use super::*; |
| 79 | |
| 80 | #[test] |
| 81 | fn current_on_empty_chain_returns_default_provider() { |
| 82 | let chain = ProviderChain { |
| 83 | providers: vec![], |
| 84 | position: 0, |
| 85 | }; |
| 86 | assert_eq!(chain.current(), ProviderKind::default()); |
| 87 | } |
| 88 | } |
| 89 |