Skip to content

Commit

Permalink
fix: create java values before throwing exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
Apehum committed Nov 22, 2023
1 parent 7e04bec commit b715ce9
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 2 deletions.
6 changes: 5 additions & 1 deletion rust/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ pub unsafe extern "system" fn Java_com_plasmoverse_opus_OpusDecoder_decodeNative
match decoder_decode(&mut env, decoder, encoded) {
Ok(decoded) => decoded,
Err(exception) => {
let result = env.new_short_array(0)
.expect("Couldn't create java short array");

env.throw_new_exception(exception);
env.new_short_array(0).expect("") // todo: ???

result
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion rust/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,12 @@ pub unsafe extern "system" fn Java_com_plasmoverse_opus_OpusEncoder_encodeNative
match encoder_encode(&mut env, encoder, samples) {
Ok(decoded) => decoded,
Err(exception) => {
let result = env.new_byte_array(0)
.expect("Couldn't create java byte array");

env.throw_new_exception(exception);
env.new_byte_array(0).expect("") // todo: ???

result
}
}
}
Expand Down
1 change: 1 addition & 0 deletions rust/src/util/exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub trait JavaExceptions {
impl<'local> JavaExceptions for JNIEnv<'local> {

fn throw_new_exception(&mut self, exception: JavaException) {
println!("{} {}", exception.class, exception.message);
let _ = self.throw_new(exception.class, exception.message);
}
}
28 changes: 28 additions & 0 deletions src/test/java/com/plasmoverse/opus/OpusTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertThrows;

public final class OpusTest {

@Test
Expand Down Expand Up @@ -42,4 +44,30 @@ public void decode() throws Exception {
// Closes the decoder, releasing allocated resources
decoder.close();
}

@Test
public void encodeBadFrame() throws Exception {
short[] badFrame = new short[444];

OpusEncoder encoder = OpusEncoder.create(48_000, false, 960, OpusMode.VOIP);

assertThrows(OpusException.class, () -> {
encoder.encode(badFrame);
});

encoder.close();
}

@Test
public void decodeBadFrame() throws Exception {
byte[] badFrame = new byte[3000];

OpusDecoder decoder = OpusDecoder.create(48_000, false, 960);

assertThrows(OpusException.class, () -> {
decoder.decode(badFrame);
});

decoder.close();
}
}

0 comments on commit b715ce9

Please sign in to comment.