-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
3318 lines (3001 loc) · 140 KB
/
main.cpp
File metadata and controls
3318 lines (3001 loc) · 140 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
/* Developed by Jimmy Hu */
/* Refactored for CLI Application capability */
// compile command:
// clang++ -std=c++20 -Xpreprocessor -fopenmp -I/usr/local/include -L/usr/local/lib -lomp main.cpp -L /usr/local/Cellar/llvm/10.0.0_3/lib/ -lm -O3 -o main -v
// https://stackoverflow.com/a/61821729/6667035
// clear && rm -rf ./main && g++-11 -std=c++20 -O4 -ffast-math -funsafe-math-optimizations -std=c++20 -fpermissive -H --verbose -Wall main.cpp -o main
//#define USE_BOOST_ITERATOR
//#define USE_BOOST_SERIALIZATION
// Standard Library Headers
#include <algorithm>
#include <any>
#include <array>
#include <charconv>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <charconv>
#include <execution>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <type_traits>
#include <valarray>
#include <vector>
// Local Headers
#include "basic_functions.h"
#include "image_io.h"
#include "image_operations.h"
#include "timer.h"
//#define BOOST_TEST_DYN_LINK
//#define BOOST_TEST_MODULE image_elementwise_tests
#ifdef BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif // BOOST_TEST_DYN_LINK
#include <boost/mpl/list.hpp>
#include <boost/mpl/vector.hpp>
#include <tao/tuple/tuple.hpp>
typedef boost::mpl::list<
byte, char, int, short, long, long long int,
unsigned int, unsigned short int, unsigned long int, unsigned long long int,
float, double, long double> test_types;
// [TODO] Avoid code duplication (https://codereview.stackexchange.com/a/267709/231235)
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
/*
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_zero_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T divider = 0;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider)); // dividing by zero test
}
*/
#endif
void difference_and_enhancement(std::string input_path1, std::string input_path2, double enhancement_times)
{
if (input_path1.empty())
{
std::cerr << "Input path is empty!";
}
std::filesystem::path input1 = input_path1;
std::filesystem::path input2 = input_path2;
}
#ifndef BOOST_TEST_MODULE
void addLeadingZeros(std::string input_path, std::string output_path);
// parse_arg template function implementation
// Helper for converting string to numeric types safely
template <typename T>
T parse_arg(const std::string_view sv)
{
T result{};
if constexpr (std::is_arithmetic_v<T>)
{
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + std::ranges::size(sv), result);
if (ec != std::errc())
{
throw std::invalid_argument(std::string("Error parsing argument: ") + std::string(sv));
}
}
else
{
// Fallback for non-arithmetic types (unlikely to be used with this function in current context)
// This path forces allocation, but is rarely hit for numeric parsing
std::string temp(sv);
std::stringstream ss(temp);
if (!(ss >> result))
{
throw std::invalid_argument(std::string("Error parsing argument: ") + temp);
}
}
return result;
}
void print(auto comment, auto const& seq, char term = ' ') {
for (std::cout << comment << '\n'; auto const& elem : seq)
std::cout << elem << term;
std::cout << '\n';
}
auto myHighLightRegion_parameters(const std::size_t index = 0)
{
std::vector<std::tuple<
std::string, // filenames
std::size_t, // start_index
std::size_t, // end_index
std::size_t, // startx
std::size_t, // endx
std::size_t, // starty
std::size_t, // endy
std::string // output_location
>> collection;
}
// ------------------------------------------------------------------------------------
// Iterable Container Detection Traits
// ------------------------------------------------------------------------------------
// is_vector template struct implementation
template <typename T> struct is_vector : std::false_type {};
template <typename T, typename A> struct is_vector<std::vector<T, A>> : std::true_type {};
template <typename T> inline constexpr bool is_vector_v = is_vector<T>::value;
template <typename T> struct is_deque : std::false_type {};
template <typename T, typename A> struct is_deque<std::deque<T, A>> : std::true_type {};
template <typename T> inline constexpr bool is_deque_v = is_deque<T>::value;
template <typename T> struct is_list : std::false_type {};
template <typename T, typename A> struct is_list<std::list<T, A>> : std::true_type {};
template <typename T> inline constexpr bool is_list_v = is_list<T>::value;
template <typename T> struct is_std_array : std::false_type {};
template <typename T, std::size_t N> struct is_std_array<std::array<T, N>> : std::true_type {};
template <typename T> inline constexpr bool is_std_array_v = is_std_array<T>::value;
// match_any_type template function implementation
template <typename TupleT, class FunT>
constexpr bool match_any_type(FunT&& func)
{
return [&]<template <typename...> class TupleLike, typename... Ts>(std::type_identity<TupleLike<Ts...>>)
{
return (... || std::forward<FunT>(func).template operator()<Ts>());
}(std::type_identity<TupleT>{});
}
// ------------------------------------------------------------------------------------
// Advanced Metaprogramming Type Generation Registries
// ------------------------------------------------------------------------------------
// Core Fundamental Types
using core_numeric_types = std::tuple<
bool, char, signed char, unsigned char,
short, unsigned short, int, unsigned int,
long, unsigned long, long long, unsigned long long,
std::int8_t, std::int16_t, std::int32_t, std::int64_t,
std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t,
float, double, long double, std::size_t, std::ptrdiff_t
>;
using core_floating_point_types = std::tuple<float, double, long double>;
// Metaprogramming Mapping Tools
template <template <typename...> class Wrapper, typename Tuple>
struct tuple_map;
template <template <typename...> class Wrapper, typename... Ts>
struct tuple_map<Wrapper, std::tuple<Ts...>>
{
using type = std::tuple<Wrapper<Ts>...>;
};
template <template <typename...> class Wrapper, typename Tuple>
using tuple_map_t = typename tuple_map<Wrapper, Tuple>::type;
template <typename... Tuples>
using tuple_cat_t = decltype(std::tuple_cat(std::declval<Tuples>()...));
// -----------------------------------------------------------------------------
// Advanced NTTP Metaprogramming: Dynamic Array Size Generation
// -----------------------------------------------------------------------------
// Generate an index sequence representing [Min, Max]
template <std::size_t Min, std::size_t Max, std::size_t... Is>
constexpr auto make_range_sequence_impl(std::index_sequence<Is...>)
{
return std::index_sequence<(Min + Is)...>{};
}
template <std::size_t Min, std::size_t Max>
requires (Min <= Max)
using make_range_sequence = decltype(make_range_sequence_impl<Min, Max>(std::make_index_sequence<Max - Min + 1>{}));
// Map an entire Tuple of types to std::array<T, N> for a fixed size N
template <typename Tuple, std::size_t N>
struct make_array_tuple;
template <typename... Ts, std::size_t N>
struct make_array_tuple<std::tuple<Ts...>, N>
{
using type = std::tuple<std::array<Ts, N>...>;
};
// Perform a cartesian product: Concatenate make_array_tuple for all Ns in the sequence
template <typename Tuple, typename IndexSeq>
struct generate_arrays_impl;
template <typename Tuple, std::size_t... Ns>
struct generate_arrays_impl<Tuple, std::index_sequence<Ns...>>
{
// Expands to tuple_cat_t< std::tuple<std::array<Ts, 3>...>, std::tuple<std::array<Ts, 4>...>, ... >
using type = tuple_cat_t<typename make_array_tuple<Tuple, Ns>::type...>;
};
// User-friendly alias
template <typename Tuple, std::size_t Min, std::size_t Max>
using generate_arrays_t = typename generate_arrays_impl<Tuple, make_range_sequence<Min, Max>>::type;
// Helper aliases to bridge TinyDIP's Non-Type Template Parameters (NTTP) for tuple mapping
template <typename T>
using multichannel_t = TinyDIP::MultiChannel<T>;
template <typename T>
using image_t = TinyDIP::Image<T>;
// Exhaustive Derived Type Auto-Generation
using all_multichannel_types = tuple_map_t<multichannel_t, core_numeric_types>;
using all_complex_types = tuple_map_t<std::complex, core_floating_point_types>;
using all_complex_multichannel_types = tuple_map_t<multichannel_t, all_complex_types>;
using all_vector_types = tuple_map_t<std::vector, core_numeric_types>;
using all_deque_types = tuple_map_t<std::deque, core_numeric_types>;
using all_list_types = tuple_map_t<std::list, core_numeric_types>;
using all_array_types = generate_arrays_t<core_numeric_types, 3, 4>;
using all_custom_scalar_types = std::tuple<TinyDIP::RGB, TinyDIP::RGB_DOUBLE, TinyDIP::HSV>;
// Master Scalar Tuple (Exhaustively includes ALL valid scalar and container output types)
using master_scalar_types = tuple_cat_t<
core_numeric_types,
all_custom_scalar_types,
all_multichannel_types,
all_complex_types,
all_complex_multichannel_types,
all_vector_types,
all_deque_types,
all_list_types,
all_array_types
>;
// Master Image Tuple (Exhaustively includes ALL valid image structures)
using master_image_types = tuple_cat_t<
tuple_map_t<image_t, core_numeric_types>,
tuple_map_t<image_t, all_custom_scalar_types>,
tuple_map_t<image_t, all_multichannel_types>,
tuple_map_t<image_t, all_complex_types>,
tuple_map_t<image_t, all_complex_multichannel_types>
>;
// Master Data Tuple (Exhaustively includes ALL valid image structures AND containers)
using master_data_types = tuple_cat_t<
master_image_types,
all_vector_types,
all_deque_types,
all_list_types,
all_array_types
>;
// Distinct tuple exclusively tailored for segregating complex formatting logic natively
using complex_scalar_types_for_printing = tuple_cat_t<
all_custom_scalar_types,
all_multichannel_types,
all_complex_types,
all_complex_multichannel_types,
all_vector_types,
all_deque_types,
all_list_types,
all_array_types
>;
// get_type_name template function implementation
// Generic compile-time helper to automatically extract exact human-readable string views for any type.
// This utilizes compile-time SFINAE reflection over compiler signature macros.
template <typename T>
constexpr std::string_view get_type_name()
{
#if defined(__clang__)
constexpr std::string_view name = __PRETTY_FUNCTION__;
constexpr std::size_t start = name.find("T = ") + 4;
constexpr std::size_t end = name.find_last_of(']');
return name.substr(start, end - start);
#elif defined(__GNUC__)
constexpr std::string_view name = __PRETTY_FUNCTION__;
constexpr std::size_t start = name.find("with T = ") + 9;
constexpr std::size_t semi_colon_pos = name.find(';', start);
constexpr std::size_t end = (semi_colon_pos != std::string_view::npos) ? semi_colon_pos : name.find_last_of(']');
return name.substr(start, end - start);
#elif defined(_MSC_VER)
constexpr std::string_view name = __FUNCSIG__;
constexpr std::size_t start = name.find("get_type_name<") + 14;
constexpr std::size_t end = name.rfind(">(void)");
return name.substr(start, end - start);
#else
return "Unknown Type";
#endif
}
// execute_type_action template function implementation
template <typename TargetT, typename TupleT, typename FallbackFun, std::size_t I = 0>
constexpr decltype(auto) execute_type_action(TupleT&& action_map, FallbackFun&& fallback)
{
if constexpr (I < std::tuple_size_v<std::remove_cvref_t<TupleT>>)
{
using CurrentPair = std::tuple_element_t<I, std::remove_cvref_t<TupleT>>;
if constexpr (std::is_same_v<TargetT, typename CurrentPair::type>)
{
return std::get<I>(std::forward<TupleT>(action_map)).action();
}
else
{
return execute_type_action<TargetT, TupleT, FallbackFun, I + 1>(
std::forward<TupleT>(action_map), std::forward<FallbackFun>(fallback));
}
}
else
{
return std::forward<FallbackFun>(fallback)();
}
}
// Workspace struct implementation
// In-Memory Workspace for REPL session state
struct Workspace
{
std::map<std::string, std::any> memory_store;
template <typename T>
void store(const std::string_view name, T&& item)
{
memory_store[std::string(name)] = std::forward<T>(item);
}
template <typename T>
const T* retrieve(const std::string_view name) const
{
if (auto it = memory_store.find(std::string(name)); it != std::ranges::end(memory_store))
{
if (it->second.type() == typeid(T))
{
return std::any_cast<T>(&(it->second));
}
}
return nullptr;
}
// remove function implementation
bool remove(const std::string_view name)
{
const std::string key = std::string(name);
if (auto it = memory_store.find(key); it != std::ranges::end(memory_store))
{
memory_store.erase(it);
return true;
}
return false;
}
// rename function implementation
bool rename(const std::string_view old_name, const std::string_view new_name)
{
const std::string old_key(old_name);
if (auto it = memory_store.find(old_key); it != std::ranges::end(memory_store))
{
// Use std::move to natively transfer ownership of the type-erased object with zero-copy
memory_store[std::string(new_name)] = std::move(it->second);
memory_store.erase(it);
return true;
}
return false;
}
// Clear all elements in the workspace memory store
void clear()
{
memory_store.clear();
}
// list_variables function implementation
void list_variables(std::ostream& os) const
{
if (std::ranges::empty(memory_store))
{
os << " (Workspace is empty)\n";
return;
}
// print_size lambda implementation
// Generic lambda to cleanly format and print image dimensions
auto print_size = [&os](const std::ranges::random_access_range auto& size_range)
{
auto it = std::ranges::begin(size_range);
const auto end = std::ranges::end(size_range);
if (it != end)
{
os << +(*it);
++it;
for (; it != end; ++it)
{
os << " x " << +(*it);
}
}
};
for (const auto& [name, value] : memory_store)
{
auto print_prefix = [&]<typename T>()
{
os << " $" << std::left << std::setw(15) << name << " : [" << get_type_name<T>() << "]";
};
// Polymorphic lambda returning true if the image type matched
auto try_print_image = [&]<typename T>() -> bool
{
if (value.type() == typeid(T))
{
print_prefix.template operator()<T>();
os << ", size = ";
const auto* image_ptr = std::any_cast<T>(&value);
print_size(image_ptr->getSize());
return true;
}
return false;
};
// Polymorphic lambda returning true if the complex custom scalar type matched
auto try_print_complex_scalar = [&]<typename T>() -> bool
{
if (value.type() == typeid(T))
{
print_prefix.template operator()<T>();
if constexpr (is_vector_v<T> || is_deque_v<T> || is_list_v<T> || is_std_array_v<T>)
{
os << ", container value = {";
bool first = true;
const auto* container_ptr = std::any_cast<T>(&value);
for (const auto& elem : *container_ptr)
{
if (!first)
{
os << ", ";
}
os << +elem;
first = false;
}
os << "}";
}
else
{
os << ", scalar value = " << std::any_cast<T>(value);
}
return true;
}
return false;
};
if (match_any_type<master_image_types>(try_print_image))
{
// Handled successfully by try_print_image short-circuit logic
}
else if (match_any_type<complex_scalar_types_for_printing>(try_print_complex_scalar))
{
// Handled successfully by try_print_complex_scalar short-circuit logic
}
else
{
// Polymorphic lambda returning true if the numeric type matched
auto try_print_numeric = [&]<typename T>() -> bool
{
if (value.type() == typeid(T))
{
print_prefix.template operator()<T>();
if constexpr (sizeof(T) == 1 && std::is_integral_v<T>) // Safely print 8-bit integer types as numbers, not unprintable chars
{
os << ", scalar value = " << +std::any_cast<T>(value);
}
else
{
os << ", scalar value = " << std::any_cast<T>(value);
}
return true;
}
return false;
};
if (!match_any_type<core_numeric_types>(try_print_numeric))
{
os << " $" << std::left << std::setw(15) << name
<< " : [Type Hash: " << value.type().hash_code() << "] (Unsupported serialization type), type is " << value.type().name();
}
}
os << '\n';
}
}
};
// MetaImageIO struct implementation
// Generic struct to deal with Workspace memory mapping and direct File I/O operations dynamically
struct MetaImageIO
{
public:
struct Loader
{
template <typename ImageType = TinyDIP::Image<TinyDIP::RGB>>
constexpr ImageType operator()(const std::string_view arg, const std::shared_ptr<Workspace>& ws) const
{
if (arg.starts_with('$'))
{
const std::string_view var_name = arg.substr(1);
if (const ImageType* img_ptr = ws->retrieve<ImageType>(var_name))
{
return *img_ptr;
}
throw std::invalid_argument(std::string("Memory variable not found or type mismatch: ") + std::string(var_name));
}
const std::filesystem::path input_path = std::string(arg);
if (!std::filesystem::exists(input_path))
{
throw std::invalid_argument(std::string("File not found: ") + input_path.string());
}
if constexpr (std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::RGB>>)
{
return TinyDIP::bmp_read(input_path.string().c_str(), true);
}
else if constexpr (std::is_same_v<ImageType, TinyDIP::Image<double>>)
{
return TinyDIP::double_image::read(input_path.string().c_str(), true);
}
else if constexpr (
std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::RGB_DOUBLE>> ||
std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::HSV>> ||
std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::MultiChannel<double>>>
)
{
throw std::invalid_argument("Direct file reading is not implemented for this complex/high-precision image type.");
}
else
{
throw std::invalid_argument("Direct file reading is not explicitly implemented for this abstract/complex image type.");
}
}
};
struct Saver
{
template <typename ImageType>
constexpr void operator()(const std::string_view arg, const std::shared_ptr<Workspace>& ws, ImageType&& img) const
{
if (arg.starts_with('$'))
{
const std::string_view var_name = arg.substr(1);
ws->store(var_name, std::forward<ImageType>(img));
}
else
{
const std::filesystem::path output_filepath = std::string(arg);
const std::filesystem::path path_without_extension = output_filepath.parent_path() / output_filepath.stem();
if constexpr (std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<double>>)
{
TinyDIP::double_image::write(path_without_extension.string().c_str(), std::forward<ImageType>(img));
}
else if constexpr (std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::RGB>>)
{
TinyDIP::bmp_write(path_without_extension.string().c_str(), std::forward<ImageType>(img));
}
else if constexpr (
std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::RGB_DOUBLE>> ||
std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::HSV>> ||
std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::MultiChannel<double>>>
)
{
throw std::invalid_argument("Direct file writing is not implemented for this complex/high-precision image type.");
}
else
{
throw std::invalid_argument("Direct file writing is not explicitly implemented for this abstract/complex image type.");
}
}
}
};
};
// dispatch_data_operation template function implementation
// Generic helper to dynamically load and dispatch data (from memory or disk) to a processor lambda
template <typename CheckingTypes = master_image_types, typename ProcessorFun, typename ImageLoaderFun>
requires (std::invocable<ImageLoaderFun, const std::string_view, const std::shared_ptr<Workspace>&> &&
std::invocable<ProcessorFun, std::invoke_result_t<ImageLoaderFun, const std::string_view, const std::shared_ptr<Workspace>&>>)
constexpr bool dispatch_data_operation(
const std::string_view input_arg,
const std::shared_ptr<Workspace>& workspace,
ImageLoaderFun&& image_loader,
ProcessorFun&& processor)
{
if (input_arg.starts_with('$'))
{
const std::string_view var_name = input_arg.substr(1);
auto try_process = [&]<typename T>() -> bool
{
if (workspace->template retrieve<T>(var_name))
{
processor(image_loader.template operator()<T>(input_arg, workspace));
return true;
}
return false;
};
return match_any_type<CheckingTypes>(try_process);
}
else
{
const std::filesystem::path input_path = std::string(input_arg);
if (input_path.extension() == ".dbmp")
{
processor(image_loader.template operator()<TinyDIP::Image<double>>(input_arg, workspace));
}
else
{
processor(image_loader.template operator()<TinyDIP::Image<TinyDIP::RGB>>(input_arg, workspace));
}
return true;
}
}
// Custom Type-Erasure Wrapper (Concept-Model Idiom)
// This acts like std::any/std::function but enforces a highly optimized span boundary internally
class CommandHandler
{
private:
// The abstract interface (Concept)
struct Concept
{
virtual ~Concept() = default;
// Using std::span provides a zero-allocation, type-erased boundary for any contiguous range
virtual void call(std::span<const std::string_view> args, std::ostream& os) const = 0;
virtual std::unique_ptr<Concept> clone() const = 0;
};
// The concrete implementation wrapper (Model)
template <typename HandlerT>
struct Model final : Concept
{
HandlerT handler_;
constexpr explicit Model(HandlerT handler) : handler_(std::move(handler))
{
}
void call(std::span<const std::string_view> args, std::ostream& os) const override
{
// Forward the span argument to the generic operator() of the encapsulated handler
handler_(args, os);
}
std::unique_ptr<Concept> clone() const override
{
return std::make_unique<Model>(*this);
}
};
std::unique_ptr<Concept> pimpl_;
public:
// Default constructor
constexpr CommandHandler() noexcept : pimpl_(nullptr)
{
}
// Generic constructor for absolutely any callable
template <typename HandlerT>
requires (!std::same_as<std::decay_t<HandlerT>, CommandHandler>)
constexpr CommandHandler(HandlerT&& handler)
: pimpl_(std::make_unique<Model<std::decay_t<HandlerT>>>(std::forward<HandlerT>(handler)))
{
}
// Copy constructor (Deep copy of the type-erased object)
CommandHandler(const CommandHandler& other)
: pimpl_(other.pimpl_ ? other.pimpl_->clone() : nullptr)
{
}
// Move constructor
constexpr CommandHandler(CommandHandler&&) noexcept = default;
// Copy assignment
CommandHandler& operator=(const CommandHandler& other)
{
if (this != &other)
{
pimpl_ = other.pimpl_ ? other.pimpl_->clone() : nullptr;
}
return *this;
}
// Move assignment
constexpr CommandHandler& operator=(CommandHandler&&) noexcept = default;
// Execution operator
void operator()(std::span<const std::string_view> args, std::ostream& os) const
{
if (pimpl_)
{
pimpl_->call(args, os);
}
else
{
throw std::bad_function_call();
}
}
};
// IOSchema struct implementation
// Schema defining implicit argument positions for the pipeline engine to auto-inject memory variables
struct IOSchema
{
int in_idx = -1;
int out_idx = -1;
};
// Define human-readable pipeline schema routing constants globally
constexpr auto GeneratorSchema = IOSchema{ -1, 1 };
constexpr auto TerminatorSchema = IOSchema{ 0, -1 };
constexpr auto TransformerSchema = IOSchema{ 0, 1 };
constexpr auto IndependentSchema = IOSchema{ -1, -1 };
// CommandRegistry class implementation
class CommandRegistry
{
public:
struct CommandInfo
{
std::string description;
IOSchema schema;
CommandHandler handler;
};
private:
std::map<std::string, CommandInfo> commands;
public:
void register_command(const std::string_view name, const std::string_view description, const IOSchema schema, CommandHandler handler)
{
commands.emplace(std::string(name), CommandInfo{std::string(description), schema, std::move(handler)});
}
// Fallback for commands without pipeline routing specifications
void register_command(const std::string_view name, const std::string_view description, CommandHandler handler)
{
commands.emplace(std::string(name), CommandInfo{std::string(description), IOSchema{-1, -1}, std::move(handler)});
}
std::optional<IOSchema> get_schema(const std::string_view command_name) const
{
if (auto it = commands.find(std::string(command_name)); it != std::ranges::end(commands))
{
return it->second.schema;
}
return std::nullopt;
}
void list_commands(std::ostream& os = std::cout) const
{
os << "Available Commands:\n";
for (const auto& [name, info] : commands)
{
os << " " << std::left << std::setw(15) << name << " : " << info.description << "\n";
}
os << "\nUsage: ./tinydip <command> [args...]\n";
os << "Tip: Use '$name' to read/write from in-memory variables.\n";
os << "Tip: Chain commands with '|' pipelines. (e.g. read file.bmp | bicubic_resize 512 512 | $out)\n";
}
template <std::ranges::random_access_range ArgsT>
requires std::convertible_to<std::ranges::range_value_t<ArgsT>, std::string_view>
void execute(const std::string& command_name, const ArgsT& args, std::ostream& os = std::cout) const
{
if (auto it = commands.find(command_name); it != std::ranges::end(commands))
{
try
{
if constexpr (std::ranges::contiguous_range<ArgsT> && std::same_as<std::ranges::range_value_t<ArgsT>, std::string_view>)
{
it->second.handler(std::span<const std::string_view>{std::ranges::data(args), std::ranges::size(args)}, os);
}
else
{
std::vector<std::string_view> contiguous_args;
contiguous_args.reserve(std::ranges::size(args));
for (const auto& arg : args)
{
contiguous_args.emplace_back(arg);
}
it->second.handler(std::span<const std::string_view>{std::ranges::data(contiguous_args), std::ranges::size(contiguous_args)}, os);
}
}
catch (const std::exception& e)
{
os << "Error executing command '" << command_name << "': " << e.what() << "\n";
}
}
else
{
os << "Unknown command: " << command_name << "\n";
list_commands(os);
}
}
};
// --------------------------------------------------------------------------
// Workspace Memory Operation Handlers
// --------------------------------------------------------------------------
// MetaTransformHandler template struct implementation
// Generic Meta Handler strictly refactoring transform commands like abs, bicubic_resize, dct2, idct2, and lanczos_resample
template <std::size_t MinArgs, typename SetupFun, typename CheckingTypes = master_image_types>
struct MetaTransformHandler
{
std::string_view usage_string_;
std::shared_ptr<Workspace> workspace_;
SetupFun setup_fun_;
template <
std::ranges::random_access_range ArgsT,