View Javadoc
1   /*
2    * Copyright 2021 TiKV Project Authors.
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  
18  package org.tikv.common.key;
19  
20  import com.google.common.base.Joiner;
21  import java.util.ArrayList;
22  import java.util.List;
23  import org.tikv.common.codec.CodecDataOutput;
24  
25  public class CompoundKey extends Key {
26  
27    private final List<Key> keys;
28  
29    protected CompoundKey(List<Key> keys, byte[] value) {
30      super(value);
31      this.keys = keys;
32    }
33  
34    public static CompoundKey concat(Key lKey, Key rKey) {
35      Builder builder = newBuilder();
36      builder.append(lKey).append(rKey);
37      return builder.build();
38    }
39  
40    public static Builder newBuilder() {
41      return new Builder();
42    }
43  
44    public List<Key> getKeys() {
45      return keys;
46    }
47  
48    @Override
49    public String toString() {
50      return String.format("[%s]", Joiner.on(",").useForNull("Null").join(keys));
51    }
52  
53    public static class Builder {
54      private final List<Key> keys = new ArrayList<>();
55  
56      public Builder append(Key key) {
57        if (key instanceof CompoundKey) {
58          CompoundKey compKey = (CompoundKey) key;
59          for (Key child : compKey.getKeys()) {
60            append(child);
61          }
62        } else {
63          keys.add(key);
64        }
65        return this;
66      }
67  
68      public CompoundKey build() {
69        int totalLen = 0;
70        for (Key key : keys) {
71          totalLen += key.getBytes().length;
72        }
73        CodecDataOutput cdo = new CodecDataOutput(totalLen);
74        for (Key key : keys) {
75          cdo.write(key.getBytes());
76        }
77        return new CompoundKey(keys, cdo.toBytes());
78      }
79    }
80  }