cluConstData 2.1.2

Compile-time macros for building persistent data structures in no_std and const environments. Supports buffer composition, and numeric formatting.
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
632
633
634
635
636
637
638
639
640
641
642
643
//! Compile-time buffer builder with UTF-8 safety and decimal formatting.
//!

pub mod size;

use crate::buf::size::ConstByteBufSize;
use core::fmt::Debug;
use core::fmt::Display;
use core::hash::Hash;
use core::marker::PhantomData;
use core::mem::MaybeUninit;

/// UTF-8 safe const buffer builder.
///
/// # Example
/// ```rust
/// use cluConstData::buf::ConstStrBuf;
/// const fn build_name() -> ConstStrBuf<16> {
///	let mut buf = ConstStrBuf::<16>::new();
///	buf.push_str("hello");
///	buf.push_char('!');
///	buf
/// }
/// ```
///
/// Suitable for compile-time generation of valid strings.
pub type ConstStrBuf<const CAP: usize> = ConstByteBuf<CAP, Utf8SafeBuf>;

/// Fixed-capacity builder for `const` contexts.
///
/// Allows appending strings, raw bytes, or `usize` in decimal form—all in `const fn`.
/// Internally uses a `[MaybeUninit<u8>; CAP]` buffer and tracks the current write position.
pub struct ConstByteBuf<const CAP: usize, TData = DefBuf>
where
	TData: ConstByteBufData,
{
	tdata: PhantomData<TData>,

	buf: [MaybeUninit<u8>; CAP],
	wpos: usize,
}

/// Marker trait for buffer behavior customization.
pub trait ConstByteBufData {}

/// Marker type enforcing UTF-8 validation.
pub enum Utf8SafeBuf {}
impl ConstByteBufData for Utf8SafeBuf {}

/// Marker type allowing unrestricted raw byte access.
///
/// Grants access to raw byte writing methods like `write_bytes`, which bypass UTF-8 checks.
pub enum DefBuf {}
impl ConstByteBufData for DefBuf {}

impl<const CAP: usize, TData: ConstByteBufData> ConstByteBuf<CAP, TData> {
	/// Creates a new empty buffer.
	///
	/// Initializes all memory to uninitialized (`MaybeUninit`),
	/// with the write cursor set to `0`.
	#[inline]
	pub const fn new() -> Self {
		Self {
			tdata: PhantomData,

			buf: [MaybeUninit::uninit(); CAP],
			wpos: 0,
		}
	}

	/// Creates an exact copy of the buffer.
	#[inline]
	pub const fn clone(&self) -> Self {
		Self {
			tdata: PhantomData,

			buf: self.buf,
			wpos: self.wpos,
		}
	}

	/// Removes and returns the last written byte.
	const fn _pop(&mut self) -> Option<u8> {
		match self.wpos {
			0 => None,
			pos => {
				let result = core::mem::replace(&mut self.buf[pos], MaybeUninit::uninit());
				self.wpos -= 1;

				Some(unsafe { result.assume_init() })
			}
		}
	}

	/// Converts this `ConstStrBuf` into a fully initialized `[u8; CAP]` array,
	/// filling remaining capacity with a custom trailing byte (`space`).
	#[cfg_attr(docsrs, doc(cfg(feature = "clufulltransmute")))]
	#[cfg(feature = "clufulltransmute")]
	const fn _into_array(mut self, space: u8) -> (usize, [u8; CAP]) {
		let len = self.len();
		while self.__try_write_byte(space).is_ok() {} // utf-8 safe

		// TODO WAIT https://github.com/rust-lang/rust/issues/96097 in stable
		(len, unsafe {
			cluFullTransmute::transmute_unchecked(self.buf as [MaybeUninit<u8>; CAP])
		})
	}

	/// Resets write position to 0, retains buffer contents.
	#[inline]
	pub const fn clear(&mut self) {
		self.wpos = 0;
	}

	/// Total capacity in bytes.
	#[inline]
	pub const fn capacity(&self) -> usize {
		self.buf.len()
	}

	/// Returns a mutable reference to the byte at the given position.
	const fn _get_mut(&mut self, pos: usize) -> Option<&mut u8> {
		if pos > self.wpos {
			return None;
		}

		unsafe { Some(self.buf[pos].assume_init_mut()) }
	}

	/// Returns an immutable reference to the byte at the given position.
	pub const fn get(&self, pos: usize) -> Option<&u8> {
		if pos > self.wpos {
			return None;
		}

		unsafe { Some(self.buf[pos].assume_init_ref()) }
	}

	/// Number of bytes already written.
	#[inline]
	pub const fn len(&self) -> usize {
		self.wpos
	}

	/// Determine if a recording has been made previously
	#[inline]
	pub const fn is_empty(&self) -> bool {
		self.wpos == 0
	}

	/// Available capacity.
	#[inline]
	pub const fn available(&self) -> usize {
		CAP - self.wpos
	}

	/// Returns a raw pointer to the slice's buffer.
	#[inline]
	pub const fn as_ptr(&self) -> *const MaybeUninit<u8> {
		self.buf.as_ptr()
	}

	/// Returns a raw mut pointer to the slice's buffer.
	#[inline]
	pub const fn as_mut_ptr(&mut self) -> *mut MaybeUninit<u8> {
		self.buf.as_mut_ptr()
	}

	/// Returns a slice of written bytes.
	#[inline]
	pub const fn as_bytes(&self) -> &[u8] {
		unsafe { core::slice::from_raw_parts(self.as_ptr() as *const u8, self.wpos) }
	}

	/// Returns a mut slice of written bytes.
	#[inline]
	const fn _as_mut_bytes(&mut self) -> &mut [u8] {
		unsafe { core::slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8, self.wpos) }
	}

	/// Appends a UTF-8 string.
	///
	/// Panics on overflow.
	#[inline]
	pub const fn push_str(&mut self, s: &str) -> usize {
		self.__write_bytes_unchecked(s.as_bytes())
	}

	/// Appends a UTF-8 string.
	#[inline]
	pub const fn try_push_str(&mut self, s: &str) -> Result<usize, StackOverflow> {
		self.__try_write_bytes_unchecked(s.as_bytes())
	}

	/// Appends raw bytes without UTF-8 check.
	///
	/// Panics on overflow.
	#[track_caller]
	#[inline]
	const fn __write_bytes_unchecked(&mut self, data: &[u8]) -> usize {
		match self.__try_write_bytes_unchecked(data) {
			Ok(a) => a,
			Err(_) => Self::cold_overflow_panic(),
		}
	}

	/// Appends raw bytes without UTF-8 check. Panics on overflow.
	const fn __try_write_bytes_unchecked(&mut self, data: &[u8]) -> Result<usize, StackOverflow> {
		let datalen = data.len();
		if self.wpos + datalen > CAP {
			return Err(StackOverflow);
		}

		let mut i = 0;
		while i < datalen {
			self.buf[self.wpos + i].write(data[i]);
			i += 1;
		}
		self.wpos += datalen;
		Ok(datalen)
	}

	/// Appends byte.
	///
	/// Panics on overflow.
	const fn __write_byte(&mut self, data: u8) -> usize {
		match self.__try_write_byte(data) {
			Ok(a) => a,
			Err(_) => Self::cold_overflow_panic(),
		}
	}

	/// Appends byte.
	const fn __try_write_byte(&mut self, data: u8) -> Result<usize, StackOverflow> {
		let datalen = 1;
		if self.wpos + datalen > CAP {
			return Err(StackOverflow);
		}

		self.buf[self.wpos].write(data);
		self.wpos += datalen;
		Ok(datalen)
	}

	/// Appends a single UTF-8 character.
	///
	/// Panics on overflow.
	pub const fn push_char(&mut self, value: char) -> usize {
		match self.try_push_char(value) {
			Ok(a) => a,
			Err(_) => Self::cold_overflow_panic(),
		}
	}

	/// Appends a single UTF-8 character.
	pub const fn try_push_char(&mut self, value: char) -> Result<usize, StackOverflow> {
		let mut buf: [u8; <char as ConstByteBufSize>::MAX_DECIMAL_LEN] =
			unsafe { core::mem::zeroed() };
		let str = value.encode_utf8(&mut buf);

		self.try_push_str(str)
	}

	/// Appends decimal representation of `usize`.
	///
	/// Panics on overflow.
	pub const fn push_usize(&mut self, value: usize) -> usize {
		match self.try_push_usize(value) {
			Ok(a) => a,
			Err(_) => Self::cold_overflow_panic(),
		}
	}

	/// Appends decimal representation of `usize`.
	pub const fn try_push_usize(&mut self, mut value: usize) -> Result<usize, StackOverflow> {
		let mut arr: [MaybeUninit<u8>; usize::MAX_DECIMAL_LEN] =
			[MaybeUninit::uninit(); usize::MAX_DECIMAL_LEN];
		let arr_len = arr.len();
		let mut len;

		if value == 0 {
			arr[arr_len - 1].write(b'0');
			len = 1;
		} else {
			len = 0;
			let mut i = arr_len;
			while value != 0 {
				i -= 1;

				arr[i].write(b'0' + (value % 10) as u8);
				value /= 10;
				len += 1;
			}
		}

		let start = arr_len - len;
		let dataptr = unsafe { arr.as_ptr().add(start) };
		let slice = unsafe { core::slice::from_raw_parts(dataptr as *const u8, len) };

		self.__try_write_bytes_unchecked(slice)
	}

	/// Appends decimal representation of `isize`.
	///
	/// Panics on overflow.
	pub const fn push_isize(&mut self, value: isize) -> usize {
		match self.try_push_isize(value) {
			Ok(a) => a,
			Err(_) => Self::cold_overflow_panic(),
		}
	}

	/// Appends decimal representation of `isize`.
	pub const fn try_push_isize(&mut self, value: isize) -> Result<usize, StackOverflow> {
		let abs: usize = match value < 0 {
			true => {
				if let Err(e) = self.__try_write_byte(b'-') {
					return Err(e);
				}

				value.wrapping_neg() as usize
			}
			false => value as usize,
		};

		self.try_push_usize(abs)
	}

	/// Panics when a `ConstByteBuf` overflows its allocated capacity.
	///
	/// This function is marked as `#[cold]` and `#[inline(never)]` to ensure
	/// it remains outside hot execution paths and does not interfere with performance.
	/// Additionally, `#[track_caller]` preserves the location of the original call site,
	/// helping diagnose overflows during compile-time or runtime evaluation.
	#[cold]
	#[track_caller]
	#[inline(never)]
	const fn cold_overflow_panic() -> ! {
		panic!("ConstByteBuf overflow: capacity exceeded");
	}
}

impl<const CAP: usize> ConstByteBuf<CAP, Utf8SafeBuf> {
	/// Returns a slice of written bytes as a UTF-8 string.
	#[inline]
	pub const fn as_str(&self) -> &str {
		unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
	}

	/// Returns a slice of written bytes as a UTF-8 string.
	#[inline]
	pub const fn as_mut_str(&mut self) -> &mut str {
		unsafe { core::str::from_utf8_unchecked_mut(self.as_mut_bytes()) }
	}

	/// Appends raw bytes without UTF-8 check.
	///
	/// Panics on overflow.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[track_caller]
	#[inline]
	pub const unsafe fn write_bytes_unchecked(&mut self, data: &[u8]) -> usize {
		self.__write_bytes_unchecked(data)
	}

	/// Appends raw bytes without UTF-8 check. Panics on overflow.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	pub const unsafe fn try_write_bytes_unchecked(
		&mut self,
		data: &[u8],
	) -> Result<usize, StackOverflow> {
		self.__try_write_bytes_unchecked(data)
	}

	/// Appends byte.
	///
	/// Panics on overflow.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	pub const unsafe fn write_byte(&mut self, data: u8) -> usize {
		self.__write_byte(data)
	}

	/// Appends byte.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	pub const unsafe fn try_write_byte(&mut self, data: u8) -> Result<usize, StackOverflow> {
		self.__try_write_byte(data)
	}

	/// Returns a mutable reference to the byte at the given position.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	pub const unsafe fn get_mut(&mut self, pos: usize) -> Option<&mut u8> {
		self._get_mut(pos)
	}

	/// Removes and returns the last written byte.
	///
	/// # Safety
	/// May break UTF-8
	#[inline]
	pub const unsafe fn pop(&mut self) -> Option<u8> {
		self._pop()
	}

	/// Returns a mut slice of written bytes.
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	pub const unsafe fn as_mut_bytes(&mut self) -> &mut [u8] {
		self._as_mut_bytes()
	}

	/// Converts this `ConstStrBuf` into a fully initialized `[u8; CAP]` array,
	/// filling remaining capacity with a custom trailing byte (0)
	/// and also returning its original length.
	#[inline]
	#[cfg_attr(docsrs, doc(cfg(feature = "clufulltransmute")))]
	#[cfg(feature = "clufulltransmute")]
	pub const fn into_array_filled_with_zero(self) -> (usize, [u8; CAP]) {
		self._into_array(b' ') // utf-8 safe
	}

	/// Converts this `ConstStrBuf` into a fully initialized `[u8; CAP]` array,
	/// filling remaining capacity with a custom trailing byte (b' ')
	/// and also returning its original length.
	#[inline]
	#[cfg_attr(docsrs, doc(cfg(feature = "clufulltransmute")))]
	#[cfg(feature = "clufulltransmute")]
	pub const fn into_array_filled_with_space(self) -> (usize, [u8; CAP]) {
		self._into_array(b' ') // utf-8 safe
	}

	/// Converts this ConstStrBuf into a fully initialized [u8; CAP] array,
	/// filling remaining capacity with a custom trailing byte (space).
	///
	/// # Safety
	/// It's safe as long as you send `utf-8` sequences,
	/// if you send non-`utf-8` sequences you just break the API.
	#[inline]
	#[cfg_attr(docsrs, doc(cfg(feature = "clufulltransmute")))]
	#[cfg(feature = "clufulltransmute")]
	pub const unsafe fn into_array(self, space: u8) -> (usize, [u8; CAP]) {
		self._into_array(space)
	}
}

impl<const CAP: usize> ConstByteBuf<CAP, DefBuf> {
	/// Appends raw bytes. Panics on overflow.
	///
	/// Panics on overflow.
	#[track_caller]
	#[inline]
	pub const fn write_bytes(&mut self, data: &[u8]) -> usize {
		self.__write_bytes_unchecked(data)
	}

	/// Appends raw bytes.
	///
	#[inline]
	pub const fn try_write_bytes(&mut self, data: &[u8]) -> Result<usize, StackOverflow> {
		self.__try_write_bytes_unchecked(data)
	}

	/// Appends byte.
	///
	/// Panics on overflow.
	#[track_caller]
	#[inline]
	pub const fn write_byte(&mut self, data: u8) -> usize {
		self.__write_byte(data)
	}

	/// Appends byte.
	#[inline]
	pub const fn try_write_byte(&mut self, data: u8) -> Result<usize, StackOverflow> {
		self.__try_write_byte(data)
	}

	/// Returns a mutable reference to the byte at the given position.
	#[inline]
	pub const fn get_mut(&mut self, pos: usize) -> Option<&mut u8> {
		self._get_mut(pos)
	}

	/// Removes and returns the last written byte.
	#[inline]
	pub const fn pop(&mut self) -> Option<u8> {
		self._pop()
	}

	/// Returns a mut slice of written bytes.
	#[inline]
	pub const fn as_mut_bytes(&mut self) -> &mut [u8] {
		self._as_mut_bytes()
	}

	/// Converts this ConstStrBuf into a fully initialized [u8; CAP] array,
	/// filling remaining capacity with a custom trailing byte (space)
	/// and also returning its original length.
	#[inline]
	#[cfg_attr(docsrs, doc(cfg(feature = "clufulltransmute")))]
	#[cfg(feature = "clufulltransmute")]
	pub const fn into_array(self, space: u8) -> (usize, [u8; CAP]) {
		self._into_array(space) // utf-8 safe
	}
}

impl<const CAP: usize, TData> Clone for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn clone(&self) -> Self {
		ConstByteBuf::clone(self)
	}
}

impl<const CAP: usize, TData> Default for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn default() -> Self {
		ConstByteBuf::new()
	}
}

impl<const CAP: usize> Display for ConstByteBuf<CAP, Utf8SafeBuf> {
	#[inline]
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		Display::fmt(self.as_str(), f)
	}
}

impl<const CAP: usize> Debug for ConstByteBuf<CAP, DefBuf> {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("ConstByteBuf")
			.field("buf", &self.as_bytes())
			.field("wpos", &self.wpos)
			.finish()
	}
}

impl<const CAP: usize> Debug for ConstByteBuf<CAP, Utf8SafeBuf> {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("ConstStrBuf")
			.field("buf", &self.as_str())
			.field("wpos", &self.wpos)
			.finish()
	}
}

impl<const CAP: usize, TData> Eq for ConstByteBuf<CAP, TData> where TData: ConstByteBufData {}

impl<const CAP: usize, TData> PartialEq for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn eq(&self, other: &Self) -> bool {
		PartialEq::eq(self.as_bytes(), other.as_bytes())
	}
}

impl<const CAP: usize> PartialEq<str> for ConstByteBuf<CAP, Utf8SafeBuf> {
	#[inline]
	fn eq(&self, other: &str) -> bool {
		PartialEq::eq(self.as_str(), other)
	}
}

impl<const CAP: usize> PartialEq<&'_ str> for ConstByteBuf<CAP, Utf8SafeBuf> {
	#[inline]
	fn eq(&self, other: &&str) -> bool {
		PartialEq::eq(self.as_str(), *other)
	}
}

impl<const CAP: usize, TData> PartialEq<[u8]> for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn eq(&self, other: &[u8]) -> bool {
		PartialEq::eq(self.as_bytes(), other)
	}
}

impl<const CAP: usize, TData> PartialEq<&'_ [u8]> for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn eq(&self, other: &&[u8]) -> bool {
		PartialEq::eq(self.as_bytes(), *other)
	}
}

impl<const CAP: usize, TData> PartialEq<&'_ mut [u8]> for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn eq(&self, other: &&mut [u8]) -> bool {
		PartialEq::eq(self.as_bytes(), *other)
	}
}

impl<const CAP: usize, TData> Hash for ConstByteBuf<CAP, TData>
where
	TData: ConstByteBufData,
{
	#[inline]
	fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
		Hash::hash(self.as_bytes(), state)
	}
}

/// Error type indicating buffer overflow during write.
///
/// Returned when a write operation exceeds the fixed capacity of a `ConstByteBuf`.
#[repr(transparent)]
pub struct StackOverflow;