summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--docs/std/vec.md1
-rw-r--r--examples/algorithms/dfs.zc4
-rw-r--r--std/vec.zc8
3 files changed, 11 insertions, 2 deletions
diff --git a/docs/std/vec.md b/docs/std/vec.md
index 7bc7c05..525e179 100644
--- a/docs/std/vec.md
+++ b/docs/std/vec.md
@@ -63,6 +63,7 @@ struct Vec<T> {
| Method | Signature | Description |
| :--- | :--- | :--- |
| **get** | `get(self, idx: usize) -> T` | Returns a copy of the element at `idx`. Panics if out of bounds. |
+| **get_ref** | `get_ref(self, idx: usize) -> T*` | Returns a pointer to the element at `idx`. Panics if out of bounds. Useful for avoiding copies. |
| **set** | `set(self, idx: usize, item: T)` | Overwrites the element at `idx`. Panics if out of bounds. |
| **first** | `first(self) -> T` | Returns a copy of the first element. Panics if empty. |
| **last** | `last(self) -> T` | Returns a copy of the last element. Panics if empty. |
diff --git a/examples/algorithms/dfs.zc b/examples/algorithms/dfs.zc
index 2d4670c..e51acfa 100644
--- a/examples/algorithms/dfs.zc
+++ b/examples/algorithms/dfs.zc
@@ -32,7 +32,7 @@ impl Graph {
visited[vertex] = true;
order.push(vertex);
- let neighbors = self.adj_list.data[vertex];
+ let neighbors = self.adj_list.get_ref(vertex);
let neighbor_count = (int)neighbors.len;
for i in 0..neighbor_count {
let neighbor = neighbors.data[i];
@@ -83,7 +83,7 @@ impl Graph {
visited.data[vertex] = true;
order.push(vertex);
- let neighbors = self.adj_list.data[vertex];
+ let neighbors = self.adj_list.get_ref(vertex);
let i = (int)neighbors.len - 1;
while i >= 0 {
let neighbor = neighbors.data[i];
diff --git a/std/vec.zc b/std/vec.zc
index 16f23a7..59142d7 100644
--- a/std/vec.zc
+++ b/std/vec.zc
@@ -190,6 +190,14 @@ impl Vec<T> {
return self.data[idx];
}
+ fn get_ref(self, idx: usize) -> T* {
+ if (idx >= self.len) {
+ !"Panic: Index out of bounds";
+ exit(1);
+ }
+ return &self.data[idx];
+ }
+
fn last(self) -> T {
if (self.len == 0) {
!"Panic: last called on empty Vec";