Sygaldry
Loading...
Searching...
No Matches
sygup-basic_logger.hpp
1#pragma once
2/*
3Copyright 2023 Travis J. West, https://traviswest.ca, Input Devices and Music
4Interaction Laboratory (IDMIL), Centre for Interdisciplinary Research in Music
5Media and Technology (CIRMMT), McGill University, Montréal, Canada, and Univ.
6Lille, Inria, CNRS, Centrale Lille, UMR 9189 CRIStAL, F-59000 Lille, France
7
8SPDX-License-Identifier: MIT
9*/
10
11#include <type_traits>
12#include <string_view>
13#include <string>
14#include <limits>
15#include <charconv>
16
17namespace sygaldry { namespace sygup {
23
24template<typename putter>
26{
27 [[no_unique_address]] putter put;
28
29 template<typename cvrT> void print_(cvrT& x)
30 {
31 using T = std::remove_cvref_t<cvrT>;
32
33 constexpr int max_num_digits =
34 (
35 // floats: mantissa digits + exponent digits + sign + e + exponent sign
36 std::is_floating_point_v<T> ? std::numeric_limits<T>::max_digits10
37 + std::numeric_limits<T>::max_exponent10 + 3
38
39 // ints: digits + sign
40 : (std::numeric_limits<T>::digits10 + std::is_signed_v<T>) ? 1 : 0
41 );
42
43 constexpr int buffer_size = max_num_digits + 16; // Extra padding for safety
44
45 char buffer[buffer_size];
46
47 std::string_view string_message;
48 if constexpr (std::is_same_v<T, bool>)
49 {
50 string_message = x ? "true" : "false";
51 }
52 else if constexpr (std::is_arithmetic_v<T>)
53 {
54 auto [ptr, ec] = std::to_chars(buffer, buffer + buffer_size, x);
55
56 if (ec == std::errc()) {
57 string_message = std::string_view(buffer, ptr - buffer);
58 } else {
59 string_message = "error:\n\
60 bindings/basic_logger/basic_logger.lili:'convert a number'\n\
61 std::to_chars scratch buffer unexpectedly too small!";
62 }
63 }
64 else if constexpr (requires {string_message = x;})
65 string_message = x;
66 else if constexpr (requires {x[0]; x.size();})
67 {
68 print("[", x[0]);
69 for (std::size_t i = 1; i < x.size(); ++i) print(" ", x[i]);
70 print("]");
71 return;
72 }
73 else string_message = "unknown type for basic logger";
74
75 for (char c : string_message)
76 put(c);
77 };
78
79 template<typename ... Ts> void print(Ts... x)
80 {
81 (print_(x), ...);
82 }
83
84 template<typename ... Ts> void println(Ts... x)
85 {
86 print(x...);
87 print("\n");
88 }
89};
90
93} }
Definition sygup-basic_logger.hpp:26