/ app / src / main / java / com / reandroid / arsc / item / StringBlock.java
StringBlock.java
 1  /*
 2   *  Copyright (C) 2022 github.com/REAndroid
 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 com.reandroid.arsc.item;
17  
18  import com.reandroid.utils.StringsUtil;
19  
20  import java.nio.charset.CharsetDecoder;
21  import java.nio.charset.StandardCharsets;
22  
23  public abstract class StringBlock extends BlockItem implements StringReference {
24  
25      private String mCache;
26  
27      public StringBlock() {
28          super(0);
29          mCache = StringsUtil.EMPTY;
30      }
31      public String get(){
32          return mCache;
33      }
34      public void set(String text){
35          set(text, true);
36      }
37      public void set(String text, boolean notify){
38          if(android.text.TextUtils.isEmpty(text)){
39              text = StringsUtil.EMPTY;
40          }
41          String old = this.mCache;
42          boolean firstTime = countBytes() == 0;
43          if(firstTime) {
44              old = null;
45          }else if(text.equals(old)) {
46              return;
47          }
48          this.mCache = text;
49          byte[] bytes = encodeString(text);
50          setBytesInternal(bytes, false);
51          if(notify){
52              onStringChanged(old, text);
53          }
54      }
55      protected void onBytesChanged(){
56          mCache = decodeString(getBytesInternal());
57      }
58      protected void onStringChanged(String old, String text){
59      }
60      protected abstract String decodeString(byte[] bytes);
61      protected abstract byte[] encodeString(String text);
62  
63      public int compareTo(StringBlock stringBlock){
64          if(stringBlock == null){
65              return -1;
66          }
67          return StringsUtil.compareStrings(get(), stringBlock.get());
68      }
69      @Override
70      public String toString() {
71          return get();
72      }
73  
74      public static final CharsetDecoder UTF8_DECODER = StandardCharsets.UTF_8.newDecoder();
75  }