ObjectId.fromHexString constructor

ObjectId.fromHexString(
  1. String hexString
)

Creates ObjectId from hex string.

Can be helpful for mapping hex strings returned from API / MongoDB to ObjectId instances.

Example usage:

final id = ObjectId();
final id2 = ObjectId.fromHexString(id.hexString);
print(id == id2) // => true

ObjectId structure:

  4 byte timestamp    5 byte process unique   3 byte counter
|<----------------->|<---------------------->|<------------>|
|----|----|----|----|----|----|----|----|----|----|----|----|
0                   4                   8                   12

Implementation

ObjectId.fromHexString(String hexString) {
  ArgumentError.checkNotNull(hexString, 'hexString');
  if (hexString.length != hexStringLength) {
    throw ArgumentError.value(
        hexString, 'hexString', 'Provided hexString has wrong length.');
  }

  final secondsSinceEpoch = int.parse(hexString.substring(0, 8), radix: 16);
  final millisecondsSinceEpoch = secondsSinceEpoch * 1000;

  final processUnique = int.parse(hexString.substring(8, 18), radix: 16);
  final counter = int.parse(hexString.substring(18, 24), radix: 16);

  /// cache this value
  _hexString = hexString;

  _initialize(millisecondsSinceEpoch, processUnique, counter);
}