Skip to content

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

Description

@v1993

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:

#[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<Vector3> {
		self.manual_points
			.get(index)
			.or_else(|| self.generated_points.get(index - self.manual_points.len()))
	}

	#[func]
	fn get_point(&self, index: i64) -> Result<Vector3, Unexpected> {
		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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionNot a problem with the library, but a question regarding usage.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions