• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.facebook.jni;
18 
19 import com.facebook.jni.annotations.DoNotStrip;
20 import java.util.Iterator;
21 import java.util.Map;
22 import javax.annotation.Nullable;
23 
24 /**
25  * To iterate over a Map from C++ requires four calls per entry: hasNext(), next(), getKey(),
26  * getValue(). This helper reduces it to one call and two field gets per entry. It does not use a
27  * generic argument, since in C++, the types will be erased, anyway. This is *not* a {@link
28  * java.util.Iterator}.
29  */
30 @DoNotStrip
31 public class MapIteratorHelper {
32   @DoNotStrip private final Iterator<Map.Entry> mIterator;
33   @DoNotStrip private @Nullable Object mKey;
34   @DoNotStrip private @Nullable Object mValue;
35 
36   @DoNotStrip
MapIteratorHelper(Map map)37   public MapIteratorHelper(Map map) {
38     mIterator = map.entrySet().iterator();
39   }
40 
41   /**
42    * Moves the helper to the next entry in the map, if any. Returns true iff there is an entry to
43    * read.
44    */
45   @DoNotStrip
hasNext()46   boolean hasNext() {
47     if (mIterator.hasNext()) {
48       Map.Entry entry = mIterator.next();
49       mKey = entry.getKey();
50       mValue = entry.getValue();
51       return true;
52     } else {
53       mKey = null;
54       mValue = null;
55       return false;
56     }
57   }
58 }
59