Skip to content

Commit

Permalink
Implemented Twitter's Snowflake ID generation and parsing funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
iWas-Coder committed Dec 6, 2024
1 parent cbaec1d commit 7087dfc
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions carbon.h
Original file line number Diff line number Diff line change
Expand Up @@ -491,9 +491,16 @@ CARBON_API u32 carbon_crypto_crc32(const u8 *in, const usz in_size);
** || Time ||
** $$==================$$
*/
typedef struct {
u64 timestamp;
u64 random;
} CBN_SnowflakeComponents;

CARBON_API f64 carbon_time_get(void);
CARBON_API char *carbon_time_get_iso8601(void);
CARBON_API void carbon_time_sleep(u64 ms);
CARBON_API u64 carbon_time_snowflake_get(void);
CARBON_API CBN_SnowflakeComponents carbon_time_snowflake_parse(u64 snowflake);

/*
** $$===================$$
Expand Down
25 changes: 25 additions & 0 deletions src/carbon_time.c
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,28 @@ void carbon_time_sleep(u64 ms) {
sleep(ms / 1e3);
#endif
}

u64 carbon_time_snowflake_get(void) {
u64 timestamp = (u64) carbon_time_get() & ((1ULL << 42) - 1);
carbon_math_mt19937_64_srand(timestamp);
u64 random = carbon_math_mt19937_64_rand() % (1ULL << 22);
/*
** [1][TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT][RRRRRRRRRRRRRRRRRRRRRR]
** ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
** | ^ ^
** | | |------- 22-bit random number at pos. [21..0]
** | |
** | |------- 42-bit Timestamp at pos. [62..22]
** |
** |------- Unused Most-Significant-Bit (MSB) set to 1 at pos. 63
** (1ULL << 60 == 2^60 == 19 digits)
*/
return (1ULL << 60) | (timestamp << 22) | random;
}

CBN_SnowflakeComponents carbon_time_snowflake_parse(u64 snowflake) {
return (CBN_SnowflakeComponents) {
.timestamp = ((snowflake >> 22) & ((1ULL << 42) - 1)) & ((1ULL << 32) - 1),
.random = snowflake & ((1ULL << 22) - 1)
};
}
11 changes: 11 additions & 0 deletions test/carbon_time_test.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) Wasym A. Alonso. All Rights Reserved.

#include <carbon.h>

CARBON_TEST(carbon_time, snowflake) {
CBN_SnowflakeComponents cmps = carbon_time_snowflake_parse(1160192133117220889);
carbon_should_be_u64(1733452918, cmps.timestamp);
carbon_should_be_u64(2594841, cmps.random);
return CARBON_OK;
}

0 comments on commit 7087dfc

Please sign in to comment.