remoc/robs/hash_map.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
//! Observable hash map.
//!
//! This provides a locally and remotely observable hash map.
//! The observable hash map sends a change event each time a change is performed on it.
//! The [resulting event stream](HashMapSubscription) can either be processed event-wise
//! or used to build a [mirrored hash map](MirroredHashMap).
//!
//! Changes are sent using a [remote broadcast channel](crate::rch::broadcast), thus
//! subscribers cannot block the observed hash map and are shed when their event buffer
//! exceeds a configurable size.
//!
//! # Basic use
//!
//! Create a [ObservableHashMap] and obtain a [subscription](HashMapSubscription) to it using
//! [ObservableHashMap::subscribe].
//! Send this subscription to a remote endpoint via a [remote channel](crate::rch) and call
//! [HashMapSubscription::mirror] on the remote endpoint to obtain a live mirror of the observed
//! hash map or process each change event individually using [HashMapSubscription::recv].
//!
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fmt,
hash::Hash,
iter::FusedIterator,
mem::take,
ops::{Deref, DerefMut},
sync::Arc,
};
use tokio::sync::{oneshot, watch, RwLock, RwLockReadGuard};
use super::{default_on_err, send_event, ChangeNotifier, ChangeSender, RecvError, SendError};
use crate::prelude::*;
/// A hash map change event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HashMapEvent<K, V> {
/// The incremental subscription has reached the value of the observed
/// hash map at the time it was subscribed.
#[serde(skip)]
InitialComplete,
/// An item was inserted or modified.
Set(K, V),
/// An item was removed.
Remove(K),
/// All items were removed.
Clear,
/// Shrink capacity to fit.
ShrinkToFit,
/// The hash map has reached its final state and
/// no further events will occur.
Done,
}
/// A hash map that emits an event for each change.
///
/// Use [subscribe](Self::subscribe) to obtain an event stream
/// that can be used for building a mirror of this hash map.
pub struct ObservableHashMap<K, V, Codec = crate::codec::Default> {
hm: HashMap<K, V>,
tx: rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
change: ChangeSender,
on_err: Arc<dyn Fn(SendError) + Send + Sync>,
done: bool,
}
impl<K, V, Codec> fmt::Debug for ObservableHashMap<K, V, Codec>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.hm.fmt(f)
}
}
impl<K, V, Codec> From<HashMap<K, V>> for ObservableHashMap<K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn from(hm: HashMap<K, V>) -> Self {
let (tx, _rx) = rch::broadcast::channel::<_, _, { rch::DEFAULT_BUFFER }>(1);
Self { hm, tx, on_err: Arc::new(default_on_err), change: ChangeSender::new(), done: false }
}
}
impl<K, V, Codec> From<ObservableHashMap<K, V, Codec>> for HashMap<K, V> {
fn from(ohm: ObservableHashMap<K, V, Codec>) -> Self {
ohm.hm
}
}
impl<K, V, Codec> Default for ObservableHashMap<K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn default() -> Self {
Self::from(HashMap::new())
}
}
impl<K, V, Codec> ObservableHashMap<K, V, Codec>
where
K: Eq + Hash + Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
/// Creates an empty observable hash map.
pub fn new() -> Self {
Self::default()
}
/// Sets the error handler function that is called when sending an
/// event fails.
pub fn set_error_handler<E>(&mut self, on_err: E)
where
E: Fn(SendError) + Send + Sync + 'static,
{
self.on_err = Arc::new(on_err);
}
/// Subscribes to change events from this observable hash map.
///
/// The current contents of the hash map is included with the subscription.
///
/// `buffer` specifies the maximum size of the event buffer for this subscription in number of events.
/// If it is exceeded the subscription is shed and the receiver gets a [RecvError::Lagged].
pub fn subscribe(&self, buffer: usize) -> HashMapSubscription<K, V, Codec> {
HashMapSubscription::new(
HashMapInitialValue::new_value(self.hm.clone()),
if self.done { None } else { Some(self.tx.subscribe(buffer)) },
)
}
/// Subscribes to change events from this observable hash map with incremental sending
/// of the current contents.
///
/// The current contents of the hash map are sent incrementally.
///
/// `buffer` specifies the maximum size of the event buffer for this subscription in number of events.
/// If it is exceeded the subscription is shed and the receiver gets a [RecvError::Lagged].
pub fn subscribe_incremental(&self, buffer: usize) -> HashMapSubscription<K, V, Codec> {
HashMapSubscription::new(
HashMapInitialValue::new_incremental(self.hm.clone(), self.on_err.clone()),
if self.done { None } else { Some(self.tx.subscribe(buffer)) },
)
}
/// Current number of subscribers.
pub fn subscriber_count(&self) -> usize {
self.tx.receiver_count()
}
/// Returns a [change notifier](ChangeNotifier) that can be used *locally* to be
/// notified of changes to this collection.
pub fn notifier(&self) -> ChangeNotifier {
self.change.subscribe()
}
/// Inserts a value under a key.
///
/// A [HashMapEvent::Set] change event is sent.
///
/// Returns the value previously stored under the key, if any.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
self.assert_not_done();
self.change.notify();
send_event(&self.tx, &*self.on_err, HashMapEvent::Set(k.clone(), v.clone()));
self.hm.insert(k, v)
}
/// Removes the value under the specified key.
///
/// A [HashMapEvent::Remove] change event is sent.
///
/// The value is returned.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
self.assert_not_done();
match self.hm.remove_entry(k) {
Some((k, v)) => {
self.change.notify();
send_event(&self.tx, &*self.on_err, HashMapEvent::Remove(k));
Some(v)
}
None => None,
}
}
/// Removes all items.
///
/// A [HashMapEvent::Clear] change event is sent.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn clear(&mut self) {
self.assert_not_done();
if !self.hm.is_empty() {
self.hm.clear();
self.change.notify();
send_event(&self.tx, &*self.on_err, HashMapEvent::Clear);
}
}
/// Retains only the elements specified by the predicate.
///
/// A [HashMapEvent::Remove] change event is sent for every element that is removed.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&K, &mut V) -> bool,
{
self.assert_not_done();
self.hm.retain(|k, v| {
if f(k, v) {
true
} else {
self.change.notify();
send_event(&self.tx, &*self.on_err, HashMapEvent::Remove(k.clone()));
false
}
});
}
/// Gets the given key’s corresponding entry in the map for in-place manipulation.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, Codec> {
self.assert_not_done();
match self.hm.entry(key) {
std::collections::hash_map::Entry::Occupied(inner) => Entry::Occupied(OccupiedEntry {
inner,
tx: &self.tx,
change: &self.change,
on_err: &*self.on_err,
}),
std::collections::hash_map::Entry::Vacant(inner) => {
Entry::Vacant(VacantEntry { inner, tx: &self.tx, change: &self.change, on_err: &*self.on_err })
}
}
}
/// Gets a mutable reference to the value under the specified key.
///
/// A [HashMapEvent::Set] change event is sent if the reference is accessed mutably.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<RefMut<'_, K, V, Codec>>
where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
self.assert_not_done();
match self.hm.get_key_value(k) {
Some((key, _)) => {
let key = key.clone();
let value = self.hm.get_mut(k).unwrap();
Some(RefMut {
key,
value,
changed: false,
tx: &self.tx,
change: &self.change,
on_err: &*self.on_err,
})
}
None => None,
}
}
/// Mutably iterates over the key-value pairs.
///
/// A [HashMapEvent::Set] change event is sent for each value that is accessed mutably.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn iter_mut(&mut self) -> IterMut<'_, K, V, Codec> {
self.assert_not_done();
IterMut { inner: self.hm.iter_mut(), tx: &self.tx, change: &self.change, on_err: &*self.on_err }
}
/// Shrinks the capacity of the hash map as much as possible.
///
/// A [HashMapEvent::ShrinkToFit] change event is sent.
///
/// # Panics
/// Panics when [done](Self::done) has been called before.
pub fn shrink_to_fit(&mut self) {
self.assert_not_done();
send_event(&self.tx, &*self.on_err, HashMapEvent::ShrinkToFit);
self.hm.shrink_to_fit()
}
/// Panics when `done` has been called.
fn assert_not_done(&self) {
if self.done {
panic!("observable hash map cannot be changed after done has been called");
}
}
/// Prevents further changes of this hash map and notifies
/// are subscribers that no further events will occur.
///
/// Methods that modify the hash map will panic after this has been called.
/// It is still possible to subscribe to this observable hash map.
pub fn done(&mut self) {
if !self.done {
send_event(&self.tx, &*self.on_err, HashMapEvent::Done);
self.done = true;
}
}
/// Returns `true` if [done](Self::done) has been called and further
/// changes are prohibited.
///
/// Methods that modify the hash map will panic in this case.
pub fn is_done(&self) -> bool {
self.done
}
/// Extracts the underlying hash map.
///
/// If [done](Self::done) has not been called before this method,
/// subscribers will receive an error.
pub fn into_inner(self) -> HashMap<K, V> {
self.into()
}
}
impl<K, V, Codec> Deref for ObservableHashMap<K, V, Codec> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.hm
}
}
impl<K, V, Codec> Extend<(K, V)> for ObservableHashMap<K, V, Codec>
where
K: Eq + Hash + Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (k, v) in iter {
self.insert(k, v);
}
}
}
/// A mutable reference to a value inside an [observable hash map](ObservableHashMap).
///
/// A [HashMapEvent::Set] change event is sent when this reference is dropped and the
/// value has been accessed mutably.
pub struct RefMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
key: K,
value: &'a mut V,
changed: bool,
tx: &'a rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
change: &'a ChangeSender,
on_err: &'a dyn Fn(SendError),
}
impl<'a, K, V, Codec> Deref for RefMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
type Target = V;
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<'a, K, V, Codec> DerefMut for RefMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.changed = true;
self.value
}
}
impl<'a, K, V, Codec> Drop for RefMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn drop(&mut self) {
if self.changed {
self.change.notify();
send_event(self.tx, self.on_err, HashMapEvent::Set(self.key.clone(), self.value.clone()));
}
}
}
/// A mutable iterator over the key-value pairs in an [observable hash map](ObservableHashMap).
///
/// A [HashMapEvent::Set] change event is sent for each value that is accessed mutably.
pub struct IterMut<'a, K, V, Codec = crate::codec::Default> {
inner: std::collections::hash_map::IterMut<'a, K, V>,
tx: &'a rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
change: &'a ChangeSender,
on_err: &'a dyn Fn(SendError),
}
impl<'a, K, V, Codec> Iterator for IterMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
type Item = RefMut<'a, K, V, Codec>;
fn next(&mut self) -> Option<Self::Item> {
match self.inner.next() {
Some((key, value)) => Some(RefMut {
key: key.clone(),
value,
changed: false,
tx: self.tx,
change: self.change,
on_err: self.on_err,
}),
None => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K, V, Codec> ExactSizeIterator for IterMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
fn len(&self) -> usize {
self.inner.len()
}
}
impl<'a, K, V, Codec> FusedIterator for IterMut<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
}
/// A view into a single entry in an observable hash map, which may either be
/// vacant or occupied.
///
/// This is returned by [ObservableHashMap::entry].
#[derive(Debug)]
pub enum Entry<'a, K, V, Codec = crate::codec::Default> {
/// An occupied entry.
Occupied(OccupiedEntry<'a, K, V, Codec>),
/// A vacant entry.
Vacant(VacantEntry<'a, K, V, Codec>),
}
impl<'a, K, V, Codec> Entry<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
/// Ensures a value is in the entry by inserting the default if empty,
/// and returns a mutable reference to the value in the entry.
pub fn or_insert(self, default: V) -> RefMut<'a, K, V, Codec> {
match self {
Self::Occupied(ocu) => ocu.into_mut(),
Self::Vacant(vac) => vac.insert(default),
}
}
/// Ensures a value is in the entry by inserting the result of the default
/// function if empty, and returns a mutable reference to the value in the entry.
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> RefMut<'a, K, V, Codec> {
match self {
Self::Occupied(ocu) => ocu.into_mut(),
Self::Vacant(vac) => vac.insert(default()),
}
}
/// Ensures a value is in the entry by inserting the result of the default
/// function with key as argument if empty, and returns a mutable reference to the value in the entry.
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> RefMut<'a, K, V, Codec> {
match self {
Self::Occupied(ocu) => ocu.into_mut(),
Self::Vacant(vac) => {
let value = default(vac.key());
vac.insert(value)
}
}
}
/// Returns a reference to this entry’s key.
pub fn key(&self) -> &K {
match self {
Self::Occupied(ocu) => ocu.key(),
Self::Vacant(vac) => vac.key(),
}
}
/// Provides in-place mutable access to an occupied entry before any potential inserts into the map.
pub fn and_modify<F: FnOnce(&mut V)>(mut self, f: F) -> Self {
if let Self::Occupied(ocu) = &mut self {
let mut value = ocu.get_mut();
f(&mut *value);
}
self
}
}
impl<'a, K, V, Codec> Entry<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend + Default,
Codec: crate::codec::Codec,
{
/// Ensures a value is in the entry by inserting the default value if empty,
/// and returns a mutable reference to the value in the entry.
pub fn or_default(self) -> RefMut<'a, K, V, Codec> {
self.or_insert_with(V::default)
}
}
/// A view into an occupied entry in an observable hash map.
pub struct OccupiedEntry<'a, K, V, Codec = crate::codec::Default> {
inner: std::collections::hash_map::OccupiedEntry<'a, K, V>,
tx: &'a rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
change: &'a ChangeSender,
on_err: &'a dyn Fn(SendError),
}
impl<'a, K, V, Codec> fmt::Debug for OccupiedEntry<'a, K, V, Codec>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<'a, K, V, Codec> OccupiedEntry<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
/// Gets a reference to the key in the entry.
pub fn key(&self) -> &K {
self.inner.key()
}
/// Take the ownership of the key and value from the map.
///
/// A [HashMapEvent::Remove] change event is sent.
pub fn remove_entry(self) -> (K, V) {
let (k, v) = self.inner.remove_entry();
self.change.notify();
send_event(self.tx, self.on_err, HashMapEvent::Remove(k.clone()));
(k, v)
}
/// Gets a reference to the value in the entry.
pub fn get(&self) -> &V {
self.inner.get()
}
/// Gets a mutable reference to the value in the entry.
pub fn get_mut(&mut self) -> RefMut<'_, K, V, Codec> {
RefMut {
key: self.inner.key().clone(),
value: self.inner.get_mut(),
changed: false,
tx: self.tx,
change: self.change,
on_err: self.on_err,
}
}
/// Converts this into a mutable reference to the value in
/// the entry with a lifetime bound to the map itself.
pub fn into_mut(self) -> RefMut<'a, K, V, Codec> {
let key = self.inner.key().clone();
RefMut {
key,
value: self.inner.into_mut(),
changed: false,
tx: self.tx,
change: self.change,
on_err: self.on_err,
}
}
/// Sets the value of the entry, and returns the entry’s old value.
///
/// A [HashMapEvent::Set] change event is sent.
pub fn insert(&mut self, value: V) -> V {
self.change.notify();
send_event(self.tx, self.on_err, HashMapEvent::Set(self.inner.key().clone(), value.clone()));
self.inner.insert(value)
}
/// Takes the value out of the entry, and returns it.
///
/// A [HashMapEvent::Remove] change event is sent.
pub fn remove(self) -> V {
let (k, v) = self.inner.remove_entry();
self.change.notify();
send_event(self.tx, self.on_err, HashMapEvent::Remove(k));
v
}
}
/// A view into a vacant entry in an observable hash map.
pub struct VacantEntry<'a, K, V, Codec = crate::codec::Default> {
inner: std::collections::hash_map::VacantEntry<'a, K, V>,
tx: &'a rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
change: &'a ChangeSender,
on_err: &'a dyn Fn(SendError),
}
impl<'a, K, V, Codec> fmt::Debug for VacantEntry<'a, K, V, Codec>
where
K: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<'a, K, V, Codec> VacantEntry<'a, K, V, Codec>
where
K: Clone + RemoteSend,
V: Clone + RemoteSend,
Codec: crate::codec::Codec,
{
/// Gets a reference to the key.
pub fn key(&self) -> &K {
self.inner.key()
}
/// Take ownership of the key.
pub fn into_key(self) -> K {
self.inner.into_key()
}
/// Sets the value of the entry, and returns a mutable reference to it.
///
/// A [HashMapEvent::Set] change event is sent.
pub fn insert(self, value: V) -> RefMut<'a, K, V, Codec> {
let key = self.inner.key().clone();
self.change.notify();
send_event(self.tx, self.on_err, HashMapEvent::Set(key.clone(), value.clone()));
let value = self.inner.insert(value);
RefMut { key, value, changed: false, tx: self.tx, change: self.change, on_err: self.on_err }
}
}
struct MirroredHashMapInner<K, V> {
hm: HashMap<K, V>,
complete: bool,
done: bool,
error: Option<RecvError>,
max_size: usize,
}
impl<K, V> MirroredHashMapInner<K, V>
where
K: Eq + Hash,
{
fn handle_event(&mut self, event: HashMapEvent<K, V>) -> Result<(), RecvError> {
match event {
HashMapEvent::InitialComplete => {
self.complete = true;
}
HashMapEvent::Set(k, v) => {
self.hm.insert(k, v);
if self.hm.len() > self.max_size {
return Err(RecvError::MaxSizeExceeded(self.max_size));
}
}
HashMapEvent::Remove(k) => {
self.hm.remove(&k);
}
HashMapEvent::Clear => {
self.hm.clear();
}
HashMapEvent::ShrinkToFit => {
self.hm.shrink_to_fit();
}
HashMapEvent::Done => {
self.done = true;
}
}
Ok(())
}
}
/// Initial value of an observable hash map subscription.
#[derive(Debug, Serialize, Deserialize)]
#[serde(bound(serialize = "K: RemoteSend + Eq + Hash, V: RemoteSend, Codec: crate::codec::Codec"))]
#[serde(bound(deserialize = "K: RemoteSend + Eq + Hash, V: RemoteSend, Codec: crate::codec::Codec"))]
enum HashMapInitialValue<K, V, Codec = crate::codec::Default> {
/// Initial value is present.
Value(HashMap<K, V>),
/// Initial value is received incrementally.
Incremental {
/// Number of elements.
len: usize,
/// Receiver.
rx: rch::mpsc::Receiver<(K, V), Codec>,
},
}
impl<K, V, Codec> HashMapInitialValue<K, V, Codec>
where
K: RemoteSend + Eq + Hash + Clone,
V: RemoteSend + Clone,
Codec: crate::codec::Codec,
{
/// Transmits the initial value as a whole.
fn new_value(hm: HashMap<K, V>) -> Self {
Self::Value(hm)
}
/// Transmits the initial value incrementally.
fn new_incremental(hm: HashMap<K, V>, on_err: Arc<dyn Fn(SendError) + Send + Sync>) -> Self {
let (tx, rx) = rch::mpsc::channel(128);
let len = hm.len();
tokio::spawn(async move {
for (k, v) in hm.into_iter() {
match tx.send((k, v)).await {
Ok(()) => (),
Err(err) if err.is_disconnected() => break,
Err(err) => match err.try_into() {
Ok(err) => (on_err)(err),
Err(_) => unreachable!(),
},
}
}
});
Self::Incremental { len, rx }
}
}
/// Observable hash map subscription.
///
/// This can be sent to a remote endpoint via a [remote channel](crate::rch).
/// Then, on the remote endpoint, [mirror](Self::mirror) can be used to build
/// and keep up-to-date a mirror of the observed hash map.
///
/// The event stream can also be processed event-wise using [recv](Self::recv).
/// If the subscription is not incremental [take_initial](Self::take_initial) must
/// be called before the first call to [recv](Self::recv).
#[derive(Debug, Serialize, Deserialize)]
#[serde(bound(serialize = "K: RemoteSend + Eq + Hash, V: RemoteSend, Codec: crate::codec::Codec"))]
#[serde(bound(deserialize = "K: RemoteSend + Eq + Hash, V: RemoteSend, Codec: crate::codec::Codec"))]
pub struct HashMapSubscription<K, V, Codec = crate::codec::Default> {
/// Value of hash map at time of subscription.
initial: HashMapInitialValue<K, V, Codec>,
/// Initial value received completely.
#[serde(skip, default)]
complete: bool,
/// Change events receiver.
///
/// `None` if [ObservableHashMap::done] has been called before subscribing.
events: Option<rch::broadcast::Receiver<HashMapEvent<K, V>, Codec>>,
/// Event stream ended.
#[serde(skip, default)]
done: bool,
}
impl<K, V, Codec> HashMapSubscription<K, V, Codec>
where
K: RemoteSend + Eq + Hash + Clone,
V: RemoteSend + Clone,
Codec: crate::codec::Codec,
{
fn new(
initial: HashMapInitialValue<K, V, Codec>,
events: Option<rch::broadcast::Receiver<HashMapEvent<K, V>, Codec>>,
) -> Self {
Self { initial, complete: false, events, done: false }
}
/// Returns whether the subscription is incremental.
pub fn is_incremental(&self) -> bool {
matches!(self.initial, HashMapInitialValue::Incremental { .. })
}
/// Returns whether the initial value event or
/// stream of events that build up the initial value
/// has completed or [take_initial](Self::take_initial) has been called.
pub fn is_complete(&self) -> bool {
self.complete
}
/// Returns whether the observed hash map has indicated that no further
/// change events will occur.
pub fn is_done(&self) -> bool {
self.events.is_none() || self.done
}
/// Take the initial value.
///
/// This is only possible if the subscription is not incremental
/// and the initial value has not already been taken.
/// Otherwise `None` is returned.
///
/// If the subscription is not incremental this must be called before the
/// first call to [recv](Self::recv).
pub fn take_initial(&mut self) -> Option<HashMap<K, V>> {
match &mut self.initial {
HashMapInitialValue::Value(value) if !self.complete => {
self.complete = true;
Some(take(value))
}
_ => None,
}
}
/// Receives the next change event.
///
/// # Panics
/// Panics when the subscription is not incremental and [take_initial](Self::take_initial)
/// has not been called.
pub async fn recv(&mut self) -> Result<Option<HashMapEvent<K, V>>, RecvError> {
// Provide initial value events.
if !self.complete {
match &mut self.initial {
HashMapInitialValue::Incremental { len, rx } => {
if *len > 0 {
match rx.recv().await? {
Some((k, v)) => {
// Provide incremental initial value event.
*len -= 1;
return Ok(Some(HashMapEvent::Set(k, v)));
}
None => return Err(RecvError::Closed),
}
} else {
// Provide incremental initial value complete event.
self.complete = true;
return Ok(Some(HashMapEvent::InitialComplete));
}
}
HashMapInitialValue::Value(_) => {
panic!("take_initial must be called before recv for non-incremental subscription");
}
}
}
// Provide change event.
if let Some(rx) = &mut self.events {
match rx.recv().await? {
HashMapEvent::Done => self.events = None,
evt => return Ok(Some(evt)),
}
}
// Provide done event.
if self.done {
Ok(None)
} else {
self.done = true;
Ok(Some(HashMapEvent::Done))
}
}
}
impl<K, V, Codec> HashMapSubscription<K, V, Codec>
where
K: RemoteSend + Eq + Hash + Clone + Sync,
V: RemoteSend + Clone + Sync,
Codec: crate::codec::Codec,
{
/// Mirror the hash map that this subscription is observing.
///
/// `max_size` specifies the maximum allowed size of the mirrored collection.
/// If this size is reached, processing of events is stopped and
/// [RecvError::MaxSizeExceeded] is returned.
pub fn mirror(mut self, max_size: usize) -> MirroredHashMap<K, V, Codec> {
let (tx, _rx) = rch::broadcast::channel::<_, _, { rch::DEFAULT_BUFFER }>(1);
let (changed_tx, changed_rx) = watch::channel(());
let (dropped_tx, mut dropped_rx) = oneshot::channel();
// Build initial state.
let inner = Arc::new(RwLock::new(Some(MirroredHashMapInner {
hm: self.take_initial().unwrap_or_default(),
complete: self.is_complete(),
done: self.is_done(),
error: None,
max_size,
})));
let inner_task = inner.clone();
// Process change events.
let tx_send = tx.clone();
tokio::spawn(async move {
loop {
let event = tokio::select! {
event = self.recv() => event,
_ = &mut dropped_rx => return,
};
let mut inner = inner_task.write().await;
let inner = match inner.as_mut() {
Some(inner) => inner,
None => return,
};
changed_tx.send_replace(());
match event {
Ok(Some(event)) => {
if tx_send.receiver_count() > 0 {
let _ = tx_send.send(event.clone());
}
if let Err(err) = inner.handle_event(event) {
inner.error = Some(err);
return;
}
if inner.done {
break;
}
}
Ok(None) => break,
Err(err) => {
inner.error = Some(err);
return;
}
}
}
});
MirroredHashMap { inner, tx, changed_rx, _dropped_tx: dropped_tx }
}
}
/// A hash map that is mirroring an observable hash map.
pub struct MirroredHashMap<K, V, Codec = crate::codec::Default> {
inner: Arc<RwLock<Option<MirroredHashMapInner<K, V>>>>,
tx: rch::broadcast::Sender<HashMapEvent<K, V>, Codec>,
changed_rx: watch::Receiver<()>,
_dropped_tx: oneshot::Sender<()>,
}
impl<K, V, Codec> fmt::Debug for MirroredHashMap<K, V, Codec> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("MirroredHashMap").finish()
}
}
impl<K, V, Codec> MirroredHashMap<K, V, Codec>
where
K: RemoteSend + Eq + Hash + Clone,
V: RemoteSend + Clone,
Codec: crate::codec::Codec,
{
/// Returns a reference to the current value of the hash map.
///
/// Updates are paused while the read lock is held.
///
/// This method returns an error if the observed hash map has been dropped
/// or the connection to it failed before it was marked as done by calling
/// [ObservableHashMap::done].
/// In this case the mirrored contents at the point of loss of connection
/// can be obtained using [detach](Self::detach).
pub async fn borrow(&self) -> Result<MirroredHashMapRef<'_, K, V>, RecvError> {
let inner = self.inner.read().await;
let inner = RwLockReadGuard::map(inner, |inner| inner.as_ref().unwrap());
match &inner.error {
None => Ok(MirroredHashMapRef(inner)),
Some(err) => Err(err.clone()),
}
}
/// Returns a reference to the current value of the hash map and marks it as seen.
///
/// Thus [changed](Self::changed) will not return immediately until the value changes
/// after this method returns.
///
/// Updates are paused while the read lock is held.
///
/// This method returns an error if the observed hash map has been dropped
/// or the connection to it failed before it was marked as done by calling
/// [ObservableHashMap::done].
/// In this case the mirrored contents at the point of loss of connection
/// can be obtained using [detach](Self::detach).
pub async fn borrow_and_update(&mut self) -> Result<MirroredHashMapRef<'_, K, V>, RecvError> {
let inner = self.inner.read().await;
self.changed_rx.borrow_and_update();
let inner = RwLockReadGuard::map(inner, |inner| inner.as_ref().unwrap());
match &inner.error {
None => Ok(MirroredHashMapRef(inner)),
Some(err) => Err(err.clone()),
}
}
/// Stops updating the hash map and returns its current contents.
pub async fn detach(self) -> HashMap<K, V> {
let mut inner = self.inner.write().await;
inner.take().unwrap().hm
}
/// Waits for a change and marks the newest value as seen.
///
/// This also returns when connection to the observed hash map has been lost
/// or the hash map has been marked as done.
pub async fn changed(&mut self) {
let _ = self.changed_rx.changed().await;
}
/// Subscribes to change events from this mirrored hash map.
///
/// The current contents of the hash map is included with the subscription.
///
/// `buffer` specifies the maximum size of the event buffer for this subscription in number of events.
/// If it is exceeded the subscription is shed and the receiver gets a [RecvError::Lagged].
pub async fn subscribe(&self, buffer: usize) -> Result<HashMapSubscription<K, V, Codec>, RecvError> {
let view = self.borrow().await?;
let initial = view.clone();
let events = if view.is_done() { None } else { Some(self.tx.subscribe(buffer)) };
Ok(HashMapSubscription::new(HashMapInitialValue::new_value(initial), events))
}
/// Subscribes to change events from this mirrored hash map with incremental sending
/// of the current contents.
///
/// The current contents of the hash map are sent incrementally.
///
/// `buffer` specifies the maximum size of the event buffer for this subscription in number of events.
/// If it is exceeded the subscription is shed and the receiver gets a [RecvError::Lagged].
pub async fn subscribe_incremental(
&self, buffer: usize,
) -> Result<HashMapSubscription<K, V, Codec>, RecvError> {
let view = self.borrow().await?;
let initial = view.clone();
let events = if view.is_done() { None } else { Some(self.tx.subscribe(buffer)) };
Ok(HashMapSubscription::new(
HashMapInitialValue::new_incremental(initial, Arc::new(default_on_err)),
events,
))
}
}
impl<K, V, Codec> Drop for MirroredHashMap<K, V, Codec> {
fn drop(&mut self) {
// empty
}
}
/// A snapshot view of an observable hash map.
pub struct MirroredHashMapRef<'a, K, V>(RwLockReadGuard<'a, MirroredHashMapInner<K, V>>);
impl<'a, K, V> MirroredHashMapRef<'a, K, V> {
/// Returns `true` if the initial state of an incremental subscription has
/// been reached.
pub fn is_complete(&self) -> bool {
self.0.complete
}
/// Returns `true` if the observed hash map has been marked as done by calling
/// [ObservableHashMap::done] and thus no further changes can occur.
pub fn is_done(&self) -> bool {
self.0.done
}
}
impl<'a, K, V> fmt::Debug for MirroredHashMapRef<'a, K, V>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.hm.fmt(f)
}
}
impl<'a, K, V> Deref for MirroredHashMapRef<'a, K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.0.hm
}
}
impl<'a, K, V> Drop for MirroredHashMapRef<'a, K, V> {
fn drop(&mut self) {
// required for drop order
}
}