1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
/*
* The MIT License (MIT)
* Copyright (c) 2018-2022 Joern Huxhorn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Copyright 2018-2022 Joern Huxhorn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#![doc(html_root_url = "https://docs.rs/rusty_ulid/1.0.0")]
#![deny(
anonymous_parameters,
bare_trait_objects,
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unused_import_braces,
unused_qualifications,
unused_results,
variant_size_differences
)]
#![warn(clippy::all)]
//#![deny(clippy::pedantic)]
#![forbid(unsafe_code)]
#![allow(unknown_lints)]
//! # ULID - Universally Unique Lexicographically Sortable Identifier
//!
//! UUID can be suboptimal for many uses-cases because:
//!
//! - It isn't the most character efficient way of encoding 128 bits of randomness
//! - UUID v1/v2 is impractical in many environments, as it requires access to a unique, stable MAC address
//! - UUID v3/v5 requires a unique seed and produces randomly distributed IDs, which can cause fragmentation in many data structures
//! - UUID v4 provides no other information than randomness which can cause fragmentation in many data structures
//!
//! Instead, herein is proposed [ULID][ulidspec]:
//!
//! `01ARZ3NDEKTSV4RRFFQ69G5FAV`
//!
//! - 128-bit compatibility with UUID
//! - 1.21e+24 unique ULIDs per millisecond
//! - Lexicographically sortable!
//! - Canonically encoded as a 26 character string, as opposed to the 36 character UUID
//! - Uses [Crockford's base32][crockford] for better efficiency and readability (5 bits per character)
//! - Case insensitive
//! - No special characters (URL safe)
//! - Monotonic sort order (correctly detects and handles the same millisecond)
//!
//! ## Specification
//!
//! Below is the current specification of [ULID][ulidspec] as implemented in this crate.
//!
//!
//! ```text
//! 01AN4Z07BY 79KA1307SR9X4MV3
//!
//! |----------| |----------------|
//! Timestamp Randomness
//! 48bits 80bits
//! ```
//!
//! ### Components
//!
//! #### Timestamp
//! - 48 bit integer
//! - UNIX-time in milliseconds
//! - Won't run out of space until `+10889-08-02T05:31:50.655Z`.
//!
//! #### Randomness
//! - 80 bits
//! - Cryptographically secure source of randomness, if possible
//!
//! ### Sorting
//!
//! The left-most character must be sorted first, and the right-most character
//! sorted last (lexical order). The default ASCII character set must be used.
//! Within the same millisecond, sort order is not guaranteed
//!
//! ### Canonical String Representation
//!
//! ```text
//! ttttttttttrrrrrrrrrrrrrrrr
//!
//! where
//! t is Timestamp (10 characters)
//! r is Randomness (16 characters)
//! ```
//!
//! ### Encoding
//!
//! [Crockford's Base32][crockford] is used as shown.
//! This alphabet excludes the letters I, L, O, and U to avoid confusion and abuse.
//!
//! `0123456789ABCDEFGHJKMNPQRSTVWXYZ`
//!
//! ### Monotonicity
//!
//! When generating a ULID within the same millisecond, we can provide some
//! guarantees regarding sort order. Namely, if the same millisecond is detected,
//! the `random` component is incremented by 1 bit in the least significant bit position
//! (with carrying).
//!
//! If, in the extremely unlikely event that, you manage to generate more than 2<sup>80</sup>
//! ULIDs within the same millisecond, or cause the random component to overflow with less,
//! the generation will fail.
//!
//! ### Overflow Errors when Parsing Base32 Strings
//!
//! Technically, a 26-character Base32 encoded string can contain 130 bits of
//! information, whereas a ULID must only contain 128 bits. Therefore, the largest
//! valid ULID encoded in Base32 is `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, which corresponds to
//! an epoch time of `281474976710655` or `2 ^ 48 - 1`.
//!
//! Any attempt to decode or encode a ULID larger than this should be rejected by all
//! implementations, to prevent overflow bugs.
//!
//! ### Binary Layout and Byte Order
//!
//! The components are encoded as 16 octets. Each component is encoded with the
//! Most Significant Byte first (network byte order).
//!
//! ```text
//! 0 1 2 3
//! 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! | 32_bit_uint_time_high |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! | 16_bit_uint_time_low | 16_bit_uint_random |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! | 32_bit_uint_random |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! | 32_bit_uint_random |
//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//! ```
//!
//! [ulidspec]: https://github.com/ulid/spec
//! [crockford]: https://crockford.com/wrmg/base32.html
#[cfg(feature = "time")]
use time::OffsetDateTime;
#[cfg(feature = "chrono")]
use chrono::prelude::{DateTime, TimeZone, Utc};
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
/// Contains functions for encoding and decoding of
/// [crockford Base32][crockford] strings.
///
/// [crockford]: https://crockford.com/wrmg/base32.html
pub mod crockford;
pub use crate::crockford::DecodingError;
/// Returns the number of non-leap milliseconds since January 1, 1970 0:00:00 UTC
/// (aka "UNIX timestamp").
#[cfg(all(feature = "rand", any(feature = "time", feature = "chrono")))]
fn unix_epoch_ms() -> u64 {
#[cfg(feature = "chrono")]
{
let now: DateTime<Utc> = Utc::now();
now.timestamp_millis() as u64
}
#[cfg(all(feature = "time", not(feature = "chrono")))]
{
let now = OffsetDateTime::now_utc();
now.unix_timestamp() as u64 * 1_000 + now.millisecond() as u64
}
}
/// Returns a new ULID string.
///
/// This function is a shortcut for `Ulid::generate().to_string()`.
///
/// # Example
/// ```
/// # use rusty_ulid::generate_ulid_string;
/// let ulid_string = generate_ulid_string();
///
/// // every ulid has exactly 26 characters
/// assert_eq!(ulid_string.len(), 26);
/// ```
#[cfg(all(feature = "rand", any(feature = "chrono", feature = "time")))]
#[must_use]
pub fn generate_ulid_string() -> String {
Ulid::generate().to_string()
}
/// Returns new ULID bytes.
///
/// This function is a shortcut for `Ulid::generate().into()`.
///
/// # Example
/// ```
/// # use rusty_ulid::generate_ulid_bytes;
/// let ulid_bytes = generate_ulid_bytes();
///
/// // a binary ulid has exactly 16 bytes
/// assert_eq!(ulid_bytes.len(), 16);
/// ```
#[cfg(all(feature = "rand", any(feature = "chrono", feature = "time")))]
#[must_use]
pub fn generate_ulid_bytes() -> [u8; 16] {
Ulid::generate().into()
}
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Hash)]
/// The ULID data type.
pub struct Ulid {
value: (u64, u64),
}
impl Ulid {
/// Creates a new ULID.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::generate();
///
/// assert_ne!(0, ulid.timestamp());
///
/// let ulid_string = ulid.to_string();
/// // every ulid has exactly 26 characters
/// assert_eq!(ulid_string.len(), 26);
/// ```
///
/// # Panics
///
/// Panics if called after `+10889-08-02T05:31:50.655Z`.
#[cfg(all(feature = "rand", any(feature = "chrono", feature = "time")))]
#[must_use]
pub fn generate() -> Self {
Self::from_timestamp_with_rng(unix_epoch_ms(), &mut rand::thread_rng())
}
/// Creates the next monotonic ULID for the given `previous_ulid`.
///
/// If the random part of `previous_ulid` would overflow, this function returns a ULID with
/// the random part set to zero.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_monotonic(previous_ulid);
///
/// assert_ne!(0, ulid.timestamp());
/// ```
///
/// # Panics
///
/// Panics if called after `+10889-08-02T05:31:50.655Z`.
#[cfg(all(feature = "rand", any(feature = "chrono", feature = "time")))]
#[must_use]
pub fn next_monotonic(previous_ulid: Self) -> Self {
Self::next_monotonic_from_timestamp_with_rng(
previous_ulid,
unix_epoch_ms(),
&mut rand::thread_rng(),
)
}
/// Creates the next strictly monotonic ULID for the given `previous_ulid`.
///
/// If the random part of `previous_ulid` would overflow, this function returns `None`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_strictly_monotonic(previous_ulid);
///
/// if let Some(ulid) = ulid {
/// assert_ne!(0, ulid.timestamp());
/// }
/// ```
///
/// # Panics
///
/// Panics if called after `+10889-08-02T05:31:50.655Z`.
#[cfg(all(feature = "rand", any(feature = "chrono", feature = "time")))]
#[must_use]
pub fn next_strictly_monotonic(previous_ulid: Self) -> Option<Self> {
Self::next_strictly_monotonic_from_timestamp_with_rng(
previous_ulid,
unix_epoch_ms(),
&mut rand::thread_rng(),
)
}
/// Creates a new ULID with the given `timestamp` obtaining randomness from
/// `rng`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from_timestamp_with_rng(0, &mut rand::thread_rng());
///
/// let timestamp = ulid.timestamp();
///
/// assert_eq!(timestamp, 0);
/// ```
///
/// # Panics
///
/// Panics if `timestamp` is larger than `0xFFFF_FFFF_FFFF`.
#[cfg(feature = "rand")]
pub fn from_timestamp_with_rng<R>(timestamp: u64, rng: &mut R) -> Self
where
R: rand::Rng,
{
if (timestamp & 0xFFFF_0000_0000_0000) != 0 {
panic!("ULID does not support timestamps after +10889-08-02T05:31:50.655Z");
}
let high = timestamp << 16 | u64::from(rng.gen::<u16>());
let low = rng.gen::<u64>();
let value = (high, low);
Self { value }
}
/// Creates the next monotonic ULID with the given `previous_ulid`, `timestamp`
/// obtaining randomness from `rng`.
///
/// If the random part of `previous_ulid` would overflow, this function returns a ULID with
/// the random part set to zero.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// assert_eq!(ulid, Ulid::from(1));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// assert_eq!(ulid, Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// // overflow results in zero random part
/// assert_eq!(ulid, Ulid::from(0));
/// ```
///
/// # Panics
///
/// Panics if `timestamp` is larger than `0xFFFF_FFFF_FFFF`.
#[cfg(feature = "rand")]
pub fn next_monotonic_from_timestamp_with_rng<R>(
previous_ulid: Self,
timestamp: u64,
rng: &mut R,
) -> Self
where
R: rand::Rng,
{
Self::next_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
timestamp,
rng,
None,
)
}
/// Creates the next monotonic ULID with the given `previous_ulid`, `timestamp`
/// obtaining randomness from `rng`. If a new ULID is created instead of simply
/// incrementing the previous ULID, then `postprocessor` is used (if available)
/// to transform the new ULID before returning it.
///
/// If the random part of `previous_ulid` would overflow, this function returns a ULID with
/// the random part set to zero.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(Some(previous_ulid), 0, &mut rand::thread_rng(), None);
///
/// assert_eq!(ulid, Ulid::from(1));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(Some(previous_ulid), 0, &mut rand::thread_rng(), None);
///
/// assert_eq!(ulid, Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(Some(previous_ulid), 0, &mut rand::thread_rng(), None);
///
/// // overflow results in zero random part
/// assert_eq!(ulid, Ulid::from(0));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// fn postprocessor_fn(ulid: Ulid) -> Ulid {
/// // zero out lowest 32 bits
/// Ulid::from(u128::from(ulid) & 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_0000_0000)
/// }
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(
/// Some(previous_ulid),
/// 1,
/// &mut rand::thread_rng(),
/// Some(&postprocessor_fn),
/// );
///
/// assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
///
/// let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(
/// None,
/// 1,
/// &mut rand::thread_rng(),
/// Some(&postprocessor_fn),
/// );
///
/// assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
/// assert_ne!(0, u128::from(ulid));
/// ```
///
/// # Panics
///
/// Panics if `timestamp` is larger than `0xFFFF_FFFF_FFFF`.
#[cfg(feature = "rand")]
pub fn next_monotonic_from_timestamp_with_rng_and_postprocessor<R>(
previous_ulid: Option<Self>,
timestamp: u64,
rng: &mut R,
postprocessor: Option<&dyn Fn(Self) -> Self>,
) -> Self
where
R: rand::Rng,
{
if let Some(previous_ulid) = previous_ulid {
if previous_ulid.timestamp() == timestamp {
return previous_ulid.increment();
}
}
let result = Self::from_timestamp_with_rng(timestamp, rng);
postprocessor.map_or(result, |postprocessor| postprocessor(result))
}
/// Creates the next strictly monotonic ULID with the given `previous_ulid`, `timestamp`
/// obtaining randomness from `rng`.
///
/// If the random part of `previous_ulid` would overflow, this function returns `None`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// assert_eq!(ulid, Some(Ulid::from(1)));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// assert_eq!(ulid, Some(Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF)));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng(previous_ulid, 0, &mut rand::thread_rng());
///
/// // overflow results in None
/// assert_eq!(ulid, None);
/// ```
///
/// # Panics
///
/// Panics if `timestamp` is larger than `0xFFFF_FFFF_FFFF`.
#[cfg(feature = "rand")]
pub fn next_strictly_monotonic_from_timestamp_with_rng<R>(
previous_ulid: Self,
timestamp: u64,
rng: &mut R,
) -> Option<Self>
where
R: rand::Rng,
{
let result = Self::next_monotonic_from_timestamp_with_rng(previous_ulid, timestamp, rng);
if previous_ulid < result {
Some(result)
} else {
None
}
}
/// Creates the next strictly monotonic ULID with the given `previous_ulid`, `timestamp`
/// obtaining randomness from `rng`.
///
/// If the random part of `previous_ulid` would overflow, this function returns `None`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
/// Some(previous_ulid),
/// 0,
/// &mut rand::thread_rng(),
/// None,
/// );
///
/// assert_eq!(ulid, Some(Ulid::from(1)));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
/// Some(previous_ulid),
/// 0,
/// &mut rand::thread_rng(),
/// None,
/// );
///
/// assert_eq!(
/// ulid,
/// Some(Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF))
/// );
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
/// Some(previous_ulid),
/// 0,
/// &mut rand::thread_rng(),
/// None,
/// );
///
/// // overflow results in None
/// assert_eq!(ulid, None);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// fn postprocessor_fn(ulid: Ulid) -> Ulid {
/// // zero out lowest 32 bits
/// Ulid::from(u128::from(ulid) & 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_0000_0000)
/// }
///
/// let previous_ulid = Ulid::from(0);
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
/// Some(previous_ulid),
/// 1,
/// &mut rand::thread_rng(),
/// Some(&postprocessor_fn),
/// );
/// let ulid = ulid.unwrap();
///
/// assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
///
/// let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
/// None,
/// 1,
/// &mut rand::thread_rng(),
/// Some(&postprocessor_fn),
/// );
/// let ulid = ulid.unwrap();
///
/// assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
/// assert_ne!(0, u128::from(ulid));
/// ```
///
/// # Panics
///
/// Panics if `timestamp` is larger than `0xFFFF_FFFF_FFFF`.
#[cfg(feature = "rand")]
pub fn next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor<R>(
previous_ulid: Option<Self>,
timestamp: u64,
rng: &mut R,
postprocessor: Option<&dyn Fn(Self) -> Self>,
) -> Option<Self>
where
R: rand::Rng,
{
let result = Self::next_monotonic_from_timestamp_with_rng_and_postprocessor(
previous_ulid,
timestamp,
rng,
postprocessor,
);
previous_ulid.map_or(Some(result), |previous_ulid| {
if previous_ulid < result {
Some(result)
} else {
None
}
})
}
/// Returns the timestamp of this ULID as number
/// of non-leap milliseconds since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
/// use std::str::FromStr;
///
/// let ulid = Ulid::from_str("01CAH7NXGRDJNE9B1NY7PQGYV7")?;
/// let timestamp = ulid.timestamp();
///
/// assert_eq!(timestamp, 1523144390168);
/// # Ok::<(), rusty_ulid::DecodingError>(())
/// ```
#[must_use]
pub fn timestamp(&self) -> u64 {
self.value.0 >> 16
}
/// Returns the timestamp of this ULID as a `DateTime<Utc>`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
/// use std::str::FromStr;
///
/// let ulid = Ulid::from_str("01CAH7NXGRDJNE9B1NY7PQGYV7")?;
/// let datetime = ulid.datetime();
///
/// assert_eq!(datetime.to_string(), "2018-04-07 23:39:50.168 UTC");
/// # Ok::<(), rusty_ulid::DecodingError>(())
/// ```
#[cfg(feature = "chrono")]
#[must_use]
pub fn datetime(&self) -> DateTime<Utc> {
let timestamp = self.timestamp();
let seconds: i64 = (timestamp / 1000) as i64;
let nanos: u32 = ((timestamp % 1000) * 1_000_000) as u32;
Utc.timestamp(seconds, nanos)
}
/// Returns the timestamp of this ULID as a `OffsetDateTime`.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
/// use std::str::FromStr;
///
/// let ulid = Ulid::from_str("01CAH7NXGRDJNE9B1NY7PQGYV7")?;
/// let datetime = ulid.offsetdatetime();
///
/// assert_eq!(datetime.to_string(), "2018-04-07 23:39:50.168 +00:00:00");
/// # Ok::<(), rusty_ulid::DecodingError>(())
/// ```
#[cfg(feature = "time")]
pub fn offsetdatetime(&self) -> OffsetDateTime {
OffsetDateTime::from_unix_timestamp_nanos((self.timestamp() * 1_000_000) as i128)
.expect("invalid or out-of-range datetime")
}
/// Returns a new ULID with the random part incremented by one.
///
/// Overflowing the random part resets it to zero without influencing
/// the timestamp.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0);
/// let incremented = ulid.increment();
///
/// assert_eq!(incremented, Ulid::from(1));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
/// let incremented = ulid.increment();
///
/// assert_eq!(incremented, Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF));
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
/// let incremented = ulid.increment();
///
/// assert_eq!(incremented, Ulid::from(0));
/// ```
#[must_use]
pub fn increment(self) -> Self {
const TIMESTAMP_PART_MASK: u128 = 0xFFFF_FFFF_FFFF_0000_0000_0000_0000_0000;
const RANDOM_PART_MASK: u128 = !TIMESTAMP_PART_MASK;
let value: u128 = self.into();
if value & RANDOM_PART_MASK == RANDOM_PART_MASK {
// overflow, set random part to zero
(value & TIMESTAMP_PART_MASK).into()
} else {
(value + 1).into()
}
}
/// Returns the string representaton of this ULID.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0);
///
/// assert_eq!(ulid.to_string(), "00000000000000000000000000");
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF);
///
/// assert_eq!(ulid.to_string(), "7ZZZZZZZZZZZZZZZZZZZZZZZZZ");
/// ```
#[allow(clippy::inherent_to_string_shadow_display)]
// impl fmt::Display is using this method
// https://github.com/rust-lang/rust-clippy/issues/4396
#[allow(clippy::wrong_self_convention)]
// 1.53.0 still requires clippy::wrong_self_convention
// 1.54.0-beta fixes this false positive
#[must_use]
pub fn to_string(&self) -> String {
let mut string = String::with_capacity(26);
crockford::append_crockford_u64_tuple(self.value, &mut string);
string
}
}
impl fmt::Display for Ulid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&self.to_string())
}
}
impl FromStr for Ulid {
type Err = DecodingError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = crockford::parse_crockford_u64_tuple(s)?;
Ok(Self { value })
}
}
impl From<[u8; 16]> for Ulid {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let bytes: [u8; 16] = [
/// 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
/// 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0, 0x0F,
/// ];
///
/// let ulid = Ulid::from(bytes);
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let bytes: [u8; 16] = [
/// 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
/// 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0, 0x0F,
/// ];
///
/// let ulid : Ulid = bytes.into();
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
/// ```
#[must_use]
fn from(bytes: [u8; 16]) -> Self {
#[rustfmt::skip]
let high = u64::from(bytes[0]) << 56
| u64::from(bytes[1]) << 48
| u64::from(bytes[2]) << 40
| u64::from(bytes[3]) << 32
| u64::from(bytes[4]) << 24
| u64::from(bytes[5]) << 16
| u64::from(bytes[6]) << 8
| u64::from(bytes[7]);
#[rustfmt::skip]
let low = u64::from(bytes[8]) << 56
| u64::from(bytes[9]) << 48
| u64::from(bytes[10]) << 40
| u64::from(bytes[11]) << 32
| u64::from(bytes[12]) << 24
| u64::from(bytes[13]) << 16
| u64::from(bytes[14]) << 8
| u64::from(bytes[15]);
let value = (high, low);
Self { value }
}
}
impl From<Ulid> for [u8; 16] {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// let bytes = <[u8; 16]>::from(ulid);
///
/// let expected_bytes: [u8; 16] = [
/// 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
/// 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0, 0x0F,
/// ];
///
/// assert_eq!(bytes, expected_bytes);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// let bytes: [u8; 16] = ulid.into();
///
/// let expected_bytes: [u8; 16] = [
/// 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
/// 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0, 0x0F,
/// ];
///
/// assert_eq!(bytes, expected_bytes);
/// ```
#[rustfmt::skip]
#[must_use]
fn from(ulid: Ulid) -> Self {
let value = ulid.value;
[
((value.0 >> 56) & 0xFF) as u8,
((value.0 >> 48) & 0xFF) as u8,
((value.0 >> 40) & 0xFF) as u8,
((value.0 >> 32) & 0xFF) as u8,
((value.0 >> 24) & 0xFF) as u8,
((value.0 >> 16) & 0xFF) as u8,
((value.0 >> 8) & 0xFF) as u8,
(value.0 & 0xFF) as u8,
((value.1 >> 56) & 0xFF) as u8,
((value.1 >> 48) & 0xFF) as u8,
((value.1 >> 40) & 0xFF) as u8,
((value.1 >> 32) & 0xFF) as u8,
((value.1 >> 24) & 0xFF) as u8,
((value.1 >> 16) & 0xFF) as u8,
((value.1 >> 8) & 0xFF) as u8,
(value.1 & 0xFF) as u8,
]
}
}
impl From<(u64, u64)> for Ulid {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let tuple = (0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F);
///
/// let ulid = Ulid::from(tuple);
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let tuple = (0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F);
///
/// let ulid : Ulid = tuple.into();
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
/// ```
#[must_use]
fn from(value: (u64, u64)) -> Self {
Self { value }
}
}
impl From<Ulid> for (u64, u64) {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// let tuple = <(u64, u64)>::from(ulid);
///
/// let expected_tuple = (0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(tuple, expected_tuple);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// let tuple : (u64, u64) = ulid.into();
///
/// let expected_tuple = (0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(tuple, expected_tuple);
/// ```
#[must_use]
fn from(ulid: Ulid) -> Self {
ulid.value
}
}
impl From<u128> for Ulid {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let value = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F;
///
/// let ulid = Ulid::from(value);
///
/// let expected_ulid = Ulid::from((0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F));
///
/// assert_eq!(ulid, expected_ulid);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let value = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F;
///
/// let ulid : Ulid = value.into();
///
/// let expected_ulid = Ulid::from((0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F));
///
/// assert_eq!(ulid, expected_ulid);
/// ```
#[must_use]
fn from(value: u128) -> Self {
let value = ((value >> 64) as u64, (value & 0xFFFF_FFFF_FFFF_FFFF) as u64);
Self { value }
}
}
impl From<Ulid> for u128 {
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from((0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F));
///
/// let value = <u128>::from(ulid);
///
/// let expected_value = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F;
///
/// assert_eq!(value, expected_value);
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
///
/// let ulid = Ulid::from((0x1122_3344_5566_7788, 0x99AA_BBCC_DDEE_F00F));
///
/// let value : u128 = ulid.into();
///
/// let expected_value = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F;
///
/// assert_eq!(value, expected_value);
/// ```
#[must_use]
fn from(ulid: Ulid) -> Self {
Self::from(ulid.value.0) << 64 | Self::from(ulid.value.1)
}
}
impl TryFrom<&[u8]> for Ulid {
type Error = DecodingError;
/// Returns a ULID for the given slice of bytes or `DecodingError::InvalidLength`
/// if the slice does not contain exactly 16 bytes.
///
/// # Examples
///
/// ```
/// use rusty_ulid::Ulid;
/// use std::convert::TryFrom;
/// use std::convert::TryInto;
///
/// let bytes: [u8; 18] = [
/// 0x00,
/// 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
/// 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0, 0x0F,
/// 0x00,
/// ];
///
/// let ulid : Ulid = Ulid::try_from(&bytes[1..17])?;
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
///
/// let ulid : Ulid = (&bytes[1..17]).try_into()?;
///
/// let expected_ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
///
/// assert_eq!(ulid, expected_ulid);
/// # Ok::<(), rusty_ulid::DecodingError>(())
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
/// use rusty_ulid::DecodingError;
/// use std::convert::TryFrom;
///
/// let mut bytes: [u8; 17] = [0; 17];
/// let result = Ulid::try_from(&bytes[0..]);
///
/// assert_eq!(result, Err(DecodingError::InvalidLength))
/// ```
///
/// ```
/// use rusty_ulid::Ulid;
/// use rusty_ulid::DecodingError;
/// use std::convert::TryFrom;
///
/// let mut bytes: [u8; 15] = [0; 15];
/// let result = Ulid::try_from(&bytes[0..]);
///
/// assert_eq!(result, Err(DecodingError::InvalidLength))
/// ```
fn try_from(bytes: &[u8]) -> Result<Self, DecodingError> {
if bytes.len() != 16 {
return Err(DecodingError::InvalidLength);
}
#[rustfmt::skip]
let high = u64::from(bytes[0]) << 56
| u64::from(bytes[1]) << 48
| u64::from(bytes[2]) << 40
| u64::from(bytes[3]) << 32
| u64::from(bytes[4]) << 24
| u64::from(bytes[5]) << 16
| u64::from(bytes[6]) << 8
| u64::from(bytes[7]);
#[rustfmt::skip]
let low = u64::from(bytes[8]) << 56
| u64::from(bytes[9]) << 48
| u64::from(bytes[10]) << 40
| u64::from(bytes[11]) << 32
| u64::from(bytes[12]) << 24
| u64::from(bytes[13]) << 16
| u64::from(bytes[14]) << 8
| u64::from(bytes[15]);
let value = (high, low);
Ok(Self { value })
}
}
#[cfg(feature = "serde")]
impl Serialize for Ulid {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
let bytes: [u8; 16] = (*self).into();
serializer.serialize_bytes(&bytes)
}
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Ulid {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if deserializer.is_human_readable() {
struct UlidStringVisitor;
impl<'vi> de::Visitor<'vi> for UlidStringVisitor {
type Value = Ulid;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a ULID string")
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<Ulid, E> {
value.parse::<Ulid>().map_err(E::custom)
}
}
deserializer.deserialize_str(UlidStringVisitor)
} else {
struct UlidBytesVisitor;
impl<'vi> de::Visitor<'vi> for UlidBytesVisitor {
type Value = Ulid;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "16 ULID bytes")
}
fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Ulid, E> {
Ulid::try_from(value).map_err(E::custom)
}
}
deserializer.deserialize_bytes(UlidBytesVisitor)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const PAST_TIMESTAMP: u64 = 1_481_195_424_879;
const PAST_TIMESTAMP_PART: &str = "01B3F2133F";
const MAX_TIMESTAMP: u64 = 0xFFFF_FFFF_FFFF;
const MAX_TIMESTAMP_PART: &str = "7ZZZZZZZZZ";
const MIN_TIMESTAMP: u64 = 0;
const MIN_TIMESTAMP_PART: &str = "0000000000";
#[test]
fn increment() {
single_increment(0x0000_0000_0000_0000_0000_0000_0000_0000, Ulid::from(1));
single_increment(
0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE,
Ulid::from(0xFFFF_FFFF_FFFF_FFFF_FFFF),
);
single_increment(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF, Ulid::from(0));
single_increment(
0x0000_0000_0001_0000_0000_0000_0000_0000,
Ulid::from(0x0000_0000_0001_0000_0000_0000_0000_0001),
);
single_increment(
0x0000_0000_0001_FFFF_FFFF_FFFF_FFFF_FFFF,
Ulid::from(0x0000_0000_0001_0000_0000_0000_0000_0000),
);
}
fn single_increment(input: u128, expected_result: Ulid) {
let input_value: Ulid = input.into();
let incremented = input_value.increment();
assert_eq!(incremented, expected_result);
assert_eq!(input_value.timestamp(), incremented.timestamp());
}
#[test]
fn from_string_to_string() {
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "0000000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "ZZZZZZZZZZZZZZZZ"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "123456789ABCDEFG"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "1000000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "1000000000000001"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "0001000000000001"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "0100000000000001"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(PAST_TIMESTAMP_PART.to_owned() + "0000000000000001"),
PAST_TIMESTAMP,
);
single_from_string_to_string(
&(MAX_TIMESTAMP_PART.to_owned() + "123456789ABCDEFG"),
MAX_TIMESTAMP,
);
single_from_string_to_string(
&(MIN_TIMESTAMP_PART.to_owned() + "123456789ABCDEFG"),
MIN_TIMESTAMP,
);
let largest_legal_ulid_string = "7ZZZZZZZZZZZZZZZZZZZZZZZZZ";
single_from_string_to_string(largest_legal_ulid_string, MAX_TIMESTAMP);
}
fn single_from_string_to_string(s: &str, timestamp: u64) {
let ulid = Ulid::from_str(s).unwrap();
assert_eq!(ulid.timestamp(), timestamp);
assert_eq!(ulid.to_string(), s);
}
#[test]
fn from_string_to_string_special_cases() {
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00i0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0010000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00I0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0010000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00l0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0010000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00L0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0010000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00o0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0000000000000000"),
PAST_TIMESTAMP,
);
single_from_string_to_string_special_case(
&(PAST_TIMESTAMP_PART.to_owned() + "00O0000000000000"),
&(PAST_TIMESTAMP_PART.to_owned() + "0000000000000000"),
PAST_TIMESTAMP,
);
}
fn single_from_string_to_string_special_case(s: &str, expected: &str, timestamp: u64) {
let ulid = Ulid::from_str(s).unwrap();
assert_eq!(ulid.timestamp(), timestamp);
assert_eq!(ulid.to_string(), expected);
}
#[test]
fn from_str_failure_too_long() {
let result = Ulid::from_str("123456789012345678901234567");
assert_eq!(result, Err(DecodingError::InvalidLength));
}
#[test]
fn from_str_failure_too_short() {
let result = Ulid::from_str("1234567890123456789012345");
assert_eq!(result, Err(DecodingError::InvalidLength));
}
#[test]
fn from_str_failure_invalid_unicode() {
let string = "012345678🦀0123456789012";
let result = Ulid::from_str(string);
assert_eq!(result, Err(DecodingError::InvalidChar('🦀')));
}
#[test]
fn from_str_failure_overflow() {
let smallest_overflowing_ulid_string = "80000000000000000000000000";
let result = Ulid::from_str(smallest_overflowing_ulid_string);
assert_eq!(result, Err(DecodingError::DataTypeOverflow));
}
#[test]
fn eq_cmp_sanity_checks() {
// yes, this is pretty paranoid.
use std::cmp::Ordering;
let ulid_one_low: Ulid = (0, 1).into();
let ulid_two_low: Ulid = (0, 2).into();
let ulid_one_high: Ulid = (1, 0).into();
let ulid_one_low_other: Ulid = (0, 1).into();
assert!(ulid_one_low.eq(&ulid_one_low));
assert_eq!(ulid_one_low.cmp(&ulid_one_low), Ordering::Equal);
assert_eq!(ulid_one_low, ulid_one_low_other);
assert!(ulid_one_low.eq(&ulid_one_low_other));
assert_eq!(ulid_one_low.cmp(&ulid_one_low_other), Ordering::Equal);
assert_ne!(ulid_one_low, ulid_two_low);
assert_ne!(ulid_two_low, ulid_one_low);
assert!(ulid_one_low < ulid_two_low);
assert!(ulid_two_low > ulid_one_low);
assert!(!ulid_one_low.eq(&ulid_two_low));
assert!(!ulid_two_low.eq(&ulid_one_low));
assert_eq!(ulid_one_low.cmp(&ulid_two_low), Ordering::Less);
assert_eq!(ulid_two_low.cmp(&ulid_one_low), Ordering::Greater);
assert_ne!(ulid_one_low, ulid_one_high);
assert_ne!(ulid_one_high, ulid_one_low);
assert!(!ulid_one_low.eq(&ulid_one_high));
assert!(!ulid_one_high.eq(&ulid_one_low));
assert_eq!(ulid_one_low.cmp(&ulid_one_high), Ordering::Less);
assert_eq!(ulid_one_high.cmp(&ulid_one_low), Ordering::Greater);
}
#[test]
fn hash_sanity_checks() {
// yes, this is also pretty paranoid.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let ulid_one_low: Ulid = (0, 1).into();
let ulid_two_low: Ulid = (0, 2).into();
let ulid_one_high: Ulid = (1, 0).into();
let ulid_one_low_other: Ulid = (0, 1).into();
let mut hasher_one_low = DefaultHasher::new();
ulid_one_low.hash(&mut hasher_one_low);
let hash_one_low = hasher_one_low.finish();
let mut hasher_one_low_other = DefaultHasher::new();
ulid_one_low_other.hash(&mut hasher_one_low_other);
let hash_one_low_other = hasher_one_low_other.finish();
let mut hasher_two_low = DefaultHasher::new();
ulid_two_low.hash(&mut hasher_two_low);
let hash_two_low = hasher_two_low.finish();
let mut hasher_one_high = DefaultHasher::new();
ulid_one_high.hash(&mut hasher_one_high);
let hash_one_high = hasher_one_high.finish();
// this must be true
assert_eq!(hash_one_low, hash_one_low_other);
// this should be true in case of a reasonable DefaultHasher implementation
assert_ne!(hash_one_low, hash_two_low);
assert_ne!(hash_one_low, hash_one_high);
}
#[cfg(not(miri))] // expected panic
#[cfg(feature = "rand")]
#[test]
#[should_panic(expected = "ULID does not support timestamps after +10889-08-02T05:31:50.655Z")]
fn y10889_bug() {
use rand::rngs::mock::StepRng;
let mut mock_rng = StepRng::new(0, 0);
let _ = Ulid::from_timestamp_with_rng(0x0001_0000_0000_0000, &mut mock_rng);
}
#[cfg(feature = "rand")]
#[test]
fn test_from_timestamp_with_rng() {
use rand::rngs::mock::StepRng;
let mut mock_rng = StepRng::new(0, 0);
let ulid = Ulid::from_timestamp_with_rng(0xFFFF_FFFF_FFFF, &mut mock_rng);
let ulid_value: u128 = ulid.into();
assert_eq!(ulid_value, 0xFFFF_FFFF_FFFF_0000_0000_0000_0000_0000);
let mut mock_rng = StepRng::new(0xF00F, 0);
let ulid = Ulid::from_timestamp_with_rng(0, &mut mock_rng);
let ulid_value: u128 = ulid.into();
assert_eq!(ulid_value, 0x0000_0000_0000_F00F_0000_0000_0000_F00F);
}
#[cfg(feature = "rand")]
#[test]
fn test_next_monotonic_from_timestamp_with_rng_and_postprocessor() {
fn postprocessor_fn(ulid: Ulid) -> Ulid {
// zero out lowest 32 bits
Ulid::from(u128::from(ulid) & 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_0000_0000)
}
let previous_ulid = Ulid::from(0);
let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
1,
&mut rand::thread_rng(),
Some(&postprocessor_fn),
);
assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
let ulid = Ulid::next_monotonic_from_timestamp_with_rng_and_postprocessor(
None,
1,
&mut rand::thread_rng(),
Some(&postprocessor_fn),
);
assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
assert_ne!(0, u128::from(ulid));
}
#[cfg(feature = "rand")]
#[test]
fn test_next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor_overflow() {
let previous_ulid = Ulid::from(0);
let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
0,
&mut rand::thread_rng(),
None,
);
assert_eq!(ulid, Some(Ulid::from(1)));
let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFE);
let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
0,
&mut rand::thread_rng(),
None,
);
assert_eq!(
ulid,
Some(Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF))
);
let previous_ulid = Ulid::from(0x0000_0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF);
let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
0,
&mut rand::thread_rng(),
None,
);
// overflow results in None
assert_eq!(ulid, None);
}
#[cfg(feature = "rand")]
#[test]
fn test_next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor() {
fn postprocessor_fn(ulid: Ulid) -> Ulid {
// zero out lowest 32 bits
Ulid::from(u128::from(ulid) & 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_0000_0000)
}
let previous_ulid = Ulid::from(0);
let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
Some(previous_ulid),
1,
&mut rand::thread_rng(),
Some(&postprocessor_fn),
);
let ulid = ulid.unwrap();
assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
let ulid = Ulid::next_strictly_monotonic_from_timestamp_with_rng_and_postprocessor(
None,
1,
&mut rand::thread_rng(),
Some(&postprocessor_fn),
);
let ulid = ulid.unwrap();
assert_eq!(0, u128::from(ulid) & 0xFFFF_FFFF);
assert_ne!(0, u128::from(ulid));
}
}
#[cfg(all(feature = "doc-comment", feature = "rand", feature = "chrono"))]
mod doc_tests {
use doc_comment::doctest;
doctest!("../README.md", readme);
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use super::*;
use serde_test::{assert_de_tokens_error, assert_tokens, Compact, Readable, Token};
#[test]
fn test_serde_readable() {
use serde_test::Configure;
let ulid = Ulid::from_str("7ZZZZZZZZZZZZZZZZZZZZZZZZZ").unwrap();
assert_tokens(
&ulid.readable(),
&[Token::Str("7ZZZZZZZZZZZZZZZZZZZZZZZZZ")],
);
let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
assert_tokens(
&ulid.readable(),
&[Token::Str("0H48SM8NB6EY49KANVSKEYXW0F")],
);
}
#[test]
fn test_serde_compact() {
use serde_test::Configure;
let ulid = Ulid::from_str("7ZZZZZZZZZZZZZZZZZZZZZZZZZ").unwrap();
assert_tokens(
&ulid.compact(),
&[Token::Bytes(&[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF,
])],
);
let ulid = Ulid::from(0x1122_3344_5566_7788_99AA_BBCC_DDEE_F00F);
assert_tokens(
&ulid.compact(),
&[Token::Bytes(&[
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
0xF0, 0x0F,
])],
);
}
#[test]
fn test_de_readable_error() {
assert_de_tokens_error::<Readable<Ulid>>(
&[Token::Bytes(&[
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
0xF0, 0x0F,
])],
"invalid type: byte array, expected a ULID string",
);
assert_de_tokens_error::<Readable<Ulid>>(
&[Token::Str("0H48SM8NB6EY49KANUSKEYXW0F")],
"invalid character 'U'",
);
assert_de_tokens_error::<Readable<Ulid>>(
&[Token::Str("0H48SM8NB6EY49KANVSKEYXW0FF")],
"invalid length",
);
assert_de_tokens_error::<Readable<Ulid>>(
&[Token::Str("0H48SM8NB6EY49KANVSKEYXW0")],
"invalid length",
);
assert_de_tokens_error::<Readable<Ulid>>(
&[Token::Str("80000000000000000000000000")],
"data type overflow",
);
}
#[test]
fn test_de_compact_error() {
assert_de_tokens_error::<Compact<Ulid>>(
&[Token::Str("0H48SM8NB6EY49KANVSKEYXW0F")],
"invalid type: string \"0H48SM8NB6EY49KANVSKEYXW0F\", expected 16 ULID bytes",
);
assert_de_tokens_error::<Compact<Ulid>>(
&[Token::Bytes(&[
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
0xF0, 0x0F, 0xFF,
])],
"invalid length",
);
assert_de_tokens_error::<Compact<Ulid>>(
&[Token::Bytes(&[
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
0xF0,
])],
"invalid length",
);
}
}