BitUtils.java revision 36e866b8e0ec08e45b5e7fbc65aeeb3a9bb7b11e
1/*
2 * Copyright (C) 2017 The Android Open Source Project
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
18package com.android.internal.util;
19
20import android.annotation.Nullable;
21
22import libcore.util.Objects;
23
24import java.util.Arrays;
25import java.util.UUID;
26
27public class BitUtils {
28    private BitUtils() {}
29
30    public static boolean maskedEquals(long a, long b, long mask) {
31        return (a & mask) == (b & mask);
32    }
33
34    public static boolean maskedEquals(byte a, byte b, byte mask) {
35        return (a & mask) == (b & mask);
36    }
37
38    public static boolean maskedEquals(byte[] a, byte[] b, @Nullable byte[] mask) {
39        if (a == null || b == null) return a == b;
40        Preconditions.checkArgument(a.length == b.length, "Inputs must be of same size");
41        if (mask == null) return Arrays.equals(a, b);
42        Preconditions.checkArgument(a.length == mask.length, "Mask must be of same size as inputs");
43        for (int i = 0; i < mask.length; i++) {
44            if (!maskedEquals(a[i], b[i], mask[i])) return false;
45        }
46        return true;
47    }
48
49    public static boolean maskedEquals(UUID a, UUID b, @Nullable UUID mask) {
50        if (mask == null) {
51            return Objects.equal(a, b);
52        }
53        return maskedEquals(a.getLeastSignificantBits(), b.getLeastSignificantBits(),
54                    mask.getLeastSignificantBits())
55                && maskedEquals(a.getMostSignificantBits(), b.getMostSignificantBits(),
56                    mask.getMostSignificantBits());
57    }
58}
59