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
use crate::{
    errors::*,
    objects::{JMethodID, JObject},
    signature::{JavaType, Primitive},
    sys::jint,
    JNIEnv,
};

/// Wrapper for JObjects that implement `java/util/List`. Provides methods to get,
/// add, and remove elements.
///
/// Looks up the class and method ids on creation rather than for every method
/// call.
pub struct JList<'a: 'b, 'b> {
    internal: JObject<'a>,
    get: JMethodID<'a>,
    add: JMethodID<'a>,
    add_idx: JMethodID<'a>,
    remove: JMethodID<'a>,
    size: JMethodID<'a>,
    env: &'b JNIEnv<'a>,
}

impl<'a: 'b, 'b> ::std::ops::Deref for JList<'a, 'b> {
    type Target = JObject<'a>;

    fn deref(&self) -> &Self::Target {
        &self.internal
    }
}

impl<'a: 'b, 'b> From<JList<'a, 'b>> for JObject<'a> {
    fn from(other: JList<'a, 'b>) -> JObject<'a> {
        other.internal
    }
}

impl<'a: 'b, 'b> JList<'a, 'b> {
    /// Create a map from the environment and an object. This looks up the
    /// necessary class and method ids to call all of the methods on it so that
    /// exra work doesn't need to be done on every method call.
    pub fn from_env(env: &'b JNIEnv<'a>, obj: JObject<'a>) -> Result<JList<'a, 'b>> {
        let class = env.auto_local(env.find_class("java/util/List")?);

        let get = env.get_method_id(&class, "get", "(I)Ljava/lang/Object;")?;
        let add = env.get_method_id(&class, "add", "(Ljava/lang/Object;)Z")?;
        let add_idx = env.get_method_id(&class, "add", "(ILjava/lang/Object;)V")?;
        let remove = env.get_method_id(&class, "remove", "(I)Ljava/lang/Object;")?;
        let size = env.get_method_id(&class, "size", "()I")?;

        Ok(JList {
            internal: obj,
            get,
            add,
            add_idx,
            remove,
            size,
            env,
        })
    }

    /// Look up the value for a key. Returns `Some` if it's found and `None` if
    /// a null pointer would be returned.
    pub fn get(&self, idx: jint) -> Result<Option<JObject<'a>>> {
        let result = self.env.call_method_unchecked(
            self.internal,
            self.get,
            JavaType::Object("java/lang/Object".into()),
            &[idx.into()],
        );

        match result {
            Ok(val) => Ok(Some(val.l()?)),
            Err(e) => match e {
                Error::NullPtr(_) => Ok(None),
                _ => Err(e),
            },
        }
    }

    /// Append an element to the list
    pub fn add(&self, value: JObject<'a>) -> Result<()> {
        let result = self.env.call_method_unchecked(
            self.internal,
            self.add,
            JavaType::Primitive(Primitive::Boolean),
            &[value.into()],
        );

        let _ = result?;
        Ok(())
    }

    /// Insert an element at a specific index
    pub fn insert(&self, idx: jint, value: JObject<'a>) -> Result<()> {
        let result = self.env.call_method_unchecked(
            self.internal,
            self.add_idx,
            JavaType::Primitive(Primitive::Void),
            &[idx.into(), value.into()],
        );

        let _ = result?;
        Ok(())
    }

    /// Remove an element from the list by index
    pub fn remove(&self, idx: jint) -> Result<Option<JObject<'a>>> {
        let result = self.env.call_method_unchecked(
            self.internal,
            self.remove,
            JavaType::Object("java/lang/Object".into()),
            &[idx.into()],
        );

        match result {
            Ok(val) => Ok(Some(val.l()?)),
            Err(e) => match e {
                Error::NullPtr(_) => Ok(None),
                _ => Err(e),
            },
        }
    }

    /// Get the size of the list
    pub fn size(&self) -> Result<jint> {
        let result = self.env.call_method_unchecked(
            self.internal,
            self.size,
            JavaType::Primitive(Primitive::Int),
            &[],
        );

        result.and_then(|v| v.i())
    }

    /// Pop the last element from the list
    ///
    /// Note that this calls `size()` to determine the last index.
    pub fn pop(&self) -> Result<Option<JObject<'a>>> {
        let size = self.size()?;
        if size == 0 {
            return Ok(None);
        }

        let result = self.env.call_method_unchecked(
            self.internal,
            self.remove,
            JavaType::Object("java/lang/Object".into()),
            &[(size - 1).into()],
        );

        match result {
            Ok(val) => Ok(Some(val.l()?)),
            Err(e) => match e {
                Error::NullPtr(_) => Ok(None),
                _ => Err(e),
            },
        }
    }

    /// Get key/value iterator for the map. This is done by getting the
    /// `EntrySet` from java and iterating over it.
    pub fn iter(&self) -> Result<JListIter<'a, 'b, '_>> {
        Ok(JListIter {
            list: &self,
            current: 0,
            size: self.size()?,
        })
    }
}

/// An iterator over the keys and values in a map.
///
/// TODO: make the iterator implementation for java iterators its own thing
/// and generic enough to use elsewhere.
pub struct JListIter<'a: 'b, 'b: 'c, 'c> {
    list: &'c JList<'a, 'b>,
    current: jint,
    size: jint,
}

impl<'a: 'b, 'b: 'c, 'c> Iterator for JListIter<'a, 'b, 'c> {
    type Item = JObject<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current == self.size {
            return None;
        }
        let res = self.list.get(self.current);
        match res {
            Ok(elem) => {
                self.current += 1;
                elem
            }
            Err(_) => {
                self.current = self.size;
                None
            }
        }
    }
}