reovim_kernel/mm/buffer_id.rs
1//! Buffer identification.
2//!
3//! Provides unique, monotonically increasing identifiers for buffers.
4
5use std::sync::atomic::{AtomicUsize, Ordering};
6
7/// Global counter for buffer IDs.
8static NEXT_BUFFER_ID: AtomicUsize = AtomicUsize::new(0);
9
10/// Unique identifier for a buffer.
11///
12/// Buffer IDs are monotonically increasing and never reused within a session.
13/// This ensures that buffer references remain unambiguous even after buffers
14/// are closed.
15///
16/// # Example
17///
18/// ```
19/// use reovim_kernel::api::v1::*;
20///
21/// let id1 = BufferId::new();
22/// let id2 = BufferId::new();
23/// assert_ne!(id1, id2);
24/// assert!(id1 < id2);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct BufferId(usize);
28
29impl BufferId {
30 /// Create a new unique buffer ID.
31 ///
32 /// Each call returns a distinct ID, guaranteed to be unique within
33 /// the current process lifetime.
34 #[must_use]
35 pub fn new() -> Self {
36 Self(NEXT_BUFFER_ID.fetch_add(1, Ordering::Relaxed))
37 }
38
39 /// Get the raw numeric value.
40 #[must_use]
41 pub const fn as_usize(self) -> usize {
42 self.0
43 }
44
45 /// Create a `BufferId` from a raw value.
46 ///
47 /// This is primarily useful for testing or deserialization.
48 ///
49 /// # Warning
50 ///
51 /// Using this incorrectly may create duplicate IDs. Prefer [`BufferId::new`]
52 /// for normal usage.
53 #[must_use]
54 pub const fn from_raw(value: usize) -> Self {
55 Self(value)
56 }
57}
58
59impl Default for BufferId {
60 fn default() -> Self {
61 Self::new()
62 }
63}
64
65impl std::fmt::Display for BufferId {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 write!(f, "Buffer({})", self.0)
68 }
69}