Skip to content

Commit e87ae95

Browse files
authored
docs: clarify ByteSpan slicing and safe range access (#9805)
1 parent b5c6d86 commit e87ae95

File tree

1 file changed

+21
-7
lines changed
  • docs/reference/src/components/cairo/modules/language_constructs/pages

1 file changed

+21
-7
lines changed

docs/reference/src/components/cairo/modules/language_constructs/pages/string-types.adoc

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,9 @@ Use `for byte in s.span()` if you need to keep using the ByteArray afterward.
129129

130130
=== Slicing with ByteSpan
131131

132-
IMPORTANT: ByteSpan is an experimental feature behind the `byte-span` feature flag. Enable it to
133-
use range-based slicing.
132+
IMPORTANT: ByteSpan is an experimental feature behind the `byte-span` feature flag. Range indexing
133+
syntax such as `span[0..5]` and `span[6..=10]` requires this feature. The safe `.get(range)` API
134+
for ranges additionally requires the `corelib-get-trait` feature.
134135

135136
Use `span()` to create a ByteSpan view for slicing operations:
136137

@@ -139,14 +140,27 @@ Use `span()` to create a ByteSpan view for slicing operations:
139140
let s: ByteArray = "Hello World";
140141
let span = s.span();
141142
142-
// Range slicing (requires byte-span feature)
143-
let slice = span[0..5]; // Returns ByteSpan
144-
let slice2 = span[6..=10]; // Returns ByteSpan
143+
// Range slicing with half-open and inclusive ranges.
144+
let hello = span[0..5]; // Returns ByteSpan for "Hello"
145+
let world = span[6..=10]; // Returns ByteSpan for "World"
145146
146-
// Convert ByteSpan back to ByteArray if needed
147-
let hello: ByteArray = slice.to_byte_array();
147+
// Convert ByteSpan back to ByteArray if needed.
148+
let hello_bytes: ByteArray = hello.to_byte_array();
148149
----
149150

151+
Range indexing with `[]` panics with `Index out of bounds` when the requested range is invalid
152+
or outside the span. If you want fallible slicing, use `get()`:
153+
154+
[source,cairo]
155+
----
156+
// Safe range slicing (requires `corelib-get-trait`)
157+
let hello = span.get(0..5); // Option<ByteSpan>
158+
let world = span.get(6..=10); // Option<ByteSpan>
159+
let missing = span.get(20..25); // Option::None
160+
----
161+
162+
`get()` also works with a single `usize` index and returns `Option<u8>`.
163+
150164
== String Formatting
151165

152166
Cairo provides powerful formatting capabilities through the `format!` macro:

0 commit comments

Comments
 (0)