View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase;
21  
22  import static org.apache.hadoop.hbase.util.Bytes.len;
23  
24  import java.io.DataInput;
25  import java.io.DataOutput;
26  import java.io.IOException;
27  import java.io.InputStream;
28  import java.io.OutputStream;
29  import java.nio.ByteBuffer;
30  import java.util.ArrayList;
31  import java.util.Arrays;
32  import java.util.Comparator;
33  import java.util.HashMap;
34  import java.util.List;
35  import java.util.Map;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.io.HeapSize;
41  import org.apache.hadoop.hbase.io.util.StreamUtils;
42  import org.apache.hadoop.hbase.util.Bytes;
43  import org.apache.hadoop.hbase.util.ClassSize;
44  import org.apache.hadoop.io.IOUtils;
45  import org.apache.hadoop.io.RawComparator;
46  
47  import com.google.common.annotations.VisibleForTesting;
48  
49  /**
50   * An HBase Key/Value. This is the fundamental HBase Type.
51   * <p>
52   * HBase applications and users should use the Cell interface and avoid directly using KeyValue
53   * and member functions not defined in Cell.
54   * <p>
55   * If being used client-side, the primary methods to access individual fields are {@link #getRow()},
56   * {@link #getFamily()}, {@link #getQualifier()}, {@link #getTimestamp()}, and {@link #getValue()}.
57   * These methods allocate new byte arrays and return copies. Avoid their use server-side.
58   * <p>
59   * Instances of this class are immutable. They do not implement Comparable but Comparators are
60   * provided. Comparators change with context, whether user table or a catalog table comparison. Its
61   * critical you use the appropriate comparator. There are Comparators for normal HFiles, Meta's
62   * Hfiles, and bloom filter keys.
63   * <p>
64   * KeyValue wraps a byte array and takes offsets and lengths into passed array at where to start
65   * interpreting the content as KeyValue. The KeyValue format inside a byte array is:
66   * <code>&lt;keylength> &lt;valuelength> &lt;key> &lt;value></code> Key is further decomposed as:
67   * <code>&lt;rowlength> &lt;row> &lt;columnfamilylength> &lt;columnfamily> &lt;columnqualifier>
68   * &lt;timestamp> &lt;keytype></code>
69   * The <code>rowlength</code> maximum is <code>Short.MAX_SIZE</code>, column family length maximum
70   * is <code>Byte.MAX_SIZE</code>, and column qualifier + key length must be <
71   * <code>Integer.MAX_SIZE</code>. The column does not contain the family/qualifier delimiter,
72   * {@link #COLUMN_FAMILY_DELIMITER}<br>
73   * KeyValue can optionally contain Tags. When it contains tags, it is added in the byte array after
74   * the value part. The format for this part is: <code>&lt;tagslength>&lt;tagsbytes></code>.
75   * <code>tagslength</code> maximum is <code>Short.MAX_SIZE</code>. The <code>tagsbytes</code>
76   * contain one or more tags where as each tag is of the form
77   * <code>&lt;taglength>&lt;tagtype>&lt;tagbytes></code>.  <code>tagtype</code> is one byte and
78   * <code>taglength</code> maximum is <code>Short.MAX_SIZE</code> and it includes 1 byte type length
79   * and actual tag bytes length.
80   */
81  @InterfaceAudience.Private
82  public class KeyValue implements Cell, HeapSize, Cloneable, SettableSequenceId, SettableTimestamp {
83    private static final ArrayList<Tag> EMPTY_ARRAY_LIST = new ArrayList<Tag>();
84  
85    static final Log LOG = LogFactory.getLog(KeyValue.class);
86  
87    /**
88     * Colon character in UTF-8
89     */
90    public static final char COLUMN_FAMILY_DELIMITER = ':';
91  
92    public static final byte[] COLUMN_FAMILY_DELIM_ARRAY =
93      new byte[]{COLUMN_FAMILY_DELIMITER};
94  
95    /**
96     * Comparator for plain key/values; i.e. non-catalog table key/values. Works on Key portion
97     * of KeyValue only.
98     */
99    public static final KVComparator COMPARATOR = new KVComparator();
100   /**
101    * A {@link KVComparator} for <code>hbase:meta</code> catalog table
102    * {@link KeyValue}s.
103    */
104   public static final KVComparator META_COMPARATOR = new MetaComparator();
105 
106   /**
107    * Needed for Bloom Filters.
108    */
109   public static final KVComparator RAW_COMPARATOR = new RawBytesComparator();
110 
111   /** Size of the key length field in bytes*/
112   public static final int KEY_LENGTH_SIZE = Bytes.SIZEOF_INT;
113 
114   /** Size of the key type field in bytes */
115   public static final int TYPE_SIZE = Bytes.SIZEOF_BYTE;
116 
117   /** Size of the row length field in bytes */
118   public static final int ROW_LENGTH_SIZE = Bytes.SIZEOF_SHORT;
119 
120   /** Size of the family length field in bytes */
121   public static final int FAMILY_LENGTH_SIZE = Bytes.SIZEOF_BYTE;
122 
123   /** Size of the timestamp field in bytes */
124   public static final int TIMESTAMP_SIZE = Bytes.SIZEOF_LONG;
125 
126   // Size of the timestamp and type byte on end of a key -- a long + a byte.
127   public static final int TIMESTAMP_TYPE_SIZE = TIMESTAMP_SIZE + TYPE_SIZE;
128 
129   // Size of the length shorts and bytes in key.
130   public static final int KEY_INFRASTRUCTURE_SIZE = ROW_LENGTH_SIZE
131       + FAMILY_LENGTH_SIZE + TIMESTAMP_TYPE_SIZE;
132 
133   // How far into the key the row starts at. First thing to read is the short
134   // that says how long the row is.
135   public static final int ROW_OFFSET =
136     Bytes.SIZEOF_INT /*keylength*/ +
137     Bytes.SIZEOF_INT /*valuelength*/;
138 
139   // Size of the length ints in a KeyValue datastructure.
140   public static final int KEYVALUE_INFRASTRUCTURE_SIZE = ROW_OFFSET;
141 
142   /** Size of the tags length field in bytes */
143   public static final int TAGS_LENGTH_SIZE = Bytes.SIZEOF_SHORT;
144 
145   public static final int KEYVALUE_WITH_TAGS_INFRASTRUCTURE_SIZE = ROW_OFFSET + TAGS_LENGTH_SIZE;
146 
147   private static final int MAX_TAGS_LENGTH = (2 * Short.MAX_VALUE) + 1;
148 
149   /**
150    * Computes the number of bytes that a <code>KeyValue</code> instance with the provided
151    * characteristics would take up for its underlying data structure.
152    *
153    * @param rlength row length
154    * @param flength family length
155    * @param qlength qualifier length
156    * @param vlength value length
157    *
158    * @return the <code>KeyValue</code> data structure length
159    */
160   public static long getKeyValueDataStructureSize(int rlength,
161       int flength, int qlength, int vlength) {
162     return KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE
163         + getKeyDataStructureSize(rlength, flength, qlength) + vlength;
164   }
165 
166   /**
167    * Computes the number of bytes that a <code>KeyValue</code> instance with the provided
168    * characteristics would take up for its underlying data structure.
169    *
170    * @param rlength row length
171    * @param flength family length
172    * @param qlength qualifier length
173    * @param vlength value length
174    * @param tagsLength total length of the tags
175    *
176    * @return the <code>KeyValue</code> data structure length
177    */
178   public static long getKeyValueDataStructureSize(int rlength, int flength, int qlength,
179       int vlength, int tagsLength) {
180     if (tagsLength == 0) {
181       return getKeyValueDataStructureSize(rlength, flength, qlength, vlength);
182     }
183     return KeyValue.KEYVALUE_WITH_TAGS_INFRASTRUCTURE_SIZE
184         + getKeyDataStructureSize(rlength, flength, qlength) + vlength + tagsLength;
185   }
186 
187   /**
188    * Computes the number of bytes that a <code>KeyValue</code> instance with the provided
189    * characteristics would take up for its underlying data structure.
190    *
191    * @param klength key length
192    * @param vlength value length
193    * @param tagsLength total length of the tags
194    *
195    * @return the <code>KeyValue</code> data structure length
196    */
197   public static long getKeyValueDataStructureSize(int klength, int vlength, int tagsLength) {
198     if (tagsLength == 0) {
199       return KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE + klength + vlength;
200     }
201     return KeyValue.KEYVALUE_WITH_TAGS_INFRASTRUCTURE_SIZE + klength + vlength + tagsLength;
202   }
203 
204   /**
205    * Computes the number of bytes that a <code>KeyValue</code> instance with the provided
206    * characteristics would take up in its underlying data structure for the key.
207    *
208    * @param rlength row length
209    * @param flength family length
210    * @param qlength qualifier length
211    *
212    * @return the key data structure length
213    */
214   public static long getKeyDataStructureSize(int rlength, int flength, int qlength) {
215     return KeyValue.KEY_INFRASTRUCTURE_SIZE + rlength + flength + qlength;
216   }
217 
218   /**
219    * Key type.
220    * Has space for other key types to be added later.  Cannot rely on
221    * enum ordinals . They change if item is removed or moved.  Do our own codes.
222    */
223   public static enum Type {
224     Minimum((byte)0),
225     Put((byte)4),
226 
227     Delete((byte)8),
228     DeleteFamilyVersion((byte)10),
229     DeleteColumn((byte)12),
230     DeleteFamily((byte)14),
231 
232     // Maximum is used when searching; you look from maximum on down.
233     Maximum((byte)255);
234 
235     private final byte code;
236 
237     Type(final byte c) {
238       this.code = c;
239     }
240 
241     public byte getCode() {
242       return this.code;
243     }
244 
245     /**
246      * Cannot rely on enum ordinals . They change if item is removed or moved.
247      * Do our own codes.
248      * @param b
249      * @return Type associated with passed code.
250      */
251     public static Type codeToType(final byte b) {
252       for (Type t : Type.values()) {
253         if (t.getCode() == b) {
254           return t;
255         }
256       }
257       throw new RuntimeException("Unknown code " + b);
258     }
259   }
260 
261   /**
262    * Lowest possible key.
263    * Makes a Key with highest possible Timestamp, empty row and column.  No
264    * key can be equal or lower than this one in memstore or in store file.
265    */
266   public static final KeyValue LOWESTKEY =
267     new KeyValue(HConstants.EMPTY_BYTE_ARRAY, HConstants.LATEST_TIMESTAMP);
268 
269   ////
270   // KeyValue core instance fields.
271   protected byte [] bytes = null;  // an immutable byte array that contains the KV
272   protected int offset = 0;  // offset into bytes buffer KV starts at
273   protected int length = 0;  // length of the KV starting from offset.
274 
275   /**
276    * @return True if a delete type, a {@link KeyValue.Type#Delete} or
277    * a {KeyValue.Type#DeleteFamily} or a {@link KeyValue.Type#DeleteColumn}
278    * KeyValue type.
279    */
280   public static boolean isDelete(byte t) {
281     return Type.Delete.getCode() <= t && t <= Type.DeleteFamily.getCode();
282   }
283 
284   /** Here be dragons **/
285 
286   // used to achieve atomic operations in the memstore.
287   @Override
288   public long getMvccVersion() {
289     return this.getSequenceId();
290   }
291 
292   /**
293    * used to achieve atomic operations in the memstore.
294    */
295   @Override
296   public long getSequenceId() {
297     return seqId;
298   }
299 
300   @Override
301   public void setSequenceId(long seqId) {
302     this.seqId = seqId;
303   }
304 
305   // multi-version concurrency control version.  default value is 0, aka do not care.
306   private long seqId = 0;
307 
308   /** Dragon time over, return to normal business */
309 
310 
311   /** Writable Constructor -- DO NOT USE */
312   public KeyValue() {}
313 
314   /**
315    * Creates a KeyValue from the start of the specified byte array.
316    * Presumes <code>bytes</code> content is formatted as a KeyValue blob.
317    * @param bytes byte array
318    */
319   public KeyValue(final byte [] bytes) {
320     this(bytes, 0);
321   }
322 
323   /**
324    * Creates a KeyValue from the specified byte array and offset.
325    * Presumes <code>bytes</code> content starting at <code>offset</code> is
326    * formatted as a KeyValue blob.
327    * @param bytes byte array
328    * @param offset offset to start of KeyValue
329    */
330   public KeyValue(final byte [] bytes, final int offset) {
331     this(bytes, offset, getLength(bytes, offset));
332   }
333 
334   /**
335    * Creates a KeyValue from the specified byte array, starting at offset, and
336    * for length <code>length</code>.
337    * @param bytes byte array
338    * @param offset offset to start of the KeyValue
339    * @param length length of the KeyValue
340    */
341   public KeyValue(final byte [] bytes, final int offset, final int length) {
342     this.bytes = bytes;
343     this.offset = offset;
344     this.length = length;
345   }
346 
347   /**
348    * Creates a KeyValue from the specified byte array, starting at offset, and
349    * for length <code>length</code>.
350    *
351    * @param bytes  byte array
352    * @param offset offset to start of the KeyValue
353    * @param length length of the KeyValue
354    * @param ts
355    */
356   public KeyValue(final byte[] bytes, final int offset, final int length, long ts) {
357     this(bytes, offset, length, null, 0, 0, null, 0, 0, ts, Type.Maximum, null, 0, 0, null);
358   }
359 
360   /** Constructors that build a new backing byte array from fields */
361 
362   /**
363    * Constructs KeyValue structure filled with null value.
364    * Sets type to {@link KeyValue.Type#Maximum}
365    * @param row - row key (arbitrary byte array)
366    * @param timestamp
367    */
368   public KeyValue(final byte [] row, final long timestamp) {
369     this(row, null, null, timestamp, Type.Maximum, null);
370   }
371 
372   /**
373    * Constructs KeyValue structure filled with null value.
374    * @param row - row key (arbitrary byte array)
375    * @param timestamp
376    */
377   public KeyValue(final byte [] row, final long timestamp, Type type) {
378     this(row, null, null, timestamp, type, null);
379   }
380 
381   /**
382    * Constructs KeyValue structure filled with null value.
383    * Sets type to {@link KeyValue.Type#Maximum}
384    * @param row - row key (arbitrary byte array)
385    * @param family family name
386    * @param qualifier column qualifier
387    */
388   public KeyValue(final byte [] row, final byte [] family,
389       final byte [] qualifier) {
390     this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum);
391   }
392 
393   /**
394    * Constructs KeyValue structure filled with null value.
395    * @param row - row key (arbitrary byte array)
396    * @param family family name
397    * @param qualifier column qualifier
398    */
399   public KeyValue(final byte [] row, final byte [] family,
400       final byte [] qualifier, final byte [] value) {
401     this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Put, value);
402   }
403 
404   /**
405    * Constructs KeyValue structure filled with specified values.
406    * @param row row key
407    * @param family family name
408    * @param qualifier column qualifier
409    * @param timestamp version timestamp
410    * @param type key type
411    * @throws IllegalArgumentException
412    */
413   public KeyValue(final byte[] row, final byte[] family,
414       final byte[] qualifier, final long timestamp, Type type) {
415     this(row, family, qualifier, timestamp, type, null);
416   }
417 
418   /**
419    * Constructs KeyValue structure filled with specified values.
420    * @param row row key
421    * @param family family name
422    * @param qualifier column qualifier
423    * @param timestamp version timestamp
424    * @param value column value
425    * @throws IllegalArgumentException
426    */
427   public KeyValue(final byte[] row, final byte[] family,
428       final byte[] qualifier, final long timestamp, final byte[] value) {
429     this(row, family, qualifier, timestamp, Type.Put, value);
430   }
431 
432   /**
433    * Constructs KeyValue structure filled with specified values.
434    * @param row row key
435    * @param family family name
436    * @param qualifier column qualifier
437    * @param timestamp version timestamp
438    * @param value column value
439    * @param tags tags
440    * @throws IllegalArgumentException
441    */
442   public KeyValue(final byte[] row, final byte[] family,
443       final byte[] qualifier, final long timestamp, final byte[] value,
444       final Tag[] tags) {
445     this(row, family, qualifier, timestamp, value, tags != null ? Arrays.asList(tags) : null);
446   }
447 
448   /**
449    * Constructs KeyValue structure filled with specified values.
450    * @param row row key
451    * @param family family name
452    * @param qualifier column qualifier
453    * @param timestamp version timestamp
454    * @param value column value
455    * @param tags tags non-empty list of tags or null
456    * @throws IllegalArgumentException
457    */
458   public KeyValue(final byte[] row, final byte[] family,
459       final byte[] qualifier, final long timestamp, final byte[] value,
460       final List<Tag> tags) {
461     this(row, 0, row==null ? 0 : row.length,
462       family, 0, family==null ? 0 : family.length,
463       qualifier, 0, qualifier==null ? 0 : qualifier.length,
464       timestamp, Type.Put,
465       value, 0, value==null ? 0 : value.length, tags);
466   }
467 
468   /**
469    * Constructs KeyValue structure filled with specified values.
470    * @param row row key
471    * @param family family name
472    * @param qualifier column qualifier
473    * @param timestamp version timestamp
474    * @param type key type
475    * @param value column value
476    * @throws IllegalArgumentException
477    */
478   public KeyValue(final byte[] row, final byte[] family,
479       final byte[] qualifier, final long timestamp, Type type,
480       final byte[] value) {
481     this(row, 0, len(row),   family, 0, len(family),   qualifier, 0, len(qualifier),
482         timestamp, type,   value, 0, len(value));
483   }
484 
485   /**
486    * Constructs KeyValue structure filled with specified values.
487    * <p>
488    * Column is split into two fields, family and qualifier.
489    * @param row row key
490    * @param family family name
491    * @param qualifier column qualifier
492    * @param timestamp version timestamp
493    * @param type key type
494    * @param value column value
495    * @throws IllegalArgumentException
496    */
497   public KeyValue(final byte[] row, final byte[] family,
498       final byte[] qualifier, final long timestamp, Type type,
499       final byte[] value, final List<Tag> tags) {
500     this(row, family, qualifier, 0, qualifier==null ? 0 : qualifier.length,
501         timestamp, type, value, 0, value==null ? 0 : value.length, tags);
502   }
503 
504   /**
505    * Constructs KeyValue structure filled with specified values.
506    * @param row row key
507    * @param family family name
508    * @param qualifier column qualifier
509    * @param timestamp version timestamp
510    * @param type key type
511    * @param value column value
512    * @throws IllegalArgumentException
513    */
514   public KeyValue(final byte[] row, final byte[] family,
515       final byte[] qualifier, final long timestamp, Type type,
516       final byte[] value, final byte[] tags) {
517     this(row, family, qualifier, 0, qualifier==null ? 0 : qualifier.length,
518         timestamp, type, value, 0, value==null ? 0 : value.length, tags);
519   }
520 
521   /**
522    * Constructs KeyValue structure filled with specified values.
523    * @param row row key
524    * @param family family name
525    * @param qualifier column qualifier
526    * @param qoffset qualifier offset
527    * @param qlength qualifier length
528    * @param timestamp version timestamp
529    * @param type key type
530    * @param value column value
531    * @param voffset value offset
532    * @param vlength value length
533    * @throws IllegalArgumentException
534    */
535   public KeyValue(byte [] row, byte [] family,
536       byte [] qualifier, int qoffset, int qlength, long timestamp, Type type,
537       byte [] value, int voffset, int vlength, List<Tag> tags) {
538     this(row, 0, row==null ? 0 : row.length,
539         family, 0, family==null ? 0 : family.length,
540         qualifier, qoffset, qlength, timestamp, type,
541         value, voffset, vlength, tags);
542   }
543 
544   /**
545    * @param row
546    * @param family
547    * @param qualifier
548    * @param qoffset
549    * @param qlength
550    * @param timestamp
551    * @param type
552    * @param value
553    * @param voffset
554    * @param vlength
555    * @param tags
556    */
557   public KeyValue(byte [] row, byte [] family,
558       byte [] qualifier, int qoffset, int qlength, long timestamp, Type type,
559       byte [] value, int voffset, int vlength, byte[] tags) {
560     this(row, 0, row==null ? 0 : row.length,
561         family, 0, family==null ? 0 : family.length,
562         qualifier, qoffset, qlength, timestamp, type,
563         value, voffset, vlength, tags, 0, tags==null ? 0 : tags.length);
564   }
565 
566   /**
567    * Constructs KeyValue structure filled with specified values.
568    * <p>
569    * Column is split into two fields, family and qualifier.
570    * @param row row key
571    * @throws IllegalArgumentException
572    */
573   public KeyValue(final byte [] row, final int roffset, final int rlength,
574       final byte [] family, final int foffset, final int flength,
575       final byte [] qualifier, final int qoffset, final int qlength,
576       final long timestamp, final Type type,
577       final byte [] value, final int voffset, final int vlength) {
578     this(row, roffset, rlength, family, foffset, flength, qualifier, qoffset,
579       qlength, timestamp, type, value, voffset, vlength, null);
580   }
581 
582   /**
583    * Constructs KeyValue structure filled with specified values. Uses the provided buffer as the
584    * data buffer.
585    * <p>
586    * Column is split into two fields, family and qualifier.
587    *
588    * @param buffer the bytes buffer to use
589    * @param boffset buffer offset
590    * @param row row key
591    * @param roffset row offset
592    * @param rlength row length
593    * @param family family name
594    * @param foffset family offset
595    * @param flength family length
596    * @param qualifier column qualifier
597    * @param qoffset qualifier offset
598    * @param qlength qualifier length
599    * @param timestamp version timestamp
600    * @param type key type
601    * @param value column value
602    * @param voffset value offset
603    * @param vlength value length
604    * @param tags non-empty list of tags or null
605    * @throws IllegalArgumentException an illegal value was passed or there is insufficient space
606    * remaining in the buffer
607    */
608   public KeyValue(byte [] buffer, final int boffset,
609       final byte [] row, final int roffset, final int rlength,
610       final byte [] family, final int foffset, final int flength,
611       final byte [] qualifier, final int qoffset, final int qlength,
612       final long timestamp, final Type type,
613       final byte [] value, final int voffset, final int vlength,
614       final Tag[] tags) {
615      this.bytes  = buffer;
616      this.length = writeByteArray(buffer, boffset,
617          row, roffset, rlength,
618          family, foffset, flength, qualifier, qoffset, qlength,
619         timestamp, type, value, voffset, vlength, tags);
620      this.offset = boffset;
621    }
622 
623   /**
624    * Constructs KeyValue structure filled with specified values.
625    * <p>
626    * Column is split into two fields, family and qualifier.
627    * @param row row key
628    * @param roffset row offset
629    * @param rlength row length
630    * @param family family name
631    * @param foffset family offset
632    * @param flength family length
633    * @param qualifier column qualifier
634    * @param qoffset qualifier offset
635    * @param qlength qualifier length
636    * @param timestamp version timestamp
637    * @param type key type
638    * @param value column value
639    * @param voffset value offset
640    * @param vlength value length
641    * @param tags tags
642    * @throws IllegalArgumentException
643    */
644   public KeyValue(final byte [] row, final int roffset, final int rlength,
645       final byte [] family, final int foffset, final int flength,
646       final byte [] qualifier, final int qoffset, final int qlength,
647       final long timestamp, final Type type,
648       final byte [] value, final int voffset, final int vlength,
649       final List<Tag> tags) {
650     this.bytes = createByteArray(row, roffset, rlength,
651         family, foffset, flength, qualifier, qoffset, qlength,
652         timestamp, type, value, voffset, vlength, tags);
653     this.length = bytes.length;
654     this.offset = 0;
655   }
656 
657   /**
658    * @param row
659    * @param roffset
660    * @param rlength
661    * @param family
662    * @param foffset
663    * @param flength
664    * @param qualifier
665    * @param qoffset
666    * @param qlength
667    * @param timestamp
668    * @param type
669    * @param value
670    * @param voffset
671    * @param vlength
672    * @param tags
673    */
674   public KeyValue(final byte [] row, final int roffset, final int rlength,
675       final byte [] family, final int foffset, final int flength,
676       final byte [] qualifier, final int qoffset, final int qlength,
677       final long timestamp, final Type type,
678       final byte [] value, final int voffset, final int vlength,
679       final byte[] tags, final int tagsOffset, final int tagsLength) {
680     this.bytes = createByteArray(row, roffset, rlength,
681         family, foffset, flength, qualifier, qoffset, qlength,
682         timestamp, type, value, voffset, vlength, tags, tagsOffset, tagsLength);
683     this.length = bytes.length;
684     this.offset = 0;
685   }
686 
687   /**
688    * Constructs an empty KeyValue structure, with specified sizes.
689    * This can be used to partially fill up KeyValues.
690    * <p>
691    * Column is split into two fields, family and qualifier.
692    * @param rlength row length
693    * @param flength family length
694    * @param qlength qualifier length
695    * @param timestamp version timestamp
696    * @param type key type
697    * @param vlength value length
698    * @throws IllegalArgumentException
699    */
700   public KeyValue(final int rlength,
701       final int flength,
702       final int qlength,
703       final long timestamp, final Type type,
704       final int vlength) {
705     this(rlength, flength, qlength, timestamp, type, vlength, 0);
706   }
707 
708   /**
709    * Constructs an empty KeyValue structure, with specified sizes.
710    * This can be used to partially fill up KeyValues.
711    * <p>
712    * Column is split into two fields, family and qualifier.
713    * @param rlength row length
714    * @param flength family length
715    * @param qlength qualifier length
716    * @param timestamp version timestamp
717    * @param type key type
718    * @param vlength value length
719    * @param tagsLength
720    * @throws IllegalArgumentException
721    */
722   public KeyValue(final int rlength,
723       final int flength,
724       final int qlength,
725       final long timestamp, final Type type,
726       final int vlength, final int tagsLength) {
727     this.bytes = createEmptyByteArray(rlength, flength, qlength, timestamp, type, vlength,
728         tagsLength);
729     this.length = bytes.length;
730     this.offset = 0;
731   }
732 
733 
734   public KeyValue(byte[] row, int roffset, int rlength,
735                   byte[] family, int foffset, int flength,
736                   ByteBuffer qualifier, long ts, Type type, ByteBuffer value, List<Tag> tags) {
737     this.bytes = createByteArray(row, roffset, rlength, family, foffset, flength,
738         qualifier, 0, qualifier == null ? 0 : qualifier.remaining(), ts, type,
739         value, 0, value == null ? 0 : value.remaining(), tags);
740     this.length = bytes.length;
741     this.offset = 0;
742   }
743 
744   public KeyValue(Cell c) {
745     this(c.getRowArray(), c.getRowOffset(), (int)c.getRowLength(),
746         c.getFamilyArray(), c.getFamilyOffset(), (int)c.getFamilyLength(),
747         c.getQualifierArray(), c.getQualifierOffset(), (int) c.getQualifierLength(),
748         c.getTimestamp(), Type.codeToType(c.getTypeByte()), c.getValueArray(), c.getValueOffset(),
749         c.getValueLength(), c.getTagsArray(), c.getTagsOffset(), c.getTagsLength());
750     this.seqId = c.getSequenceId();
751   }
752 
753   /**
754    * Create a KeyValue that is smaller than all other possible KeyValues
755    * for the given row. That is any (valid) KeyValue on 'row' would sort
756    * _after_ the result.
757    *
758    * @param row - row key (arbitrary byte array)
759    * @return First possible KeyValue on passed <code>row</code>
760    * @deprecated Since 0.99.2. Use {@link KeyValueUtil#createFirstOnRow(byte [])} instead
761    */
762   @Deprecated
763   public static KeyValue createFirstOnRow(final byte [] row) {
764     return KeyValueUtil.createFirstOnRow(row, HConstants.LATEST_TIMESTAMP);
765   }
766 
767   /**
768    * Create a KeyValue for the specified row, family and qualifier that would be
769    * smaller than all other possible KeyValues that have the same row,family,qualifier.
770    * Used for seeking.
771    * @param row - row key (arbitrary byte array)
772    * @param family - family name
773    * @param qualifier - column qualifier
774    * @return First possible key on passed <code>row</code>, and column.
775    * @deprecated Since 0.99.2. Use {@link KeyValueUtil#createFirstOnRow(byte[], byte[], byte[])}
776    * instead
777    */
778   @Deprecated
779   public static KeyValue createFirstOnRow(final byte [] row, final byte [] family,
780       final byte [] qualifier) {
781     return KeyValueUtil.createFirstOnRow(row, family, qualifier);
782   }
783 
784   /**
785    * Create a KeyValue for the specified row, family and qualifier that would be
786    * smaller than all other possible KeyValues that have the same row,
787    * family, qualifier.
788    * Used for seeking.
789    * @param row row key
790    * @param roffset row offset
791    * @param rlength row length
792    * @param family family name
793    * @param foffset family offset
794    * @param flength family length
795    * @param qualifier column qualifier
796    * @param qoffset qualifier offset
797    * @param qlength qualifier length
798    * @return First possible key on passed Row, Family, Qualifier.
799    * @deprecated Since 0.99.2. Use {@link KeyValueUtil#createFirstOnRow(byte[], int, int,
800    * byte[], int, int, byte[], int, int)} instead
801    */
802   @Deprecated
803   public static KeyValue createFirstOnRow(final byte [] row,
804       final int roffset, final int rlength, final byte [] family,
805       final int foffset, final int flength, final byte [] qualifier,
806       final int qoffset, final int qlength) {
807     return new KeyValue(row, roffset, rlength, family,
808         foffset, flength, qualifier, qoffset, qlength,
809         HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0);
810   }
811 
812   /**
813    * Create an empty byte[] representing a KeyValue
814    * All lengths are preset and can be filled in later.
815    * @param rlength
816    * @param flength
817    * @param qlength
818    * @param timestamp
819    * @param type
820    * @param vlength
821    * @return The newly created byte array.
822    */
823   private static byte[] createEmptyByteArray(final int rlength, int flength,
824       int qlength, final long timestamp, final Type type, int vlength, int tagsLength) {
825     if (rlength > Short.MAX_VALUE) {
826       throw new IllegalArgumentException("Row > " + Short.MAX_VALUE);
827     }
828     if (flength > Byte.MAX_VALUE) {
829       throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE);
830     }
831     // Qualifier length
832     if (qlength > Integer.MAX_VALUE - rlength - flength) {
833       throw new IllegalArgumentException("Qualifier > " + Integer.MAX_VALUE);
834     }
835     checkForTagsLength(tagsLength);
836     // Key length
837     long longkeylength = getKeyDataStructureSize(rlength, flength, qlength);
838     if (longkeylength > Integer.MAX_VALUE) {
839       throw new IllegalArgumentException("keylength " + longkeylength + " > " +
840         Integer.MAX_VALUE);
841     }
842     int keylength = (int)longkeylength;
843     // Value length
844     if (vlength > HConstants.MAXIMUM_VALUE_LENGTH) { // FindBugs INT_VACUOUS_COMPARISON
845       throw new IllegalArgumentException("Valuer > " +
846           HConstants.MAXIMUM_VALUE_LENGTH);
847     }
848 
849     // Allocate right-sized byte array.
850     byte[] bytes= new byte[(int) getKeyValueDataStructureSize(rlength, flength, qlength, vlength,
851         tagsLength)];
852     // Write the correct size markers
853     int pos = 0;
854     pos = Bytes.putInt(bytes, pos, keylength);
855     pos = Bytes.putInt(bytes, pos, vlength);
856     pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff));
857     pos += rlength;
858     pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff));
859     pos += flength + qlength;
860     pos = Bytes.putLong(bytes, pos, timestamp);
861     pos = Bytes.putByte(bytes, pos, type.getCode());
862     pos += vlength;
863     if (tagsLength > 0) {
864       pos = Bytes.putAsShort(bytes, pos, tagsLength);
865     }
866     return bytes;
867   }
868 
869   /**
870    * Checks the parameters passed to a constructor.
871    *
872    * @param row row key
873    * @param rlength row length
874    * @param family family name
875    * @param flength family length
876    * @param qlength qualifier length
877    * @param vlength value length
878    *
879    * @throws IllegalArgumentException an illegal value was passed
880    */
881   private static void checkParameters(final byte [] row, final int rlength,
882       final byte [] family, int flength, int qlength, int vlength)
883           throws IllegalArgumentException {
884     if (rlength > Short.MAX_VALUE) {
885       throw new IllegalArgumentException("Row > " + Short.MAX_VALUE);
886     }
887     if (row == null) {
888       throw new IllegalArgumentException("Row is null");
889     }
890     // Family length
891     flength = family == null ? 0 : flength;
892     if (flength > Byte.MAX_VALUE) {
893       throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE);
894     }
895     // Qualifier length
896     if (qlength > Integer.MAX_VALUE - rlength - flength) {
897       throw new IllegalArgumentException("Qualifier > " + Integer.MAX_VALUE);
898     }
899     // Key length
900     long longKeyLength = getKeyDataStructureSize(rlength, flength, qlength);
901     if (longKeyLength > Integer.MAX_VALUE) {
902       throw new IllegalArgumentException("keylength " + longKeyLength + " > " +
903           Integer.MAX_VALUE);
904     }
905     // Value length
906     if (vlength > HConstants.MAXIMUM_VALUE_LENGTH) { // FindBugs INT_VACUOUS_COMPARISON
907       throw new IllegalArgumentException("Value length " + vlength + " > " +
908           HConstants.MAXIMUM_VALUE_LENGTH);
909     }
910   }
911 
912   /**
913    * Write KeyValue format into the provided byte array.
914    *
915    * @param buffer the bytes buffer to use
916    * @param boffset buffer offset
917    * @param row row key
918    * @param roffset row offset
919    * @param rlength row length
920    * @param family family name
921    * @param foffset family offset
922    * @param flength family length
923    * @param qualifier column qualifier
924    * @param qoffset qualifier offset
925    * @param qlength qualifier length
926    * @param timestamp version timestamp
927    * @param type key type
928    * @param value column value
929    * @param voffset value offset
930    * @param vlength value length
931    *
932    * @return The number of useful bytes in the buffer.
933    *
934    * @throws IllegalArgumentException an illegal value was passed or there is insufficient space
935    * remaining in the buffer
936    */
937   public static int writeByteArray(byte [] buffer, final int boffset,
938       final byte [] row, final int roffset, final int rlength,
939       final byte [] family, final int foffset, int flength,
940       final byte [] qualifier, final int qoffset, int qlength,
941       final long timestamp, final Type type,
942       final byte [] value, final int voffset, int vlength, Tag[] tags) {
943 
944     checkParameters(row, rlength, family, flength, qlength, vlength);
945 
946     // Calculate length of tags area
947     int tagsLength = 0;
948     if (tags != null && tags.length > 0) {
949       for (Tag t: tags) {
950         tagsLength += t.getLength();
951       }
952     }
953     checkForTagsLength(tagsLength);
954     int keyLength = (int) getKeyDataStructureSize(rlength, flength, qlength);
955     int keyValueLength = (int) getKeyValueDataStructureSize(rlength, flength, qlength, vlength,
956         tagsLength);
957     if (keyValueLength > buffer.length - boffset) {
958       throw new IllegalArgumentException("Buffer size " + (buffer.length - boffset) + " < " +
959           keyValueLength);
960     }
961 
962     // Write key, value and key row length.
963     int pos = boffset;
964     pos = Bytes.putInt(buffer, pos, keyLength);
965     pos = Bytes.putInt(buffer, pos, vlength);
966     pos = Bytes.putShort(buffer, pos, (short)(rlength & 0x0000ffff));
967     pos = Bytes.putBytes(buffer, pos, row, roffset, rlength);
968     pos = Bytes.putByte(buffer, pos, (byte) (flength & 0x0000ff));
969     if (flength != 0) {
970       pos = Bytes.putBytes(buffer, pos, family, foffset, flength);
971     }
972     if (qlength != 0) {
973       pos = Bytes.putBytes(buffer, pos, qualifier, qoffset, qlength);
974     }
975     pos = Bytes.putLong(buffer, pos, timestamp);
976     pos = Bytes.putByte(buffer, pos, type.getCode());
977     if (value != null && value.length > 0) {
978       pos = Bytes.putBytes(buffer, pos, value, voffset, vlength);
979     }
980     // Write the number of tags. If it is 0 then it means there are no tags.
981     if (tagsLength > 0) {
982       pos = Bytes.putAsShort(buffer, pos, tagsLength);
983       for (Tag t : tags) {
984         pos = Bytes.putBytes(buffer, pos, t.getBuffer(), t.getOffset(), t.getLength());
985       }
986     }
987     return keyValueLength;
988   }
989 
990   private static void checkForTagsLength(int tagsLength) {
991     if (tagsLength > MAX_TAGS_LENGTH) {
992       throw new IllegalArgumentException("tagslength "+ tagsLength + " > " + MAX_TAGS_LENGTH);
993     }
994   }
995 
996   /**
997    * Write KeyValue format into a byte array.
998    * @param row row key
999    * @param roffset row offset
1000    * @param rlength row length
1001    * @param family family name
1002    * @param foffset family offset
1003    * @param flength family length
1004    * @param qualifier column qualifier
1005    * @param qoffset qualifier offset
1006    * @param qlength qualifier length
1007    * @param timestamp version timestamp
1008    * @param type key type
1009    * @param value column value
1010    * @param voffset value offset
1011    * @param vlength value length
1012    * @return The newly created byte array.
1013    */
1014   private static byte [] createByteArray(final byte [] row, final int roffset,
1015       final int rlength, final byte [] family, final int foffset, int flength,
1016       final byte [] qualifier, final int qoffset, int qlength,
1017       final long timestamp, final Type type,
1018       final byte [] value, final int voffset,
1019       int vlength, byte[] tags, int tagsOffset, int tagsLength) {
1020 
1021     checkParameters(row, rlength, family, flength, qlength, vlength);
1022     checkForTagsLength(tagsLength);
1023     // Allocate right-sized byte array.
1024     int keyLength = (int) getKeyDataStructureSize(rlength, flength, qlength);
1025     byte[] bytes = new byte[(int) getKeyValueDataStructureSize(rlength, flength, qlength, vlength,
1026       tagsLength)];
1027     // Write key, value and key row length.
1028     int pos = 0;
1029     pos = Bytes.putInt(bytes, pos, keyLength);
1030     pos = Bytes.putInt(bytes, pos, vlength);
1031     pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff));
1032     pos = Bytes.putBytes(bytes, pos, row, roffset, rlength);
1033     pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff));
1034     if(flength != 0) {
1035       pos = Bytes.putBytes(bytes, pos, family, foffset, flength);
1036     }
1037     if(qlength != 0) {
1038       pos = Bytes.putBytes(bytes, pos, qualifier, qoffset, qlength);
1039     }
1040     pos = Bytes.putLong(bytes, pos, timestamp);
1041     pos = Bytes.putByte(bytes, pos, type.getCode());
1042     if (value != null && value.length > 0) {
1043       pos = Bytes.putBytes(bytes, pos, value, voffset, vlength);
1044     }
1045     // Add the tags after the value part
1046     if (tagsLength > 0) {
1047       pos = Bytes.putAsShort(bytes, pos, tagsLength);
1048       pos = Bytes.putBytes(bytes, pos, tags, tagsOffset, tagsLength);
1049     }
1050     return bytes;
1051   }
1052 
1053   /**
1054    * @param qualifier can be a ByteBuffer or a byte[], or null.
1055    * @param value can be a ByteBuffer or a byte[], or null.
1056    */
1057   private static byte [] createByteArray(final byte [] row, final int roffset,
1058       final int rlength, final byte [] family, final int foffset, int flength,
1059       final Object qualifier, final int qoffset, int qlength,
1060       final long timestamp, final Type type,
1061       final Object value, final int voffset, int vlength, List<Tag> tags) {
1062 
1063     checkParameters(row, rlength, family, flength, qlength, vlength);
1064 
1065     // Calculate length of tags area
1066     int tagsLength = 0;
1067     if (tags != null && !tags.isEmpty()) {
1068       for (Tag t : tags) {
1069         tagsLength += t.getLength();
1070       }
1071     }
1072     checkForTagsLength(tagsLength);
1073     // Allocate right-sized byte array.
1074     int keyLength = (int) getKeyDataStructureSize(rlength, flength, qlength);
1075     byte[] bytes = new byte[(int) getKeyValueDataStructureSize(rlength, flength, qlength, vlength,
1076         tagsLength)];
1077 
1078     // Write key, value and key row length.
1079     int pos = 0;
1080     pos = Bytes.putInt(bytes, pos, keyLength);
1081 
1082     pos = Bytes.putInt(bytes, pos, vlength);
1083     pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff));
1084     pos = Bytes.putBytes(bytes, pos, row, roffset, rlength);
1085     pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff));
1086     if(flength != 0) {
1087       pos = Bytes.putBytes(bytes, pos, family, foffset, flength);
1088     }
1089     if (qlength > 0) {
1090       if (qualifier instanceof ByteBuffer) {
1091         pos = Bytes.putByteBuffer(bytes, pos, (ByteBuffer) qualifier);
1092       } else {
1093         pos = Bytes.putBytes(bytes, pos, (byte[]) qualifier, qoffset, qlength);
1094       }
1095     }
1096     pos = Bytes.putLong(bytes, pos, timestamp);
1097     pos = Bytes.putByte(bytes, pos, type.getCode());
1098     if (vlength > 0) {
1099       if (value instanceof ByteBuffer) {
1100         pos = Bytes.putByteBuffer(bytes, pos, (ByteBuffer) value);
1101       } else {
1102         pos = Bytes.putBytes(bytes, pos, (byte[]) value, voffset, vlength);
1103       }
1104     }
1105     // Add the tags after the value part
1106     if (tagsLength > 0) {
1107       pos = Bytes.putAsShort(bytes, pos, tagsLength);
1108       for (Tag t : tags) {
1109         pos = Bytes.putBytes(bytes, pos, t.getBuffer(), t.getOffset(), t.getLength());
1110       }
1111     }
1112     return bytes;
1113   }
1114 
1115   /**
1116    * Needed doing 'contains' on List.  Only compares the key portion, not the value.
1117    */
1118   @Override
1119   public boolean equals(Object other) {
1120     if (!(other instanceof Cell)) {
1121       return false;
1122     }
1123     return CellComparator.equals(this, (Cell)other);
1124   }
1125 
1126   @Override
1127   public int hashCode() {
1128     byte[] b = getBuffer();
1129     int start = getOffset(), end = getOffset() + getLength();
1130     int h = b[start++];
1131     for (int i = start; i < end; i++) {
1132       h = (h * 13) ^ b[i];
1133     }
1134     return h;
1135   }
1136 
1137   //---------------------------------------------------------------------------
1138   //
1139   //  KeyValue cloning
1140   //
1141   //---------------------------------------------------------------------------
1142 
1143   /**
1144    * Clones a KeyValue.  This creates a copy, re-allocating the buffer.
1145    * @return Fully copied clone of this KeyValue
1146    * @throws CloneNotSupportedException
1147    */
1148   @Override
1149   public KeyValue clone() throws CloneNotSupportedException {
1150     super.clone();
1151     byte [] b = new byte[this.length];
1152     System.arraycopy(this.bytes, this.offset, b, 0, this.length);
1153     KeyValue ret = new KeyValue(b, 0, b.length);
1154     // Important to clone the memstoreTS as well - otherwise memstore's
1155     // update-in-place methods (eg increment) will end up creating
1156     // new entries
1157     ret.setSequenceId(seqId);
1158     return ret;
1159   }
1160 
1161   /**
1162    * Creates a shallow copy of this KeyValue, reusing the data byte buffer.
1163    * http://en.wikipedia.org/wiki/Object_copy
1164    * @return Shallow copy of this KeyValue
1165    */
1166   public KeyValue shallowCopy() {
1167     KeyValue shallowCopy = new KeyValue(this.bytes, this.offset, this.length);
1168     shallowCopy.setSequenceId(this.seqId);
1169     return shallowCopy;
1170   }
1171 
1172   //---------------------------------------------------------------------------
1173   //
1174   //  String representation
1175   //
1176   //---------------------------------------------------------------------------
1177 
1178   @Override
1179   public String toString() {
1180     if (this.bytes == null || this.bytes.length == 0) {
1181       return "empty";
1182     }
1183     return keyToString(this.bytes, this.offset + ROW_OFFSET, getKeyLength()) + "/vlen="
1184       + getValueLength() + "/seqid=" + seqId;
1185   }
1186 
1187   /**
1188    * @param k Key portion of a KeyValue.
1189    * @return Key as a String, empty string if k is null.
1190    */
1191   public static String keyToString(final byte [] k) {
1192     if (k == null) {
1193       return "";
1194     }
1195     return keyToString(k, 0, k.length);
1196   }
1197 
1198   /**
1199    * Produces a string map for this key/value pair. Useful for programmatic use
1200    * and manipulation of the data stored in an WALKey, for example, printing
1201    * as JSON. Values are left out due to their tendency to be large. If needed,
1202    * they can be added manually.
1203    *
1204    * @return the Map<String,?> containing data from this key
1205    */
1206   public Map<String, Object> toStringMap() {
1207     Map<String, Object> stringMap = new HashMap<String, Object>();
1208     stringMap.put("row", Bytes.toStringBinary(getRow()));
1209     stringMap.put("family", Bytes.toStringBinary(getFamily()));
1210     stringMap.put("qualifier", Bytes.toStringBinary(getQualifier()));
1211     stringMap.put("timestamp", getTimestamp());
1212     stringMap.put("vlen", getValueLength());
1213     List<Tag> tags = getTags();
1214     if (tags != null) {
1215       List<String> tagsString = new ArrayList<String>();
1216       for (Tag t : tags) {
1217         tagsString.add((t.getType()) + ":" +Bytes.toStringBinary(t.getValue()));
1218       }
1219       stringMap.put("tag", tagsString);
1220     }
1221     return stringMap;
1222   }
1223 
1224   /**
1225    * Use for logging.
1226    * @param b Key portion of a KeyValue.
1227    * @param o Offset to start of key
1228    * @param l Length of key.
1229    * @return Key as a String.
1230    */
1231   public static String keyToString(final byte [] b, final int o, final int l) {
1232     if (b == null) return "";
1233     int rowlength = Bytes.toShort(b, o);
1234     String row = Bytes.toStringBinary(b, o + Bytes.SIZEOF_SHORT, rowlength);
1235     int columnoffset = o + Bytes.SIZEOF_SHORT + 1 + rowlength;
1236     int familylength = b[columnoffset - 1];
1237     int columnlength = l - ((columnoffset - o) + TIMESTAMP_TYPE_SIZE);
1238     String family = familylength == 0? "":
1239       Bytes.toStringBinary(b, columnoffset, familylength);
1240     String qualifier = columnlength == 0? "":
1241       Bytes.toStringBinary(b, columnoffset + familylength,
1242       columnlength - familylength);
1243     long timestamp = Bytes.toLong(b, o + (l - TIMESTAMP_TYPE_SIZE));
1244     String timestampStr = humanReadableTimestamp(timestamp);
1245     byte type = b[o + l - 1];
1246     return row + "/" + family +
1247       (family != null && family.length() > 0? ":" :"") +
1248       qualifier + "/" + timestampStr + "/" + Type.codeToType(type);
1249   }
1250 
1251   public static String humanReadableTimestamp(final long timestamp) {
1252     if (timestamp == HConstants.LATEST_TIMESTAMP) {
1253       return "LATEST_TIMESTAMP";
1254     }
1255     if (timestamp == HConstants.OLDEST_TIMESTAMP) {
1256       return "OLDEST_TIMESTAMP";
1257     }
1258     return String.valueOf(timestamp);
1259   }
1260 
1261   //---------------------------------------------------------------------------
1262   //
1263   //  Public Member Accessors
1264   //
1265   //---------------------------------------------------------------------------
1266 
1267   /**
1268    * @return The byte array backing this KeyValue.
1269    * @deprecated Since 0.98.0.  Use Cell Interface instead.  Do not presume single backing buffer.
1270    */
1271   @Deprecated
1272   public byte [] getBuffer() {
1273     return this.bytes;
1274   }
1275 
1276   /**
1277    * @return Offset into {@link #getBuffer()} at which this KeyValue starts.
1278    */
1279   public int getOffset() {
1280     return this.offset;
1281   }
1282 
1283   /**
1284    * @return Length of bytes this KeyValue occupies in {@link #getBuffer()}.
1285    */
1286   public int getLength() {
1287     return length;
1288   }
1289 
1290   //---------------------------------------------------------------------------
1291   //
1292   //  Length and Offset Calculators
1293   //
1294   //---------------------------------------------------------------------------
1295 
1296   /**
1297    * Determines the total length of the KeyValue stored in the specified
1298    * byte array and offset.  Includes all headers.
1299    * @param bytes byte array
1300    * @param offset offset to start of the KeyValue
1301    * @return length of entire KeyValue, in bytes
1302    */
1303   private static int getLength(byte [] bytes, int offset) {
1304     int klength = ROW_OFFSET + Bytes.toInt(bytes, offset);
1305     int vlength = Bytes.toInt(bytes, offset + Bytes.SIZEOF_INT);
1306     return klength + vlength;
1307   }
1308 
1309   /**
1310    * @return Key offset in backing buffer..
1311    */
1312   public int getKeyOffset() {
1313     return this.offset + ROW_OFFSET;
1314   }
1315 
1316   public String getKeyString() {
1317     return Bytes.toStringBinary(getBuffer(), getKeyOffset(), getKeyLength());
1318   }
1319 
1320   /**
1321    * @return Length of key portion.
1322    */
1323   public int getKeyLength() {
1324     return Bytes.toInt(this.bytes, this.offset);
1325   }
1326 
1327   /**
1328    * @return the backing array of the entire KeyValue (all KeyValue fields are in a single array)
1329    */
1330   @Override
1331   public byte[] getValueArray() {
1332     return bytes;
1333   }
1334 
1335   /**
1336    * @return the value offset
1337    */
1338   @Override
1339   public int getValueOffset() {
1340     int voffset = getKeyOffset() + getKeyLength();
1341     return voffset;
1342   }
1343 
1344   /**
1345    * @return Value length
1346    */
1347   @Override
1348   public int getValueLength() {
1349     int vlength = Bytes.toInt(this.bytes, this.offset + Bytes.SIZEOF_INT);
1350     return vlength;
1351   }
1352 
1353   /**
1354    * @return the backing array of the entire KeyValue (all KeyValue fields are in a single array)
1355    */
1356   @Override
1357   public byte[] getRowArray() {
1358     return bytes;
1359   }
1360 
1361   /**
1362    * @return Row offset
1363    */
1364   @Override
1365   public int getRowOffset() {
1366     return getKeyOffset() + Bytes.SIZEOF_SHORT;
1367   }
1368 
1369   /**
1370    * @return Row length
1371    */
1372   @Override
1373   public short getRowLength() {
1374     return Bytes.toShort(this.bytes, getKeyOffset());
1375   }
1376 
1377   /**
1378    * @return the backing array of the entire KeyValue (all KeyValue fields are in a single array)
1379    */
1380   @Override
1381   public byte[] getFamilyArray() {
1382     return bytes;
1383   }
1384 
1385   /**
1386    * @return Family offset
1387    */
1388   @Override
1389   public int getFamilyOffset() {
1390     return getFamilyOffset(getRowLength());
1391   }
1392 
1393   /**
1394    * @return Family offset
1395    */
1396   private int getFamilyOffset(int rlength) {
1397     return this.offset + ROW_OFFSET + Bytes.SIZEOF_SHORT + rlength + Bytes.SIZEOF_BYTE;
1398   }
1399 
1400   /**
1401    * @return Family length
1402    */
1403   @Override
1404   public byte getFamilyLength() {
1405     return getFamilyLength(getFamilyOffset());
1406   }
1407 
1408   /**
1409    * @return Family length
1410    */
1411   public byte getFamilyLength(int foffset) {
1412     return this.bytes[foffset-1];
1413   }
1414 
1415   /**
1416    * @return the backing array of the entire KeyValue (all KeyValue fields are in a single array)
1417    */
1418   @Override
1419   public byte[] getQualifierArray() {
1420     return bytes;
1421   }
1422 
1423   /**
1424    * @return Qualifier offset
1425    */
1426   @Override
1427   public int getQualifierOffset() {
1428     return getQualifierOffset(getFamilyOffset());
1429   }
1430 
1431   /**
1432    * @return Qualifier offset
1433    */
1434   private int getQualifierOffset(int foffset) {
1435     return foffset + getFamilyLength(foffset);
1436   }
1437 
1438   /**
1439    * @return Qualifier length
1440    */
1441   @Override
1442   public int getQualifierLength() {
1443     return getQualifierLength(getRowLength(),getFamilyLength());
1444   }
1445 
1446   /**
1447    * @return Qualifier length
1448    */
1449   private int getQualifierLength(int rlength, int flength) {
1450     return getKeyLength() - (int) getKeyDataStructureSize(rlength, flength, 0);
1451   }
1452 
1453   /**
1454    * @return Timestamp offset
1455    */
1456   public int getTimestampOffset() {
1457     return getTimestampOffset(getKeyLength());
1458   }
1459 
1460   /**
1461    * @param keylength Pass if you have it to save on a int creation.
1462    * @return Timestamp offset
1463    */
1464   private int getTimestampOffset(final int keylength) {
1465     return getKeyOffset() + keylength - TIMESTAMP_TYPE_SIZE;
1466   }
1467 
1468   /**
1469    * @return True if this KeyValue has a LATEST_TIMESTAMP timestamp.
1470    */
1471   public boolean isLatestTimestamp() {
1472     return Bytes.equals(getBuffer(), getTimestampOffset(), Bytes.SIZEOF_LONG,
1473       HConstants.LATEST_TIMESTAMP_BYTES, 0, Bytes.SIZEOF_LONG);
1474   }
1475 
1476   /**
1477    * @param now Time to set into <code>this</code> IFF timestamp ==
1478    * {@link HConstants#LATEST_TIMESTAMP} (else, its a noop).
1479    * @return True is we modified this.
1480    */
1481   public boolean updateLatestStamp(final byte [] now) {
1482     if (this.isLatestTimestamp()) {
1483       int tsOffset = getTimestampOffset();
1484       System.arraycopy(now, 0, this.bytes, tsOffset, Bytes.SIZEOF_LONG);
1485       // clear cache or else getTimestamp() possibly returns an old value
1486       return true;
1487     }
1488     return false;
1489   }
1490 
1491   @Override
1492   public void setTimestamp(long ts) {
1493     Bytes.putBytes(this.bytes, this.getTimestampOffset(), Bytes.toBytes(ts), 0, Bytes.SIZEOF_LONG);
1494   }
1495 
1496   @Override
1497   public void setTimestamp(byte[] ts, int tsOffset) {
1498     Bytes.putBytes(this.bytes, this.getTimestampOffset(), ts, tsOffset, Bytes.SIZEOF_LONG);
1499   }
1500 
1501   //---------------------------------------------------------------------------
1502   //
1503   //  Methods that return copies of fields
1504   //
1505   //---------------------------------------------------------------------------
1506 
1507   /**
1508    * Do not use unless you have to.  Used internally for compacting and testing.
1509    *
1510    * Use {@link #getRow()}, {@link #getFamily()}, {@link #getQualifier()}, and
1511    * {@link #getValue()} if accessing a KeyValue client-side.
1512    * @return Copy of the key portion only.
1513    */
1514   public byte [] getKey() {
1515     int keylength = getKeyLength();
1516     byte [] key = new byte[keylength];
1517     System.arraycopy(getBuffer(), getKeyOffset(), key, 0, keylength);
1518     return key;
1519   }
1520 
1521   /**
1522    * Returns value in a new byte array.
1523    * Primarily for use client-side. If server-side, use
1524    * {@link #getBuffer()} with appropriate offsets and lengths instead to
1525    * save on allocations.
1526    * @return Value in a new byte array.
1527    */
1528   @Override
1529   @Deprecated // use CellUtil.getValueArray()
1530   public byte [] getValue() {
1531     return CellUtil.cloneValue(this);
1532   }
1533 
1534   /**
1535    * Primarily for use client-side.  Returns the row of this KeyValue in a new
1536    * byte array.<p>
1537    *
1538    * If server-side, use {@link #getBuffer()} with appropriate offsets and
1539    * lengths instead.
1540    * @return Row in a new byte array.
1541    */
1542   @Override
1543   @Deprecated // use CellUtil.getRowArray()
1544   public byte [] getRow() {
1545     return CellUtil.cloneRow(this);
1546   }
1547 
1548   /**
1549    *
1550    * @return Timestamp
1551    */
1552   @Override
1553   public long getTimestamp() {
1554     return getTimestamp(getKeyLength());
1555   }
1556 
1557   /**
1558    * @param keylength Pass if you have it to save on a int creation.
1559    * @return Timestamp
1560    */
1561   long getTimestamp(final int keylength) {
1562     int tsOffset = getTimestampOffset(keylength);
1563     return Bytes.toLong(this.bytes, tsOffset);
1564   }
1565 
1566   /**
1567    * @return Type of this KeyValue.
1568    */
1569   @Deprecated
1570   public byte getType() {
1571     return getTypeByte();
1572   }
1573 
1574   /**
1575    * @return KeyValue.TYPE byte representation
1576    */
1577   @Override
1578   public byte getTypeByte() {
1579     return this.bytes[this.offset + getKeyLength() - 1 + ROW_OFFSET];
1580   }
1581 
1582   /**
1583    * @return True if a delete type, a {@link KeyValue.Type#Delete} or
1584    * a {KeyValue.Type#DeleteFamily} or a {@link KeyValue.Type#DeleteColumn}
1585    * KeyValue type.
1586    */
1587   @Deprecated // use CellUtil#isDelete
1588   public boolean isDelete() {
1589     return KeyValue.isDelete(getType());
1590   }
1591 
1592   /**
1593    * Primarily for use client-side.  Returns the family of this KeyValue in a
1594    * new byte array.<p>
1595    *
1596    * If server-side, use {@link #getBuffer()} with appropriate offsets and
1597    * lengths instead.
1598    * @return Returns family. Makes a copy.
1599    */
1600   @Override
1601   @Deprecated // use CellUtil.getFamilyArray
1602   public byte [] getFamily() {
1603     return CellUtil.cloneFamily(this);
1604   }
1605 
1606   /**
1607    * Primarily for use client-side.  Returns the column qualifier of this
1608    * KeyValue in a new byte array.<p>
1609    *
1610    * If server-side, use {@link #getBuffer()} with appropriate offsets and
1611    * lengths instead.
1612    * Use {@link #getBuffer()} with appropriate offsets and lengths instead.
1613    * @return Returns qualifier. Makes a copy.
1614    */
1615   @Override
1616   @Deprecated // use CellUtil.getQualifierArray
1617   public byte [] getQualifier() {
1618     return CellUtil.cloneQualifier(this);
1619   }
1620 
1621   /**
1622    * This returns the offset where the tag actually starts.
1623    */
1624   @Override
1625   public int getTagsOffset() {
1626     int tagsLen = getTagsLength();
1627     if (tagsLen == 0) {
1628       return this.offset + this.length;
1629     }
1630     return this.offset + this.length - tagsLen;
1631   }
1632 
1633   /**
1634    * This returns the total length of the tag bytes
1635    */
1636   @Override
1637   public int getTagsLength() {
1638     int tagsLen = this.length - (getKeyLength() + getValueLength() + KEYVALUE_INFRASTRUCTURE_SIZE);
1639     if (tagsLen > 0) {
1640       // There are some Tag bytes in the byte[]. So reduce 2 bytes which is added to denote the tags
1641       // length
1642       tagsLen -= TAGS_LENGTH_SIZE;
1643     }
1644     return tagsLen;
1645   }
1646 
1647   /**
1648    * Returns any tags embedded in the KeyValue.  Used in testcases.
1649    * @return The tags
1650    */
1651   public List<Tag> getTags() {
1652     int tagsLength = getTagsLength();
1653     if (tagsLength == 0) {
1654       return EMPTY_ARRAY_LIST;
1655     }
1656     return Tag.asList(getTagsArray(), getTagsOffset(), tagsLength);
1657   }
1658 
1659   /**
1660    * @return the backing array of the entire KeyValue (all KeyValue fields are in a single array)
1661    */
1662   @Override
1663   public byte[] getTagsArray() {
1664     return bytes;
1665   }
1666 
1667   /**
1668    * Creates a new KeyValue that only contains the key portion (the value is
1669    * set to be null).
1670    *
1671    * TODO only used by KeyOnlyFilter -- move there.
1672    * @param lenAsVal replace value with the actual value length (false=empty)
1673    */
1674   public KeyValue createKeyOnly(boolean lenAsVal) {
1675     // KV format:  <keylen:4><valuelen:4><key:keylen><value:valuelen>
1676     // Rebuild as: <keylen:4><0:4><key:keylen>
1677     int dataLen = lenAsVal? Bytes.SIZEOF_INT : 0;
1678     byte [] newBuffer = new byte[getKeyLength() + ROW_OFFSET + dataLen];
1679     System.arraycopy(this.bytes, this.offset, newBuffer, 0,
1680         Math.min(newBuffer.length,this.length));
1681     Bytes.putInt(newBuffer, Bytes.SIZEOF_INT, dataLen);
1682     if (lenAsVal) {
1683       Bytes.putInt(newBuffer, newBuffer.length - dataLen, this.getValueLength());
1684     }
1685     return new KeyValue(newBuffer);
1686   }
1687 
1688   /**
1689    * Splits a column in {@code family:qualifier} form into separate byte arrays. An empty qualifier
1690    * (ie, {@code fam:}) is parsed as <code>{ fam, EMPTY_BYTE_ARRAY }</code> while no delimiter (ie,
1691    * {@code fam}) is parsed as an array of one element, <code>{ fam }</code>.
1692    * <p>
1693    * Don't forget, HBase DOES support empty qualifiers. (see HBASE-9549)
1694    * </p>
1695    * <p>
1696    * Not recommend to be used as this is old-style API.
1697    * </p>
1698    * @param c The column.
1699    * @return The parsed column.
1700    */
1701   public static byte [][] parseColumn(byte [] c) {
1702     final int index = getDelimiter(c, 0, c.length, COLUMN_FAMILY_DELIMITER);
1703     if (index == -1) {
1704       // If no delimiter, return array of size 1
1705       return new byte [][] { c };
1706     } else if(index == c.length - 1) {
1707       // family with empty qualifier, return array size 2
1708       byte [] family = new byte[c.length-1];
1709       System.arraycopy(c, 0, family, 0, family.length);
1710       return new byte [][] { family, HConstants.EMPTY_BYTE_ARRAY};
1711     }
1712     // Family and column, return array size 2
1713     final byte [][] result = new byte [2][];
1714     result[0] = new byte [index];
1715     System.arraycopy(c, 0, result[0], 0, index);
1716     final int len = c.length - (index + 1);
1717     result[1] = new byte[len];
1718     System.arraycopy(c, index + 1 /* Skip delimiter */, result[1], 0, len);
1719     return result;
1720   }
1721 
1722   /**
1723    * Makes a column in family:qualifier form from separate byte arrays.
1724    * <p>
1725    * Not recommended for usage as this is old-style API.
1726    * @param family
1727    * @param qualifier
1728    * @return family:qualifier
1729    */
1730   public static byte [] makeColumn(byte [] family, byte [] qualifier) {
1731     return Bytes.add(family, COLUMN_FAMILY_DELIM_ARRAY, qualifier);
1732   }
1733 
1734   /**
1735    * @param b
1736    * @param delimiter
1737    * @return Index of delimiter having started from start of <code>b</code>
1738    * moving rightward.
1739    */
1740   public static int getDelimiter(final byte [] b, int offset, final int length,
1741       final int delimiter) {
1742     if (b == null) {
1743       throw new IllegalArgumentException("Passed buffer is null");
1744     }
1745     int result = -1;
1746     for (int i = offset; i < length + offset; i++) {
1747       if (b[i] == delimiter) {
1748         result = i;
1749         break;
1750       }
1751     }
1752     return result;
1753   }
1754 
1755   /**
1756    * Find index of passed delimiter walking from end of buffer backwards.
1757    * @param b
1758    * @param delimiter
1759    * @return Index of delimiter
1760    */
1761   public static int getDelimiterInReverse(final byte [] b, final int offset,
1762       final int length, final int delimiter) {
1763     if (b == null) {
1764       throw new IllegalArgumentException("Passed buffer is null");
1765     }
1766     int result = -1;
1767     for (int i = (offset + length) - 1; i >= offset; i--) {
1768       if (b[i] == delimiter) {
1769         result = i;
1770         break;
1771       }
1772     }
1773     return result;
1774   }
1775 
1776   /**
1777    * A {@link KVComparator} for <code>hbase:meta</code> catalog table
1778    * {@link KeyValue}s.
1779    */
1780   public static class MetaComparator extends KVComparator {
1781     /**
1782      * Compare key portion of a {@link KeyValue} for keys in <code>hbase:meta</code>
1783      * table.
1784      */
1785     @Override
1786     public int compare(final Cell left, final Cell right) {
1787       int c = compareRowKey(left, right);
1788       if (c != 0) {
1789         return c;
1790       }
1791       return CellComparator.compareWithoutRow(left, right);
1792     }
1793 
1794     @Override
1795     public int compareOnlyKeyPortion(Cell left, Cell right) {
1796       return compare(left, right);
1797     }
1798 
1799     @Override
1800     public int compareRows(byte [] left, int loffset, int llength,
1801         byte [] right, int roffset, int rlength) {
1802       int leftDelimiter = getDelimiter(left, loffset, llength,
1803           HConstants.DELIMITER);
1804       int rightDelimiter = getDelimiter(right, roffset, rlength,
1805           HConstants.DELIMITER);
1806       // Compare up to the delimiter
1807       int lpart = (leftDelimiter < 0 ? llength :leftDelimiter - loffset);
1808       int rpart = (rightDelimiter < 0 ? rlength :rightDelimiter - roffset);
1809       int result = Bytes.compareTo(left, loffset, lpart, right, roffset, rpart);
1810       if (result != 0) {
1811         return result;
1812       } else {
1813         if (leftDelimiter < 0 && rightDelimiter >= 0) {
1814           return -1;
1815         } else if (rightDelimiter < 0 && leftDelimiter >= 0) {
1816           return 1;
1817         } else if (leftDelimiter < 0 && rightDelimiter < 0) {
1818           return 0;
1819         }
1820       }
1821       // Compare middle bit of the row.
1822       // Move past delimiter
1823       leftDelimiter++;
1824       rightDelimiter++;
1825       int leftFarDelimiter = getDelimiterInReverse(left, leftDelimiter,
1826           llength - (leftDelimiter - loffset), HConstants.DELIMITER);
1827       int rightFarDelimiter = getDelimiterInReverse(right,
1828           rightDelimiter, rlength - (rightDelimiter - roffset),
1829           HConstants.DELIMITER);
1830       // Now compare middlesection of row.
1831       lpart = (leftFarDelimiter < 0 ? llength + loffset: leftFarDelimiter) - leftDelimiter;
1832       rpart = (rightFarDelimiter < 0 ? rlength + roffset: rightFarDelimiter)- rightDelimiter;
1833       result = super.compareRows(left, leftDelimiter, lpart, right, rightDelimiter, rpart);
1834       if (result != 0) {
1835         return result;
1836       }  else {
1837         if (leftDelimiter < 0 && rightDelimiter >= 0) {
1838           return -1;
1839         } else if (rightDelimiter < 0 && leftDelimiter >= 0) {
1840           return 1;
1841         } else if (leftDelimiter < 0 && rightDelimiter < 0) {
1842           return 0;
1843         }
1844       }
1845       // Compare last part of row, the rowid.
1846       leftFarDelimiter++;
1847       rightFarDelimiter++;
1848       result = Bytes.compareTo(left, leftFarDelimiter, llength - (leftFarDelimiter - loffset),
1849           right, rightFarDelimiter, rlength - (rightFarDelimiter - roffset));
1850       return result;
1851     }
1852 
1853     /**
1854      * Don't do any fancy Block Index splitting tricks.
1855      */
1856     @Override
1857     public byte[] getShortMidpointKey(final byte[] leftKey, final byte[] rightKey) {
1858       return Arrays.copyOf(rightKey, rightKey.length);
1859     }
1860 
1861     /**
1862      * The HFileV2 file format's trailer contains this class name.  We reinterpret this and
1863      * instantiate the appropriate comparator.
1864      * TODO: With V3 consider removing this.
1865      * @return legacy class name for FileFileTrailer#comparatorClassName
1866      */
1867     @Override
1868     public String getLegacyKeyComparatorName() {
1869       return "org.apache.hadoop.hbase.KeyValue$MetaKeyComparator";
1870     }
1871 
1872     @Override
1873     protected Object clone() throws CloneNotSupportedException {
1874       return new MetaComparator();
1875     }
1876 
1877     /**
1878      * Override the row key comparison to parse and compare the meta row key parts.
1879      */
1880     @Override
1881     protected int compareRowKey(final Cell l, final Cell r) {
1882       byte[] left = l.getRowArray();
1883       int loffset = l.getRowOffset();
1884       int llength = l.getRowLength();
1885       byte[] right = r.getRowArray();
1886       int roffset = r.getRowOffset();
1887       int rlength = r.getRowLength();
1888       return compareRows(left, loffset, llength, right, roffset, rlength);
1889     }
1890   }
1891 
1892   /**
1893    * Compare KeyValues.  When we compare KeyValues, we only compare the Key
1894    * portion.  This means two KeyValues with same Key but different Values are
1895    * considered the same as far as this Comparator is concerned.
1896    */
1897   public static class KVComparator implements RawComparator<Cell>, SamePrefixComparator<byte[]> {
1898 
1899     /**
1900      * The HFileV2 file format's trailer contains this class name.  We reinterpret this and
1901      * instantiate the appropriate comparator.
1902      * TODO: With V3 consider removing this.
1903      * @return legacy class name for FileFileTrailer#comparatorClassName
1904      */
1905     public String getLegacyKeyComparatorName() {
1906       return "org.apache.hadoop.hbase.KeyValue$KeyComparator";
1907     }
1908 
1909     @Override // RawComparator
1910     public int compare(byte[] l, int loff, int llen, byte[] r, int roff, int rlen) {
1911       return compareFlatKey(l,loff,llen, r,roff,rlen);
1912     }
1913 
1914 
1915     /**
1916      * Compares the only the user specified portion of a Key.  This is overridden by MetaComparator.
1917      * @param left
1918      * @param right
1919      * @return 0 if equal, <0 if left smaller, >0 if right smaller
1920      */
1921     protected int compareRowKey(final Cell left, final Cell right) {
1922       return CellComparator.compareRows(left, right);
1923     }
1924 
1925     /**
1926      * Compares left to right assuming that left,loffset,llength and right,roffset,rlength are
1927      * full KVs laid out in a flat byte[]s.
1928      * @param left
1929      * @param loffset
1930      * @param llength
1931      * @param right
1932      * @param roffset
1933      * @param rlength
1934      * @return  0 if equal, <0 if left smaller, >0 if right smaller
1935      */
1936     public int compareFlatKey(byte[] left, int loffset, int llength,
1937         byte[] right, int roffset, int rlength) {
1938       // Compare row
1939       short lrowlength = Bytes.toShort(left, loffset);
1940       short rrowlength = Bytes.toShort(right, roffset);
1941       int compare = compareRows(left, loffset + Bytes.SIZEOF_SHORT,
1942           lrowlength, right, roffset + Bytes.SIZEOF_SHORT, rrowlength);
1943       if (compare != 0) {
1944         return compare;
1945       }
1946 
1947       // Compare the rest of the two KVs without making any assumptions about
1948       // the common prefix. This function will not compare rows anyway, so we
1949       // don't need to tell it that the common prefix includes the row.
1950       return compareWithoutRow(0, left, loffset, llength, right, roffset,
1951           rlength, rrowlength);
1952     }
1953 
1954     public int compareFlatKey(byte[] left, byte[] right) {
1955       return compareFlatKey(left, 0, left.length, right, 0, right.length);
1956     }
1957 
1958     // compare a key against row/fam/qual/ts/type
1959     public int compareKey(Cell cell,
1960         byte[] row, int roff, int rlen,
1961         byte[] fam, int foff, int flen,
1962         byte[] col, int coff, int clen,
1963         long ts, byte type) {
1964 
1965       int compare = compareRows(
1966         cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
1967         row, roff, rlen);
1968       if (compare != 0) {
1969         return compare;
1970       }
1971       // If the column is not specified, the "minimum" key type appears the
1972       // latest in the sorted order, regardless of the timestamp. This is used
1973       // for specifying the last key/value in a given row, because there is no
1974       // "lexicographically last column" (it would be infinitely long). The
1975       // "maximum" key type does not need this behavior.
1976       if (cell.getFamilyLength() + cell.getQualifierLength() == 0
1977           && cell.getTypeByte() == Type.Minimum.getCode()) {
1978         // left is "bigger", i.e. it appears later in the sorted order
1979         return 1;
1980       }
1981       if (flen+clen == 0 && type == Type.Minimum.getCode()) {
1982         return -1;
1983       }
1984 
1985       compare = compareFamilies(
1986         cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
1987         fam, foff, flen);
1988       if (compare != 0) {
1989         return compare;
1990       }
1991       compare = compareColumns(
1992         cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
1993         col, coff, clen);
1994       if (compare != 0) {
1995         return compare;
1996       }
1997       // Next compare timestamps.
1998       compare = compareTimestamps(cell.getTimestamp(), ts);
1999       if (compare != 0) {
2000         return compare;
2001       }
2002 
2003       // Compare types. Let the delete types sort ahead of puts; i.e. types
2004       // of higher numbers sort before those of lesser numbers. Maximum (255)
2005       // appears ahead of everything, and minimum (0) appears after
2006       // everything.
2007       return (0xff & type) - (0xff & cell.getTypeByte());
2008     }
2009 
2010     public int compareOnlyKeyPortion(Cell left, Cell right) {
2011       return CellComparator.compare(left, right, true);
2012     }
2013 
2014     /**
2015      * Compares the Key of a cell -- with fields being more significant in this order:
2016      * rowkey, colfam/qual, timestamp, type, mvcc
2017      */
2018     @Override
2019     public int compare(final Cell left, final Cell right) {
2020       int compare = CellComparator.compare(left, right, false);
2021       return compare;
2022     }
2023 
2024     public int compareTimestamps(final Cell left, final Cell right) {
2025       return CellComparator.compareTimestamps(left, right);
2026     }
2027 
2028     /**
2029      * @param left
2030      * @param right
2031      * @return Result comparing rows.
2032      */
2033     public int compareRows(final Cell left, final Cell right) {
2034       return compareRows(left.getRowArray(),left.getRowOffset(), left.getRowLength(),
2035       right.getRowArray(), right.getRowOffset(), right.getRowLength());
2036     }
2037 
2038     /**
2039      * Get the b[],o,l for left and right rowkey portions and compare.
2040      * @param left
2041      * @param loffset
2042      * @param llength
2043      * @param right
2044      * @param roffset
2045      * @param rlength
2046      * @return 0 if equal, <0 if left smaller, >0 if right smaller
2047      */
2048     public int compareRows(byte [] left, int loffset, int llength,
2049         byte [] right, int roffset, int rlength) {
2050       return Bytes.compareTo(left, loffset, llength, right, roffset, rlength);
2051     }
2052 
2053     int compareColumns(final Cell left, final short lrowlength, final Cell right,
2054         final short rrowlength) {
2055       return CellComparator.compareColumns(left, right);
2056     }
2057 
2058     protected int compareColumns(
2059         byte [] left, int loffset, int llength, final int lfamilylength,
2060         byte [] right, int roffset, int rlength, final int rfamilylength) {
2061       // Compare family portion first.
2062       int diff = Bytes.compareTo(left, loffset, lfamilylength,
2063         right, roffset, rfamilylength);
2064       if (diff != 0) {
2065         return diff;
2066       }
2067       // Compare qualifier portion
2068       return Bytes.compareTo(left, loffset + lfamilylength,
2069         llength - lfamilylength,
2070         right, roffset + rfamilylength, rlength - rfamilylength);
2071       }
2072 
2073     static int compareTimestamps(final long ltimestamp, final long rtimestamp) {
2074       // The below older timestamps sorting ahead of newer timestamps looks
2075       // wrong but it is intentional. This way, newer timestamps are first
2076       // found when we iterate over a memstore and newer versions are the
2077       // first we trip over when reading from a store file.
2078       if (ltimestamp < rtimestamp) {
2079         return 1;
2080       } else if (ltimestamp > rtimestamp) {
2081         return -1;
2082       }
2083       return 0;
2084     }
2085 
2086     /**
2087      * Overridden
2088      * @param commonPrefix
2089      * @param left
2090      * @param loffset
2091      * @param llength
2092      * @param right
2093      * @param roffset
2094      * @param rlength
2095      * @return 0 if equal, <0 if left smaller, >0 if right smaller
2096      */
2097     @Override // SamePrefixComparator
2098     public int compareIgnoringPrefix(int commonPrefix, byte[] left,
2099         int loffset, int llength, byte[] right, int roffset, int rlength) {
2100       // Compare row
2101       short lrowlength = Bytes.toShort(left, loffset);
2102       short rrowlength;
2103 
2104       int comparisonResult = 0;
2105       if (commonPrefix < ROW_LENGTH_SIZE) {
2106         // almost nothing in common
2107         rrowlength = Bytes.toShort(right, roffset);
2108         comparisonResult = compareRows(left, loffset + ROW_LENGTH_SIZE,
2109             lrowlength, right, roffset + ROW_LENGTH_SIZE, rrowlength);
2110       } else { // the row length is the same
2111         rrowlength = lrowlength;
2112         if (commonPrefix < ROW_LENGTH_SIZE + rrowlength) {
2113           // The rows are not the same. Exclude the common prefix and compare
2114           // the rest of the two rows.
2115           int common = commonPrefix - ROW_LENGTH_SIZE;
2116           comparisonResult = compareRows(
2117               left, loffset + common + ROW_LENGTH_SIZE, lrowlength - common,
2118               right, roffset + common + ROW_LENGTH_SIZE, rrowlength - common);
2119         }
2120       }
2121       if (comparisonResult != 0) {
2122         return comparisonResult;
2123       }
2124 
2125       assert lrowlength == rrowlength;
2126       return compareWithoutRow(commonPrefix, left, loffset, llength, right,
2127           roffset, rlength, lrowlength);
2128     }
2129 
2130     /**
2131      * Compare columnFamily, qualifier, timestamp, and key type (everything
2132      * except the row). This method is used both in the normal comparator and
2133      * the "same-prefix" comparator. Note that we are assuming that row portions
2134      * of both KVs have already been parsed and found identical, and we don't
2135      * validate that assumption here.
2136      * @param commonPrefix
2137      *          the length of the common prefix of the two key-values being
2138      *          compared, including row length and row
2139      */
2140     private int compareWithoutRow(int commonPrefix, byte[] left, int loffset,
2141         int llength, byte[] right, int roffset, int rlength, short rowlength) {
2142       /***
2143        * KeyValue Format and commonLength:
2144        * |_keyLen_|_valLen_|_rowLen_|_rowKey_|_famiLen_|_fami_|_Quali_|....
2145        * ------------------|-------commonLength--------|--------------
2146        */
2147       int commonLength = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + rowlength;
2148 
2149       // commonLength + TIMESTAMP_TYPE_SIZE
2150       int commonLengthWithTSAndType = TIMESTAMP_TYPE_SIZE + commonLength;
2151       // ColumnFamily + Qualifier length.
2152       int lcolumnlength = llength - commonLengthWithTSAndType;
2153       int rcolumnlength = rlength - commonLengthWithTSAndType;
2154 
2155       byte ltype = left[loffset + (llength - 1)];
2156       byte rtype = right[roffset + (rlength - 1)];
2157 
2158       // If the column is not specified, the "minimum" key type appears the
2159       // latest in the sorted order, regardless of the timestamp. This is used
2160       // for specifying the last key/value in a given row, because there is no
2161       // "lexicographically last column" (it would be infinitely long). The
2162       // "maximum" key type does not need this behavior.
2163       if (lcolumnlength == 0 && ltype == Type.Minimum.getCode()) {
2164         // left is "bigger", i.e. it appears later in the sorted order
2165         return 1;
2166       }
2167       if (rcolumnlength == 0 && rtype == Type.Minimum.getCode()) {
2168         return -1;
2169       }
2170 
2171       int lfamilyoffset = commonLength + loffset;
2172       int rfamilyoffset = commonLength + roffset;
2173 
2174       // Column family length.
2175       int lfamilylength = left[lfamilyoffset - 1];
2176       int rfamilylength = right[rfamilyoffset - 1];
2177       // If left family size is not equal to right family size, we need not
2178       // compare the qualifiers.
2179       boolean sameFamilySize = (lfamilylength == rfamilylength);
2180       int common = 0;
2181       if (commonPrefix > 0) {
2182         common = Math.max(0, commonPrefix - commonLength);
2183         if (!sameFamilySize) {
2184           // Common should not be larger than Math.min(lfamilylength,
2185           // rfamilylength).
2186           common = Math.min(common, Math.min(lfamilylength, rfamilylength));
2187         } else {
2188           common = Math.min(common, Math.min(lcolumnlength, rcolumnlength));
2189         }
2190       }
2191       if (!sameFamilySize) {
2192         // comparing column family is enough.
2193         return Bytes.compareTo(left, lfamilyoffset + common, lfamilylength
2194             - common, right, rfamilyoffset + common, rfamilylength - common);
2195       }
2196       // Compare family & qualifier together.
2197       final int comparison = Bytes.compareTo(left, lfamilyoffset + common,
2198           lcolumnlength - common, right, rfamilyoffset + common,
2199           rcolumnlength - common);
2200       if (comparison != 0) {
2201         return comparison;
2202       }
2203 
2204       ////
2205       // Next compare timestamps.
2206       long ltimestamp = Bytes.toLong(left,
2207           loffset + (llength - TIMESTAMP_TYPE_SIZE));
2208       long rtimestamp = Bytes.toLong(right,
2209           roffset + (rlength - TIMESTAMP_TYPE_SIZE));
2210       int compare = compareTimestamps(ltimestamp, rtimestamp);
2211       if (compare != 0) {
2212         return compare;
2213       }
2214 
2215       // Compare types. Let the delete types sort ahead of puts; i.e. types
2216       // of higher numbers sort before those of lesser numbers. Maximum (255)
2217       // appears ahead of everything, and minimum (0) appears after
2218       // everything.
2219       return (0xff & rtype) - (0xff & ltype);
2220     }
2221 
2222     protected int compareFamilies(final byte[] left, final int loffset, final int lfamilylength,
2223         final byte[] right, final int roffset, final int rfamilylength) {
2224       int diff = Bytes.compareTo(left, loffset, lfamilylength, right, roffset, rfamilylength);
2225       return diff;
2226     }
2227 
2228     protected int compareColumns(final byte[] left, final int loffset, final int lquallength,
2229         final byte[] right, final int roffset, final int rquallength) {
2230       int diff = Bytes.compareTo(left, loffset, lquallength, right, roffset, rquallength);
2231       return diff;
2232     }
2233     /**
2234      * Compares the row and column of two keyvalues for equality
2235      * @param left
2236      * @param right
2237      * @return True if same row and column.
2238      */
2239     public boolean matchingRowColumn(final Cell left,
2240         final Cell right) {
2241       short lrowlength = left.getRowLength();
2242       short rrowlength = right.getRowLength();
2243 
2244       // TsOffset = end of column data. just comparing Row+CF length of each
2245       if ((left.getRowLength() + left.getFamilyLength() + left.getQualifierLength()) != (right
2246           .getRowLength() + right.getFamilyLength() + right.getQualifierLength())) {
2247         return false;
2248       }
2249 
2250       if (!matchingRows(left, lrowlength, right, rrowlength)) {
2251         return false;
2252       }
2253 
2254       int lfoffset = left.getFamilyOffset();
2255       int rfoffset = right.getFamilyOffset();
2256       int lclength = left.getQualifierLength();
2257       int rclength = right.getQualifierLength();
2258       int lfamilylength = left.getFamilyLength();
2259       int rfamilylength = right.getFamilyLength();
2260       int diff = compareFamilies(left.getFamilyArray(), lfoffset, lfamilylength,
2261           right.getFamilyArray(), rfoffset, rfamilylength);
2262       if (diff != 0) {
2263         return false;
2264       } else {
2265         diff = compareColumns(left.getQualifierArray(), left.getQualifierOffset(), lclength,
2266             right.getQualifierArray(), right.getQualifierOffset(), rclength);
2267         return diff == 0;
2268       }
2269     }
2270 
2271     /**
2272      * Compares the row of two keyvalues for equality
2273      * @param left
2274      * @param right
2275      * @return True if rows match.
2276      */
2277     public boolean matchingRows(final Cell left, final Cell right) {
2278       short lrowlength = left.getRowLength();
2279       short rrowlength = right.getRowLength();
2280       return matchingRows(left, lrowlength, right, rrowlength);
2281     }
2282 
2283     /**
2284      * @param left
2285      * @param lrowlength
2286      * @param right
2287      * @param rrowlength
2288      * @return True if rows match.
2289      */
2290     private boolean matchingRows(final Cell left, final short lrowlength,
2291         final Cell right, final short rrowlength) {
2292       return lrowlength == rrowlength &&
2293           matchingRows(left.getRowArray(), left.getRowOffset(), lrowlength,
2294               right.getRowArray(), right.getRowOffset(), rrowlength);
2295     }
2296 
2297     /**
2298      * Compare rows. Just calls Bytes.equals, but it's good to have this encapsulated.
2299      * @param left Left row array.
2300      * @param loffset Left row offset.
2301      * @param llength Left row length.
2302      * @param right Right row array.
2303      * @param roffset Right row offset.
2304      * @param rlength Right row length.
2305      * @return Whether rows are the same row.
2306      */
2307     public boolean matchingRows(final byte [] left, final int loffset, final int llength,
2308         final byte [] right, final int roffset, final int rlength) {
2309       return Bytes.equals(left, loffset, llength, right, roffset, rlength);
2310     }
2311 
2312     public byte[] calcIndexKey(byte[] lastKeyOfPreviousBlock, byte[] firstKeyInBlock) {
2313       byte[] fakeKey = getShortMidpointKey(lastKeyOfPreviousBlock, firstKeyInBlock);
2314       if (compareFlatKey(fakeKey, firstKeyInBlock) > 0) {
2315         LOG.error("Unexpected getShortMidpointKey result, fakeKey:"
2316             + Bytes.toStringBinary(fakeKey) + ", firstKeyInBlock:"
2317             + Bytes.toStringBinary(firstKeyInBlock));
2318         return firstKeyInBlock;
2319       }
2320       if (lastKeyOfPreviousBlock != null && compareFlatKey(lastKeyOfPreviousBlock, fakeKey) >= 0) {
2321         LOG.error("Unexpected getShortMidpointKey result, lastKeyOfPreviousBlock:" +
2322             Bytes.toStringBinary(lastKeyOfPreviousBlock) + ", fakeKey:" +
2323             Bytes.toStringBinary(fakeKey));
2324         return firstKeyInBlock;
2325       }
2326       return fakeKey;
2327     }
2328 
2329     /**
2330      * This is a HFile block index key optimization.
2331      * @param leftKey
2332      * @param rightKey
2333      * @return 0 if equal, <0 if left smaller, >0 if right smaller
2334      * @deprecated Since 0.99.2; Use
2335      *             {@link CellComparator#getMidpoint(KeyValue.KVComparator, Cell, Cell) instead}
2336      */
2337     @Deprecated
2338     public byte[] getShortMidpointKey(final byte[] leftKey, final byte[] rightKey) {
2339       if (rightKey == null) {
2340         throw new IllegalArgumentException("rightKey can not be null");
2341       }
2342       if (leftKey == null) {
2343         return Arrays.copyOf(rightKey, rightKey.length);
2344       }
2345       if (compareFlatKey(leftKey, rightKey) >= 0) {
2346         throw new IllegalArgumentException("Unexpected input, leftKey:" + Bytes.toString(leftKey)
2347           + ", rightKey:" + Bytes.toString(rightKey));
2348       }
2349 
2350       short leftRowLength = Bytes.toShort(leftKey, 0);
2351       short rightRowLength = Bytes.toShort(rightKey, 0);
2352       int leftCommonLength = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + leftRowLength;
2353       int rightCommonLength = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + rightRowLength;
2354       int leftCommonLengthWithTSAndType = TIMESTAMP_TYPE_SIZE + leftCommonLength;
2355       int rightCommonLengthWithTSAndType = TIMESTAMP_TYPE_SIZE + rightCommonLength;
2356       int leftColumnLength = leftKey.length - leftCommonLengthWithTSAndType;
2357       int rightColumnLength = rightKey.length - rightCommonLengthWithTSAndType;
2358       // rows are equal
2359       if (leftRowLength == rightRowLength && compareRows(leftKey, ROW_LENGTH_SIZE, leftRowLength,
2360         rightKey, ROW_LENGTH_SIZE, rightRowLength) == 0) {
2361         // Compare family & qualifier together.
2362         int comparison = Bytes.compareTo(leftKey, leftCommonLength, leftColumnLength, rightKey,
2363           rightCommonLength, rightColumnLength);
2364         // same with "row + family + qualifier", return rightKey directly
2365         if (comparison == 0) {
2366           return Arrays.copyOf(rightKey, rightKey.length);
2367         }
2368         // "family + qualifier" are different, generate a faked key per rightKey
2369         byte[] newKey = Arrays.copyOf(rightKey, rightKey.length);
2370         Bytes.putLong(newKey, rightKey.length - TIMESTAMP_TYPE_SIZE, HConstants.LATEST_TIMESTAMP);
2371         Bytes.putByte(newKey, rightKey.length - TYPE_SIZE, Type.Maximum.getCode());
2372         return newKey;
2373       }
2374       // rows are different
2375       short minLength = leftRowLength < rightRowLength ? leftRowLength : rightRowLength;
2376       short diffIdx = 0;
2377       while (diffIdx < minLength
2378           && leftKey[ROW_LENGTH_SIZE + diffIdx] == rightKey[ROW_LENGTH_SIZE + diffIdx]) {
2379         diffIdx++;
2380       }
2381       byte[] newRowKey = null;
2382       if (diffIdx >= minLength) {
2383         // leftKey's row is prefix of rightKey's.
2384         newRowKey = new byte[diffIdx + 1];
2385         System.arraycopy(rightKey, ROW_LENGTH_SIZE, newRowKey, 0, diffIdx + 1);
2386       } else {
2387         int diffByte = leftKey[ROW_LENGTH_SIZE + diffIdx];
2388         if ((0xff & diffByte) < 0xff && (diffByte + 1) <
2389             (rightKey[ROW_LENGTH_SIZE + diffIdx] & 0xff)) {
2390           newRowKey = new byte[diffIdx + 1];
2391           System.arraycopy(leftKey, ROW_LENGTH_SIZE, newRowKey, 0, diffIdx);
2392           newRowKey[diffIdx] = (byte) (diffByte + 1);
2393         } else {
2394           newRowKey = new byte[diffIdx + 1];
2395           System.arraycopy(rightKey, ROW_LENGTH_SIZE, newRowKey, 0, diffIdx + 1);
2396         }
2397       }
2398       return new KeyValue(newRowKey, null, null, HConstants.LATEST_TIMESTAMP,
2399         Type.Maximum).getKey();
2400     }
2401 
2402     @Override
2403     protected Object clone() throws CloneNotSupportedException {
2404       super.clone();
2405       return new KVComparator();
2406     }
2407 
2408   }
2409 
2410   /**
2411    * @param b
2412    * @return A KeyValue made of a byte array that holds the key-only part.
2413    * Needed to convert hfile index members to KeyValues.
2414    */
2415   public static KeyValue createKeyValueFromKey(final byte [] b) {
2416     return createKeyValueFromKey(b, 0, b.length);
2417   }
2418 
2419   /**
2420    * @param bb
2421    * @return A KeyValue made of a byte buffer that holds the key-only part.
2422    * Needed to convert hfile index members to KeyValues.
2423    */
2424   public static KeyValue createKeyValueFromKey(final ByteBuffer bb) {
2425     return createKeyValueFromKey(bb.array(), bb.arrayOffset(), bb.limit());
2426   }
2427 
2428   /**
2429    * @param b
2430    * @param o
2431    * @param l
2432    * @return A KeyValue made of a byte array that holds the key-only part.
2433    * Needed to convert hfile index members to KeyValues.
2434    */
2435   public static KeyValue createKeyValueFromKey(final byte [] b, final int o,
2436       final int l) {
2437     byte [] newb = new byte[l + ROW_OFFSET];
2438     System.arraycopy(b, o, newb, ROW_OFFSET, l);
2439     Bytes.putInt(newb, 0, l);
2440     Bytes.putInt(newb, Bytes.SIZEOF_INT, 0);
2441     return new KeyValue(newb);
2442   }
2443 
2444   /**
2445    * @param in Where to read bytes from.  Creates a byte array to hold the KeyValue
2446    * backing bytes copied from the steam.
2447    * @return KeyValue created by deserializing from <code>in</code> OR if we find a length
2448    * of zero, we will return null which can be useful marking a stream as done.
2449    * @throws IOException
2450    */
2451   public static KeyValue create(final DataInput in) throws IOException {
2452     return create(in.readInt(), in);
2453   }
2454 
2455   /**
2456    * Create a KeyValue reading <code>length</code> from <code>in</code>
2457    * @param length
2458    * @param in
2459    * @return Created KeyValue OR if we find a length of zero, we will return null which
2460    * can be useful marking a stream as done.
2461    * @throws IOException
2462    */
2463   public static KeyValue create(int length, final DataInput in) throws IOException {
2464 
2465     if (length <= 0) {
2466       if (length == 0) return null;
2467       throw new IOException("Failed read " + length + " bytes, stream corrupt?");
2468     }
2469 
2470     // This is how the old Writables.readFrom used to deserialize.  Didn't even vint.
2471     byte [] bytes = new byte[length];
2472     in.readFully(bytes);
2473     return new KeyValue(bytes, 0, length);
2474   }
2475 
2476   /**
2477    * Create a new KeyValue by copying existing cell and adding new tags
2478    * @param c
2479    * @param newTags
2480    * @return a new KeyValue instance with new tags
2481    */
2482   public static KeyValue cloneAndAddTags(Cell c, List<Tag> newTags) {
2483     List<Tag> existingTags = null;
2484     if(c.getTagsLength() > 0) {
2485       existingTags = Tag.asList(c.getTagsArray(), c.getTagsOffset(), c.getTagsLength());
2486       existingTags.addAll(newTags);
2487     } else {
2488       existingTags = newTags;
2489     }
2490     return new KeyValue(c.getRowArray(), c.getRowOffset(), (int)c.getRowLength(),
2491       c.getFamilyArray(), c.getFamilyOffset(), (int)c.getFamilyLength(),
2492       c.getQualifierArray(), c.getQualifierOffset(), (int) c.getQualifierLength(),
2493       c.getTimestamp(), Type.codeToType(c.getTypeByte()), c.getValueArray(), c.getValueOffset(),
2494       c.getValueLength(), existingTags);
2495   }
2496 
2497   /**
2498    * Create a KeyValue reading from the raw InputStream.
2499    * Named <code>iscreate</code> so doesn't clash with {@link #create(DataInput)}
2500    * @param in
2501    * @return Created KeyValue OR if we find a length of zero, we will return null which
2502    * can be useful marking a stream as done.
2503    * @throws IOException
2504    */
2505   public static KeyValue iscreate(final InputStream in) throws IOException {
2506     byte [] intBytes = new byte[Bytes.SIZEOF_INT];
2507     int bytesRead = 0;
2508     while (bytesRead < intBytes.length) {
2509       int n = in.read(intBytes, bytesRead, intBytes.length - bytesRead);
2510       if (n < 0) {
2511         if (bytesRead == 0) return null; // EOF at start is ok
2512         throw new IOException("Failed read of int, read " + bytesRead + " bytes");
2513       }
2514       bytesRead += n;
2515     }
2516     // TODO: perhaps some sanity check is needed here.
2517     byte [] bytes = new byte[Bytes.toInt(intBytes)];
2518     IOUtils.readFully(in, bytes, 0, bytes.length);
2519     return new KeyValue(bytes, 0, bytes.length);
2520   }
2521 
2522   /**
2523    * Write out a KeyValue in the manner in which we used to when KeyValue was a Writable.
2524    * @param kv
2525    * @param out
2526    * @return Length written on stream
2527    * @throws IOException
2528    * @see #create(DataInput) for the inverse function
2529    */
2530   public static long write(final KeyValue kv, final DataOutput out) throws IOException {
2531     // This is how the old Writables write used to serialize KVs.  Need to figure way to make it
2532     // work for all implementations.
2533     int length = kv.getLength();
2534     out.writeInt(length);
2535     out.write(kv.getBuffer(), kv.getOffset(), length);
2536     return length + Bytes.SIZEOF_INT;
2537   }
2538 
2539   /**
2540    * Write out a KeyValue in the manner in which we used to when KeyValue was a Writable but do
2541    * not require a {@link DataOutput}, just take plain {@link OutputStream}
2542    * Named <code>oswrite</code> so does not clash with {@link #write(KeyValue, DataOutput)}
2543    * @param kv
2544    * @param out
2545    * @return Length written on stream
2546    * @throws IOException
2547    * @see #create(DataInput) for the inverse function
2548    * @see #write(KeyValue, DataOutput)
2549    * @deprecated use {@link #oswrite(KeyValue, OutputStream, boolean)} instead
2550    */
2551   @Deprecated
2552   public static long oswrite(final KeyValue kv, final OutputStream out)
2553       throws IOException {
2554     int length = kv.getLength();
2555     // This does same as DataOuput#writeInt (big-endian, etc.)
2556     out.write(Bytes.toBytes(length));
2557     out.write(kv.getBuffer(), kv.getOffset(), length);
2558     return length + Bytes.SIZEOF_INT;
2559   }
2560 
2561   /**
2562    * Write out a KeyValue in the manner in which we used to when KeyValue was a Writable but do
2563    * not require a {@link DataOutput}, just take plain {@link OutputStream}
2564    * Named <code>oswrite</code> so does not clash with {@link #write(KeyValue, DataOutput)}
2565    * @param kv
2566    * @param out
2567    * @param withTags
2568    * @return Length written on stream
2569    * @throws IOException
2570    * @see #create(DataInput) for the inverse function
2571    * @see #write(KeyValue, DataOutput)
2572    * @see KeyValueUtil#oswrite(Cell, OutputStream, boolean)
2573    */
2574   public static long oswrite(final KeyValue kv, final OutputStream out, final boolean withTags)
2575       throws IOException {
2576     // In KeyValueUtil#oswrite we do a Cell serialization as KeyValue. Any changes doing here, pls
2577     // check KeyValueUtil#oswrite also and do necessary changes.
2578     int length = kv.getLength();
2579     if (!withTags) {
2580       length = kv.getKeyLength() + kv.getValueLength() + KEYVALUE_INFRASTRUCTURE_SIZE;
2581     }
2582     // This does same as DataOuput#writeInt (big-endian, etc.)
2583     StreamUtils.writeInt(out, length);
2584     out.write(kv.getBuffer(), kv.getOffset(), length);
2585     return length + Bytes.SIZEOF_INT;
2586   }
2587 
2588   /**
2589    * Comparator that compares row component only of a KeyValue.
2590    */
2591   public static class RowOnlyComparator implements Comparator<KeyValue> {
2592     final KVComparator comparator;
2593 
2594     public RowOnlyComparator(final KVComparator c) {
2595       this.comparator = c;
2596     }
2597 
2598     @Override
2599     public int compare(KeyValue left, KeyValue right) {
2600       return comparator.compareRows(left, right);
2601     }
2602   }
2603 
2604 
2605   /**
2606    * Avoids redundant comparisons for better performance.
2607    *
2608    * TODO get rid of this wart
2609    */
2610   public interface SamePrefixComparator<T> {
2611     /**
2612      * Compare two keys assuming that the first n bytes are the same.
2613      * @param commonPrefix How many bytes are the same.
2614      */
2615     int compareIgnoringPrefix(int commonPrefix, byte[] left, int loffset, int llength,
2616         byte[] right, int roffset, int rlength
2617     );
2618   }
2619 
2620   /**
2621    * This is a TEST only Comparator used in TestSeekTo and TestReseekTo.
2622    */
2623   public static class RawBytesComparator extends KVComparator {
2624     /**
2625      * The HFileV2 file format's trailer contains this class name.  We reinterpret this and
2626      * instantiate the appropriate comparator.
2627      * TODO: With V3 consider removing this.
2628      * @return legacy class name for FileFileTrailer#comparatorClassName
2629      */
2630     @Override
2631     public String getLegacyKeyComparatorName() {
2632       return "org.apache.hadoop.hbase.util.Bytes$ByteArrayComparator";
2633     }
2634 
2635     /**
2636      * @deprecated Since 0.99.2.
2637      */
2638     @Override
2639     @Deprecated
2640     public int compareFlatKey(byte[] left, int loffset, int llength, byte[] right,
2641         int roffset, int rlength) {
2642       return Bytes.BYTES_RAWCOMPARATOR.compare(left,  loffset, llength, right, roffset, rlength);
2643     }
2644 
2645     @Override
2646     public int compare(Cell left, Cell right) {
2647       return compareOnlyKeyPortion(left, right);
2648     }
2649 
2650     @Override
2651     @VisibleForTesting
2652     public int compareOnlyKeyPortion(Cell left, Cell right) {
2653       int c = Bytes.BYTES_RAWCOMPARATOR.compare(left.getRowArray(), left.getRowOffset(),
2654           left.getRowLength(), right.getRowArray(), right.getRowOffset(), right.getRowLength());
2655       if (c != 0) {
2656         return c;
2657       }
2658       c = Bytes.BYTES_RAWCOMPARATOR.compare(left.getFamilyArray(), left.getFamilyOffset(),
2659           left.getFamilyLength(), right.getFamilyArray(), right.getFamilyOffset(),
2660           right.getFamilyLength());
2661       if (c != 0) {
2662         return c;
2663       }
2664       c = Bytes.BYTES_RAWCOMPARATOR.compare(left.getQualifierArray(), left.getQualifierOffset(),
2665           left.getQualifierLength(), right.getQualifierArray(), right.getQualifierOffset(),
2666           right.getQualifierLength());
2667       if (c != 0) {
2668         return c;
2669       }
2670       c = compareTimestamps(left.getTimestamp(), right.getTimestamp());
2671       if (c != 0) {
2672         return c;
2673       }
2674       return (0xff & left.getTypeByte()) - (0xff & right.getTypeByte());
2675     }
2676 
2677     @Override
2678     public byte[] calcIndexKey(byte[] lastKeyOfPreviousBlock, byte[] firstKeyInBlock) {
2679       return firstKeyInBlock;
2680     }
2681 
2682   }
2683 
2684   /**
2685    * HeapSize implementation
2686    *
2687    * We do not count the bytes in the rowCache because it should be empty for a KeyValue in the
2688    * MemStore.
2689    */
2690   @Override
2691   public long heapSize() {
2692     int sum = 0;
2693     sum += ClassSize.OBJECT;// the KeyValue object itself
2694     sum += ClassSize.REFERENCE;// pointer to "bytes"
2695     sum += ClassSize.align(ClassSize.ARRAY);// "bytes"
2696     sum += ClassSize.align(length);// number of bytes of data in the "bytes" array
2697     sum += 2 * Bytes.SIZEOF_INT;// offset, length
2698     sum += Bytes.SIZEOF_LONG;// memstoreTS
2699     return ClassSize.align(sum);
2700   }
2701 
2702   /**
2703    * This is a hack that should be removed once we don't care about matching
2704    * up client- and server-side estimations of cell size. It needed to be
2705    * backwards compatible with estimations done by older clients. We need to
2706    * pretend that tags never exist and KeyValues aren't serialized with tag
2707    * length included. See HBASE-13262 and HBASE-13303
2708    */
2709   @Deprecated
2710   public long heapSizeWithoutTags() {
2711     int sum = 0;
2712     sum += ClassSize.OBJECT;// the KeyValue object itself
2713     sum += ClassSize.REFERENCE;// pointer to "bytes"
2714     sum += ClassSize.align(ClassSize.ARRAY);// "bytes"
2715     sum += KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE;
2716     sum += getKeyLength();
2717     sum += getValueLength();
2718     sum += 2 * Bytes.SIZEOF_INT;// offset, length
2719     sum += Bytes.SIZEOF_LONG;// memstoreTS
2720     return ClassSize.align(sum);
2721   }
2722 
2723   /**
2724    * A simple form of KeyValue that creates a keyvalue with only the key part of the byte[]
2725    * Mainly used in places where we need to compare two cells.  Avoids copying of bytes
2726    * In places like block index keys, we need to compare the key byte[] with a cell.
2727    * Hence create a Keyvalue(aka Cell) that would help in comparing as two cells
2728    */
2729   public static class KeyOnlyKeyValue extends KeyValue {
2730     public KeyOnlyKeyValue() {
2731 
2732     }
2733     public KeyOnlyKeyValue(byte[] b) {
2734       this(b, 0, b.length);
2735     }
2736 
2737     public KeyOnlyKeyValue(byte[] b, int offset, int length) {
2738       this.bytes = b;
2739       this.length = length;
2740       this.offset = offset;
2741     }
2742 
2743     @Override
2744     public int getKeyOffset() {
2745       return this.offset;
2746     }
2747 
2748     /**
2749      * A setter that helps to avoid object creation every time and whenever
2750      * there is a need to create new KeyOnlyKeyValue.
2751      * @param key
2752      * @param offset
2753      * @param length
2754      */
2755     public void setKey(byte[] key, int offset, int length) {
2756       this.bytes = key;
2757       this.offset = offset;
2758       this.length = length;
2759     }
2760 
2761     @Override
2762     public byte[] getKey() {
2763       int keylength = getKeyLength();
2764       byte[] key = new byte[keylength];
2765       System.arraycopy(this.bytes, getKeyOffset(), key, 0, keylength);
2766       return key;
2767     }
2768 
2769     @Override
2770     public byte[] getRowArray() {
2771       return bytes;
2772     }
2773 
2774     @Override
2775     public int getRowOffset() {
2776       return getKeyOffset() + Bytes.SIZEOF_SHORT;
2777     }
2778 
2779     @Override
2780     public byte[] getFamilyArray() {
2781       return bytes;
2782     }
2783 
2784     @Override
2785     public byte getFamilyLength() {
2786       return this.bytes[getFamilyOffset() - 1];
2787     }
2788 
2789     @Override
2790     public int getFamilyOffset() {
2791       return this.offset + Bytes.SIZEOF_SHORT + getRowLength() + Bytes.SIZEOF_BYTE;
2792     }
2793 
2794     @Override
2795     public byte[] getQualifierArray() {
2796       return bytes;
2797     }
2798 
2799     @Override
2800     public int getQualifierLength() {
2801       return getQualifierLength(getRowLength(), getFamilyLength());
2802     }
2803 
2804     @Override
2805     public int getQualifierOffset() {
2806       return getFamilyOffset() + getFamilyLength();
2807     }
2808 
2809     @Override
2810     public int getKeyLength() {
2811       return length;
2812     }
2813 
2814     @Override
2815     public short getRowLength() {
2816       return Bytes.toShort(this.bytes, getKeyOffset());
2817     }
2818 
2819     @Override
2820     public byte getTypeByte() {
2821       return this.bytes[this.offset + getKeyLength() - 1];
2822     }
2823 
2824     private int getQualifierLength(int rlength, int flength) {
2825       return getKeyLength() - (int) getKeyDataStructureSize(rlength, flength, 0);
2826     }
2827 
2828     @Override
2829     public long getTimestamp() {
2830       int tsOffset = getTimestampOffset();
2831       return Bytes.toLong(this.bytes, tsOffset);
2832     }
2833 
2834     @Override
2835     public int getTimestampOffset() {
2836       return getKeyOffset() + getKeyLength() - TIMESTAMP_TYPE_SIZE;
2837     }
2838 
2839     @Override
2840     public byte[] getTagsArray() {
2841       return HConstants.EMPTY_BYTE_ARRAY;
2842     }
2843 
2844     @Override
2845     public int getTagsOffset() {
2846       return 0;
2847     }
2848 
2849     @Override
2850     public byte[] getValueArray() {
2851       throw new IllegalArgumentException("KeyOnlyKeyValue does not work with values.");
2852     }
2853 
2854     @Override
2855     public int getValueOffset() {
2856       throw new IllegalArgumentException("KeyOnlyKeyValue does not work with values.");
2857     }
2858 
2859     @Override
2860     public int getValueLength() {
2861       throw new IllegalArgumentException("KeyOnlyKeyValue does not work with values.");
2862     }
2863 
2864     @Override
2865     public int getTagsLength() {
2866       return 0;
2867     }
2868 
2869     @Override
2870     public String toString() {
2871       if (this.bytes == null || this.bytes.length == 0) {
2872         return "empty";
2873       }
2874       return keyToString(this.bytes, this.offset, getKeyLength()) + "/vlen=0/mvcc=0";
2875     }
2876 
2877     @Override
2878     public int hashCode() {
2879       return super.hashCode();
2880     }
2881 
2882     @Override
2883     public boolean equals(Object other) {
2884       return super.equals(other);
2885     }
2886   }
2887 }