track method

void track(
  1. String name,
  2. Object resource
)

Register resource under name. Repeated (name, resource) pairs are deduped by identity — identical() walk over same-name refs (hash equality cannot stand in for object identity). Held via WeakReference so registration cannot prevent GC.

Primitives (num, String, bool, Symbol) and WeakReference construction failures are silently dropped and counted via droppedTargetsCount.

Implementation

void track(String name, Object resource) {
  if (!_isEnabled) return;
  // Primitives + records can't be weakly referenced.
  if (resource is num ||
      resource is String ||
      resource is bool ||
      resource is Symbol) {
    _droppedTargets++;
    return;
  }
  final WeakReference<Object> ref;
  try {
    ref = WeakReference<Object>(resource);
  } catch (_) {
    _droppedTargets++;
    return;
  }
  final hash = identityHashCode(resource);
  final bucket = _buckets.putIfAbsent(name, _Bucket.new);
  // Move to MRU position.
  _buckets.remove(name);
  _buckets[name] = bucket;
  // Identity-keyed dedup — Dart allows distinct objects to share an
  // identity hash, so hash-only would silently drop a colliding ref.
  for (final r in bucket.refs) {
    if (identical(r.ref.target, resource)) return;
  }
  final token = _FinalizerToken(name: name, identityHash: hash);
  bucket.add(
    _TrackedRef(
      ref: ref,
      identityHash: hash,
      firstSeenMicros: _clock().microsecondsSinceEpoch,
      token: token,
    ),
  );
  _finalizer.attach(resource, token, detach: token);
  _hasTracked = true;
  _enforceLruCap();
  _ensureSweepRunning();
}