put method

V? put(
  1. K key,
  2. V value
)

Inserts or replaces a key-value pair. Returns the previous value if the key already existed.

Implementation

V? put(K key, V value) {
  final objHash = key.hashCode;
  final groupIdx = _groupIndex(objHash, _groups.length);

  final groupPos = _groups[groupIdx];
  var cursor = groupPos;

  while (cursor > 0) {
    if (_chainHash[cursor] == objHash && key == _chainKey[cursor]) {
      final prev = _chainVal[cursor];
      _chainKey[cursor] = key;
      _chainVal[cursor] = value;
      return prev;
    }
    cursor = _chainNext[cursor];
  }

  int newPos;
  if (_chainRemoved > 0) {
    newPos = _chainRemoved;
    _chainRemoved = _chainNext[newPos];

    _chainNext[newPos] = groupPos;
    _chainHash[newPos] = objHash;
    _chainKey[newPos] = key;
    _chainVal[newPos] = value;
  } else {
    newPos = _chainLength;

    _addEntry(groupPos, objHash, key, value);
  }

  _groups[groupIdx] = newPos;
  _groupsSizes[groupIdx]++;
  _size++;

  _checkRehashNeeded();
  return null;
}