ArrayTagSet add()

in spectator-api/src/main/java/com/netflix/spectator/api/ArrayTagSet.java [107:141]


  ArrayTagSet add(String k, String v) {
    Preconditions.checkNotNull(k, "key");
    Preconditions.checkNotNull(v, "value");
    if (length == 0) {
      return new ArrayTagSet(new String[] {k, v});
    }

    int idx = 0;
    int cmp = -1;
    while (idx < length) {
      cmp = tags[idx].compareTo(k);
      if (cmp >= 0) {
        break;
      }
      idx += 2;
    }

    // Update an existing tag
    if (cmp == 0) {
      if (tags[idx + 1].equals(v)) {
        return this;
      }
      String[] newTags = Arrays.copyOf(tags, length);
      newTags[idx + 1] = v;
      return new ArrayTagSet(newTags);
    }

    String[] newTags = new String[length + 2];
    newTags[idx] = k;
    newTags[idx + 1] = v;

    System.arraycopy(tags, 0, newTags, 0, idx);
    System.arraycopy(tags, idx, newTags, idx + 2, length - idx);
    return new ArrayTagSet(newTags);
  }