UUID.fromString constructor

UUID.fromString(
  1. String value
)

Creates a new UUID from the string format encoding (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where xx is a hexadecimal number).

Implementation

factory UUID.fromString(String value) {
  // 16 or 32 bits UUID.
  if (value.length == 4 || value.length == 8) {
    final shortValue = int.tryParse(value, radix: 16);
    if (shortValue == null) {
      throw const FormatException('Invalid UUID string');
    }
    return UUID.short(shortValue);
  }
  var groups = value.split('-');
  if (groups.length != 5 ||
      groups[0].length != 8 ||
      groups[1].length != 4 ||
      groups[2].length != 4 ||
      groups[3].length != 4 ||
      groups[4].length != 12) {
    throw const FormatException('Invalid UUID string');
  }
  int group0, group1, group2, group3, group4;
  try {
    group0 = int.parse(groups[0], radix: 16);
    group1 = int.parse(groups[1], radix: 16);
    group2 = int.parse(groups[2], radix: 16);
    group3 = int.parse(groups[3], radix: 16);
    group4 = int.parse(groups[4], radix: 16);
  } catch (e) {
    throw const FormatException('Invalid UUID string');
  }
  return UUID([
    (group0 >> 24) & 0xff,
    (group0 >> 16) & 0xff,
    (group0 >> 8) & 0xff,
    (group0 >> 0) & 0xff,
    (group1 >> 8) & 0xff,
    (group1 >> 0) & 0xff,
    (group2 >> 8) & 0xff,
    (group2 >> 0) & 0xff,
    (group3 >> 8) & 0xff,
    (group3 >> 0) & 0xff,
    (group4 >> 40) & 0xff,
    (group4 >> 32) & 0xff,
    (group4 >> 24) & 0xff,
    (group4 >> 16) & 0xff,
    (group4 >> 8) & 0xff,
    (group4 >> 0) & 0xff,
  ]);
}