Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 23e0eef4 authored by Kweku Adams's avatar Kweku Adams
Browse files

Add methods to simplify UptcMap usage.

Add a getOrCreate method so an object can be created if one doesn't
exist.
Add a new forEach method that will also supply the userId, packageName,
and tag to the consumer.

Bug: 135764360
Test: atest CountQuotaTrackerTest
Test: atest DurationQuotaTrackerTest
Change-Id: I9807fdd25ee2434e6c53b07cba4c0be7e5879237
parent 8268f080
Loading
Loading
Loading
Loading
+40 −0
Original line number Diff line number Diff line
@@ -22,6 +22,7 @@ import android.util.ArrayMap;
import android.util.SparseArrayMap;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * A SparseArrayMap of ArrayMaps, which is suitable for holding userId-packageName-tag combination
@@ -94,6 +95,23 @@ class UptcMap<T> {
        return data != null ? data.get(tag) : null;
    }

    /**
     * Returns the saved object for the given UPTC. If there was no saved object, it will create a
     * new object using creator, insert it, and return it.
     */
    @Nullable
    public T getOrCreate(int userId, @NonNull String packageName, @Nullable String tag,
            Function<Void, T> creator) {
        final ArrayMap<String, T> data = mData.get(userId, packageName);
        if (data == null || !data.containsKey(tag)) {
            // We've never inserted data for this combination before. Create a new object.
            final T val = creator.apply(null);
            add(userId, packageName, tag, val);
            return val;
        }
        return data.get(tag);
    }

    /**
     * Returns the index for which {@link #getUserIdAtIndex(int)} would return the specified userId,
     * or a negative number if the specified userId is not mapped.
@@ -160,4 +178,26 @@ class UptcMap<T> {
            }
        });
    }

    public void forEach(UptcDataConsumer<T> consumer) {
        final int uCount = userCount();
        for (int u = 0; u < uCount; ++u) {
            final int userId = getUserIdAtIndex(u);

            final int pkgCount = packageCountForUser(userId);
            for (int p = 0; p < pkgCount; ++p) {
                final String pkgName = getPackageNameAtIndex(u, p);

                final int tagCount = tagCountForUserAndPackage(userId, pkgName);
                for (int t = 0; t < tagCount; ++t) {
                    final String tag = getTagAtIndex(u, p, t);
                    consumer.accept(userId, pkgName, tag, get(userId, pkgName, tag));
                }
            }
        }
    }

    interface UptcDataConsumer<D> {
        void accept(int userId, @NonNull String packageName, @Nullable String tag, @Nullable D obj);
    }
}