daily pastebin goal
72%
SHARE
TWEET

Untitled

a guest Dec 25th, 2018 15 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
  2. From: belovedeagle <>
  3. Date: Tue, 25 Dec 2018 06:59:17 +0000
  4. Subject: [PATCH 1/2] Remove two unnecessary Arc layers.
  5. MIME-Version: 1.0
  6. Content-Type: multipart/mixed; boundary="------------QCH+vwZuai4vjjjitHhzi13H"
  7.  
  8. This is a multi-part message in MIME format.
  9. --------------QCH+vwZuai4vjjjitHhzi13H
  10. Content-Type: text/plain; charset=UTF-8; format=fixed
  11. Content-Transfer-Encoding: 8bit
  12.  
  13.  
  14. Holy Arc, Batman!
  15. ---
  16.  src/lib.rs | 36 +++++++++++++++++++++++++-----------
  17.  1 file changed, 25 insertions(+), 11 deletions(-)
  18.  
  19.  
  20. --------------QCH+vwZuai4vjjjitHhzi13H
  21. Content-Type: text/x-patch; name="0001-Remove-two-unnecessary-Arc-layers.patch"
  22. Content-Transfer-Encoding: 8bit
  23. Content-Disposition: attachment; filename="0001-Remove-two-unnecessary-Arc-layers.patch"
  24.  
  25. diff --git a/src/lib.rs b/src/lib.rs
  26. index 658e955..2d9a128 100644
  27. --- a/src/lib.rs
  28. +++ b/src/lib.rs
  29. @@ -173,7 +173,6 @@ mod id_map {
  30.      use std::sync::atomic::ATOMIC_USIZE_INIT;
  31.      use std::sync::atomic::Ordering as AtomicOrdering;
  32.      use std::sync::Mutex;
  33. -    use std::sync::Arc;
  34.      use super::Event;
  35.      use super::Handlers;
  36.      lazy_static! {
  37. @@ -187,8 +186,8 @@ mod id_map {
  38.      pub fn get_event_id<T: Event + ?Sized>() -> usize {
  39.          static EVENT_ID_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
  40.          EVENT_ID_MAP.lock().expect("failed to allocate event id").entry::<EventId<T>>().or_insert_with(|| {
  41. -            let handlers: Arc<Handlers<T>> = Default::default();
  42. -            Arc::make_mut(&mut super::HANDLERS.write().expect("???")).push(handlers);
  43. +            let handlers: Box<Handlers<T>> = Default::default();
  44. +            super::HANDLERS.write().expect("???").push(handlers);
  45.              EventId { id: EVENT_ID_COUNT.fetch_add(1, AtomicOrdering::SeqCst), _t: PhantomData }
  46.          }).id
  47.      }
  48. @@ -212,7 +211,21 @@ impl<T: Event + ?Sized> Default for Handlers<T> {
  49.  }
  50.  
  51.  lazy_static! {
  52. -    static ref HANDLERS: RwArcVec<Arc<dyn Any + Send + Sync>> = Default::default();
  53. +    static ref HANDLERS: RwLock<Vec<Box<dyn Any + Send + Sync>>> = Default::default();
  54. +}
  55. +
  56. +/// FIXFIX: Does a thing, need to explain it (although this function isn't pub).
  57. +///
  58. +/// # Panics
  59. +///
  60. +/// Panics if `id` doesn't match the given `T` (but not if the given `id` doesn't exist).
  61. +fn with_handlers<T: Event + ?Sized, R, F: FnOnce(&Handlers<T>) -> R>(id: usize, f: F) -> Option<R> {
  62. +    HANDLERS.read().expect("failed to lock for reading").get(id).map(|any| {
  63. +        // normally one doesn't need to use deref explicitly,
  64. +        // but here even the &* pattern won't work due to the inferred type being "Any"
  65. +        let box_contents = std::ops::Deref::deref(any);
  66. +        f(Any::downcast_ref(box_contents).expect("Wrong id"))
  67. +    })
  68.  }
  69.  
  70.  /// Low-level event handling function,  returns the handlers that should be called to post the
  71. @@ -224,10 +237,11 @@ lazy_static! {
  72.  ///
  73.  /// Panics if `id` doesn't match the given `T` (but not if the given `id` doesn't exist).
  74.  pub fn get_post_targets<T: Event + ?Sized>(bus: &EventBus, _event: &mut T, id: usize) -> Arc<Vec<(i32, Arc<dyn Fn(&mut T) + Send + Sync>)>> {
  75. -    let target: Option<Arc<Vec<_>>> = HANDLERS.read().expect("failed to lock for reading").get(id).map(|arc| Arc::clone(arc))
  76. -        .map(|any| Arc::downcast::<Handlers<T>>(any).expect("Wrong id"))
  77. -        .and_then(|handlers| handlers.0.read().expect("failed to lock for reading").get(bus.id).map(|hooks| Arc::clone(&*hooks.read().expect("failed to lock for reading"))));
  78. -    target.unwrap_or_else(|| Arc::new(Vec::new()))
  79. +    with_handlers(id, |handlers| {
  80. +        handlers.0.read().expect("failed to lock for reading").get(bus.id).map(|hooks| Arc::clone(&*hooks.read().expect("failed to lock for reading")))
  81. +    })
  82. +    .and_then(|x| x)
  83. +    .unwrap_or_else(|| Arc::new(Vec::new()))
  84.  }
  85.  
  86.  /// Low-level event handling function, registers an event.
  87. @@ -239,9 +253,9 @@ pub fn get_post_targets<T: Event + ?Sized>(bus: &EventBus, _event: &mut T, id: u
  88.  ///
  89.  /// Panics if `id` doesn't match the given `T`, or if `id` doesn't exist.
  90.  pub fn register<T: Event + ?Sized, F: for<'a> Fn(&'a mut T) + Send + Sync + 'static>(bus: &EventBus, priority: i32, handler: F, id: usize) {
  91. -    HANDLERS.read().expect("failed to lock for reading").get(id).map(|arc| Arc::clone(arc))
  92. -        .map(|any| Arc::downcast::<Handlers<T>>(any).expect("Wrong id"))
  93. -        .map(|handlers| {
  94. +    // FIXFIX: bad formatting to simplify diff
  95. +    let () =
  96. +        with_handlers(id, |handlers| {
  97.             let mut lock = handlers.0.read().expect("failed to lock for reading");
  98.             if lock.len() <= id {
  99.                 mem::drop(lock);
  100.  
  101. --------------QCH+vwZuai4vjjjitHhzi13H--
  102.  
  103.  
  104.  
  105. From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
  106. From: belovedeagle <>
  107. Date: Tue, 25 Dec 2018 06:59:46 +0000
  108. Subject: [PATCH 2/2] Fix indenting.
  109. MIME-Version: 1.0
  110. Content-Type: multipart/mixed; boundary="------------QCH+vwZuai4vjjjitHhzi13H"
  111.  
  112. This is a multi-part message in MIME format.
  113. --------------QCH+vwZuai4vjjjitHhzi13H
  114. Content-Type: text/plain; charset=UTF-8; format=fixed
  115. Content-Transfer-Encoding: 8bit
  116.  
  117. ---
  118. src/lib.rs | 54 ++++++++++++++++++++++++++----------------------------
  119. 1 file changed, 26 insertions(+), 28 deletions(-)
  120.  
  121.  
  122. --------------QCH+vwZuai4vjjjitHhzi13H
  123. Content-Type: text/x-patch; name="0002-Fix-indenting.patch"
  124. Content-Transfer-Encoding: 8bit
  125. Content-Disposition: attachment; filename="0002-Fix-indenting.patch"
  126.  
  127. diff --git a/src/lib.rs b/src/lib.rs
  128. index 2d9a128..0ca2ef9 100644
  129. --- a/src/lib.rs
  130. +++ b/src/lib.rs
  131. @@ -253,36 +253,34 @@ pub fn get_post_targets<T: Event + ?Sized>(bus: &EventBus, _event: &mut T, id: u
  132. ///
  133. /// Panics if `id` doesn't match the given `T`, or if `id` doesn't exist.
  134. pub fn register<T: Event + ?Sized, F: for<'a> Fn(&'a mut T) + Send + Sync + 'static>(bus: &EventBus, priority: i32, handler: F, id: usize) {
  135. -    // FIXFIX: bad formatting to simplify diff
  136. -    let () =
  137. -        with_handlers(id, |handlers| {
  138. -            let mut lock = handlers.0.read().expect("failed to lock for reading");
  139. -            if lock.len() <= id {
  140. -                mem::drop(lock);
  141. -                let mut wlock = handlers.0.write().expect("failed to lock for writing");
  142. -                if wlock.len() <= id { // another thread may have touched this
  143. -                    let vec = Arc::get_mut(&mut wlock).expect("failed to mutate busses");
  144. -                    let count = id - vec.len() + 1;
  145. -                    vec.reserve_exact(count);
  146. -                    for _ in 0..count {
  147. -                        vec.push(Default::default());
  148. -                    }
  149. +    let () = with_handlers(id, |handlers| {
  150. +        let mut lock = handlers.0.read().expect("failed to lock for reading");
  151. +        if lock.len() <= id {
  152. +            mem::drop(lock);
  153. +            let mut wlock = handlers.0.write().expect("failed to lock for writing");
  154. +            if wlock.len() <= id { // another thread may have touched this
  155. +                let vec = Arc::get_mut(&mut wlock).expect("failed to mutate busses");
  156. +                let count = id - vec.len() + 1;
  157. +                vec.reserve_exact(count);
  158. +                for _ in 0..count {
  159. +                    vec.push(Default::default());
  160.                  }
  161. -                // there's no way to downgrade a write lock, but as long as we never shrink the
  162. -                // vecs it should be fine.
  163. -                mem::drop(wlock);
  164. -                lock = handlers.0.read().expect("failed to lock for reading");
  165.              }
  166. -            let option = lock.get(bus.id);
  167. -            // last RwLock
  168. -            let hooks = option.expect("failed to make vecs");
  169. -            let hook: (i32, Arc<dyn Fn(&mut T) + Send + Sync + 'static>) = (priority, Arc::new(handler));
  170. -            let mut wlock = hooks.write().expect("failed to lock for writing");
  171. -            let vec = Arc::make_mut(&mut wlock);
  172. -            // would be nice if Result had a .coalesce()
  173. -            let pos = match vec.binary_search_by(|probe| probe.0.cmp(&priority)) { Ok(p) => p, Err(p) => p };
  174. -            vec.insert(pos, hook);
  175. -        }).expect("No such id");
  176. +            // there's no way to downgrade a write lock, but as long as we never shrink the
  177. +            // vecs it should be fine.
  178. +            mem::drop(wlock);
  179. +            lock = handlers.0.read().expect("failed to lock for reading");
  180. +        }
  181. +        let option = lock.get(bus.id);
  182. +        // last RwLock
  183. +        let hooks = option.expect("failed to make vecs");
  184. +        let hook: (i32, Arc<dyn Fn(&mut T) + Send + Sync + 'static>) = (priority, Arc::new(handler));
  185. +        let mut wlock = hooks.write().expect("failed to lock for writing");
  186. +        let vec = Arc::make_mut(&mut wlock);
  187. +        // would be nice if Result had a .coalesce()
  188. +        let pos = match vec.binary_search_by(|probe| probe.0.cmp(&priority)) { Ok(p) => p, Err(p) => p };
  189. +        vec.insert(pos, hook);
  190. +    }).expect("No such id");
  191. }
  192.  
  193. static BUS_ID: AtomicUsize = ATOMIC_USIZE_INIT;
  194.  
  195. --------------QCH+vwZuai4vjjjitHhzi13H--
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top