Convert guava's {@link RangeSet} to Bigtable's {@link ByteStringRange}. Please note that this will convert
boundless ranges into unset key cases.
502396
@VisibleForTesting
  void rangeSetToByteStringRange(RangeSet<RowKeyWrapper> guavaRangeSet, Query query) {

    for (Range<RowKeyWrapper> guavaRange : guavaRangeSet.asRanges()) {
      // Is it a point?
      if (guavaRange.hasLowerBound() && guavaRange.lowerBoundType() == BoundType.CLOSED
          && guavaRange.hasUpperBound() && guavaRange.upperBoundType() == BoundType.CLOSED
          && guavaRange.lowerEndpoint().equals(guavaRange.upperEndpoint())) {

        query.rowKey(guavaRange.lowerEndpoint().getKey());
      } else {
        ByteStringRange byteRange = ByteStringRange.unbounded();

        // Handle start key
        if (guavaRange.hasLowerBound()) {
          switch (guavaRange.lowerBoundType()) {
            case CLOSED:
              byteRange.startClosed(guavaRange.lowerEndpoint().getKey());
              break;
            case OPEN:
              byteRange.startOpen(guavaRange.lowerEndpoint().getKey());
              break;
            default:
              throw new IllegalArgumentException("Unexpected lower bound type: "
                  + guavaRange.lowerBoundType());
          }
        }

        // handle end key
        if (guavaRange.hasUpperBound()) {
          switch (guavaRange.upperBoundType()) {
            case CLOSED:
              byteRange.endClosed(guavaRange.upperEndpoint().getKey());
              break;
            case OPEN:
              byteRange.endOpen(guavaRange.upperEndpoint().getKey());
              break;
            default:
              throw new IllegalArgumentException("Unexpected upper bound type: " +
                  guavaRange.upperBoundType());
          }
        }
        query.range(byteRange);
      }
    }
  }
1132768
protected /*@pure@*/ int rangeSingle(/*@non_null@*/String singleSelection) {

        String single = singleSelection.trim();
        if (single.toLowerCase().equals("first")) {
            return 0;
        }
        if (single.toLowerCase().equals("last") || single.toLowerCase().equals("-1")) {
            return -1;
        }
        int index = Integer.parseInt(single);
        if (index >= 1) { //Non for negatives
            index--;
        }
        return index;
    }
878147
private List<String> extractRanges(String range) {
		List<String> ranges;
		String[] rangeSpl = range.split(",");

		// Recent versions of scop always specify a chain, so no processing is needed
		if(scopVersion.compareTo("1.73") < 0 ) {
			for(int i=0; i<rangeSpl.length;i++) {
				String subRange = rangeSpl[i];

				// Allow single-chains, as well as the '-' special case
				if(subRange.length()<2) {
					continue;
				}

				// Allow explicit chain syntax
				if(subRange.charAt(1) != ':') {
					// Early versions sometimes skip the chain identifier for single-chain domains
					// Indicate this with a chain "_"
					rangeSpl[i] = "_:"+subRange;
				}
			}
		}
		ranges = Arrays.asList(rangeSpl);
		return ranges;
	}
1309590
private void convert(int set[], UnicodeSet uset)
    {
        uset.clear();
        if (!initNameSetsLengths()) {
            return;
        }

        // build a char string with all chars that are used in character names
        for (char c = 255; c > 0; c --) {
            if (contains(set, c)) {
                uset.add(c);
            }
        }
    }
1290513
private static Set<Integer> setForRange(int max) {
    Set<Integer> set = Sets.newLinkedHashSet();
    for (int i = 0; i < max; i++) {
      set.add(i);
    }
    return set;
  }
248699
public static ByteRange parse(String rangeHeader) {
        if(rangeHeader == null || rangeHeader.length() < 7) {
            return null;
        }
        if(!rangeHeader.startsWith("bytes=")) {
            return null;
        }
        List<Range> ranges = new ArrayList<>();
        String[] parts = rangeHeader.substring(6).split(",");
        for(String part : parts) {
            try {
                int index = part.indexOf('-');
                if (index == 0) {
                    //suffix range spec
                    //represents the last N bytes
                    //internally we represent this using a -1 as the start position
                    long val = Long.parseLong(part.substring(1));
                    if(val < 0) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader);
                        return null;
                    }
                    ranges.add(new Range(-1, val));
                } else {
                    if(index == -1) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader);
                        return null;
                    }
                    long start = Long.parseLong(part.substring(0, index));
                    if(start < 0) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader);
                        return null;
                    }
                    long end;
                    if (index + 1 < part.length()) {
                        end = Long.parseLong(part.substring(index + 1));
                    } else {
                        end = -1;
                    }
                    ranges.add(new Range(start, end));
                }
            } catch (NumberFormatException e) {
                UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader);
                return null;
            }
        }
        if(ranges.isEmpty()) {
            return null;
        }
        return new ByteRange(ranges);
    }
1022072
private BitSet toBitSet(int[] mapping) {
        BitSet hits = new BitSet();
        for (int v : mapping)
            hits.set(v);
        return hits;
    }
569854
private static Iterator<ImmutableRoaringBitmap> selectRangeWithoutCopy(
      final Iterator<? extends ImmutableRoaringBitmap> bitmaps,
      final long rangeStart, final long rangeEnd) {
    Iterator<ImmutableRoaringBitmap> bitmapsIterator;
    bitmapsIterator = new Iterator<ImmutableRoaringBitmap>() {
      @Override
      public boolean hasNext() {
        return bitmaps.hasNext();
      }

      @Override
      public ImmutableRoaringBitmap next() {
        ImmutableRoaringBitmap next = bitmaps.next();
        return selectRangeWithoutCopy(next, rangeStart, rangeEnd);
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException("Remove not supported");
      }
    };
    return bitmapsIterator;
  }
1037691
@Override
    public void readAndDeleteSet(int requestNumber, SIMessageHandle[] msgHandles, int tran) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "readAndDeleteSet",
                                           new Object[] { requestNumber, msgHandles, tran });

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(this, tc, "Request to read / delete " + msgHandles.length +
                                                     " message(s)");

        final ConversationState convState = (ConversationState) getConversation().getAttachment();

        try {
            SITransaction siTran = null;
            if (tran != CommsConstants.NO_TRANSACTION) {
                siTran =
                                ((ServerLinkLevelState) getConversation().getLinkLevelAttachment()).getTransactionTable().get(tran);
            }

            SIBusMessage[] messages;
            if (siTran != IdToTransactionTable.INVALID_TRANSACTION) {
                messages = bifSession.readAndDeleteSet(msgHandles, siTran);
            } else {
                messages = new SIBusMessage[0];
            }

            // Add the number of items first
            CommsServerByteBuffer buff = poolManager.allocate();
            buff.putInt(messages.length);

            for (int x = 0; x < messages.length; x++) {
                buff.putMessage((JsMessage) messages[x],
                                convState.getCommsConnection(),
                                getConversation());
            }

            try {
                getConversation().send(buff,
                                       JFapChannelConstants.SEG_READ_AND_DELETE_SET_R,
                                       requestNumber,
                                       JFapChannelConstants.PRIORITY_MEDIUM,
                                       true,
                                       ThrottlingPolicy.BLOCK_THREAD,
                                       null);
            } catch (SIException e) {
                FFDCFilter.processException(e,
                                            CLASS_NAME + ".readAndDeleteSet",
                                            CommsConstants.CATBIFCONSUMER_READANDDELTESET_01,
                                            this);

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(this, tc, e.getMessage(), e);

                SibTr.error(tc, "COMMUNICATION_ERROR_SICO2033", e);
            }
        } catch (Exception e) {
            //No FFDC code needed
            //Only FFDC if we haven't received a meTerminated event OR if this Exception isn't a SIException.
            if (!(e instanceof SIException) || !convState.hasMETerminated()) {
                FFDCFilter.processException(e,
                                            CLASS_NAME + ".readAndDeleteSet",
                                            CommsConstants.CATBIFCONSUMER_READANDDELTESET_02,
                                            this);
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(this, tc, e.getMessage(), e);

            StaticCATHelper.sendExceptionToClient(e,
                                                  CommsConstants.CATBIFCONSUMER_READANDDELTESET_02,
                                                  getConversation(), requestNumber);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "readAndDeleteSet");
    }
10962
public Domain simplify()
    {
        ValueSet simplifiedValueSet = values.getValuesProcessor().<Optional<ValueSet>>transform(
                ranges -> {
                    if (ranges.getOrderedRanges().size() <= 32) {
                        return Optional.empty();
                    }
                    return Optional.of(ValueSet.ofRanges(ranges.getSpan()));
                },
                discreteValues -> {
                    if (discreteValues.getValues().size() <= 32) {
                        return Optional.empty();
                    }
                    return Optional.of(ValueSet.all(values.getType()));
                },
                allOrNone -> Optional.empty())
                .orElse(values);
        return Domain.create(simplifiedValueSet, nullAllowed);
    }
634940
@SuppressWarnings("rawtypes")
	public List mget(Object... keys) {
		Jedis jedis = getJedis();
		try {
			byte[][] keysBytesArray = keysToBytesArray(keys);
			List<byte[]> data = jedis.mget(keysBytesArray);
			return valueListFromBytesList(data);
		}
		finally {close(jedis);}
	}
773487
public static String bytesToString(byte[] bytes, boolean noCase) {
        char[] digits = noCase ? DIGITS_NOCASE : DIGITS;
        int digitsLength = digits.length;

        if (ArrayUtils.isEmpty(bytes)) {
            return String.valueOf(digits[0]);
        }

        StringBuilder strValue = new StringBuilder();
        int value = 0;
        int limit = Integer.MAX_VALUE >>> 8;
        int i = 0;

        do {
            while (i < bytes.length && value < limit) {
                value = (value << 8) + (0xFF & bytes[i++]);
            }

            while (value >= digitsLength) {
                strValue.append(digits[value % digitsLength]);
                value = value / digitsLength;
            }
        } while (i < bytes.length);

        if (value != 0 || strValue.length() == 0) {
            strValue.append(digits[value]);
        }

        return strValue.toString();
    }
1198357
private static byte[] toBytes(Object input) {
        if (input instanceof byte[]) {
            return (byte[]) input;
        } else if (input instanceof String) {
            String inputString = (String) input;
            return inputString.getBytes();
        } else if (input instanceof Long) {
            Long inputLong = (Long) input;
            return (inputLong == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputLong));
        } else if (input instanceof Integer) {
            Integer inputInt = (Integer) input;
            return (inputInt == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputInt));
        } else if (input instanceof BigInteger) {
            BigInteger inputBigInt = (BigInteger) input;
            return (inputBigInt.equals(BigInteger.ZERO)) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(inputBigInt);
        }
        throw new RuntimeException("Unsupported type: Only accepting String, Integer and BigInteger for now");
    }
788251
public static RangeSet split(Collection<RangeSet> rangeSets)
    {
        RangeSet result = new RangeSet();
        SortedSet<Integer> ss = new TreeSet<Integer>();
        for (RangeSet rs : rangeSets)
        {
            for (CharRange r : rs)
            {
                ss.add(r.getFrom());
                ss.add(r.getTo());
            }
        }
        Iterator<Integer> i = ss.iterator();
        if (i.hasNext())
        {
            int from = i.next();
            while (i.hasNext())
            {
                int to = i.next();
                if (from != to)
                {
                    for (RangeSet rs : rangeSets)
                    {
                        if (rs.contains(from, to))
                        {
                            result.add(from, to);
                            break;
                        }
                    }
                }
                from = to;
            }
        }
        return result;
    }
740561
RangeSet possibleMoves()
    {
        List<RangeSet> list = new ArrayList<>();
        for (NFAState<T> nfa : nfaSet)
        {
            list.add(nfa.getConditions());
        }
        return RangeSet.split(list);
    }
449399
public void setRange(String range) {
        String single = range.trim();
        int hyphenIndex = range.indexOf('-');

        if (hyphenIndex > 0) {
            this.start = rangeSingle(range.substring(0, hyphenIndex));
            this.end = rangeSingle(range.substring(hyphenIndex + 1));
        } else {
            int number = rangeSingle(range);
            if (number >= 0) { // first n attributes
                this.start = 0;
                this.end = number;
            } else { // last n attributes
                this.start = this.upperLimit + number > 0 ? this.upperLimit + number : 0;
                this.end = this.upperLimit - 1;
            }
        }
    }
343356
@SuppressWarnings("rawtypes")
	public Set zrangeByScore(Object key, double min, double max) {
		Jedis jedis = getJedis();
		try {
			Set<byte[]> data = jedis.zrangeByScore(keyToBytes(key), min, max);
			Set<Object> result = new LinkedHashSet<Object>();	// 有序集合必须 LinkedHashSet
			valueSetFromBytesSet(data, result);
			return result;
		}
		finally {close(jedis);}
	}