Use helper function getIndexForValue in MulticastRoutingCoordinator.

The SparseArray.indexOfValue() uses == to compare values,
MulticastRoutingCoordinator uses SparseArray with String type values,
and the indexOfValue function would sometimes return -1 when looking for
a value in the SparseArray.

Added a helper function getIndexForValue in CollectionUtils to get index
by comparing values with equals, and used this function in MulticastRoutingCoordinator.

Updated
MulticastRoutingCoordinatorServiceTest#testMulticastRouting_applyConfigNone_removesMfc
test case to use copies of interface names when updating the multicast
configs, so the test would fail without this fix.

Test: atest NetworkStaticLibTests:com.android.net.moduletests.util.CollectionUtilsTest#testGetIndexForValue
atest android.net.connectivity.com.android.server.connectivity.MulticastRoutingCoordinatorServiceTest#testMulticastRouting_applyConfigNone_removesMfc

Change-Id: I862242d6be01b8552cdd6af6c9691948a9f0bfe0
This commit is contained in:
Yang Sun 2024-04-14 16:24:37 +08:00
commit 4e7baadc71
2 changed files with 52 additions and 6 deletions

View file

@ -389,4 +389,28 @@ public final class CollectionUtils {
}
return dest;
}
/**
* Returns an index of the given SparseArray that contains the given value, or -1
* number if no keys map to the given value.
*
* <p>Note this is a linear search, and if multiple keys can map to the same value
* then the smallest index is returned.
*
* <p>This function compares values with {@code equals} while the
* {@link SparseArray#indexOfValue} compares values using {@code ==}.
*/
public static <T> int getIndexForValue(SparseArray<T> sparseArray, T value) {
for(int i = 0, nsize = sparseArray.size(); i < nsize; i++) {
T valueAt = sparseArray.valueAt(i);
if (valueAt == null) {
if (value == null) {
return i;
};
} else if (valueAt.equals(value)) {
return i;
}
}
return -1;
}
}

View file

@ -16,6 +16,7 @@
package com.android.net.module.util
import android.util.SparseArray
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.android.testutils.assertThrows
@ -179,4 +180,20 @@ class CollectionUtilsTest {
CollectionUtils.assoc(listOf(1, 2), list15)
}
}
@Test
fun testGetIndexForValue() {
val sparseArray = SparseArray<String>();
sparseArray.put(5, "hello");
sparseArray.put(10, "abcd");
sparseArray.put(20, null);
val value1 = "abcd";
val value1Copy = String(value1.toCharArray())
val value2 = null;
assertEquals(1, CollectionUtils.getIndexForValue(sparseArray, value1));
assertEquals(1, CollectionUtils.getIndexForValue(sparseArray, value1Copy));
assertEquals(2, CollectionUtils.getIndexForValue(sparseArray, value2));
}
}