Last active
August 29, 2015 14:18
-
-
Save alan-morey/01a8d5650ae173901a1a to your computer and use it in GitHub Desktop.
UUID Apex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Uuid { | |
static final String GROUP_SEP = '-'; | |
Uuid() {} | |
public static String randomUuid() { | |
String hex = EncodingUtil.convertToHex(Crypto.generateAesKey(128)); | |
return String.join(new String[] { | |
hex.substring(0,8), | |
hex.substring(8,12), | |
hex.substring(12,16), | |
hex.substring(16,20), | |
hex.substring(20) | |
}, GROUP_SEP); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UuidX { | |
static final Pattern SPLIT_PATTERN = Pattern.compile('\\p{XDigit}{8}(\\p{XDigit}{4}){3}\\p{XDigit}{12}'); | |
static final String GROUP_SEP = '-'; | |
static final String GROUP_FORMAT_STR = '{0}-{1}-{2}-{3}-{4}'; | |
UuidX() {} | |
public static String randomUuid_1() { | |
// 10,000 iterations (Start: 19:26:13.08, End: 19:26:14.50, Duration: 00:01.42) | |
return formatGroups(random128HexGrouped()); | |
} | |
public static String randomUuid_2() { | |
// 10,000 iterations (Start: 19:26:30.04, End: 19:26:30.05, Duration: 00:00.01) | |
return joinGroups(random128HexGrouped()); | |
} | |
public static String randomUuid_3() { | |
// 10,000 iterations (Start: 19:34:18.07, End: 19:34:19.11, Duration: 00:01.04) | |
return formatGroups(random128HexPatternSplitGrouped()); | |
} | |
public static String randomUuid_4() { | |
// 10,000 iterations (Start: 19:35:08.03, End: 19:35:09.18, Duration: 00:01.14) | |
return joinGroups(random128HexPatternSplitGrouped()); | |
} | |
static String formatGroups(String[] groups) { | |
return String.format(GROUP_FORMAT_STR, random128HexGrouped()); | |
} | |
static String joinGroups(String[] groups) { | |
return String.join(random128HexGrouped(), GROUP_SEP); | |
} | |
static String[] random128HexPatternSplitGrouped() { | |
return SPLIT_PATTERN.split(random128Hex()); | |
} | |
static String[] random128HexGrouped() { | |
String h = random128Hex(); | |
return new String[] { | |
h.substring(0,8), | |
h.substring(8,12), | |
h.substring(12,16), | |
h.substring(16,20), | |
h.substring(20) | |
}; | |
} | |
static String random128Hex() { | |
return EncodingUtil.convertToHex(Crypto.generateAesKey(128)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment