put method

TraceState put(
  1. String key,
  2. String value
)

Creates a new TraceState with the given key-value pair added. If adding this pair would exceed the 32 key-value pair limit, the oldest entries are removed to make room.

Implementation

TraceState put(String key, String value) {
  if (!_isValidKey(key) || !_isValidValue(value)) {
    OTelErrorHandling.report(
        ArgumentError('Invalid TraceState key or value; entry ignored.'));
    return this;
  }
  final factory = OTelFactory.getOrCreateDefault();

  final newEntries = Map<String, String>.from(_entries);

  // If we already have this key, just update its value
  if (newEntries.containsKey(key)) {
    newEntries[key] = value;
    return factory.traceState(newEntries);
  }

  // If adding a new key would exceed the limit, remove the oldest entry
  if (newEntries.length >= _maxKeyValuePairs) {
    // Remove the first key to make room
    if (newEntries.isNotEmpty) {
      final oldestKey = newEntries.keys.first;
      newEntries.remove(oldestKey);
    }
  }

  newEntries[key] = value;
  return factory.traceState(newEntries);
}