001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.client;
020
021import edu.umd.cs.findbugs.annotations.CheckForNull;
022import java.io.DataInputStream;
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.Arrays;
026import java.util.Comparator;
027import java.util.List;
028import java.util.stream.Collectors;
029import org.apache.hadoop.hbase.HConstants;
030import org.apache.hadoop.hbase.TableName;
031import org.apache.hadoop.hbase.exceptions.DeserializationException;
032import org.apache.hadoop.hbase.util.ByteArrayHashKey;
033import org.apache.hadoop.hbase.util.Bytes;
034import org.apache.hadoop.hbase.util.HashKey;
035import org.apache.hadoop.hbase.util.JenkinsHash;
036import org.apache.hadoop.hbase.util.MD5Hash;
037import org.apache.hadoop.io.DataInputBuffer;
038import org.apache.yetus.audience.InterfaceAudience;
039import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
040import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
041
042/**
043 * Information about a region. A region is a range of keys in the whole keyspace
044 * of a table, an identifier (a timestamp) for differentiating between subset
045 * ranges (after region split) and a replicaId for differentiating the instance
046 * for the same range and some status information about the region.
047 *
048 * The region has a unique name which consists of the following fields:
049 * <ul>
050 * <li> tableName   : The name of the table </li>
051 * <li> startKey    : The startKey for the region. </li>
052 * <li> regionId    : A timestamp when the region is created. </li>
053 * <li> replicaId   : An id starting from 0 to differentiate replicas of the
054 * same region range but hosted in separated servers. The same region range can
055 * be hosted in multiple locations.</li>
056 * <li> encodedName : An MD5 encoded string for the region name.</li>
057 * </ul>
058 *
059 * <br> Other than the fields in the region name, region info contains:
060 * <ul>
061 * <li> endKey      : the endKey for the region (exclusive) </li>
062 * <li> split       : Whether the region is split </li>
063 * <li> offline     : Whether the region is offline </li>
064 * </ul>
065 *
066 */
067@InterfaceAudience.Public
068public interface RegionInfo extends Comparable<RegionInfo> {
069  /**
070   * @deprecated since 2.3.2/3.0.0; to be removed in 4.0.0 with no replacement (for internal use).
071   */
072  @Deprecated
073  @InterfaceAudience.Private
074  // Not using RegionInfoBuilder intentionally to avoid a static loading deadlock: HBASE-24896
075  RegionInfo UNDEFINED = new MutableRegionInfo(0, TableName.valueOf("__UNDEFINED__"),
076    RegionInfo.DEFAULT_REPLICA_ID);
077
078  /**
079   * Separator used to demarcate the encodedName in a region name
080   * in the new format. See description on new format above.
081   */
082  @InterfaceAudience.Private
083  int ENC_SEPARATOR = '.';
084
085  @InterfaceAudience.Private
086  int MD5_HEX_LENGTH = 32;
087
088  @InterfaceAudience.Private
089  int DEFAULT_REPLICA_ID = 0;
090
091  /**
092   * to keep appended int's sorted in string format. Only allows 2 bytes
093   * to be sorted for replicaId.
094   */
095  @InterfaceAudience.Private
096  String REPLICA_ID_FORMAT = "%04X";
097
098  @InterfaceAudience.Private
099  byte REPLICA_ID_DELIMITER = (byte)'_';
100
101  @InterfaceAudience.Private
102  String INVALID_REGION_NAME_FORMAT_MESSAGE = "Invalid regionName format";
103
104  @InterfaceAudience.Private
105  Comparator<RegionInfo> COMPARATOR
106    = (RegionInfo lhs, RegionInfo rhs) -> {
107      if (rhs == null) {
108        return 1;
109      }
110
111      // Are regions of same table?
112      int result = lhs.getTable().compareTo(rhs.getTable());
113      if (result != 0) {
114        return result;
115      }
116
117      // Compare start keys.
118      result = Bytes.compareTo(lhs.getStartKey(), rhs.getStartKey());
119      if (result != 0) {
120        return result;
121      }
122
123      // Compare end keys.
124      result = Bytes.compareTo(lhs.getEndKey(), rhs.getEndKey());
125
126      if (result != 0) {
127        if (lhs.getStartKey().length != 0
128                && lhs.getEndKey().length == 0) {
129            return 1; // this is last region
130        }
131        if (rhs.getStartKey().length != 0
132                && rhs.getEndKey().length == 0) {
133            return -1; // o is the last region
134        }
135        return result;
136      }
137
138      // regionId is usually milli timestamp -- this defines older stamps
139      // to be "smaller" than newer stamps in sort order.
140      if (lhs.getRegionId() > rhs.getRegionId()) {
141        return 1;
142      } else if (lhs.getRegionId() < rhs.getRegionId()) {
143        return -1;
144      }
145
146      int replicaDiff = lhs.getReplicaId() - rhs.getReplicaId();
147      if (replicaDiff != 0) {
148        return replicaDiff;
149      }
150
151      if (lhs.isOffline() == rhs.isOffline()) {
152        return 0;
153      }
154      if (lhs.isOffline()) {
155        return -1;
156      }
157
158      return 1;
159  };
160
161
162  /**
163   * @return Return a short, printable name for this region
164   * (usually encoded name) for us logging.
165   */
166  String getShortNameToLog();
167
168  /**
169   * @return the regionId.
170   */
171  long getRegionId();
172
173  /**
174   * @return the regionName as an array of bytes.
175   * @see #getRegionNameAsString()
176   */
177  byte [] getRegionName();
178
179  /**
180   * @return Region name as a String for use in logging, etc.
181   */
182  String getRegionNameAsString();
183
184  /**
185   * @return the encoded region name.
186   */
187  String getEncodedName();
188
189  /**
190   * @return the encoded region name as an array of bytes.
191   */
192  byte [] getEncodedNameAsBytes();
193
194  /**
195   * @return the startKey.
196   */
197  byte [] getStartKey();
198
199  /**
200   * @return the endKey.
201   */
202  byte [] getEndKey();
203
204  /**
205   * @return current table name of the region
206   */
207  TableName getTable();
208
209  /**
210   * @return returns region replica id
211   */
212  int getReplicaId();
213
214  /**
215   * @return True if has been split and has daughters.
216   */
217  boolean isSplit();
218
219  /**
220   * @return True if this region is offline.
221   * @deprecated since 3.0.0 and will be removed in 4.0.0
222   * @see <a href="https://issues.apache.org/jira/browse/HBASE-25210">HBASE-25210</a>
223   */
224  @Deprecated
225  boolean isOffline();
226
227  /**
228   * @return True if this is a split parent region.
229   * @deprecated since 3.0.0 and will be removed in 4.0.0, Use {@link #isSplit()} instead.
230   * @see <a href="https://issues.apache.org/jira/browse/HBASE-25210">HBASE-25210</a>
231   */
232  @Deprecated
233  boolean isSplitParent();
234
235  /**
236   * @return true if this region is a meta region.
237   */
238  boolean isMetaRegion();
239
240  /**
241   * @return true if the given inclusive range of rows is fully contained
242   * by this region. For example, if the region is foo,a,g and this is
243   * passed ["b","c"] or ["a","c"] it will return true, but if this is passed
244   * ["b","z"] it will return false.
245   * @throws IllegalArgumentException if the range passed is invalid (ie. end &lt; start)
246   */
247  boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey);
248
249  /**
250   * @return true if the given row falls in this region.
251   */
252  boolean containsRow(byte[] row);
253
254  /**
255   * Does region name contain its encoded name?
256   * @param regionName region name
257   * @return boolean indicating if this a new format region
258   *         name which contains its encoded name.
259   */
260  @InterfaceAudience.Private
261  static boolean hasEncodedName(final byte[] regionName) {
262    // check if region name ends in ENC_SEPARATOR
263    return (regionName.length >= 1) &&
264      (regionName[regionName.length - 1] == RegionInfo.ENC_SEPARATOR);
265  }
266
267  /**
268   * @return the encodedName
269   */
270  @InterfaceAudience.Private
271  static String encodeRegionName(final byte [] regionName) {
272    String encodedName;
273    if (hasEncodedName(regionName)) {
274      // region is in new format:
275      // <tableName>,<startKey>,<regionIdTimeStamp>/encodedName/
276      encodedName = Bytes.toString(regionName,
277      regionName.length - MD5_HEX_LENGTH - 1,
278      MD5_HEX_LENGTH);
279    } else {
280      // old format region name. First hbase:meta region also
281      // use this format.EncodedName is the JenkinsHash value.
282      HashKey<byte[]> key = new ByteArrayHashKey(regionName, 0, regionName.length);
283      int hashVal = Math.abs(JenkinsHash.getInstance().hash(key, 0));
284      encodedName = String.valueOf(hashVal);
285    }
286    return encodedName;
287  }
288
289  @InterfaceAudience.Private
290  static String getRegionNameAsString(byte[] regionName) {
291    return getRegionNameAsString(null, regionName);
292  }
293
294  @InterfaceAudience.Private
295  static String getRegionNameAsString(@CheckForNull RegionInfo ri, byte[] regionName) {
296    if (RegionInfo.hasEncodedName(regionName)) {
297      // new format region names already have their encoded name.
298      return Bytes.toStringBinary(regionName);
299    }
300
301    // old format. regionNameStr doesn't have the region name.
302    if (ri == null) {
303      return Bytes.toStringBinary(regionName) + "." + RegionInfo.encodeRegionName(regionName);
304    } else {
305      return Bytes.toStringBinary(regionName) + "." + ri.getEncodedName();
306    }
307  }
308
309  /**
310   * @return Return a String of short, printable names for <code>hris</code>
311   * (usually encoded name) for us logging.
312   */
313  static String getShortNameToLog(RegionInfo...hris) {
314    return getShortNameToLog(Arrays.asList(hris));
315  }
316
317  /**
318   * @return Return a String of short, printable names for <code>hris</code> (usually encoded name)
319   *   for us logging.
320   */
321  static String getShortNameToLog(final List<RegionInfo> ris) {
322    return ris.stream().map(RegionInfo::getEncodedName).collect(Collectors.toList()).toString();
323  }
324
325  /**
326   * Gets the table name from the specified region name.
327   * @param regionName to extract the table name from
328   * @return Table name
329   */
330  @InterfaceAudience.Private
331  // This method should never be used. Its awful doing parse from bytes.
332  // It is fallback in case we can't get the tablename any other way. Could try removing it.
333  // Keeping it Audience Private so can remove at later date.
334  static TableName getTable(final byte [] regionName) {
335    int offset = -1;
336    for (int i = 0; i < regionName.length; i++) {
337      if (regionName[i] == HConstants.DELIMITER) {
338        offset = i;
339        break;
340      }
341    }
342    if (offset <= 0) {
343      throw new IllegalArgumentException("offset=" + offset);
344    }
345    byte[] buff  = new byte[offset];
346    System.arraycopy(regionName, 0, buff, 0, offset);
347    return TableName.valueOf(buff);
348  }
349
350  /**
351   * Gets the start key from the specified region name.
352   * @return Start key.
353   */
354  static byte[] getStartKey(final byte[] regionName) throws IOException {
355    return parseRegionName(regionName)[1];
356  }
357
358  /**
359   * Figure if the passed bytes represent an encoded region name or not.
360   * @param regionName A Region name either encoded or not.
361   * @return True if <code>regionName</code> represents an encoded name.
362   */
363  @InterfaceAudience.Private // For use by internals only.
364  public static boolean isEncodedRegionName(byte[] regionName) {
365    // If not parseable as region name, presume encoded. TODO: add stringency; e.g. if hex.
366    if (parseRegionNameOrReturnNull(regionName) == null) {
367      if (regionName.length > MD5_HEX_LENGTH) {
368        return false;
369      } else if (regionName.length == MD5_HEX_LENGTH) {
370        return true;
371      } else {
372        String encodedName = Bytes.toString(regionName);
373        try {
374          Integer.parseInt(encodedName);
375          // If this is a valid integer, it could be hbase:meta's encoded region name.
376          return true;
377        } catch(NumberFormatException er) {
378          return false;
379        }
380      }
381    }
382    return false;
383  }
384
385  /**
386   * @return A deserialized {@link RegionInfo}
387   * or null if we failed deserialize or passed bytes null
388   */
389  @InterfaceAudience.Private
390  static RegionInfo parseFromOrNull(final byte [] bytes) {
391    if (bytes == null) return null;
392    return parseFromOrNull(bytes, 0, bytes.length);
393  }
394
395  /**
396   * @return A deserialized {@link RegionInfo} or null
397   *  if we failed deserialize or passed bytes null
398   */
399  @InterfaceAudience.Private
400  static RegionInfo parseFromOrNull(final byte [] bytes, int offset, int len) {
401    if (bytes == null || len <= 0) return null;
402    try {
403      return parseFrom(bytes, offset, len);
404    } catch (DeserializationException e) {
405      return null;
406    }
407  }
408
409  /**
410   * @param bytes A pb RegionInfo serialized with a pb magic prefix.
411   * @return A deserialized {@link RegionInfo}
412   */
413  @InterfaceAudience.Private
414  static RegionInfo parseFrom(final byte [] bytes) throws DeserializationException {
415    if (bytes == null) return null;
416    return parseFrom(bytes, 0, bytes.length);
417  }
418
419  /**
420   * @param bytes A pb RegionInfo serialized with a pb magic prefix.
421   * @param offset starting point in the byte array
422   * @param len length to read on the byte array
423   * @return A deserialized {@link RegionInfo}
424   */
425  @InterfaceAudience.Private
426  static RegionInfo parseFrom(final byte [] bytes, int offset, int len)
427  throws DeserializationException {
428    if (ProtobufUtil.isPBMagicPrefix(bytes, offset, len)) {
429      int pblen = ProtobufUtil.lengthOfPBMagic();
430      try {
431        HBaseProtos.RegionInfo.Builder builder = HBaseProtos.RegionInfo.newBuilder();
432        ProtobufUtil.mergeFrom(builder, bytes, pblen + offset, len - pblen);
433        HBaseProtos.RegionInfo ri = builder.build();
434        return ProtobufUtil.toRegionInfo(ri);
435      } catch (IOException e) {
436        throw new DeserializationException(e);
437      }
438    } else {
439      throw new DeserializationException("PB encoded RegionInfo expected");
440    }
441  }
442
443  /**
444   * Check whether two regions are adjacent; i.e. lies just before or just
445   * after in a table.
446   * @return true if two regions are adjacent
447   */
448  static boolean areAdjacent(RegionInfo regionA, RegionInfo regionB) {
449    if (regionA == null || regionB == null) {
450      throw new IllegalArgumentException(
451      "Can't check whether adjacent for null region");
452    }
453    if (!regionA.getTable().equals(regionB.getTable())) {
454      return false;
455    }
456    RegionInfo a = regionA;
457    RegionInfo b = regionB;
458    if (Bytes.compareTo(a.getStartKey(), b.getStartKey()) > 0) {
459      a = regionB;
460      b = regionA;
461    }
462    return Bytes.equals(a.getEndKey(), b.getStartKey());
463  }
464
465  /**
466   * @return This instance serialized as protobuf w/ a magic pb prefix.
467   * @see #parseFrom(byte[])
468   */
469  static byte [] toByteArray(RegionInfo ri) {
470    byte [] bytes = ProtobufUtil.toRegionInfo(ri).toByteArray();
471    return ProtobufUtil.prependPBMagic(bytes);
472  }
473
474  /**
475   * Use logging.
476   * @param encodedRegionName The encoded regionname.
477   * @return <code>hbase:meta</code> if passed <code>1028785192</code> else returns
478   * <code>encodedRegionName</code>
479   */
480  static String prettyPrint(final String encodedRegionName) {
481    if (encodedRegionName.equals("1028785192")) {
482      return encodedRegionName + "/hbase:meta";
483    }
484    return encodedRegionName;
485  }
486
487  /**
488   * Make a region name of passed parameters.
489   * @param startKey Can be null
490   * @param regionid Region id (Usually timestamp from when region was created).
491   * @param newFormat should we create the region name in the new format
492   *                  (such that it contains its encoded name?).
493   * @return Region name made of passed tableName, startKey and id
494   */
495  static byte [] createRegionName(final TableName tableName, final byte[] startKey,
496                                  final long regionid, boolean newFormat) {
497    return createRegionName(tableName, startKey, Long.toString(regionid), newFormat);
498  }
499
500  /**
501   * Make a region name of passed parameters.
502   * @param startKey Can be null
503   * @param id Region id (Usually timestamp from when region was created).
504   * @param newFormat should we create the region name in the new format
505   *                  (such that it contains its encoded name?).
506   * @return Region name made of passed tableName, startKey and id
507   */
508  static byte [] createRegionName(final TableName tableName,
509                                  final byte[] startKey, final String id, boolean newFormat) {
510    return createRegionName(tableName, startKey, Bytes.toBytes(id), newFormat);
511  }
512
513  /**
514   * Make a region name of passed parameters.
515   * @param startKey Can be null
516   * @param regionid Region id (Usually timestamp from when region was created).
517   * @param newFormat should we create the region name in the new format
518   *                  (such that it contains its encoded name?).
519   * @return Region name made of passed tableName, startKey, id and replicaId
520   */
521  static byte [] createRegionName(final TableName tableName,
522      final byte[] startKey, final long regionid, int replicaId, boolean newFormat) {
523    return createRegionName(tableName, startKey, Bytes.toBytes(Long.toString(regionid)),
524      replicaId, newFormat);
525  }
526
527  /**
528   * Make a region name of passed parameters.
529   * @param startKey Can be null
530   * @param id Region id (Usually timestamp from when region was created).
531   * @param newFormat should we create the region name in the new format
532   *                  (such that it contains its encoded name?).
533   * @return Region name made of passed tableName, startKey and id
534   */
535  static byte [] createRegionName(final TableName tableName,
536      final byte[] startKey, final byte[] id, boolean newFormat) {
537    return createRegionName(tableName, startKey, id, DEFAULT_REPLICA_ID, newFormat);
538  }
539
540  /**
541   * Make a region name of passed parameters.
542   * @param startKey Can be null
543   * @param id Region id (Usually timestamp from when region was created).
544   * @param newFormat should we create the region name in the new format
545   * @return Region name made of passed tableName, startKey, id and replicaId
546   */
547  static byte [] createRegionName(final TableName tableName,
548      final byte[] startKey, final byte[] id, final int replicaId, boolean newFormat) {
549    int len = tableName.getName().length + 2 + id.length + (startKey == null? 0: startKey.length);
550    if (newFormat) {
551      len += MD5_HEX_LENGTH + 2;
552    }
553    byte[] replicaIdBytes = null;
554    // Special casing: replicaId is only appended if replicaId is greater than
555    // 0. This is because all regions in meta would have to be migrated to the new
556    // name otherwise
557    if (replicaId > 0) {
558      // use string representation for replica id
559      replicaIdBytes = Bytes.toBytes(String.format(REPLICA_ID_FORMAT, replicaId));
560      len += 1 + replicaIdBytes.length;
561    }
562
563    byte [] b = new byte [len];
564
565    int offset = tableName.getName().length;
566    System.arraycopy(tableName.getName(), 0, b, 0, offset);
567    b[offset++] = HConstants.DELIMITER;
568    if (startKey != null && startKey.length > 0) {
569      System.arraycopy(startKey, 0, b, offset, startKey.length);
570      offset += startKey.length;
571    }
572    b[offset++] = HConstants.DELIMITER;
573    System.arraycopy(id, 0, b, offset, id.length);
574    offset += id.length;
575
576    if (replicaIdBytes != null) {
577      b[offset++] = REPLICA_ID_DELIMITER;
578      System.arraycopy(replicaIdBytes, 0, b, offset, replicaIdBytes.length);
579      offset += replicaIdBytes.length;
580    }
581
582    if (newFormat) {
583      //
584      // Encoded name should be built into the region name.
585      //
586      // Use the region name thus far (namely, <tablename>,<startKey>,<id>_<replicaId>)
587      // to compute a MD5 hash to be used as the encoded name, and append
588      // it to the byte buffer.
589      //
590      String md5Hash = MD5Hash.getMD5AsHex(b, 0, offset);
591      byte [] md5HashBytes = Bytes.toBytes(md5Hash);
592
593      if (md5HashBytes.length != MD5_HEX_LENGTH) {
594        System.out.println("MD5-hash length mismatch: Expected=" + MD5_HEX_LENGTH +
595        "; Got=" + md5HashBytes.length);
596      }
597
598      // now append the bytes '.<encodedName>.' to the end
599      b[offset++] = ENC_SEPARATOR;
600      System.arraycopy(md5HashBytes, 0, b, offset, MD5_HEX_LENGTH);
601      offset += MD5_HEX_LENGTH;
602      b[offset] = ENC_SEPARATOR;
603    }
604
605    return b;
606  }
607
608  /**
609   * Creates a RegionInfo object for MOB data.
610   *
611   * @param tableName the name of the table
612   * @return the MOB {@link RegionInfo}.
613   */
614  static RegionInfo createMobRegionInfo(TableName tableName) {
615    // Skipping reference to RegionInfoBuilder in this class.
616    return new MutableRegionInfo(tableName, Bytes.toBytes(".mob"),
617      HConstants.EMPTY_END_ROW, false, 0, DEFAULT_REPLICA_ID, false);
618  }
619
620  /**
621   * Separate elements of a regionName.
622   * @return Array of byte[] containing tableName, startKey and id OR null if
623   *   not parseable as a region name.
624   * @throws IOException if not parseable as regionName.
625   */
626  static byte [][] parseRegionName(final byte[] regionName) throws IOException {
627    byte [][] result = parseRegionNameOrReturnNull(regionName);
628    if (result == null) {
629      throw new IOException(INVALID_REGION_NAME_FORMAT_MESSAGE + ": " + Bytes.toStringBinary(regionName));
630    }
631    return result;
632  }
633
634  /**
635   * Separate elements of a regionName.
636   * Region name is of the format:
637   * <code>tablename,startkey,regionIdTimestamp[_replicaId][.encodedName.]</code>.
638   * Startkey can contain the delimiter (',') so we parse from the start and then parse from
639   * the end.
640   * @return Array of byte[] containing tableName, startKey and id OR null if not parseable
641   * as a region name.
642   */
643  static byte [][] parseRegionNameOrReturnNull(final byte[] regionName) {
644    int offset = -1;
645    for (int i = 0; i < regionName.length; i++) {
646      if (regionName[i] == HConstants.DELIMITER) {
647        offset = i;
648        break;
649      }
650    }
651    if (offset == -1) {
652      return null;
653    }
654    byte[] tableName = new byte[offset];
655    System.arraycopy(regionName, 0, tableName, 0, offset);
656    offset = -1;
657
658    int endOffset = regionName.length;
659    // check whether regionName contains encodedName
660    if (regionName.length > MD5_HEX_LENGTH + 2 &&
661        regionName[regionName.length-1] == ENC_SEPARATOR &&
662        regionName[regionName.length-MD5_HEX_LENGTH-2] == ENC_SEPARATOR) {
663      endOffset = endOffset - MD5_HEX_LENGTH - 2;
664    }
665
666    // parse from end
667    byte[] replicaId = null;
668    int idEndOffset = endOffset;
669    for (int i = endOffset - 1; i > 0; i--) {
670      if (regionName[i] == REPLICA_ID_DELIMITER) { //replicaId may or may not be present
671        replicaId = new byte[endOffset - i - 1];
672        System.arraycopy(regionName, i + 1, replicaId, 0,
673        endOffset - i - 1);
674        idEndOffset = i;
675        // do not break, continue to search for id
676      }
677      if (regionName[i] == HConstants.DELIMITER) {
678        offset = i;
679        break;
680      }
681    }
682    if (offset == -1) {
683      return null;
684    }
685    byte [] startKey = HConstants.EMPTY_BYTE_ARRAY;
686    if(offset != tableName.length + 1) {
687      startKey = new byte[offset - tableName.length - 1];
688      System.arraycopy(regionName, tableName.length + 1, startKey, 0,
689      offset - tableName.length - 1);
690    }
691    byte [] id = new byte[idEndOffset - offset - 1];
692    System.arraycopy(regionName, offset + 1, id, 0,
693    idEndOffset - offset - 1);
694    byte [][] elements = new byte[replicaId == null ? 3 : 4][];
695    elements[0] = tableName;
696    elements[1] = startKey;
697    elements[2] = id;
698    if (replicaId != null) {
699      elements[3] = replicaId;
700    }
701    return elements;
702  }
703
704  /**
705   * Serializes given RegionInfo's as a byte array. Use this instead of
706   * {@link RegionInfo#toByteArray(RegionInfo)} when
707   * writing to a stream and you want to use the pb mergeDelimitedFrom (w/o the delimiter, pb reads
708   * to EOF which may not be what you want). {@link #parseDelimitedFrom(byte[], int, int)} can
709   * be used to read back the instances.
710   * @param infos RegionInfo objects to serialize
711   * @return This instance serialized as a delimited protobuf w/ a magic pb prefix.
712   */
713  static byte[] toDelimitedByteArray(RegionInfo... infos) throws IOException {
714    byte[][] bytes = new byte[infos.length][];
715    int size = 0;
716    for (int i = 0; i < infos.length; i++) {
717      bytes[i] = toDelimitedByteArray(infos[i]);
718      size += bytes[i].length;
719    }
720
721    byte[] result = new byte[size];
722    int offset = 0;
723    for (byte[] b : bytes) {
724      System.arraycopy(b, 0, result, offset, b.length);
725      offset += b.length;
726    }
727    return result;
728  }
729
730  /**
731   * Use this instead of {@link RegionInfo#toByteArray(RegionInfo)} when writing to a stream and you want to use
732   * the pb mergeDelimitedFrom (w/o the delimiter, pb reads to EOF which may not be what you want).
733   * @return This instance serialized as a delimied protobuf w/ a magic pb prefix.
734   */
735  static byte [] toDelimitedByteArray(RegionInfo ri) throws IOException {
736    return ProtobufUtil.toDelimitedByteArray(ProtobufUtil.toRegionInfo(ri));
737  }
738
739  /**
740   * Parses an RegionInfo instance from the passed in stream.
741   * Presumes the RegionInfo was serialized to the stream with
742   * {@link #toDelimitedByteArray(RegionInfo)}.
743   * @return An instance of RegionInfo.
744   */
745  static RegionInfo parseFrom(final DataInputStream in) throws IOException {
746    // I need to be able to move back in the stream if this is not a pb
747    // serialization so I can do the Writable decoding instead.
748    int pblen = ProtobufUtil.lengthOfPBMagic();
749    byte [] pbuf = new byte[pblen];
750    if (in.markSupported()) { //read it with mark()
751      in.mark(pblen);
752    }
753
754    //assumption: if Writable serialization, it should be longer than pblen.
755    int read = in.read(pbuf);
756    if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
757    if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
758      return ProtobufUtil.toRegionInfo(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
759    } else {
760      throw new IOException("PB encoded RegionInfo expected");
761    }
762  }
763
764  /**
765   * Parses all the RegionInfo instances from the passed in stream until EOF. Presumes the
766   * RegionInfo's were serialized to the stream with oDelimitedByteArray()
767   * @param bytes serialized bytes
768   * @param offset the start offset into the byte[] buffer
769   * @param length how far we should read into the byte[] buffer
770   * @return All the RegionInfos that are in the byte array. Keeps reading till we hit the end.
771   */
772  static List<RegionInfo> parseDelimitedFrom(final byte[] bytes, final int offset,
773                                             final int length) throws IOException {
774    if (bytes == null) {
775      throw new IllegalArgumentException("Can't build an object with empty bytes array");
776    }
777    List<RegionInfo> ris = new ArrayList<>();
778    try (DataInputBuffer in = new DataInputBuffer()) {
779      in.reset(bytes, offset, length);
780      while (in.available() > 0) {
781        RegionInfo ri = parseFrom(in);
782        ris.add(ri);
783      }
784    }
785    return ris;
786  }
787
788  /**
789   * @return True if this is first Region in Table
790   */
791  default boolean isFirst() {
792    return Bytes.equals(getStartKey(), HConstants.EMPTY_START_ROW);
793  }
794
795  /**
796   * @return True if this is last Region in Table
797   */
798  default boolean isLast() {
799    return Bytes.equals(getEndKey(), HConstants.EMPTY_END_ROW);
800  }
801
802  /**
803   * @return True if region is next, adjacent but 'after' this one.
804   * @see #isAdjacent(RegionInfo)
805   * @see #areAdjacent(RegionInfo, RegionInfo)
806   */
807  default boolean isNext(RegionInfo after) {
808    return getTable().equals(after.getTable()) && Bytes.equals(getEndKey(), after.getStartKey());
809  }
810
811  /**
812   * @return True if region is adjacent, either just before or just after this one.
813   * @see #isNext(RegionInfo)
814   */
815  default boolean isAdjacent(RegionInfo other) {
816    return getTable().equals(other.getTable()) && areAdjacent(this, other);
817  }
818
819  /**
820   * @return True if RegionInfo is degenerate... if startKey > endKey.
821   */
822  default boolean isDegenerate() {
823    return !isLast() && Bytes.compareTo(getStartKey(), getEndKey()) > 0;
824  }
825
826  /**
827   * @return True if an overlap in region range.
828   * @see #isDegenerate()
829   */
830  default boolean isOverlap(RegionInfo other) {
831    if (other == null) {
832      return false;
833    }
834    if (!getTable().equals(other.getTable())) {
835      return false;
836    }
837    int startKeyCompare = Bytes.compareTo(getStartKey(), other.getStartKey());
838    if (startKeyCompare == 0) {
839      return true;
840    }
841    if (startKeyCompare < 0) {
842      if (isLast()) {
843        return true;
844      }
845      return Bytes.compareTo(getEndKey(), other.getStartKey()) > 0;
846    }
847    if (other.isLast()) {
848      return true;
849    }
850    return Bytes.compareTo(getStartKey(), other.getEndKey()) < 0;
851  }
852
853  default int compareTo(RegionInfo other) {
854    return RegionInfo.COMPARATOR.compare(this, other);
855  }
856}