use std::collections::BTreeSet;
use std::fmt;
#[cfg(debug_assertions)]
use std::cell::RefCell;
#[cfg(debug_assertions)]
use std::sync::Arc;
#[cfg(doc)]
use crate::Shared;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Access {
reads: BTreeSet<String>,
writes: BTreeSet<String>,
}
impl Access {
#[must_use]
pub const fn none() -> Self {
Self {
reads: BTreeSet::new(),
writes: BTreeSet::new(),
}
}
#[must_use]
pub fn reads(mut self, name: impl Into<String>) -> Self {
let name = name.into();
if !self.writes.contains(&name) {
self.reads.insert(name);
}
self
}
#[must_use]
pub fn writes(mut self, name: impl Into<String>) -> Self {
let name = name.into();
self.reads.remove(&name);
self.writes.insert(name);
self
}
pub fn read_names(&self) -> impl Iterator<Item = &str> {
self.reads.iter().map(String::as_str)
}
pub fn write_names(&self) -> impl Iterator<Item = &str> {
self.writes.iter().map(String::as_str)
}
#[must_use]
pub fn is_none(&self) -> bool {
self.reads.is_empty() && self.writes.is_empty()
}
pub(crate) fn touched(&self) -> impl Iterator<Item = &str> {
self.reads.union(&self.writes).map(String::as_str)
}
fn allows_read(&self, name: &str) -> bool {
self.reads.contains(name) || self.writes.contains(name)
}
fn allows_write(&self, name: &str) -> bool {
self.writes.contains(name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConflictKind {
WriteWrite,
ReadWrite,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Conflict {
pub before: usize,
pub after: usize,
pub resource: String,
pub kind: ConflictKind,
}
pub(crate) fn conflicts_between(
before: usize,
earlier: &Access,
after: usize,
later: &Access,
out: &mut Vec<Conflict>,
) {
for resource in earlier.touched() {
if !later.allows_read(resource) {
continue;
}
let kind = match (earlier.allows_write(resource), later.allows_write(resource)) {
(true, true) => ConflictKind::WriteWrite,
(true, false) | (false, true) => ConflictKind::ReadWrite,
(false, false) => continue,
};
out.push(Conflict {
before,
after,
resource: resource.to_owned(),
kind,
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessError {
UnknownResource {
system: String,
resource: String,
},
DuplicateResource {
resource: String,
},
}
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownResource { system, resource } => write!(
f,
"system `{system}` declares shared resource `{resource}`, which is not \
registered with its schedule"
),
Self::DuplicateResource { resource } => write!(
f,
"a shared resource named `{resource}` is already registered with this schedule"
),
}
}
}
impl std::error::Error for AccessError {}
#[derive(Debug)]
pub(crate) struct Declared {
#[cfg(debug_assertions)]
pub(crate) system: String,
pub(crate) access: Access,
}
#[cfg(debug_assertions)]
thread_local! {
static RUNNING: RefCell<Option<Arc<Declared>>> = const { RefCell::new(None) };
}
#[cfg(debug_assertions)]
pub(crate) struct Running {
previous: Option<Arc<Declared>>,
}
#[cfg(debug_assertions)]
impl Running {
pub(crate) fn enter(declared: &Arc<Declared>) -> Self {
let previous = RUNNING.with(|running| running.replace(Some(Arc::clone(declared))));
Self { previous }
}
}
#[cfg(debug_assertions)]
impl Drop for Running {
fn drop(&mut self) {
let previous = self.previous.take();
RUNNING.with(|running| *running.borrow_mut() = previous);
}
}
#[cfg(debug_assertions)]
pub(crate) fn check(resource: &str, write: bool) {
RUNNING.with_borrow(|running| {
let Some(declared) = running else {
return;
};
let (allowed, verb) = if write {
(declared.access.allows_write(resource), "wrote")
} else {
(declared.access.allows_read(resource), "read")
};
assert!(
allowed,
"system `{}` {verb} shared resource `{resource}` without declaring that access",
declared.system
);
});
}
#[cfg(test)]
mod tests {
use super::*;
fn conflicts(earlier: &Access, later: &Access) -> Vec<(String, ConflictKind)> {
let mut out = Vec::new();
conflicts_between(0, earlier, 1, later, &mut out);
out.into_iter()
.map(|conflict| (conflict.resource, conflict.kind))
.collect()
}
#[test]
fn two_writers_of_one_resource_conflict() {
let writer = Access::none().writes("score");
assert_eq!(
conflicts(&writer, &writer),
[("score".to_owned(), ConflictKind::WriteWrite)]
);
}
#[test]
fn a_reader_and_a_writer_of_one_resource_conflict_either_way_round() {
let reader = Access::none().reads("wind");
let writer = Access::none().writes("wind");
let read_write = [("wind".to_owned(), ConflictKind::ReadWrite)];
assert_eq!(conflicts(&reader, &writer), read_write);
assert_eq!(conflicts(&writer, &reader), read_write);
}
#[test]
fn two_readers_of_one_resource_do_not_conflict() {
let reader = Access::none().reads("wind");
assert_eq!(conflicts(&reader, &reader), []);
}
#[test]
fn systems_touching_different_resources_do_not_conflict() {
let a = Access::none().writes("score");
let b = Access::none().writes("wind");
assert_eq!(conflicts(&a, &b), []);
}
#[test]
fn a_name_declared_both_ways_is_a_write() {
for access in [
Access::none().reads("wind").writes("wind"),
Access::none().writes("wind").reads("wind"),
] {
assert_eq!(access.read_names().count(), 0);
assert_eq!(access.write_names().collect::<Vec<_>>(), ["wind"]);
assert!(access.allows_read("wind"));
}
}
#[test]
fn the_refusals_name_what_was_refused() {
let unknown = AccessError::UnknownResource {
system: "mover".to_owned(),
resource: "wind".to_owned(),
};
let message = unknown.to_string();
assert!(message.contains("`mover`"), "{message}");
assert!(message.contains("`wind`"), "{message}");
let duplicate = AccessError::DuplicateResource {
resource: "wind".to_owned(),
};
assert!(duplicate.to_string().contains("`wind`"));
}
}