/// <summary> /// If <paramref name="value"/> is <see langword="null"/> or empty, removes the entry with <paramref name="name"/> (if any). /// Otherwise, removes existing entries with <paramref name="name"/> and inserts an new entry. /// </summary> // Insertion sort should be sufficient. Generally we do not have tens of extra environment variables. public void InsertOrRemove(string name, string value) { EnvironmentVariableUtil.ValidateNameAndValue(name, value); var(start, end) = SearchMatchingElements(_array.AsSpan(0, _count), name); Debug.Assert(end >= start); if (string.IsNullOrEmpty(value)) { // Remove if (start == end) { // _array does not have any element with the name. Do nothing. } else { // Remove the matching elements. Array.Copy(_array, end, _array, start, _count - end); _count -= end - start; } } else { // Insert if (start == end) { // _array does not have any element with the name. Insert the new element. Array.Copy(_array, end, _array, end + 1, _count - end); _array[start] = new(name, value); _count++; } else if (end == start + 1) { // _array has exactly one element with the name. Just overwrite it. _array[start] = new(name, value); } else { // _array has multiple elements with the name. Overwrite the first one and remove the rest. _array[start] = new(name, value); Array.Copy(_array, end, _array, start + 1, _count - end); _count -= end - start - 1; } } }