Skip to main content

A hybrid logical clock

hlc_dart orders the events of many peers with no central server. The engine stamps every change with it, and you can use it on its own.

A hybrid logical clockSource ↗

A Dart program that moves a hybrid logical clock through a local event and a message from another peer, compares the two clocks and stores the clock.

Dart VMFlutter native✓ tested in CI
import 'dart:io';

import 'package:hlc_dart/hlc_dart.dart';

/// Moves a clock through a local event and a received message.
///
/// Returns whether the message comes before the clock, and whether the 64-bit
/// and the 8-byte forms read back the same clock, in this order.
List<bool> runClock() {
final clock = HybridLogicalClock.now();

// Another peer has its own clock: here it lives in the same program.
final received = HybridLogicalClock.now();

// A local event: an edit, a write, anything this peer does.
clock.localEvent(DateTime.now().millisecondsSinceEpoch);
stdout.writeln(clock); // <milliseconds>.<counter>

// A message from the other peer carries its clock.
clock.receiveEvent(DateTime.now().millisecondsSinceEpoch, received);

// After the receive, the message comes before this clock.
final ordered = received.happenedBefore(clock);
stdout.writeln(ordered); // true

// 64 bits, or 8 big-endian bytes.
final fromInt = HybridLogicalClock.fromInt64(clock.toInt64());
final fromBytes = HybridLogicalClock.fromUint8List(clock.toUint8List());
stdout.writeln(fromInt == clock && fromBytes == clock); // true

return [ordered, fromInt == clock, fromBytes == clock];
}

void main() {
runClock();
}

Key points

  • Call localEvent for what this peer does, and receiveEvent for every clock that comes from another peer.
  • After receiveEvent, the clock is ahead of the message: received.happenedBefore(clock) is true.
  • toInt64 needs 64-bit integers, so use it on native platforms. On the web, store the clock with toUint8List (8 bytes) or toString.