1 // Copyright 2019 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.shared_preferences; 6 7 /** 8 * A prefix for a range of SharedPreferences keys generated dynamically. 9 * 10 * Instances should be declared as keys in the PreferenceKeys registry. 11 */ 12 public class KeyPrefix { 13 private final String mPrefix; 14 KeyPrefix(String pattern)15 public KeyPrefix(String pattern) { 16 // More thorough checking is performed in ChromePreferenceKeysTest. 17 assert pattern.endsWith("*"); 18 mPrefix = pattern.substring(0, pattern.length() - 1); 19 } 20 21 /** 22 * @param stem A non-empty string. The '*' character is reserved. 23 * @return The complete SharedPreferences key to be passed to {@link SharedPreferencesManager}. 24 */ createKey(String stem)25 public String createKey(String stem) { 26 return mPrefix + stem; 27 } 28 29 /** 30 * @param index An int to generate a unique key. 31 * @return The complete SharedPreferences key to be passed to {@link SharedPreferencesManager}. 32 */ createKey(int index)33 public String createKey(int index) { 34 return mPrefix + index; 35 } 36 pattern()37 public String pattern() { 38 return mPrefix + "*"; 39 } 40 hasGenerated(String key)41 public boolean hasGenerated(String key) { 42 return key.startsWith(mPrefix); 43 } 44 } 45