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
//! The **Compact** strategy for `Bytes`.
//!
//! This module provides the [`Bytes`](crate::compact::Bytes) type alias configured with the
//! [`Compact`](crate::compact::Compact) strategy,
//! which prioritizes **memory efficiency** by aggressively converting heap allocations back
//! to inline storage whenever possible.
//!
//! # Key Characteristics
//!
//! - **Aggressive inlining**: Automatically converts heap→inline when data fits (≤62 bytes)
//! - **Memory-efficient**: Minimizes heap allocations and memory overhead
//! - **Smart optimization**: Operations like `advance()`, `truncate()`, and `split_to/off()` trigger conversions
//! - **Best for constrained environments**: Ideal for embedded systems and memory-critical applications
//!
//! # When to Use
//!
//! Choose this strategy when:
//!
//! - **Memory is limited**: Embedded systems, microcontrollers, or memory-constrained environments
//! - **Many small buffers**: You work with numerous buffers that frequently shrink over time
//! - **Rare `Bytes` conversions**: You don't often convert to/from `bytes::Bytes`
//! - **Allocation minimization**: You want to minimize heap allocations at the cost of occasional copies
//!
//! # Basic Usage
//!
//! ```rust
//! use smol_bytes::{compact::Bytes, Buf};
//!
//! // Small data (≤62 bytes) is stored inline
//! let small = Bytes::from_static(b"hello world");
//! assert!(!small.is_heap());
//!
//! // Large data starts on heap
//! let mut large = Bytes::from(vec![1u8; 100]);
//! assert!(large.is_heap());
//!
//! // After shrinking, automatically converts to inline!
//! large.advance(70); // 30 bytes remain
//! assert!(!large.is_heap()); // ✓ Now inline!
//! ```
//!
//! # Behavior Details
//!
//! ## Memory Layout (Same as Shared)
//!
//! ```text
//! ┌─────────────────────────────────────────┐
//! │ Bytes (64 bytes on stack) │
//! ├─────────────────────────────────────────┤
//! │ Variant: Inline (≤62 bytes) │
//! │ ┌────────────────────────────────────┐ │
//! │ │ [u8; 62] data │ │
//! │ │ u8 length │ │
//! │ │ u8 current_offset │ │
//! │ └────────────────────────────────────┘ │
//! │ │
//! │ Variant: Heap (>62 bytes only) │
//! │ ┌────────────────────────────────────┐ │
//! │ │ bytes::Bytes (Arc<[u8]>) │ │
//! │ └────────────────────────────────────┘ │
//! └─────────────────────────────────────────┘
//! ```
//!
//! ## Operations and Allocation Behavior
//!
//! ```rust
//! use smol_bytes::{compact::Bytes, Buf};
//!
//! // Start with large heap allocation
//! let mut data = Bytes::from(vec![1u8; 100]);
//! assert!(data.is_heap());
//!
//! // After advance, automatically inlined (Compact strategy)
//! data.advance(70); // 30 bytes remain
//! assert!(!data.is_heap()); // ✓ Converted to inline!
//! ```
//!
//! ## Comparison: Heap→Inline Conversion Triggers
//!
//! | Operation | Before | After | Conversion? |
//! |-----------|--------|-------|-------------|
//! | `advance(n)` | Heap (100 bytes) | Inline (30 bytes) | ✅ Yes (if ≤62 bytes remain) |
//! | `truncate(n)` | Heap (100 bytes) | Inline (30 bytes) | ✅ Yes (if n ≤62) |
//! | `split_to(n)` | Heap (100 bytes) | Inline (remaining) | ✅ Yes (if remaining ≤62) |
//! | `split_off(n)` | Heap (100 bytes) | Inline (first part) | ✅ Yes (if first ≤62) |
//! | `slice(range)` | Heap | Inline | ✅ Yes (if result ≤62) |
//!
//! # Performance Characteristics
//!
//! ## Fast Operations (O(1))
//!
//! - `clone()` when inline - Simple memcpy
//! - `advance()` when staying inline or heap
//! - `truncate()` when staying inline or heap
//! - Operations that don't trigger conversion
//!
//! ## Linear Operations (O(62) - copies up to 62 bytes)
//!
//! - **Heap→Inline conversion** - Copies data to stack (up to 62 bytes)
//! - `advance()` when triggering conversion
//! - `truncate()` when triggering conversion
//! - `split_to()` / `split_off()` when triggering conversion
//! - `into::<Bytes>()` when inline (must copy to heap)
//!
//! **Note**: Since the maximum copy size is fixed at 62 bytes, these operations are very fast in practice!
//!
//! # Examples
//!
//! ## Stream Processing with Automatic Inlining
//!
//! ```rust
//! use smol_bytes::{compact::Bytes, Buf};
//!
//! // Process incoming stream
//! let mut buffer = Bytes::from(vec![0u8; 1024]);
//! assert!(buffer.is_heap());
//!
//! // As we consume data, it automatically inlines
//! buffer.advance(1000); // 24 bytes remain
//! assert!(!buffer.is_heap()); // Saved memory!
//! ```
//!
//! ## Memory-Efficient Buffer Pool
//!
//! ```rust
//! use smol_bytes::compact::Bytes;
//!
//! struct BufferPool {
//! buffers: Vec<Bytes>,
//! }
//!
//! impl BufferPool {
//! fn new() -> Self {
//! Self { buffers: Vec::new() }
//! }
//!
//! fn add(&mut self, data: Vec<u8>) {
//! // Automatically inlines if small enough
//! self.buffers.push(Bytes::from(data));
//! }
//!
//! fn total_heap_allocations(&self) -> usize {
//! self.buffers.iter()
//! .filter(|b| b.is_heap())
//! .count()
//! }
//! }
//!
//! let mut pool = BufferPool::new();
//!
//! // Add mix of small and large buffers
//! pool.add(vec![1; 10]); // Inline
//! pool.add(vec![2; 30]); // Inline
//! pool.add(vec![3; 100]); // Heap
//!
//! // Only one heap allocation!
//! assert_eq!(pool.total_heap_allocations(), 1);
//! ```
//!
//! ## Truncate for Memory Savings
//!
//! ```rust
//! use smol_bytes::compact::Bytes;
//!
//! let mut data = Bytes::from(vec![1u8; 100]);
//! assert!(data.is_heap());
//!
//! // Truncate to small size - automatically inlines
//! data.truncate(20);
//! assert!(!data.is_heap());
//! assert_eq!(data.len(), 20);
//! ```
//!
//! ## Smart Split Operations
//!
//! ```rust
//! use smol_bytes::compact::Bytes;
//!
//! let mut data = Bytes::from(vec![1u8; 100]);
//!
//! // Split off small portion - both parts optimize
//! let first = data.split_to(30); // first: 30 bytes (inline)
//! // data: 70 bytes (heap)
//!
//! assert!(!first.is_heap()); // Automatically inlined!
//! assert!(data.is_heap()); // Still too large for inline
//! ```
//!
//! # Trade-offs vs Shared ImmutableStorage
//!
//! ## Advantages
//!
//! - ✅ **Lower memory usage**: Fewer heap allocations
//! - ✅ **Better cache locality**: More data on stack
//! - ✅ **Fewer allocations**: Automatic heap→inline conversion
//! - ✅ **Simpler deallocation**: Inline data needs no cleanup
//!
//! ## Disadvantages
//!
//! - ❌ **Conversion overhead**: O(62) copy when heap→inline (up to 62 bytes)
//! - ❌ **Bytes conversion cost**: Must copy when inline
//! - ❌ **More copies**: Cloning inline data copies all bytes
//! - ❌ **No zero-copy for small data**: Inline can't share with `Bytes`
//!
//! # Benchmarks
//!
//! Typical performance characteristics (on x86_64):
//!
//! - **Heap→Inline conversion**: ~10-20ns for 62 bytes
//! - **Inline clone**: ~5-10ns for 62 bytes
//! - **Memory saved**: 32 bytes per buffer (no heap overhead)
//!
//! # Migration Guide
//!
//! If you're currently using `shared::Bytes` and considering switching:
//!
//! ```rust
//! // Before (Shared strategy)
//! use smol_bytes::{shared, compact, Buf};
//!
//! let mut data = shared::Bytes::from(vec![1u8; 100]);
//! data.advance(70); // Still heap-allocated
//! let bytes: bytes::Bytes = data.into(); // Zero-copy ✓
//!
//! // After (Compact strategy)
//!
//! let mut data = compact::Bytes::from(vec![1u8; 100]);
//! data.advance(70); // Now inline! Saved memory ✓
//! let bytes: bytes::Bytes = data.into(); // Copies 30 bytes (still fast!)
//! ```
//!
//! **Rule of thumb**: If you convert to `Bytes` more than once per buffer lifetime,
//! use `Shared`. If memory is more important than conversion speed, use `Compact`.
use ImmutableStorage;
use crate::;
use Buf;
use mem;
use RangeBounds;
pub use PyCompactBytes;
/// A strategy that aggressively inlines data to minimize heap allocations and memory usage.
///
/// # Overview
///
/// The `Compact` strategy prioritizes **memory efficiency** over conversion speed. It
/// automatically converts heap-allocated data back to inline storage whenever possible
/// (when data size ≤62 bytes) after operations like `advance()`, `truncate()`, or
/// `split_to/off()`.
///
/// This makes `Compact` ideal when:
/// - Memory footprint is critical
/// - You want to minimize heap allocations
/// - You're working with small, frequently-modified buffers
/// - Conversions to `Bytes` are rare
///
/// # Behavior
///
/// - **Inline → Inline**: Small data stays inline (≤62 bytes)
/// - **Heap → Inline**: Automatically inlines when data shrinks ≤62 bytes
/// - **Smart optimization**: Operations like `advance()`, `truncate()`, and `split_to/off()`
/// can trigger heap→inline conversion
///
/// ## Example
///
/// ```rust
/// use smol_bytes::compact::Bytes;
/// use bytes::Buf;
///
/// // Create heap-allocated bytes (>62 bytes)
/// let mut data = Bytes::from(vec![1u8; 100]);
/// assert!(data.is_heap());
///
/// // Advance past most data
/// data.advance(70); // Only 30 bytes remain
///
/// // Automatically converted to inline! (Compact strategy saves memory)
/// assert!(!data.is_heap());
/// ```
///
/// # Comparison with Shared
///
/// | Operation | Compact | Shared |
/// |-----------|---------|--------|
/// | Heap→Inline on shrink | ✅ Yes | ❌ No |
/// | Bytes conversion | 📋 May copy | ⚡ Zero-copy |
/// | Memory usage | 💾 Lower | 💾 Higher |
/// | Best for | Memory efficiency | Speed, Bytes interop |
);
/// A memory-efficient byte buffer that aggressively inlines data to minimize heap usage.
///
/// This type alias uses the [`Compact`] strategy.
///
/// # When to use
///
/// Use `Bytes` (with `Compact` strategy) when:
/// - Memory footprint is critical
/// - You're working with small, frequently-modified buffers
/// - Heap allocations should be minimized
/// - Conversions to `bytes::Bytes` are infrequent
///
/// For applications that frequently convert to/from `Bytes`, consider [`shared::Bytes`](super::shared::Bytes) instead.
///
/// ## Example
///
/// ```rust
/// use smol_bytes::compact::Bytes;
/// use bytes::Buf;
///
/// let mut data = Bytes::from(vec![1u8; 100]);
/// assert!(data.is_heap());
///
/// // After advancing, automatically converts to inline
/// data.advance(70);
/// assert!(!data.is_heap()); // Saved memory!
/// ```
pub type Bytes = ;
/// A compact, memory-efficient UTF-8 string type alias using the [`Compact`] strategy.
///
/// This is the compact-strategy immutable UTF-8 wrapper.
pub type Utf8Bytes = crateUtf8Bytes;