Repository navigation
Expand file tree
/
Copy pathtest_util.cpp
More file actions
2013 lines (1698 loc) · 96.1 KB
/
Copy pathtest_util.cpp
File metadata and controls
2013 lines (1698 loc) · 96.1 KB
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
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Purpose: Tests for the shared utility layer (util*, crypto*) -- strings, wildcards, versions, natural compare, interning, cancellation tokens, result scopes, hashes and perceptual hashes, json parsing, file presence and memory-mapped files.
#include "pch.h"
#include "files.h"
#include "test.h"
#include "app_command_line.h"
#include "crypto.h"
#include "libdesktop/core/base64.h"
#include "crypto_sha.h"
#include "libdesktop/core/json.h"
#include "libdesktop/core/kdtree.h"
#include "libdesktop/core/simd.h"
#include "util_top.h"
#include "test_fixtures.h"
#include "test_runner.h"
#include "app_util.h"
static void assert_assertion_fails(const std::function<void()>& f, const std::string_view name)
{
auto failed = false;
try
{
f();
}
catch (const test_assert_exception&)
{
failed = true;
}
assert_equal(true, failed, name);
}
static void should_name_files_after_the_application()
{
// The foundation and the platform layer derive their file, folder and key names from the
// application's name. These are the names Diffractor always used, so existing logs, settings
// and caches are still found.
assert_equal("diffractor"sv, core::app_file_stem(), "file stem");
assert_equal("diffractor.log"sv, platform::log_path.name(), "log");
assert_equal("diffractor.previous.log"sv, platform::previous_log_path.name(), "previous log");
}
static void should_complete_result_scope()
{
const auto results = std::make_shared<null_item_results_ui>();
{
result_scope scope(results);
}
assert_equal(1, results->complete_count, "normal scope exit completes results");
assert_equal(0, results->abort_count, "normal scope exit does not abort results");
}
static void should_abort_result_scope_during_exception()
{
const auto results = std::make_shared<null_item_results_ui>();
try
{
result_scope scope(results);
throw std::runtime_error("test");
}
catch (const std::runtime_error&)
{
}
assert_equal(0, results->complete_count, "exception unwinding does not complete results");
assert_equal(1, results->abort_count, "exception unwinding aborts results");
}
// EXIF text can arrive as UTF-16, and which way round it is decides whether it reads as words or
// as mojibake. Testing only the even bytes for zero recognised big-endian alone - so a
// little-endian value, which is what Windows writes, was read a byte at a time.
static void should_detect_utf16_either_way_round()
{
const auto is_utf16 = [](const std::initializer_list<uint8_t> bytes)
{
const std::vector<uint8_t> v(bytes);
return core::is_utf16(v.data(), static_cast<int>(v.size()));
};
// "Hi" with no mark, each way round.
assert_equal(true, is_utf16({'H', 0, 'i', 0}), "unmarked little-endian is recognised");
assert_equal(true, is_utf16({0, 'H', 0, 'i'}), "and so is unmarked big-endian");
// Marked, each way round.
assert_equal(true, is_utf16({0xff, 0xfe, 'H', 0}), "a little-endian mark is recognised");
assert_equal(true, is_utf16({0xfe, 0xff, 0, 'H'}), "and so is a big-endian mark");
// UTF-32 LE opens with the UTF-16 LE mark and must not be taken for it.
assert_equal(false, is_utf16({0xff, 0xfe, 0x00, 0x00}), "a utf-32 mark is not utf-16");
// Plain bytes stay plain.
assert_equal(false, is_utf16({'H', 'e', 'l', 'l', 'o'}), "ascii is not utf-16");
assert_equal(false, is_utf16({0xe2, 0x82, 0xac, 'x'}), "utf-8 is not utf-16");
assert_equal(false, is_utf16({'H'}), "and a single byte cannot be");
// Recognising either order is only half of it: the text is decoded the same way round it was
// recognised, and a mark is not part of the value. Copied as it lay, big-endian text came out
// backwards and a marked value kept an invisible U+FEFF at its start.
const auto decode = [](const std::initializer_list<uint8_t> bytes)
{
const std::vector<uint8_t> v(bytes);
return core::utf16_from_bytes(v.data(), static_cast<int>(v.size()));
};
assert_equal(true, decode({'H', 0, 'i', 0}) == u"Hi", "unmarked little-endian decodes");
assert_equal(true, decode({0, 'H', 0, 'i'}) == u"Hi", "and so does unmarked big-endian");
assert_equal(true, decode({0xff, 0xfe, 'H', 0, 'i', 0}) == u"Hi", "a little-endian mark is not part of the text");
assert_equal(true, decode({0xfe, 0xff, 0, 'H', 0, 'i'}) == u"Hi", "and a big-endian mark sets the order");
}
static void should_icmp_natural()
{
// Test basic numeric comparison - the key bug fix
// Files like 43_100 should come after 43_99, not between 43_10 and 43_11
assert_equal(true, core::icmp_natural("43_09", "43_10") < 0, "43_09 < 43_10");
assert_equal(true, core::icmp_natural("43_10", "43_11") < 0, "43_10 < 43_11");
assert_equal(true, core::icmp_natural("43_10", "43_100") < 0, "43_10 < 43_100");
assert_equal(true, core::icmp_natural("43_99", "43_100") < 0, "43_99 < 43_100");
assert_equal(true, core::icmp_natural("43_100", "43_101") < 0, "43_100 < 43_101");
// Verify the order reported in the bug is fixed
assert_equal(true, core::icmp_natural("43_09", "43_100") < 0, "43_09 < 43_100");
assert_equal(true, core::icmp_natural("43_11", "43_100") < 0, "43_11 < 43_100");
// Test equality
assert_equal(0, core::icmp_natural("file10", "file10"), "equal strings");
assert_equal(0, core::icmp_natural("", ""), "empty strings");
// Test case insensitivity
assert_equal(0, core::icmp_natural("File10", "file10"), "case insensitive");
assert_equal(0, core::icmp_natural("FILE10", "file10"), "case insensitive upper");
// Test basic natural ordering
assert_equal(true, core::icmp_natural("file1", "file2") < 0, "file1 < file2");
assert_equal(true, core::icmp_natural("file2", "file10") < 0, "file2 < file10");
assert_equal(true, core::icmp_natural("file9", "file10") < 0, "file9 < file10");
assert_equal(true, core::icmp_natural("file10", "file11") < 0, "file10 < file11");
assert_equal(true, core::icmp_natural("file19", "file20") < 0, "file19 < file20");
// Issue #197: "43_100" sorted between "43_10" and "43_11" (lexicographic instead of numeric).
assert_equal(true, core::icmp_natural("file99", "file100") < 0, "file99 < file100");
assert_equal(true, core::icmp_natural("file100", "file1000") < 0, "file100 < file1000");
// Test reverse ordering
assert_equal(true, core::icmp_natural("file10", "file9") > 0, "file10 > file9");
assert_equal(true, core::icmp_natural("file100", "file99") > 0, "file100 > file99");
// Test with different prefixes
assert_equal(true, core::icmp_natural("a10", "b1") < 0, "a10 < b1");
assert_equal(true, core::icmp_natural("img001", "img002") < 0, "img001 < img002");
assert_equal(true, core::icmp_natural("img009", "img010") < 0, "img009 < img010");
// Test numbers at the start
assert_equal(true, core::icmp_natural("1file", "2file") < 0, "1file < 2file");
assert_equal(true, core::icmp_natural("9file", "10file") < 0, "9file < 10file");
assert_equal(true, core::icmp_natural("10file", "100file") < 0, "10file < 100file");
// Test multiple number groups
assert_equal(true, core::icmp_natural("file1-1", "file1-2") < 0, "file1-1 < file1-2");
assert_equal(true, core::icmp_natural("file1-9", "file1-10") < 0, "file1-9 < file1-10");
assert_equal(true, core::icmp_natural("file1-10", "file2-1") < 0, "file1-10 < file2-1");
// Test leading zeros
assert_equal(true, core::icmp_natural("file007", "file7") > 0, "file007 > file7 (more leading zeros)");
assert_equal(true, core::icmp_natural("file07", "file007") < 0, "file07 < file007 (fewer leading zeros)");
assert_equal(0, core::icmp_natural("file007", "file007"), "same with leading zeros");
// Test purely numeric strings
assert_equal(true, core::icmp_natural("1", "2") < 0, "1 < 2");
assert_equal(true, core::icmp_natural("9", "10") < 0, "9 < 10");
assert_equal(true, core::icmp_natural("99", "100") < 0, "99 < 100");
assert_equal(true, core::icmp_natural("999", "1000") < 0, "999 < 1000");
// Test strings with no numbers
assert_equal(true, core::icmp_natural("abc", "abd") < 0, "abc < abd");
assert_equal(true, core::icmp_natural("abc", "abcd") < 0, "abc < abcd");
assert_equal(0, core::icmp_natural("abc", "ABC"), "abc == ABC (case insensitive)");
// Test image sequence patterns (common use case)
assert_equal(true, core::icmp_natural("DSC_0001.jpg", "DSC_0002.jpg") < 0, "DSC sequence");
assert_equal(true, core::icmp_natural("DSC_0099.jpg", "DSC_0100.jpg") < 0, "DSC sequence 99-100");
assert_equal(true, core::icmp_natural("IMG_9999.png", "IMG_10000.png") < 0, "IMG sequence overflow");
// A run longer than nineteen digits does not fit a uint64_t. Accumulating the value wrapped it,
// and the wrapped result compared as something small - so a long serial number, a hash or a
// phone-camera timestamp landed at an arbitrary point in the listing. Leading zeros have
// already been consumed by this point, so the longer run is simply the larger number.
assert_equal(true, core::icmp_natural("id_99999999999999999999", "id_100000000000000000000") < 0,
"twenty digits beats twenty");
assert_equal(true, core::icmp_natural("id_18446744073709551615", "id_18446744073709551616") < 0,
"one past the widest value a uint64 holds still orders after it");
assert_equal(true, core::icmp_natural("id_9", "id_99999999999999999999999999") < 0,
"a short run orders before a very long one");
assert_equal(0, core::icmp_natural("id_99999999999999999999", "id_99999999999999999999"),
"and two of the same are equal");
// 2^64 wraps to zero, so any comparison that forms the value puts it below a bare 1.
assert_equal(true, core::icmp_natural("id_1", "id_18446744073709551616") < 0,
"two to the sixty-four is larger than one, not smaller");
assert_equal(true, core::icmp_natural("id_18446744073709551616", "id_1") > 0, "and the reverse holds");
}
static void should_follow_the_filesystem_for_path_identity()
{
// The subject is identity, not spelling, so the literals use the running platform's root.
const auto root = core::folder_path(core::windows_path_semantics ? "c:\\photos" : "/photos");
const auto root_upper = core::folder_path(core::windows_path_semantics ? "C:\\PHOTOS" : "/PHOTOS");
const auto lower = root.combine_file("holiday.jpg");
const auto upper = root.combine_file("HOLIDAY.JPG");
const auto other = root.combine_file("apple.jpg");
// Case-folded where the filesystem folds, and two distinct files where it does not.
constexpr auto same = core::case_insensitive_path_identity;
assert_equal(same, root.compare(root_upper) == 0, "folder identity");
assert_equal(same, lower.icmp(upper) == 0, "file identity");
assert_equal(same, lower == upper, "file equality follows the comparison");
// A hash that disagreed with the comparison would leave one file in two buckets.
const core::ihash hash;
assert_equal(same, hash(lower) == hash(upper), "file hash agrees with file identity");
assert_equal(same, hash(root) == hash(root_upper), "folder hash agrees with folder identity");
assert_equal(true, hash(lower) == hash(root.combine_file("holiday.jpg")), "one path, one hash");
core::hash_set<core::file_path, core::ihash, core::ieq> paths;
paths.emplace(lower);
paths.emplace(upper);
assert_equal(same ? 1 : 2, static_cast<int>(paths.size()), "a set holds one entry per file");
// Ordering still folds case on both platforms, so a case variant sorts beside its twin rather
// than ahead of every lower-case name. A byte comparison would put "HOLIDAY.JPG" before
// "apple.jpg", which is what this asserts against.
assert_equal(true, lower.icmp(other) > 0, "ordering is lexicographic");
assert_equal(true, upper.icmp(other) > 0, "a case variant orders with its twin, not before it");
// Type is a different question and never follows the filesystem: an upper-case extension names
// the same format on every platform.
assert_equal(0, core::icmp(lower.extension(), upper.extension()), "extension matching stays folded");
const auto ft_lower = files::file_type_from_name(lower);
const auto ft_upper = files::file_type_from_name(upper);
assert_equal(true, ft_lower == ft_upper, "file type does not follow path identity");
const auto accented_acute = root.parent().combine("album-é");
const auto accented_grave = root.parent().combine("album-è");
assert_equal(false, core::folder_contains(accented_acute.text(), accented_grave.combine("child").text()),
"accented sibling folders are distinct");
assert_equal(true, core::folder_contains(accented_acute.text(), accented_acute.combine("child").text()),
"a real child is contained");
assert_equal(false, core::folder_contains(root.text(), root.parent().combine("photoshop").text()),
"prefix matches stop at a separator boundary");
assert_equal(same, core::folder_contains(root_upper.text(), root.combine("child").text()),
"case aliases follow filesystem identity only");
// A key held as a string has to answer the same way, or the rename planner disagrees with the
// index about whether a destination is occupied.
assert_equal(same, core::compare_path_key(lower.pack(), upper.pack()) == 0, "packed key identity");
assert_equal(same, core::path_text_starts(root_upper.text(), root.text()), "prefix match identity");
assert_equal(true, core::path_text_starts(root.text(), root.text()), "a path contains itself");
}
static void should_parse_files_directly_under_the_root()
{
const auto root = core::folder_path(core::windows_path_semantics ? "c:\\" : "/");
const auto direct_text = core::windows_path_semantics ? "c:\\photo.jpg" : "/photo.jpg";
const auto direct = core::file_path(direct_text);
const auto combined = root.combine_file("photo.jpg");
assert_equal(root.text(), direct.folder().text(), "root folder is preserved");
assert_equal("photo.jpg", direct.name(), "root child keeps its name");
assert_equal(".jpg", direct.extension(), "root child keeps its extension");
assert_equal(direct_text, direct.pack(), "root child packs without a trailing folder separator");
assert_equal(true, direct == combined, "direct and combined root children are equal");
const core::ihash hash;
assert_equal(hash(combined), hash(direct), "direct and combined root children hash alike");
auto reused = root.combine_file("old-name.txt");
reused.un_pack(direct_text);
assert_equal(root.text(), reused.folder().text(), "reuse refreshes the folder");
assert_equal("photo.jpg", reused.name(), "reuse refreshes the name");
reused.un_pack(std::string(root.text()));
assert_equal(root.text(), reused.folder().text(), "folder-only unpack keeps the folder");
assert_equal(true, reused.name().is_empty(), "folder-only unpack clears a stale name");
}
static void should_group_elements_by_folder()
{
struct element
{
core::folder_path folder;
int id = 0;
bool skip = false;
};
// The subject is grouping, not path spelling, so the literals use the running platform's root.
constexpr auto a = core::windows_path_semantics ? "c:\\a" : "/a";
constexpr auto b = core::windows_path_semantics ? "c:\\b" : "/b";
constexpr auto c = core::windows_path_semantics ? "c:\\c" : "/c";
constexpr auto a_upper = core::windows_path_semantics ? "C:\\A" : "/A";
const std::vector<element> elements{
{core::folder_path(a), 1}, {core::folder_path(b), 2}, {core::folder_path(a), 3},
{core::folder_path(b), 4, true}, {core::folder_path(a_upper), 5}, {core::folder_path(c), 6},
};
// Path identity follows the filesystem, so the case variant is a fourth folder where two
// spellings are two places and a member of the first group where they are one.
constexpr auto expected_groups = core::case_insensitive_path_identity ? 3 : 4;
core::folder_groups groups;
groups.build(elements, [](const element& e) { return e.folder; }, [](const element& e) { return !e.skip; });
assert_equal(expected_groups, static_cast<int>(groups.groups().size()), "one group per distinct folder");
// Groups are in first-seen order and each keeps its elements in input order.
assert_equal(a, groups.groups()[0].folder.text().str(), "first group");
assert_equal(b, groups.groups()[1].folder.text().str(), "second group");
assert_equal(c, groups.groups()[expected_groups - 1].folder.text().str(), "last group");
const auto ids = [&](const size_t g)
{
std::string result;
for (const auto i : groups.elements(groups.groups()[g])) result += std::to_string(elements[i].id);
return result;
};
assert_equal(core::case_insensitive_path_identity ? "135" : "13", ids(0), "case variant follows path identity");
assert_equal("2", ids(1), "excluded element is dropped");
assert_equal("6", ids(expected_groups - 1), "single element group");
groups.build(elements, [](const element& e) { return e.folder; });
assert_equal(expected_groups, static_cast<int>(groups.groups().size()), "rebuild replaces the previous grouping");
assert_equal("24", ids(1), "no predicate includes every element");
// Enough distinct folders to force the lookup tables to grow and rehash.
std::vector<element> many;
many.reserve(1000);
const auto numbered = [](const int i)
{
return core::folder_path(core::windows_path_semantics ? std::format("c:\\f{}", i) : std::format("/f{}", i));
};
for (auto i = 0; i < 500; ++i) many.emplace_back(numbered(i), i);
for (auto i = 0; i < 500; ++i) many.emplace_back(numbered(i), i);
groups.build(many, [](const element& e) { return e.folder; });
assert_equal(500, static_cast<int>(groups.groups().size()), "grown tables keep folders distinct");
for (const auto& g : groups.groups())
{
assert_equal(2, static_cast<int>(groups.elements(g).size()), "each folder collected both elements");
}
groups.clear();
assert_equal(true, groups.empty(), "cleared grouping has no groups");
}
static void should_cancel_superseded_tokens()
{
std::atomic_int version = 0;
const core::cancel_token first(version);
const auto first_copy = first;
assert_equal(false, first.is_cancelled(), "current token is active");
assert_equal(false, first_copy.is_cancelled(), "copied current token is active");
const core::cancel_token second(version);
assert_equal(true, first.is_cancelled(), "new generation cancels previous token");
assert_equal(true, first_copy.is_cancelled(), "new generation cancels copies of previous token");
assert_equal(false, second.is_cancelled(), "new generation remains active");
}
static void should_calc_HMACSHA1()
{
const auto signature = crypto::hmac_sha1("Jefe", "what do ya want for nothing?");
assert_equal_strict("7/zfauXrL6LSdBbV8YTfnCWafHk=", signature, "Signature");
}
static void should_calc_hashes()
{
assert_equal("A9993E364706816ABA3E25717850C26C9CD0D89D", crypto::to_sha1("abc"), "SHA1");
assert_equal("187797D630ECAA0FC1B920CD9F809C2BBFFCBF4C", crypto::to_sha1(long_text), "SHA1");
assert_equal("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD", crypto::to_sha256("abc"),
"SHA256");
assert_equal("1660F10AEC042D762CF8B1C53E976F890C8E797BEF74807F505EDCE20308FC2F", crypto::to_sha256(long_text),
"SHA256");
const auto crc_data = "hello world"s;
const auto crc_result = core::crc32c(crc_data.data(), crc_data.size());
assert_equal(0xc99465aa, crc_result, "crc32");
assert_equal(0xe3069283, core::crc32c("123456789"sv), "crc32 standard vector");
const auto crc_c = ~calc_crc32c_c(core::crc32c_init, crc_data.data(), crc_data.size());
assert_equal(0xc99465aa, crc_c, "crc32 c");
assert_equal(0xe3069283, ~calc_crc32c_c(core::crc32c_init, "123456789", 9), "crc32 c standard vector");
if (core::crc32_supported)
{
const auto crc_x86 = ~calc_crc32c_x86(core::crc32c_init, crc_data.data(), crc_data.size());
assert_equal(0xc99465aa, crc_x86, "crc32 x86");
assert_equal(0xe3069283, ~calc_crc32c_x86(core::crc32c_init, "123456789", 9), "crc32 x86 standard vector");
}
if (core::arm_crc32_supported)
{
const auto crc_neon = ~calc_crc32c_arm(core::crc32c_init, crc_data.data(), crc_data.size());
assert_equal(0xc99465aa, crc_neon, "crc32 neon");
assert_equal(0xe3069283, ~calc_crc32c_arm(core::crc32c_init, "123456789", 9), "crc32 arm standard vector");
}
alignas(16) std::array<uint8_t, 96> boundary_data;
for (auto i = 0u; i < boundary_data.size(); ++i)
{
boundary_data[i] = static_cast<uint8_t>(i * 37u + 11u);
}
for (auto offset = 0u; offset < 16u; ++offset)
{
for (auto len = 0u; len <= 80u; ++len)
{
const auto* const data = boundary_data.data() + offset;
const auto expected = calc_crc32c_c(core::crc32c_init, data, len);
assert_equal(~expected, core::crc32c(data, len), "crc32 dispatched boundary");
if (core::crc32_supported)
{
assert_equal(expected, calc_crc32c_x86(core::crc32c_init, data, len), "crc32 x86 boundary");
const auto split = len / 2;
const auto first = calc_crc32c_x86(core::crc32c_init, data, split);
assert_equal(expected, calc_crc32c_x86(first, data + split, len - split), "crc32 x86 continuation");
}
if (core::arm_crc32_supported)
{
assert_equal(expected, calc_crc32c_arm(core::crc32c_init, data, len), "crc32 arm boundary");
const auto split = len / 2;
const auto first = calc_crc32c_arm(core::crc32c_init, data, split);
assert_equal(expected, calc_crc32c_arm(first, data + split, len - split), "crc32 arm continuation");
}
}
}
}
// A synthetic 32x32 field, so the hash is tested on its own terms without a decoder in the way.
static std::array<uint8_t, crypto::phash_pixels> make_phash_field(const int seed)
{
std::array<uint8_t, crypto::phash_pixels> result{};
for (auto y = 0u; y < crypto::phash_extent; ++y)
{
for (auto x = 0u; x < crypto::phash_extent; ++x)
{
const auto v = (x * 7 + y * 13 + seed * 29) % 251;
result[y * crypto::phash_extent + x] = static_cast<uint8_t>((v * v) % 256);
}
}
return result;
}
static void should_calc_perceptual_hashes()
{
const auto field = make_phash_field(1);
const auto hash = crypto::perceptual_hash(field.data(), field.size());
assert_equal(true, crypto::phash_is_usable(hash), "a detailed field hashes");
assert_equal(hash, crypto::perceptual_hash(field.data(), field.size()), "the same pixels hash the same");
assert_equal(0, crypto::phash_distance(hash, hash), "distance to itself");
// Bit 0 comes from the DC coefficient, which is excluded, so it is free to mark a declined hash.
// Typed rather than 0ull: under LP64 unsigned long long is distinct from uint64_t, so the
// assert_equal overload set has no exact match.
assert_equal(uint64_t{0}, hash & uint64_t{1}, "a real hash never sets the reserved bit");
assert_equal(false, crypto::phash_is_usable(crypto::phash_declined), "the declined marker is not a hash");
assert_equal(false, crypto::phash_is_usable(0), "not computed is not a hash");
// Brightness and contrast move every pixel but not the picture, which is what a re-encode does.
auto brightened = field;
for (auto& v : brightened) v = static_cast<uint8_t>(std::min(255, v + 20));
assert_equal(true, crypto::phash_distance(hash, crypto::perceptual_hash(brightened.data(), brightened.size())) <= 6,
"brightness does not change the picture");
// A different picture has to land far away, or the threshold means nothing.
const auto other = make_phash_field(9);
assert_equal(true, crypto::phash_distance(hash, crypto::perceptual_hash(other.data(), other.size())) > 6,
"a different picture is far away");
// Flat fields are where a 64-bit hash quietly starts matching everything.
std::array<uint8_t, crypto::phash_pixels> blank{};
blank.fill(128);
assert_equal(false, crypto::phash_is_usable(crypto::perceptual_hash(blank.data(), blank.size())),
"a blank image has no opinion");
std::array<uint8_t, crypto::phash_pixels> almost_blank{};
almost_blank.fill(128);
almost_blank[0] = 129;
assert_equal(false, crypto::phash_is_usable(crypto::perceptual_hash(almost_blank.data(), almost_blank.size())),
"one different pixel is not detail");
assert_equal(0ull, crypto::perceptual_hash(nullptr, crypto::phash_pixels), "no pixels");
assert_equal(0ull, crypto::perceptual_hash(field.data(), crypto::phash_pixels - 1), "short buffer");
}
static uint64_t phash_of_file(const std::string_view name)
{
files ff;
file_read_stream stream;
if (!stream.open(test_files_folder().combine_file(name))) return 0;
core::blob owner;
return ff.calc_perceptual_hash(stream.view_all(owner));
}
static crypto::phash_rotations phash_rotations_of_file(const std::string_view name)
{
files ff;
file_read_stream stream;
if (!stream.open(test_files_folder().combine_file(name))) return {};
core::blob owner;
return ff.calc_perceptual_hash_rotations(stream.view_all(owner));
}
// The point of the hash is the case a checksum cannot see: the same picture in a different file.
static void should_recognise_the_same_picture()
{
const auto original = phash_of_file("Test.jpg");
const auto resized = phash_of_file("Small.jpg");
assert_equal(true, crypto::phash_is_usable(original), "Test.jpg hashes");
assert_equal(true, crypto::phash_is_usable(resized), "Small.jpg hashes");
// Measured separation on these fixtures: 0 for the resize, 30 for a rotation, 32 for an
// unrelated photo. The threshold sits in that gap rather than near either side of it.
assert_equal(0, crypto::phash_distance(original, resized), "a resized copy is the same picture");
// A rotation is a different bitmap, so the single-orientation hash must still land far away: the
// rotations are what recognise it, and nothing else should quietly start matching.
assert_equal(true, crypto::phash_distance(original, phash_of_file("Test90.jpg")) > 20,
"a rotated copy is not the same bitmap");
const auto unrelated = phash_of_file("IMG_0096.JPG");
assert_equal(true, crypto::phash_is_usable(unrelated), "an unrelated photo hashes");
assert_equal(true, crypto::phash_distance(original, unrelated) > 20, "an unrelated photo is far away");
}
// A quarter turn is a common grading step, so the same picture rotated has to be recognised as a
// copy - while an unrelated photo stays clear in every orientation, not just the one it was saved in.
static void should_recognise_a_rotated_picture()
{
const auto original = phash_of_file("Test.jpg");
assert_equal(true, crypto::phash_is_usable(original), "Test.jpg hashes");
// Every quarter turn of the same photograph, and a losslessly rotated pair from a second source.
for (const auto name : {"Test90.jpg"sv, "Test180.jpg"sv, "Test270.jpg"sv})
{
const auto rotated = phash_rotations_of_file(name);
assert_equal(true, crypto::phash_is_usable(rotated[0]), "a turned copy hashes");
assert_equal(true, crypto::phash_distance(original, rotated) <= 6, "a turned copy is the same picture");
}
const auto lossless = phash_of_file("Lossless0.jpg");
assert_equal(true, crypto::phash_is_usable(lossless), "Lossless0.jpg hashes");
assert_equal(true, crypto::phash_distance(lossless, phash_rotations_of_file("Lossless90.jpg")) <= 6,
"a losslessly rotated copy matches");
// Whichever side carries the turns, the pair has to meet: presence compares the outside file's
// stored hash against an indexed picture's turns, and duplicate search does the reverse.
assert_equal(true, crypto::phash_distance(phash_of_file("Test90.jpg"), phash_rotations_of_file("Test.jpg")) <= 6,
"the turned file recognises the upright original");
assert_equal(true, crypto::phash_is_usable(phash_rotations_of_file("Test.jpg")[0]),
"the upright original keeps a usable set of turns");
// The rotations must not become a way for anything to match anything.
assert_equal(true, crypto::phash_distance(original, phash_rotations_of_file("IMG_0096.JPG")) > 6,
"an unrelated photo stays clear in every orientation");
assert_equal(true, crypto::phash_distance(original, phash_rotations_of_file("Lossless0.jpg")) > 6,
"a second unrelated photo stays clear in every orientation");
// A resize still matches without needing a turn, so the plain comparison is not weakened.
assert_equal(0, crypto::phash_distance(original, phash_rotations_of_file("Small.jpg")),
"a resized copy still matches at zero");
}
static void should_convert_utf8()
{
// icon font
wchar_t stars_utf16[6] = {};
for (auto i = 0; i < 5; i++)
{
stars_utf16[i] = static_cast<uint16_t>(i & 0x01 ? icon_index::star_solid : icon_index::star);
}
stars_utf16[5] = 0;
const auto stars = platform::utf16_to_utf8(stars_utf16);
std::string_view strings[] = {
"In vollen Zügen genießen", "Nældens takvinge", "💉💎👦🏻👓⚡", "Žižkov",
"Доброго ранку!", "Japanese こんにちは世界", "Arabic مرحبا العالم", stars,
};
for (const auto src : strings)
{
assert_equal(src, platform::utf16_to_utf8(platform::utf8_to_utf16(src)), "platform conversions");
assert_equal(platform::utf8_to_utf16(src), core::utf8_to_utf16(src), "to utf16");
assert_equal(src, core::utf16_to_utf8(platform::utf8_to_utf16(src)), "to utf8");
assert_equal(src, core::utf16_to_utf8(core::utf8_to_utf16(src)), "internal conversions");
}
constexpr wchar_t icon_text[2] = {static_cast<wchar_t>(icon_index::fit), 0};
const auto icon_text_converted = core::utf8_to_utf16(core::utf16_to_utf8(icon_text));
assert_equal(icon_text, icon_text_converted, "icon to utf8");
// Verify icon_to_utf8 matches the old wchar_t + utf16_to_utf8 approach
const auto icon_new = icon_to_utf8(icon_index::fit);
constexpr wchar_t icon_old_text[2] = {static_cast<wchar_t>(icon_index::fit), 0};
const auto icon_old = core::utf16_to_utf8(icon_old_text);
assert_equal(icon_old, icon_new, "icon_to_utf8 matches old approach");
assert_equal(true, icon_index::rotate_clockwise != icon_index::rotate_anticlockwise,
"the two rotations are different glyphs");
// Verify char32_to_utf8 round-trips for icon code points
std::string char32_result;
core::char32_to_utf8(std::back_inserter(char32_result), static_cast<uint32_t>(icon_index::fit) & 0xFFFF);
assert_equal(icon_old, char32_result, "char32_to_utf8 for icon");
// Verify every icon in the icon_index enum round-trips correctly through UTF-8
constexpr icon_index all_icons[] = {
// clang-format off
icon_index::add, icon_index::remove, icon_index::audio, icon_index::camera,
icon_index::cancel, icon_index::check, icon_index::del, icon_index::edit,
icon_index::folder, icon_index::search, icon_index::star, icon_index::star_solid,
icon_index::play, icon_index::pause, icon_index::stop, icon_index::copyright,
icon_index::photo, icon_index::video, icon_index::settings, icon_index::save,
icon_index::rotate_clockwise, icon_index::rotate_anticlockwise,
icon_index::fit, icon_index::zoom_in, icon_index::zoom_out,
// clang-format on
};
for (const auto icon : all_icons)
{
const auto icon_val = static_cast<uint32_t>(icon) & 0xFFFF;
const wchar_t expected_utf16[2] = {static_cast<wchar_t>(icon_val), 0};
const auto expected_utf8 = platform::utf16_to_utf8(expected_utf16);
// icon_to_utf8 should produce correct UTF-8
const auto actual_utf8 = icon_to_utf8(icon);
assert_equal(expected_utf8, actual_utf8, std::format("icon_to_utf8 for 0x{:X}", static_cast<uint32_t>(icon)));
// UTF-8 should be exactly 3 bytes for BMP icons >= 0x800
if (icon_val >= 0x800)
{
assert_equal(3, static_cast<int>(actual_utf8.size()),
std::format("icon UTF-8 byte count for 0x{:X}", icon_val));
}
// Round-trip: UTF-8 -> UTF-16 should recover the original code point
const auto round_tripped_utf16 = core::utf8_to_utf16(actual_utf8);
assert_equal(1, static_cast<int>(round_tripped_utf16.size()),
std::format("icon round-trip UTF-16 length for 0x{:X}", icon_val));
assert_equal(static_cast<int>(icon_val), round_tripped_utf16[0],
std::format("icon round-trip code point for 0x{:X}", icon_val));
// Also verify str:: matches platform:: conversion
const auto platform_utf16 = platform::utf8_to_utf16(actual_utf8);
assert_equal(platform_utf16, round_tripped_utf16,
std::format("icon str vs platform utf8_to_utf16 for 0x{:X}", icon_val));
}
}
static void should_split()
{
constexpr auto to_be_split = "H:\\2-Archief VIDEO privé\\Eigen video's\nF:\\1-Archief FOTOGRAFIE privé";
const auto parts = core::split(to_be_split, false, [](const char c) { return c == '\n' || c == '\r'; });
assert_equal("H:\\2-Archief VIDEO privé\\Eigen video's", parts[0], "Split 1");
assert_equal("F:\\1-Archief FOTOGRAFIE privé", parts[1], "Split 2");
constexpr auto to_be_split2 = "aaa 'bbb ccc' ddd \"ee ff \"";
const auto parts2 = core::split(to_be_split2, true);
constexpr auto to_be_split3 = "Доброго ранку!";
const auto parts3 = core::split(to_be_split3, true);
assert_equal("aaa", parts2[0], "Split 1");
assert_equal("bbb ccc", parts2[1], "Split 2");
assert_equal("ddd", parts2[2], "Split 3");
assert_equal("ee ff ", parts2[3], "Split 4");
assert_equal("ранку!", parts3[1], "Split 5");
const auto internal_quote = core::split("Jane O'Brien; Alex", true, core::is_artist_separator);
assert_equal(2_z, internal_quote.size(), "internal apostrophe does not merge names");
assert_equal("Jane O'Brien", internal_quote[0], "internal apostrophe is preserved");
assert_equal(" Alex", internal_quote[1], "separator policy still owns surrounding spaces");
const auto quoted_separators = core::split("'Jane; O\\'Brien';\"Alex, Pat\";Sam", true, core::is_artist_separator);
assert_equal(3_z, quoted_separators.size(), "outer quotes protect separators");
assert_equal("Jane; O\\'Brien", quoted_separators[0], "single-quoted separator");
assert_equal("Alex, Pat", quoted_separators[1], "double-quoted separator");
assert_equal("Sam", quoted_separators[2], "unquoted tail");
const auto spaced_quote = core::split("Jane; \"Smith; Pat\"", true, core::is_artist_separator);
assert_equal(2_z, spaced_quote.size(), "quote after separator whitespace wraps");
assert_equal("Smith; Pat", spaced_quote[1], "separator whitespace is outside the wrapping quote");
const auto quoted_prefix = core::split("\"Weird Al\" Yankovic; Madonna", true, core::is_artist_separator);
assert_equal(2_z, quoted_prefix.size(), "quoted prefix does not swallow artist separator");
assert_equal("\"Weird Al\" Yankovic", quoted_prefix[0], "quoted prefix stays literal");
assert_equal(" Madonna", quoted_prefix[1], "quoted prefix tail splits");
const auto quote_with_space_before_separator = core::split("\"Doe, Jane\" ; Alex", true, core::is_artist_separator);
assert_equal(2_z, quote_with_space_before_separator.size(), "space before separator keeps wrapping quote");
assert_equal("Doe, Jane", quote_with_space_before_separator[0], "wrapped token before spaced separator");
assert_equal(" Alex", quote_with_space_before_separator[1], "spaced separator tail splits");
const auto quote_with_trailing_space = core::split("\"Doe, Jane\" ", true, core::is_artist_separator);
assert_equal(1_z, quote_with_trailing_space.size(), "trailing whitespace keeps wrapping quote");
assert_equal("Doe, Jane", quote_with_trailing_space[0], "trailing whitespace outside quote");
// A tab separates artists and genres while a space does not; skipping whitespace after a closing
// quote must stop at that separator rather than carry on past it.
for (const auto& pred :
{std::function<bool(char)>(core::is_artist_separator), std::function<bool(char)>(core::is_genre_separator)})
{
const auto quote_space_tab = core::split("\"Doe, Jane\" \tAlex", true, pred);
assert_equal(2_z, quote_space_tab.size(), "space then tab after a closing quote ends the token");
assert_equal("Doe, Jane", quote_space_tab[0], "quoted token before a space and tab separator");
assert_equal("Alex", quote_space_tab[1], "token after a space and tab separator");
}
const auto quoted_first_word = core::split("Jane Doe; 'Bud' Abbott; Lou Costello", true, core::is_artist_separator);
assert_equal(3_z, quoted_first_word.size(), "quoted first word does not swallow later separators");
assert_equal(" 'Bud' Abbott", quoted_first_word[1], "quoted first word stays literal");
assert_equal(" Lou Costello", quoted_first_word[2], "tail after quoted first word splits");
const auto unmatched_leading_quote = core::split("Alex; 'Til Tuesday; Bob", true, core::is_artist_separator);
assert_equal(3_z, unmatched_leading_quote.size(), "unmatched leading quote does not swallow later separators");
assert_equal(" 'Til Tuesday", unmatched_leading_quote[1], "unmatched leading quote stays literal");
assert_equal(" Bob", unmatched_leading_quote[2], "tail after unmatched quote splits");
const auto collection_roots = core::split("\"C:\\Photos\"\n\"D:\\\"", true,
[](const char c) { return c == '\n' || c == '\r'; });
assert_equal(2_z, collection_roots.size(), "quoted collection roots split");
assert_equal("C:\\Photos", collection_roots[0], "quoted collection root");
assert_equal("D:\\", collection_roots[1], "quoted drive root keeps trailing slash");
const auto command_line_drive = core::split("\"D:\\\" -no-gpu", true, core::is_white_space);
assert_equal(2_z, command_line_drive.size(), "quoted drive-root argument splits from switch");
assert_equal("D:\\", command_line_drive[0], "quoted drive-root argument");
assert_equal("-no-gpu", command_line_drive[1], "switch after quoted drive-root");
const auto command_line_trailing_slash = core::split("\"C:\\My Photos\\\" -no-gpu", true, core::is_white_space);
assert_equal(2_z, command_line_trailing_slash.size(), "quoted trailing-slash path splits from switch");
assert_equal("C:\\My Photos\\", command_line_trailing_slash[0], "quoted trailing-slash path");
assert_equal("-no-gpu", command_line_trailing_slash[1], "switch after quoted trailing-slash path");
std::string long_escaped_artist;
constexpr auto escaped_artist_count = 50'000;
for (auto i = 0; i < escaped_artist_count; ++i)
{
if (i != 0) long_escaped_artist += '\\';
long_escaped_artist += "'a";
}
const auto long_escaped_artist_parts = core::split(long_escaped_artist, true, core::is_artist_separator);
assert_equal(static_cast<size_t>(escaped_artist_count), long_escaped_artist_parts.size(),
"long escaped-quote artist text splits");
assert_equal("'a", long_escaped_artist_parts.front(), "long escaped-quote first token");
assert_equal("'a", long_escaped_artist_parts.back(), "long escaped-quote last token");
for (const auto part : long_escaped_artist_parts)
{
assert_equal("'a", part, "long escaped-quote token");
}
// The same chain ending in a quote that cannot close: every token-start quote stops at that final
// quote, which the scan caches instead of rescanning to it once per token (linearity was verified
// separately; this asserts the tokens).
const auto stopped_chain = long_escaped_artist + "'b";
const auto stopped_chain_parts = core::split(stopped_chain, true, core::is_artist_separator);
assert_equal(static_cast<size_t>(escaped_artist_count), stopped_chain_parts.size(),
"escaped-quote chain ending in an unclosed quote splits");
assert_equal("'a", stopped_chain_parts.front(), "stopped chain first token");
assert_equal("'a'b", stopped_chain_parts.back(), "stopped chain keeps the unclosed quote literal");
std::string long_blank = "A;";
long_blank.append(200'000, ' ');
long_blank += 'B';
const auto long_blank_parts = core::split(long_blank, true, core::is_artist_separator);
assert_equal(2_z, long_blank_parts.size(), "long whitespace-prefix token splits");
assert_equal("A", long_blank_parts[0], "long whitespace first token");
assert_equal(200'001_z, long_blank_parts[1].size(), "long whitespace token length");
assert_equal(' ', long_blank_parts[1].front(), "long whitespace token starts with space");
assert_equal('B', long_blank_parts[1].back(), "long whitespace token keeps tail");
const auto mixed_quotes = core::split("\"Jane 'JJ' Doe\" 'Alex \"Ace\" Roe' \"unmatched", true);
assert_equal(3_z, mixed_quotes.size(), "mixed quote characters split into tokens");
assert_equal("Jane 'JJ' Doe", mixed_quotes[0], "inner single quotes preserved");
assert_equal("Alex \"Ace\" Roe", mixed_quotes[1], "inner double quotes preserved");
assert_equal("\"unmatched", mixed_quotes[2], "unmatched wrapping quote stays literal");
// Random data checking for crashes
std::string_view strings[] = {
"In vollen Zügen genießen",
"Nældens takvinge",
"Žižkov",
"Доброго ранку!",
"Japanese こんにちは世界",
"Arabic مرحبا العالم",
"Доброго ранку!",
"\"'",
"\" \" \"",
"''''",
"aaa'bb bbb'aa",
"aaa\0\0\'",
"\r\t\naaaa\" aaa bbb",
"'\t \n abc",
"'",
};
for (const auto& src : strings)
{
core::split_count(src, true);
}
}
static void should_split_genre()
{
// Genre values use ';' as the multi-value separator. Multi-word genres and
// genres containing '&' or '/' must survive splitting intact.
const auto parts = core::split("Rock; Pop ; Hip Hop", false, core::is_genre_separator);
assert_equal(size_t{3}, parts.size(), "genre part count");
assert_equal("Rock", core::trim(parts[0]), "genre 1");
assert_equal("Pop", core::trim(parts[1]), "genre 2");
assert_equal("Hip Hop", core::trim(parts[2]), "genre 3");
const auto parts2 = core::split("Action & Adventure; R&B/Soul", false, core::is_genre_separator);
assert_equal(size_t{2}, parts2.size(), "genre part count 2");
assert_equal("Action & Adventure", core::trim(parts2[0]), "genre with ampersand");
assert_equal("R&B/Soul", core::trim(parts2[1]), "genre with slash");
const auto parts3 = core::split("Jazz", false, core::is_genre_separator);
assert_equal(size_t{1}, parts3.size(), "single genre part count");
assert_equal("Jazz", core::trim(parts3[0]), "single genre");
}
static void should_parse_dates()
{
const auto parsed = [](const std::string_view text)
{
core::date_t d;
return d.parse(text) ? d.date() : core::day_t{0};
};
assert_equal(2006, parsed("2006-01-14 15:51:31").year, "an ISO date parses");
assert_equal(31, parsed("2006-01-14 15:51:31").second, "including its seconds");
assert_equal(2006, parsed("2006:01:14 15:51:31").year, "an EXIF date parses");
assert_equal(13, parsed("2011-10-03T02:59:13.000000Z").second, "fractional seconds truncate to the second");
// The seconds field is read with %lg, which accepts "inf", "nan" and an overflowing exponent.
// Converting any of those to int is undefined, so they fail the parse instead of reaching it.
core::date_t d;
assert_equal(false, d.parse("2006-01-14 15:51:inf"), "infinite seconds is not a date");
assert_equal(false, d.parse("2006-01-14 15:51:nan"), "seconds that are not a number is not a date");
assert_equal(false, d.parse("2006-01-14 15:51:1e400"), "an overflowing seconds exponent is not a date");
assert_equal(false, d.parse("2006-01-14 15:51:-1"), "negative seconds is not a date");
assert_equal(false, d.parse("2006-01-14 15:51:99"), "seconds past a leap second is not a date");
assert_equal(true, d.parse("2006-01-14 15:51:60"), "a leap second still is");
}
#ifndef _WIN32
static void should_convert_local_dates_with_date_specific_rules()
{
assert_equal(uint64_t{0}, platform::utc_to_local(0), "an absent UTC timestamp remains absent");
assert_equal(uint64_t{0}, platform::local_to_utc(0), "an absent local timestamp remains absent");
const std::array days = {
core::day_t{2024, 1, 15, 12, 0, 0},
core::day_t{2024, 7, 15, 12, 0, 0},
core::day_t{2024, 3, 10, 3, 30, 0},
core::day_t{2024, 11, 3, 3, 30, 0},
};
for (const auto& day : days)
{
std::tm local{};
local.tm_year = day.year - 1900;
local.tm_mon = day.month - 1;
local.tm_mday = day.day;
local.tm_hour = day.hour;
local.tm_min = day.minute;
local.tm_isdst = -1;
const auto unix_time = std::mktime(&local);
constexpr uint64_t fraction = 1234567;
const auto expected = (static_cast<int64_t>(unix_time) + 11644473600ll) * 10000000ll + fraction;
const auto wall = core::date_t(day.year, day.month, day.day, day.hour, day.minute, 0).to_int64() + fraction;
assert_equal(expected, platform::local_to_utc(wall),
"local conversion matches the date-specific timezone rule");
}
}
#endif
static void should_extract_url()
{
constexpr auto input1 = "Visit my website at https://www.example.com for more info.";
constexpr auto input2 = "Check out this article: http://anotherexample.org/article";
constexpr auto input3 = "No URLs here.";
constexpr auto input4 =
"Quite nice <a href=\"http://bighugelabs.com/flickr/onblack.php?id=1397504988\"> On Black</a>";
assert_equal("https://www.example.com", core::url_extract(input1), "extract url");
assert_equal("http://anotherexample.org/article", core::url_extract(input2), "extract url");
assert_equal("", core::url_extract(input3), "extract url");
assert_equal("", core::url_extract(input3), "extract url");
assert_equal("http://bighugelabs.com/flickr/onblack.php?id=1397504988", core::url_extract(input4), "extract url");
// A description panel offering a choice of links needs every distinct one, in reading order.
const auto all = core::url_extract_all(
"See https://example.com/a and https://example.com/b then https://example.com/a again.");
assert_equal(size_t{2}, all.size(), "repeated url listed once");
assert_equal("https://example.com/a", all[0], "first url in source order");
assert_equal("https://example.com/b", all[1], "second url in source order");
assert_equal(size_t{0}, core::url_extract_all(input3).size(), "no urls found");
}
static void should_match_wildcard()
{
assert_equal(true, core::wildcard_icmp("", ""));
assert_equal(true, core::wildcard_icmp("", "*"));
assert_equal(true, core::wildcard_icmp(" ", "*"));
assert_equal(true, core::wildcard_icmp(" ", " *"));
assert_equal(false, core::wildcard_icmp(" ", " *"));
assert_equal(true, core::wildcard_icmp("hello world", "hello world"));
assert_equal(true, core::wildcard_icmp("hello ?! world", "hello * world"));
assert_equal(true, core::wildcard_icmp("hello-xx-world", "hello*world"));
assert_equal(false, core::wildcard_icmp("hello-xx-world", "hello *world"));
assert_equal(true, core::wildcard_icmp("hello-xx-world", "*world"));
assert_equal(true, core::wildcard_icmp("hello-xx-world", "hello*"));
assert_equal(true, core::wildcard_icmp("HELLO-XX-WORLD", "hello*"));
assert_equal(true, core::wildcard_icmp("HELLO-XX-WORLD", "hello*world"));
assert_equal(0, core::icmp("ДОБРОГО РАНКУ", "Доброго ранку"));
assert_equal(0, core::icmp("ARABIC مرحبا العالم", "Arabic مرحبا العالم"));
assert_equal(0, core::icmp("JAPANESE こんにちは世界", "Japanese こんにちは世界"));
assert_equal(0, core::icmp("💉💎👦🏻👓⚡", "💉💎👦🏻👓⚡"));
assert_equal(true, core::wildcard_icmp("Доброго ранку", "Доброго*"));
assert_equal(true, core::wildcard_icmp("ДОБРОГО РАНКУ", "Доброго*"));
assert_equal(true, core::wildcard_icmp("ДОБРОГО РАНКУ", "*ранку"));
assert_equal(true, core::wildcard_icmp("💉💎👦🏻👓⚡", "*💎*"));
assert_equal(true, core::wildcard_icmp("💉💎👦🏻👓⚡", "💉*"));
assert_equal(true, core::wildcard_icmp("Οδός", "οδ*"));
assert_equal(false, core::wildcard_icmp("Οδός", "sd*"));
}
static void should_detect_wildcard()
{
assert_equal(false, core::is_wildcard(""));
assert_equal(false, core::is_wildcard("abcdef"));
assert_equal(true, core::is_wildcard("abc*"));
assert_equal(false, core::is_wildcard("abc\\*"));
assert_equal(false, core::is_wildcard("abc\\*ef"));
}
static void should_parse_command_line()
{
command_line_t cl1;
cl1.parse("-no-gpu");
assert_equal(true, cl1.no_gpu, "no_gpu");
assert_equal(false, cl1.no_indexing, "no_indexing");
command_line_t cl2;
cl2.parse(test_files_folder().text());
assert_equal(false, cl2.folder_path.is_empty(), "folder_path");
assert_equal(std::string_view{}, cl2.selection.name(), "selection name");
assert_equal(test_files_folder().text(), cl2.folder_path.folder().text(), "folder path");
assert_equal(false, cl2.no_gpu, "no_gpu");
assert_equal(false, cl2.no_indexing, "no_indexing");
// The fixture's own spelling: a case-folded name only resolves on a case-insensitive volume.
const auto path3 = test_files_folder().combine_file("Test.jpg");
command_line_t cl3;
cl3.parse(std::format("{} -no-indexing", path3));
assert_equal(path3.folder().text(), cl3.folder_path.folder().text(), "folder_path");
assert_equal(path3.name(), cl3.selection.name(), "selection name");
assert_equal(path3.folder().text(), cl3.selection.folder().text(), "selection folder");
assert_equal(false, cl3.no_gpu, "no_gpu");
assert_equal(true, cl3.no_indexing, "no_indexing");
// The subject is that quotes hold a spaced path together as one part, so the folder is made
// here rather than borrowed from whatever the platform happens to install.