receive method Null safety

HLC receive(
  1. HLC remote,
  2. {Duration? maximumDrift,
  3. int? now}
)

Synchronizes with a given remote clock.

If a maximumDrift is configured and the remote clock is sufficiently in the future, a TimeDriftException will be thrown.

The now parameter indicates the wall clock in milliseconds. It is primarily used for testing.

Implementation

HLC receive(
  HLC remote, {
  Duration? maximumDrift,
  int? now,
}) {
  now ??= DateTime.now().millisecondsSinceEpoch;
  final local = this;

  if (maximumDrift != null) {
    final drift = Duration(milliseconds: remote.timestamp - now);

    if (drift > maximumDrift) {
      throw TimeDriftException(
        drift: drift,
        maximumDrift: maximumDrift,
      );
    }
  }

  if (now > local.timestamp && now > remote.timestamp) {
    return copy(timestamp: now, count: 0);
  }

  if (local.timestamp < remote.timestamp) {
    return copy(timestamp: remote.timestamp, count: remote.count + 1);
  } else if (local.timestamp > remote.timestamp) {
    return copy(count: count + 1);
  } else {
    return copy(count: max(local.count, remote.count) + 1);
  }
}