1 /* 2 * Copyright (C) 2018 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 package android.ext.services.autofill; 17 18 import android.os.Bundle; 19 import android.view.autofill.AutofillValue; 20 21 import androidx.annotation.Nullable; 22 import androidx.annotation.VisibleForTesting; 23 24 final class ExactMatch { 25 26 /** 27 * Arg for {@link #calculateScore} that enforces only matching the last N values. 28 * 29 * <p>Must supply an int N.</p> 30 */ 31 public static final String MATCH_SUFFIX = "MATCH_SUFFIX"; 32 33 /** 34 * Gets the field classification score of 2 values based on whether they are an exact match 35 * 36 * @return {@code 1.0} if the two values are an exact match, {@code 0.0} otherwise. 37 */ 38 @VisibleForTesting calculateScore(@ullable AutofillValue actualValue, @Nullable String userDataValue, @Nullable Bundle args)39 static float calculateScore(@Nullable AutofillValue actualValue, 40 @Nullable String userDataValue, @Nullable Bundle args) { 41 if (actualValue == null || !actualValue.isText() || userDataValue == null) return 0; 42 43 final String actualValueText = actualValue.getTextValue().toString(); 44 45 if (args == null) { 46 return actualValueText.equalsIgnoreCase(userDataValue) ? 1 : 0; 47 } 48 49 final int suffixLength = args.getInt(MATCH_SUFFIX, -1); 50 51 if (suffixLength < 0) { 52 throw new IllegalArgumentException("suffix argument is invalid"); 53 } 54 55 final String actualValueSuffix; 56 if (suffixLength < actualValueText.length()) { 57 actualValueSuffix = actualValueText.substring(actualValueText.length() 58 - suffixLength); 59 } else { 60 actualValueSuffix = actualValueText; 61 } 62 63 final String userDataValueSuffix; 64 if (suffixLength < userDataValue.length()) { 65 userDataValueSuffix = userDataValue.substring(userDataValue.length() 66 - suffixLength); 67 } else { 68 userDataValueSuffix = userDataValue; 69 } 70 71 return (actualValueSuffix.equalsIgnoreCase(userDataValueSuffix)) ? 1 : 0; 72 } 73 } 74