|
18 | 18 |
|
19 | 19 | #include <limits.h>
|
20 | 20 | #include <stdarg.h>
|
| 21 | +#include <stdbool.h> |
21 | 22 | #include <stdlib.h>
|
22 | 23 | #include <string.h>
|
| 24 | +#include <stdint.h> |
23 | 25 |
|
24 | 26 | #include <bson/bson-context-private.h>
|
25 | 27 | #include <bson/bson-oid.h>
|
@@ -74,39 +76,41 @@ BSON_MAYBE_UNUSED static const uint16_t gHexCharPairs[] = {
|
74 | 76 | #endif
|
75 | 77 | };
|
76 | 78 |
|
77 |
| - |
78 |
| -void |
79 |
| -bson_oid_init_sequence (bson_oid_t *oid, /* OUT */ |
80 |
| - bson_context_t *context) /* IN */ |
| 79 | +static inline void |
| 80 | +_oid_init (bson_oid_t *oid, bson_context_t *context, bool add_random) |
81 | 81 | {
|
82 |
| - uint32_t now = (uint32_t) (time (NULL)); |
83 |
| - |
| 82 | + BSON_ASSERT (oid); |
84 | 83 | if (!context) {
|
85 | 84 | context = bson_context_get_default ();
|
86 | 85 | }
|
87 | 86 |
|
88 |
| - now = BSON_UINT32_TO_BE (now); |
89 |
| - memcpy (&oid->bytes[0], &now, sizeof (now)); |
90 |
| - _bson_context_set_oid_seq64 (context, oid); |
| 87 | + const time_t now = time (NULL); |
| 88 | + // Big-endian encode the low 32 bits of the time as the leading 32 bits of the new OID |
| 89 | + oid->bytes[0] = (uint8_t) (now >> 24); |
| 90 | + oid->bytes[1] = (uint8_t) (now >> 16); |
| 91 | + oid->bytes[2] = (uint8_t) (now >> 8); |
| 92 | + oid->bytes[3] = (uint8_t) (now >> 0); |
| 93 | + // Maybe add randomness if the caller wants it |
| 94 | + if (add_random) { |
| 95 | + _bson_context_set_oid_rand (context, oid); |
| 96 | + _bson_context_set_oid_seq32 (context, oid); |
| 97 | + } else { |
| 98 | + _bson_context_set_oid_seq64 (context, oid); |
| 99 | + } |
91 | 100 | }
|
92 | 101 |
|
| 102 | +void |
| 103 | +bson_oid_init_sequence (bson_oid_t *oid, /* OUT */ |
| 104 | + bson_context_t *context) /* IN */ |
| 105 | +{ |
| 106 | + _oid_init (oid, context, false /* no randomness */); |
| 107 | +} |
93 | 108 |
|
94 | 109 | void
|
95 | 110 | bson_oid_init (bson_oid_t *oid, /* OUT */
|
96 | 111 | bson_context_t *context) /* IN */
|
97 | 112 | {
|
98 |
| - uint32_t now = (uint32_t) (time (NULL)); |
99 |
| - |
100 |
| - BSON_ASSERT (oid); |
101 |
| - |
102 |
| - if (!context) { |
103 |
| - context = bson_context_get_default (); |
104 |
| - } |
105 |
| - |
106 |
| - now = BSON_UINT32_TO_BE (now); |
107 |
| - memcpy (&oid->bytes[0], &now, sizeof (now)); |
108 |
| - _bson_context_set_oid_rand (context, oid); |
109 |
| - _bson_context_set_oid_seq32 (context, oid); |
| 113 | + _oid_init (oid, context, true /* add randomness */); |
110 | 114 | }
|
111 | 115 |
|
112 | 116 |
|
|
0 commit comments