From b42b1ad99bfab7f348e97768d484c8ac0d7e9eea Mon Sep 17 00:00:00 2001 From: Alexander Krotov Date: Sun, 13 Sep 2020 13:59:23 +0300 Subject: [PATCH] Make dc_accounts_get_all return accounts sorted HashMap may rearrange all accounts after each insertion and deletion, making it unpredictable where the new account appears. --- src/accounts.rs | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/accounts.rs b/src/accounts.rs index 025c41144..7c23a6346 100644 --- a/src/accounts.rs +++ b/src/accounts.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::BTreeMap; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; use std::task::{Context as TaskContext, Poll}; @@ -20,7 +20,7 @@ use crate::events::Event; pub struct Accounts { dir: PathBuf, config: Config, - accounts: Arc>>, + accounts: Arc>>, } impl Accounts { @@ -342,9 +342,9 @@ impl Config { }) } - pub async fn load_accounts(&self) -> Result> { + pub async fn load_accounts(&self) -> Result> { let cfg = &*self.inner.read().await; - let mut accounts = HashMap::with_capacity(cfg.accounts.len()); + let mut accounts = BTreeMap::new(); for account_config in &cfg.accounts { let ctx = Context::new( cfg.os_name.clone(), @@ -530,4 +530,23 @@ mod tests { ctx.get_config(crate::config::Config::Addr).await.unwrap() ); } + + /// Tests that accounts are sorted by ID. + #[async_std::test] + async fn test_accounts_sorted() { + let dir = tempfile::tempdir().unwrap(); + let p: PathBuf = dir.path().join("accounts").into(); + + let accounts = Accounts::new("my_os".into(), p.clone()).await.unwrap(); + + for expected_id in 2..10 { + let id = accounts.add_account().await.unwrap(); + assert_eq!(id, expected_id); + } + + let ids = accounts.get_all().await; + for (i, expected_id) in (1..10).enumerate() { + assert_eq!(ids.get(i), Some(&expected_id)); + } + } }