-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.h
More file actions
2334 lines (2082 loc) · 93.9 KB
/
Copy pathmain.h
File metadata and controls
2334 lines (2082 loc) · 93.9 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
#ifndef TINYDIP_MAIN_H
#define TINYDIP_MAIN_H
// Standard Library Headers
#include <algorithm>
#include <any>
#include <array>
#include <charconv>
#include <cmath>
#include <complex>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <execution>
#include <filesystem>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <numbers>
#include <optional>
#include <random>
#include <ranges>
#include <span>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <tuple>
#include <typeinfo>
#include <type_traits>
#include <utility>
#include <vector>
// Local Headers
#include "basic_functions.h"
#include "image_io.h"
#include "image_operations.h"
#include "timer.h"
// sanitize_string_view function implementation
// Helper for safely sanitizing cross-platform path strings and REPL tokens natively with zero allocations
constexpr std::string_view sanitize_string_view(std::string_view sv)
{
auto is_junk = [](unsigned char c) { return std::isspace(c) || c == '\r' || c == '\n' || c == '\"' || c == '\''; };
while (!sv.empty() && is_junk(static_cast<unsigned char>(sv.back())))
{
sv.remove_suffix(1);
}
while (!sv.empty() && is_junk(static_cast<unsigned char>(sv.front())))
{
sv.remove_prefix(1);
}
return sv;
}
// parse_arg template function implementation
// Helper for converting string to numeric types safely
template <typename T>
T parse_arg(const std::string_view sv)
{
const std::string_view clean_sv = sanitize_string_view(sv);
T result{};
if constexpr (std::is_arithmetic_v<T>)
{
auto [ptr, ec] = std::from_chars(clean_sv.data(), clean_sv.data() + std::ranges::size(clean_sv), result);
if (ec != std::errc())
{
throw std::invalid_argument(std::string("Error parsing argument: ") + std::string(clean_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(clean_sv);
std::stringstream ss(temp);
if (!(ss >> result))
{
throw std::invalid_argument(std::string("Error parsing argument: ") + temp);
}
}
return result;
}
// ------------------------------------------------------------------------------------
// 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>;
// gaussian_params_t helper alias
// gaussian_params_t is a helper alias to bridge GaussianParameters2D's NTTP for tuple mapping.
// Helper alias to bridge GaussianParameters2D's NTTP for tuple mapping
template <typename T>
using gaussian_params_t = TinyDIP::GaussianParameters2D<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>;
using all_gaussian_params_types = tuple_map_t<gaussian_params_t, core_floating_point_types>;
// 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,
all_gaussian_params_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,
all_gaussian_params_types
>;
using all_vector_image_types = tuple_map_t<std::vector, master_image_types>;
using all_deque_image_types = tuple_map_t<std::deque, master_image_types>;
using all_list_image_types = tuple_map_t<std::list, master_image_types>;
// master_image_container_types type is used to identify all container types
// that hold images, which allows the workspace listing function to apply special
// formatting logic for these types (e.g. printing count and first image size) without having to check each container type separately.
using master_image_container_types = tuple_cat_t<
all_vector_image_types,
all_deque_image_types,
all_list_image_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;
mutable std::mutex mtx;
template <typename T>
void store(const std::string_view name, T&& item)
{
std::lock_guard<std::mutex> lock(mtx);
memory_store[std::string(sanitize_string_view(name))] = std::forward<T>(item);
}
template <typename T>
const T* retrieve(const std::string_view name) const
{
std::lock_guard<std::mutex> lock(mtx);
if (auto it = memory_store.find(std::string(sanitize_string_view(name))); it != std::ranges::end(memory_store))
{
if (it->second.type() == typeid(T))
{
return std::any_cast<T>(&(it->second));
}
}
return nullptr;
}
// retrieve_any function implementation
std::optional<std::any> retrieve_any(const std::string_view name) const
{
std::lock_guard<std::mutex> lock(mtx);
if (auto it = memory_store.find(std::string(sanitize_string_view(name))); it != std::ranges::end(memory_store))
{
return it->second;
}
return std::nullopt;
}
// remove function implementation
bool remove(const std::string_view name)
{
std::lock_guard<std::mutex> lock(mtx);
const std::string key = std::string(sanitize_string_view(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)
{
std::lock_guard<std::mutex> lock(mtx);
const std::string old_key(sanitize_string_view(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(sanitize_string_view(new_name))] = std::move(it->second);
memory_store.erase(it);
return true;
}
return false;
}
// Clear all elements in the workspace memory store
void clear()
{
std::lock_guard<std::mutex> lock(mtx);
memory_store.clear();
}
// list_variables function implementation
void list_variables(std::ostream& os) const
{
std::lock_guard<std::mutex> lock(mtx);
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 image container type matched
auto try_print_image_container = [&]<typename T>() -> bool
{
if (value.type() == typeid(T))
{
print_prefix.template operator()<T>();
const auto* container_ptr = std::any_cast<T>(&value);
os << ", count = " << std::ranges::size(*container_ptr);
if (!std::ranges::empty(*container_ptr))
{
os << " (first image size: ";
print_size(std::ranges::begin(*container_ptr)->getSize());
os << ")";
}
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<master_image_container_types>(try_print_image_container))
{
// Handled successfully by try_print_image_container 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, 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::string_view clean_arg = sanitize_string_view(arg);
const std::filesystem::path input_path = std::string(clean_arg);
const bool has_ext = input_path.has_extension();
std::string ext{};
if (has_ext)
{
ext = input_path.extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
}
if constexpr (std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::RGB>>)
{
if (ext == ".ppm")
{
return TinyDIP::pnm::read(input_path);
}
return TinyDIP::bmp_read(input_path.string().c_str(), has_ext);
}
else if constexpr (std::is_same_v<ImageType, TinyDIP::Image<double>>)
{
if (ext == ".csv")
{
return TinyDIP::double_image::read_from_csv(input_path.string().c_str());
}
return TinyDIP::double_image::read(input_path.string().c_str(), has_ext);
}
else if constexpr (std::is_same_v<ImageType, TinyDIP::Image<TinyDIP::HSV>>)
{
return TinyDIP::hsv_read(input_path.string().c_str(), has_ext);
}
else
{
throw std::invalid_argument("Direct file reading is not explicitly implemented for this abstract/complex data type.");
}
}
};
struct Saver
{
template <typename ImageType>
constexpr void operator()(const std::string_view arg, 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::string_view clean_arg = sanitize_string_view(arg);
const std::filesystem::path output_filepath = std::string(clean_arg);
const bool has_ext = output_filepath.has_extension();
std::string ext{};
if (has_ext)
{
ext = output_filepath.extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
}
const std::filesystem::path base_path = has_ext ? (output_filepath.parent_path() / output_filepath.stem()) : output_filepath;
if constexpr (std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<double>>)
{
if (ext == ".csv")
{
TinyDIP::double_image::write_to_csv(output_filepath.string().c_str(), std::forward<ImageType>(img));
}
else
{
TinyDIP::double_image::write(base_path.string().c_str(), std::forward<ImageType>(img));
}
}
else if constexpr (std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::RGB>>)
{
if (ext == ".ppm")
{
TinyDIP::pnm::write(std::forward<ImageType>(img), output_filepath);
}
else
{
TinyDIP::bmp_write(base_path.string().c_str(), std::forward<ImageType>(img));
}
}
else if constexpr (std::is_same_v<std::decay_t<ImageType>, TinyDIP::Image<TinyDIP::HSV>>)
{
TinyDIP::hsv_write(base_path.string().c_str(), std::forward<ImageType>(img));
}
else
{
throw std::invalid_argument("Direct file writing is not explicitly implemented for this abstract/complex data 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, Workspace&> &&
std::invocable<ProcessorFun, std::invoke_result_t<ImageLoaderFun, const std::string_view, Workspace&>>)
constexpr bool dispatch_data_operation(
const std::string_view input_arg,
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::string_view clean_arg = sanitize_string_view(input_arg);
const std::filesystem::path input_path = std::string(clean_arg);
std::string ext{};
if (input_path.has_extension())
{
ext = input_path.extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
}
if (ext == ".dbmp" || ext == ".csv")
{
processor(image_loader.template operator()<TinyDIP::Image<double>>(clean_arg, workspace));
}
else if (ext == ".hsv")
{
processor(image_loader.template operator()<TinyDIP::Image<TinyDIP::HSV>>(clean_arg, workspace));
}
else
{
processor(image_loader.template operator()<TinyDIP::Image<TinyDIP::RGB>>(clean_arg, workspace));
}
return true;
}
}
// CommandHandler type alias definition
// Modern C++ Standard Function signature for highly robust, state-injected execution
using CommandHandler = std::function<void(Workspace&, std::span<const std::string_view>, std::ostream&)>;
// 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 CombinerSchema = IOSchema{ 0, 2 };
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";
}
void execute(Workspace& workspace, const std::string& command_name, std::span<const std::string_view> args, std::ostream& os = std::cout) const
{
if (auto it = commands.find(command_name); it != std::ranges::end(commands))
{
try
{
it->second.handler(workspace, 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);
}
}
};
// ------------------------------------------------------------------------------------
// Peephole Optimization Engine (Lazy Evaluation AST)
// ------------------------------------------------------------------------------------
// QueuedCommand struct implementation
struct QueuedCommand
{
std::string name;
std::vector<std::string> args;
};
// match_any template function implementation
// Helper function to flawlessly check if a target string matches any element in an input container
template <std::ranges::input_range RangeT>
requires (std::same_as<std::remove_cvref_t<std::ranges::range_value_t<RangeT>>, std::string_view> or
std::same_as<std::remove_cvref_t<std::ranges::range_value_t<RangeT>>, std::string> or
std::convertible_to<std::ranges::range_value_t<RangeT>, std::string_view> or
std::convertible_to<std::ranges::range_value_t<RangeT>, std::string>)
constexpr bool match_any(const std::string_view target, const RangeT& container)
{
return std::ranges::find(std::ranges::begin(container), std::ranges::end(container), target) != std::ranges::end(container);
}
// PeepholeOptimizer template class implementation
template <std::ranges::input_range RangeT>
requires std::same_as<std::remove_cvref_t<std::ranges::range_value_t<RangeT>>, QueuedCommand>
class PeepholeOptimizer
{
public:
static void optimize(RangeT& pipeline, const CommandRegistry& registry, std::ostream& os)
{
if (std::ranges::empty(pipeline))
{
return;
}
bool changed = true;
while (changed)
{
changed = false;
RangeT optimized_pipeline;
if constexpr (std::ranges::sized_range<RangeT> && requires { optimized_pipeline.reserve(1); })
{
optimized_pipeline.reserve(std::ranges::size(pipeline));
}
auto it = std::ranges::begin(pipeline);
const auto end = std::ranges::end(pipeline);
std::optional<QueuedCommand> pending_cmd;
auto push_to_optimized = [&](QueuedCommand&& cmd)
{
if constexpr (requires { optimized_pipeline.emplace_back(std::move(cmd)); })
{
optimized_pipeline.emplace_back(std::move(cmd));
}
else
{
optimized_pipeline.push_back(std::move(cmd));
}
};
// Dynamically evaluate schemas at runtime to find inputs and outputs for ANY registered command
auto get_io = [&](const QueuedCommand& c) -> std::pair<std::string, std::string>
{
if (c.name == "copy" && std::ranges::size(c.args) >= 2)
{
return {c.args[0], c.args[1]};
}
auto schema_opt = registry.get_schema(c.name);
if (schema_opt && schema_opt->in_idx != -1 && schema_opt->out_idx != -1)
{
std::string in_val = "";
std::string out_val = "";
std::size_t non_policy_count = 0;
constexpr std::array<std::string_view, 4> policies = {"seq", "par", "par_unseq", "unseq"};
// Zero-allocation loop tracking non-policy arguments securely using match_any
for (const auto& arg : c.args)
{
if (!match_any(arg, policies))
{
if (non_policy_count == static_cast<std::size_t>(schema_opt->in_idx))
{
in_val = arg;
}
if (non_policy_count == static_cast<std::size_t>(schema_opt->out_idx))
{
out_val = arg;
}
++non_policy_count;
}
}
if (!in_val.empty() && !out_val.empty())
{
return {in_val, out_val};
}
}
return {"", ""};
};
auto update_arg_by_schema = [&](QueuedCommand& c, int logical_idx, const std::string& new_val) -> bool
{
std::size_t non_policy_count = 0;
constexpr std::array<std::string_view, 4> policies = {"seq", "par", "par_unseq", "unseq"};
for (std::size_t i = 0; i < std::ranges::size(c.args); ++i)
{
const auto& arg = c.args[i];
if (!match_any(arg, policies))
{
if (non_policy_count == static_cast<std::size_t>(logical_idx))
{
c.args[i] = new_val;
return true;
}
++non_policy_count;
}
}
return false;
};
auto update_in = [&](QueuedCommand& c, const std::string& new_in) -> bool
{
if (c.name == "copy" && std::ranges::size(c.args) >= 2)
{
c.args[0] = new_in;
return true;
}
auto schema_opt = registry.get_schema(c.name);
if (schema_opt && schema_opt->in_idx != -1)
{
return update_arg_by_schema(c, schema_opt->in_idx, new_in);
}
return false;
};
auto update_out = [&](QueuedCommand& c, const std::string& new_out) -> bool
{
if (c.name == "copy" && std::ranges::size(c.args) >= 2)
{
c.args[1] = new_out;
return true;
}
auto schema_opt = registry.get_schema(c.name);
if (schema_opt && schema_opt->out_idx != -1)
{
return update_arg_by_schema(c, schema_opt->out_idx, new_out);
}
return false;
};
while (it != end || pending_cmd.has_value())
{
QueuedCommand cmd1;
if (pending_cmd.has_value())
{
cmd1 = std::move(pending_cmd.value());
pending_cmd.reset();
}
else
{
cmd1 = std::move(*it);
++it;
}
// 1. Identify Redundant Scalar Math (Multiply by 1.0)
if (cmd1.name == "multiply" && std::ranges::size(cmd1.args) >= 3)
{
const std::string_view factor = cmd1.args.back();
const std::string_view clean_factor = sanitize_string_view(factor);
double factor_val = 0.0;
auto [ptr, ec] = std::from_chars(clean_factor.data(), clean_factor.data() + std::ranges::size(clean_factor), factor_val);
if (ec == std::errc() && factor_val == 1.0)
{
auto [cmd1_in, cmd1_out] = get_io(cmd1);
os << " [Peephole Optimizer] Detected Identity operation: 'multiply' by 1.0.\n";
os << " [Peephole Optimizer] Downgrading to zero-overhead 'copy'.\n";
QueuedCommand copy_cmd;
copy_cmd.name = "copy";
copy_cmd.args = {cmd1_in, cmd1_out};
cmd1 = std::move(copy_cmd);
changed = true;
}
}