SafeManuallyDrop 1.0.3

A safe version of ManuallyDrop with various features and options to track undefined behavior when working with ManuallyDrop.
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

//! AtomicStates for ManuallyDrop

#[cfg(all(test, feature = "support_panic_trig"))]
use crate::core::trig::panic::PanicTrigManuallyDrop;
use core::fmt::Display;
use crate::core::trig::TrigManuallyDrop;
use core::fmt::Debug;
use core::sync::atomic::Ordering;
use core::sync::atomic::AtomicU8;

const READ_ORDERING_METHOD: Ordering = Ordering::SeqCst;
const WRITE_ORDERING_METHOD: Ordering = Ordering::SeqCst; // 

/// Atomic safe states for ManuallyDrop
#[repr(transparent)]
pub struct StateManuallyDrop {
	state: AtomicU8,
}

impl Clone for StateManuallyDrop {
	#[inline]
	fn clone(&self) -> Self {
		Self {
			state: AtomicU8::new(self.__read_byte())
		}
	}
}

impl Debug for StateManuallyDrop {
	#[inline]
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
		f.debug_struct("StateManuallyDrop")
		.field("state", &self.read())
		.finish()
	}
}

impl Display for StateManuallyDrop {
	#[inline(always)]
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
		Display::fmt(&self.read(), f)
	}
}

/// Safe States for ManuallyDrop
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StateManuallyDropData {
	/// It is allowed to convert ManuallyDrop to 
	/// anything without calling a trigger.
	Empty = 1,
	
	/// With the take function, the value is forgotten, subsequent work 
	/// with ManuallyDrop will necessarily call the trigger.
	TakeModeTrig = 5,
	/// With the drop function, the value is released, subsequent work 
	/// with ManuallyDrop will necessarily call the trigger.
	DropModeTrig = 15,
	/// With the into_inner function, the value is cast, subsequent work 
	/// with ManuallyDrop will definitely find the trigger.
	IntoInnerModeTrig = 25,
	
	/// (unsafe/manual_behavior) ManuallyDrop must be forgotten, subsequent work 
	/// with ManuallyDrop will definitely call the trigger.
	IgnoreTrigWhenDrop = 30,
}

impl Display for StateManuallyDropData {
	#[inline]
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
		let str = match self {
			Self::Empty => "Empty",
			
			Self::TakeModeTrig => "TakeModeTrig",
			Self::DropModeTrig => "DropModeTrig",
			Self::IntoInnerModeTrig => "IntoInnerModeTrig",
			
			Self::IgnoreTrigWhenDrop => "IgnoreTrigWhenDrop",
		};
		
		Display::fmt(str, f)
	}
}

impl From<u8> for StateManuallyDropData {
	#[inline(always)]
	fn from(a: u8) -> Self {
		StateManuallyDropData::from_or_empty(a)
	}
}

impl Default for StateManuallyDropData {
	#[inline(always)]
	fn default() -> Self {
		Self::empty()
	}
}

impl StateManuallyDropData {
	/// Convert state to byte
	#[inline(always)]
	pub const fn into(self) -> u8 {
		self as _
	}
	
	/// Create a state from a byte, in case of an error, 
	/// return the default state.
	#[inline]
	pub /*const*/ fn from_or_empty(a: u8) -> Self {
		Self::is_valid_byte_fn(
			a, 
			|| unsafe {
				Self::force_from(a)
			},
			|| Self::empty()
		)
	}
	
	/// Create a state from a byte, return None on error.
	#[inline]
	pub /*const*/ fn from(a: u8) -> Option<Self> {
		Self::is_valid_byte_fn(
			a, 
			|| {
				let sself = unsafe {
					Self::force_from(a)
				};
				
				Some(sself)
			},
			|| None
		)
	}
	
	/// Create default state
	#[inline(always)]
	const fn __empty() -> Self {
		let sself = Self::Empty;
		sself
	}
	
	/// Create default state
	#[inline(always)]
	pub const fn empty() -> Self {
		Self::__empty()
	}
	
	/// Create default state
	#[inline(always)]
	pub const fn no_panic_state() -> Self {
		Self::empty()
	}
	
	/// Generic Status Byte Validation Function
	#[inline(always)]
	pub /*const*/ fn is_valid_byte_fn<R>(a: u8, next: impl FnOnce() -> R, errf: impl FnOnce() -> R) -> R {
		match a {
			a if a == Self::Empty as _ ||
			
				a == Self::TakeModeTrig as _ ||
				a == Self::DropModeTrig as _ ||
				a == Self::IntoInnerModeTrig as _ ||
				
				a == Self::IgnoreTrigWhenDrop as _ => next(),
			_ => errf()
		}
	}
	
	/// General function to check the status byte, 
	/// return false on error, true on success.
	#[inline]
	pub fn is_valid_byte(a: u8) -> bool {
		Self::is_valid_byte_fn(
			a, 
			|| true,
			|| false,
		)
	}
	
	/// Create a state from a byte quickly and without checks 
	/// (important, the byte is checked anyway, but only in a debug build)
	#[inline(always)]
	pub unsafe fn force_from(a: u8) -> Self {
		crate::__fullinternal_debug_assertions!(
			Self::is_valid_byte(a),
			true
		);
		
		Self::__force_form(a)
	}
	
	/// Create a state from a byte quickly and without checks 
	/// (important, the byte is checked anyway, but only in a debug build)
	#[inline(always)]
	const fn __force_form(a: u8) -> Self {
		let result: StateManuallyDropData = unsafe {
			// safe, u8 -> StateManuallyDropData (enum)
			core::mem::transmute(a as u8)
		};
		result
	}
	
	/// Determining if a trigger should be executed
	#[inline(always)]
	pub const fn is_next_trig(&self) -> bool {
		match self {
			StateManuallyDropData::Empty => false,
			_ => true,
		}
	}
	
	/// Whether the current state is like a new unused object.
	#[inline(always)]
	pub const fn is_empty(&self) -> bool {
		match self {
			StateManuallyDropData::Empty => true,
			_ => false,
		}
	}
}

/// Empty state, needed only for some implementations of const functions.
pub const EMPTY_STATE: StateManuallyDrop = StateManuallyDrop::__empty();

impl StateManuallyDrop {
	/// Create default state
	#[inline(always)]
	pub /*const*/ fn empty() -> Self {
		let sself = Self::__empty();
		
		crate::__fullinternal_debug_assertions!(sself.is_empty(), true);
		crate::__fullinternal_debug_assertions!(sself.is_next_trig(), false);
		
		sself
	}
	
	/// Create default state
	#[inline(always)]
	const fn __empty() -> Self {
		Self {
			state: AtomicU8::new(StateManuallyDropData::empty() as _)
		}
	}
	
	/// Whether the current state is like a new unused object.
	#[inline(always)]
	pub fn is_empty(&self) -> bool {
		self.read().is_empty()
	}
	
	/// Getting the status byte of the current ManuallyDrop.
	#[inline(always)]
	fn __read_byte(&self) -> u8 {
		self.state.load(READ_ORDERING_METHOD)
	}
	
	/// Getting the status of the current ManuallyDrop.
	#[inline(always)]
	pub fn read(&self) -> StateManuallyDropData {
		let byte = self.__read_byte();
		unsafe {
			StateManuallyDropData::force_from(byte)
		}
	}
	
	/// Quick substitution of the state of the current ManuallyDrop 
	/// (note that the previous state of ManuallyDrop is returned)
	#[inline(always)]
	fn __force_write(&self, a: StateManuallyDropData) -> StateManuallyDropData {
		let byte = self.state.swap(a as _, WRITE_ORDERING_METHOD);
		unsafe {
			StateManuallyDropData::force_from(byte)
		}
	}
	
	/// Resets the ManuallyDrop state to the initial state
	pub unsafe fn get_and_reset(&self) -> StateManuallyDropData {
		let old_value = self.__force_write(
			StateManuallyDropData::Empty
		);
		crate::__fullinternal_debug_assertions!(self.is_empty(), true);
		crate::__fullinternal_debug_assertions!(self.is_next_trig(), false);
		
		old_value
	}
	
	/// Function to safely replace the state of the ManuallyDrop trigger 
	/// definer (note that the new state must fire on validation)
	#[inline]
	fn __safe_replace_mutstate<Trig: TrigManuallyDrop>(&self, new_state: StateManuallyDropData) {
		crate::__fullinternal_debug_assertions!(new_state.is_next_trig(), true);
		
		let old_state = self.__force_write(new_state);
		
		// COMBO REPLACE STATE -> ERR
		if old_state.is_next_trig() {
			Trig::trig_next_invalid_beh(
				format_args!(
					"Undefined behavior when using ManuallyDrop(combo_replace_manudropstate), instead of the expected default state, the current state: {:?}.", 
					old_state
				)
			);
		}
	}
	
	/// Change the ManuallyDrop state to a panicked state, or execute a trigger 
	/// function if the current state was not empty.
	#[inline(always)]
	pub fn to_dropmode_or_trig<Trig: TrigManuallyDrop>(&self) {
		self.__safe_replace_mutstate::<Trig>(
			StateManuallyDropData::DropModeTrig
		);
		
		crate::__fullinternal_debug_assertions!(self.is_next_trig(), true);
	}
	
	/// Change the state of ManuallyDrop to the state of the released value, 
	/// or execute the trigger function if the current state was not empty.
	#[inline(always)]
	pub fn to_takemode_or_trig<Trig: TrigManuallyDrop>(&self) {
		self.__safe_replace_mutstate::<Trig>(
			StateManuallyDropData::TakeModeTrig
		);
		
		crate::__fullinternal_debug_assertions!(self.is_next_trig(), true);
	}
	
	/// Change the ManuallyDrop state to ignore freeing the value, or execute the 
	/// trigger function if the current state was not empty.
	#[inline(always)]
	pub fn to_ignore_trig_when_drop<Trig: TrigManuallyDrop>(&self) {
		self.__safe_replace_mutstate::<Trig>(
			StateManuallyDropData::IgnoreTrigWhenDrop
		);
		
		crate::__fullinternal_debug_assertions!(self.is_next_trig(), true);
	}
	
	/// Change the state of ManuallyDrop to the state of the released value, or execute 
	/// the trigger function if the current state was not empty.
	#[inline(always)]
	pub fn to_intoinnermode_or_trig<Trig: TrigManuallyDrop>(&self) {
		self.__safe_replace_mutstate::<Trig>(
			StateManuallyDropData::IntoInnerModeTrig
		);
		
		crate::__fullinternal_debug_assertions!(self.is_next_trig(), true);
	}
	
	/// Check the state of ManuallyDrop for a readable state, or execute a trigger 
	/// function if the current state was not empty.
	#[inline(always)]
	pub fn deref_or_trig<Trig: TrigManuallyDrop>(&self) {
		let a_state = self.read();
		
		if a_state.is_next_trig() {
			Trig::trig_next_invalid_beh(
				format_args!(
					"Undefined behavior when using ManuallyDrop.deref(), instead of the expected default state, the current state: {:?}.",
					a_state
				)
			)
		}
	}
	
	/// Check if the ManuallyDrop state is empty, or execute the trigger function if 
	/// the current state was not empty.
	pub fn if_empty_then_run_trigfn<Trig: TrigManuallyDrop, F: FnOnce()>(&self, exp_str: &'static str, fn_trig: F) {
		let a_state = self.read();
		
		if a_state.is_empty() {
			fn_trig();
			
			Trig::trig_next_invalid_beh(
				format_args!(
					"Undefined behavior when using ManuallyDrop ({}), state should not be default, current state is {:?}.",
					exp_str,
					a_state
				)
			)
		}
	}
	
	/// Determining if a trigger should be executed
	#[inline(always)]
	pub fn is_next_trig(&self) -> bool {
		self.read().is_next_trig()
	}
}

impl Default for StateManuallyDrop {
	#[inline(always)]
	fn default() -> Self {
		StateManuallyDrop::empty()
	}
}

#[cfg(all(test, feature = "support_panic_trig"))]
#[test]
fn test_state() {
	let state = StateManuallyDrop::empty();
	assert_eq!(state.is_empty(), true);
	assert_eq!(state.is_next_trig(), false);
	
	state.deref_or_trig::<PanicTrigManuallyDrop>(); // ok
}

#[cfg(all(test, feature = "support_panic_trig"))]
#[test]
fn test_const_empty_state() {
	let state = EMPTY_STATE; // Copy
	assert_eq!(state.is_empty(), true);
	assert_eq!(state.is_next_trig(), false);
	
	state.deref_or_trig::<PanicTrigManuallyDrop>(); // ok
}


#[cfg(all(test, feature = "support_panic_trig"))]
#[test]
fn test_reset() {
	let state = StateManuallyDrop::empty();
	assert_eq!(state.is_empty(), true);
	assert_eq!(state.is_next_trig(), false);
	
	state.deref_or_trig::<PanicTrigManuallyDrop>(); // ok
	state.to_dropmode_or_trig::<PanicTrigManuallyDrop>();
	
	assert_eq!(state.is_empty(), false);
	assert_eq!(state.is_next_trig(), true);
	
	let old_state = unsafe {
		state.get_and_reset()
	};
	assert_eq!(state.is_empty(), true);
	assert_eq!(state.is_next_trig(), false);
	assert_eq!(old_state.is_empty(), false);
	assert_eq!(old_state.is_next_trig(), true);
	assert_eq!(old_state, StateManuallyDropData::DropModeTrig);
}