godot-rust / godot-rust/gdext

Problem with usize/i64 mismatch for indices in custom array-like APIs

Open
#1,604 4 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Rust
Stars
5.2k
Forks
312
Avg merge
12h 59m
Merged PRs (30d)
9

Description

I have a Resource that provides an API to access its two arrays as if they were continuous (one is created manually and the other one is baked). On the Rust side of things I'd like to have index be a `usize` - which both fits logically and is consistent with other index types godot-rust exposes (e.g. those of `PackedArray`) - yet `usize` can't be used in Godot-facing interfaces due to type restrictions and i64 must be used instead. Since there's no function renaming or overloading available I currently have to deal with a rather silly workaround:

```rust
#[derive(GodotClass)]
#[class(init, tool, base = Resource)]
pub(crate) struct MyResource {
#[var(pub)]
#[export]
manual_points: PackedVector3Array,

#[var(pub)]
#[export]
generated_points: PackedVector3Array,
}

#[godot_api]
impl MyResource {
pub fn get_point_rs(&self, index: usize) -> Option {
self.manual_points
.get(index)
.or_else(|| self.generated_points.get(index - self.manual_points.len()))
}

#[func]
fn get_point(&self, index: i64) -> Result {
let index = index.try_into()?;
Ok(self.get_point_rs(index).ok_or("Tried to get a non-existent point")?)
}

pub fn get_point_count_rs(&self) -> usize {
self.manual_points.len() + self.generated_points.len()
}

#[func]
fn get_point_count(&self) -> i64 {
self.get_point_count_rs().try_into().unwrap()
}
}
```

I see two ways out of this:

1. Implement `ToGodot`/`FromGodot` for `usize` - debatable due to conversion being able to fail, but would eliminate the need for separate functions in this scenario
2. Allow overriding function names in `#[func]` (e.g. `#[func(name = "new_name")]`) so that Rust and GDScript versions of functions could keep identical names

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.