1/*
2 * Copyright 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
17package androidx.room.migration.bundle;
18
19import androidx.annotation.Nullable;
20import androidx.annotation.RestrictTo;
21
22import java.util.List;
23import java.util.Map;
24
25/**
26 * utility class to run schema equality on collections.
27 *
28 * @hide
29 */
30@RestrictTo(RestrictTo.Scope.LIBRARY)
31class SchemaEqualityUtil {
32    static <T, K extends SchemaEquality<K>> boolean checkSchemaEquality(
33            @Nullable Map<T, K> map1, @Nullable Map<T, K> map2) {
34        if (map1 == null) {
35            return map2 == null;
36        }
37        if (map2 == null) {
38            return false;
39        }
40        if (map1.size() != map2.size()) {
41            return false;
42        }
43        for (Map.Entry<T, K> pair : map1.entrySet()) {
44            if (!checkSchemaEquality(pair.getValue(), map2.get(pair.getKey()))) {
45                return false;
46            }
47        }
48        return true;
49    }
50
51    static <K extends SchemaEquality<K>> boolean checkSchemaEquality(
52            @Nullable List<K> list1, @Nullable List<K> list2) {
53        if (list1 == null) {
54            return list2 == null;
55        }
56        if (list2 == null) {
57            return false;
58        }
59        if (list1.size() != list2.size()) {
60            return false;
61        }
62        // we don't care this is n^2, small list + only used for testing.
63        for (K item1 : list1) {
64            // find matching item
65            boolean matched = false;
66            for (K item2 : list2) {
67                if (checkSchemaEquality(item1, item2)) {
68                    matched = true;
69                    break;
70                }
71            }
72            if (!matched) {
73                return false;
74            }
75        }
76        return true;
77    }
78
79    @SuppressWarnings("SimplifiableIfStatement")
80    static <K extends SchemaEquality<K>> boolean checkSchemaEquality(
81            @Nullable K item1, @Nullable K item2) {
82        if (item1 == null) {
83            return item2 == null;
84        }
85        if (item2 == null) {
86            return false;
87        }
88        return item1.isSchemaEqual(item2);
89    }
90
91    private SchemaEqualityUtil() {
92    }
93}
94