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
use std::{cell::RefCell, rc::Rc, task::Poll};

use crate::utils::{
    debug_pointer::{
        DebugHigherKindFnPointerRefMut, DebugHigherKindFnPointerRefOutput, DebugPointerType,
    },
    RcStatus,
};

#[derive(Debug)]
pub enum NewState<'a, T> {
    Value(T),
    Fn(NewStateFn<'a, T>),
}

pub type NewStateDynReplacer<'a, T> = dyn 'a + FnOnce(&T) -> T;
pub type NewStateDynReplacerMaybe<'a, T> = dyn 'a + FnOnce(&T) -> Option<T>;
pub type NewStateDynMutator<'a, T> = dyn 'a + FnOnce(&mut T);

pub enum NewStateFn<'a, T> {
    ReplacerBox(Box<NewStateDynReplacer<'a, T>>),
    ReplacerFnPointer(fn(&T) -> T),
    ReplacerMaybeBox(Box<NewStateDynReplacerMaybe<'a, T>>),
    ReplacerMaybeFnPointer(fn(&T) -> Option<T>),
    MutatorBox(Box<NewStateDynMutator<'a, T>>),
    MutatorFnPointer(fn(&mut T)),
}

impl<'a, T> From<fn(&T) -> T> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: fn(&T) -> T) -> Self {
        Self::ReplacerFnPointer(v)
    }
}

impl<'a, T> From<Box<dyn 'a + FnOnce(&T) -> T>> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: Box<dyn 'a + FnOnce(&T) -> T>) -> Self {
        Self::ReplacerBox(v)
    }
}

impl<'a, T> From<fn(&T) -> Option<T>> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: fn(&T) -> Option<T>) -> Self {
        Self::ReplacerMaybeFnPointer(v)
    }
}

impl<'a, T> From<Box<dyn 'a + FnOnce(&T) -> Option<T>>> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: Box<dyn 'a + FnOnce(&T) -> Option<T>>) -> Self {
        Self::ReplacerMaybeBox(v)
    }
}

impl<'a, T> From<fn(&mut T)> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: fn(&mut T)) -> Self {
        Self::MutatorFnPointer(v)
    }
}

impl<'a, T> From<Box<dyn 'a + FnOnce(&mut T)>> for NewStateFn<'a, T> {
    #[inline]
    fn from(v: Box<dyn 'a + FnOnce(&mut T)>) -> Self {
        Self::MutatorBox(v)
    }
}

impl<'a, T: std::fmt::Debug> std::fmt::Debug for NewStateFn<'a, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ReplacerBox(arg0) => f
                .debug_tuple("ByReplacerBox")
                .field(&DebugPointerType::<Box<dyn 'a + FnOnce(&T) -> T>>(arg0))
                .finish(),
            Self::ReplacerFnPointer(arg0) => f
                .debug_tuple("ByReplacerFnPointer")
                .field(&DebugHigherKindFnPointerRefOutput(arg0))
                .finish(),
            Self::ReplacerMaybeBox(arg0) => f
                .debug_tuple("ReplacerMaybeBox")
                .field(&DebugPointerType(arg0))
                .finish(),
            Self::ReplacerMaybeFnPointer(arg0) => f
                .debug_tuple("ReplacerMaybeFnPointer")
                .field(&DebugHigherKindFnPointerRefOutput(arg0))
                .finish(),
            Self::MutatorBox(arg0) => f
                .debug_tuple("ByMutatorBox")
                .field(&DebugPointerType::<Box<dyn 'a + FnOnce(&mut T)>>(arg0))
                .finish(),
            Self::MutatorFnPointer(arg0) => f
                .debug_tuple("ByMutatorFnPointer")
                .field(&DebugHigherKindFnPointerRefMut(arg0))
                .finish(),
        }
    }
}

pub const STAGING_STATES_DEFAULT_STACK_COUNT: usize = 3;

#[derive(Default, Debug)]
pub struct StagingStates<'a, T, const N: usize = STAGING_STATES_DEFAULT_STACK_COUNT> {
    new_state: Option<T>,
    fns: smallvec::SmallVec<[NewStateFn<'a, T>; N]>,
}

impl<'a, T, const N: usize> StagingStates<'a, T, N> {
    #[inline]
    pub fn new() -> Self {
        Self {
            new_state: None,
            fns: smallvec::SmallVec::new(),
        }
    }

    /// Return `compare(&old_value, &new_value)`.
    pub fn drain_into_and_compare(
        &mut self,
        state: &mut T,
        mut compare: impl FnMut(&T, &T) -> bool,
    ) -> bool {
        if let Some(mut new_state) = self.new_state.take() {
            self.drain_fns_into(&mut new_state);

            let is_equal = compare(&*state, &new_state);

            *state = new_state;

            is_equal
        } else {
            let drain = self.fns.drain(..);

            let mut mutated = false;

            let mut last_state: Option<T> = None;

            for new_state in drain {
                match new_state {
                    NewStateFn::ReplacerBox(f) => {
                        if let Some(last_state) = &mut last_state {
                            *last_state = f(&*last_state)
                        } else {
                            last_state = Some(f(&*state))
                        }
                    }
                    NewStateFn::ReplacerFnPointer(f) => {
                        if let Some(last_state) = &mut last_state {
                            *last_state = f(&*last_state)
                        } else {
                            last_state = Some(f(&*state))
                        }
                    }
                    NewStateFn::ReplacerMaybeBox(f) => {
                        if let Some(last_state) = &mut last_state {
                            if let Some(new_state) = f(&*last_state) {
                                *last_state = new_state;
                            }
                        } else {
                            last_state = f(&*state)
                        }
                    }
                    NewStateFn::ReplacerMaybeFnPointer(f) => {
                        if let Some(last_state) = &mut last_state {
                            if let Some(new_state) = f(&*last_state) {
                                *last_state = new_state;
                            }
                        } else {
                            last_state = f(&*state)
                        }
                    }
                    NewStateFn::MutatorFnPointer(f) => {
                        if let Some(last_state) = &mut last_state {
                            f(last_state)
                        } else {
                            mutated = true;
                            f(state)
                        }
                    }
                    NewStateFn::MutatorBox(f) => {
                        if let Some(last_state) = &mut last_state {
                            f(last_state)
                        } else {
                            mutated = true;
                            f(state)
                        }
                    }
                }
            }

            if let Some(last_state) = last_state {
                let is_equal = !mutated && compare(&*state, &last_state);
                *state = last_state;
                is_equal
            } else {
                !mutated
            }
        }
    }

    /// Returning `true` indicates there are no new states.
    #[inline]
    pub fn drain_into(&mut self, state: &mut T) -> bool {
        if self.is_empty() {
            return true;
        }

        let mut is_equal = true;

        if let Some(new_state) = self.new_state.take() {
            *state = new_state;
            is_equal = false;
        }

        self.drain_fns_into(state) && is_equal
    }

    /// Returning `true` indicates there are no new states.
    fn drain_fns_into(&mut self, state: &mut T) -> bool {
        if self.fns.is_empty() {
            return true;
        }

        let mut is_equal = true;

        let drain = self.fns.drain(..);
        for a in drain {
            match a {
                NewStateFn::ReplacerBox(f) => {
                    *state = f(state);
                    is_equal = false;
                }
                NewStateFn::ReplacerFnPointer(f) => {
                    *state = f(state);
                    is_equal = false;
                }
                NewStateFn::ReplacerMaybeBox(f) => {
                    if let Some(new_state) = f(state) {
                        *state = new_state;
                        is_equal = false;
                    }
                }
                NewStateFn::ReplacerMaybeFnPointer(f) => {
                    if let Some(new_state) = f(state) {
                        *state = new_state;
                        is_equal = false;
                    }
                }
                NewStateFn::MutatorFnPointer(f) => {
                    f(state);
                    is_equal = false;
                }
                NewStateFn::MutatorBox(f) => {
                    f(state);
                    is_equal = false;
                }
            }
        }

        is_equal
    }

    pub fn push(&mut self, new_state: NewState<'a, T>) {
        match new_state {
            NewState::Value(new_state) => {
                self.fns.truncate(0);
                self.new_state = Some(new_state);
            }
            NewState::Fn(f) => self.fns.push(f),
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.new_state.is_none() && self.fns.is_empty()
    }
}

#[derive(Debug)]
pub struct StateUpdater<'a, T, const N: usize = STAGING_STATES_DEFAULT_STACK_COUNT> {
    waker_and_staging_states: Rc<RefCell<(Option<std::task::Waker>, StagingStates<'a, T, N>)>>,
}

impl<'a, T, const N: usize> PartialEq for StateUpdater<'a, T, N> {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(
            &self.waker_and_staging_states,
            &other.waker_and_staging_states,
        )
    }
}

impl<'a, T, const N: usize> Clone for StateUpdater<'a, T, N> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            waker_and_staging_states: self.waker_and_staging_states.clone(),
        }
    }
}

impl<'a, T, const N: usize> Default for StateUpdater<'a, T, N> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, T, const N: usize> StateUpdater<'a, T, N> {
    #[inline]
    pub fn new() -> Self {
        Self {
            waker_and_staging_states: Rc::new(RefCell::new((None, StagingStates::new()))),
        }
    }

    pub fn update_by(&self, new_state: NewState<'a, T>) {
        let mut waker_and_staging_states = self.waker_and_staging_states.borrow_mut();
        waker_and_staging_states.1.push(new_state);

        if let Some(waker) = waker_and_staging_states.0.take() {
            waker.wake();
        }
    }

    #[inline]
    pub fn set(&self, new_state: T) {
        self.update_by(NewState::Value(new_state))
    }

    #[inline]
    pub fn update_by_fn(&self, f: impl Into<NewStateFn<'a, T>>) {
        self.update_by(NewState::Fn(f.into()))
    }

    #[inline]
    pub fn replace_with_fn_box(&self, f: impl 'a + FnOnce(&T) -> T) {
        self.update_by(NewState::Fn(NewStateFn::ReplacerBox(Box::new(f))))
    }

    #[inline]
    pub fn replace_with_fn_pointer(&self, f: fn(&T) -> T) {
        self.update_by(NewState::Fn(NewStateFn::ReplacerFnPointer(f)))
    }

    #[inline]
    pub fn replace_maybe_with_fn_box(&self, f: impl 'a + FnOnce(&T) -> Option<T>) {
        self.update_by(NewState::Fn(NewStateFn::ReplacerMaybeBox(Box::new(f))))
    }

    #[inline]
    pub fn replace_maybe_with_fn_pointer(&self, f: fn(&T) -> Option<T>) {
        self.update_by(NewState::Fn(NewStateFn::ReplacerMaybeFnPointer(f)))
    }

    #[inline]
    pub fn mutate_with_fn_box(&self, f: impl 'a + FnOnce(&mut T)) {
        self.update_by(NewState::Fn(NewStateFn::MutatorBox(Box::new(f))))
    }

    #[inline]
    pub fn mutate_with_fn_pointer(&self, f: fn(&mut T)) {
        self.update_by(NewState::Fn(NewStateFn::MutatorFnPointer(f)))
    }

    /// The second argument indicates whether `RefCell::borrow_mut` is called.
    /// - [`RcStatus::Shared`] means the `Rc<RefCell<T>>` is shared, causing a runtime `RefCell::borrow_mut`.
    /// - [`RcStatus::Owned`] means there are no other Rc or Weak pointers to the same allocation.
    #[inline]
    pub(crate) fn map_mut<
        R,
        F: FnOnce(&mut (Option<std::task::Waker>, StagingStates<'a, T, N>), RcStatus) -> R,
    >(
        &mut self,
        f: F,
    ) -> R {
        crate::utils::rc_ref_cell_borrow_mut(&mut self.waker_and_staging_states, f)
    }

    /// If `compare` returns true,
    /// which indicates the old and new values are equal,
    /// the polling will keep pending.
    pub fn poll_next_update_if_not_equal(
        &mut self,
        current_state: &mut T,
        compare: impl FnMut(&T, &T) -> bool,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<bool> {
        self.map_mut(|(waker, staging_states), rc_status| {
            if staging_states.is_empty() {
                match rc_status {
                    crate::utils::RcStatus::Shared => {
                        // further updates are possible
                        *waker = Some(cx.waker().clone());
                        Poll::Pending
                    }
                    crate::utils::RcStatus::Owned => {
                        // no further updates
                        Poll::Ready(false)
                    }
                }
            } else {
                let is_equal = staging_states.drain_into_and_compare(current_state, compare);

                if is_equal {
                    Poll::Pending
                } else {
                    Poll::Ready(true)
                }
            }
        })
    }

    pub fn poll_next_update_always_not_equal(
        &mut self,
        current_state: &mut T,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<bool> {
        self.map_mut(|(waker, staging_states), rc_status| {
            let not_changed = staging_states.drain_into(current_state);

            if not_changed {
                match rc_status {
                    crate::utils::RcStatus::Shared => {
                        // further updates are possible
                        *waker = Some(cx.waker().clone());
                        Poll::Pending
                    }
                    crate::utils::RcStatus::Owned => {
                        // no further updates
                        Poll::Ready(false)
                    }
                }
            } else {
                Poll::Ready(true)
            }
        })
    }
}

impl<'a, T, const N: usize> Drop for StateUpdater<'a, T, N> {
    /// When [`StateUpdater`] is dropped,
    /// it will wake up the task to notify
    /// the shared count has changed.
    fn drop(&mut self) {
        let mut waker_and_staging_states = self.waker_and_staging_states.borrow_mut();

        if let Some(waker) = waker_and_staging_states.0.take() {
            waker.wake()
        }
    }
}