glp-companion/lib/core/utils/uuid.dart

26 lines
934 B
Dart

import 'dart:math';
/// Generates a random RFC 4122 version 4 UUID string.
///
/// Example: `f47ac10b-58cc-4372-a567-0e02b2c3d479`.
///
/// The project deliberately avoids a `uuid` package dependency; these keys
/// are local-only record identifiers (recipe catalog, meal-plan slots), so a
/// `dart:math` pseudo-random source is sufficient and behaves identically on
/// Android, iOS, Web, macOS, and Windows.
String generateUuid([Random? random]) {
final rng = random ?? Random();
final bytes = List<int>.generate(16, (_) => rng.nextInt(256));
// Version 4 (random) + variant 10xx per RFC 4122 §4.4.
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
return '${hex.substring(0, 8)}-'
'${hex.substring(8, 12)}-'
'${hex.substring(12, 16)}-'
'${hex.substring(16, 20)}-'
'${hex.substring(20)}';
}