nutex 0.1.3

Nutex stands for NUllable muTEX: mutex that may contain value that doesn't exist.
Documentation
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
#![allow(unreachable_pub, dead_code)]
use std::{
    ops::{Deref, DerefMut},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};
use tokio::sync::{Mutex, MutexGuard, TryLockError};

#[derive(Debug)]
/// A nullable `Mutex`-like type based on [`tokio::sync::Mutex`] implementation.
///
/// [`Nutex`] stands for **NU**llable mu**TEX** and it gives you
/// convenience to work with [`Option`]al values, such as connection that
/// cannot be set at the time when they was created:
/// you no more need to unwrap the value all the time in functions
/// that cannot be accessed without `Mutex<Option<T>>` value defining.
///
/// Note that locking [`Nutex`] requires to be certain that value is not `None`
/// and if you are not sure that function cannot be accessed without value defining
/// use [`Nutex::safe_lock`] or [`Nutex::safe_blocking_lock`] instead.
///
/// Otherwise if value is [`None`], [`Nutex::lock`]ing will lead you to panic.
///
/// ---
///
/// # Usage Examples
///
/// For example, you created an app and you want to access and process
/// the user client data stored in mutex in the some function
/// that may be called only if user is logged in.
///
/// With using the standard Tokio mutex you should unwrap the value
/// all the time:
///
/// ```rust,no_run
/// pub struct AppState {
///     pub client: Mutex<Option<Client>>,
///     // ...
/// }
///
/// #[tauri::command]
/// pub async fn send_message(
///     state: State<'_, AppState>,
///     message: String,
///     to: RecId
/// ) -> Result<(), SendError> {
///     // ? You need to do THIS:
///     state
///         .client
///         .lock()
///         .await
///         .expect("User must be logged in, blah, blah, blah...")
///         .user_id()
///         .expect("User must be logged in, blah blah blah...")
///         .process()
///         .yet_another_process()
///         .et_cetera();
///     // ...
///     Ok(())
/// }
///
/// #[tauri::command]
/// pub async fn register(
///     state: State<'_, AppState>,
///     auth_data: AuthData,
/// ) -> Result<(), ErrorResponse> {
///     // ? And THIS...
///     state.client.lock().await = Some(
///         Client::builder()
///             .register(auth_data)
///             .build()
///             .await?
///             .map_err(/* ... */)?;
///     )
///     // ...
///     Ok(())
/// }
/// ```
///
/// Double checking. Double headache.
/// But `Nutex` gives you this:
///
/// ```rust,no_run
/// pub struct AppState {
///     pub client: Nutex<Client>,
///     // ...
/// }
///
/// #[tauri::command]
/// pub async fn send_message(
///     state: State<'_, AppState>,
///     message: String,
///     to: RecId
/// ) -> Result<(), SendError> {
///     state
///         .client
///         .lock()
///         .await
///         .user_id()
///         .expect("User must be logged in, blah blah blah...")
///         .process();
///     // ...
///     Ok(())
/// }
///
/// #[tauri::command]
/// pub async fn register(
///     state: State<'_, AppState>,
///     auth_data: AuthData,
/// ) -> Result<(), ErrorResponse> {
///     state.client.set(
///         Client::builder()
///             .register(auth_data)
///             .build()
///             .await?
///             .map_err(/* ... */)?;
///             // ...
///     ).await;
///
///     Ok(())
/// }
/// ```
///
/// It simplifies the code a lot because `Mutex`es frequently
/// used with values that cannot be known at the time when
/// they are created.
///
/// # Examples
///
/// If you certainly know that value is not [`None`], then you
/// can just lock the [`Nutex`] and access the value:
/// ```rust,no_run
/// let nutex = Nutex::from(String::from("foo"));
/// *nutex.lock().await = String::from("bar");
/// assert_eq!(String::from("bar"), *nutex.lock().await);
/// ```
///
/// But if you're not sure that it's not [`None`], prefer using [`Nutex::safe_lock`]:
/// ```rust,no_run
/// if let Some(mut guard) = nutex.safe_lock().await {
///     *guard = String::from("foo");
/// }
/// ```
///
/// ---
///
/// Other documentation about [`Nutex`] may be found in the [`tokio::sync::Mutex`] docs:
/// [`Nutex`] is just a wrapper for this anyway.
/// ```
pub struct Nutex<T: Sized> {
    mutex: Mutex<Option<T>>,
    is_some: Arc<AtomicBool>,
}

#[derive(Debug)]
/// A custom handle that holds `Nutex` and contains `MutexGuard` of original Tokio `Mutex`.
/// The guard can be held across any `.await` point as it is [`Send`] thanks to the
/// original Tokio `MutexGuard` and `Mutex`.
///
/// As long as you have this guard, you have exclusive access to the underlying
/// `T`. The guard internally borrows the `Nutex`, so it guarantees that
/// [`Nutex`] reference won't be dropped early.
///
/// [`Nutex`] will unlock automatically when guard drop.
#[clippy::has_significant_drop]
#[must_use = "if unused the Nutex will immediately unlock"]
pub struct NutexGuard<'a, T: Sized> {
    lock: &'a Nutex<T>,
    guard: MutexGuard<'a, Option<T>>,
}

impl<'a, T: Sized> Nutex<T> {
    /// Creates a new `Nutex` that contains `None`.
    /// Value may be set later by [`Nutex::set`] or
    /// dereferencing [`Nutex::safe_lock`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Asynchronously gets the value snapshot.
    /// Because of result value is clone and not the immutable reference,
    /// it's not reactive and cannot be observed later.
    ///
    /// ---
    ///
    /// # Panics
    ///
    /// * Panics if [`Nutex`] value is not set.
    /// If you are not sure that calling function cannot be called without
    /// setting the value, use [`Nutex::safe_get`] instead.
    pub async fn get(&self) -> T
    where
        T: Clone + Sized,
    {
        self.lock().await.clone()
    }

    /// Same as [`Nutex::get`], but blocks the code execution until value is get.
    pub fn blocking_get(&self) -> T
    where
        T: Clone + Sized,
    {
        self.blocking_lock().clone()
    }

    /// "Safe" edition of the original [`Nutex::get`] method.
    ///
    /// Note that "safe" doesn't mean that original
    /// method usage is discouraged: this method may be used
    /// if you are not sure that value exist.
    ///
    /// Although if more than half of your code contains this method,
    /// think about the original [`tokio::sync::Mutex`] instead of [`Nutex`].
    pub async fn safe_get(&self) -> Option<T>
    where
        T: Clone + Sized,
    {
        self.safe_lock().await.map(|g| g.clone())
    }

    /// Same as [`Nutex::safe_get`], but blocks the code execution until value is get.
    pub fn safe_blocking_get(&self) -> Option<T>
    where
        T: Clone + Sized,
    {
        self.safe_blocking_lock().map(|g| g.clone())
    }

    /// Sets the value in the [`Nutex`], replacing inner [`None`]
    /// to the `Some(value)`.
    ///
    /// Note that this method does nothing if value is already set:
    /// if you need to mutate the value that `Nutex` contains,
    /// use [`Nutex::lock`] or [`Nutex::blocking_lock`] instead.
    pub async fn set(&self, val: T) {
        if self.is_some.load(Ordering::Relaxed) {
            *self.mutex.lock().await = Some(val);
            self.is_some.swap(true, Ordering::Relaxed);
        }
    }

    /// Same as [`Nutex::set`], but blocks the code execution until value is set.
    pub fn blocking_set(&self, val: T) {
        if self.is_some.load(Ordering::Relaxed) {
            *self.mutex.blocking_lock() = Some(val);
            self.is_some.swap(true, Ordering::Relaxed);
        }
    }

    /// Sets inner value of the `Nutex` as `None`.
    pub async fn clear(&self) {
        *self.mutex.lock().await = None;
    }

    /// Same as [`Nutex::clear`], but blocks the code execution until value is cleared.
    pub fn blocking_clear(&self) {
        *self.mutex.blocking_lock() = None;
    }

    fn guard(&'a self, guard: MutexGuard<'a, Option<T>>) -> NutexGuard<'a, T> {
        if self.is_some.load(Ordering::Relaxed) {
            NutexGuard {
                lock: self,
                guard: guard,
            }
        } else {
            panic!(
                "Accessed inner Nutex value that's `None`.
                If you're not sure that value is certainly set,
                prefer using `.safe_lock()` or `.safe_blocking_lock()` methods instead."
            )
        }
    }

    fn guard_expect(&'a self, guard: MutexGuard<'a, Option<T>>, msg: &str) -> NutexGuard<'a, T> {
        if self.is_some.load(Ordering::Relaxed) {
            NutexGuard {
                lock: self,
                guard: guard,
            }
        } else {
            panic!("{}", msg)
        }
    }

    fn safe_guard(&'a self, guard: MutexGuard<'a, Option<T>>) -> Option<NutexGuard<'a, T>> {
        if self.is_some.load(Ordering::Relaxed) {
            Some(NutexGuard {
                lock: self,
                guard: guard,
            })
        } else {
            None
        }
    }

    /// Locks this [`Nutex`], causing the current task to yield until the lock has
    /// been acquired.  When the lock has been acquired, function returns a
    /// [`NutexGuard`].
    ///
    /// If the `Nutex` is available to be acquired immediately, then this call
    /// will typically not yield to the runtime. However, this is not guaranteed
    /// under all circumstances.
    ///
    /// ---
    ///
    /// # Panics
    /// * Panics if [`Nutex`] value is not set.
    /// If you are not sure that calling function cannot be called without
    /// setting the value, use [`Nutex::safe_lock`] instead.
    pub async fn lock(&'a self) -> NutexGuard<'a, T> {
        self.guard(self.mutex.lock().await)
    }

    /// Same as [`Nutex::lock`], but if value is not set, it panics with a custom message.
    ///
    /// Useful if panic impossibility reason is opaque and you should explain
    /// why panic is impossible.
    pub async fn lock_expect(&'a self, msg: &str) -> NutexGuard<'a, T> {
        self.guard_expect(self.mutex.lock().await, msg)
    }

    /// Same as [`Nutex::lock`], but blocks the code execution until `Nutex` is locked.
    pub fn blocking_lock(&'a self) -> NutexGuard<'a, T> {
        self.guard(self.mutex.blocking_lock())
    }

    /// Same as [`Nutex::lock_expect`], but blocks the code execution until `Nutex` is locked.
    pub fn blocking_lock_expect(&'a self, msg: &str) -> NutexGuard<'a, T> {
        self.guard_expect(self.mutex.blocking_lock(), msg)
    }

    /// "Safe" edition of the original [`Nutex::lock`] method.
    ///
    /// Note that "safe" doesn't mean that original
    /// method usage is discouraged: this method may be used
    /// if you are not sure that value exist.
    ///
    /// Although if more than half of your code contains this method,
    /// think about the original [`tokio::sync::Mutex`] instead of `Nutex`.
    pub async fn safe_lock(&'a self) -> Option<NutexGuard<'a, T>> {
        self.safe_guard(self.mutex.lock().await)
    }

    /// Same as [`Nutex::safe_lock`], but blocks the code execution until `Nutex` is locked.
    pub fn safe_blocking_lock(&'a self) -> Option<NutexGuard<'a, T>> {
        self.safe_guard(self.mutex.blocking_lock())
    }

    /// Synchronous function to lock [`Nutex`].
    ///
    /// Returns [`tokio::sync::mutex::TryLockError`] if [`Nutex`]
    /// is locked currently.
    pub fn try_lock(&'a self) -> Result<NutexGuard<'a, T>, TryLockError> {
        self.mutex.try_lock().map(|g| self.guard(g))
    }

    /// Locks the [`Nutex`] and transforms the type inside to other.
    ///
    /// This method is **lazily evaluated** that means closure won't be executed
    /// if [`Nutex`] contains [`None`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// let nutex = Nutex::from(String::from("foo"));
    ///
    /// nutex.lock_then(async |mut g| {
    ///     assert_eq!(String::from("foo"), *g);
    ///     *g = String::from("bar");
    ///     assert_eq!(String::from("bar"), *g);
    /// });
    /// ```
    pub async fn lock_then<U, F: AsyncFnOnce(NutexGuard<'a, T>) -> U>(&'a self, f: F) -> Option<U> {
        if self.is_some() {
            Some(f(self.guard(self.mutex.lock().await)).await)
        } else {
            None
        }
    }

    /// Same as [`Nutex::lock_then`], but if closure should be executed
    /// it'll block the code execution until its evaluation is done.
    ///
    /// This method is also **lazily evaluated** that means closure won't be executed
    /// if [`Nutex`] contains [`None`].
    pub fn blocking_lock_then<U, F: FnOnce(NutexGuard<'a, T>) -> U>(&'a self, f: F) -> Option<U> {
        if self.is_some() {
            // SAFETY: Race condition is impossible because
            // this function is synchronous and blocks the code execution.
            Some(f(self.guard(self.mutex.blocking_lock())))
        } else {
            None
        }
    }

    /// Atomic checker that inner value is not [`None`].
    ///
    /// Note that this method shouldn't be used to check
    /// that [`Nutex`] should be locked because it's
    /// not asynchronous that means that you may face
    /// to the race condition.
    ///
    /// Consider using [`Nutex::safe_lock`] or [`Nutex::safe_blocking_lock`]
    /// with `if let Some(val)` statement, or
    /// [`Nutex::lock_then`]/[`Nutex::blocking_lock_then`]
    /// to evaluate the statement lazily.
    pub fn is_some(&self) -> bool {
        self.is_some.load(Ordering::Relaxed)
    }

    /// Atomic checker that inner value is [`None`].
    pub fn is_none(&self) -> bool {
        !self.is_some.load(Ordering::Relaxed)
    }

    /// Consumes the [`Nutex`], returning the underlying data.
    pub fn into_inner(self) -> Option<T> {
        self.mutex.into_inner()
    }
}

impl<T: Sized> Default for Nutex<T> {
    /// Creates default value of [`Nutex`].
    /// Shorthand of this expression is [`Nutex::new`].
    ///
    /// Inner value of [`Nutex`] is [`None`] by default.
    fn default() -> Self {
        Self {
            mutex: Mutex::new(None),
            is_some: Arc::new(AtomicBool::new(false)),
        }
    }
}

impl<T: Sized> From<T> for Nutex<T> {
    /// Creates [`Nutex`] with the inner value from the argument.
    fn from(value: T) -> Self {
        Self {
            mutex: Mutex::new(Some(value)),
            is_some: Arc::new(AtomicBool::new(true)),
        }
    }
}

impl<'a, T: Sized> NutexGuard<'a, T> {
    /// Returns a reference to the inner [`Nutex`] that lives
    /// the same time as the guard.
    pub fn nutex(&self) -> &'a Nutex<T> {
        self.lock
    }
}

impl<'a, T: Sized> Deref for NutexGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &'a Self::Target {
        match &*self.guard {
            // SAFETY: Man what the fuck it's just a lifetime annotation
            Some(val) => unsafe { std::mem::transmute::<&T, &'a T>(val) },
            None => unreachable!("MutexGuard can be accessed only if value exist"),
        }
    }
}

impl<'a, T: Sized> DerefMut for NutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &'a mut Self::Target {
        match &mut *self.guard {
            // SAFETY: Man what the fuck it's just a lifetime annotation
            Some(val) => unsafe { std::mem::transmute::<&mut T, &'a mut T>(val) },
            None => unreachable!("MutexGuard can be accessed only if value exist"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn access_test() {
        let nutex = Nutex::from(String::from("foo"));
        assert_eq!(String::from("foo"), *nutex.blocking_lock())
    }

    #[test]
    fn mutation_test() {
        let nutex: Nutex<String> = Nutex::new();
        nutex.blocking_set(String::from("bar"));
        assert_eq!(String::from("bar"), *nutex.blocking_lock())
    }

    #[test]
    fn clear_test() {
        let nutex: Nutex<String> = Nutex::new();
        nutex.blocking_set(String::from("bar"));
        assert_eq!(String::from("bar"), *nutex.blocking_lock());
        nutex.blocking_clear();
        assert!(nutex.safe_blocking_lock().is_none());
    }

    #[test]
    fn closure_test() {
        let nutex = Nutex::from(String::from("foo"));

        nutex.blocking_lock_then(|mut g| {
            println!("{}", *g);
            assert_eq!(String::from("foo"), *g);

            *g = String::from("bar");
            println!("{}", *g);
            assert_eq!(String::from("bar"), *g);
        });

        let none_nutex: Nutex<u8> = Nutex::new();
        none_nutex.blocking_lock_then(|g| {
            println!("{}", *g);
        });
    }
}