Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+1
View File
@@ -0,0 +1 @@
crate::bind_java_type! { pub JByteBuffer => "java.nio.ByteBuffer" }
+22
View File
@@ -0,0 +1,22 @@
crate::bind_java_type! {
pub JCharSequence => "java.lang.CharSequence",
methods {
/// Returns the character at the specified index.
///
/// # Throws
/// - `IndexOutOfBoundsException` - if the index is negative or not less than the length of
/// this sequence.
fn char_at(index: jint) -> jchar,
/// Returns the length of this character sequence.
fn length() -> jint,
/// Returns a new character sequence that is a subsequence of this sequence.
///
/// The subsequence starts with the character at the specified index and ends with the
/// character at index end - 1.
///
/// # Throws
/// - `IndexOutOfBoundsException` - if start or end are negative, if end is greater than
/// length(), or if start is greater than end.
fn sub_sequence(start: jint, end: jint) -> JCharSequence,
}
}
+72
View File
@@ -0,0 +1,72 @@
use crate::jni_str;
crate::bind_java_type! {
pub JClass => "java.lang.Class",
__jni_core = true,
__sys_type = jclass,
hooks {
load_class = |env, _loader_context, _initialize| {
// As a special-case; we ignore loader_context and use `env.find_class` just to be clear
// that there's no risk of recursion. (`LoaderContext::load_class` depends on the
// `JClassAPI`)
env.find_class(const { jni_str!("java/lang/Class") })
}
},
methods {
/// Returns the name of the class.
///
/// This returns a binary name, such as `java.lang.String`.
///
/// If the class represents a primitive type then this will return the same letter used for
/// that primitive in a JNI type signature - such as `I` for `int`.
///
/// Similarly; if the class represents an array type the name will have a prefix of one or
/// more "[" characters, followed by the binary name of the element type.
fn get_name() -> JString,
/// Finds a class by its fully-qualified binary name or array descriptor.
///
/// This is a method binding for `java.lang.Class.forName(String)`
///
/// This method is used to locate a class by its name, which may be either a fully-qualified
/// binary name (e.g., `java.lang.String`) or an array descriptor (e.g., `[Ljava.lang.String;`).
///
/// Note: that unlike `FindClass` the names use dot (`.`) notation instead of slash (`/`) notation.
///
/// # Throws
///
/// This method may throw a `ClassNotFoundException` if the class cannot be found.
static fn for_name(name: JString) -> JClass,
/// Finds a class by its fully-qualified binary name or array descriptor.
///
/// This is a method binding for `java.lang.Class.forName(String, boolean, ClassLoader)`
///
/// This method is used to locate a class by its name (via the ClassLoader) which may be either
/// a fully-qualified binary name (e.g., `java.lang.String`) or an array descriptor (e.g.,
/// `[Ljava.lang.String;`).
///
/// Note: that unlike `FindClass` the names use dot (`.`) notation instead of slash (`/`) notation.
///
/// If initialized is true, the class will be initialized before it is returned.
///
/// # Throws
///
/// This method may throw a `ClassNotFoundException` if the class cannot be found.
static fn for_name_with_loader {
name = "forName",
sig = (name: JString, initialize: bool, loader: JClassLoader) -> JClass,
},
/// Returns the class loader for this class.
///
/// This is used to find the class loader that was responsible for loading this class.
///
/// It may return null for bootstrap classes or objects representing primitive types not associated with a class loader.
///
/// # Throws
///
/// `SecurityException` if the class loader cannot be accessed.
fn get_class_loader() -> JClassLoader
}
}
+32
View File
@@ -0,0 +1,32 @@
use crate::jni_str;
crate::bind_java_type! {
pub JClassLoader => "java.lang.ClassLoader",
hooks {
load_class = |env, _loader_context, _initialize| {
// As a special-case; we ignore loader_context and use `env.find_class` just to be clear that there's no risk of
// recursion. (`LoaderContext::load_class` depends on the `JClassLoaderAPI`)
env.find_class(const { jni_str!("java/lang/ClassLoader") })
}
},
methods {
/// Gets the system class loader.
///
/// This is a method binding for `java.lang.ClassLoader.getSystemClassLoader()`.
///
/// # Throws
///
/// - `SecurityException` if a security manager doesn't allow access to the system class loader.
/// - `IllegalStateException` if called recursively while the system class loader is being initialized.
/// - `Error` if the system class loader could not be created according to the system property "java.system.class.loader".
static fn get_system_class_loader() -> JClassLoader,
/// Loads a class by name using this class loader.
///
/// This is a Java method binding for `java.lang.ClassLoader.loadClass(String)`.
///
/// # Throws
///
/// `ClassNotFoundException` if the class cannot be found.
fn load_class(name: JString) -> JClass,
}
}
+60
View File
@@ -0,0 +1,60 @@
crate::bind_java_type! {
pub JCollection => "java.util.Collection",
methods {
/// Adds the given element to this set if it is not already present
///
/// Returns `true` if the collection was modified. Returns false if the collection already contains the element and
/// the collection doesn't allow duplicates.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the add operation is not supported
/// - `ClassCastException` - if the element type isn't compatible with the collection
/// - `NullPointerException` - if the given element is null and the collection does not allow null values
/// - `IllegalArgumentException` - if the element has a property that prevents it from being added to this collection
/// - `IllegalStateException` - if the element cannot be added due to the current state of the collection
fn add(element: JObject) -> bool,
/// Removes the given element from this collection if it is present
///
/// Returns true if the element was contained in the collection and removed, false otherwise.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported
/// - `ClassCastException` - if the element type isn't compatible with the collection
/// - `NullPointerException` - if the given element is null and the collection does not allow null values
fn remove(element: JObject) -> bool,
/// Removes all of the elements from this collection.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the clear operation is not supported
fn clear() -> (),
/// Checks if the given element is present in this set.
///
/// Returns `true` if the element is present, `false` otherwise.
///
/// # Throws
///
/// - `ClassCastException` - if the element type isn't compatible with the set
/// - `NullPointerException` - if the given element is null and the set does not allow null values
fn contains(element: JObject) -> bool,
/// Returns the number of elements in this collection.
///
/// Returns [i32::MAX] if the collection size is too large to be represented as an i32.
fn size() -> jint,
/// Returns `true` if this collection contains no elements.
fn is_empty() -> bool,
/// Returns an iterator (`java.util.Iterator`) over the elements in this collection.
fn iterator() -> JIterator,
/// Returns an array containing all of the elements in this collection.
fn to_array() -> JObject[],
}
}
+62
View File
@@ -0,0 +1,62 @@
use crate::{
env::Env,
errors::{Error, Result},
objects::JObject,
};
crate::bind_java_type! {
pub JIterator => "java.util.Iterator",
methods {
/// Returns true if the iteration has more elements.
fn has_next() -> bool,
priv fn _next() -> JObject,
/// Removes the current element from the iteration (if supported by the iterator)
///
/// This can only be called once after [Self::next] is called.
///
/// # Throws
///
/// - `UnsupportedOperationException` if the operation is not supported.
/// - `IllegalStateException` if the iterator is in an invalid state (i.e [Self::next] has not been called).
fn remove()
}
}
impl<'local> JIterator<'local> {
/// Returns the next element in the iteration, if it exists.
///
/// Returns `Some(element)` if the iteration has more elements, or `None` if
/// it has reached the end.
///
/// This is like [`std::iter::Iterator::next`], but requires a parameter of
/// type `&mut Env` in order to call into Java.
///
/// Any exceptions thrown are assumed to be a `NoSuchElementException` and
/// are caught + cleared before returning `None`.
///
/// ## Beware of creating excessive local references in the current JNI stack frame
///
/// This method creates a new local reference. To prevent excessive memory
/// usage or overflow errors (when called repeatedly in a loop), the local
/// reference should be deleted using [`Env::delete_local_ref`] or wrapped
/// with [`crate::objects::IntoAuto::auto`] before the next loop iteration.
/// Alternatively, if the collection is known to have a small, predictable
/// size, the loop could be wrapped in [`Env::with_local_frame`] to delete
/// all of the local references at once.
pub fn next<'env_local>(
&self,
env: &mut Env<'env_local>,
) -> Result<Option<JObject<'env_local>>> {
match self._next(env) {
Ok(v) => Ok(Some(v)),
Err(Error::JavaException) => {
// Assume `NoSuchElementException` is thrown
env.exception_clear();
Ok(None)
}
Err(e) => Err(e),
}
}
}
+144
View File
@@ -0,0 +1,144 @@
use crate::{
Env,
errors::*,
objects::{JIterator, JObject, Reference},
sys::jint,
};
crate::bind_java_type! {
pub JList => "java.util.List",
is_instance_of {
collection = JCollection,
},
methods = {
/// Returns the list element at the given `idx`
///
/// # Throws
///
/// - `IndexOutOfBoundsException` - if the index is out of range (index < 0 || index >= size())
fn get(index: jint) -> JObject,
/// Insert an element at a specific index
fn insert {
name = "add",
sig = (index: jint, element: JObject) -> void,
},
/// Remove an element from the list by index
///
/// Returns the removed element
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported
/// - `IndexOutOfBoundsException` - if the index is out of bounds
fn remove(index: jint) -> JObject,
}
}
impl<'local> JList<'local> {
/// Cast a local reference to a `JList`
///
/// See [`JList::cast_local`] for more information.
#[deprecated(
since = "0.22.0",
note = "use JList::cast_local instead or Env::new_cast_local_ref/cast_local/as_cast_local or Env::new_cast_global_ref/cast_global/as_cast_global"
)]
pub fn from_env<'any_local>(
env: &mut Env<'_>,
obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
) -> Result<JList<'any_local>> {
env.cast_local::<JList>(obj)
}
/// Append an element to the list
pub fn add(&self, env: &Env, value: &JObject) -> Result<bool> {
self.as_collection().add(env, value)
}
/// Removes the first occurrence of `value` from this [JList], if it's present.
///
/// Returns `true` if an element was removed.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported
/// - `ClassCastException` - if the element type isn't compatible with the set
/// - `NullPointerException` - if the given element is null and the set does not allow null values
pub fn remove_item(&self, env: &Env<'_>, value: &JObject) -> Result<bool> {
self.as_collection().remove(env, value)
}
/// Removes all of the elements from this list.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the clear operation is not supported
pub fn clear(&self, env: &Env<'_>) -> Result<()> {
self.as_collection().clear(env)
}
/// Get the size of the list
pub fn size(&self, env: &Env) -> Result<jint> {
self.as_collection().size(env)
}
/// Returns `true` if this list is empty.
pub fn is_empty(&self, env: &Env<'_>) -> Result<bool> {
self.as_collection().is_empty(env)
}
/// Pop the last element from the list
///
/// # Deprecated
///
/// Note that this is a non-standard utility API that first calls `size()`
/// to determine the last index and so it's inherently race condition-prone
/// and it's not recommended to use.
#[deprecated(
since = "0.22.0",
note = "java.util.List has no pop() method. This non-standard utility will be removed from a future version"
)]
pub fn pop<'other_local_2>(
&self,
env: &mut Env<'other_local_2>,
) -> Result<Option<JObject<'other_local_2>>> {
let size = self.size(env)?;
if size == 0 {
return Ok(None);
}
self.remove(env, size - 1).map(Some)
}
/// Returns an iterator (`java.util.Iterator`) over the elements in this
/// list.
///
/// The returned iterator does not implement [`std::iter::Iterator`] and
/// cannot be used with a `for` loop. This is because its `next` method uses
/// a `&mut Env` to call the Java iterator. Use a `while let` loop instead:
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::{JList, JObject}};
/// #
/// # fn example(env: &mut Env, list: JList) -> Result<()> {
/// use jni::objects::IntoAuto as _; // for .auto()
/// let mut iterator = list.iter(env)?;
///
/// while let Some(obj) = iterator.next(env)? {
/// let obj = obj.auto(); // Wrap as Auto<T> to avoid leaking while iterating
///
/// // Do something with `obj` here.
/// }
/// # Ok(())
/// # }
/// ```
///
/// Each call to `next` creates a new local reference. To prevent excessive
/// memory usage or overflow errors, the local reference should be deleted
/// using [`Env::delete_local_ref`] or wrapped with
/// [`crate::objects::IntoAuto::auto`] before the next loop iteration.
/// Alternatively, if the list is known to have a small, predictable size,
/// the loop could be wrapped in [`Env::with_local_frame`] to delete all of
/// the local references at once.
pub fn iter<'env_local>(&self, env: &mut Env<'env_local>) -> Result<JIterator<'env_local>> {
self.as_collection().iterator(env)
}
}
+337
View File
@@ -0,0 +1,337 @@
use crate::{
Env,
errors::*,
objects::{JIterator, JObject, Reference},
};
use std::ops::Deref;
#[cfg(doc)]
use crate::objects::JSet;
crate::bind_java_type! {
pub JMap => "java.util.Map",
methods = {
/// Returns the number of key-value mappings in this map
///
/// If the map contains more than `jint::MAX` mappings, returns `jint::MAX`.
fn size() -> jint,
/// Returns `true` if this map contains no key-value mappings
fn is_empty() -> bool,
/// Look up the value for a key
priv fn _get(key: JObject) -> JObject,
/// Get the value for a key, or return the default value if the key is not present
///
/// # Throws
///
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
fn get_or_default(key: JObject, default_value: JObject) -> JObject,
// Associates the specified value with the specified key in this map
priv fn _put(key: JObject, value: JObject) -> JObject,
/// Copies all of the mappings from the specified map to this map
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the putAll operation is not supported by this map
/// - `ClassCastException` - if a key or value in the specified map is of an inappropriate type for this map
/// - `NullPointerException` - if the given map is null, or if a key or value in the specified map is null and this map does not allow null keys or values
/// - `IllegalArgumentException` - if some property of a key or value in the specified map prevents it from being stored by this map
fn put_all(other_map: JMap),
/// If the specified key is not already associated with a value, associate it with the given value.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the `putIfAbsent` operation is not supported by this map
/// - `ClassCastException` - if the key or value are of an inappropriate type for this map
/// - `NullPointerException` - if the key or value is null and this map does not allow null keys or values
/// - `IllegalArgumentException` - if some property of the key or value prevents it from being stored by this map
fn put_if_absent(key: JObject, value: JObject) -> JObject,
/// Remove a mapping for a key from the map
priv fn _remove(key: JObject) -> JObject,
/// Removes the entry for the specified key only if it is currently mapped to the specified value
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported by this map
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
priv fn remove_value {
name = "remove",
sig = (key: JObject, value: JObject) -> bool,
},
/// Replaces the entry for the specified key only if it is currently mapped to some value
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the replace operation is not supported by this map
/// - `ClassCastException` - if the key or value are of an inappropriate type for this map
/// - `NullPointerException` - if the key or value is null and this map does not allow null keys or values
/// - `IllegalArgumentException` - if some property of the value prevents it from being stored by this map
fn replace(key: JObject, value: JObject) -> JObject,
/// Replaces the entry for the specified key only if currently mapped to a given value
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the replace operation is not supported by this map
/// - `ClassCastException` - if the key or value are of an inappropriate type for this map
/// - `NullPointerException` - if the key, new_value or old_value is null and this map does not allow null keys or values
/// - `IllegalArgumentException` - if some property of the value prevents it from being stored by this map
fn replace_value {
name = "replace",
sig = (key: JObject, old_value: JObject, new_value: JObject) -> bool,
},
/// Removes all of the mappings from this map
fn clear(),
/// Determines if the map contains a mapping for the specified key
///
/// # Throws
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
fn contains_key(key: JObject) -> bool,
/// Determines if the map maps one or more keys to the specified value
///
/// # Throws
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
fn contains_value(value: JObject) -> bool,
/// Get a `JSet` view of the mappings contained in this map
///
/// Returns a [JSet] view of the mappings contained in the map, which can be used to iterate over the key/value pairs.
///
/// Also see [JSet::iterator] and [Self::iter]
fn entry_set() -> JSet,
/// Get a `JSet` view of the keys contained in this map
fn key_set() -> JSet,
/// Get a `JCollection` view of the values contained in this map
fn values() -> JCollection,
}
}
impl<'local> JMap<'local> {
/// Cast a local reference to a `JMap`
///
/// See [`JMap::cast_local`] for more information.
#[deprecated(
since = "0.22.0",
note = "use JMap::cast_local instead or Env::new_cast_local_ref/cast_local/as_cast_local or Env::new_cast_global_ref/cast_global/as_cast_global"
)]
pub fn from_env<'any_local>(
env: &mut Env<'_>,
obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
) -> Result<JMap<'any_local>> {
env.cast_local::<JMap>(obj)
}
/// Look up the value for a key.
///
/// Returns `Some` if a non-null value is found and `None` if a null pointer
/// would be returned.
///
/// If the map permits null values, this method cannot distinguish between a
/// key that is not present and a key that is explicitly mapped to `null`.
/// In that case, use [JMap::contains_key] to determine if the key is
/// present.
///
/// # Throws
///
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
pub fn get<'env_local>(
&self,
env: &mut Env<'env_local>,
key: &JObject,
) -> Result<Option<JObject<'env_local>>> {
let value = self._get(env, key)?;
if value.is_null() {
Ok(None)
} else {
Ok(Some(value))
}
}
/// Associates the specified value with the specified key in this map
///
/// Returns `Some` with the old value if the key already existed and `None`
/// if it's a new key.
///
/// If the map permits null values, a `None` return value could also indicate
/// that the previous value associated with the key was explicitly `null`.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the put operation is not supported by this map
/// - `ClassCastException` - if the key or value are of an inappropriate type
/// - `NullPointerException` - if the key or value is null and this map does not allow null keys or values
/// - `IllegalArgumentException` - if some property of the key or value prevents it
pub fn put<'env_local>(
&self,
env: &mut Env<'env_local>,
key: &JObject,
value: &JObject,
) -> Result<Option<JObject<'env_local>>> {
let old = self._put(env, key, value)?;
if old.is_null() {
Ok(None)
} else {
Ok(Some(old))
}
}
/// Remove a mapping for a key from the map
///
/// Returns `Some` with the non-null removed value and `None` if there was no value
/// for the key, or if the removed value was `null`.
///
/// If the map permits null values, this method cannot distinguish between a
/// key that was not present and a key that was explicitly mapped to `null`.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported by this map
/// - `ClassCastException` - if the key is of an inappropriate type for this map
/// - `NullPointerException` - if the key is null and this map does not allow null keys
pub fn remove<'env_local>(
&self,
env: &mut Env<'env_local>,
key: &JObject,
) -> Result<Option<JObject<'env_local>>> {
let old = self._remove(env, key)?;
if old.is_null() {
Ok(None)
} else {
Ok(Some(old))
}
}
/// Get key/value iterator for the map. This is done by getting the
/// `EntrySet` from java and iterating over it.
///
/// The returned iterator does not implement [`std::iter::Iterator`] and
/// cannot be used with a `for` loop. This is because its `next` method uses
/// a `&mut Env` to call the Java iterator. Use a `while let` loop instead:
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::{JMap, JObject}};
/// #
/// # fn example(env: &mut Env, map: JMap) -> Result<()> {
/// use jni::objects::IntoAuto as _; // for .auto()
/// let mut iterator = map.iter(env)?;
///
/// while let Some(entry) = iterator.next(env)? {
/// // Wrap as Auto<T> to avoid leaking while iterating
/// let key = entry.key(env)?.auto();
/// let value = entry.value(env)?.auto();
///
/// // Do something with `key` and `value` here.
/// }
/// # Ok(())
/// # }
/// ```
///
/// Each call to `next` creates two new local references. To prevent
/// excessive memory usage or overflow error, the local references should be
/// deleted using [`Env::delete_local_ref`] or wrapped with
/// [`crate::objects::IntoAuto::auto`] before the next loop iteration.
/// Alternatively, if the map is known to have a small, predictable size,
/// the loop could be wrapped in [`Env::with_local_frame`] to delete all of
/// the local references at once.
pub fn iter<'env_local>(&self, env: &mut Env<'env_local>) -> Result<JMapIter<'env_local>> {
let set = self.entry_set(env)?;
let iterator = set.iterator(env)?;
Ok(JMapIter { iterator })
}
}
crate::bind_java_type! {
pub JMapEntry => "java.util.Map$Entry",
methods = {
/// Get the key of the map entry by calling the `getKey` method.
///
/// # Throws
///
/// May throw `IllegalStateException` if the entry has been removed from the map (depending on implementation)
fn key {
name = "getKey",
sig = () -> JObject,
},
/// Get the value of the map entry by calling the `getValue` method.
///
/// # Throws
///
/// May throw `IllegalStateException` if the entry has been removed from the map (depending on implementation)
fn value {
name = "getValue",
sig = () -> JObject,
},
/// Set the value of the map entry by calling the `setValue` method.
///
/// # Throws
///
/// - `UnsupportedOperationException` if the backing map does not support the put operation
/// - `ClassCastException` if the value is not of a compatible type
/// - `NullPointerException` if a null value is given and the backing map doesn't allow storing null values
/// - `IllegalArgumentException` if the values has a property that prevents it from being stored by the backing map
/// - May throw `IllegalStateException` if the entry has been removed from the map (depending on implementation)
fn set_value(value: JObject) -> JObject,
}
}
/// An iterator over the keys and values in a map. See [`JMap::iter`] for more
/// information.
///
/// This is implemented as a thin wrapper over [`JIterator`] and the only
/// difference is that [JMapIter::next] will yield [JMapEntry] values,
/// (avoiding the need for a runtime type check, compared to using
/// [JIterator::next] followed by [`JMapEntry::cast_local`]).
///
/// This derefs to [`JIterator`].
#[derive(Debug)]
pub struct JMapIter<'iter_local> {
iterator: JIterator<'iter_local>,
}
impl<'local> Deref for JMapIter<'local> {
type Target = JIterator<'local>;
fn deref(&self) -> &Self::Target {
&self.iterator
}
}
impl<'local> JMapIter<'local> {
/// Advances the iterator and returns the next key-value pair in the
/// `java.util.Map`, or `None` if there are no more objects.
///
/// See [`JMap::iter`] for more information.
///
/// This method creates two new local references. To prevent excessive
/// memory usage or overflow error, the local references should be deleted
/// using [`Env::delete_local_ref`] or wrapped with
/// [`crate::objects::IntoAuto::auto`] before the next loop iteration.
/// Alternatively, if the map is known to have a small, predictable size,
/// the loop could be wrapped in [`Env::with_local_frame`] to delete all of
/// the local references at once.
///
/// This method returns:
///
/// * `Ok(Some(_))`: if there was another key-value pair in the map.
/// * `Ok(None)`: if there are no more key-value pairs in the map.
/// * `Err(_)`: if there was an error calling the Java method to get the
/// next key-value pair.
///
/// This is like [`std::iter::Iterator::next`], but requires a parameter of
/// type `&mut Env` in order to call into Java.
pub fn next<'env_local>(
&mut self,
env: &mut Env<'env_local>,
) -> Result<Option<JMapEntry<'env_local>>> {
self.iterator.next(env)?.map_or(Ok(None), |entry| {
// SAFETY: we know that the entrySet iterator will yield Map.Entry values
// so we can safely downcast without needing a runtime type check
let entry = unsafe { JMapEntry::from_raw(env, entry.into_raw()) };
Ok(Some(entry))
})
}
}
+206
View File
@@ -0,0 +1,206 @@
use std::{borrow::Cow, marker::PhantomData, ops::Deref};
use crate::{
Env,
errors::Result,
jni_str,
objects::{Global, JClass, LoaderContext},
strings::JNIStr,
sys::jobject,
};
use super::Reference;
#[cfg(doc)]
use crate::{objects::JString, refs::Weak};
/// A `java.lang.Object` reference, tied to a JNI local reference frame.
///
/// This is a `#[repr(transparent)]` wrapper around a `jobject` JNI reference.
///
/// Since it is `#[repr(transparent)]`, it can be used to capture references
/// passed to native methods while also associating them with a local reference
/// frame lifetime for the method call.
///
/// # Casting
///
/// Most other types in the `objects` module implement `Into<JObject>` or
/// `AsRef<JObject>` to allow easy upcasting to `JObject`.
///
/// For downcasting (i.e converting to a more specific type), with runtime
/// checks, use one of these APIs:
/// - [Env::as_cast]
/// - [Env::new_cast_local_ref]
/// - [Env::cast_local]
/// - [Env::new_cast_global_ref]
/// - [Env::cast_global]
///
/// or look for a `cast_local` API like [`JString::cast_local`].
///
/// # Local Reference Frame Lifetime
///
/// The lifetime `'local` represents the local reference frame that this
/// reference belongs to. See the [`Env`] documentation for more information
/// about local reference frames.
///
/// The lifetime may be `'static` if the reference has a [`Global`] or [`Weak`]
/// wrapper that indicates that the reference is global or weak (i.e it does not
/// belong to a local reference frame).
///
/// Note that an *owned* `JObject` is always a local reference and will never
/// have the `'static` lifetime. [`Global`] does implement
/// <code>[AsRef]&lt;JObject&lt;'static>></code>, but this only yields a
/// *borrowed* `&JObject<'static>`, never an owned `JObject<'static>`.
///
/// Local references belong to a single thread and are not safe to share across
/// threads. This type implements [`Send`] and [`Sync`] if and only if the
/// lifetime `'local` is `'static`.
#[repr(transparent)]
#[derive(Debug)]
pub struct JObject<'local> {
internal: jobject,
lifetime: PhantomData<&'local ()>,
}
unsafe impl Send for JObject<'static> {}
unsafe impl Sync for JObject<'static> {}
impl<'local> AsRef<JObject<'local>> for JObject<'local> {
fn as_ref(&self) -> &JObject<'local> {
self
}
}
impl<'local> AsMut<JObject<'local>> for JObject<'local> {
fn as_mut(&mut self) -> &mut JObject<'local> {
self
}
}
impl ::std::ops::Deref for JObject<'_> {
type Target = jobject;
fn deref(&self) -> &Self::Target {
&self.internal
}
}
pub(crate) struct JObjectAPI {
class: Global<JClass<'static>>,
// no methods cached for now
}
impl JObjectAPI {
pub(crate) fn get(env: &Env<'_>) -> Result<&'static Self> {
static API: std::sync::OnceLock<JObjectAPI> = std::sync::OnceLock::new();
// Fast path: already initialized
if let Some(api) = API.get() {
return Ok(api);
}
// Slow path: Lookup class
// Although this isn't really a concern for java.lang.Object, the
// general pattern here is to avoid holding any lock while performing
// class lookups and API initialization in case we need to be re-entrant
// (e.g. due to class initializers that call back into Rust).
//
// This matters more for other types where we lookup method IDs and
// field IDs which may trigger class initialization, and especially for
// types that register native methods that may need to be registered
// before the class can be initialized and then called during class
// initialization.
// NB: the purpose of the `OnceLock` here is to amortize the cost of
// class lookups and API initialization over multiple uses, so we aren't
// really concerned about a small amount of redundant work if multiple
// threads race here.
let api = env.with_local_frame(8, |env| -> crate::errors::Result<_> {
let class = env.find_class(jni_str!("java/lang/Object"))?;
let class = env.new_global_ref(class)?;
Ok(JObjectAPI { class })
})?;
let _ = API.set(api);
Ok(API.get().unwrap())
}
}
impl JObject<'_> {
/// Creates a [`JObject`] that wraps the given `raw` [`jobject`]
///
/// # Safety
///
/// - `raw` must be a valid raw JNI local reference (or `null`).
/// - There must not be any other owning [`Reference`] wrapper for the same reference.
/// - The local reference must belong to the current thread and not outlive the
/// JNI stack frame associated with the [Env] `'local` lifetime.
pub unsafe fn from_raw<'local>(_env: &Env<'local>, raw: jobject) -> JObject<'local> {
unsafe { JObject::kind_from_raw(raw) }
}
/// Creates a new null reference.
///
/// Null references are always valid and do not belong to a local reference frame. Therefore,
/// the returned `JObject` always has the `'static` lifetime.
pub const fn null() -> JObject<'static> {
JObject {
internal: std::ptr::null_mut(),
lifetime: PhantomData,
}
}
/// Returns the raw JNI pointer.
pub const fn as_raw(&self) -> jobject {
self.internal
}
/// Unwrap to the internal jni type.
pub const fn into_raw(self) -> jobject {
self.internal
}
}
impl std::default::Default for JObject<'_> {
fn default() -> Self {
Self::null()
}
}
// SAFETY: JObject is a transparent jobject wrapper with no Drop side effects
unsafe impl Reference for JObject<'_> {
type Kind<'env> = JObject<'env>;
type GlobalKind = JObject<'static>;
fn as_raw(&self) -> jobject {
self.as_raw()
}
fn class_name() -> Cow<'static, JNIStr> {
Cow::Borrowed(jni_str!("java.lang.Object"))
}
fn lookup_class<'caller>(
env: &Env<'_>,
_loader_context: &LoaderContext,
) -> crate::errors::Result<impl Deref<Target = Global<JClass<'static>>> + 'caller> {
// As a special-case; we ignore loader_context just to be clear that there's no risk of
// recursion. (`LoaderContext::load_class` depends on the `JObjectAPI`)
let api = JObjectAPI::get(env)?;
Ok(&api.class)
}
unsafe fn kind_from_raw<'env>(local_ref: jobject) -> Self::Kind<'env> {
JObject {
internal: local_ref,
lifetime: PhantomData,
}
}
unsafe fn global_kind_from_raw(global_ref: jobject) -> Self::GlobalKind {
JObject {
internal: global_ref,
lifetime: PhantomData,
}
}
}
+393
View File
@@ -0,0 +1,393 @@
use std::{
any::{Any, TypeId},
borrow::Cow,
collections::HashMap,
ops::Deref,
sync::{OnceLock, RwLock},
};
use crate::{
DEFAULT_LOCAL_FRAME_CAPACITY, JavaVM,
env::Env,
errors::{Error, JniError, Result},
objects::{Global, JClass, JObject, LoaderContext, Reference},
strings::{JNIStr, JNIString},
sys::{jobject, jobjectArray},
};
use super::AsJArrayRaw;
/// A `java.lang.Object[]` reference, tied to a JNI local reference frame.
///
/// See the [`JObject`] documentation for more information about reference
/// wrappers, how to cast them, and local reference frame lifetimes.
///
/// # Example
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::{JObjectArray, JString}};
/// # fn example<'local>(env: &mut Env<'local>) -> Result<()> {
/// // Create some strings
/// let str1 = JString::from_str(env, "hello")?;
/// let str2 = JString::from_str(env, "world")?;
///
/// // Create an array of 2 strings, with all elements initially set to str1
/// let arr = JObjectArray::<JString>::new(env, 2, &str1)?;
///
/// // Set the second element to str2
/// arr.set_element(env, 1, &str2)?;
///
/// // Get elements from the array
/// let element0: JString = arr.get_element(env, 0)?;
/// let element1: JString = arr.get_element(env, 1)?;
///
/// assert_eq!(element0.to_string(), "hello");
/// assert_eq!(element1.to_string(), "world");
///
/// // Get the length of the array
/// let len = arr.len(env)?;
/// assert_eq!(len, 2);
/// # Ok(())
/// # }
/// ```
#[repr(transparent)]
#[derive(Debug, Default)]
pub struct JObjectArray<'local, E: Reference + 'local = JObject<'local>> {
array: JObject<'local>,
_marker: std::marker::PhantomData<E>,
}
impl<'local, E: Reference> AsRef<JObjectArray<'local, E>> for JObjectArray<'local, E> {
fn as_ref(&self) -> &JObjectArray<'local, E> {
self
}
}
impl<'local, E: Reference> AsRef<JObject<'local>> for JObjectArray<'local, E> {
fn as_ref(&self) -> &JObject<'local> {
self
}
}
impl<'local, E: Reference> ::std::ops::Deref for JObjectArray<'local, E> {
type Target = JObject<'local>;
fn deref(&self) -> &Self::Target {
&self.array
}
}
impl<'local, E: Reference> From<JObjectArray<'local, E>> for JObject<'local> {
fn from(other: JObjectArray<'local, E>) -> JObject<'local> {
other.array
}
}
unsafe impl<'local, E: Reference> AsJArrayRaw<'local> for JObjectArray<'local, E> {}
pub(crate) struct JObjectArrayAPI<E: Reference> {
class: Global<JClass<'static>>,
_marker: std::marker::PhantomData<E>,
}
// Unlike other Reference types, JObjectArray is generic and we can't simply use
// a static `OnceCell` to cache state since Rust statics can't be generic.
static API_REGISTRY: OnceLock<RwLock<HashMap<TypeId, &'static (dyn Any + Send + Sync)>>> =
OnceLock::new();
impl<E: Reference + Send + Sync> JObjectArrayAPI<E> {
pub(crate) fn get<'any_local>(
env: &Env<'_>,
loader_context: &LoaderContext<'any_local, '_>,
) -> Result<&'static Self> {
let map = API_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()));
let tid = TypeId::of::<Self>();
// Fast path (read-lock)
if let Some(any_ref) = map.read().unwrap().get(&tid) {
// Stored as &'static dyn Any; downcast back to &'static JObjectArrayAPI<E>
return Ok(any_ref
.downcast_ref::<Self>()
.expect("TypeId matched but downcast failed"));
}
// Slow path: do the class lookup and cache
// So we can avoid holding any lock while doing (slow) JNI lookups, then
// in the unlikely case that another thread is also trying to look up
// the same state then we let them race and keep the first one to finish.
let created: JObjectArrayAPI<E> = {
env.with_local_frame(DEFAULT_LOCAL_FRAME_CAPACITY, |env| -> Result<_> {
let class = loader_context.load_class_for_type::<JObjectArray<E>>(env, false)?;
let class = env.new_global_ref(&class)?;
Ok(JObjectArrayAPI {
class,
_marker: std::marker::PhantomData,
})
})?
};
let mut write = map.write().unwrap();
// Another thread might have inserted while we acquired the write lock:
if let Some(any_ref) = write.get(&tid) {
let api = any_ref
.downcast_ref::<Self>()
.expect("TypeId matched but downcast failed");
return Ok(api);
}
// Leak it to get a true 'static reference and erase the type for storage
let leaked: &'static JObjectArrayAPI<E> = Box::leak(Box::new(created));
write.insert(tid, leaked as &'static (dyn Any + Send + Sync));
Ok(leaked)
}
}
impl<'local, E: Reference + 'local> JObjectArray<'local, E> {
/// Creates a new [`JObjectArray`] of the given `length`, with each element initialized to
/// `initial_element`.
///
/// # Example
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::{JObjectArray, JString}};
/// # fn example<'local>(env: &mut Env<'local>) -> Result<()> {
/// let str = JString::from_str(env, "hello")?;
/// let arr = JObjectArray::<JString>::new(env, 5, &str)?;
/// # Ok(())
/// # }
/// ```
pub fn new<'env_local, 'any_local>(
env: &mut Env<'env_local>,
length: usize,
initial_element: impl AsRef<E::Kind<'any_local>>,
) -> Result<JObjectArray<'env_local, E::Kind<'env_local>>> {
if length > crate::sys::jsize::MAX as usize {
return Err(crate::errors::Error::JniCall(
crate::errors::JniError::InvalidArguments,
));
}
env.assert_top();
let element_class = E::lookup_class(env, &LoaderContext::default())?;
let array = unsafe {
jni_call_with_catch_and_null_check!(
catch |env| {
crate::exceptions::JOutOfMemoryError =>
Err(Error::JniCall(JniError::NoMemory)),
else => Err(Error::NullPtr("Unexpected Exception")),
},
env,
v1_1,
NewObjectArray,
length as i32,
element_class.as_raw(),
initial_element.as_ref().as_raw()
)
.map(|array| JObjectArray::<E>::from_raw(env, array))?
};
// Ensure that `element_class` isn't dropped before the JNI call returns.
drop(element_class);
Ok(array)
}
/// Creates a [`JObjectArray`] that wraps the given `raw` [`jobjectArray`]
///
/// # Safety
///
/// - `raw` must be a valid raw JNI local reference (or `null`).
/// - `raw` must be an instance of `java.lang.Object[]` where each element is an instance of `E`.
/// - There must not be any other owning [`Reference`] wrapper for the same reference.
/// - The local reference must belong to the current thread and not outlive the
/// JNI stack frame associated with the [Env] `'env_local` lifetime.
pub unsafe fn from_raw<'env_local>(
env: &Env<'env_local>,
raw: jobjectArray,
) -> JObjectArray<'env_local, E::Kind<'env_local>> {
JObjectArray {
array: unsafe { JObject::from_raw(env, raw as jobject) },
_marker: std::marker::PhantomData,
}
}
/// Creates a new null reference.
///
/// Null references are always valid and do not belong to a local reference frame. Therefore,
/// the returned `JObjectArray` always has the `'static` lifetime.
pub const fn null() -> JObjectArray<'static, E::GlobalKind> {
JObjectArray {
array: JObject::null(),
_marker: std::marker::PhantomData,
}
}
/// Unwrap to the raw jni type.
pub const fn into_raw(self) -> jobjectArray {
self.array.into_raw() as jobjectArray
}
/// Cast a local reference to a [`JObjectArray<T>`]
///
/// This will do a runtime (`IsInstanceOf`) check that the object is an instance of `T[]`.
///
/// Also see these other options for casting local or global references to a [`JObjectArray<T>`]:
/// - [Env::as_cast]
/// - [Env::new_cast_local_ref]
/// - [Env::cast_local]
/// - [Env::new_cast_global_ref]
/// - [Env::cast_global]
///
/// # Errors
///
/// Returns [Error::WrongObjectType] if the `IsInstanceOf` check fails.
pub fn cast_local<'any_local>(
env: &mut Env<'_>,
obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
) -> Result<<JObjectArray<'any_local, E> as Reference>::Kind<'any_local>>
where
E: 'any_local,
{
env.cast_local::<JObjectArray<'any_local, E>>(obj)
}
/// Returns the length of the array.
pub fn len(&self, env: &Env) -> Result<usize> {
let array = null_check!(
self.as_raw() as jobjectArray,
"JObjectArray::len self argument"
)?;
let len = unsafe { jni_call_no_post_check_ex!(env, v1_1, GetArrayLength, array)? } as usize;
Ok(len)
}
/// Returns a local reference to an element of the [`JObjectArray`] `array`.
///
/// Returns [Error::IndexOutOfBounds] if the `index` is out of bounds.
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
pub fn get_element<'env_local>(
&self,
env: &mut Env<'env_local>,
index: usize,
) -> Result<E::Kind<'env_local>> {
// Runtime check that the 'local reference lifetime will be tied to
// Env lifetime for the top JNI stack frame
assert_eq!(env.level, JavaVM::thread_attach_guard_level());
let array = null_check!(
self.as_raw() as jobjectArray,
"get_object_array_element array argument"
)?;
if index > i32::MAX as usize {
return Err(crate::errors::Error::JniCall(
crate::errors::JniError::InvalidArguments,
));
}
unsafe {
jni_call_with_catch!(
catch |env| {
crate::exceptions::JArrayIndexOutOfBoundsException =>
Err(Error::IndexOutOfBounds),
else => Err(Error::JniCall(JniError::Unknown)),
},
env, v1_1, GetObjectArrayElement, array, index as i32)
.map(|obj| E::kind_from_raw(obj))
}
}
/// Sets an element of the [`JObjectArray`] `array`.
///
/// Returns:
/// - [Error::IndexOutOfBounds] if the `index` is out of bounds.
/// - [Error::WrongObjectType] if the `value` is not of the correct type.
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
pub fn set_element<'any_local>(
&self,
env: &Env<'_>,
index: usize,
value: impl AsRef<E::Kind<'any_local>>,
) -> Result<()> {
let array = null_check!(
self.as_raw() as jobjectArray,
"set_object_array_element array argument"
)?;
if index > i32::MAX as usize {
return Err(crate::errors::Error::JniCall(
crate::errors::JniError::InvalidArguments,
));
}
unsafe {
jni_call_with_catch!(
catch |env| {
crate::exceptions::JArrayIndexOutOfBoundsException =>
Err(Error::IndexOutOfBounds),
crate::exceptions::JArrayStoreException =>
Err(Error::WrongObjectType),
else => Err(Error::JniCall(JniError::Unknown)),
},
env,
v1_1,
SetObjectArrayElement,
array,
index as i32,
value.as_ref().as_raw()
)?;
}
Ok(())
}
}
// SAFETY: JObjectArray is a transparent JObject wrapper with no Drop side effects
unsafe impl<'local, E: Reference + 'local> Reference for JObjectArray<'local, E> {
type Kind<'env>
= JObjectArray<'env, E::Kind<'env>>
where
<E as Reference>::Kind<'env>: 'env;
type GlobalKind = JObjectArray<'static, E::GlobalKind>;
fn as_raw(&self) -> jobject {
self.array.as_raw()
}
fn class_name() -> Cow<'static, JNIStr> {
let inner = E::class_name();
let inner = inner.to_str();
let name = if inner.len() == 1 || inner.starts_with("[") {
// inner = primitive OR array
format!("[{inner}")
} else {
// inner = object
format!("[L{inner};")
};
let name: JNIString = name.into();
Cow::Owned(name)
}
fn lookup_class<'caller>(
env: &Env<'_>,
loader_context: &LoaderContext,
) -> crate::errors::Result<impl Deref<Target = Global<JClass<'static>>> + 'caller> {
let api = JObjectArrayAPI::<E::GlobalKind>::get(env, loader_context)?;
Ok(&api.class)
}
unsafe fn kind_from_raw<'env>(local_ref: jobject) -> Self::Kind<'env> {
JObjectArray {
array: unsafe { JObject::kind_from_raw(local_ref) },
_marker: std::marker::PhantomData,
}
}
unsafe fn global_kind_from_raw(global_ref: jobject) -> Self::GlobalKind {
JObjectArray {
array: unsafe { JObject::global_kind_from_raw(global_ref) },
_marker: std::marker::PhantomData,
}
}
}
+489
View File
@@ -0,0 +1,489 @@
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::Deref;
use crate::{
env::Env,
errors::Result,
objects::{
AutoElements, AutoElementsCritical, Global, JClass, JObject, LoaderContext, Reference,
ReleaseMode,
},
strings::JNIStr,
sys::{jarray, jobject},
};
use super::TypeArray;
#[cfg(doc)]
use crate::{MonitorGuard, errors::Error, objects::JObjectArray};
/// A primitive array reference, tied to a JNI local reference frame.
///
/// This is a `#[transparent]` reference wrapper for primitive array types like `boolean[]` or
/// `int[]`.
///
/// For convenience it's recommended to use one of the type aliases like:
/// - [JBooleanArray]
/// - [JByteArray]
/// - [JCharArray]
/// - [JShortArray]
/// - [JIntArray]
/// - [JLongArray]
/// - [JFloatArray]
/// - [JDoubleArray]
///
/// See [JObjectArray] for non-primitive object arrays.
///
/// See the [`JObject`] documentation for more information about reference wrappers, how to cast
/// them, and local reference frame lifetimes.
///
#[repr(transparent)]
#[derive(Debug)]
pub struct JPrimitiveArray<'local, T: TypeArray> {
obj: JObject<'local>,
_marker: PhantomData<T>,
}
impl<'local, T: TypeArray> AsRef<JPrimitiveArray<'local, T>> for JPrimitiveArray<'local, T> {
fn as_ref(&self) -> &JPrimitiveArray<'local, T> {
self
}
}
impl<'local, T: TypeArray> AsMut<JPrimitiveArray<'local, T>> for JPrimitiveArray<'local, T> {
fn as_mut(&mut self) -> &mut JPrimitiveArray<'local, T> {
self
}
}
impl<'local, T: TypeArray> AsRef<JObject<'local>> for JPrimitiveArray<'local, T> {
fn as_ref(&self) -> &JObject<'local> {
&self.obj
}
}
impl<'local, T: TypeArray> ::std::ops::Deref for JPrimitiveArray<'local, T> {
type Target = JObject<'local>;
fn deref(&self) -> &Self::Target {
&self.obj
}
}
impl<'local, T: TypeArray> From<JPrimitiveArray<'local, T>> for JObject<'local> {
fn from(other: JPrimitiveArray<'local, T>) -> JObject<'local> {
other.obj
}
}
impl<T: TypeArray> std::default::Default for JPrimitiveArray<'_, T> {
fn default() -> Self {
Self {
obj: JObject::null(),
_marker: PhantomData,
}
}
}
impl<'local, T: TypeArray> JPrimitiveArray<'local, T> {
/// Creates a new [`JPrimitiveArray`] of the given `length`.
pub fn new<'env_local>(
env: &mut Env<'env_local>,
length: usize,
) -> Result<JPrimitiveArray<'env_local, T>> {
if length > crate::sys::jsize::MAX as usize {
return Err(crate::errors::Error::JniCall(
crate::errors::JniError::InvalidArguments,
));
}
// Runtime check that the 'local reference lifetime will be tied to
// Env lifetime for the top JNI stack frame
env.assert_top();
let raw_array = unsafe { T::new_array(env, length as crate::sys::jsize)? };
unsafe { Ok(JPrimitiveArray::from_raw(env, raw_array)) }
}
/// Creates a [`JPrimitiveArray`] that wraps the given `raw` [`jarray`]
///
/// # Safety
///
/// - `raw` must be a valid raw JNI local reference (or `null`).
/// - `raw` must be an instance of the appropriate primitive array type, e.g. `int[]`.
/// - There must not be any other owning [`Reference`] wrapper for the same reference.
/// - The local reference must belong to the current thread and not outlive the
/// JNI stack frame associated with the [Env] `'env_local` lifetime.
pub unsafe fn from_raw<'env_local>(
env: &Env<'env_local>,
raw: jarray,
) -> JPrimitiveArray<'env_local, T> {
JPrimitiveArray {
obj: unsafe { JObject::from_raw(env, raw as jobject) },
_marker: PhantomData,
}
}
/// Creates a new null reference.
///
/// Null references are always valid and do not belong to a local reference frame. Therefore,
/// the returned `JPrimitiveArray` always has the `'static` lifetime.
pub const fn null() -> JPrimitiveArray<'static, T> {
JPrimitiveArray {
obj: JObject::null(),
_marker: PhantomData,
}
}
/// Unwrap to the raw jni type.
pub const fn into_raw(self) -> jarray {
self.obj.into_raw() as jarray
}
/// Returns the length of the array.
pub fn len(&self, env: &Env) -> Result<usize> {
let array = null_check!(self.as_raw(), "JPrimitiveArray::len self argument")?;
let len = unsafe { jni_call_no_post_check_ex!(env, v1_1, GetArrayLength, array)? } as usize;
Ok(len)
}
/// Returns an [`AutoElements`] to access the elements of the given Java `array`.
///
/// The elements are accessible until the returned auto-release guard is dropped.
///
/// The returned array may be a copy of the Java array and changes made to
/// the returned array will not necessarily be reflected in the original
/// array until the [`AutoElements`] guard is dropped.
///
/// If you know in advance that you will only be reading from the array then
/// pass [`ReleaseMode::NoCopyBack`] so that the JNI implementation knows
/// that it's not necessary to copy any data back to the original Java array
/// when the [`AutoElements`] guard is dropped.
///
/// Since the returned array may be a copy of the Java array, changes made to the
/// returned array will not necessarily be reflected in the original array until
/// the corresponding `Release*ArrayElements` JNI method is called.
/// [`AutoElements`] has a commit() method, to force a copy back of pending
/// array changes if needed (and without releasing it).
///
/// # Safety
///
/// ## No data races
///
/// This API has no built-in synchronization that ensures there won't be any data
/// races while accessing the array elements.
///
/// To avoid undefined behaviour it is the caller's responsibility to ensure there
/// will be no data races between other Rust or Java threads trying to access the
/// same array.
///
/// Acquiring a [`MonitorGuard`] lock for the `array` could be one way of ensuring
/// mutual exclusion between Rust and Java threads, so long as the Java threads
/// also acquire the same lock via `synchronized(array) {}`.
///
/// ## No aliasing
///
/// Callers must not create more than one [`AutoElements`] or
/// [`AutoElementsCritical`] per Java array at the same time - even if
/// there is no risk of a data race.
///
/// The reason for this restriction is that [`AutoElements`] and
/// [`AutoElementsCritical`] implement `DerefMut` which can provide a
/// mutable `&mut [T]` slice reference for the elements and it would
/// constitute undefined behaviour to allow there to be more than one
/// mutable reference that points to the same memory.
///
/// # jboolean elements
///
/// Keep in mind that arrays of `jboolean` values should only ever hold
/// values of `0` or `1` because any other value could lead to undefined
/// behaviour within the JVM.
///
/// Also see
/// [`Env::get_array_elements_critical`] which
/// imposes additional restrictions that make it less likely to incur the
/// cost of copying the array elements.
pub unsafe fn get_elements(
&self,
env: &Env,
mode: ReleaseMode,
) -> Result<AutoElements<'local, T, &Self>> {
AutoElements::new(env, self, mode)
}
/// Returns an [`AutoElementsCritical`] to access the elements of this
/// array.
///
/// The elements are accessible during the critical section that exists
/// until the returned auto-release guard is dropped.
///
/// This API imposes some strict restrictions that help the JNI
/// implementation avoid any need to copy the underlying array elements
/// before making them accessible to native code:
///
/// 1. No other use of JNI calls are allowed (on the same thread) within the
/// critical section that exists while holding the
/// [`AutoElementsCritical`] guard.
/// 2. No system calls can be made (Such as `read`) that may depend on a
/// result from another Java thread.
///
/// The JNI spec does not specify what will happen if these rules aren't
/// adhered to but it should be assumed it will lead to undefined behaviour,
/// likely deadlock and possible program termination.
///
/// Even with these restrictions the returned array may still be a copy of
/// the Java array and changes made to the returned array will not
/// necessarily be reflected in the original array until the
/// [`AutoElementsCritical`] guard is dropped.
///
/// If you know in advance that you will only be reading from the array then
/// pass [`ReleaseMode::NoCopyBack`] so that the JNI implementation knows
/// that it's not necessary to copy any data back to the original Java array
/// when the [`AutoElementsCritical`] guard is dropped.
///
/// A nested scope or explicit use of `std::mem::drop` can be used to
/// control when the returned [`AutoElementsCritical`] is dropped to
/// minimize the length of the critical section.
///
/// If this array is `null`, an [`Error::NullPtr`] is returned.
///
/// # Safety
///
/// ## Critical Section Restrictions
///
/// This API is marked as `unsafe` due to the complex, far-reaching nature
/// of the critical-section restrictions imposed here that can't be enforced
/// through Rust's borrow checker rules.
///
/// The rules above about JNI usage and system calls _must_ be adhered to.
///
/// Using this API implies:
///
/// 1. All garbage collection will likely be paused during the critical
/// section
/// 2. Any use of JNI in other threads may block if they need to allocate
/// memory (due to the garbage collector being paused)
/// 3. Any use of system calls that will wait for a result from another Java
/// thread could deadlock if that other thread is blocked by a paused
/// garbage collector.
///
/// A failure to adhere to the critical section rules could lead to any
/// undefined behaviour, including aborting the program.
///
/// ## No data races
///
/// This API has no built-in synchronization that ensures there won't be any
/// data races while accessing the array elements.
///
/// To avoid undefined behaviour it is the caller's responsibility to ensure
/// there will be no data races between other Rust or Java threads trying to
/// access the same array.
///
/// Acquiring a [`MonitorGuard`] lock for this array could be one way of
/// ensuring mutual exclusion between Rust and Java threads, so long as the
/// Java threads also acquire the same lock via `synchronized(array) {}`.
///
/// ## No aliasing
///
/// Callers must not create more than one [`AutoElements`] or
/// [`AutoElementsCritical`] per Java array at the same time - even if there
/// is no risk of a data race.
///
/// The reason for this restriction is that [`AutoElements`] and
/// [`AutoElementsCritical`] implement `DerefMut` which can provide a
/// mutable `&mut [T]` slice reference for the elements and it would
/// constitute undefined behaviour to allow there to be more than one
/// mutable reference that points to the same memory.
///
/// ## jboolean elements
///
/// Keep in mind that arrays of `jboolean` values should only ever hold
/// values of `0` or `1` because any other value could lead to undefined
/// behaviour within the JVM.
///
/// Also see [`get_elements`](Self::get_elements) which has
/// fewer restrictions, but is more likely to incur a cost from copying
/// the array elements.
pub unsafe fn get_elements_critical(
&self,
env: &Env<'_>,
mode: ReleaseMode,
) -> Result<AutoElementsCritical<'local, T, &Self>> {
AutoElementsCritical::new(env, self, mode)
}
/// Copy elements of the array from the `start` index to the `buf` slice.
/// The number of copied elements is equal to the `buf` length.
///
/// # Errors
///
/// Returns [Error::IndexOutOfBounds] if `start` is negative _or_ `start +
/// buf.len()` is greater than [`Self::len`].
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending
/// exception).
pub fn get_region(&self, env: &Env, start: crate::sys::jsize, buf: &mut [T]) -> Result<()> {
unsafe { T::get_region(env, self.as_raw() as jarray, start, buf) }
}
/// Copy the contents of the `buf` slice to the java byte array at the
/// `start` index.
///
/// # Errors
///
/// Returns [Error::IndexOutOfBounds] if `start` is negative _or_ `start +
/// buf.len()` is greater than [`Self::len`].
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
pub fn set_region(&self, env: &Env, start: crate::sys::jsize, buf: &[T]) -> Result<()> {
unsafe { T::set_region(env, self.as_raw() as jarray, start, buf) }
}
}
/// A `boolean[]` array reference, tied to a JNI local reference frame
pub type JBooleanArray<'local> = JPrimitiveArray<'local, crate::sys::jboolean>;
/// A `byte[]` array reference, tied to a JNI local reference frame
pub type JByteArray<'local> = JPrimitiveArray<'local, crate::sys::jbyte>;
/// A `char[]` array reference, tied to a JNI local reference frame
pub type JCharArray<'local> = JPrimitiveArray<'local, crate::sys::jchar>;
/// A `short[]` array reference, tied to a JNI local reference frame
pub type JShortArray<'local> = JPrimitiveArray<'local, crate::sys::jshort>;
/// A `int[]` array reference, tied to a JNI local reference frame
pub type JIntArray<'local> = JPrimitiveArray<'local, crate::sys::jint>;
/// A `long[]` array reference, tied to a JNI local reference frame
pub type JLongArray<'local> = JPrimitiveArray<'local, crate::sys::jlong>;
/// A `float[]` array reference, tied to a JNI local reference frame
pub type JFloatArray<'local> = JPrimitiveArray<'local, crate::sys::jfloat>;
/// A `double[]` array reference, tied to a JNI local reference frame
pub type JDoubleArray<'local> = JPrimitiveArray<'local, crate::sys::jdouble>;
/// Trait to access the raw `jarray` pointer for types that wrap an array reference
///
/// # Safety
///
/// Implementing this trait will allow a type to be passed to [`Env::get_array_length()`]
/// or other JNI APIs that only work with a valid reference to an array (or `null`)
///
pub unsafe trait AsJArrayRaw<'local>: AsRef<JObject<'local>> {
/// Returns the raw JNI pointer as a `jarray`
fn as_jarray_raw(&self) -> jarray {
self.as_ref().as_raw() as jarray
}
}
unsafe impl<'local, T: TypeArray> AsJArrayRaw<'local> for JPrimitiveArray<'local, T> {}
macro_rules! impl_ref_for_jprimitive_array {
($type:ident, $class_name:expr, $api_type:ident) => {
#[allow(non_camel_case_types)]
pub(crate) struct $api_type {
class: Global<JClass<'static>>,
}
impl $api_type {
pub(crate) fn get<'any_local>(
env: &Env<'_>,
loader_context: &LoaderContext<'any_local, '_>,
) -> Result<&'static Self> {
static API: std::sync::OnceLock<$api_type> = std::sync::OnceLock::new();
// Fast path
if let Some(api) = API.get() {
return Ok(api);
}
// Lookup class and cache
// Note: we don't mind racing here, and follow the general pattern of avoiding
// locks while looking up classes and initializing APIs, because in the more
// general case it can lead to deadlocks via class initialization dependencies.
let api = env.with_local_frame(4, |env| -> Result<_> {
let class = loader_context
.load_class_for_type::<JPrimitiveArray<crate::sys::$type>>(env, false)?;
let class = env.new_global_ref(&class).unwrap();
Ok(Self { class })
})?;
let _ = API.set(api);
Ok(API.get().unwrap())
}
}
impl JPrimitiveArray<'_, crate::sys::$type> {
/// Cast a local reference to a [`JPrimitiveArray<T>`]
///
/// This will do a runtime (`IsInstanceOf`) check that the object is an instance of `T[]`.
///
/// Also see these other options for casting local or global references to a [`JPrimitiveArray<T>`]:
/// - [Env::as_cast]
/// - [Env::new_cast_local_ref]
/// - [Env::cast_local]
/// - [Env::new_cast_global_ref]
/// - [Env::cast_global]
///
/// # Errors
///
/// Returns [Error::WrongObjectType] if the `IsInstanceOf` check fails.
pub fn cast_local<'any_local>(
env: &mut Env<'_>,
obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>,
) -> Result<
<JPrimitiveArray<'any_local, crate::sys::$type> as Reference>::Kind<'any_local>,
> {
env.cast_local::<JPrimitiveArray<crate::sys::$type>>(obj)
}
}
// SAFETY: JPrimitiveArray is a transparent JObject wrapper with no Drop side effects
unsafe impl Reference for JPrimitiveArray<'_, crate::sys::$type> {
type Kind<'env> = JPrimitiveArray<'env, crate::sys::$type>;
type GlobalKind = JPrimitiveArray<'static, crate::sys::$type>;
fn as_raw(&self) -> jobject {
self.obj.as_raw()
}
fn class_name() -> Cow<'static, JNIStr> {
Cow::Borrowed($crate::jni_str!($class_name))
}
fn lookup_class<'caller>(
env: &Env<'_>,
loader_context: &LoaderContext,
) -> crate::errors::Result<impl Deref<Target = Global<JClass<'static>>> + 'caller> {
let api = $api_type::get(env, &loader_context)?;
Ok(&api.class)
}
unsafe fn kind_from_raw<'env>(local_ref: jobject) -> Self::Kind<'env> {
JPrimitiveArray {
obj: unsafe { JObject::kind_from_raw(local_ref) },
_marker: PhantomData,
}
}
unsafe fn global_kind_from_raw(global_ref: jobject) -> Self::GlobalKind {
JPrimitiveArray {
obj: unsafe { JObject::global_kind_from_raw(global_ref) },
_marker: PhantomData,
}
}
}
};
}
impl_ref_for_jprimitive_array!(jboolean, "[Z", JPrimitiveArrayAPI_jboolean);
impl_ref_for_jprimitive_array!(jbyte, "[B", JPrimitiveArrayAPI_jbyte);
impl_ref_for_jprimitive_array!(jchar, "[C", JPrimitiveArrayAPI_jchar);
impl_ref_for_jprimitive_array!(jshort, "[S", JPrimitiveArrayAPI_jshort);
impl_ref_for_jprimitive_array!(jint, "[I", JPrimitiveArrayAPI_jint);
impl_ref_for_jprimitive_array!(jlong, "[J", JPrimitiveArrayAPI_jlong);
impl_ref_for_jprimitive_array!(jfloat, "[F", JPrimitiveArrayAPI_jfloat);
impl_ref_for_jprimitive_array!(jdouble, "[D", JPrimitiveArrayAPI_jdouble);
+85
View File
@@ -0,0 +1,85 @@
use crate::{
env::Env,
errors::Result,
objects::{JIterator, JObject},
};
crate::bind_java_type! {
pub JSet => "java.util.Set",
is_instance_of {
collection = JCollection,
}
}
impl<'local> JSet<'local> {
/// Adds the given element to this set if it is not already present
///
/// Returns `true` if the element was added, `false` if it was already present.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the add operation is not supported
/// - `ClassCastException` - if the element type isn't compatible with the set
/// - `NullPointerException` - if the given element is null and the set does not allow null values
/// - `IllegalArgumentException` - if the element has a property that prevents it from being added to this set
pub fn add<'any_local>(
&self,
env: &mut Env<'_>,
element: impl AsRef<JObject<'any_local>>,
) -> Result<bool> {
self.as_collection().add(env, element)
}
/// Removes the given element from this set if it is present
///
/// Returns `true` if the element was removed.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the remove operation is not supported
/// - `ClassCastException` - if the element type isn't compatible with the set
/// - `NullPointerException` - if the given element is null and the set does not allow null values
pub fn remove<'any_local>(
&self,
env: &mut Env<'_>,
element: impl AsRef<JObject<'any_local>>,
) -> Result<bool> {
self.as_collection().remove(env, element)
}
/// Removes all of the elements from this set.
///
/// # Throws
///
/// - `UnsupportedOperationException` - if the clear operation is not supported
pub fn clear(&self, env: &mut Env<'_>) -> Result<()> {
self.as_collection().clear(env)
}
/// Checks if the given element is present in this set.
///
/// Returns `true` if the element is present, `false` otherwise.
///
/// # Throws
///
/// - `ClassCastException` - if the element type isn't compatible with the set
/// - `NullPointerException` - if the given element is null and the set does not allow null values
pub fn contains(&self, env: &mut Env<'_>, element: &JObject) -> Result<bool> {
self.as_collection().contains(env, element)
}
/// Returns the number of elements in this set.
pub fn size(&self, env: &mut Env<'_>) -> Result<i32> {
self.as_collection().size(env)
}
/// Returns `true` if this set contains no elements.
pub fn is_empty(&self, env: &mut Env<'_>) -> Result<bool> {
self.as_collection().is_empty(env)
}
/// Returns an iterator (`java.util.Iterator`) over the elements in this set.
pub fn iterator<'env_local>(&self, env: &mut Env<'env_local>) -> Result<JIterator<'env_local>> {
self.as_collection().iterator(env)
}
}
+35
View File
@@ -0,0 +1,35 @@
crate::bind_java_type! {
pub JStackTraceElement => "java.lang.StackTraceElement",
methods {
/// Get the class name of the stack trace element.
fn get_class_name() -> JString,
/// Get the file name of the stack trace element, if available.
fn get_file_name() -> JString,
/// Get the line number of the stack trace element.
fn get_line_number() -> jint,
/// Get the method name of the stack trace element.
fn get_method_name() -> JString,
/// Check if the stack trace element corresponds with a native method.
fn is_native_method() -> bool,
/// Returns a string representation of this stack trace element.
fn try_to_string {
name = "toString",
sig = () -> JString,
}
}
}
impl<'local> JStackTraceElement<'local> {
// In jni 0.22.0 and 0.22.1 we were incorrectly trying to lookup an isNative
// method and although it was impossible to call (because this API binding
// would fail to initialize) we also exported a public `is_native()` method
// that code could potentially have linked against.
#[doc(hidden)]
#[deprecated(since = "0.22.1", note = "Use `is_native_method` instead")]
pub fn is_native<'env_local>(
&self,
env: &::jni::Env<'env_local>,
) -> ::jni::errors::Result<bool> {
self.is_native_method(env)
}
}
+239
View File
@@ -0,0 +1,239 @@
use thiserror::Error;
use crate::{
Env, JavaVM,
errors::{Error, JniError, Result},
strings::{JNIStr, JNIString, MUTF8Chars},
};
use super::Reference as _;
crate::bind_java_type! {
pub JString => "java.lang.String",
__jni_core = true,
__sys_type = jstring,
is_instance_of {
char_sequence = JCharSequence,
},
methods {
/// Returns a canonical, interned version of this string.
fn intern() -> JString,
}
}
#[allow(rustdoc::invalid_html_tags)]
/// Display the contents of a `JString`
///
/// This implementation relies on JNI (GetStringUTFChars) to retrieve the string contents for
/// display.
///
/// If you try and format a null reference this will output "<NULL>"
///
/// In case you attempt to format a JString before [`JavaVM::singleton`] has been initialized then
/// this will simply output "<JNI Not Initialized>" and log an error.
///
/// In case of any other unexpected JNI error, this will output "<JNI Error>" and log the error
/// details.
impl<'local> std::fmt::Display for JString<'local> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
#[derive(Error, Debug)]
#[error(transparent)]
enum FmtOrJniError {
Fmt(#[from] std::fmt::Error),
Jni(#[from] crate::errors::Error),
}
if self.is_null() {
return write!(f, "<NULL>");
}
// The only way it's possible to have a `JString` while `JavaVM::singleton` is
// not initialized would be if the `JString` was used to capture a native method
// argument and `EnvUnowned::with_env` has not been called yet (and nothing
// else has initialized this crate already)
//
// I.e. it's highly unlikely that this should return an error.
JavaVM::singleton()
.map_err(FmtOrJniError::Jni)
.and_then(|vm| {
// In the common case we expect this attachment will be a NOOP.
//
// In the (unlikely) case that a `Global<JString>` is being formatted from an
// arbitrary thread that's not attached to the JVM then we create a scoped
// attachment so we avoid the side effect of attaching the current thread
// permanently.
vm.attach_current_thread_for_scope(
|env| -> std::result::Result<(), FmtOrJniError> {
// Since we have already checked for a null reference it should be highly
// unlikely for there to be any JNI errors.
//
// Note: there won't be any local reference created as a side effect.
// Note: there's no risk of side effects from an exception being thrown.
// A `GetStringUTFChars` failure may result in a `NullPtr` error that
// is handled below as a general JNI error.
let mutf8_chars = self.mutf8_chars(env)?;
let s = mutf8_chars.to_str();
write!(f, "{}", s)?;
Ok(())
},
)
})
.or_else(|err| {
match err {
FmtOrJniError::Fmt(err) => Err(err),
FmtOrJniError::Jni(crate::errors::Error::UninitializedJavaVM) => {
log::error!(
"error getting JavaVM singleton to format JString: {:#?}",
err
);
write!(f, "<JNI Not Initialized>")
}
FmtOrJniError::Jni(err) => {
// If we failed to get the string contents, just print the error
log::error!("error getting JString contents: {:#?}", err);
write!(f, "<JNI Error>")
}
}
})
}
}
impl JString<'_> {
/// Encodes a Rust `&str` to MUTF-8 and creates a `JString` (`java.lang.String` object).
///
/// This is a convenience that's equivalent to calling [`Self::from_str`]
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
///
/// # Performance
///
/// The input string is re-encoded to modified UTF-8, so this involves a copy of your input to
/// encode, before calling into JNI to create the `JString`.
///
/// To avoid the overhead of encoding and copying, use [`Self::from_jni_str`] and the
/// [crate::jni_str!] macro to encode strings to MUTF-8 at compile time.
pub fn new<'env_local>(
env: &mut Env<'env_local>,
from: impl AsRef<str>,
) -> Result<JString<'env_local>> {
Self::from_str(env, from)
}
/// Encodes a Rust `&str` to MUTF-8 and creates a `JString` (`java.lang.String` object).
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
///
/// # Performance
///
/// The input string is re-encoded to modified UTF-8, so this involves a copy of your input to
/// encode, before calling into JNI to create the `JString`.
///
/// To avoid the overhead of encoding and copying, use [`Self::from_jni_str`] and the
/// [crate::jni_str!] macro to encode strings to MUTF-8 at compile time.
pub fn from_str<'env_local>(
env: &mut Env<'env_local>,
from: impl AsRef<str>,
) -> Result<JString<'env_local>> {
Self::from_jni_str(env, JNIString::new(from))
}
/// Creates a `JString` (`java.lang.String` object) from a [JNIStr] (modified UTF-8).
///
/// For simple string literals, consider using the [crate::jni_str!] macro to create / encode
/// [JNIStr] literals at compile time.
///
/// This API catches exceptions internally and is not expected to return
/// [`Error::JavaException`] (unless called while there is a pending exception).
pub fn from_jni_str<'env_local>(
env: &mut Env<'env_local>,
from: impl AsRef<JNIStr>,
) -> Result<JString<'env_local>> {
// Runtime check that the 'local reference lifetime will be tied to
// Env lifetime for the top JNI stack frame
env.assert_top();
let ffi_str: &JNIStr = from.as_ref();
unsafe {
jni_call_with_catch_and_null_check!(
catch |env| {
crate::exceptions::JOutOfMemoryError =>
Err(Error::JniCall(JniError::NoMemory)),
else => Err(Error::NullPtr("Unexpected Exception")),
},
env, v1_1, NewStringUTF, ffi_str.as_ptr())
.map(|s| JString::from_raw(env, s))
}
}
/// Gets the contents of this string, in [modified UTF-8] encoding (via `GetStringUTFChars`).
///
/// The returned [MUTF8Chars] guard can be used to access the modified UTF-8 bytes, or to
/// convert to a Rust string (UTF-8).
///
/// For example:
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::*, strings::*};
/// #
/// # fn f(env: &mut Env) -> Result<()> {
/// let my_jstring = JString::from_str(env, "Hello, world!")?;
/// let mutf8_chars = my_jstring.mutf8_chars(env)?;
/// let jni_str: &JNIStr = &mutf8_chars;
/// let rust_str = jni_str.to_str();
/// # Ok(())
/// # }
/// ```
///
/// When the [MUTF8Chars] guard is dropped, the reference to the contents gets released.
///
/// The [MUTF8Chars] guard dereferences to a [JNIStr].
///
/// Also note that [MUTF8Chars] (and also [`JString`] itself) implements `Display` and
/// `ToString` so it's also possible to use `.to_string()` to get a Rust String from a [JString]
///
/// [modified UTF-8]: https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
///
/// # Errors
///
/// Returns an [Error::NullPtr] if this [`JString`] is null.
pub fn mutf8_chars(&self, env: &Env<'_>) -> Result<MUTF8Chars<'_, &JString<'_>>> {
MUTF8Chars::from_get_string_utf_chars(env, self)
}
/// Gets the contents of this string as a Rust `String`.
///
/// For example:
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::*};
/// #
/// # fn f(env: &mut Env) -> Result<()> {
/// let jstring = JString::from_str(env, "Hello, world!")?;
/// let rust_string = jstring.try_to_string(&env)?;
/// assert_eq!(rust_string, "Hello, world!");
/// # ; Ok(())
/// # }
/// ```
///
/// This is equivalent to calling [`Self::mutf8_chars`] and then converting that to a `String`, like:
///
/// ```rust,no_run
/// # use jni::{errors::Result, Env, objects::*};
/// #
/// # fn f(env: &mut Env) -> Result<()> {
/// let jstring = JString::from_str(env, "Hello, world!")?;
/// let mutf8_chars = jstring.mutf8_chars(&env)?;
/// let rust_string = mutf8_chars.to_string();
/// # ; Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an [Error::NullPtr] if this [`JString`] is null.
pub fn try_to_string(&self, env: &Env<'_>) -> Result<String> {
let mutf8_chars = self.mutf8_chars(env)?;
Ok(mutf8_chars.to_string())
}
}
+45
View File
@@ -0,0 +1,45 @@
use crate::jni_str;
crate::bind_java_type! {
pub JThread => "java.lang.Thread",
hooks {
load_class = |env, _loader_context, _initialize| {
// As a special-case; we ignore loader_context and use `env.find_class` just to be clear that there's no risk of
// recursion. (`LoaderContext::load_class` depends on the `JThreadAPI`)
env.find_class(const { jni_str!("java/lang/Thread") })
}
},
methods {
/// Returns a reference to the currently executing thread object.
///
/// This is a Java method binding for `java.lang.Thread.currentThread()`.
static fn current_thread() -> JThread,
/// Get the name of this thread.
fn get_name() -> JString,
/// Sets the name of this thread.
///
/// # Throws
///
/// - `SecurityException` if the current thread is not allowed to modify this thread's name
fn set_name(name: JString) -> (),
/// Gets the ID of this thread.
fn get_id() -> jlong,
/// Gets the context class loader for this thread.
///
/// This is a Java method binding for `java.lang.Thread#getContextClassLoader()`.
///
/// # Throws
///
/// - `SecurityException` if the current thread can't access its context class loader.
fn get_context_class_loader() -> JClassLoader,
/// Sets the context class loader for this thread.
///
/// The `loader` may be `null` to indicate the system class loader.
/// This is a Java method binding for `java.lang.Thread#setContextClassLoader(java.lang.ClassLoader)`.
///
/// # Throws
///
/// - `SecurityException` if the current thread can't access its context class loader.
fn set_context_class_loader(loader: JClassLoader) -> (),
}
}
+27
View File
@@ -0,0 +1,27 @@
crate::bind_java_type! {
pub JThrowable => "java.lang.Throwable",
__jni_core = true,
__sys_type = jthrowable,
methods {
/// Get the message of the throwable by calling the `getMessage` method.
fn get_message() -> JString,
/// Get the cause of the throwable by calling the `getCause` method.
fn get_cause() -> JThrowable,
/// Gets the stack trace of the throwable by calling the `getStackTrace` method.
fn get_stack_trace() -> JStackTraceElement[],
/// Associate a suppressed throwable with this throwable by calling the `addSuppressed`
/// method.
///
/// A suppressed exception is one that was thrown but not propagated because another
/// exception was thrown with a higher precedence. This is distinct from the "cause" of the
/// exception because it's not assumed to be the direct cause of the higher-precedence
/// exception.
fn add_suppressed(throwable: JThrowable),
/// Get the list of throwables that were suppressed by this throwable.
fn get_suppressed() -> JThrowable[],
}
}
+80
View File
@@ -0,0 +1,80 @@
mod jobject;
pub use self::jobject::*;
mod jthrowable;
pub use self::jthrowable::*;
mod jstack_trace_element;
pub use self::jstack_trace_element::*;
mod jclass;
pub use self::jclass::*;
mod jclass_loader;
pub use self::jclass_loader::*;
mod jchar_sequence;
pub use self::jchar_sequence::*;
mod jstring;
pub use self::jstring::*;
mod jcollection;
pub use self::jcollection::*;
mod jset;
pub use self::jset::*;
mod jiterator;
pub use self::jiterator::*;
mod jmap;
pub use self::jmap::*;
mod jlist;
pub use self::jlist::*;
mod jbytebuffer;
pub use self::jbytebuffer::*;
mod jthread;
pub use self::jthread::*;
/// Primitive Array types
mod jobject_array;
pub use self::jobject_array::*;
mod type_array;
pub use self::type_array::*;
/// Primitive Array types
mod jprimitive_array;
pub use self::jprimitive_array::*;
#[doc(hidden)]
#[deprecated(
since = "0.22.0",
note = "Please use `jni::JValue*` instead of `jni::objects::JValue*`."
)]
pub use crate::jvalue::*;
#[doc(hidden)]
#[deprecated(
since = "0.22.0",
note = "Please use ID types under `jni::ids::*` instead of `jni::objects::*`."
)]
pub use crate::ids::*;
#[doc(hidden)]
#[deprecated(
since = "0.22.0",
note = "Please use reference types under `jni::refs::*` instead of `jni::objects::*`."
)]
pub use crate::refs::*;
#[doc(hidden)]
#[deprecated(
since = "0.22.0",
note = "Please use array elements types under `jni::elements::*` instead of `jni::objects::*`."
)]
pub use crate::elements::*;
+284
View File
@@ -0,0 +1,284 @@
use crate::sys::{jboolean, jbyte, jchar, jdouble, jfloat, jint, jlong, jshort};
pub(crate) mod type_array_sealed {
use jni_sys::jsize;
use crate::sys::{jarray, jboolean, jbyte, jchar, jdouble, jfloat, jint, jlong, jshort};
use crate::{env::Env, errors::*};
use std::ptr::NonNull;
/// Trait to define type array access/release
///
/// # Safety
///
/// The methods of this trait must uphold the invariants described in [`Env::unsafe_clone`] when
/// using the provided [`Env`].
///
/// The `get` method must return a valid pointer to the beginning of the JNI array.
///
/// The `release` method must not invalidate the `ptr` if the `mode` is [`sys::JNI_COMMIT`].
pub unsafe trait TypeArraySealed: Copy + Send + Sync {
/// Creates a new array of this type with the given length.
unsafe fn new_array(env: &mut Env, length: jsize) -> Result<jarray>;
/// getter
///
/// # Safety
///
/// `array` must be a valid pointer to an `Array` object, or `null`
///
/// The caller is responsible for passing the returned pointer to [`release`], along
/// with the same `env` and `array` reference (which needs to still be valid)
unsafe fn get_elements(
env: &Env,
array: jarray,
is_copy: &mut jboolean,
) -> Result<*mut Self>;
/// releaser
///
/// # Safety
///
/// `array` must be a valid pointer to an `Array` object, or `null`
///
/// `ptr` must have been previously returned by the `get` function.
///
/// If `mode` is not [`sys::JNI_COMMIT`], `ptr` must not be used again after calling this
/// function.
unsafe fn release_elements(
env: &Env,
array: jarray,
ptr: NonNull<Self>,
mode: i32,
) -> Result<()>;
/// Copy elements of the array from the `start` index to the `buf` slice. The number of
/// copied elements is equal to the `buf` length.
///
/// # Errors
///
/// If `start` is negative _or_ `start + buf.len()` is greater than [`JPrimitiveArray::len`]
/// then no elements are copied, an `ArrayIndexOutOfBoundsException` is thrown, and `Err` is
/// returned.
///
/// # Safety
///
/// `array` must be a valid pointer to a primitive JNI array object, matching the type of
/// `Self`, or `null`.
unsafe fn get_region(
env: &Env,
array: jarray,
start: jsize,
buf: &mut [Self],
) -> Result<()>;
/// Copy the contents of the `buf` slice to the java byte array at the
/// `start` index.
///
/// # Safety
///
/// `array` must be a valid pointer to a primitive JNI array object, matching the type of
/// `Self`, or `null`.
unsafe fn set_region(env: &Env, array: jarray, start: jsize, buf: &[Self]) -> Result<()>;
}
// TypeArray builder
macro_rules! type_array {
( $jni_type:ty, $jni_type_name:ident, $new_array:ident, $get_elements:ident, $release_elements:ident, $get_region:ident, $set_region:ident) => {
/// $jni_type array access/release impl
unsafe impl TypeArraySealed for $jni_type {
/// Create new Java $jni_type array
unsafe fn new_array(env: &mut Env, length: jsize) -> Result<jarray> {
let raw_array = unsafe {
jni_call_with_catch_and_null_check!(
catch |env| {
crate::exceptions::JOutOfMemoryError =>
Err(Error::JniCall(JniError::NoMemory)),
else => Err(Error::JniCall(JniError::Unknown)),
},
env, v1_1, $new_array, length)?
};
Ok(raw_array)
}
/// Get Java $jni_type array
unsafe fn get_elements(
env: &Env,
array: jarray,
is_copy: &mut jboolean,
) -> Result<*mut Self> {
// There are no documented exceptions for Get<Primitive>ArrayElements() but
// they may return `NULL`.
let ptr = unsafe {
jni_call_with_catch_and_null_check!(
catch |env| {
crate::exceptions::JOutOfMemoryError =>
Err(Error::JniCall(JniError::NoMemory)),
else => Err(Error::JniCall(JniError::Unknown)),
},
env, v1_1, $get_elements, array, is_copy)?
};
Ok(ptr as _)
}
/// Release Java $jni_type array
unsafe fn release_elements(
env: &Env,
array: jarray,
ptr: NonNull<Self>,
mode: i32,
) -> Result<()> {
// Release<Primitive>ArrayElements() is safe to call while there is a
// pending exception and there are no documented exceptions for
// Release<Primitive>ArrayElements()
unsafe {
ex_safe_jni_call_no_post_check_ex!(
env,
v1_1,
$release_elements,
array,
ptr.as_ptr(),
mode as i32
)
};
Ok(())
}
unsafe fn get_region(
env: &Env,
array: jarray,
start: jsize,
buf: &mut [Self],
) -> Result<()> {
let array = null_check!(array, "get_*_array_region array argument")?;
unsafe {
Ok(jni_call_with_catch!(
catch |env| {
crate::exceptions::JArrayIndexOutOfBoundsException =>
Err(Error::IndexOutOfBounds),
else => Err(Error::JniCall(JniError::Unknown)),
},
env,
v1_1,
$get_region,
array,
start,
buf.len() as jsize,
buf.as_mut_ptr()
)?)
}
}
unsafe fn set_region(
env: &Env,
array: jarray,
start: jsize,
buf: &[Self],
) -> Result<()> {
let array = null_check!(array, "set_*_array_region array argument")?;
unsafe {
Ok(jni_call_with_catch!(
catch |env| {
crate::exceptions::JArrayIndexOutOfBoundsException =>
Err(Error::IndexOutOfBounds),
else => Err(Error::JniCall(JniError::Unknown)),
},
env,
v1_1,
$set_region,
array,
start,
buf.len() as jsize,
buf.as_ptr()
)?)
}
}
}
};
}
type_array!(
jint,
Int,
NewIntArray,
GetIntArrayElements,
ReleaseIntArrayElements,
GetIntArrayRegion,
SetIntArrayRegion
);
type_array!(
jlong,
Long,
NewLongArray,
GetLongArrayElements,
ReleaseLongArrayElements,
GetLongArrayRegion,
SetLongArrayRegion
);
type_array!(
jbyte,
Byte,
NewByteArray,
GetByteArrayElements,
ReleaseByteArrayElements,
GetByteArrayRegion,
SetByteArrayRegion
);
type_array!(
jboolean,
Boolean,
NewBooleanArray,
GetBooleanArrayElements,
ReleaseBooleanArrayElements,
GetBooleanArrayRegion,
SetBooleanArrayRegion
);
type_array!(
jchar,
Char,
NewCharArray,
GetCharArrayElements,
ReleaseCharArrayElements,
GetCharArrayRegion,
SetCharArrayRegion
);
type_array!(
jshort,
Short,
NewShortArray,
GetShortArrayElements,
ReleaseShortArrayElements,
GetShortArrayRegion,
SetShortArrayRegion
);
type_array!(
jfloat,
Float,
NewFloatArray,
GetFloatArrayElements,
ReleaseFloatArrayElements,
GetFloatArrayRegion,
SetFloatArrayRegion
);
type_array!(
jdouble,
Double,
NewDoubleArray,
GetDoubleArrayElements,
ReleaseDoubleArrayElements,
GetDoubleArrayRegion,
SetDoubleArrayRegion
);
}
/// A sealed trait to define type array access/release for primitive JNI types
pub trait TypeArray: type_array_sealed::TypeArraySealed {}
impl TypeArray for jint {}
impl TypeArray for jlong {}
impl TypeArray for jbyte {}
impl TypeArray for jboolean {}
impl TypeArray for jchar {}
impl TypeArray for jshort {}
impl TypeArray for jfloat {}
impl TypeArray for jdouble {}