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
//! A Rust library providing **strongly typed indices** for collections, designed for both `std` and `no_std` environments.
//!
//! ## What are typed indices?
//!
//! In standard Rust, collections use `usize` for indexing. This works well but provides no compile-time
//! protection against using an index from one collection with another. Typed indices solve this by
//! creating custom index types that are statically associated with specific collections.
//!
//! In standard Rust, a raw `usize` can index any collection. This allows subtle bugs:
//! ```rust
//! # #[derive(Default, Clone, Copy)]
//! # struct Node;
//! # #[derive(Default, Clone, Copy)]
//! # struct Edge;
//! let nodes: Vec<Node> = vec![Node::default(); 10]; // 10 nodes
//! let edges: Vec<Edge> = vec![Edge::default(); 5]; // 5 edges
//! let node_index = 3;
//! nodes[node_index];
//! edges[node_index]; // compiles just fine!
//! ```
//!
//! With typed indices, cross-contamination becomes a compile error:
//! ```compile_fail
//! # use index_type::{IndexType, typed_vec::TypedVec};
//! # #[derive(Default, Clone, Copy)]
//! # struct Node;
//! # #[derive(Default, Clone, Copy)]
//! # struct Edge;
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct NodeId(u32);
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct EdgeId(u32);
//!
//! let nodes: TypedVec<NodeId, Node> = TypedVec::new();
//! let edges: TypedVec<EdgeId, Edge> = TypedVec::new();
//! let node_id = NodeId(3);
//! nodes[node_id]; // OK
//! edges[node_id]; // COMPILE ERROR: expected EdgeId, found NodeId
//! ```
//!
//! ## Features
//!
//! - **Type Safety**: Prevents accidental misuse of indices between different collections at compile time
//! - **`no_std` Support**: Works in embedded systems and other `no_std` environments
//! - **Memory Efficiency**: Use smaller integer types (`u8`, `u16`) for indices when collections are bounded
//! - **Niche Optimization**: Supports [`NonZero`](core::num::NonZero) types so `Option<Index>` has the same size as `Index`
//! - **Rich Collections**: Provides [`TypedSlice`](crate::typed_slice::TypedSlice), [`TypedVec`](crate::typed_vec::TypedVec), [`TypedArray`](crate::typed_array::TypedArray), and [`TypedArrayVec`](crate::typed_array_vec::TypedArrayVec)
//! - **Derive Macros**: Easy to define custom index types with `#[derive(IndexType)]`
//! - **Range Iterators**: Iterate over ranges using custom index types
//!
//! ## Quick Start
//!
//! ```rust
//! use index_type::IndexType;
//! use index_type::typed_vec::TypedVec;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct MyIndex(u32);
//!
//! let mut vec: TypedVec<MyIndex, i32> = TypedVec::new();
//! let idx = vec.push(42);
//!
//! assert_eq!(vec[idx], 42);
//! // vec[0usize]; // This won't compile - requires MyIndex type
//! ```
//!
//! ## Defining Index Types
//!
//! Use the `#[derive(IndexType)]` macro on a newtype struct:
//!
//! ```
//! use index_type::IndexType;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct MyIndex(u32);
//! ```
//!
//! The macro automatically implements the [`IndexType`] trait for your custom type. By default,
//! it generates an error type `MyIndexTooBigError`. You can specify a custom error type:
//!
//! ```
//! use index_type::IndexType;
//! use index_type::IndexTooBigError;
//!
//! #[derive(Debug, IndexTooBigError)]
//! #[index_too_big_error(msg = "item id too big")]
//! struct ItemIdTooBigError;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! #[index_type(error = ItemIdTooBigError)]
//! struct ItemId(u32);
//! ```
//!
//! ## Typed Collections
//!
//! ### TypedVec
//!
//! A growable vector with typed indexing. See [`TypedVec`](crate::typed_vec::TypedVec) for the full API.
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_vec::TypedVec;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct NodeId(u32);
//!
//! let mut nodes: TypedVec<NodeId, String> = TypedVec::new();
//! let id0 = nodes.push("Alice".to_string());
//! let id1 = nodes.push("Bob".to_string());
//!
//! println!("Node 0: {}", nodes[id0]);
//! ```
//!
//! Operations that can fail due to index overflow have both panicking and fallible variants:
//!
//! ```
//! # use index_type::IndexType;
//! # use index_type::typed_vec::TypedVec;
//! # #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! # struct MyIndex(u32);
//! let mut vec: TypedVec<MyIndex, i32> = TypedVec::new();
//! vec.push(1); // Panics if index too big
//! let result = vec.try_push(2); // Returns Result<(), Error>
//! ```
//!
//! ### TypedSlice
//!
//! A slice wrapper with typed indexing. See [`TypedSlice`](crate::typed_slice::TypedSlice) for the full API.
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_vec::TypedVec;
//! use index_type::typed_slice::TypedSlice;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct RowId(u16);
//!
//! let vec: TypedVec<RowId, f64> = TypedVec::from_vec(vec![1.0, 2.0, 3.0]);
//! let slice: &TypedSlice<RowId, f64> = vec.as_slice();
//!
//! // Safe indexing with custom type
//! let first = slice[RowId::ZERO];
//! ```
//!
//! ### TypedArray
//!
//! A fixed-size array with typed indexing. The array length `N` is checked at compile time
//! to ensure it fits within the index type's range. See [`TypedArray`](crate::typed_array::TypedArray) for the full API.
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_array::TypedArray;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct PixelIdx(u8);
//!
//! let mut pixels: TypedArray<PixelIdx, [u8; 3], 4> = TypedArray::default();
//! pixels[PixelIdx::ZERO] = [255, 0, 0]; // Red
//! pixels[PixelIdx(1)] = [0, 255, 0]; // Green
//! ```
//!
//! ### TypedArrayVec
//!
//! A fixed-capacity vector ideal for embedded systems. It never allocates after creation.
//! See [`TypedArrayVec`](crate::typed_array_vec::TypedArrayVec) for the full API.
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_array_vec::TypedArrayVec;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct BufferIndex(u8);
//!
//! let mut buffer: TypedArrayVec<BufferIndex, u8, 16> = TypedArrayVec::new();
//! buffer.push(42);
//! assert_eq!(buffer.len().to_raw_index(), 1);
//! ```
//!
//! A `TypedArrayVec<u8, u8, 3>` is only 4 bytes (3 bytes for data + 1 byte for length).
//!
//! ## Memory-Efficient Indices
//!
//! Using smaller integer types reduces memory when storing many indices:
//!
//! ```
//! # use index_type::IndexType;
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct SmallIndex(u8); // Only 1 byte per index!
//!
//! println!("SmallIndex: {} bytes", std::mem::size_of::<SmallIndex>());
//! println!("u32 index: {} bytes", std::mem::size_of::<u32>());
//! ```
//!
//! For collections with at most 255 elements, `u8` saves 75% memory compared to `u32`.
//!
//! ## NonZero Indices and Niche Optimization
//!
//! Using [`NonZero`](core::num::NonZero) types enables niche optimization, where `Option<Index>`
//! has the same size as `Index`:
//!
//! ```
//! use index_type::IndexType;
//! use core::num::NonZeroU32;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct SafeId(NonZeroU32);
//!
//! // Option<SafeId> takes only 4 bytes, not 8!
//! assert_eq!(std::mem::size_of::<SafeId>(), 4);
//! assert_eq!(std::mem::size_of::<Option<SafeId>>(), 4);
//! ```
//!
//! ## Range Iterators
//!
//! Standard Rust ranges require the unstable [`Step`](core::iter::Step) trait. This crate provides
//! [`TypedRangeIterExt`](crate::typed_range_iter::TypedRangeIterExt) for iterating over ranges with custom index types:
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_range_iter::TypedRangeIterExt;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct MyIdx(u32);
//!
//! let start = MyIdx(5);
//! let end = MyIdx(10);
//!
//! for idx in (start..end).iter() {
//! println!("{:?}", idx);
//! }
//! ```
//!
//! ## Typed Enumerate
//!
//! Use [`TypedIteratorExt`](crate::typed_enumerate::TypedIteratorExt) to enumerate any iterator with typed indices:
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_enumerate::TypedIteratorExt;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct RowIdx(u32);
//!
//! let pairs: Vec<_> = ["a", "b", "c"]
//! .into_iter()
//! .typed_enumerate::<RowIdx>()
//! .collect();
//!
//! assert_eq!(pairs[1].0, RowIdx(1));
//! assert_eq!(pairs[1].1, "b");
//! ```
//!
//! ## Macros
//!
//! Convenience macros for creating typed collections:
//!
//! ```
//! use index_type::{typed_vec, typed_array, typed_array_vec, typed_slice, typed_slice_mut, IndexType};
//! use index_type::typed_vec::TypedVec;
//! use index_type::typed_array::TypedArray;
//! use index_type::typed_array_vec::TypedArrayVec;
//! use index_type::typed_slice::TypedSlice;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct MyIndex(u32);
//!
//! // Create a TypedVec
//! let v: TypedVec<MyIndex, i32> = typed_vec![1, 2, 3];
//!
//! // Create a TypedArray
//! let a: TypedArray<MyIndex, i32, 3> = typed_array![1, 2, 3];
//!
//! // Create a TypedArrayVec
//! let av: TypedArrayVec<MyIndex, u8, 4> = typed_array_vec![1, 2, 3, 4];
//!
//! // Create a TypedSlice reference
//! let s: &TypedSlice<MyIndex, i32> = typed_slice![1, 2, 3];
//! ```
//!
//! ## Error Handling
//!
//! Operations that can fail due to index overflow return `Result` types:
//!
//! ```
//! use index_type::IndexType;
//! use index_type::typed_vec::TypedVec;
//!
//! #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! struct MyIndex(u8); // MAX_RAW_INDEX = 255
//!
//! let mut vec: TypedVec<MyIndex, i32> = TypedVec::new();
//!
//! // Fill up to capacity
//! for i in 0..255 {
//! vec.try_push(i).unwrap();
//! }
//!
//! // This fails gracefully
//! assert!(vec.try_push(255).is_err());
//! ```
//!
//! ## no_std Compatibility
//!
//! This crate is `no_std` compatible. The `alloc` feature (enabled by default) enables
//! heap-allocated collections ([`TypedVec`](crate::typed_vec::TypedVec) and related macros).
//!
//! For pure `no_std` environments without heap allocation, disable the `alloc` feature:
//!
//! ```toml
//! [dependencies]
//! index_type = { version = "...", default-features = false }
//! ```
//!
pub use crateGenericIndexTooBigError;
pub extern crate alloc;
pub use ;
/// A trait for types that can be used as indices into typed collections.
///
/// This trait is the foundation of the crate. It is implemented for primitive unsigned integer
/// types (`u8`, `u16`, `u32`, `u64`, `usize`) and their [`NonZero`](core::num::NonZero) variants. Custom index types
/// should be defined using the `#[derive(IndexType)]` macro, which implements this trait for a
/// newtype struct.
///
/// # Safety
///
/// Do not implement directly; use `#[derive(IndexType)]` instead.
///
/// # Index vs Raw Index
///
/// The distinction between "index" and "raw index" is important for [`NonZero`](core::num::NonZero) types.
/// For a regular type like `u8`:
/// - Raw index 0 maps to `u8::ZERO` (0)
/// - Raw index 255 maps to `u8::MAX` (255)
///
/// For a [`NonZero`](core::num::NonZero) type like `NonZeroU8`:
/// - Raw index 0 maps to `NonZeroU8::new_unchecked(1)` (the minimum valid value)
/// - Raw index 254 maps to `NonZeroU8::new_unchecked(255)` (the maximum valid value)
/// - Raw index 255 is **invalid** because it would overflow when adding 1 to get the inner value
///
/// This design allows `Option<NonZeroU8>` to occupy a single byte (niche optimization).
///
/// # Example
///
/// ```
/// use index_type::IndexType;
///
/// #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// struct MyIndex(u32);
///
/// let idx = MyIndex::ZERO;
/// let next = MyIndex::try_from_raw_index(5).unwrap();
/// assert_eq!(next.to_raw_index(), 5);
/// ```
pub unsafe
/// A trait for scalar types used with [`IndexType`].
///
/// This trait is implemented for unsigned integer types (`u8`, `u16`, `u32`, `u64`, `usize`)
/// and provides the arithmetic operations needed for index manipulation.
///
/// # Safety
///
/// Implementations must be for unsigned integer types whose size is less than or equal to `usize`.
pub unsafe
/// A trait for errors indicating that an index value is too large.
///
/// This trait is implemented by error types returned when index operations would
/// exceed the maximum representable value for an [`IndexType`].
///
/// # Example
///
/// ```
/// use index_type::IndexType;
/// use index_type::GenericIndexTooBigError;
///
/// #[derive(IndexType, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// #[index_type(error = GenericIndexTooBigError)]
/// struct MyIndex(u32);
///
/// let result = MyIndex::try_from_raw_index(u32::MAX as usize + 1);
/// assert!(result.is_err());
/// ```