1 use crate::{
2     objects::JObject,
3     sys::{jobject, jstring},
4 };
5 
6 /// Lifetime'd representation of a `jstring`. Just a `JObject` wrapped in a new
7 /// class.
8 #[repr(transparent)]
9 pub struct JString<'local>(JObject<'local>);
10 
11 impl<'local> AsRef<JString<'local>> for JString<'local> {
as_ref(&self) -> &JString<'local>12     fn as_ref(&self) -> &JString<'local> {
13         self
14     }
15 }
16 
17 impl<'local> AsRef<JObject<'local>> for JString<'local> {
as_ref(&self) -> &JObject<'local>18     fn as_ref(&self) -> &JObject<'local> {
19         self
20     }
21 }
22 
23 impl<'local> ::std::ops::Deref for JString<'local> {
24     type Target = JObject<'local>;
25 
deref(&self) -> &Self::Target26     fn deref(&self) -> &Self::Target {
27         &self.0
28     }
29 }
30 
31 impl<'local> From<JString<'local>> for JObject<'local> {
from(other: JString) -> JObject32     fn from(other: JString) -> JObject {
33         other.0
34     }
35 }
36 
37 impl<'local> From<JObject<'local>> for JString<'local> {
from(other: JObject) -> Self38     fn from(other: JObject) -> Self {
39         unsafe { Self::from_raw(other.into_raw()) }
40     }
41 }
42 
43 impl<'local, 'obj_ref> From<&'obj_ref JObject<'local>> for &'obj_ref JString<'local> {
from(other: &'obj_ref JObject<'local>) -> Self44     fn from(other: &'obj_ref JObject<'local>) -> Self {
45         // Safety: `JString` is `repr(transparent)` around `JObject`.
46         unsafe { &*(other as *const JObject<'local> as *const JString<'local>) }
47     }
48 }
49 
50 impl<'local> std::default::Default for JString<'local> {
default() -> Self51     fn default() -> Self {
52         Self(JObject::null())
53     }
54 }
55 
56 impl<'local> JString<'local> {
57     /// Creates a [`JString`] that wraps the given `raw` [`jstring`]
58     ///
59     /// # Safety
60     ///
61     /// `raw` may be a null pointer. If `raw` is not a null pointer, then:
62     ///
63     /// * `raw` must be a valid raw JNI local reference.
64     /// * There must not be any other `JObject` representing the same local reference.
65     /// * The lifetime `'local` must not outlive the local reference frame that the local reference
66     ///   was created in.
from_raw(raw: jstring) -> Self67     pub unsafe fn from_raw(raw: jstring) -> Self {
68         Self(JObject::from_raw(raw as jobject))
69     }
70 
71     /// Unwrap to the raw jni type.
into_raw(self) -> jstring72     pub fn into_raw(self) -> jstring {
73         self.0.into_raw() as jstring
74     }
75 }
76