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) {
  if (hexString.length != hexStringLength) {
    throw ArgumentError.value(
      hexString,
      'hexString',
      'ObjectId hexString must be exactly $hexStringLength characters long.',
    );
  }

  for (var i = 0; i < byteLength; i++) {
    final o = i * 2;
    _bytes[i] = (_hexCharToNibble(hexString.codeUnitAt(o)) << 4) |
        _hexCharToNibble(hexString.codeUnitAt(o + 1));
  }

  _hexString = hexString;
}