View Javadoc

1   /**
2    * Copyright 2009 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 java.io.DataInput;
23  import java.io.DataOutput;
24  import java.io.IOException;
25  import java.nio.ByteBuffer;
26  import java.util.Comparator;
27  
28  import com.google.common.primitives.Longs;
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.io.HeapSize;
32  import org.apache.hadoop.hbase.io.hfile.HFile;
33  import org.apache.hadoop.hbase.util.Bytes;
34  import org.apache.hadoop.hbase.util.ClassSize;
35  import org.apache.hadoop.io.RawComparator;
36  import org.apache.hadoop.io.Writable;
37  
38  /**
39   * An HBase Key/Value.
40   *
41   * <p>If being used client-side, the primary methods to access individual fields
42   * are {@link #getRow()}, {@link #getFamily()}, {@link #getQualifier()},
43   * {@link #getTimestamp()}, and {@link #getValue()}.  These methods allocate new
44   * byte arrays and return copies so they should be avoided server-side.
45   *
46   * <p>Instances of this class are immutable.  They are not
47   * comparable but Comparators are provided.  Comparators change with context,
48   * whether user table or a catalog table comparison context.  Its
49   * important that you use the appropriate comparator comparing rows in
50   * particular.  There are Comparators for KeyValue instances and then for
51   * just the Key portion of a KeyValue used mostly in {@link HFile}.
52   *
53   * <p>KeyValue wraps a byte array and has offset and length for passed array
54   * at where to start interpreting the content as a KeyValue blob.  The KeyValue
55   * blob format inside the byte array is:
56   * <code>&lt;keylength> &lt;valuelength> &lt;key> &lt;value></code>
57   * Key is decomposed as:
58   * <code>&lt;rowlength> &lt;row> &lt;columnfamilylength> &lt;columnfamily> &lt;columnqualifier> &lt;timestamp> &lt;keytype></code>
59   * Rowlength maximum is Short.MAX_SIZE, column family length maximum is
60   * Byte.MAX_SIZE, and column qualifier + key length must be < Integer.MAX_SIZE.
61   * The column does not contain the family/qualifier delimiter.
62   *
63   * <p>TODO: Group Key-only comparators and operations into a Key class, just
64   * for neatness sake, if can figure what to call it.
65   */
66  public class KeyValue implements Writable, HeapSize {
67    static final Log LOG = LogFactory.getLog(KeyValue.class);
68  
69    /**
70     * Colon character in UTF-8
71     */
72    public static final char COLUMN_FAMILY_DELIMITER = ':';
73  
74    public static final byte[] COLUMN_FAMILY_DELIM_ARRAY =
75      new byte[]{COLUMN_FAMILY_DELIMITER};
76  
77    /**
78     * Comparator for plain key/values; i.e. non-catalog table key/values.
79     */
80    public static KVComparator COMPARATOR = new KVComparator();
81  
82    /**
83     * Comparator for plain key; i.e. non-catalog table key.  Works on Key portion
84     * of KeyValue only.
85     */
86    public static KeyComparator KEY_COMPARATOR = new KeyComparator();
87  
88    /**
89     * A {@link KVComparator} for <code>.META.</code> catalog table
90     * {@link KeyValue}s.
91     */
92    public static KVComparator META_COMPARATOR = new MetaComparator();
93  
94    /**
95     * A {@link KVComparator} for <code>.META.</code> catalog table
96     * {@link KeyValue} keys.
97     */
98    public static KeyComparator META_KEY_COMPARATOR = new MetaKeyComparator();
99  
100   /**
101    * A {@link KVComparator} for <code>-ROOT-</code> catalog table
102    * {@link KeyValue}s.
103    */
104   public static KVComparator ROOT_COMPARATOR = new RootComparator();
105 
106   /**
107    * A {@link KVComparator} for <code>-ROOT-</code> catalog table
108    * {@link KeyValue} keys.
109    */
110   public static KeyComparator ROOT_KEY_COMPARATOR = new RootKeyComparator();
111 
112   /**
113    * Get the appropriate row comparator for the specified table.
114    *
115    * Hopefully we can get rid of this, I added this here because it's replacing
116    * something in HSK.  We should move completely off of that.
117    *
118    * @param tableName  The table name.
119    * @return The comparator.
120    */
121   public static KeyComparator getRowComparator(byte [] tableName) {
122     if(Bytes.equals(HTableDescriptor.ROOT_TABLEDESC.getName(),tableName)) {
123       return ROOT_COMPARATOR.getRawComparator();
124     }
125     if(Bytes.equals(HTableDescriptor.META_TABLEDESC.getName(), tableName)) {
126       return META_COMPARATOR.getRawComparator();
127     }
128     return COMPARATOR.getRawComparator();
129   }
130 
131   // Size of the timestamp and type byte on end of a key -- a long + a byte.
132   public static final int TIMESTAMP_TYPE_SIZE =
133     Bytes.SIZEOF_LONG /* timestamp */ +
134     Bytes.SIZEOF_BYTE /*keytype*/;
135 
136   // Size of the length shorts and bytes in key.
137   public static final int KEY_INFRASTRUCTURE_SIZE =
138     Bytes.SIZEOF_SHORT /*rowlength*/ +
139     Bytes.SIZEOF_BYTE /*columnfamilylength*/ +
140     TIMESTAMP_TYPE_SIZE;
141 
142   // How far into the key the row starts at. First thing to read is the short
143   // that says how long the row is.
144   public static final int ROW_OFFSET =
145     Bytes.SIZEOF_INT /*keylength*/ +
146     Bytes.SIZEOF_INT /*valuelength*/;
147 
148   // Size of the length ints in a KeyValue datastructure.
149   public static final int KEYVALUE_INFRASTRUCTURE_SIZE = ROW_OFFSET;
150 
151   /**
152    * Key type.
153    * Has space for other key types to be added later.  Cannot rely on
154    * enum ordinals . They change if item is removed or moved.  Do our own codes.
155    */
156   public static enum Type {
157     Minimum((byte)0),
158     Put((byte)4),
159 
160     Delete((byte)8),
161     DeleteColumn((byte)12),
162     DeleteFamily((byte)14),
163 
164     // Maximum is used when searching; you look from maximum on down.
165     Maximum((byte)255);
166 
167     private final byte code;
168 
169     Type(final byte c) {
170       this.code = c;
171     }
172 
173     public byte getCode() {
174       return this.code;
175     }
176 
177     /**
178      * Cannot rely on enum ordinals . They change if item is removed or moved.
179      * Do our own codes.
180      * @param b
181      * @return Type associated with passed code.
182      */
183     public static Type codeToType(final byte b) {
184       for (Type t : Type.values()) {
185         if (t.getCode() == b) {
186           return t;
187         }
188       }
189       throw new RuntimeException("Unknown code " + b);
190     }
191   }
192 
193   /**
194    * Lowest possible key.
195    * Makes a Key with highest possible Timestamp, empty row and column.  No
196    * key can be equal or lower than this one in memstore or in store file.
197    */
198   public static final KeyValue LOWESTKEY =
199     new KeyValue(HConstants.EMPTY_BYTE_ARRAY, HConstants.LATEST_TIMESTAMP);
200 
201   private byte [] bytes = null;
202   private int offset = 0;
203   private int length = 0;
204 
205   // the row cached
206   private byte [] rowCache = null;
207 
208 
209   /** Here be dragons **/
210 
211   // used to achieve atomic operations in the memstore.
212   public long getMemstoreTS() {
213     return memstoreTS;
214   }
215 
216   public void setMemstoreTS(long memstoreTS) {
217     this.memstoreTS = memstoreTS;
218   }
219 
220   // default value is 0, aka DNC
221   private long memstoreTS = 0;
222 
223   /** Dragon time over, return to normal business */
224 
225 
226   /** Writable Constructor -- DO NOT USE */
227   public KeyValue() {}
228 
229   /**
230    * Creates a KeyValue from the start of the specified byte array.
231    * Presumes <code>bytes</code> content is formatted as a KeyValue blob.
232    * @param bytes byte array
233    */
234   public KeyValue(final byte [] bytes) {
235     this(bytes, 0);
236   }
237 
238   /**
239    * Creates a KeyValue from the specified byte array and offset.
240    * Presumes <code>bytes</code> content starting at <code>offset</code> is
241    * formatted as a KeyValue blob.
242    * @param bytes byte array
243    * @param offset offset to start of KeyValue
244    */
245   public KeyValue(final byte [] bytes, final int offset) {
246     this(bytes, offset, getLength(bytes, offset));
247   }
248 
249   /**
250    * Creates a KeyValue from the specified byte array, starting at offset, and
251    * for length <code>length</code>.
252    * @param bytes byte array
253    * @param offset offset to start of the KeyValue
254    * @param length length of the KeyValue
255    */
256   public KeyValue(final byte [] bytes, final int offset, final int length) {
257     this.bytes = bytes;
258     this.offset = offset;
259     this.length = length;
260   }
261 
262   /** Constructors that build a new backing byte array from fields */
263 
264   /**
265    * Constructs KeyValue structure filled with null value.
266    * Sets type to {@link KeyValue.Type#Maximum}
267    * @param row - row key (arbitrary byte array)
268    * @param timestamp
269    */
270   public KeyValue(final byte [] row, final long timestamp) {
271     this(row, timestamp, Type.Maximum);
272   }
273 
274   /**
275    * Constructs KeyValue structure filled with null value.
276    * @param row - row key (arbitrary byte array)
277    * @param timestamp
278    */
279   public KeyValue(final byte [] row, final long timestamp, Type type) {
280     this(row, null, null, timestamp, type, null);
281   }
282 
283   /**
284    * Constructs KeyValue structure filled with null value.
285    * Sets type to {@link KeyValue.Type#Maximum}
286    * @param row - row key (arbitrary byte array)
287    * @param family family name
288    * @param qualifier column qualifier
289    */
290   public KeyValue(final byte [] row, final byte [] family,
291       final byte [] qualifier) {
292     this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum);
293   }
294 
295   /**
296    * Constructs KeyValue structure filled with null value.
297    * @param row - row key (arbitrary byte array)
298    * @param family family name
299    * @param qualifier column qualifier
300    */
301   public KeyValue(final byte [] row, final byte [] family,
302       final byte [] qualifier, final byte [] value) {
303     this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Put, value);
304   }
305 
306   /**
307    * Constructs KeyValue structure filled with specified values.
308    * @param row row key
309    * @param family family name
310    * @param qualifier column qualifier
311    * @param timestamp version timestamp
312    * @param type key type
313    * @throws IllegalArgumentException
314    */
315   public KeyValue(final byte[] row, final byte[] family,
316       final byte[] qualifier, final long timestamp, Type type) {
317     this(row, family, qualifier, timestamp, type, null);
318   }
319 
320   /**
321    * Constructs KeyValue structure filled with specified values.
322    * @param row row key
323    * @param family family name
324    * @param qualifier column qualifier
325    * @param timestamp version timestamp
326    * @param value column value
327    * @throws IllegalArgumentException
328    */
329   public KeyValue(final byte[] row, final byte[] family,
330       final byte[] qualifier, final long timestamp, final byte[] value) {
331     this(row, family, qualifier, timestamp, Type.Put, value);
332   }
333 
334   /**
335    * Constructs KeyValue structure filled with specified values.
336    * @param row row key
337    * @param family family name
338    * @param qualifier column qualifier
339    * @param timestamp version timestamp
340    * @param type key type
341    * @param value column value
342    * @throws IllegalArgumentException
343    */
344   public KeyValue(final byte[] row, final byte[] family,
345       final byte[] qualifier, final long timestamp, Type type,
346       final byte[] value) {
347     this(row, family, qualifier, 0, qualifier==null ? 0 : qualifier.length,
348         timestamp, type, value, 0, value==null ? 0 : value.length);
349   }
350 
351   /**
352    * Constructs KeyValue structure filled with specified values.
353    * @param row row key
354    * @param family family name
355    * @param qualifier column qualifier
356    * @param qoffset qualifier offset
357    * @param qlength qualifier length
358    * @param timestamp version timestamp
359    * @param type key type
360    * @param value column value
361    * @param voffset value offset
362    * @param vlength value length
363    * @throws IllegalArgumentException
364    */
365   public KeyValue(byte [] row, byte [] family,
366       byte [] qualifier, int qoffset, int qlength, long timestamp, Type type,
367       byte [] value, int voffset, int vlength) {
368     this(row, 0, row==null ? 0 : row.length,
369         family, 0, family==null ? 0 : family.length,
370         qualifier, qoffset, qlength, timestamp, type,
371         value, voffset, vlength);
372   }
373 
374   /**
375    * Constructs KeyValue structure filled with specified values.
376    * <p>
377    * Column is split into two fields, family and qualifier.
378    * @param row row key
379    * @param roffset row offset
380    * @param rlength row length
381    * @param family family name
382    * @param foffset family offset
383    * @param flength family length
384    * @param qualifier column qualifier
385    * @param qoffset qualifier offset
386    * @param qlength qualifier length
387    * @param timestamp version timestamp
388    * @param type key type
389    * @param value column value
390    * @param voffset value offset
391    * @param vlength value length
392    * @throws IllegalArgumentException
393    */
394   public KeyValue(final byte [] row, final int roffset, final int rlength,
395       final byte [] family, final int foffset, final int flength,
396       final byte [] qualifier, final int qoffset, final int qlength,
397       final long timestamp, final Type type,
398       final byte [] value, final int voffset, final int vlength) {
399     this.bytes = createByteArray(row, roffset, rlength,
400         family, foffset, flength, qualifier, qoffset, qlength,
401         timestamp, type, value, voffset, vlength);
402     this.length = bytes.length;
403     this.offset = 0;
404   }
405 
406   /**
407    * Write KeyValue format into a byte array.
408    *
409    * @param row row key
410    * @param roffset row offset
411    * @param rlength row length
412    * @param family family name
413    * @param foffset family offset
414    * @param flength family length
415    * @param qualifier column qualifier
416    * @param qoffset qualifier offset
417    * @param qlength qualifier length
418    * @param timestamp version timestamp
419    * @param type key type
420    * @param value column value
421    * @param voffset value offset
422    * @param vlength value length
423    * @return The newly created byte array.
424    */
425   static byte [] createByteArray(final byte [] row, final int roffset,
426       final int rlength, final byte [] family, final int foffset, int flength,
427       final byte [] qualifier, final int qoffset, int qlength,
428       final long timestamp, final Type type,
429       final byte [] value, final int voffset, int vlength) {
430     if (rlength > Short.MAX_VALUE) {
431       throw new IllegalArgumentException("Row > " + Short.MAX_VALUE);
432     }
433     if (row == null) {
434       throw new IllegalArgumentException("Row is null");
435     }
436     // Family length
437     flength = family == null ? 0 : flength;
438     if (flength > Byte.MAX_VALUE) {
439       throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE);
440     }
441     // Qualifier length
442     qlength = qualifier == null ? 0 : qlength;
443     if (qlength > Integer.MAX_VALUE - rlength - flength) {
444       throw new IllegalArgumentException("Qualifier > " + Integer.MAX_VALUE);
445     }
446     // Key length
447     long longkeylength = KEY_INFRASTRUCTURE_SIZE + rlength + flength + qlength;
448     if (longkeylength > Integer.MAX_VALUE) {
449       throw new IllegalArgumentException("keylength " + longkeylength + " > " +
450         Integer.MAX_VALUE);
451     }
452     int keylength = (int)longkeylength;
453     // Value length
454     vlength = value == null? 0 : vlength;
455     if (vlength > HConstants.MAXIMUM_VALUE_LENGTH) { // FindBugs INT_VACUOUS_COMPARISON
456       throw new IllegalArgumentException("Valuer > " +
457           HConstants.MAXIMUM_VALUE_LENGTH);
458     }
459 
460     // Allocate right-sized byte array.
461     byte [] bytes = new byte[KEYVALUE_INFRASTRUCTURE_SIZE + keylength + vlength];
462     // Write key, value and key row length.
463     int pos = 0;
464     pos = Bytes.putInt(bytes, pos, keylength);
465     pos = Bytes.putInt(bytes, pos, vlength);
466     pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff));
467     pos = Bytes.putBytes(bytes, pos, row, roffset, rlength);
468     pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff));
469     if(flength != 0) {
470       pos = Bytes.putBytes(bytes, pos, family, foffset, flength);
471     }
472     if(qlength != 0) {
473       pos = Bytes.putBytes(bytes, pos, qualifier, qoffset, qlength);
474     }
475     pos = Bytes.putLong(bytes, pos, timestamp);
476     pos = Bytes.putByte(bytes, pos, type.getCode());
477     if (value != null && value.length > 0) {
478       pos = Bytes.putBytes(bytes, pos, value, voffset, vlength);
479     }
480     return bytes;
481   }
482 
483   /**
484    * Write KeyValue format into a byte array.
485    * <p>
486    * Takes column in the form <code>family:qualifier</code>
487    * @param row - row key (arbitrary byte array)
488    * @param roffset
489    * @param rlength
490    * @param column
491    * @param coffset
492    * @param clength
493    * @param timestamp
494    * @param type
495    * @param value
496    * @param voffset
497    * @param vlength
498    * @return The newly created byte array.
499    */
500   static byte [] createByteArray(final byte [] row, final int roffset,
501         final int rlength,
502       final byte [] column, final int coffset, int clength,
503       final long timestamp, final Type type,
504       final byte [] value, final int voffset, int vlength) {
505     // If column is non-null, figure where the delimiter is at.
506     int delimiteroffset = 0;
507     if (column != null && column.length > 0) {
508       delimiteroffset = getFamilyDelimiterIndex(column, coffset, clength);
509       if (delimiteroffset > Byte.MAX_VALUE) {
510         throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE);
511       }
512     } else {
513       return createByteArray(row,roffset,rlength,null,0,0,null,0,0,timestamp,
514           type,value,voffset,vlength);
515     }
516     int flength = delimiteroffset-coffset;
517     int qlength = clength - flength - 1;
518     return createByteArray(row, roffset, rlength, column, coffset,
519         flength, column, delimiteroffset+1, qlength, timestamp, type,
520         value, voffset, vlength);
521   }
522 
523   // Needed doing 'contains' on List.  Only compares the key portion, not the
524   // value.
525   public boolean equals(Object other) {
526     if (!(other instanceof KeyValue)) {
527       return false;
528     }
529     KeyValue kv = (KeyValue)other;
530     // Comparing bytes should be fine doing equals test.  Shouldn't have to
531     // worry about special .META. comparators doing straight equals.
532     boolean result = Bytes.BYTES_RAWCOMPARATOR.compare(getBuffer(),
533         getKeyOffset(), getKeyLength(),
534       kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength()) == 0;
535     return result;
536   }
537 
538   public int hashCode() {
539     byte[] b = getBuffer();
540     int start = getOffset(), end = getOffset() + getLength();
541     int h = b[start++];
542     for (int i = start; i < end; i++) {
543       h = (h * 13) ^ b[i];
544     }
545     return h;
546   }
547 
548   //---------------------------------------------------------------------------
549   //
550   //  KeyValue cloning
551   //
552   //---------------------------------------------------------------------------
553 
554   /**
555    * Clones a KeyValue.  This creates a copy, re-allocating the buffer.
556    * @return Fully copied clone of this KeyValue
557    */
558   public KeyValue clone() {
559     byte [] b = new byte[this.length];
560     System.arraycopy(this.bytes, this.offset, b, 0, this.length);
561     KeyValue ret = new KeyValue(b, 0, b.length);
562     // Important to clone the memstoreTS as well - otherwise memstore's
563     // update-in-place methods (eg increment) will end up creating
564     // new entries
565     ret.setMemstoreTS(memstoreTS);
566     return ret;
567   }
568 
569   //---------------------------------------------------------------------------
570   //
571   //  String representation
572   //
573   //---------------------------------------------------------------------------
574 
575   public String toString() {
576     if (this.bytes == null || this.bytes.length == 0) {
577       return "empty";
578     }
579     return keyToString(this.bytes, this.offset + ROW_OFFSET, getKeyLength()) +
580       "/vlen=" + getValueLength();
581   }
582 
583   /**
584    * @param k Key portion of a KeyValue.
585    * @return Key as a String.
586    */
587   public static String keyToString(final byte [] k) {
588     return keyToString(k, 0, k.length);
589   }
590 
591   /**
592    * Use for logging.
593    * @param b Key portion of a KeyValue.
594    * @param o Offset to start of key
595    * @param l Length of key.
596    * @return Key as a String.
597    */
598   public static String keyToString(final byte [] b, final int o, final int l) {
599     if (b == null) return "";
600     int rowlength = Bytes.toShort(b, o);
601     String row = Bytes.toStringBinary(b, o + Bytes.SIZEOF_SHORT, rowlength);
602     int columnoffset = o + Bytes.SIZEOF_SHORT + 1 + rowlength;
603     int familylength = b[columnoffset - 1];
604     int columnlength = l - ((columnoffset - o) + TIMESTAMP_TYPE_SIZE);
605     String family = familylength == 0? "":
606       Bytes.toStringBinary(b, columnoffset, familylength);
607     String qualifier = columnlength == 0? "":
608       Bytes.toStringBinary(b, columnoffset + familylength,
609       columnlength - familylength);
610     long timestamp = Bytes.toLong(b, o + (l - TIMESTAMP_TYPE_SIZE));
611     byte type = b[o + l - 1];
612 //    return row + "/" + family +
613 //      (family != null && family.length() > 0? COLUMN_FAMILY_DELIMITER: "") +
614 //      qualifier + "/" + timestamp + "/" + Type.codeToType(type);
615     return row + "/" + family +
616       (family != null && family.length() > 0? ":" :"") +
617       qualifier + "/" + timestamp + "/" + Type.codeToType(type);
618   }
619 
620   //---------------------------------------------------------------------------
621   //
622   //  Public Member Accessors
623   //
624   //---------------------------------------------------------------------------
625 
626   /**
627    * @return The byte array backing this KeyValue.
628    */
629   public byte [] getBuffer() {
630     return this.bytes;
631   }
632 
633   /**
634    * @return Offset into {@link #getBuffer()} at which this KeyValue starts.
635    */
636   public int getOffset() {
637     return this.offset;
638   }
639 
640   /**
641    * @return Length of bytes this KeyValue occupies in {@link #getBuffer()}.
642    */
643   public int getLength() {
644     return length;
645   }
646 
647   //---------------------------------------------------------------------------
648   //
649   //  Length and Offset Calculators
650   //
651   //---------------------------------------------------------------------------
652 
653   /**
654    * Determines the total length of the KeyValue stored in the specified
655    * byte array and offset.  Includes all headers.
656    * @param bytes byte array
657    * @param offset offset to start of the KeyValue
658    * @return length of entire KeyValue, in bytes
659    */
660   private static int getLength(byte [] bytes, int offset) {
661     return (2 * Bytes.SIZEOF_INT) +
662         Bytes.toInt(bytes, offset) +
663         Bytes.toInt(bytes, offset + Bytes.SIZEOF_INT);
664   }
665 
666   /**
667    * @return Key offset in backing buffer..
668    */
669   public int getKeyOffset() {
670     return this.offset + ROW_OFFSET;
671   }
672 
673   public String getKeyString() {
674     return Bytes.toStringBinary(getBuffer(), getKeyOffset(), getKeyLength());
675   }
676 
677   /**
678    * @return Length of key portion.
679    */
680   private int keyLength = 0;
681 
682   public int getKeyLength() {
683     if (keyLength == 0) {
684       keyLength = Bytes.toInt(this.bytes, this.offset);
685     }
686     return keyLength;
687   }
688 
689   /**
690    * @return Value offset
691    */
692   public int getValueOffset() {
693     return getKeyOffset() + getKeyLength();
694   }
695 
696   /**
697    * @return Value length
698    */
699   public int getValueLength() {
700     return Bytes.toInt(this.bytes, this.offset + Bytes.SIZEOF_INT);
701   }
702 
703   /**
704    * @return Row offset
705    */
706   public int getRowOffset() {
707     return getKeyOffset() + Bytes.SIZEOF_SHORT;
708   }
709 
710   /**
711    * @return Row length
712    */
713   public short getRowLength() {
714     return Bytes.toShort(this.bytes, getKeyOffset());
715   }
716 
717   /**
718    * @return Family offset
719    */
720   public int getFamilyOffset() {
721     return getFamilyOffset(getRowLength());
722   }
723 
724   /**
725    * @return Family offset
726    */
727   public int getFamilyOffset(int rlength) {
728     return this.offset + ROW_OFFSET + Bytes.SIZEOF_SHORT + rlength + Bytes.SIZEOF_BYTE;
729   }
730 
731   /**
732    * @return Family length
733    */
734   public byte getFamilyLength() {
735     return getFamilyLength(getFamilyOffset());
736   }
737 
738   /**
739    * @return Family length
740    */
741   public byte getFamilyLength(int foffset) {
742     return this.bytes[foffset-1];
743   }
744 
745   /**
746    * @return Qualifier offset
747    */
748   public int getQualifierOffset() {
749     return getQualifierOffset(getFamilyOffset());
750   }
751 
752   /**
753    * @return Qualifier offset
754    */
755   public int getQualifierOffset(int foffset) {
756     return foffset + getFamilyLength(foffset);
757   }
758 
759   /**
760    * @return Qualifier length
761    */
762   public int getQualifierLength() {
763     return getQualifierLength(getRowLength(),getFamilyLength());
764   }
765 
766   /**
767    * @return Qualifier length
768    */
769   public int getQualifierLength(int rlength, int flength) {
770     return getKeyLength() -
771       (KEY_INFRASTRUCTURE_SIZE + rlength + flength);
772   }
773 
774   /**
775    * @return Column (family + qualifier) length
776    */
777   public int getTotalColumnLength() {
778     int rlength = getRowLength();
779     int foffset = getFamilyOffset(rlength);
780     return getTotalColumnLength(rlength,foffset);
781   }
782 
783   /**
784    * @return Column (family + qualifier) length
785    */
786   public int getTotalColumnLength(int rlength, int foffset) {
787     int flength = getFamilyLength(foffset);
788     int qlength = getQualifierLength(rlength,flength);
789     return flength + qlength;
790   }
791 
792   /**
793    * @return Timestamp offset
794    */
795   public int getTimestampOffset() {
796     return getTimestampOffset(getKeyLength());
797   }
798 
799   /**
800    * @param keylength Pass if you have it to save on a int creation.
801    * @return Timestamp offset
802    */
803   public int getTimestampOffset(final int keylength) {
804     return getKeyOffset() + keylength - TIMESTAMP_TYPE_SIZE;
805   }
806 
807   /**
808    * @return True if this KeyValue has a LATEST_TIMESTAMP timestamp.
809    */
810   public boolean isLatestTimestamp() {
811     return  Bytes.compareTo(getBuffer(), getTimestampOffset(), Bytes.SIZEOF_LONG,
812       HConstants.LATEST_TIMESTAMP_BYTES, 0, Bytes.SIZEOF_LONG) == 0;
813   }
814 
815   /**
816    * @param now Time to set into <code>this</code> IFF timestamp ==
817    * {@link HConstants#LATEST_TIMESTAMP} (else, its a noop).
818    * @return True is we modified this.
819    */
820   public boolean updateLatestStamp(final byte [] now) {
821     if (this.isLatestTimestamp()) {
822       int tsOffset = getTimestampOffset();
823       System.arraycopy(now, 0, this.bytes, tsOffset, Bytes.SIZEOF_LONG);
824       return true;
825     }
826     return false;
827   }
828 
829   //---------------------------------------------------------------------------
830   //
831   //  Methods that return copies of fields
832   //
833   //---------------------------------------------------------------------------
834 
835   /**
836    * Do not use unless you have to.  Used internally for compacting and testing.
837    *
838    * Use {@link #getRow()}, {@link #getFamily()}, {@link #getQualifier()}, and
839    * {@link #getValue()} if accessing a KeyValue client-side.
840    * @return Copy of the key portion only.
841    */
842   public byte [] getKey() {
843     int keylength = getKeyLength();
844     byte [] key = new byte[keylength];
845     System.arraycopy(getBuffer(), getKeyOffset(), key, 0, keylength);
846     return key;
847   }
848 
849   /**
850    * Returns value in a new byte array.
851    * Primarily for use client-side. If server-side, use
852    * {@link #getBuffer()} with appropriate offsets and lengths instead to
853    * save on allocations.
854    * @return Value in a new byte array.
855    */
856   public byte [] getValue() {
857     int o = getValueOffset();
858     int l = getValueLength();
859     byte [] result = new byte[l];
860     System.arraycopy(getBuffer(), o, result, 0, l);
861     return result;
862   }
863 
864   /**
865    * Primarily for use client-side.  Returns the row of this KeyValue in a new
866    * byte array.<p>
867    *
868    * If server-side, use {@link #getBuffer()} with appropriate offsets and
869    * lengths instead.
870    * @return Row in a new byte array.
871    */
872   public byte [] getRow() {
873     if (rowCache == null) {
874       int o = getRowOffset();
875       short l = getRowLength();
876       rowCache = new byte[l];
877       System.arraycopy(getBuffer(), o, rowCache, 0, l);
878     }
879     return rowCache;
880   }
881 
882   /**
883    *
884    * @return Timestamp
885    */
886   private long timestampCache = -1;
887   public long getTimestamp() {
888     if (timestampCache == -1) {
889       timestampCache = getTimestamp(getKeyLength());
890     }
891     return timestampCache;
892   }
893 
894   /**
895    * @param keylength Pass if you have it to save on a int creation.
896    * @return Timestamp
897    */
898   long getTimestamp(final int keylength) {
899     int tsOffset = getTimestampOffset(keylength);
900     return Bytes.toLong(this.bytes, tsOffset);
901   }
902 
903   /**
904    * @return Type of this KeyValue.
905    */
906   public byte getType() {
907     return getType(getKeyLength());
908   }
909 
910   /**
911    * @param keylength Pass if you have it to save on a int creation.
912    * @return Type of this KeyValue.
913    */
914   byte getType(final int keylength) {
915     return this.bytes[this.offset + keylength - 1 + ROW_OFFSET];
916   }
917 
918   /**
919    * @return True if a delete type, a {@link KeyValue.Type#Delete} or
920    * a {KeyValue.Type#DeleteFamily} or a {@link KeyValue.Type#DeleteColumn}
921    * KeyValue type.
922    */
923   public boolean isDelete() {
924     int t = getType();
925     return Type.Delete.getCode() <= t && t <= Type.DeleteFamily.getCode();
926   }
927 
928   /**
929    * @return True if this KV is a {@link KeyValue.Type#Delete} type.
930    */
931   public boolean isDeleteType() {
932     return getType() == Type.Delete.getCode();
933   }
934 
935   /**
936    * @return True if this KV is a delete family type.
937    */
938   public boolean isDeleteFamily() {
939     return getType() == Type.DeleteFamily.getCode();
940   }
941 
942   /**
943    *
944    * @return True if this KV is a delete family or column type.
945    */
946   public boolean isDeleteColumnOrFamily() {
947     int t = getType();
948     return t == Type.DeleteColumn.getCode() || t == Type.DeleteFamily.getCode();
949   }
950 
951   /**
952    * Primarily for use client-side.  Returns the family of this KeyValue in a
953    * new byte array.<p>
954    *
955    * If server-side, use {@link #getBuffer()} with appropriate offsets and
956    * lengths instead.
957    * @return Returns family. Makes a copy.
958    */
959   public byte [] getFamily() {
960     int o = getFamilyOffset();
961     int l = getFamilyLength(o);
962     byte [] result = new byte[l];
963     System.arraycopy(this.bytes, o, result, 0, l);
964     return result;
965   }
966 
967   /**
968    * Primarily for use client-side.  Returns the column qualifier of this
969    * KeyValue in a new byte array.<p>
970    *
971    * If server-side, use {@link #getBuffer()} with appropriate offsets and
972    * lengths instead.
973    * Use {@link #getBuffer()} with appropriate offsets and lengths instead.
974    * @return Returns qualifier. Makes a copy.
975    */
976   public byte [] getQualifier() {
977     int o = getQualifierOffset();
978     int l = getQualifierLength();
979     byte [] result = new byte[l];
980     System.arraycopy(this.bytes, o, result, 0, l);
981     return result;
982   }
983 
984   //---------------------------------------------------------------------------
985   //
986   //  KeyValue splitter
987   //
988   //---------------------------------------------------------------------------
989 
990   /**
991    * Utility class that splits a KeyValue buffer into separate byte arrays.
992    * <p>
993    * Should get rid of this if we can, but is very useful for debugging.
994    */
995   public static class SplitKeyValue {
996     private byte [][] split;
997     SplitKeyValue() {
998       this.split = new byte[6][];
999     }
1000     public void setRow(byte [] value) { this.split[0] = value; }
1001     public void setFamily(byte [] value) { this.split[1] = value; }
1002     public void setQualifier(byte [] value) { this.split[2] = value; }
1003     public void setTimestamp(byte [] value) { this.split[3] = value; }
1004     public void setType(byte [] value) { this.split[4] = value; }
1005     public void setValue(byte [] value) { this.split[5] = value; }
1006     public byte [] getRow() { return this.split[0]; }
1007     public byte [] getFamily() { return this.split[1]; }
1008     public byte [] getQualifier() { return this.split[2]; }
1009     public byte [] getTimestamp() { return this.split[3]; }
1010     public byte [] getType() { return this.split[4]; }
1011     public byte [] getValue() { return this.split[5]; }
1012   }
1013 
1014   public SplitKeyValue split() {
1015     SplitKeyValue split = new SplitKeyValue();
1016     int splitOffset = this.offset;
1017     int keyLen = Bytes.toInt(bytes, splitOffset);
1018     splitOffset += Bytes.SIZEOF_INT;
1019     int valLen = Bytes.toInt(bytes, splitOffset);
1020     splitOffset += Bytes.SIZEOF_INT;
1021     short rowLen = Bytes.toShort(bytes, splitOffset);
1022     splitOffset += Bytes.SIZEOF_SHORT;
1023     byte [] row = new byte[rowLen];
1024     System.arraycopy(bytes, splitOffset, row, 0, rowLen);
1025     splitOffset += rowLen;
1026     split.setRow(row);
1027     byte famLen = bytes[splitOffset];
1028     splitOffset += Bytes.SIZEOF_BYTE;
1029     byte [] family = new byte[famLen];
1030     System.arraycopy(bytes, splitOffset, family, 0, famLen);
1031     splitOffset += famLen;
1032     split.setFamily(family);
1033     int colLen = keyLen -
1034       (rowLen + famLen + Bytes.SIZEOF_SHORT + Bytes.SIZEOF_BYTE +
1035       Bytes.SIZEOF_LONG + Bytes.SIZEOF_BYTE);
1036     byte [] qualifier = new byte[colLen];
1037     System.arraycopy(bytes, splitOffset, qualifier, 0, colLen);
1038     splitOffset += colLen;
1039     split.setQualifier(qualifier);
1040     byte [] timestamp = new byte[Bytes.SIZEOF_LONG];
1041     System.arraycopy(bytes, splitOffset, timestamp, 0, Bytes.SIZEOF_LONG);
1042     splitOffset += Bytes.SIZEOF_LONG;
1043     split.setTimestamp(timestamp);
1044     byte [] type = new byte[1];
1045     type[0] = bytes[splitOffset];
1046     splitOffset += Bytes.SIZEOF_BYTE;
1047     split.setType(type);
1048     byte [] value = new byte[valLen];
1049     System.arraycopy(bytes, splitOffset, value, 0, valLen);
1050     split.setValue(value);
1051     return split;
1052   }
1053 
1054   //---------------------------------------------------------------------------
1055   //
1056   //  Compare specified fields against those contained in this KeyValue
1057   //
1058   //---------------------------------------------------------------------------
1059 
1060   /**
1061    * @param family
1062    * @return True if matching families.
1063    */
1064   public boolean matchingFamily(final byte [] family) {
1065     return matchingFamily(family, 0, family.length);
1066   }
1067 
1068   public boolean matchingFamily(final byte[] family, int offset, int length) {
1069     if (this.length == 0 || this.bytes.length == 0) {
1070       return false;
1071     }
1072     return Bytes.compareTo(family, offset, length,
1073         this.bytes, getFamilyOffset(), getFamilyLength()) == 0;
1074   }
1075 
1076   public boolean matchingFamily(final KeyValue other) {
1077     return matchingFamily(other.getBuffer(), other.getFamilyOffset(),
1078         other.getFamilyLength());
1079   }
1080 
1081   /**
1082    * @param qualifier
1083    * @return True if matching qualifiers.
1084    */
1085   public boolean matchingQualifier(final byte [] qualifier) {
1086     return matchingQualifier(qualifier, 0, qualifier.length);
1087   }
1088 
1089   public boolean matchingQualifier(final byte [] qualifier, int offset, int length) {
1090     return Bytes.compareTo(qualifier, offset, length,
1091         this.bytes, getQualifierOffset(), getQualifierLength()) == 0;
1092   }
1093 
1094   public boolean matchingQualifier(final KeyValue other) {
1095     return matchingQualifier(other.getBuffer(), other.getQualifierOffset(),
1096         other.getQualifierLength());
1097   }
1098 
1099   public boolean matchingRow(final byte [] row) {
1100     return matchingRow(row, 0, row.length);
1101   }
1102 
1103   public boolean matchingRow(final byte[] row, int offset, int length) {
1104     return Bytes.compareTo(row, offset, length,
1105         this.bytes, getRowOffset(), getRowLength()) == 0;
1106   }
1107 
1108   public boolean matchingRow(KeyValue other) {
1109     return matchingRow(other.getBuffer(), other.getRowOffset(),
1110         other.getRowLength());
1111   }
1112 
1113   /**
1114    * @param column Column minus its delimiter
1115    * @return True if column matches.
1116    */
1117   public boolean matchingColumnNoDelimiter(final byte [] column) {
1118     int rl = getRowLength();
1119     int o = getFamilyOffset(rl);
1120     int fl = getFamilyLength(o);
1121     int l = fl + getQualifierLength(rl,fl);
1122     return Bytes.compareTo(column, 0, column.length, this.bytes, o, l) == 0;
1123   }
1124 
1125   /**
1126    *
1127    * @param family column family
1128    * @param qualifier column qualifier
1129    * @return True if column matches
1130    */
1131   public boolean matchingColumn(final byte[] family, final byte[] qualifier) {
1132     int rl = getRowLength();
1133     int o = getFamilyOffset(rl);
1134     int fl = getFamilyLength(o);
1135     int ql = getQualifierLength(rl,fl);
1136     if (Bytes.compareTo(family, 0, family.length, this.bytes, o, family.length)
1137         != 0) {
1138       return false;
1139     }
1140     if (qualifier == null || qualifier.length == 0) {
1141       if (ql == 0) {
1142         return true;
1143       }
1144       return false;
1145     }
1146     return Bytes.compareTo(qualifier, 0, qualifier.length,
1147         this.bytes, o + fl, ql) == 0;
1148   }
1149 
1150   /**
1151    * @param left
1152    * @param loffset
1153    * @param llength
1154    * @param lfamilylength Offset of family delimiter in left column.
1155    * @param right
1156    * @param roffset
1157    * @param rlength
1158    * @param rfamilylength Offset of family delimiter in right column.
1159    * @return The result of the comparison.
1160    */
1161   static int compareColumns(final byte [] left, final int loffset,
1162       final int llength, final int lfamilylength,
1163       final byte [] right, final int roffset, final int rlength,
1164       final int rfamilylength) {
1165     // Compare family portion first.
1166     int diff = Bytes.compareTo(left, loffset, lfamilylength,
1167       right, roffset, rfamilylength);
1168     if (diff != 0) {
1169       return diff;
1170     }
1171     // Compare qualifier portion
1172     return Bytes.compareTo(left, loffset + lfamilylength,
1173       llength - lfamilylength,
1174       right, roffset + rfamilylength, rlength - rfamilylength);
1175   }
1176 
1177   /**
1178    * @return True if non-null row and column.
1179    */
1180   public boolean nonNullRowAndColumn() {
1181     return getRowLength() > 0 && !isEmptyColumn();
1182   }
1183 
1184   /**
1185    * @return True if column is empty.
1186    */
1187   public boolean isEmptyColumn() {
1188     return getQualifierLength() == 0;
1189   }
1190 
1191   /**
1192    * Splits a column in family:qualifier form into separate byte arrays.
1193    * <p>
1194    * Not recommend to be used as this is old-style API.
1195    * @param c  The column.
1196    * @return The parsed column.
1197    */
1198   public static byte [][] parseColumn(byte [] c) {
1199     final int index = getDelimiter(c, 0, c.length, COLUMN_FAMILY_DELIMITER);
1200     if (index == -1) {
1201       // If no delimiter, return array of size 1
1202       return new byte [][] { c };
1203     } else if(index == c.length - 1) {
1204       // Only a family, return array size 1
1205       byte [] family = new byte[c.length-1];
1206       System.arraycopy(c, 0, family, 0, family.length);
1207       return new byte [][] { family };
1208     }
1209     // Family and column, return array size 2
1210     final byte [][] result = new byte [2][];
1211     result[0] = new byte [index];
1212     System.arraycopy(c, 0, result[0], 0, index);
1213     final int len = c.length - (index + 1);
1214     result[1] = new byte[len];
1215     System.arraycopy(c, index + 1 /*Skip delimiter*/, result[1], 0,
1216       len);
1217     return result;
1218   }
1219 
1220   /**
1221    * Makes a column in family:qualifier form from separate byte arrays.
1222    * <p>
1223    * Not recommended for usage as this is old-style API.
1224    * @param family
1225    * @param qualifier
1226    * @return family:qualifier
1227    */
1228   public static byte [] makeColumn(byte [] family, byte [] qualifier) {
1229     return Bytes.add(family, COLUMN_FAMILY_DELIM_ARRAY, qualifier);
1230   }
1231 
1232   /**
1233    * @param b
1234    * @return Index of the family-qualifier colon delimiter character in passed
1235    * buffer.
1236    */
1237   public static int getFamilyDelimiterIndex(final byte [] b, final int offset,
1238       final int length) {
1239     return getRequiredDelimiter(b, offset, length, COLUMN_FAMILY_DELIMITER);
1240   }
1241 
1242   private static int getRequiredDelimiter(final byte [] b,
1243       final int offset, final int length, final int delimiter) {
1244     int index = getDelimiter(b, offset, length, delimiter);
1245     if (index < 0) {
1246       throw new IllegalArgumentException("No " + (char)delimiter + " in <" +
1247         Bytes.toString(b) + ">" + ", length=" + length + ", offset=" + offset);
1248     }
1249     return index;
1250   }
1251 
1252   static int getRequiredDelimiterInReverse(final byte [] b,
1253       final int offset, final int length, final int delimiter) {
1254     int index = getDelimiterInReverse(b, offset, length, delimiter);
1255     if (index < 0) {
1256       throw new IllegalArgumentException("No " + delimiter + " in <" +
1257         Bytes.toString(b) + ">" + ", length=" + length + ", offset=" + offset);
1258     }
1259     return index;
1260   }
1261 
1262   /**
1263    * @param b
1264    * @param delimiter
1265    * @return Index of delimiter having started from start of <code>b</code>
1266    * moving rightward.
1267    */
1268   public static int getDelimiter(final byte [] b, int offset, final int length,
1269       final int delimiter) {
1270     if (b == null) {
1271       throw new NullPointerException();
1272     }
1273     int result = -1;
1274     for (int i = offset; i < length + offset; i++) {
1275       if (b[i] == delimiter) {
1276         result = i;
1277         break;
1278       }
1279     }
1280     return result;
1281   }
1282 
1283   /**
1284    * Find index of passed delimiter walking from end of buffer backwards.
1285    * @param b
1286    * @param delimiter
1287    * @return Index of delimiter
1288    */
1289   public static int getDelimiterInReverse(final byte [] b, final int offset,
1290       final int length, final int delimiter) {
1291     if (b == null) {
1292       throw new NullPointerException();
1293     }
1294     int result = -1;
1295     for (int i = (offset + length) - 1; i >= offset; i--) {
1296       if (b[i] == delimiter) {
1297         result = i;
1298         break;
1299       }
1300     }
1301     return result;
1302   }
1303 
1304   /**
1305    * A {@link KVComparator} for <code>-ROOT-</code> catalog table
1306    * {@link KeyValue}s.
1307    */
1308   public static class RootComparator extends MetaComparator {
1309     private final KeyComparator rawcomparator = new RootKeyComparator();
1310 
1311     public KeyComparator getRawComparator() {
1312       return this.rawcomparator;
1313     }
1314 
1315     @Override
1316     protected Object clone() throws CloneNotSupportedException {
1317       return new RootComparator();
1318     }
1319   }
1320 
1321   /**
1322    * A {@link KVComparator} for <code>.META.</code> catalog table
1323    * {@link KeyValue}s.
1324    */
1325   public static class MetaComparator extends KVComparator {
1326     private final KeyComparator rawcomparator = new MetaKeyComparator();
1327 
1328     public KeyComparator getRawComparator() {
1329       return this.rawcomparator;
1330     }
1331 
1332     @Override
1333     protected Object clone() throws CloneNotSupportedException {
1334       return new MetaComparator();
1335     }
1336   }
1337 
1338   /**
1339    * Compare KeyValues.  When we compare KeyValues, we only compare the Key
1340    * portion.  This means two KeyValues with same Key but different Values are
1341    * considered the same as far as this Comparator is concerned.
1342    * Hosts a {@link KeyComparator}.
1343    */
1344   public static class KVComparator implements java.util.Comparator<KeyValue> {
1345     private final KeyComparator rawcomparator = new KeyComparator();
1346 
1347     /**
1348      * @return RawComparator that can compare the Key portion of a KeyValue.
1349      * Used in hfile where indices are the Key portion of a KeyValue.
1350      */
1351     public KeyComparator getRawComparator() {
1352       return this.rawcomparator;
1353     }
1354 
1355     public int compare(final KeyValue left, final KeyValue right) {
1356       int ret = getRawComparator().compare(left.getBuffer(),
1357           left.getOffset() + ROW_OFFSET, left.getKeyLength(),
1358           right.getBuffer(), right.getOffset() + ROW_OFFSET,
1359           right.getKeyLength());
1360       if (ret != 0) return ret;
1361       // Negate this comparison so later edits show up first
1362       return -Longs.compare(left.getMemstoreTS(), right.getMemstoreTS());
1363     }
1364 
1365     public int compareTimestamps(final KeyValue left, final KeyValue right) {
1366       return compareTimestamps(left, left.getKeyLength(), right,
1367         right.getKeyLength());
1368     }
1369 
1370     int compareTimestamps(final KeyValue left, final int lkeylength,
1371         final KeyValue right, final int rkeylength) {
1372       // Compare timestamps
1373       long ltimestamp = left.getTimestamp(lkeylength);
1374       long rtimestamp = right.getTimestamp(rkeylength);
1375       return getRawComparator().compareTimestamps(ltimestamp, rtimestamp);
1376     }
1377 
1378     /**
1379      * @param left
1380      * @param right
1381      * @return Result comparing rows.
1382      */
1383     public int compareRows(final KeyValue left, final KeyValue right) {
1384       return compareRows(left, left.getRowLength(), right,
1385           right.getRowLength());
1386     }
1387 
1388     /**
1389      * @param left
1390      * @param lrowlength Length of left row.
1391      * @param right
1392      * @param rrowlength Length of right row.
1393      * @return Result comparing rows.
1394      */
1395     public int compareRows(final KeyValue left, final short lrowlength,
1396         final KeyValue right, final short rrowlength) {
1397       return getRawComparator().compareRows(left.getBuffer(),
1398           left.getRowOffset(), lrowlength,
1399         right.getBuffer(), right.getRowOffset(), rrowlength);
1400     }
1401 
1402     /**
1403      * @param left
1404      * @param row - row key (arbitrary byte array)
1405      * @return RawComparator
1406      */
1407     public int compareRows(final KeyValue left, final byte [] row) {
1408       return getRawComparator().compareRows(left.getBuffer(),
1409           left.getRowOffset(), left.getRowLength(), row, 0, row.length);
1410     }
1411 
1412     public int compareRows(byte [] left, int loffset, int llength,
1413         byte [] right, int roffset, int rlength) {
1414       return getRawComparator().compareRows(left, loffset, llength,
1415         right, roffset, rlength);
1416     }
1417 
1418     public int compareColumns(final KeyValue left, final byte [] right,
1419         final int roffset, final int rlength, final int rfamilyoffset) {
1420       int offset = left.getFamilyOffset();
1421       int length = left.getFamilyLength() + left.getQualifierLength();
1422       return getRawComparator().compareColumns(left.getBuffer(), offset, length,
1423         left.getFamilyLength(offset),
1424         right, roffset, rlength, rfamilyoffset);
1425     }
1426 
1427     int compareColumns(final KeyValue left, final short lrowlength,
1428         final KeyValue right, final short rrowlength) {
1429       int lfoffset = left.getFamilyOffset(lrowlength);
1430       int rfoffset = right.getFamilyOffset(rrowlength);
1431       int lclength = left.getTotalColumnLength(lrowlength,lfoffset);
1432       int rclength = right.getTotalColumnLength(rrowlength, rfoffset);
1433       int lfamilylength = left.getFamilyLength(lfoffset);
1434       int rfamilylength = right.getFamilyLength(rfoffset);
1435       return getRawComparator().compareColumns(left.getBuffer(), lfoffset,
1436           lclength, lfamilylength,
1437         right.getBuffer(), rfoffset, rclength, rfamilylength);
1438     }
1439 
1440     /**
1441      * Compares the row and column of two keyvalues for equality
1442      * @param left
1443      * @param right
1444      * @return True if same row and column.
1445      */
1446     public boolean matchingRowColumn(final KeyValue left,
1447         final KeyValue right) {
1448       short lrowlength = left.getRowLength();
1449       short rrowlength = right.getRowLength();
1450       // TsOffset = end of column data. just comparing Row+CF length of each
1451       return left.getTimestampOffset() == right.getTimestampOffset() &&
1452         matchingRows(left, lrowlength, right, rrowlength) &&
1453         compareColumns(left, lrowlength, right, rrowlength) == 0;
1454     }
1455 
1456     /**
1457      * @param left
1458      * @param right
1459      * @return True if rows match.
1460      */
1461     public boolean matchingRows(final KeyValue left, final byte [] right) {
1462       return compareRows(left, right) == 0;
1463     }
1464 
1465     /**
1466      * Compares the row of two keyvalues for equality
1467      * @param left
1468      * @param right
1469      * @return True if rows match.
1470      */
1471     public boolean matchingRows(final KeyValue left, final KeyValue right) {
1472       short lrowlength = left.getRowLength();
1473       short rrowlength = right.getRowLength();
1474       return matchingRows(left, lrowlength, right, rrowlength);
1475     }
1476 
1477     /**
1478      * @param left
1479      * @param lrowlength
1480      * @param right
1481      * @param rrowlength
1482      * @return True if rows match.
1483      */
1484     public boolean matchingRows(final KeyValue left, final short lrowlength,
1485         final KeyValue right, final short rrowlength) {
1486       return lrowlength == rrowlength &&
1487         compareRows(left, lrowlength, right, rrowlength) == 0;
1488     }
1489 
1490     public boolean matchingRows(final byte [] left, final int loffset,
1491         final int llength,
1492         final byte [] right, final int roffset, final int rlength) {
1493       int compare = compareRows(left, loffset, llength,
1494           right, roffset, rlength);
1495       if (compare != 0) {
1496         return false;
1497       }
1498       return true;
1499     }
1500 
1501     /**
1502      * Compares the row and timestamp of two keys
1503      * Was called matchesWithoutColumn in HStoreKey.
1504      * @param right Key to compare against.
1505      * @return True if same row and timestamp is greater than the timestamp in
1506      * <code>right</code>
1507      */
1508     public boolean matchingRowsGreaterTimestamp(final KeyValue left,
1509         final KeyValue right) {
1510       short lrowlength = left.getRowLength();
1511       short rrowlength = right.getRowLength();
1512       if (!matchingRows(left, lrowlength, right, rrowlength)) {
1513         return false;
1514       }
1515       return left.getTimestamp() >= right.getTimestamp();
1516     }
1517 
1518     @Override
1519     protected Object clone() throws CloneNotSupportedException {
1520       return new KVComparator();
1521     }
1522 
1523     /**
1524      * @return Comparator that ignores timestamps; useful counting versions.
1525      */
1526     public KVComparator getComparatorIgnoringTimestamps() {
1527       KVComparator c = null;
1528       try {
1529         c = (KVComparator)this.clone();
1530         c.getRawComparator().ignoreTimestamp = true;
1531       } catch (CloneNotSupportedException e) {
1532         LOG.error("Not supported", e);
1533       }
1534       return c;
1535     }
1536 
1537     /**
1538      * @return Comparator that ignores key type; useful checking deletes
1539      */
1540     public KVComparator getComparatorIgnoringType() {
1541       KVComparator c = null;
1542       try {
1543         c = (KVComparator)this.clone();
1544         c.getRawComparator().ignoreType = true;
1545       } catch (CloneNotSupportedException e) {
1546         LOG.error("Not supported", e);
1547       }
1548       return c;
1549     }
1550   }
1551 
1552   /**
1553    * Creates a KeyValue that is last on the specified row id. That is,
1554    * every other possible KeyValue for the given row would compareTo()
1555    * less than the result of this call.
1556    * @param row row key
1557    * @return Last possible KeyValue on passed <code>row</code>
1558    */
1559   public static KeyValue createLastOnRow(final byte[] row) {
1560     return new KeyValue(row, null, null, HConstants.LATEST_TIMESTAMP, Type.Minimum);
1561   }
1562 
1563   /**
1564    * Create a KeyValue that is smaller than all other possible KeyValues
1565    * for the given row. That is any (valid) KeyValue on 'row' would sort
1566    * _after_ the result.
1567    *
1568    * @param row - row key (arbitrary byte array)
1569    * @return First possible KeyValue on passed <code>row</code>
1570    */
1571   public static KeyValue createFirstOnRow(final byte [] row) {
1572     return createFirstOnRow(row, HConstants.LATEST_TIMESTAMP);
1573   }
1574 
1575   /**
1576    * Creates a KeyValue that is smaller than all other KeyValues that
1577    * are older than the passed timestamp.
1578    * @param row - row key (arbitrary byte array)
1579    * @param ts - timestamp
1580    * @return First possible key on passed <code>row</code> and timestamp.
1581    */
1582   public static KeyValue createFirstOnRow(final byte [] row,
1583       final long ts) {
1584     return new KeyValue(row, null, null, ts, Type.Maximum);
1585   }
1586 
1587   /**
1588    * @param row - row key (arbitrary byte array)
1589    * @param c column - {@link #parseColumn(byte[])} is called to split
1590    * the column.
1591    * @param ts - timestamp
1592    * @return First possible key on passed <code>row</code>, column and timestamp
1593    * @deprecated
1594    */
1595   public static KeyValue createFirstOnRow(final byte [] row, final byte [] c,
1596       final long ts) {
1597     byte [][] split = parseColumn(c);
1598     return new KeyValue(row, split[0], split[1], ts, Type.Maximum);
1599   }
1600 
1601   /**
1602    * Create a KeyValue for the specified row, family and qualifier that would be
1603    * smaller than all other possible KeyValues that have the same row,family,qualifier.
1604    * Used for seeking.
1605    * @param row - row key (arbitrary byte array)
1606    * @param family - family name
1607    * @param qualifier - column qualifier
1608    * @return First possible key on passed <code>row</code>, and column.
1609    */
1610   public static KeyValue createFirstOnRow(final byte [] row, final byte [] family,
1611       final byte [] qualifier) {
1612     return new KeyValue(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum);
1613   }
1614 
1615   /**
1616    * @param row - row key (arbitrary byte array)
1617    * @param f - family name
1618    * @param q - column qualifier
1619    * @param ts - timestamp
1620    * @return First possible key on passed <code>row</code>, column and timestamp
1621    */
1622   public static KeyValue createFirstOnRow(final byte [] row, final byte [] f,
1623       final byte [] q, final long ts) {
1624     return new KeyValue(row, f, q, ts, Type.Maximum);
1625   }
1626 
1627   /**
1628    * Create a KeyValue for the specified row, family and qualifier that would be
1629    * smaller than all other possible KeyValues that have the same row,
1630    * family, qualifier.
1631    * Used for seeking.
1632    * @param row row key
1633    * @param roffset row offset
1634    * @param rlength row length
1635    * @param family family name
1636    * @param foffset family offset
1637    * @param flength family length
1638    * @param qualifier column qualifier
1639    * @param qoffset qualifier offset
1640    * @param qlength qualifier length
1641    * @return First possible key on passed Row, Family, Qualifier.
1642    */
1643   public static KeyValue createFirstOnRow(final byte [] row,
1644       final int roffset, final int rlength, final byte [] family,
1645       final int foffset, final int flength, final byte [] qualifier,
1646       final int qoffset, final int qlength) {
1647     return new KeyValue(row, roffset, rlength, family,
1648         foffset, flength, qualifier, qoffset, qlength,
1649         HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0);
1650   }
1651 
1652   /**
1653    * @param b
1654    * @return A KeyValue made of a byte array that holds the key-only part.
1655    * Needed to convert hfile index members to KeyValues.
1656    */
1657   public static KeyValue createKeyValueFromKey(final byte [] b) {
1658     return createKeyValueFromKey(b, 0, b.length);
1659   }
1660 
1661   /**
1662    * @param bb
1663    * @return A KeyValue made of a byte buffer that holds the key-only part.
1664    * Needed to convert hfile index members to KeyValues.
1665    */
1666   public static KeyValue createKeyValueFromKey(final ByteBuffer bb) {
1667     return createKeyValueFromKey(bb.array(), bb.arrayOffset(), bb.limit());
1668   }
1669 
1670   /**
1671    * @param b
1672    * @param o
1673    * @param l
1674    * @return A KeyValue made of a byte array that holds the key-only part.
1675    * Needed to convert hfile index members to KeyValues.
1676    */
1677   public static KeyValue createKeyValueFromKey(final byte [] b, final int o,
1678       final int l) {
1679     byte [] newb = new byte[b.length + ROW_OFFSET];
1680     System.arraycopy(b, o, newb, ROW_OFFSET, l);
1681     Bytes.putInt(newb, 0, b.length);
1682     Bytes.putInt(newb, Bytes.SIZEOF_INT, 0);
1683     return new KeyValue(newb);
1684   }
1685 
1686   /**
1687    * Compare key portion of a {@link KeyValue} for keys in <code>-ROOT-<code>
1688    * table.
1689    */
1690   public static class RootKeyComparator extends MetaKeyComparator {
1691     public int compareRows(byte [] left, int loffset, int llength,
1692         byte [] right, int roffset, int rlength) {
1693       // Rows look like this: .META.,ROW_FROM_META,RID
1694       //        LOG.info("ROOT " + Bytes.toString(left, loffset, llength) +
1695       //          "---" + Bytes.toString(right, roffset, rlength));
1696       final int metalength = 7; // '.META.' length
1697       int lmetaOffsetPlusDelimiter = loffset + metalength;
1698       int leftFarDelimiter = getDelimiterInReverse(left,
1699           lmetaOffsetPlusDelimiter,
1700           llength - metalength, HRegionInfo.DELIMITER);
1701       int rmetaOffsetPlusDelimiter = roffset + metalength;
1702       int rightFarDelimiter = getDelimiterInReverse(right,
1703           rmetaOffsetPlusDelimiter, rlength - metalength,
1704           HRegionInfo.DELIMITER);
1705       if (leftFarDelimiter < 0 && rightFarDelimiter >= 0) {
1706         // Nothing between .META. and regionid.  Its first key.
1707         return -1;
1708       } else if (rightFarDelimiter < 0 && leftFarDelimiter >= 0) {
1709         return 1;
1710       } else if (leftFarDelimiter < 0 && rightFarDelimiter < 0) {
1711         return 0;
1712       }
1713       int result = super.compareRows(left, lmetaOffsetPlusDelimiter,
1714           leftFarDelimiter - lmetaOffsetPlusDelimiter,
1715           right, rmetaOffsetPlusDelimiter,
1716           rightFarDelimiter - rmetaOffsetPlusDelimiter);
1717       if (result != 0) {
1718         return result;
1719       }
1720       // Compare last part of row, the rowid.
1721       leftFarDelimiter++;
1722       rightFarDelimiter++;
1723       result = compareRowid(left, leftFarDelimiter,
1724           llength - (leftFarDelimiter - loffset),
1725           right, rightFarDelimiter, rlength - (rightFarDelimiter - roffset));
1726       return result;
1727     }
1728   }
1729 
1730   /**
1731    * Comparator that compares row component only of a KeyValue.
1732    */
1733   public static class RowComparator implements Comparator<KeyValue> {
1734     final KVComparator comparator;
1735 
1736     public RowComparator(final KVComparator c) {
1737       this.comparator = c;
1738     }
1739 
1740     public int compare(KeyValue left, KeyValue right) {
1741       return comparator.compareRows(left, right);
1742     }
1743   }
1744 
1745   /**
1746    * Compare key portion of a {@link KeyValue} for keys in <code>.META.</code>
1747    * table.
1748    */
1749   public static class MetaKeyComparator extends KeyComparator {
1750     public int compareRows(byte [] left, int loffset, int llength,
1751         byte [] right, int roffset, int rlength) {
1752       //        LOG.info("META " + Bytes.toString(left, loffset, llength) +
1753       //          "---" + Bytes.toString(right, roffset, rlength));
1754       int leftDelimiter = getDelimiter(left, loffset, llength,
1755           HRegionInfo.DELIMITER);
1756       int rightDelimiter = getDelimiter(right, roffset, rlength,
1757           HRegionInfo.DELIMITER);
1758       if (leftDelimiter < 0 && rightDelimiter >= 0) {
1759         // Nothing between .META. and regionid.  Its first key.
1760         return -1;
1761       } else if (rightDelimiter < 0 && leftDelimiter >= 0) {
1762         return 1;
1763       } else if (leftDelimiter < 0 && rightDelimiter < 0) {
1764         return 0;
1765       }
1766       // Compare up to the delimiter
1767       int result = Bytes.compareTo(left, loffset, leftDelimiter - loffset,
1768           right, roffset, rightDelimiter - roffset);
1769       if (result != 0) {
1770         return result;
1771       }
1772       // Compare middle bit of the row.
1773       // Move past delimiter
1774       leftDelimiter++;
1775       rightDelimiter++;
1776       int leftFarDelimiter = getRequiredDelimiterInReverse(left, leftDelimiter,
1777           llength - (leftDelimiter - loffset), HRegionInfo.DELIMITER);
1778       int rightFarDelimiter = getRequiredDelimiterInReverse(right,
1779           rightDelimiter, rlength - (rightDelimiter - roffset),
1780           HRegionInfo.DELIMITER);
1781       // Now compare middlesection of row.
1782       result = super.compareRows(left, leftDelimiter,
1783           leftFarDelimiter - leftDelimiter, right, rightDelimiter,
1784           rightFarDelimiter - rightDelimiter);
1785       if (result != 0) {
1786         return result;
1787       }
1788       // Compare last part of row, the rowid.
1789       leftFarDelimiter++;
1790       rightFarDelimiter++;
1791       result = compareRowid(left, leftFarDelimiter,
1792           llength - (leftFarDelimiter - loffset),
1793           right, rightFarDelimiter, rlength - (rightFarDelimiter - roffset));
1794       return result;
1795     }
1796 
1797     protected int compareRowid(byte[] left, int loffset, int llength,
1798         byte[] right, int roffset, int rlength) {
1799       return Bytes.compareTo(left, loffset, llength, right, roffset, rlength);
1800     }
1801   }
1802 
1803   /**
1804    * Compare key portion of a {@link KeyValue}.
1805    */
1806   public static class KeyComparator implements RawComparator<byte []> {
1807     volatile boolean ignoreTimestamp = false;
1808     volatile boolean ignoreType = false;
1809 
1810     public int compare(byte[] left, int loffset, int llength, byte[] right,
1811         int roffset, int rlength) {
1812       // Compare row
1813       short lrowlength = Bytes.toShort(left, loffset);
1814       short rrowlength = Bytes.toShort(right, roffset);
1815       int compare = compareRows(left, loffset + Bytes.SIZEOF_SHORT,
1816           lrowlength,
1817           right, roffset + Bytes.SIZEOF_SHORT, rrowlength);
1818       if (compare != 0) {
1819         return compare;
1820       }
1821 
1822       // Compare column family.  Start compare past row and family length.
1823       int lcolumnoffset = Bytes.SIZEOF_SHORT + lrowlength + 1 + loffset;
1824       int rcolumnoffset = Bytes.SIZEOF_SHORT + rrowlength + 1 + roffset;
1825       int lcolumnlength = llength - TIMESTAMP_TYPE_SIZE -
1826         (lcolumnoffset - loffset);
1827       int rcolumnlength = rlength - TIMESTAMP_TYPE_SIZE -
1828         (rcolumnoffset - roffset);
1829 
1830       // if row matches, and no column in the 'left' AND put type is 'minimum',
1831       // then return that left is larger than right.
1832 
1833       // This supports 'last key on a row' - the magic is if there is no column in the
1834       // left operand, and the left operand has a type of '0' - magical value,
1835       // then we say the left is bigger.  This will let us seek to the last key in
1836       // a row.
1837 
1838       byte ltype = left[loffset + (llength - 1)];
1839       byte rtype = right[roffset + (rlength - 1)];
1840 
1841       if (lcolumnlength == 0 && ltype == Type.Minimum.getCode()) {
1842         return 1; // left is bigger.
1843       }
1844       if (rcolumnlength == 0 && rtype == Type.Minimum.getCode()) {
1845         return -1;
1846       }
1847 
1848       // TODO the family and qualifier should be compared separately
1849       compare = Bytes.compareTo(left, lcolumnoffset, lcolumnlength, right,
1850           rcolumnoffset, rcolumnlength);
1851       if (compare != 0) {
1852         return compare;
1853       }
1854 
1855       if (!this.ignoreTimestamp) {
1856         // Get timestamps.
1857         long ltimestamp = Bytes.toLong(left,
1858             loffset + (llength - TIMESTAMP_TYPE_SIZE));
1859         long rtimestamp = Bytes.toLong(right,
1860             roffset + (rlength - TIMESTAMP_TYPE_SIZE));
1861         compare = compareTimestamps(ltimestamp, rtimestamp);
1862         if (compare != 0) {
1863           return compare;
1864         }
1865       }
1866 
1867       if (!this.ignoreType) {
1868         // Compare types. Let the delete types sort ahead of puts; i.e. types
1869         // of higher numbers sort before those of lesser numbers
1870         return (0xff & rtype) - (0xff & ltype);
1871       }
1872       return 0;
1873     }
1874 
1875     public int compare(byte[] left, byte[] right) {
1876       return compare(left, 0, left.length, right, 0, right.length);
1877     }
1878 
1879     public int compareRows(byte [] left, int loffset, int llength,
1880         byte [] right, int roffset, int rlength) {
1881       return Bytes.compareTo(left, loffset, llength, right, roffset, rlength);
1882     }
1883 
1884     protected int compareColumns(
1885         byte [] left, int loffset, int llength, final int lfamilylength,
1886         byte [] right, int roffset, int rlength, final int rfamilylength) {
1887       return KeyValue.compareColumns(left, loffset, llength, lfamilylength,
1888         right, roffset, rlength, rfamilylength);
1889     }
1890 
1891     int compareTimestamps(final long ltimestamp, final long rtimestamp) {
1892       // The below older timestamps sorting ahead of newer timestamps looks
1893       // wrong but it is intentional. This way, newer timestamps are first
1894       // found when we iterate over a memstore and newer versions are the
1895       // first we trip over when reading from a store file.
1896       if (ltimestamp < rtimestamp) {
1897         return 1;
1898       } else if (ltimestamp > rtimestamp) {
1899         return -1;
1900       }
1901       return 0;
1902     }
1903   }
1904 
1905   // HeapSize
1906   public long heapSize() {
1907     return ClassSize.align(ClassSize.OBJECT + (2 * ClassSize.REFERENCE) +
1908         ClassSize.align(ClassSize.ARRAY + length) +
1909         (3 * Bytes.SIZEOF_INT) +
1910         ClassSize.align(ClassSize.ARRAY + (rowCache == null ? 0 : rowCache.length)) +
1911         (2 * Bytes.SIZEOF_LONG));
1912   }
1913 
1914   // this overload assumes that the length bytes have already been read,
1915   // and it expects the length of the KeyValue to be explicitly passed
1916   // to it.
1917   public void readFields(int length, final DataInput in) throws IOException {
1918     this.length = length;
1919     this.offset = 0;
1920     this.bytes = new byte[this.length];
1921     in.readFully(this.bytes, 0, this.length);
1922   }
1923 
1924   // Writable
1925   public void readFields(final DataInput in) throws IOException {
1926     int length = in.readInt();
1927     readFields(length, in);
1928   }
1929 
1930   public void write(final DataOutput out) throws IOException {
1931     out.writeInt(this.length);
1932     out.write(this.bytes, this.offset, this.length);
1933   }
1934 }