reinhardt-core 0.1.1

Core components for Reinhardt framework
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Recursive serialization support
//!
//! This module provides utilities for handling recursive and deeply nested serialization.

use std::collections::HashSet;

/// Context for tracking serialization depth and visited objects
#[derive(Debug, Clone)]
pub struct SerializationContext {
	/// Current depth level (0 = root)
	current_depth: usize,
	/// Maximum allowed depth
	max_depth: usize,
	/// Set of visited object identities (pointer addresses) to detect circular references
	visited: HashSet<usize>,
}

impl SerializationContext {
	/// Create a new serialization context
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// let context = SerializationContext::new(3);
	/// // Verify context is initialized with correct depth settings
	/// assert_eq!(context.current_depth(), 0);
	/// assert_eq!(context.max_depth(), 3);
	/// ```
	pub fn new(max_depth: usize) -> Self {
		Self {
			current_depth: 0,
			max_depth,
			visited: HashSet::new(),
		}
	}

	/// Get the current depth
	pub fn current_depth(&self) -> usize {
		self.current_depth
	}

	/// Get the maximum depth
	pub fn max_depth(&self) -> usize {
		self.max_depth
	}

	/// Check if we can go deeper
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// let context = SerializationContext::new(2);
	/// // Verify depth check works correctly
	/// assert!(context.can_go_deeper());
	/// ```
	pub fn can_go_deeper(&self) -> bool {
		self.current_depth < self.max_depth
	}

	/// Visit an object, marking it as visited for circular reference detection
	///
	/// Returns `true` if the object can be visited (not visited before),
	/// `false` if it's already visited.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// struct User { id: i64 }
	/// let user = User { id: 1 };
	///
	/// let mut context = SerializationContext::new(5);
	/// // Verify circular reference detection
	/// assert!(context.visit(&user));
	/// assert!(!context.visit(&user)); // Already visited
	/// ```
	pub fn visit<T>(&mut self, obj: &T) -> bool {
		let id = obj as *const T as usize;

		if self.visited.contains(&id) {
			return false; // Circular reference detected
		}

		self.visited.insert(id);
		true
	}

	/// Leave an object, unmarking it as visited (for backtracking)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// struct User { id: i64 }
	/// let user = User { id: 1 };
	///
	/// let mut context = SerializationContext::new(5);
	/// context.visit(&user);
	/// context.leave(&user);
	/// // Verify object can be visited again after leaving
	/// assert!(context.visit(&user)); // Can visit again after leaving
	/// ```
	pub fn leave<T>(&mut self, obj: &T) {
		let id = obj as *const T as usize;
		self.visited.remove(&id);
	}

	/// Create a child context with increased depth
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// let context = SerializationContext::new(3);
	/// let child = context.child();
	///
	/// // Verify child context has incremented depth
	/// assert_eq!(child.current_depth(), 1);
	/// assert_eq!(child.max_depth(), 3);
	/// ```
	pub fn child(&self) -> Self {
		Self {
			current_depth: self.current_depth + 1,
			max_depth: self.max_depth,
			visited: self.visited.clone(),
		}
	}

	/// Reset the context to initial state
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// let mut context = SerializationContext::new(3);
	/// let child = context.child();
	/// assert_eq!(child.current_depth(), 1);
	///
	/// let mut reset_context = child;
	/// reset_context.reset();
	/// // Verify context resets to initial state
	/// assert_eq!(reset_context.current_depth(), 0);
	/// ```
	pub fn reset(&mut self) {
		self.current_depth = 0;
		self.visited.clear();
	}

	/// Get the remaining depth
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::SerializationContext;
	///
	/// let context = SerializationContext::new(3);
	/// // Verify remaining depth calculation
	/// assert_eq!(context.remaining_depth(), 3);
	///
	/// let child = context.child();
	/// assert_eq!(child.remaining_depth(), 2);
	/// ```
	pub fn remaining_depth(&self) -> usize {
		self.max_depth.saturating_sub(self.current_depth)
	}
}

impl Default for SerializationContext {
	fn default() -> Self {
		Self::new(1)
	}
}

/// Result type for recursive serialization
pub type RecursiveResult<T> = Result<T, RecursiveError>;

/// Errors that can occur during recursive serialization
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecursiveError {
	/// Maximum depth exceeded
	MaxDepthExceeded {
		/// The depth at which the limit was hit.
		current_depth: usize,
		/// The configured maximum depth.
		max_depth: usize,
	},
	/// Circular reference detected
	CircularReference {
		/// Identifier of the object that caused the circular reference.
		object_id: String,
	},
	/// General serialization error
	SerializationError {
		/// Human-readable error description.
		message: String,
	},
}

impl std::fmt::Display for RecursiveError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			RecursiveError::MaxDepthExceeded {
				current_depth,
				max_depth,
			} => write!(
				f,
				"Maximum depth exceeded: current={}, max={}",
				current_depth, max_depth
			),
			RecursiveError::CircularReference { object_id } => {
				write!(f, "Circular reference detected: {}", object_id)
			}
			RecursiveError::SerializationError { message } => {
				write!(f, "Serialization error: {}", message)
			}
		}
	}
}

impl std::error::Error for RecursiveError {}

/// Helper trait for objects that can provide an identifier
pub trait ObjectIdentifiable {
	/// Get a unique identifier for this object
	///
	/// This identifier should be stable and unique across instances.
	/// Typically uses the model name and primary key (e.g., "User:123").
	fn object_id(&self) -> String;
}

/// Helper functions for circular reference detection
pub mod circular {
	use super::*;

	/// Visit an object and execute a function, automatically cleaning up on completion
	///
	/// This ensures proper cleanup even if the function panics or returns an error.
	/// Uses pointer-based identity for accurate circular reference detection.
	/// Manages depth automatically by creating a child context.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::{SerializationContext, circular};
	///
	/// struct User { id: i64 }
	/// let user = User { id: 1 };
	///
	/// let mut context = SerializationContext::new(5);
	///
	/// let result = circular::visit_with(&mut context, &user, |ctx| {
	///     // Do serialization work here
	///     Ok(42)
	/// });
	///
	/// assert_eq!(result.unwrap(), 42);
	/// // Verify automatic cleanup after function completion
	/// assert!(context.visit(&user)); // Can visit again
	/// ```
	pub fn visit_with<T, F, R>(
		context: &mut SerializationContext,
		obj: &T,
		f: F,
	) -> RecursiveResult<R>
	where
		F: FnOnce(&mut SerializationContext) -> RecursiveResult<R>,
	{
		// Check circular reference
		if !context.visit(obj) {
			let id = obj as *const T as usize;
			return Err(RecursiveError::CircularReference {
				object_id: format!("0x{:x}", id),
			});
		}

		// Check depth limit
		if !context.can_go_deeper() {
			context.leave(obj);
			return Err(RecursiveError::MaxDepthExceeded {
				current_depth: context.current_depth(),
				max_depth: context.max_depth(),
			});
		}

		// Create child context with increased depth
		let mut child_context = context.child();

		// Execute function
		let result = f(&mut child_context);

		// Cleanup
		context.leave(obj);
		result
	}
}

/// Helper functions for depth management
pub mod depth {
	use super::*;

	/// Check if we can descend to the next level
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::{SerializationContext, depth};
	///
	/// let context = SerializationContext::new(2);
	/// // Verify descent check works correctly
	/// assert!(depth::can_descend(&context));
	/// ```
	pub fn can_descend(context: &SerializationContext) -> bool {
		context.can_go_deeper()
	}

	/// Attempt to descend to the next level, returning an error if max depth is reached
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::{SerializationContext, depth};
	///
	/// let context = SerializationContext::new(2);
	/// assert!(depth::try_descend(&context).is_ok());
	///
	/// // Verify error when max depth is reached
	/// let child = context.child().child();
	/// assert!(depth::try_descend(&child).is_err());
	/// ```
	pub fn try_descend(context: &SerializationContext) -> RecursiveResult<SerializationContext> {
		if !can_descend(context) {
			return Err(RecursiveError::MaxDepthExceeded {
				current_depth: context.current_depth(),
				max_depth: context.max_depth(),
			});
		}
		Ok(context.child())
	}

	/// Descend to the next level and execute a function
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::serializers::recursive::{SerializationContext, depth};
	///
	/// let context = SerializationContext::new(3);
	///
	/// let result = depth::descend_with(&context, |child_ctx| {
	///     // Verify child context depth in callback
	///     assert_eq!(child_ctx.current_depth(), 1);
	///     Ok(())
	/// });
	///
	/// assert!(result.is_ok());
	/// ```
	pub fn descend_with<F, T>(context: &SerializationContext, f: F) -> RecursiveResult<T>
	where
		F: FnOnce(&SerializationContext) -> RecursiveResult<T>,
	{
		let child = try_descend(context)?;
		f(&child)
	}
}

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

	#[test]
	fn test_context_new() {
		let context = SerializationContext::new(3);
		assert_eq!(context.current_depth(), 0);
		assert_eq!(context.max_depth(), 3);
		assert!(context.can_go_deeper());
	}

	#[test]
	fn test_context_child() {
		let context = SerializationContext::new(3);
		let child = context.child();

		assert_eq!(child.current_depth(), 1);
		assert_eq!(child.max_depth(), 3);
		assert!(child.can_go_deeper());
	}

	#[test]
	fn test_context_can_go_deeper() {
		let context = SerializationContext::new(2);
		assert!(context.can_go_deeper());

		let child1 = context.child();
		assert!(child1.can_go_deeper());

		let child2 = child1.child();
		assert!(!child2.can_go_deeper());
	}

	#[test]
	fn test_context_visit_and_leave() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(5);
		assert!(context.visit(&user));

		// Second visit should fail (circular reference)
		assert!(!context.visit(&user));

		// After leaving, can visit again
		context.leave(&user);
		assert!(context.visit(&user));
	}

	#[test]
	fn test_context_reset() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(3);
		context.visit(&user);

		let child = context.child();
		assert_eq!(child.current_depth(), 1);

		let mut reset_context = child;
		reset_context.reset();
		assert_eq!(reset_context.current_depth(), 0);
	}

	#[test]
	fn test_remaining_depth() {
		let context = SerializationContext::new(3);
		assert_eq!(context.remaining_depth(), 3);

		let child1 = context.child();
		assert_eq!(child1.remaining_depth(), 2);

		let child2 = child1.child();
		assert_eq!(child2.remaining_depth(), 1);

		let child3 = child2.child();
		assert_eq!(child3.remaining_depth(), 0);
	}

	#[test]
	fn test_context_default() {
		let context = SerializationContext::default();
		assert_eq!(context.current_depth(), 0);
		assert_eq!(context.max_depth(), 1);
	}

	#[test]
	fn test_recursive_error_display() {
		let err = RecursiveError::MaxDepthExceeded {
			current_depth: 5,
			max_depth: 3,
		};
		assert_eq!(err.to_string(), "Maximum depth exceeded: current=5, max=3");

		let err = RecursiveError::CircularReference {
			object_id: "user:1".to_string(),
		};
		assert_eq!(err.to_string(), "Circular reference detected: user:1");

		let err = RecursiveError::SerializationError {
			message: "test error".to_string(),
		};
		assert_eq!(err.to_string(), "Serialization error: test error");
	}

	#[test]
	fn test_circular_reference_detection() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(5);

		// First visit succeeds
		assert!(context.visit(&user));

		// Second visit fails (circular reference detected)
		assert!(!context.visit(&user));
	}

	#[test]
	fn test_circular_visit_with() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(5);

		let result = visit_with(&mut context, &user, |_ctx| Ok(42));

		assert_eq!(result.unwrap(), 42);
		// Object is automatically unmarked after the function completes
		assert!(context.visit(&user)); // Can visit again
	}

	#[test]
	fn test_circular_visit_with_error() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(5);

		let result: RecursiveResult<()> = visit_with(&mut context, &user, |_ctx| {
			Err(RecursiveError::SerializationError {
				message: "test".to_string(),
			})
		});

		assert!(result.is_err());
		// Object is automatically unmarked even on error
		assert!(context.visit(&user)); // Can visit again
	}

	#[test]
	fn test_different_objects_same_string_representation() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user1 = User { id: 1 };
		let user2 = User { id: 1 };

		let mut context = SerializationContext::new(5);

		// Both users have same ID but different memory addresses
		assert!(context.visit(&user1));
		assert!(context.visit(&user2)); // Should succeed - different objects

		context.leave(&user1);
		context.leave(&user2);
	}

	#[test]
	fn test_same_object_multiple_references() {
		// Allow dead_code: test-only struct; fields used only for pointer-based identity in circular reference detection
		#[allow(dead_code)]
		struct User {
			id: i64,
		}
		let user = User { id: 1 };

		let mut context = SerializationContext::new(5);

		// Visit the same object
		assert!(context.visit(&user));

		// Create another reference to the same object
		let user_ref = &user;

		// Second visit with different reference should fail (same object)
		assert!(!context.visit(user_ref));
	}

	#[test]
	fn test_depth_can_descend() {
		let context = SerializationContext::new(2);
		assert!(can_descend(&context));

		let child = context.child();
		assert!(can_descend(&child));

		let grandchild = child.child();
		assert!(!can_descend(&grandchild));
	}

	#[test]
	fn test_depth_try_descend() {
		let context = SerializationContext::new(2);
		assert!(try_descend(&context).is_ok());

		let child = context.child().child();
		let err = try_descend(&child).unwrap_err();
		assert_eq!(
			err,
			RecursiveError::MaxDepthExceeded {
				current_depth: 2,
				max_depth: 2
			}
		);
	}

	#[test]
	fn test_depth_descend_with() {
		let context = SerializationContext::new(3);

		let result = descend_with(&context, |child_ctx| {
			assert_eq!(child_ctx.current_depth(), 1);
			assert_eq!(child_ctx.max_depth(), 3);
			Ok(123)
		});

		assert_eq!(result.unwrap(), 123);
	}
}