1 8 9 package com.sleepycat.je.tree; 10 11 import java.util.Comparator ; 12 13 import com.sleepycat.bind.tuple.IntegerBinding; 14 import com.sleepycat.je.DatabaseEntry; 15 16 25 26 public final class Key implements Comparable { 27 public static boolean DUMP_BINARY = true; 28 29 public static boolean DUMP_INT_BINDING = false; 30 public static final byte[] EMPTY_KEY = new byte[0]; 31 private byte[] key; 32 33 36 public Key(byte[] key) { 37 if (key == null) { 38 this.key = null; 39 } else { 40 this.key = new byte[key.length]; 41 System.arraycopy(key, 0, this.key, 0, key.length); 42 } 43 } 44 45 public static byte[] makeKey(DatabaseEntry dbt) { 46 byte[] entryKey = dbt.getData(); 47 if (entryKey == null) { 48 return EMPTY_KEY; 49 } else { 50 byte[] newKey = new byte[dbt.getSize()]; 51 System.arraycopy(entryKey, dbt.getOffset(), newKey, 52 0, dbt.getSize()); 53 return newKey; 54 } 55 } 56 57 60 public byte[] getKey() { 61 return key; 62 } 63 64 71 public int compareTo(Object o) { 72 if (o == null) { 73 throw new NullPointerException (); 74 } 75 76 Key argKey = (Key) o; 77 return compareUnsignedBytes(this.key, argKey.key); 78 } 79 80 83 public boolean equals(Object o) { 84 return (o instanceof Key) && (compareTo(o) == 0); 85 } 86 87 90 public int hashCode() { 91 int code = 0; 92 for (int i = 0; i < key.length; i += 1) { 93 code += key[i]; 94 } 95 return code; 96 } 97 98 101 public static int compareKeys(byte[] key1, byte[] key2, 102 Comparator comparator) { 103 if (comparator != null) { 104 return comparator.compare(key1, key2); 105 } else { 106 return compareUnsignedBytes(key1, key2); 107 } 108 } 109 110 113 private static int compareUnsignedBytes(byte[] key1, byte[] key2) { 114 int a1Len = key1.length; 115 int a2Len = key2.length; 116 117 int limit = Math.min(a1Len, a2Len); 118 119 for (int i = 0; i < limit; i++) { 120 byte b1 = key1[i]; 121 byte b2 = key2[i]; 122 if (b1 == b2) { 123 continue; 124 } else { 125 127 return (b1 & 0xff) - (b2 & 0xff); 128 } 129 } 130 131 return (a1Len - a2Len); 132 } 133 134 public static String dumpString(byte[] key, int nspaces) { 135 StringBuffer sb = new StringBuffer (); 136 sb.append(TreeUtils.indent(nspaces)); 137 sb.append("<key v=\""); 138 139 144 145 if (DUMP_BINARY) { 146 if (key == null) { 147 sb.append("<null>"); 148 } else { 149 sb.append(TreeUtils.dumpByteArray(key)); 150 } 151 } else if (DUMP_INT_BINDING) { 152 if (key == null) { 153 sb.append("<null>"); 154 } else { 155 DatabaseEntry e = new DatabaseEntry(key); 156 sb.append(IntegerBinding.entryToInt(e)); 157 } 158 } else { 159 sb.append(key == null ? "" : new String (key)); 160 } 161 sb.append("\"/>"); 162 163 return sb.toString(); 164 } 165 166 169 public static String getNoFormatString(byte[] key) { 170 return "key=" + dumpString(key, 0); 171 } 172 } 173 | Popular Tags |