snowflake_me 2.1.0

A distributed unique ID generator inspired by Twitter's Snowflake
Documentation
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
// Copyright 2022 houseme
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[cfg(feature = "std")]
use crate::ClockDriftStrategy;
use crate::{SnowflakeId, error::*, snowflake::Snowflake};
#[cfg(feature = "std")]
use std::time::Duration;
#[cfg(feature = "std")]
use std::{
    collections::HashSet,
    sync::{Mutex, atomic::Ordering},
};
use std::{sync::Arc, thread, time::Instant};
#[cfg(feature = "std")]
use thiserror::Error;

#[cfg(feature = "std")]
#[test]
fn test_next_id() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;
    assert!(sf.next_id().is_ok());
    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_once() -> Result<(), BoxDynError> {
    let start_instant = Instant::now();
    let now = crate::time::current_millis();
    let expected_machine_id = 10u64;
    let expected_data_center_id = 5u64;

    let sf = Snowflake::builder()
        .start_time(now)
        .machine_id(&|| Ok(expected_machine_id as u16))
        .data_center_id(&|| Ok(expected_data_center_id as u16))
        .finalize()?;

    let sleep_duration_ms = 500;
    thread::sleep(Duration::from_millis(sleep_duration_ms));

    let id = sf.next_id()?;
    let elapsed_ms = start_instant.elapsed().as_millis() as i64;
    let parts = sf.decompose(id);

    let actual_time = parts.time;
    // parts.time is the milliseconds elapsed since start_time, captured right
    // before the sleep above. We compare it against an independent monotonic
    // measurement rather than the raw sleep duration: thread::sleep only
    // guarantees sleeping *at least* the requested duration, and the test
    // runner / OS scheduler (notably on macOS) can add noticeable overhead.
    let diff = actual_time as i64 - elapsed_ms;
    assert!(
        diff.abs() <= 100,
        "unexpected time difference: actual={}ms, elapsed={}ms",
        actual_time,
        elapsed_ms
    );

    assert_eq!(
        parts.machine_id, expected_machine_id,
        "Unexpected machine id"
    );
    assert_eq!(
        parts.data_center_id, expected_data_center_id,
        "Unexpected data center id"
    );

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_run_for_1s() -> Result<(), BoxDynError> {
    let now = crate::time::current_millis();
    let start_time = now;
    let expected_machine_id = 15u64;

    let sf = Snowflake::builder()
        .start_time(now)
        .machine_id(&|| Ok(expected_machine_id as u16))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    let mut last_id = SnowflakeId::new(0);
    let mut max_sequence: u64 = 0;

    let initial = crate::time::current_millis();
    let mut current = initial;
    while current - initial < 1000 {
        current = crate::time::current_millis();

        let id = sf.next_id()?;
        let parts = sf.decompose(id);

        assert!(
            id > last_id,
            "duplicated id (id: {}, last_id: {})",
            id,
            last_id
        );
        last_id = id;

        let actual_time = parts.time;
        let expected_time_range = current - start_time;
        assert!(
            (actual_time as i64 - expected_time_range).abs() <= 50,
            "unexpected time difference: actual={}, expected_range={}",
            actual_time,
            expected_time_range
        );

        if max_sequence < parts.sequence {
            max_sequence = parts.sequence;
        }

        assert_eq!(
            parts.machine_id, expected_machine_id,
            "unexpected machine id: {}",
            parts.machine_id
        );
    }

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_threads_uniqueness() -> Result<(), BoxDynError> {
    let sf = Arc::new(
        Snowflake::builder()
            .machine_id(&|| Ok(1))
            .data_center_id(&|| Ok(2))
            .finalize()?,
    );
    let ids = Arc::new(Mutex::new(HashSet::new()));
    let mut children = Vec::new();
    let num_threads = 10;
    let ids_per_thread = 10_000;

    for _ in 0..num_threads {
        let thread_sf = Arc::clone(&sf);
        let thread_ids = Arc::clone(&ids);
        children.push(thread::spawn(move || {
            let mut local_ids = Vec::with_capacity(ids_per_thread);
            for _ in 0..ids_per_thread {
                local_ids.push(thread_sf.next_id().unwrap());
            }
            let mut ids_lock = thread_ids.lock().unwrap();
            for id in local_ids {
                assert!(ids_lock.insert(id), "Duplicate ID detected: {id}");
            }
        }));
    }

    for child in children {
        child.join().expect("Child thread panicked");
    }

    let final_count = ids.lock().unwrap().len();
    assert_eq!(final_count, num_threads * ids_per_thread);
    println!(
        "Successfully verified {} unique IDs across {} threads.",
        final_count, num_threads
    );

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_generate_10_ids() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(30))
        .data_center_id(&|| Ok(1))
        .finalize()?;
    let mut ids = HashSet::new();
    for _ in 0..10 {
        let id = sf.next_id()?;
        assert!(ids.insert(id), "duplicated id: {id}");
    }
    Ok(())
}

#[cfg(feature = "std")]
#[derive(Error, Debug)]
pub enum TestError {
    #[error("some error")]
    SomeError,
}

#[cfg(feature = "std")]
#[test]
fn test_builder_errors() {
    let start_time = crate::time::current_millis() + 1_000;
    assert!(matches!(
        Snowflake::builder().start_time(start_time).finalize(),
        Err(Error::StartTimeAheadOfCurrentTime(_))
    ));

    assert!(matches!(
        Snowflake::builder()
            .machine_id(&|| Err(Box::new(TestError::SomeError)))
            .finalize(),
        Err(Error::MachineIdFailed(_))
    ));

    assert!(matches!(
        Snowflake::builder()
            .machine_id(&|| Ok(1))
            .check_machine_id(&|_| false)
            .finalize(),
        Err(Error::CheckMachineIdFailed)
    ));
}

#[test]
fn test_error_send_sync() {
    // This test ensures the Error type is Send + Sync
    let err = Error::CheckMachineIdFailed;
    thread::spawn(move || {
        let _ = err;
    })
    .join()
    .unwrap();
}

#[cfg(feature = "std")]
#[test]
fn test_over_time_limit() -> Result<(), BoxDynError> {
    let bit_len_time = 30;
    let sf = Snowflake::builder()
        .bit_len_time(bit_len_time)
        .bit_len_sequence(10)
        .bit_len_data_center_id(10)
        .bit_len_machine_id(13)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    // Manually set the state to be over the time limit
    let time_max = 1u64 << bit_len_time;
    let time_shift = sf.0.bit_len_sequence;
    let state_over_limit = time_max << time_shift;
    sf.0.state.store(state_over_limit, Ordering::Relaxed);

    assert!(matches!(sf.next_id(), Err(Error::OverTimeLimit)));
    Ok(())
}

// --- SnowflakeId trait tests ---

#[test]
fn test_snowflake_id_display() {
    let id = SnowflakeId::new(12345);
    assert_eq!(id.to_string(), "12345");
}

#[test]
fn test_snowflake_id_from_u64() {
    let id: SnowflakeId = 12345u64.into();
    assert_eq!(id.as_u64(), 12345);
    let raw: u64 = id.into();
    assert_eq!(raw, 12345);
}

#[test]
fn test_snowflake_id_from_str() {
    let id: SnowflakeId = "12345".parse().unwrap();
    assert_eq!(id.as_u64(), 12345);

    let err = "not_a_number".parse::<SnowflakeId>();
    assert!(err.is_err());
}

#[test]
fn test_snowflake_id_ord() {
    let id1 = SnowflakeId::new(100);
    let id2 = SnowflakeId::new(200);
    assert!(id1 < id2);
    assert!(id2 > id1);
    assert_eq!(id1, SnowflakeId::new(100));
}

#[test]
fn test_snowflake_id_deref() {
    let id = SnowflakeId::new(42);
    assert_eq!(*id, 42u64);
    // Can use u64 methods via Deref
    assert_eq!(id.leading_zeros(), 58);
}

#[test]
fn test_snowflake_id_encodings() {
    let id = SnowflakeId::new(255);
    assert_eq!(id.hex(), "ff");
    assert_eq!(id.base2(), "11111111");
    assert_eq!(id.string(), "255");
    assert_eq!(id.int64(), 255);
    assert_eq!(id.int_bytes(), [0, 0, 0, 0, 0, 0, 0, 255]);
}

#[test]
fn test_snowflake_id_partial_eq_u64() {
    let id = SnowflakeId::new(100);
    assert_eq!(id, 100u64);
    assert_ne!(id, 200u64);
}

#[test]
fn test_snowflake_id_from_str_hex() {
    let id1: SnowflakeId = "12345".parse().unwrap();
    let id2: SnowflakeId = "0x3039".parse().unwrap();
    assert_eq!(id1, id2);
    assert_eq!(id1.as_u64(), 12345);

    let id3: SnowflakeId = "0X3039".parse().unwrap();
    assert_eq!(id1, id3);
}

#[test]
fn test_snowflake_id_try_from_string() {
    let id = SnowflakeId::try_from("12345".to_string()).unwrap();
    assert_eq!(id.as_u64(), 12345);
}

#[test]
fn test_snowflake_id_try_from_str() {
    let id = SnowflakeId::try_from("0x3039").unwrap();
    assert_eq!(id.as_u64(), 12345);
}

#[test]
fn test_snowflake_id_try_from_i64() {
    let id = SnowflakeId::try_from(12345i64).unwrap();
    assert_eq!(id.as_u64(), 12345);

    assert!(SnowflakeId::try_from(-1i64).is_err());
}

// --- Serde tests ---

#[cfg(feature = "serde")]
#[test]
fn test_serde_snowflake_id_roundtrip() {
    let id = SnowflakeId::new(1_234_567_890_123_456_789);
    let json = serde_json::to_string(&id).unwrap();
    assert_eq!(json, "1234567890123456789");
    let back: SnowflakeId = serde_json::from_str(&json).unwrap();
    assert_eq!(id, back);
}

#[cfg(feature = "serde")]
#[test]
fn test_serde_snowflake_id_string_roundtrip() {
    use crate::SnowflakeIdString;
    let id = SnowflakeIdString(SnowflakeId::new(1_234_567_890_123_456_789));
    let json = serde_json::to_string(&id).unwrap();
    assert_eq!(json, "\"1234567890123456789\"");
    let back: SnowflakeIdString = serde_json::from_str(&json).unwrap();
    assert_eq!(id, back);
}

#[cfg(feature = "serde")]
#[test]
fn test_serde_decomposed_snowflake() {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()
        .unwrap();
    let id = sf.next_id().unwrap();
    let decomposed = sf.decompose(id);
    let json = serde_json::to_string(&decomposed).unwrap();
    assert!(json.contains("\"id\""));
    assert!(json.contains("\"time\""));
    assert!(json.contains("\"sequence\""));
    assert!(json.contains("\"data_center_id\""));
    assert!(json.contains("\"machine_id\""));
}

// --- Clock drift tests ---

#[cfg(feature = "std")]
#[test]
fn test_clock_drift_error_strategy() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .clock_drift_strategy(ClockDriftStrategy::Error)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    // Generate one ID to establish a baseline time
    let _id = sf.next_id()?;

    // Read current elapsed time and set state to a time far ahead of it
    let time_shift = sf.0.bit_len_sequence;
    let current_elapsed = crate::time::current_millis() - sf.0.start_time;
    let future_time = (current_elapsed as u64) + 100_000; // 100 seconds in the future
    sf.0.state
        .store(future_time << time_shift, Ordering::Relaxed);

    // Now next_id should detect clock drift and return Error::ClockDrift
    let result = sf.next_id();
    assert!(matches!(result, Err(Error::ClockDrift { .. })));

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_clock_drift_last_timestamp_strategy() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .clock_drift_strategy(ClockDriftStrategy::LastTimestamp)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    // Generate one ID to establish a baseline
    let _id = sf.next_id()?;

    // Read current elapsed time and set state to a time far ahead of it
    let time_shift = sf.0.bit_len_sequence;
    let current_elapsed = crate::time::current_millis() - sf.0.start_time;
    let future_time = (current_elapsed as u64) + 100_000;
    sf.0.state
        .store(future_time << time_shift, Ordering::Relaxed);

    // With LastTimestamp strategy, should still generate IDs using the old timestamp
    let id1 = sf.next_id()?;
    let id2 = sf.next_id()?;
    assert!(id2 > id1, "IDs should be monotonically increasing");

    // Decompose and verify the time matches the "last known" timestamp
    let parts = sf.decompose(id1);
    assert_eq!(parts.time, future_time);

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_clock_drift_exceeded() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .clock_drift_strategy(ClockDriftStrategy::Wait)
        .max_clock_drift_ms(50)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    // Generate one ID to establish a baseline
    let _id = sf.next_id()?;

    // Read current elapsed time and set state to a time far ahead (drift > 50ms)
    let time_shift = sf.0.bit_len_sequence;
    let current_elapsed = crate::time::current_millis() - sf.0.start_time;
    let future_time = (current_elapsed as u64) + 100_000; // 100 seconds >> 50ms
    sf.0.state
        .store(future_time << time_shift, Ordering::Relaxed);

    // Should return ClockDriftExceeded since drift (100s) >> max (50ms)
    let result = sf.next_id();
    assert!(matches!(
        result,
        Err(Error::ClockDriftExceeded {
            drift_ms: _,
            max_ms: 50
        })
    ));

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_clock_drift_wait_strategy_normal() -> Result<(), BoxDynError> {
    // Default Wait strategy should work normally when there's no clock drift
    let sf = Snowflake::builder()
        .clock_drift_strategy(ClockDriftStrategy::Wait)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    let mut last_id = SnowflakeId::new(0);
    for _ in 0..100 {
        let id = sf.next_id()?;
        assert!(id > last_id, "IDs should be monotonically increasing");
        last_id = id;
    }

    Ok(())
}

// --- Combined feature test ---

#[cfg(feature = "std")]
#[test]
fn test_full_features() {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()
        .unwrap();

    let id = sf.next_id().unwrap();
    assert!(id.as_u64() > 0);

    let decomposed = sf.decompose(id);
    assert_eq!(decomposed.machine_id, 1);
    assert_eq!(decomposed.data_center_id, 1);

    // Verify serde roundtrip when serde feature is enabled
    #[cfg(feature = "serde")]
    {
        let json = serde_json::to_string(&id).unwrap();
        let back: SnowflakeId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, back);
    }
}

// --- Performance optimization tests ---

#[cfg(feature = "std")]
#[test]
fn test_next_ids_uniqueness() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    let ids = sf.next_ids(10_000)?;
    assert_eq!(ids.len(), 10_000);

    let set: HashSet<_> = ids.iter().collect();
    assert_eq!(set.len(), 10_000, "duplicate IDs found in batch");

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_next_ids_empty() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;

    let ids = sf.next_ids(0)?;
    assert!(ids.is_empty());

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_next_ids_concurrent() -> Result<(), BoxDynError> {
    let sf = Arc::new(
        Snowflake::builder()
            .machine_id(&|| Ok(1))
            .data_center_id(&|| Ok(1))
            .finalize()?,
    );
    let ids = Arc::new(Mutex::new(HashSet::new()));
    let mut handles = vec![];

    for _ in 0..10 {
        let sf_clone = Arc::clone(&sf);
        let ids_clone = Arc::clone(&ids);
        handles.push(thread::spawn(move || {
            let batch = sf_clone.next_ids(1000).unwrap();
            let mut lock = ids_clone.lock().unwrap();
            for id in batch {
                assert!(lock.insert(id), "duplicate ID detected: {id}");
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    let final_count = ids.lock().unwrap().len();
    assert_eq!(final_count, 10_000);

    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_next_ids_monotonic() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(7))
        .data_center_id(&|| Ok(3))
        .finalize()?;

    let ids = sf.next_ids(1000)?;
    assert_eq!(ids.len(), 1000);
    // Batched IDs are returned in strictly increasing order, both within a
    // millisecond (sequence advances) and across the millisecond boundary.
    for w in ids.windows(2) {
        assert!(w[1] > w[0], "batch IDs must be strictly increasing");
    }
    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_next_ids_spans_millis() -> Result<(), BoxDynError> {
    // Default bit_len_sequence = 12 -> sequence range is 0..=4095 per millisecond.
    // Requesting 10_000 IDs forces the batch across multiple millisecond
    // boundaries, exercising the multi-segment allocation path.
    let expected_machine = 11u64;
    let expected_dc = 13u64;
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(expected_machine as u16))
        .data_center_id(&|| Ok(expected_dc as u16))
        .finalize()?;

    let count = 10_000;
    let ids = sf.next_ids(count)?;
    assert_eq!(ids.len(), count);

    // All unique, even across the millisecond boundary.
    let set: HashSet<_> = ids.iter().collect();
    assert_eq!(
        set.len(),
        count,
        "duplicate IDs across millisecond boundary"
    );

    // Strictly increasing across segments.
    for w in ids.windows(2) {
        assert!(w[1] > w[0], "IDs not monotonic across boundary");
    }

    // Every ID decomposes back to the configured machine / data center id,
    // proving the batched assembly uses the same layout as `next_id`.
    for id in &ids {
        let parts = sf.decompose(*id);
        assert_eq!(parts.machine_id, expected_machine);
        assert_eq!(parts.data_center_id, expected_dc);
    }

    Ok(())
}

#[test]
fn test_cache_line_alignment() {
    use crate::snowflake::SharedSnowflake;
    use std::mem::align_of;
    assert!(
        align_of::<SharedSnowflake>() >= 64,
        "SharedSnowflake alignment {} is less than 64",
        align_of::<SharedSnowflake>()
    );
}

// --- Performance Benchmarks ---
// These tests are ignored by default. Run with `cargo test -- --ignored`.

#[test]
#[ignore = "benchmark, run with `cargo test -- --ignored`"]
fn bench_single_thread_performance() -> Result<(), BoxDynError> {
    let sf = Snowflake::new()?;
    let iterations = 1_000_000;

    let start = Instant::now();
    for _ in 0..iterations {
        // Using black_box would be better with a real bench harness,
        // but for a simple test, this is okay.
        let _ = sf.next_id()?;
    }
    let duration = start.elapsed();
    let rate = iterations as f64 / duration.as_secs_f64();

    println!("\n--- Single-Thread Benchmark ---");
    println!(
        "Generated {} IDs in {:?}. Rate: {:.2} IDs/sec",
        iterations, duration, rate
    );
    println!("-----------------------------\n");

    Ok(())
}

#[test]
#[ignore = "benchmark, run with `cargo test -- --ignored`"]
fn bench_multi_thread_throughput() -> Result<(), BoxDynError> {
    let sf = Arc::new(Snowflake::new()?);
    let num_threads = num_cpus::get().max(2); // Use available cores, at least 2
    let ids_per_thread = 1_000_000 / num_threads;
    let total_ids = num_threads * ids_per_thread;

    let start = Instant::now();
    let mut handles = vec![];

    for _ in 0..num_threads {
        let sf_clone = Arc::clone(&sf);
        handles.push(thread::spawn(move || {
            for _ in 0..ids_per_thread {
                let _ = sf_clone.next_id().unwrap();
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    let duration = start.elapsed();
    let rate = total_ids as f64 / duration.as_secs_f64();

    println!("\n--- Multi-Thread Benchmark ---");
    println!("Threads: {}", num_threads);
    println!(
        "Generated {} IDs in {:?}. Throughput: {:.2} IDs/sec",
        total_ids, duration, rate
    );
    println!("----------------------------\n");

    Ok(())
}

// --- no_std verification ---
//
// The crate must compile with `--no-default-features` (verified by CI).
// `cargo test` itself requires std, so these tests exercise the shared code paths
// that work in both std and no_std modes.

#[cfg(feature = "std")]
#[test]
fn test_time_source_abstraction() {
    // Verify that the time module's current_millis works (std path)
    let t1 = crate::time::current_millis();
    std::thread::sleep(Duration::from_millis(10));
    let t2 = crate::time::current_millis();
    assert!(t2 >= t1, "time should not go backward");
}

#[test]
fn test_snowflake_id_core_traits() {
    // Verify core trait implementations that must work without std
    let id = SnowflakeId::new(12345);
    assert_eq!(id.as_u64(), 12345);
    assert_eq!(format!("{id}"), "12345");
    assert_eq!(id.int64(), 12345i64);

    let id2 = SnowflakeId::new(12345);
    assert_eq!(id, id2);
    assert_eq!(id, 12345u64);

    let id3 = SnowflakeId::new(99999);
    assert!(id < id3);
}

// --- Encoding decode roundtrip + API enhancement tests (v2.1.3) ---

#[test]
fn test_snowflake_id_encoding_roundtrip() {
    // base32 / base58 / base64 encode -> decode must be the identity.
    for raw in [0_u64, 1, 255, 4095, 1_000_000, u64::MAX / 2, u64::MAX] {
        let id = SnowflakeId::new(raw);
        assert_eq!(
            SnowflakeId::from_base64(&id.base64()).unwrap(),
            id,
            "base64 roundtrip for {raw}"
        );
        assert_eq!(
            SnowflakeId::from_base58(&id.base58()).unwrap(),
            id,
            "base58 roundtrip for {raw}"
        );
        assert_eq!(
            SnowflakeId::from_base32(&id.base32()).unwrap(),
            id,
            "base32 roundtrip for {raw}"
        );
    }
}

#[test]
fn test_snowflake_id_decode_invalid() {
    // Characters outside each alphabet are rejected.
    assert!(SnowflakeId::from_base32("!!invalid!!").is_err());
    // 0, O, I, l are deliberately excluded from the base58 alphabet.
    assert!(SnowflakeId::from_base58("0OIl").is_err());
    assert!(SnowflakeId::from_base64("not-base64@@@").is_err());
    // base64 that does not decode to exactly 8 bytes is rejected.
    assert!(SnowflakeId::from_base64("AAAA").is_err());
}

#[cfg(feature = "std")]
#[test]
fn test_compose_decompose_roundtrip() -> Result<(), BoxDynError> {
    let sf = Snowflake::builder()
        .machine_id(&|| Ok(7))
        .data_center_id(&|| Ok(3))
        .finalize()?;

    let (time, dc, machine, seq) = (123_u64, 3, 7, 999);
    let id = sf.compose(time, dc, machine, seq)?;
    let parts = sf.decompose(id);
    assert_eq!(parts.time, time);
    assert_eq!(parts.data_center_id, dc);
    assert_eq!(parts.machine_id, machine);
    assert_eq!(parts.sequence, seq);

    // Components outside their bit width are rejected.
    assert!(sf.compose(1_u64 << 41, 0, 0, 0).is_err()); // time overflow (default 41 bits)
    assert!(sf.compose(0, 1 << 5, 0, 0).is_err()); // data center overflow (default 5 bits)
    assert!(sf.compose(0, 0, 0, 1 << 12).is_err()); // sequence overflow (default 12 bits)
    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_snowflake_default() -> Result<(), BoxDynError> {
    // Default uses zero machine / data center IDs (no IP fallback dependency).
    let sf = Snowflake::default();
    let id = sf.next_id()?;
    assert!(id.as_u64() > 0);
    let parts = sf.decompose(id);
    assert_eq!(parts.machine_id, 0);
    assert_eq!(parts.data_center_id, 0);
    Ok(())
}

#[cfg(feature = "std")]
#[test]
fn test_absolute_millis() -> Result<(), BoxDynError> {
    let start = crate::time::current_millis();
    let sf = Snowflake::builder()
        .start_time(start)
        .machine_id(&|| Ok(1))
        .data_center_id(&|| Ok(1))
        .finalize()?;
    let id = sf.next_id()?;
    let parts = sf.decompose(id);
    let abs = parts.absolute_millis(start);
    // absolute_millis == start + elapsed, so it must fall within [start, now].
    let now = crate::time::current_millis();
    assert!(
        abs >= start && abs <= now + 100,
        "absolute_millis={abs}, start={start}, now={now}"
    );
    assert_eq!(abs, start + parts.time as i64);
    Ok(())
}