summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-31 01:15:25 +0000
committerZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-31 01:15:25 +0000
commit856c9fe56b412779e045ef86a767b93d5c7f563b (patch)
tree6f851bb9bf300970c4a0d7186db0de86e510a18d /docs
parent03a6a57f500ee4230ce2cee887866b3850ed7ed9 (diff)
Improvements for slice + better iteration for arrays
Diffstat (limited to 'docs')
-rw-r--r--docs/std/slice.md90
1 files changed, 90 insertions, 0 deletions
diff --git a/docs/std/slice.md b/docs/std/slice.md
new file mode 100644
index 0000000..b70c5fe
--- /dev/null
+++ b/docs/std/slice.md
@@ -0,0 +1,90 @@
+# Standard Library: Slice (`std/slice.zc`)
+
+`Slice<T>` is a lightweight, non-owning view into a contiguous sequence of elements. It's particularly useful for working with fixed-size arrays and enabling iteration.
+
+## Usage
+
+```zc
+import "std/slice.zc"
+
+fn main() {
+ let arr: int[5] = [1, 2, 3, 4, 5];
+
+ // Direct iteration (Recommended)
+ for val in arr {
+ println "{val}";
+ }
+
+ // Manual slice creation (for partial views or specific needs)
+ let slice = Slice<int>::from_array((int*)(&arr), 5);
+ for val in slice {
+ println "{val}";
+ }
+}
+```
+
+## Structure
+
+```zc
+struct Slice<T> {
+ data: T*;
+ len: usize;
+}
+```
+
+## Methods
+
+### Construction
+
+| Method | Signature | Description |
+| :--- | :--- | :--- |
+| **from_array** | `Slice<T>::from_array(arr: T*, len: usize) -> Slice<T>` | Creates a slice view over an array. |
+
+### Iteration
+
+| Method | Signature | Description |
+| :--- | :--- | :--- |
+| **iterator** | `iterator(self) -> SliceIter<T>` | Returns an iterator for `for-in` loops. |
+
+`SliceIter<T>` implements the iterator protocol with a `next() -> Option<T>` method.
+
+### Access & Query
+
+| Method | Signature | Description |
+| :--- | :--- | :--- |
+| **length** | `length(self) -> usize` | Returns the number of elements. |
+| **is_empty** | `is_empty(self) -> bool` | Returns true if length is 0. |
+| **get** | `get(self, idx: usize) -> Option<T>` | Returns the element at index, or None if out of bounds. |
+| **at** | `at(self, idx: usize) -> Option<T>` | Alias for `get`. |
+
+## Examples
+
+### Iterating over fixed-size arrays
+
+```zc
+let numbers: int[3] = [10, 20, 30];
+let slice = Slice<int>::from_array((int*)(&numbers), 3);
+
+for n in slice {
+ println "Number: {n}";
+}
+```
+
+### Safe indexed access
+
+```zc
+let arr: int[3] = [1, 2, 3];
+let slice = Slice<int>::from_array((int*)(&arr), 3);
+
+let opt = slice.get(1);
+if (!opt.is_none()) {
+ println "Value: {opt.unwrap()}"; // Prints: Value: 2
+}
+```
+
+## Notes
+
+- `Slice<T>` does not own its data - it's just a view
+- No memory management needed (no `free()` method)
+- Must specify the generic type explicitly: `Slice<int>`, `Slice<String>`, etc.
+- The array pointer cast `(T*)(&arr)` is required for fixed-size arrays