ejni 0.1.0

Library to make working with JNI more pleasant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::class::Class;
use crate::object::Object;
use jni::objects::JValue;
use jni::sys::_jobject;
use jni::{errors::Result, JNIEnv};

/// Wrapper around `java.util.List`
pub struct List<'a> {
    /// The list itself
    pub inner: Object<'a>,

    /// The type contained in the List
    pub class: Class<'a>,

    env: &'a JNIEnv<'a>,
}

impl<'a> From<Object<'a>> for List<'a> {
    fn from(obj: Object<'a>) -> Self {
        Self {
            inner: obj.clone(),
            class: obj.class,
            env: obj.env,
        }
    }
}

#[allow(clippy::from_over_into)]
impl<'a> Into<*mut _jobject> for List<'a> {
    fn into(self) -> *mut _jobject {
        self.inner.inner.into_inner()
    }
}

impl<'a> Drop for List<'a> {
    fn drop(&mut self) {
        let _ = self.env.delete_local_ref(self.inner.inner);
    }
}

impl<'a> List<'a> {
    /// Create a List abstraction from it's raw components. The caller must guarantee that `object` implements `java.util.List` and that `class` is the correct Class
    pub fn new(env: &'a JNIEnv<'a>, object: Object<'a>, class: Class<'a>) -> Self {
        Self {
            inner: object,
            class,
            env,
        }
    }

    /// Create a new `java.util.ArrayList`
    pub fn arraylist(env: &'a JNIEnv<'a>, v_class: Class<'a>) -> Result<Self> {
        let arraylist = env.new_object("java/util/ArrayList", "()V", &[])?;
        Ok(Self {
            inner: Object::new(env, arraylist, Class::ArrayList(env)?),
            class: v_class,
            env,
        })
    }

    /// Appends the specified element to the end of this list (optional operation).
    pub fn add(&self, object: &Object<'a>) -> Result<bool> {
        let object = self.env.call_method(
            self.inner.inner,
            "add",
            "(Ljava/lang/Object;)Z",
            &[object.into()],
        )?;
        object.z()
    }

    /// Inserts the specified element at the specified position in this list (optional operation).
    pub fn add_at(&self, object: &Object<'a>, index: i32) -> Result<()> {
        self.env.call_method(
            self.inner.inner,
            "add",
            "(ILjava/lang/Object;)V",
            &[JValue::Int(index), object.into()],
        )?;
        Ok(())
    }

    /// Removes all of the elements from this list (optional operation).
    pub fn clear(&self) -> Result<()> {
        self.env
            .call_method(self.inner.inner, "clear", "()V", &[])?;
        Ok(())
    }

    /// Returns true if this list contains the specified element.
    pub fn contains(&self, object: &Object<'a>) -> Result<bool> {
        let contains = self.env.call_method(
            self.inner.inner,
            "contains",
            "(Ljava/lang/Object;)Z",
            &[object.into()],
        )?;
        contains.z()
    }

    /// Returns the element at the specified position in this list.
    pub fn get(&self, index: i32) -> Result<Option<Object<'a>>> {
        let value = self.env.call_method(
            self.inner.inner,
            "get",
            "(I)Ljava/lang/Object;",
            &[JValue::Int(index)],
        )?;
        let maybe_object = value.l()?;
        match maybe_object.is_null() {
            true => Ok(None),
            false => Ok(Some(Object::new(
                self.env,
                maybe_object,
                self.class.clone(),
            ))),
        }
    }

    /// Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
    pub fn index_of(&self, object: &Object<'a>) -> Result<i32> {
        let index = self.env.call_method(
            self.inner.inner,
            "indexOf",
            "(Ljava/lang/Object;)I",
            &[object.into()],
        )?;
        index.i()
    }

    /// Returns true if this list contains no elements.
    pub fn is_empty(&self) -> Result<bool> {
        let is_empty = self
            .env
            .call_method(self.inner.inner, "isEmpty", "()Z", &[])?;
        is_empty.z()
    }

    /// Removes the first occurrence of the specified element from this list, if it is present (optional operation).
    pub fn remove(&self, object: &Object<'a>) -> Result<bool> {
        let remove = self.env.call_method(
            self.inner.inner,
            "remove",
            "(Ljava/lang/Object;)Z",
            &[object.into()],
        )?;
        remove.z()
    }

    /// Removes the element at the specified position in this list (optional operation).
    pub fn remove_at(&self, index: i32) -> Result<Option<Object<'a>>> {
        let value = self.env.call_method(
            self.inner.inner,
            "remove",
            "(I)Ljava/lang/Object;",
            &[JValue::Int(index)],
        )?;
        let maybe_removed = value.l()?;
        match maybe_removed.is_null() {
            true => Ok(None),
            false => Ok(Some(Object::new(
                self.env,
                maybe_removed,
                self.class.clone(),
            ))),
        }
    }

    /// Replaces the element at the specified position in this list with the specified element (optional operation).
    pub fn set(&self, object: &Object<'a>, index: i32) -> Result<Option<Object<'a>>> {
        let replaced = self.env.call_method(
            self.inner.inner,
            "set",
            "(ILjava/lang/Object;)Ljava/lang/Object;",
            &[JValue::Int(index), object.into()],
        )?;
        let maybe_replaced = replaced.l()?;
        match maybe_replaced.is_null() {
            true => Ok(None),
            false => Ok(Some(Object::new(
                self.env,
                maybe_replaced,
                self.class.clone(),
            ))),
        }
    }

    /// Returns the number of elements in this list.
    pub fn size(&self) -> Result<i32> {
        let size = self.env.call_method(self.inner.inner, "size", "()I", &[])?;
        size.i()
    }

    /// Returns a view of the portion of this list between the specified from index, inclusive, and to index, exclusive.
    pub fn sublist(&self, from: i32, to: i32) -> Result<List<'a>> {
        let sublist = self.env.call_method(
            self.inner.inner,
            "subList",
            "(II)Ljava/util/List;",
            &[JValue::Int(from), JValue::Int(to)],
        )?;
        Ok(Self::new(
            self.env,
            Object::new(self.env, sublist.l()?, self.inner.class.clone()),
            self.class.clone(),
        ))
    }

    /// Returns an iterator over the elements in this list in proper sequence.
    pub fn iterator(&self) -> Result<crate::Iterator<'a>> {
        let iterator =
            self.env
                .call_method(self.inner.inner, "iterator", "()Ljava/util/Iterator;", &[])?;
        Ok(crate::Iterator::new(
            self.env,
            Object::new(self.env, iterator.l()?, Class::Iterator(self.env)?),
            self.class.clone(),
        ))
    }
}

#[cfg(test)]
mod test {
    use super::List;
    use crate::class::Class;
    use crate::object::Object;
    use crate::test::JVM;

    #[test]
    fn arraylist() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        assert!(List::arraylist(&env, Class::Object(&env).unwrap()).is_ok())
    }

    #[test]
    fn add() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();

        let has_changed = list
            .add(&Object::new_integer_object(&env, 10).unwrap())
            .unwrap();
        assert!(has_changed);

        let size = list.size().unwrap();
        assert_eq!(1, size);
    }

    #[test]
    fn add_at() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        list.add(&Object::new_integer_object(&env, 20).unwrap())
            .unwrap();

        list.add_at(&Object::new_integer_object(&env, 10).unwrap(), 0)
            .unwrap();

        let zeroth = list.get(0).unwrap().unwrap();
        let zeroth_int = env
            .call_method(zeroth.inner, "intValue", "()I", &[])
            .unwrap()
            .i()
            .unwrap();
        assert_eq!(10, zeroth_int);

        let first = list.get(1).unwrap().unwrap();
        let first_int = env
            .call_method(first.inner, "intValue", "()I", &[])
            .unwrap()
            .i()
            .unwrap();
        assert_eq!(20, first_int);
    }

    #[test]
    fn clear() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        list.add(&Object::new_integer_object(&env, 20).unwrap())
            .unwrap();

        list.clear().unwrap();

        let size = list.size().unwrap();
        assert_eq!(0, size);
    }

    #[test]
    fn contains() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let contains = list.contains(&integer).unwrap();
        assert!(contains)
    }

    #[test]
    fn get() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let zeroth = list.get(0).unwrap().unwrap();
        assert!(integer.equals(&zeroth).unwrap())
    }

    #[test]
    fn index_of() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let index_of = list.index_of(&integer).unwrap();
        assert_eq!(0, index_of);
    }

    #[test]
    fn is_empty() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();

        let is_empty = list.is_empty().unwrap();
        assert!(is_empty);
    }

    #[test]
    fn remove() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let list_changed = list.remove(&integer).unwrap();
        assert!(list_changed);
    }

    #[test]
    fn remove_at() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let removed = list.remove_at(0).unwrap().unwrap();
        let equals = integer.equals(&removed).unwrap();

        assert!(equals)
    }

    #[test]
    fn set() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let new_integer = Object::new_integer_object(&env, 10).unwrap();

        let old_integer = list.set(&new_integer, 0).unwrap().unwrap();
        let equal = integer.equals(&old_integer).unwrap();
        assert!(equal);
    }

    #[test]
    fn size() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        let integer = Object::new_integer_object(&env, 20).unwrap();
        list.add(&integer).unwrap();

        let size = list.size().unwrap();
        assert_eq!(1, size);
    }

    #[test]
    fn sublist() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();
        list.add(&Object::new_integer_object(&env, 10).unwrap())
            .unwrap();
        list.add(&Object::new_integer_object(&env, 20).unwrap())
            .unwrap();
        list.add(&Object::new_integer_object(&env, 30).unwrap())
            .unwrap();

        let sublist = list.sublist(1, 3).unwrap();
        let size = sublist.size().unwrap();
        assert_eq!(2, size);
    }

    #[test]
    fn iterator() {
        let jvm = JVM.lock().unwrap();
        let env = jvm.attach_current_thread().unwrap();
        let list = List::arraylist(&env, Class::Integer(&env).unwrap()).unwrap();

        let iterator = list.iterator();
        assert!(iterator.is_ok());
    }
}