Skip to content

Commit 262c1cf

Browse files
committed
Add string lastindexof
1 parent 18c88f0 commit 262c1cf

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

java_runtime/src/classes/java/lang/string.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ impl String {
6060
JavaMethodProto::new("indexOf", "(II)I", Self::index_of_from, Default::default()),
6161
JavaMethodProto::new("indexOf", "(Ljava/lang/String;)I", Self::index_of_string, Default::default()),
6262
JavaMethodProto::new("indexOf", "(Ljava/lang/String;I)I", Self::index_of_string_from, Default::default()),
63+
JavaMethodProto::new("lastIndexOf", "(I)I", Self::last_index_of, Default::default()),
6364
JavaMethodProto::new("trim", "()Ljava/lang/String;", Self::trim, Default::default()),
6465
JavaMethodProto::new("startsWith", "(Ljava/lang/String;)Z", Self::starts_with, Default::default()),
6566
JavaMethodProto::new("startsWith", "(Ljava/lang/String;I)Z", Self::starts_with_offset, Default::default()),
@@ -373,6 +374,21 @@ impl String {
373374
Ok(index.unwrap_or(-1))
374375
}
375376

377+
async fn last_index_of(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, ch: i32) -> Result<i32> {
378+
tracing::debug!("java.lang.String::lastIndexOf({:?}, {:?})", &this, ch);
379+
380+
let this_string = JavaLangString::to_rust_string(jvm, &this.clone()).await?;
381+
382+
let index = this_string
383+
.chars()
384+
.collect::<Vec<_>>() // TODO i think we don't need collect..
385+
.into_iter()
386+
.rposition(|x| x as u32 == ch as u32)
387+
.map(|x| x as i32);
388+
389+
Ok(index.unwrap_or(-1))
390+
}
391+
376392
async fn trim(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<Self>> {
377393
tracing::debug!("java.lang.String::trim({:?})", &this);
378394

java_runtime/tests/classes/java/lang/test_string.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,21 @@ async fn test_starts_with() -> Result<()> {
130130

131131
Ok(())
132132
}
133+
134+
#[tokio::test]
135+
async fn test_last_index_of() -> Result<()> {
136+
let jvm = test_jvm().await?;
137+
138+
let string = JavaLangString::from_rust_string(&jvm, "456 가나다 456").await?;
139+
140+
let index: i32 = jvm.invoke_virtual(&string, "lastIndexOf", "(I)I", (b'4' as i32,)).await?;
141+
assert_eq!(index, 8);
142+
let index: i32 = jvm.invoke_virtual(&string, "lastIndexOf", "(I)I", (b'5' as i32,)).await?;
143+
assert_eq!(index, 9);
144+
let index: i32 = jvm.invoke_virtual(&string, "lastIndexOf", "(I)I", (b'6' as i32,)).await?;
145+
assert_eq!(index, 10);
146+
let index: i32 = jvm.invoke_virtual(&string, "lastIndexOf", "(I)I", (b'7' as i32,)).await?;
147+
assert_eq!(index, -1);
148+
149+
Ok(())
150+
}

0 commit comments

Comments
 (0)