Skip to content

Commit

Permalink
refactor: use BTreeMap instead of HashMap for small collections
Browse files Browse the repository at this point in the history
  • Loading branch information
colinmarc committed Oct 21, 2024
1 parent fd85726 commit e5bf42a
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 62 deletions.
26 changes: 12 additions & 14 deletions mm-server/src/compositor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod video;
mod xwayland;

use std::{
collections::BTreeMap,
ffi::{OsStr, OsString},
fs::File,
io::{BufRead, BufReader},
Expand All @@ -36,7 +37,6 @@ use child::*;
pub use control::*;
use crossbeam_channel as crossbeam;
pub use handle::*;
use hashbrown::HashMap;
pub use input::GamepadLayout;
use lazy_static::lazy_static;
use protocols::*;
Expand Down Expand Up @@ -121,7 +121,7 @@ pub struct State {

default_seat: seat::Seat,
input_manager: input::InputDeviceManager,
gamepads: HashMap<u64, input::GamepadHandle>,
gamepads: BTreeMap<u64, input::GamepadHandle>,

app_config: AppConfig,
display_params: DisplayParams,
Expand All @@ -138,7 +138,7 @@ pub struct State {
audio_pipeline: audio::EncodePipeline,

xwm: Option<xwayland::Xwm>,
xwayland_surface_lookup: HashMap<u64, surface::SurfaceKey>,
xwayland_surface_lookup: BTreeMap<u64, surface::SurfaceKey>,

// At the bottom for drop order.
vk: Arc<VkContext>,
Expand Down Expand Up @@ -226,7 +226,7 @@ impl Compositor {

// Set up input emulation (this is just for gamepads).
let mut input_manager = input::InputDeviceManager::new(&mut container)?;
let mut gamepads = HashMap::new();
let mut gamepads = BTreeMap::new();

for (pad_id, layout) in permanent_gamepads {
let dev = input_manager.plug_gamepad(pad_id, layout, true)?;
Expand Down Expand Up @@ -265,7 +265,7 @@ impl Compositor {
audio_pipeline,

xwm: None,
xwayland_surface_lookup: HashMap::default(),
xwayland_surface_lookup: BTreeMap::default(),

vk,
};
Expand Down Expand Up @@ -1007,19 +1007,17 @@ impl Compositor {
self.state.default_seat.lift_pointer(&self.state.serial);
}
ControlMessage::GamepadAvailable(id) => {
if !self.state.gamepads.contains_key(&id) {
self.state.gamepads.insert(
use std::collections::btree_map::Entry;
if let Entry::Vacant(e) = self.state.gamepads.entry(id) {
e.insert(self.state.input_manager.plug_gamepad(
id,
self.state.input_manager.plug_gamepad(
id,
input::GamepadLayout::GenericDualStick,
false,
)?,
);
input::GamepadLayout::GenericDualStick,
false,
)?);
}
}
ControlMessage::GamepadUnavailable(id) => {
use hashbrown::hash_map::Entry;
use std::collections::btree_map::Entry;
match self.state.gamepads.entry(id) {
Entry::Occupied(v) if !v.get().permanent => {
v.remove();
Expand Down
11 changes: 5 additions & 6 deletions mm-server/src/compositor/audio/pulse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// SPDX-License-Identifier: BUSL-1.1

use std::{
collections::VecDeque,
collections::{BTreeMap, VecDeque},
ffi::{CStr, CString},
io::{prelude::*, Cursor},
path::Path,
Expand All @@ -15,7 +15,6 @@ use anyhow::{bail, Context};
use bytes::BytesMut;
use crossbeam_channel as crossbeam;
use cstr::cstr;
use hashbrown::HashMap;
use mio::net::UnixListener;
use pulseaudio::protocol::{self as pulse, ClientInfoList};
use tracing::{debug, error, trace, warn};
Expand Down Expand Up @@ -62,7 +61,7 @@ struct Client {
protocol_version: u16,
props: Option<pulse::Props>,
incoming: BytesMut,
playback_streams: HashMap<u32, PlaybackStream>,
playback_streams: BTreeMap<u32, PlaybackStream>,
}

struct ServerState {
Expand All @@ -82,7 +81,7 @@ pub struct PulseServer {
unencoded_tx: crossbeam::Sender<EncodeFrame>,
done_rx: crossbeam::Receiver<EncodeFrame>,

clients: HashMap<mio::Token, Client>,
clients: BTreeMap<mio::Token, Client>,
server_state: ServerState,
}

Expand Down Expand Up @@ -188,7 +187,7 @@ impl PulseServer {
unencoded_tx,
done_rx,
close_rx,
clients: HashMap::new(),
clients: BTreeMap::new(),
server_state: ServerState {
server_info,
cards: vec![], // vec![dummy_card],
Expand Down Expand Up @@ -258,7 +257,7 @@ impl PulseServer {
protocol_version: pulse::MAX_VERSION,
props: None,
incoming: BytesMut::new(),
playback_streams: HashMap::new(),
playback_streams: BTreeMap::new(),
},
);
}
Expand Down
4 changes: 2 additions & 2 deletions mm-server/src/compositor/child/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ fn sync_barrier(barrier: &ipc::EventfdBarrier) -> rustix::io::Result<()> {

#[cfg(test)]
mod test {
use std::{collections::HashMap, fs::File, io::Read as _};
use std::{fs::File, io::Read as _};

use rustix::pipe::{pipe_with, PipeFlags};

Expand All @@ -839,7 +839,7 @@ mod test {
let app_config = AppConfig {
description: None,
command: vec!["echo".to_owned().into(), "done".to_owned().into()],
env: HashMap::new(),
env: Default::default(),
xwayland: false,
force_1x_scale: false,
home_isolation_mode: HomeIsolationMode::Unisolated,
Expand Down
12 changes: 7 additions & 5 deletions mm-server/src/compositor/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
//
// SPDX-License-Identifier: BUSL-1.1

use std::sync::{Arc, RwLock};
use std::{
collections::BTreeMap,
sync::{Arc, RwLock},
};

use crossbeam_channel as crossbeam;
use hashbrown::HashMap;

use super::CompositorEvent;

#[derive(Debug, Clone)]
struct Inner {
attachments: HashMap<u64, crossbeam::Sender<CompositorEvent>>,
attachments: BTreeMap<u64, crossbeam::Sender<CompositorEvent>>,
}

#[derive(Debug, Clone)]
Expand All @@ -21,7 +23,7 @@ impl CompositorHandle {
pub fn new(waker: Arc<mio::Waker>) -> Self {
Self(
Arc::new(RwLock::new(Inner {
attachments: HashMap::new(),
attachments: BTreeMap::new(),
})),
waker,
)
Expand Down Expand Up @@ -52,7 +54,7 @@ impl CompositorHandle {

pub fn kick_clients(&self) {
let attachments = &mut self.0.write().unwrap().attachments;
for (_, sender) in attachments.drain() {
for (_, sender) in std::mem::take(attachments) {
sender.send(CompositorEvent::Shutdown).ok();
}
}
Expand Down
4 changes: 2 additions & 2 deletions mm-server/src/compositor/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ impl InputDeviceManager {

#[cfg(test)]
mod test {
use std::{collections::HashMap, fs::File, io::Read as _};
use std::{fs::File, io::Read as _};

use rustix::pipe::{pipe_with, PipeFlags};

Expand All @@ -255,7 +255,7 @@ mod test {
let app_config = AppConfig {
description: None,
command,
env: HashMap::new(),
env: Default::default(),
xwayland: false,
force_1x_scale: false,
home_isolation_mode: HomeIsolationMode::Unisolated,
Expand Down
6 changes: 3 additions & 3 deletions mm-server/src/compositor/input/udevfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// SPDX-License-Identifier: BUSL-1.1

use std::{collections::HashMap, path::PathBuf, str::FromStr as _, sync::Arc, time};
use std::{collections::BTreeMap, path::PathBuf, str::FromStr as _, sync::Arc, time};

use fuser as fuse;
use libc::EBADF;
Expand Down Expand Up @@ -125,14 +125,14 @@ impl TryFrom<u64> for DeviceInode {
/// device.
pub struct UdevFs {
state: Arc<Mutex<super::InputManagerState>>,
static_inodes: HashMap<u64, StaticEntry>, // Indexed by inode.
static_inodes: BTreeMap<u64, StaticEntry>, // Indexed by inode.
}

impl UdevFs {
pub fn new(state: Arc<Mutex<super::InputManagerState>>) -> Self {
let ctime = time::SystemTime::now();

let mut static_inodes: HashMap<u64, StaticEntry> = HashMap::new();
let mut static_inodes: BTreeMap<u64, StaticEntry> = BTreeMap::new();

for (idx, entry) in STATIC_DIRS.iter().enumerate() {
let mut relpath = PathBuf::from_str(entry).unwrap();
Expand Down
9 changes: 4 additions & 5 deletions mm-server/src/compositor/video/vulkan_encode/dpb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
//
// SPDX-License-Identifier: BUSL-1.1

use std::sync::Arc;
use std::{collections::BTreeMap, sync::Arc};

use ash::vk;
use hashbrown::HashMap;

use crate::vulkan::*;

Expand All @@ -22,7 +21,7 @@ pub struct DpbPicture {
pub struct DpbPool {
_store: Vec<VkImage>,
slots: Vec<DpbPicture>,
ids: HashMap<u32, usize>,
ids: BTreeMap<u32, usize>,
}

impl DpbPool {
Expand Down Expand Up @@ -58,7 +57,7 @@ impl DpbPool {
Ok(Self {
_store: vec![image],
slots,
ids: HashMap::new(),
ids: BTreeMap::new(),
})
}

Expand Down Expand Up @@ -93,7 +92,7 @@ impl DpbPool {
Ok(Self {
_store: store,
slots,
ids: HashMap::new(),
ids: BTreeMap::new(),
})
}

Expand Down
10 changes: 5 additions & 5 deletions mm-server/src/compositor/xwayland/xwm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// SPDX-License-Identifier: BUSL-1.1

use std::{
collections::HashMap,
collections::BTreeMap,
os::fd::{AsFd as _, BorrowedFd},
};

Expand Down Expand Up @@ -116,8 +116,8 @@ pub struct Xwm {
client_list: Vec<u32>,
client_list_stacking: Vec<u32>,

pub xwindows: HashMap<u32, XWindow>,
pub serials: HashMap<u64, u32>,
pub xwindows: BTreeMap<u32, XWindow>,
pub serials: BTreeMap<u64, u32>,
}

impl Xwm {
Expand Down Expand Up @@ -219,8 +219,8 @@ impl Xwm {
client_list: Vec::new(),
client_list_stacking: Vec::new(),

xwindows: HashMap::new(),
serials: HashMap::new(),
xwindows: BTreeMap::new(),
serials: BTreeMap::new(),
})
}

Expand Down
18 changes: 9 additions & 9 deletions mm-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// SPDX-License-Identifier: BUSL-1.1

use std::{
collections::HashMap,
collections::BTreeMap,
ffi::{OsStr, OsString},
net::ToSocketAddrs,
num::NonZeroU32,
Expand All @@ -23,7 +23,7 @@ lazy_static! {

/// Serde representations of the configuration files.
mod parsed {
use std::{collections::HashMap, num::NonZeroU32, path::PathBuf};
use std::{collections::BTreeMap, num::NonZeroU32, path::PathBuf};

use converge::Converge;
use serde::Deserialize;
Expand Down Expand Up @@ -65,7 +65,7 @@ mod parsed {
#[derive(Debug, Clone, PartialEq, Deserialize, Converge)]
pub(super) struct Config {
pub(super) include_apps: Option<Vec<PathBuf>>,
pub(super) apps: Option<HashMap<String, AppConfig>>,
pub(super) apps: Option<BTreeMap<String, AppConfig>>,

pub(super) data_home: Option<PathBuf>,

Expand Down Expand Up @@ -100,7 +100,7 @@ mod parsed {
pub(super) struct AppConfig {
pub(super) description: Option<String>,
pub(super) command: Vec<String>,
pub(super) environment: Option<HashMap<String, String>>,
pub(super) environment: Option<BTreeMap<String, String>>,
pub(super) xwayland: Option<bool>,
pub(super) force_1x_scale: Option<bool>,
pub(super) isolate_home: Option<bool>,
Expand All @@ -112,7 +112,7 @@ mod parsed {
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
pub server: ServerConfig,
pub apps: HashMap<String, AppConfig>,
pub apps: BTreeMap<String, AppConfig>,
pub data_home: PathBuf,

pub bug_report_dir: Option<PathBuf>,
Expand All @@ -132,7 +132,7 @@ pub struct ServerConfig {
pub struct AppConfig {
pub description: Option<String>,
pub command: Vec<OsString>,
pub env: HashMap<OsString, OsString>,
pub env: BTreeMap<OsString, OsString>,
pub xwayland: bool,
pub force_1x_scale: bool,
pub home_isolation_mode: HomeIsolationMode,
Expand Down Expand Up @@ -218,8 +218,8 @@ impl Config {
},
},
data_home: data_home.clone(),
apps: HashMap::new(), // Handled below.
bug_report_dir: None, // This is only set from the command line.
apps: BTreeMap::new(), // Handled below.
bug_report_dir: None, // This is only set from the command line.
};

// Collect additional app definitions from app_dirs.
Expand Down Expand Up @@ -409,7 +409,7 @@ mod test {
static ref EXAMPLE_APP: AppConfig = AppConfig {
description: None,
command: vec!["echo".to_owned().into(), "hello".to_owned().into()],
env: HashMap::new(),
env: Default::default(),
xwayland: true,
force_1x_scale: false,
home_isolation_mode: HomeIsolationMode::Unisolated,
Expand Down
Loading

0 comments on commit e5bf42a

Please sign in to comment.