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
use ;
/// Attempts to get a mutable reference to the inner data of an Rc.
///
/// If the Rc has a strong count of 1 and a weak count of 0, it returns
/// the mutable reference directly.
///
/// If the Rc has a strong count greater than 1, it returns None.
///
/// If the Rc has a strong count of 1 and a weak count greater than 0,
/// it attempts to replace the Rc instance with a new one containing the
/// same data, effectively invalidating all existing weak pointers. This
/// involves an internal allocation for the new Rc instance. If this
/// allocation fails, the function will panic (before modifying the input Rc).
///
/// Returns Ok(&mut T) on success, or Err(&mut Rc<T>) if the strong count was
/// greater than 1.
///
/// The Err variant is useful for the caller to avoid borrow-checker issues
/// due to rust's lack of non-lexical lifetimes. That is, if the caller
/// only has a mutable reference to the Rc, they may not be able to reborrow
/// it when calling this function if they want to return a mutable reference
/// to the inner data. Thus, if the function fails, they may have "lost" the
/// only reference they had. The Err variant gives it back so they can try
/// something else.
///
/// (See https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-2-conditional-control-flow)
//
// # Safety Notes
// This function uses unsafe code internally to handle the Rc replacement
// while aiming to be panic-safe *after* the initial allocation check.
// It relies on ptr::read/write and careful state management.
/// Use [`Rc::get_mut_unchecked`] when stable.
///
/// ```compile_fail
/// use std::sync::Rc;
/// let mut a = Rc::new(0usize);
/// let b = unsafe { Rc::get_mut_unchecked(&mut a) };
/// *b += 1;
/// ```
unsafe