Exemple #1
0
  public V put(K key, V val) {
    if (root == null) {
      root = ctx().nf.mkLeaf(key, val);
      size++;
      return null;
    }
    if (!root.isInternal()) {
      int diffBit = ctx().chk.bitIndex(key, root.getKey());
      V oldVal = root.getValue();
      root = root.insert(diffBit, key, val, ctx());
      if (diffBit >= 0) {
        size++;
        return null;
      } else {
        return oldVal;
      }
    }

    final SearchResult<K, V> sr = search(root, key);
    final int diffBit = ctx().chk.bitIndex(key, sr.key(ctx()));
    final V out;
    if (diffBit >= 0) {
      out = null;
      size++;
    } else {
      out = sr.value(ctx());
    }

    if (sr.parent == null) {
      root = root.insert(diffBit, key, val, ctx());
      return out;
    } else if (diffBit < 0 || diffBit >= sr.parent.bit()) {
      switch (sr.pDirection) {
        case LEFT:
          sr.parent.setLeft(diffBit, key, val, ctx());
          return out;
        case RIGHT:
          sr.parent.setRight(diffBit, key, val, ctx());
          return out;
      }
    }

    if (diffBit < root.bit()) {
      root = root.insert(diffBit, key, val, ctx());
      return out;
    }

    Node<K, V> prev = root;
    Node<K, V> current = prev.nextNode(key, ctx());
    for (; ; ) {
      if (diffBit < current.bit()) {
        if (ctx().chk.isBitSet(key, prev.bit())) {
          prev.setRight(diffBit, key, val, ctx());
        } else {
          prev.setLeft(diffBit, key, val, ctx());
        }
        return out;
      } else {
        prev = current;
        current = current.nextNode(key, ctx());
      }
    }
  }