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