text
stringlengths
1
2.12k
source
dict
c++, recursion, template, c++20, constrained-templates template<std::ranges::input_range T> constexpr auto recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&& x) { std::cout << std::string(level, ' ') << x << std::endl; return x; } ); return output; } template<std::ranges::input_range T> requires (std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr T recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&& element) { return recursive_print(element, level + 1); } ); return output; } void recursive_all_of_tests() { auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3); test_vectors_1[0][0][0][0] = 2; std::cout << "Play with test_vectors_1:\n"; if (recursive_all_of(test_vectors_1, [](int i) { return i % 2 == 0; })) std::cout << "All numbers are even\n"; auto test_vectors_2 = n_dim_container_generator<std::vector, 4, int>(2, 3); test_vectors_2[0][0][0][0] = 4; std::cout << "Play with test_vectors_2:\n"; if (recursive_all_of(test_vectors_2, [](int i) { return i % 2 == 0; })) std::cout << "All numbers are even\n"; return; }
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates int main() { auto start = std::chrono::system_clock::now(); recursive_all_of_tests(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the test code above: Play with test_vectors_1: Play with test_vectors_2: All numbers are even Computation finished at Fri Jan 19 12:05:11 2024 elapsed time: 4.4001e-05 Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_foreach_all Template Function Implementation in C++ What changes has been made in the code since last question? I am trying to implement recursive_all_of template function in this post. Why a new review is being asked for? Please review the recursive_all_of template function and all suggestions are welcome.
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates Answer: Match the interface of std::ranges::all_of() When you implement a recursive version of a STL algorithm, make sure you match the interface of the STL algorithm as best as possible. Note how std::ranges::all_of() takes the input by forwarding reference. This is important since it will be able to take anything as a parameter, including r-value references, which your code does not. Another difference is that std::ranges::all_of() allows you to specify a projection. The STL also puts constraints on the type of the unary predicate. This helps produce somewhat better error messages in case an incompatible predicate is passed. Make more use of std::ranges::all_of() The recursing case can be implemented using std::ranges::all_of() instead of using a for-loop: template<std::ranges::input_range T, class UnaryPredicate> requires(std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr auto recursive_all_of(T&& inputRange, UnaryPredicate p) { return std::ranges::all_of(inputRange, [&](auto&& range) { return impl::recursive_all_of(range, p); }); } Simplify the base case The code is a little bit more complex than necessary because you made the innermost range the base case. But if you instead use the values of the innermost range the base case your code can look like: template<class T, class UnaryPredicate> constexpr auto recursive_all_of(T&& value, UnaryPredicate p) { return std::invoke(p, value); } template<std::ranges::input_range T, class UnaryPredicate> constexpr auto recursive_all_of(T& inputRange, UnaryPredicate p) { return std::ranges::all_of(inputRange, [&](auto&& range) { return impl::recursive_all_of(range, p); }); }
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates There should be no impact on performance. Also, the declaration of recursive_all_of() outside namespace impl can stay the same, so it will still be an error to try to call it on something that isn't a range to begin with. Consider passing the predicate by reference to the implementation Predicates can be function objects or lambdas that contain state. By passing it by value to recursive calls, copies of the state are made, but that might be unexpected for the caller. I mentioned the same issue in the review of your recursive_foreach_all(). I think a simple fix is to have the predicate passed by reference to impl::recursive_all_of().
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, beginner, rock-paper-scissors Title: Rock Paper Scissors. My first C++ program. Please judge harshly Question: I am new and only know the basics of C++. Any help will be appreciated. I want to know how to make my code less lines, more efficient, proper practice and play better. #include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <cstdio> using std::cout; using std::cin; using std::string; using std::endl; using std::getchar; short CPUplay(int num) { srand(time(nullptr) + num); short CPUchoice = (rand() % 3) + 1; return CPUchoice; } int playerPlay() { string playerPlay; int playValue = 1; while (1 == 1) { cout << "rock, paper or scissors: "; cin >> playerPlay; if (playerPlay == "rock") { playValue = 1; break; } else if (playerPlay == "paper") { playValue = 2; break; } else if (playerPlay == "scissors") { playValue = 3; break; } else { cout << "Not a valid input." << endl; } } return playValue; }
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors int main() { int numRounds; int CPUscore = 0; int playerScore = 0; cout << "Welcome to Rock, Paper, Scissors!" << endl; cout << "How many games would you like to play? "; cin >> numRounds; while (!cin) { cin.clear(); cin.ignore(1000, '\n'); cout << "Invalid input."; cout << "How many rounds would you like to play? "; cin >> numRounds; } for (int i = 0; i < numRounds; i++) { cout << "\033[2J\033[1;1H"; int playerTurn = playerPlay(); int CPUturn = CPUplay(i); switch (playerTurn) { case 1: // When player chose rock if (CPUturn == 1) { //When CPU chose rock cout << "The computer chose rock. Draw." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 2) { //When CPU chose paper CPUscore++; cout << "The computer chose paper. You lose this round :(." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 3) { // When CPU chose scissors playerScore++; cout << "The computer chose scissors. You win this round!!" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } break; case 2: // When player chose paper if (CPUturn == 1) { //When CPU chose rock playerScore++; cout << "The computer chose rock. You win this round!!." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl;
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 2) { //When CPU chose paper
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors cout << "The computer chose paper. Draw." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 3) { // When CPU chose scissors CPUscore++; cout << "The computer chose scissors. You lose this round!!" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } break; case 3: // When player chose scissors if (CPUturn == 1) { //When CPU chose rock CPUscore++; cout << "The computer chose rock. You lose this round :(" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 2) { //When CPU chose paper playerScore++; cout << "The computer chose paper. You win this round!" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUturn == 3) { // When CPU chose scissors cout << "The computer chose scissors. You draw." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } break; } cout << "Press enter to continue... "; cin.ignore(); cin.get(); } cout << "\033[2J\033[1;1H"; if (CPUscore > playerScore) { cout << "You lose the match :(" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl;
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (playerScore > CPUscore) { cout << "You win the match!!" << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } else if (CPUscore == playerScore) { cout << "Match drawn. " << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; } return 0; }
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors Answer: It's not too terrible, especially for a first program, but there are a number of things that you might improve. Decompose your program into functions Almost all of the logic here is in main in one rather long and repetitive chunk of code in main. It would be better to decompose this into separate functions. Use only necessary #includes Restricting #includes to those that are really needed is good practice. In particular there is nothing used from <cstdio> and the using std::getchar is not necessary either. Be careful with using Although you have avoided the bad habit of putting using namespace std at the top of your program, one could simply omit those entirely and use the explicit std:: prefix everywhere. It makes it clear to readers of the code that you're using the std version and doesn't really clutter up the code very much. Don't use std::endl if you don't really need it The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized. Use string concatenation and operator chaining The code includes these lines: cout << "The computer chose rock. Draw." << endl; cout << "Score: " << endl; cout << "You: " << playerScore << endl; cout << "Computer: " << CPUscore << endl; Each of those is a separate call to operator<< but they don't need to be. Another way to write that would be like this: std::cout << "The computer chose rock. Draw.\n" "Score: \n" "You: " << playerScore << "\n" "Computer: " << CPUscore << "\n";
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors Consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler and the return type for the stream operator<< is std::ostream& so you can chain them together like this to make the code a bit easier to read. Consider using a better random number generator You are currently using short CPUchoice = (rand() % 3) + 1; There are two problems with this approach. One is that the low order bits of the random number generator are not particularly random, so neither is CPUchoice. On my machine, there's a slight but measurable bias toward 1 with that. The second problem is that it's not thread safe because rand stores hidden state. A better solution, if your compiler and library supports it, would be to use the C++11 std::uniform_int_distribution. It looks complex, but it's actually pretty easy to use. Avoid "magic numbers" The code includes this line in two places: std::cout << "\033[2J\033[1;1H"; Better would be to give this constant a name to suggest what it means or to factor it out into a function such as clear() to make it a lot more obvious what is happening. Don't Repeat Yourself (DRY) The code includes this: if (CPUscore > playerScore) { std::cout << "You lose the match :(\n"; std::cout << "Score: \n"; std::cout << "You: " << playerScore << endl; std::cout << "Computer: " << CPUscore << endl; } else if (playerScore > CPUscore) { std::cout << "You win the match!!\n"; std::cout << "Score: \n"; std::cout << "You: " << playerScore << endl; std::cout << "Computer: " << CPUscore << endl; } else if (CPUscore == playerScore) { std::cout << "Match drawn. \n"; std::cout << "Score: \n"; std::cout << "You: " << playerScore << endl; std::cout << "Computer: " << CPUscore << endl; }
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors Instead of repeating code, it's generally better to make common code into a function or separate things out. This, for example, could be written like this: if (CPUscore > playerScore) { std::cout << "You lose the match :(\n"; } else if (playerScore > CPUscore) { std::cout << "You win the match!!\n"; } else if (CPUscore == playerScore) { std::cout << "Match drawn. \n"; } std::cout << "Score: \n"; std::cout << "You: " << playerScore << endl; std::cout << "Computer: " << CPUscore << endl; Use a function to evaluate win/loss/draw Both the computer and the human choose either "rock", "paper" or "scissors" and the rules for which combination wins, loses or draws are clear. One could separate that out into a function like this: enum class Result { win, lose, draw}; Result evaluateRound(int computer, int human) { if (computer == human) { return Result::draw; } else if (human == computer + 1 || human == 1 && computer == 3) { return Result::win; } return Result::lose; } Now we can use this like this: int playerTurn{playerPlay()}; int CPUturn{CPUplay()}; auto result{evaluateRound(CPUturn, playerTurn)}; std::cout << "The computer chose " << text(CPUturn); if (result == Result::win) { std::cout << " You win this round!\n"; ++playerScore; } else if (result == Result::draw) { std::cout << " Draw.\n"; } else { std::cout << " You lose this round :(.\n"; ++CPUscore; } std::cout << "Score: \n" "You: " << playerScore << "\n" "Computer: " << CPUscore << "\n" "Press enter to continue... "; std::cin.ignore(); std::cin.get(); }
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++, beginner, rock-paper-scissors I imagine that you can figure out what the text() function does and how to write it. A further enhancement would be to use an enum class for the guesses, too. Use consistent capitalization We have both CPUscore and playerScore in the program. In one case Score is capitalized and the other place not. In one case, the name begins with a capital letter and the other place not. Consistency can aid readability, and so one possibility would be to use CpuScore and PlayerScore even though "CPU" in English is properly all capitalized.
{ "domain": "codereview.stackexchange", "id": 45439, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, rock-paper-scissors", "url": null }
c++ Title: Fast tolower function Question: C++ Standard Library functions like std::tolower, std::isalpha, etc. could be quite slow when it comes to large texts and handling locales. So, I decided to have fast tolower function, caching the values. They are blazingly fast. Assumption: nobody will intentionally try to hack the code, trying all possible and impossible ways to call tolower_fast before cache is filled. I assume that tolower_fast will be called much later in common program flow from function main. Performace measurement On godbolt.org test it gives: Duration of std::tolower = 0.17513s Duration of tolower_fast = 0.000366216s Duration of tolower_fast2 = 1.38e-06s On my PC with VS 2022 release: Duration std::tolower = 1.46942s Duration tolower_fast = 0.0001968s Duration tolower_fast2 = 5.35e-05s (Actually, tolower_fast and tolower_fast2 don't differ so much between each other, this is measurement error). So, real performance difference is about 1000 times in Release on local PC. Real large texts processing improved from minutes to seconds. The code I see many ways to implement caching, for example the following two (demo): #include <locale> const std::locale locale(""); // Any reasonable locale static struct tolower_cache_t { char cache[UCHAR_MAX + 1]; tolower_cache_t() { for (size_t c = 0; c <= UCHAR_MAX; ++c) cache[c] = std::tolower((char)c, locale); } } tolower_cache; inline char tolower_fast(char ch) { return tolower_cache.cache[ch]; } class ToLower { public: ToLower() { for (size_t c = 0; c <= UCHAR_MAX; ++c) cache[c] = std::tolower((char)c, locale); } bool operator()(char c) const { return cache[c]; } private: bool cache[UCHAR_MAX + 1]; }; static ToLower tolower_fast2; int main() { char c = 'A'; char lc1 = tolower_fast(c); char lc2 = tolower_fast2(c); }
{ "domain": "codereview.stackexchange", "id": 45440, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ int main() { char c = 'A'; char lc1 = tolower_fast(c); char lc2 = tolower_fast2(c); } The first one uses object and a function, the second one uses functional object. I guess that from compilation perspective (when it comes to call tolower itself) they should give the similar code. The questions are: Which of two implementations is better? I mean here potential problems and maintainability. Are there any issues with the approach and code? Is there a better way to do this which will still guarantee cache filling before tolower_fast? Answer: Which of two implementations is better? I mean here potential problems and maintainability. There is a third way. You don't need structs to build the cache, instead you can just use free functions: static auto make_tolower_cache() { std::array<char, UCHAR_MAX + 1> cache; for (std::size_t c = 0; c < cache.size(); ++c) cache[c] = std::tolower(static_cast<char>(c), locale); return cache; } static auto tolower_cache = make_tolower_cache(); inline char tolower_fast(char ch) { return tolower_cache[ch]; } Are there any issues with the approach and code? It only works for simple 8-bit locales. For Unicode, especially if it is encoded using UTF-8, you will need a different approach. Is there a better way to do this which will still guarantee cache filling before tolower_fast? You can declare a static array inside a function. When that function is then called for the first time, it will be initialized. Subsequent times it doesn't have to do the full initialization anymore, but there is some overhead because it still needs to check somehow whether it is the first time the function is called: inline char tolower_fast(char ch) { static auto tolower_cache = make_tolower_cache(); return tolower_cache[ch]; }
{ "domain": "codereview.stackexchange", "id": 45440, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ So if performance is the most important thing, then that is not the way to go. There are various other ways to address this: call a function early in main() to initialize the cache, never call tolower_fast() before main() starts, ensure the link order is such that a global static cache is initialized early enough, and so on. Note that if you need even more perfomance, then search for or create a function that lowers multiple characters at a time using SIMD instructions.
{ "domain": "codereview.stackexchange", "id": 45440, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++, c++20 Title: Generic feedback on a replacement of `` Question: I use a lot <cctype> functions, but they're not very type safe and and calling them with a negative char is (theoretically) undefined behavior, so my code is cluttered with static_casts like: [](const char ch){ return static_cast<char>(std::tolower(static_cast<unsigned char>(ch))); }); So I started to write a simple wrapper, then I wanted to have a little more control and one thing led to another I finished to replace the thing entirely. I know it's not good, but the damage is already done and I'm actually quite happy using it. I'm posting here the code to get some feedback and advices from more experience developers in order to improve and consolidate a little bit. godbolt github #pragma once // --------------------------------------------- // ASCII encoding predicates and facilities // --------------------------------------------- // #include "ascii_predicates.hpp" // ascii::is_* // --------------------------------------------- #include <concepts> // std::same_as<> #include <cstdint> // std::uint16_t //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: namespace ascii //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: {
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 namespace details { // The standard <cctype> behaviour: // | | |is |is |is |is |is |is |is |is |is |is |is |is | // | ASCII | characters |cntrl|print|graph|space|blank|punct|alnum|alpha|upper|lower|digit|xdigit| // |---------|---------------------------|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------| // | 0–8 | control codes (NUL, etc.) | X | | | | | | | | | | | | // | 9 | tab (\t) | X | | | X | X | | | | | | | | // | 10–13 | whitespaces (\n,\v,\f,\r) | X | | | X | | | | | | | | | // | 14–31 | control codes | X | | | | | | | | | | | | // | 32 | space | | X | | X | X | | | | | | | | // | 33–47 | !"#$%&amp;'()*+,-./ | | X | X | | | X | | | | | | | // | 48–57 | 0123456789 | | X | X | | | | X | | | | X | X | // | 58–64 | :;&lt;=&gt;?@ | | X | X | | | X | | | | | | | // | 65–70 | ABCDEF | | X | X | | | | X | X | X | | | X | // | 71–90 | GHIJKLMNOPQRSTUVWXYZ | | X | X | | | | X | X | X | | | | // | 91–96 | [\]^_` | | X | X | | | X | | | | | | | // | 97–102 | abcdef | | X | X | | | | X | X | | X | | X | // | 103–122 | ghijklmnopqrstuvwxyz | | X | X | | | | X | X | | X | | |
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 // | 123–126 | {|}~ | | X | X | | | X | | | | | | | // | 127 | backspace character (DEL) | X | | | | | | | | | | | |
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 using table_entry_t = std::uint16_t; enum mask_t : table_entry_t { ISLOWER = 0x0001u, // std::islower ISUPPER = 0x0002u, // std::isupper ISSPACE = 0x0004u, // std::isspace ISBLANK = 0x0008u, // std::isspace except '\n' (not equiv to std::isblank) ISALPHA = 0x0010u, // std::isalpha ISALNUM = 0x0020u, // std::isalnum ISDIGIT = 0x0040u, // std::isdigit ISXDIGI = 0x0080u, // std::isxdigit ISPUNCT = 0x0100u, // std::ispunct ISIDENT = 0x0200u, // std::isalnum plus '_' ISCNTRL = 0x1000u, // std::iscntrl ISGRAPH = 0x2000u, // std::isgraph ISPRINT = 0x4000u // std::isprint };
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 static_assert( sizeof(unsigned char)==1 ); // Should I check CHAR_BIT? static constexpr table_entry_t ascii_lookup_table[256] = // Lookup table generation: https://gcc.godbolt.org/z/4G6nxh8vh { 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x100C, 0x1004, 0x100C, 0x100C, 0x100C, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x400C, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x62E0, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x6100, 0x62B2, 0x62B2, 0x62B2, 0x62B2, 0x62B2, 0x62B2, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6232, 0x6100, 0x6100, 0x6100, 0x6100, 0x6300, 0x6100, 0x62B1, 0x62B1, 0x62B1, 0x62B1, 0x62B1, 0x62B1, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6231, 0x6100, 0x6100, 0x6100, 0x6100, 0x1000, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0,
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0, 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 , 0x0 };
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 [[nodiscard]] inline constexpr bool check(const unsigned char ch, const mask_t mask){ return ascii_lookup_table[ch] & mask; } [[nodiscard]] inline constexpr bool check(const char ch, const mask_t mask){ return check(static_cast<unsigned char>(ch), mask); } [[nodiscard]] inline constexpr bool check(const char32_t cp, const mask_t mask) { // Good enough for parsing code where non ASCII codepoints are just in strings or comments if( cp<U'\x80' ) [[likely]] { return check(static_cast<unsigned char>(cp), mask); } return false; } // Facility for case conversion template<bool SET> [[nodiscard]] inline constexpr char set_case_bit(char c) noexcept { static constexpr char case_bit = '\x20'; if constexpr (SET) c |= case_bit; else c &= ~case_bit; return c; } } // Supporting the following character types: template<typename T> concept CharLike = std::same_as<T, char> or std::same_as<T, unsigned char> or std::same_as<T, char32_t>;
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 // Basic predicates template<CharLike Chr> [[nodiscard]] constexpr bool is_lower(const Chr c) noexcept { return details::check(c, details::ISLOWER); } template<CharLike Chr> [[nodiscard]] constexpr bool is_upper(const Chr c) noexcept { return details::check(c, details::ISUPPER); } template<CharLike Chr> [[nodiscard]] constexpr bool is_space(const Chr c) noexcept { return details::check(c, details::ISSPACE); } template<CharLike Chr> [[nodiscard]] constexpr bool is_blank(const Chr c) noexcept { return details::check(c, details::ISBLANK); } // not equiv to std::isblank template<CharLike Chr> [[nodiscard]] constexpr bool is_alpha(const Chr c) noexcept { return details::check(c, details::ISALPHA); } template<CharLike Chr> [[nodiscard]] constexpr bool is_alnum(const Chr c) noexcept { return details::check(c, details::ISALNUM); } template<CharLike Chr> [[nodiscard]] constexpr bool is_digit(const Chr c) noexcept { return details::check(c, details::ISDIGIT); } template<CharLike Chr> [[nodiscard]] constexpr bool is_xdigi(const Chr c) noexcept { return details::check(c, details::ISXDIGI); } template<CharLike Chr> [[nodiscard]] constexpr bool is_punct(const Chr c) noexcept { return details::check(c, details::ISPUNCT); } template<CharLike Chr> [[nodiscard]] constexpr bool is_ident(const Chr c) noexcept { return details::check(c, details::ISIDENT); } // std::isalnum or '_' template<CharLike Chr> [[nodiscard]] constexpr bool is_cntrl(const Chr c) noexcept { return details::check(c, details::ISCNTRL); } template<CharLike Chr> [[nodiscard]] constexpr bool is_graph(const Chr c) noexcept { return details::check(c, details::ISGRAPH); } template<CharLike Chr> [[nodiscard]] constexpr bool is_print(const Chr c) noexcept { return details::check(c, details::ISPRINT); } // Other predicates template<CharLike Chr> [[nodiscard]] constexpr bool is_endline(const Chr c) noexcept { return c==static_cast<Chr>('\n'); }
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 template<CharLike Chr> [[nodiscard]] constexpr bool is_always_false(const Chr) noexcept { return false; } // Composite predicates template<CharLike Chr> [[nodiscard]] constexpr bool is_space_or_punct(const Chr c) noexcept { return details::check(c, details::ISSPACE | details::ISPUNCT); }
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 //--------------------------------------------------------------------------- // Non-type parameterized template predicates template<CharLike auto CH> [[nodiscard]] constexpr bool is(const decltype(CH) ch) noexcept { return ch==CH; } template<CharLike auto CH1, decltype(CH1)... CHS> [[nodiscard]] constexpr bool is_any_of(const decltype(CH1) ch) { return ch==CH1 or ((ch==CHS) or ...); } template<CharLike auto CH1, decltype(CH1)... CHS> [[nodiscard]] constexpr bool is_none_of(const decltype(CH1) ch) { return ch!=CH1 and ((ch!=CHS) and ...); } // Some examples of composite predicates template<CharLike auto CH1, decltype(CH1)... CHS> [[nodiscard]] constexpr bool is_space_or_any_of(const decltype(CH1) ch) { return is_space(ch) or is_any_of<CH1, CHS ...>(ch); } template<CharLike auto CH1, decltype(CH1)... CHS> [[nodiscard]] constexpr bool is_alnum_or_any_of(const decltype(CH1) ch) { return is_alnum(ch) or is_any_of<CH1, CHS ...>(ch); } template<CharLike auto CH1, decltype(CH1)... CHS> [[nodiscard]] constexpr bool is_punct_and_none_of(const decltype(CH1) ch) { return is_punct(ch) and is_none_of<CH1, CHS ...>(ch); } //--------------------------------------------------------------------------- // Case conversion [[nodiscard]] constexpr char to_lower(char c) noexcept { if(is_upper(c)) c = details::set_case_bit<true>(c); return c; } [[nodiscard]] constexpr char to_upper(char c) noexcept { if(is_lower(c)) c = details::set_case_bit<false>(c); return c; } }//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 }//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Answer: Consider using the versions from <locale> As Toby Speight already mentioned, all these C functions have a much nicer C++ counterpart in the <locale> header. These are templated on a character type, just like your code. A drawback of these functions is that you always need to provide a locale to every call, and that this locale has to be checked every call, which means performance is going to be much worse, which might be a problem if you are calling them a lot. What is the point of CharLike if you are only handling US-ASCII? Your code only handles US-ASCII characters. It doesn't make sense to handle other types than char then; if you feed it wide character strings or Unicode, it's just going to return unexpected results. I think it would be better to get a compile error in that case. You are also inconsistent; why are the is_something() functions templated on CharLike, but your to_upper() and to_lower() are not? Why doesn't CharLike accept wchar_t and other standard character types? You limit CharLike to char, unsigned char and char32_t, but there is also wchar_t, char8_t and char16_t. About your parameter packs I see why you made your "non-type parameterized template predicates" take a CH1 and CHS; you want to ensure all the parameters have the same type. However, some conversions are still allowed. For example, the following will compile just fine without any warning: auto result = is_any_of<U'a', L'b', u8'c', 'd'>(42); To fix this, don't restrict any of the (template) parameter types where they are declared, and instead use a requires clause to ensure all types are the same, like so: template<CharLike auto... CHS, typename CH> requires (std::same_as<CH, decltype(CHS)> and ...) [[nodiscard]] constexpr bool is_any_of(const CH ch) { return ((ch == CHS) or ...); }
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 Unnecessary use of non-type template parameters There is no reason to pass SET as a template parameter. You can just pass it as a regular parameter. The same goes for your other predicates. All these functions are constexpr, so everything can be evaluated at compile time anyway.
{ "domain": "codereview.stackexchange", "id": 45441, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_all_of Template Function with Unwrap Level Implementation in C++ Question: This is a follow-up question for A recursive_find_if_all Template Function Implementation in C++ and A recursive_all_of Template Function Implementation in C++. To support std::string, std::wstring, std::u8string and std::pmr::string (making recursive_all_of template function more generic), I am trying to implement recursive_all_of template function with unwrap level in this post. The experimental implementation recursive_all_of Template Function /* recursive_all_of template function implementation with unwrap level */ template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate> requires(unwrap_level <= recursive_depth<T>()) constexpr auto recursive_all_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { if constexpr (unwrap_level > 0) { return std::ranges::all_of(value, [&](auto&& element) { return recursive_all_of<unwrap_level - 1>(element, p, proj); }); } else { return std::invoke(p, std::invoke(proj, value)); } } Full Testing Code The full testing code: // A recursive_all_of template function implementation with unwrap level #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <concepts> #include <deque> #include <execution> #include <exception> //#include <experimental/ranges/algorithm> #include <experimental/array> #include <functional> #include <iostream> #include <ranges> #include <string> #include <utility> #include <vector> // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; template<typename T> concept is_summable = requires(T x) { x + x; };
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_unwrap_type_t struct implementation template<std::size_t, typename, typename...> struct recursive_unwrap_type { }; template<class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...> { using type = std::ranges::range_value_t<Container1<Ts1...>>; }; template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...> { using type = typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>> >::type; }; template<std::size_t unwrap_level, typename T1, typename... Ts> using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type; // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; // recursive_array_invoke_result implementation template<std::size_t, typename, typename, typename...> struct recursive_array_invoke_result { }; template< typename F, template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_invoke_result<1, F, Container<T, N>> { using type = Container< std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>, N>; };
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>> { using type = Container< typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>> >::type, N>; }; template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type; // recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035 template<std::size_t, typename> struct recursive_array_unwrap_type { }; template<template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_unwrap_type<1, Container<T, N>> { using type = std::ranges::range_value_t<Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_unwrap_type<unwrap_level, Container<T, N>> { using type = typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>> >::type; }; template<std::size_t unwrap_level, class Container> using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type; // https://codereview.stackexchange.com/a/253039/231235 template<std::size_t dim, class T, template<class...> class Container = std::vector> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<dim - 1, T, Container>(input, times)); } } template<std::size_t dim, std::size_t times, class T> constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output; for (size_t i = 0; i < times; i++) { output[i] = n_dim_array_generator<dim - 1, times>(input); } return output; } } // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1}; }
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_depth function implementation with target type template<typename T_Base, typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<typename T_Base, std::ranges::input_range Range> requires (!std::same_as<Range, T_Base>) constexpr std::size_t recursive_depth() { return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1}; } /* recursive_foreach_all template function performs specific function on input container exhaustively https://codereview.stackexchange.com/a/286525/231235 */ namespace impl { template<class F, class Proj = std::identity> struct recursive_for_each_state { F f; Proj proj; }; // recursive_foreach_all template function implementation template<class T, class State> requires (recursive_depth<T>() == 0) constexpr void recursive_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<class T, class State> requires (recursive_depth<T>() != 0) constexpr void recursive_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange) impl::recursive_foreach_all(item, state); } // recursive_reverse_foreach_all template function implementation template<class T, class State> requires (recursive_depth<T>() == 0) constexpr void recursive_reverse_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<class T, class State> requires (recursive_depth<T>() != 0) constexpr void recursive_reverse_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange | std::views::reverse) impl::recursive_reverse_foreach_all(item, state); } }
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class T, class Proj = std::identity, class F> constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class Proj = std::identity, class F> constexpr auto recursive_reverse_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_reverse_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class I, class F> constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f) { recursive_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, init, value); }); return init; } template<class T, class I, class F> constexpr auto recursive_fold_right_all(const T& inputRange, I init, F f) { recursive_reverse_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, value, init); }); return init; } // recursive_count_if template function implementation template<class T, std::invocable<T> Pred> requires (recursive_depth<T>() == 0) constexpr std::size_t recursive_count_if_all(const T& input, const Pred& predicate) { return predicate(input) ? std::size_t{1} : std::size_t{0}; } template<std::ranges::input_range Range, class Pred> requires (recursive_depth<Range>() != 0) constexpr auto recursive_count_if_all(const Range& input, const Pred& predicate) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) { return recursive_count_if_all(element, predicate); }); }
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, class T, class Pred> requires(unwrap_level <= recursive_depth<T>()) constexpr auto recursive_count_if(const T& input, const Pred& predicate) { if constexpr (unwrap_level > 0) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) { return recursive_count_if<unwrap_level - 1>(element, predicate); }); } else { return predicate(input) ? 1 : 0; } } /* recursive_all_of template function implementation with unwrap level */ template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate> requires(unwrap_level <= recursive_depth<T>()) constexpr auto recursive_all_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { if constexpr (unwrap_level > 0) { return std::ranges::all_of(value, [&](auto&& element) { return recursive_all_of<unwrap_level - 1>(element, p, proj); }); } else { return std::invoke(p, std::invoke(proj, value)); } } template<std::ranges::input_range T> constexpr auto recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&& x) { std::cout << std::string(level, ' ') << x << std::endl; return x; } ); return output; }
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::ranges::input_range T> requires (std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr T recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&& element) { return recursive_print(element, level + 1); } ); return output; } void recursive_all_of_tests() { auto test_vectors_1 = n_dim_container_generator<4, int, std::vector>(1, 3); test_vectors_1[0][0][0][0] = 2; assert(recursive_all_of<4>(test_vectors_1, [](auto&& i) { return i % 2 == 0; }) == false); auto test_vectors_2 = n_dim_container_generator<4, int, std::vector>(2, 3); test_vectors_2[0][0][0][0] = 4; assert(recursive_all_of<4>(test_vectors_2, [](auto&& i) { return i % 2 == 0; })); // Tests with std::string auto test_vector_string = n_dim_container_generator<4, std::string, std::vector>("1", 3); assert(recursive_all_of<4>(test_vector_string, [](auto&& i) { return i == "1"; })); assert(recursive_all_of<4>(test_vector_string, [](auto&& i) { return i == "2"; }) == false); // Tests with std::string, projection assert(recursive_all_of<4>( test_vector_string, [](auto&& i) { return i == "1"; }, [](auto&& element) {return std::to_string(stoi(element) + 1); }) == false); assert(recursive_all_of<4>( test_vector_string, [](auto&& i) { return i == "2"; }, [](auto&& element) {return std::to_string(stoi(element) + 1); })); // Tests with std::array of std::string std::array<std::string, 3> word_array1 = {"foo", "foo", "foo"}; assert(recursive_all_of<1>(word_array1, [](auto&& i) { return i == "foo"; })); assert(recursive_all_of<1>(word_array1, [](auto&& i) { return i == "bar"; }) == false);
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // Tests with std::deque of std::string std::deque<std::string> word_deque1 = {"foo", "foo", "foo", "foo"}; assert(recursive_all_of<1>(word_deque1, [](auto&& i) { return i == "foo"; })); assert(recursive_all_of<1>(word_deque1, [](auto&& i) { return i == "bar"; }) == false); std::vector<std::wstring> wstring_vector1{}; for(int i = 0; i < 4; ++i) { wstring_vector1.push_back(std::to_wstring(1)); } assert(recursive_all_of<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(1); })); assert(recursive_all_of<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(2); }) == false); std::vector<std::u8string> u8string_vector1{}; for(int i = 0; i < 4; ++i) { u8string_vector1.push_back(u8"\u20AC2.00"); } assert(recursive_all_of<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC2.00"; })); assert(recursive_all_of<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC1.00"; }) == false); std::pmr::string pmr_string1 = "123"; std::vector<std::pmr::string> pmr_string_vector1 = {pmr_string1, pmr_string1, pmr_string1}; assert(recursive_all_of<1>(pmr_string_vector1, [](auto&& i) { return i == "123"; })); assert(recursive_all_of<1>(pmr_string_vector1, [](auto&& i) { return i == "456"; }) == false); std::cout << "All tests passed!\n"; return; } int main() { auto start = std::chrono::system_clock::now(); recursive_all_of_tests(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the test code above: All tests passed! Computation finished at Mon Jan 29 13:52:59 2024 elapsed time: 4.7914e-05
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_find_if_all Template Function Implementation in C++ and A recursive_all_of Template Function Implementation in C++ What changes has been made in the code since last question? I am trying to implement recursive_all_of template function with unwrap level in this post. Why a new review is being asked for? Please review the revised recursive_all_of template function and its tests. All suggestions are welcome. Answer: This looks very good. The only issue I can see is that you did not constrain the types Proj and UnaryPredicate. That means that if you provide an incorrect projection and/or predicate, you will get an error message at the deepest level of recursion, which will likely result in a hard to read error message. It would be great if you could constrain the allowed types of these template parameters somehow.
{ "domain": "codereview.stackexchange", "id": 45442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, performance, concurrency Title: Multi Threaded File Processing C++ Question: Background: The program reads 1000000 lines in the file. Every four line will be parsed into an object in a vector. If it has 2 objects with the same name, it will drop 1 object and increment one of the field in another object. After that, the vector is required to sort out. Finally, it writes to output file. The main code #include <cmath> #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <mutex> #include <queue> #include <thread> #include <vector> std::queue<FASTQentry> shared_queue; bool queue_closed = false; std::mutex shared_queue_mutex; int main(int argc, char* argv[]) { std::ifstream input_file; std::ofstream output_file; std::size_t total_reads = 0; std::vector<FASTQentry> fqs; // parse input fastq file // fqs = parse_fastq_file(input_file, total_reads); std::thread readerThread(parse_fastq_file_mutli, std::ref(input_file), std::ref(total_reads)); std::thread processThread(count_frequencies_and_merge_qualities_multi, std::ref(fqs)); readerThread.join(); processThread.join(); sort(fqs.begin(), fqs.end(), sort_by_freq_quality); for (auto& out_entry : fqs) { output_file << out_entry; } return 0; } Class class FASTQentry { public: FASTQentry() = default; FASTQentry(const std::string& hdr, const std::string& seq, const std::string& plus, const std::vector<double>& probs) { header = hdr; sequence = seq; this->plus = plus; probas = probs; freq = 1; } std::string header; std::string sequence; std::string plus; std::vector<double> probas; int freq; friend std::ostream& operator<<(std::ostream& o, const FASTQentry& fq_entry); friend std::istream& operator>>(std::istream& is, FASTQentry& fq_entry); };
{ "domain": "codereview.stackexchange", "id": 45443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, concurrency", "url": null }
c++, performance, concurrency Parse File Function void parse_fastq_file_mutli(std::ifstream& infile, std::size_t& total_reads) { while (!infile.eof()) { FASTQentry fq; fq.freq = 1; infile >> fq; { std::lock_guard<std::mutex> lock(shared_queue_mutex); shared_queue.push(fq); } ++total_reads; } { std::lock_guard<std::mutex> lock(shared_queue_mutex); queue_closed = true; } } std::istream& operator>>(std::istream& is, FASTQentry& fq_entry) { is.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::getline(is, fq_entry.sequence); is.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::string quals; std::getline(is, quals); fq_entry.probas = qualities_to_probabilities(quals); return is; } std::vector<double> qualities_to_probabilities(const std::string& quals) { std::vector<double> result; result.reserve(quals.size()); for (auto& q : quals) { result.push_back(std::pow(10, (q - 33) / -10)); } return result; } Processing Function void count_frequencies_and_merge_qualities_multi(std::vector<FASTQentry>& fqs) { std::map<std::string, int> read2fqs; bool is_closed; bool empty_entry; int counter = 1; // Check if the file has been closed or if there are no more entries { std::lock_guard<std::mutex> lock(shared_queue_mutex); is_closed = queue_closed; empty_entry = shared_queue.empty(); } while (!is_closed || !empty_entry) { if (!empty_entry) { FASTQentry fq; { std::lock_guard<std::mutex> lock(shared_queue_mutex); fq = shared_queue.front(); shared_queue.pop(); } if (read2fqs.count(fq.sequence) > 0) { int index = read2fqs[fq.sequence] - 1; fqs[index].freq += 1;
{ "domain": "codereview.stackexchange", "id": 45443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, concurrency", "url": null }
c++, performance, concurrency for (int i = 0; i < fqs[index].probas.size(); ++i) { fqs[index].probas[i] += fq.probas[i]; } } else { read2fqs[fq.sequence] = counter; fq.header = "@seq_" + std::to_string(counter) + "_x"; fq.plus = "+"; fqs.push_back(fq); counter += 1; } } // Check if the file has been closed or if there are no more entries { std::lock_guard<std::mutex> lock(shared_queue_mutex); is_closed = queue_closed; empty_entry = shared_queue.empty(); } } } Sorting Function bool sort_by_freq_quality(FASTQentry fq1, FASTQentry fq2) { if (fq1.freq != fq2.freq) { return fq1.freq > fq2.freq; } else { // cumulative sum of quality auto s1 = 0.; auto s2 = 0.; for (auto i = 0ul; i < fq1.probas.size(); ++i) { s1 += fq1.probas[i]; } for (auto i = 0ul; i < fq2.probas.size(); ++i) { s2 += fq2.probas[i]; } s1 /= fq1.freq; s2 /= fq2.freq; if (s1 != s2){ return s1 > s2; } return fq1.sequence > fq2.sequence; } } Write to File std::string probabilities_to_qualities(const std::vector<double>& probas, int freq) { std::string result; result.reserve(probas.size()); for (auto& p : probas) { result.push_back(-10 * std::log10(p / freq) + 33); } return result; } I convert the code from single thread to this but I can't see much improvement. What is the bottleneck of these code? Thanks!
{ "domain": "codereview.stackexchange", "id": 45443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, concurrency", "url": null }
c++, performance, concurrency Answer: Use or make a thread-safe queue You are using a std::queue and a separate std::mutex to ensure thread-safe access. However, it's easy to make mistakes or introduce inefficiencies. For example, between the check for shared_queue.empty() and the call to shared_queue.pop_front(), you have unlocked the mutex. This is not a problem right now, since other threads only ever push items, so it can not happen that you pop while the queue is empty. But what if you want to speed up processing and want to add a second thread running count_frequencies_and_merge_qualities_multi()? Second, if you process the data faster than you can read from file, your data processing thread will do a busy loop, wasting CPU time, wasting power and increasing the temperature (which might cause the CPU to throttle). Ideally, you go to sleep until another thread pushes a new item to the queue. A proper thread-safe queue class takes care of all these things. You can find examples of them here on Code Review (be sure to read the answers of course). They also make the code using them simpler. Consider being able to write: ThreadSafeQueue<FASTQentry> shared_queue; … void parse_fastq_file_mutli(…) { while (!infile.eof()) { … infile >> fq; shared_queue.push(fq); } shared_queue.close(); } … void count_frequencies_and_merge_qualities_multi(…) { while (std::optional<FASTQentry> fq = shared_queue.pop()) { … } } Avoid code duplication You have duplicated code in sort_by_freq_quality(). Create a function that calculates the "quality" for a single FASTQentry(), so that you can then write: bool sort_by_freq_quality(FASTQentry fq1, FASTQentry fq2) { if (fq1.freq != fq2.freq) { return fq1.freq > fq2.freq; } else { return quality(fq1) > quality(fq2); } }
{ "domain": "codereview.stackexchange", "id": 45443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, concurrency", "url": null }
c++, performance, concurrency Make more use of the standard library Newer versions of the C++ standard add simpler and more useful features, such as std::ranges::sort(). But there are also features that have existed for a long time that might help simplify your code. For example, you can use std::istream_iterator along with std::copy to simplify reading the input, at least with a thread safe queue class that supports push_back(): void parse_fastq_file_mutli(std::ifstream& infile) { std::copy(std::istream_iterator<FASTQentry>(infile), std::istream_iterator<FASTQentry>(), std::back_inserter(shared_queue)); shared_queue.close(); } But you can also make use of std::accumulate to sum things and std::transform() to do conversions on ranges. Missing error checking Lots of things can go wrong when reading from and writing to files. Make sure you check the state of the stream to ensure it is still good. If you did encounter an error, make sure your program exits with an error message written to std::cerr and error code EXIT_FAILURE, otherwise errors might get missed and unexpected things might happen. Avoid global variables You already pass references to local variables in main() to the threads that you are starting, but why is the queue a global variable? You can declare that in main() and pass a reference to it as well.
{ "domain": "codereview.stackexchange", "id": 45443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, concurrency", "url": null }
c, shell, posix Title: A simple shell in C Question: The M-Shell (msh) provides a basic command-line interface similar, and features some builtins (cd, exit, help, whoami, kill). #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #ifdef _XOPEN_SOURCE #undef _XOPEN_SOURCE #endif #define _POSIX_C_SOURCE 200819L #define _XOPEN_SOURCE 700 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdint.h> #include <ctype.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <pwd.h> #include <libgen.h> #define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof ((x)[0])) #define MSH_TOK_DELIM " \t\r\n\v\f" static int msh_cd(const char *const *argv); static int msh_help(const char *const *argv); static int msh_exit(const char *const *argv); static int msh_kill(const char *const *argv); static int msh_whoami(const char *const *argv); /* * List of builtin commands, followed by their corresponding functions. */ static struct { const char *const builtin_str; int (* const builtin_func)(const char *const *); } const builtin[] = { { "cd", &msh_cd }, { "help", &msh_help }, { "exit", &msh_exit }, { "kill", &msh_kill }, { "whoami", &msh_whoami }, }; static int msh_whoami(const char *const *argv) { const uid_t uid = geteuid(); const struct passwd *const pw = (errno = 0, getpwuid(uid)); if (argv[1]) { fputs("-msh: extra operand to \"whoami\".\n", stderr); } else if (!pw || errno) { perror("-msh: "); } else { puts(pw->pw_name); } return 1; } static int msh_kill(const char *const *argv) { if (!argv[1] || !argv[2]) { fputs("-msh: expected argument to \"kill\".\n", stderr); } else if (kill((pid_t) strtol(argv[2], 0, 10), (int) strtol(argv[1], 0, 10)) == -1) { perror("-msh "); } return 1; }
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix static int msh_cd(const char *const *argv) { if (!argv[1]) { fputs("-msh: expected argument to \"cd\".\n", stderr); } else if (chdir(argv[1])) { perror("-msh"); } return 1; } static int msh_help(const char *const *argv) { (void) argv; puts("Z-Shell\n" "Type program names and arguments, and hit enter.\n" "The following are built-in:\n"); for (size_t i = 0; i < ARRAY_CARDINALITY(builtin); ++i) { puts(builtin[i].builtin_str); } puts("Use the man command for information on other programs.\n"); return 1; } static int msh_exit(const char *const *argv) { (void) argv; return 0; } /* Calls fork and execvp to duplicate and replace a process, returns 0 on failure and 1 on success */ static int msh_launch(const char *const *argv) { int status = 0; int pid = fork(); if (!pid) { if (execvp(argv[0], (char *const *) argv) == -1) { perror("msh: "); return 0; } } if (pid == -1) { perror("msh: "); return 0; } do { waitpid(pid, &status, WUNTRACED); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); return 1; } /* Returns 1 in the absence of commands or a pointer to a function if argv[0] was a built-in command. */ static int msh_execute(const char *const *argv) { if (!argv[0]) { /* No commands were entered. */ return 1; } for (size_t i = 0; i < ARRAY_CARDINALITY(builtin); ++i) { if (!strcmp(argv[0], builtin[i].builtin_str)) { return (*builtin[i].builtin_func) (argv); } } return msh_launch(argv); }
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix /* Returns a char pointer on success, or a null pointer on failure. * Caller must free the line on success. * Otherwise, msh_read_line frees all allocations and set them to point to NULL. */ static char *msh_read_line(int *err_code) { const size_t page_size = BUFSIZ; size_t position = 0; size_t size = 0; char *content = 0; clearerr(stdin); for (;;) { if (position >= size) { size += page_size; char *new = realloc(content, size); if (!new) { *err_code = ENOMEM; return 0; } content = new; } int c = getc(stdin); if (c == EOF || c == '\n') { if (feof(stdin)) { free(content); *err_code = EOF; return 0; } else { content[position] = '\0'; return content; } } else { content[position] = (char) c; } position++; } } /* Returns a pointer to pointers to null-terminated strings, or a NULL pointer on failure. * Does not free the passed char * in case of failure. */ static char **msh_parse_args(char *line) { const size_t page_size = 128; size_t position = 0; size_t size = 0; char **tokens = 0; for (char *next = line; (next = strtok(next, MSH_TOK_DELIM)); next = 0) { if (position >= size) { size += page_size; char **tmp = realloc(tokens, size * sizeof *tmp); if (!tmp) { free(tokens); return 0; } tokens = tmp; } tokens[position++] = next; } if (tokens) { tokens[position] = 0; } return tokens; } static int msh_loop(void) { int status = 0;
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix static int msh_loop(void) { int status = 0; do { char *line = NULL; char **args = NULL; /* getuid() is always successful. */ const uid_t uid = getuid(); const struct passwd *const pw = getpwuid(uid); char *cwd = getcwd(0, 0); char *base_name = cwd ? basename(cwd) : 0; printf("%s:~/%s $ ", pw ? pw->pw_name : "", base_name? base_name : ""); int err_code = 0; line = msh_read_line(&err_code); if (!line) { if (err_code == ENOMEM) { perror("-msh "); } fputc('\n', stdout); free(cwd); return 0; } if (!*line) { continue; } if (!(args = msh_parse_args(line))) { perror("-msh "); free(line); free(cwd); return 0; } status = msh_execute((const char *const *) args); free(line); free(args); free(cwd); } while (status); return 1; } int main(void) { return !msh_loop() ? EXIT_FAILURE : EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix int main(void) { return !msh_loop() ? EXIT_FAILURE : EXIT_SUCCESS; } The final executable is 14552 bytes, does not have a large memory footprint: 3442: ./msh Address Kbytes RSS Dirty Mode Mapping 0000564a55b19000 4 4 0 r---- msh 0000564a55b1a000 4 4 0 r-x-- msh 0000564a55b1b000 4 4 0 r---- msh 0000564a55b1c000 4 4 4 r---- msh 0000564a55b1d000 4 4 4 rw--- msh 0000564a579fb000 132 16 16 rw--- [ anon ] 00007f1e932fa000 12 8 8 rw--- [ anon ] 00007f1e932fd000 160 160 0 r---- libc.so.6 00007f1e93325000 1620 1004 0 r-x-- libc.so.6 00007f1e934ba000 352 216 0 r---- libc.so.6 00007f1e93512000 4 0 0 ----- libc.so.6 00007f1e93513000 16 16 16 r---- libc.so.6 00007f1e93517000 8 8 8 rw--- libc.so.6 00007f1e93519000 52 24 24 rw--- [ anon ] 00007f1e93538000 8 4 4 rw--- [ anon ] 00007f1e9353a000 8 8 0 r---- ld-linux-x86-64.so.2 00007f1e9353c000 168 168 0 r-x-- ld-linux-x86-64.so.2 00007f1e93566000 44 44 0 r---- ld-linux-x86-64.so.2 00007f1e93572000 8 8 8 r---- ld-linux-x86-64.so.2 00007f1e93574000 8 8 8 rw--- ld-linux-x86-64.so.2 00007ffd60554000 132 12 12 rw--- [ stack ] 00007ffd605b7000 16 0 0 r---- [ anon ] 00007ffd605bb000 8 4 0 r-x-- [ anon ] ffffffffff600000 4 0 0 --x-- [ anon ] ---------------- ------- ------- ------- total kB 2780 1728 112 and unlike other shells, reports no memory leaks under valgrind. Review Goals: Is the code structured properly? General coding comments, style, etc. Does any part of the code invoke undefined/implementation-defined behavior?
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix Answer: Good job! It definitely lives up to its name of "minimal shell". And while a small codebase doesn't always translate to a bug-free codebase, there's certainly fewer places for bugs to hide. I really like the layering. It makes a lot of sense as you read the source. name static int msh_help( ... ) { ... puts("Z-Shell\n" Z ?!? I was kind expecting to see "msh" there. automated tests This submission would benefit from adding a test suite that exercises the target code. NULL https://linux.die.net/man/3/getcwd As an extension to the POSIX.1-2001 standard, Linux (libc4, libc5, glibc) getcwd() allocates the buffer dynamically using malloc(3) if buf is NULL. char *cwd = getcwd(0, 0); Call me old fashioned, but I would rather see getcwd(NULL, 0) there. (Yes, yes, I know, zero and NULL are nearly the same.) check error status Thank you for helpfully pointing out that getuid() always succeeds. But some of the calls you make can fail, e.g. with ENOMEM on an unlucky call to getcwd(). I am very glad to see you carefully calling free(). goto outN line = msh_read_line( ... ); if (!line) { ... free(cwd); I feel that, instead of freeing cwd, this should be goto out3;. if (!( ... msh_parse_args(line))) { ... free(line); free(cwd); Similarly, goto out2;. And out1: would free line. out2: free(args); out3: free(cwd); return ret_val; We would need to properly set up the return value. The idea here is, for each allocate call, we write exactly one deallocate call, nicely paired up. Following such a pattern should make it harder to accidentally introduce code defects. allocation lifetime * Does not free the passed char * in case of failure. */ static char **msh_parse_args(char *line) { ... if ( ... ) { free(tokens);
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix I started writing this review remark thinking I would ask for caller to always be responsible for free'ing line. But then I realized the comment was misleading me. I imagine it used to be true, at one time. lint static int msh_exit(const char *const *argv) { (void) argv; I assume you wrote this to silence a -Wall -pedantic type of warning, and that's great, I support such practice. IDK, maybe assert that there's no arguments supplied? Which should keep the compiler happy, since we actually used the input parameter. boolean static int msh_execute( ... ) Rather than int, I feel this is more naturally a bool. Though the sense is negated. OIC, launch can return arbitrary values, so maybe introduce a status type? Similar to EXIT_{FAILURE,SUCCESS} ? I keep finding it harder than necessary to read things like this: static int msh_launch( ... ) ... return 0; because it doesn't say something like return EXIT_SUCCESS. I do like how you DRYed up help by looping and displaying each .builtin_str. The whoami and similar routines are wonderfully simple and robust. This codebase tackles modest goals, and accomplishes them, within a small memory footprint. I would be willing to delegate or accept maintenance tasks on it. EDIT for @pacmaninbw (As far as "teaching" goes, I would rather teach folks to choose a high level language instead of portable assembly. Then we do a better job of conveying technical ideas to other humans. But hey, C is what it is, sometimes ya gotta use it, so I roll with the punches.) Assume "mutex acquisition failed" is represented by a NULL return value. Here is the usual (carefully structured, nested) pattern: void do_stuff() { int ret = EXIT_FAILURE; if ((a = acquire_mutex("a")) == NULL) { goto out_a; } if ((b = acquire_mutex("b")) == NULL) { goto out_b; } if ((c = acquire_mutex("c")) == NULL) { goto out_c; } do_cool_stuff_while_holding(a, b, c); ret = EXIT_SUCCESS;
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c, shell, posix unlock("c"); out_c: unlock("b"); out_b: unlock("a"); out_a: return ret; } Notice that we obey lexical ordering of lock names, and carefully release them in reverse order, to prevent ugly scenarios like deadlock. It doesn't matter what the resource is. Could be a lock, a malloc'd string, a file descriptor, whatever. The routine needs them in order to accomplish its contract. It acquires them in sequence. But sometimes things don't go smoothly. So it releases them in reverse sequence when it bails out. If we don't follow this pattern, we may wind up replacing the if ... goto clauses with copy-pasta code. First if ... "release A, then bail". Second if ... "release B, A, then bail". (Wait, did I carefully release in the proper order?) Third if ... "release C, B, A, then bail". Now someone refactors B, turning it into D. And correctly fixes 50% of the places where we free it. Sigh! Or someone messes up the unlock order. Remember this is the exceptional path we're considering here, not the happy path. So test coverage is going to be challenging, and spotty. Forcing every single release to always execute in the Happy Path is a boon to testing. So jumping into the middle of the "release" flow is a big win here. Cultural digression: An engineer, perhaps Edsger Dijkstra or Niklaus Wirth, could nest structured elements so that a,b,c nest nicely, and so does the unwinding code for releasing resources. But hey, Linus don't code that way. So we roll with it, we don't write a bunch of trivial helpers, and we don't see the bulk of our logic inching further and further away from the left margin. Here is a typical example in BIND9, that is, in some non-kernel code: 00331 static inline dns_rdatalist_t * 00332 newrdatalist(dns_message_t *msg) { 00337 if ( ... ) { ... 00339 goto out; 00340 } ... 00355 out: 00356 if ( ... ) 00357 dns_rdatalist_init(rdatalist); 00358 00359 return (rdatalist); 00360 }
{ "domain": "codereview.stackexchange", "id": 45444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, shell, posix", "url": null }
c++, programming-challenge, functional-programming, c++23 Title: Locate and multiply numbers in a 2D grid (Advent of Code 2023 Day 3, Part 2) Question: I am using the Advent of Code 2023 to study functional programming and the ranges library in C++. This code is for the second part of Day 3 and is the best solution using FB I've created. I'd appreciate comments or advice on how this code might be improved. The input for the problem is: 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. The challenge is to extract the values adjacent to a * on the same or adjacent lines. When two numbers are near the same star, they are multiplied and summed for the final total. The example gives 467✕35 and 755✕598 for a total of 467835. The code is in my repo. I am also documenting my activities. #include <algorithm> #include <cstdint> #include <iostream> #include <ranges> #include <string_view> #include <vector> #include "../AdventCpp.h" #include "inc/fp_utility.h" #if 1 #include "inc/Trace.h" using mys::tout, mys::nl, mys::sp, mys::tab; #endif namespace rng = std::ranges; namespace vws = std::views; using rng::fold_left; using std::get, std::tuple, std::string_view; using vws::split, vws::drop_while, vws::filter, vws::enumerate, // vws::transform, vws::take, vws::chunk_by, vws::drop, vws::filter; //------------------------------------------------------------------------------ // name types for better understanding in the code // CLion shows definition using these names using LineNUmber = int64_t; using StarColumn = int64_t; using StarPosition = tuple<LineNUmber, StarColumn>; using StarRng = std::vector<StarPosition>; using ValueColumn = StarColumn; using ValueType = uint64_t; using ValuePosition = tuple<LineNUmber, ValueColumn, ValueColumn, ValueType>; using ValueRng = std::vector<ValuePosition>; using ValStarRngs = tuple<ValueRng, StarRng>; using ProductType = std::optional<ValueType>; using Products = tuple<ProductType, ProductType>; // as in multiplicands
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 using SumType = ValueType; using SumProducts = tuple<SumType, Products>; #if 0 //------------------------------------------------------------------------------ void print_val_star_vec(ValStarRngs& val_star_vec) noexcept { auto& [values, stars] {val_star_vec}; for (auto s: stars) { auto [l, p] {s}; tout << code_line << "* " << l << tab << p << tab << '*'; } tout << sp; for (auto vs: values) { auto [l, b, e, v] {vs}; tout << code_line << "V " << l << tab << b << tab << e << tab << v; } } #endif /*----------------------------------------------------------------------------- * The following routines parse the input to create a vectors for the stars * and values. The star vector contains the line an column of the star. The * values vector contains the line, starting and ending column, and the value. *----------------------------------------------------------------------------*/ constexpr auto chunk_on_digit_star = [ ](auto&& lhs, auto&& rhs) noexcept { // auto lch = get<1>(lhs); auto rch = get<1>(rhs); return !(lch == '*' or lch == '.' or rch == '*' or rch == '.'); }; //------------------------------------------------------------------------------ constexpr auto remove_non_stars = [ ](auto&& tup) noexcept { auto ch = get<1>(tup[0]); return !(ispunct(ch) and (ch != '*')); }; //------------------------------------------------------------------------------ auto extract_with_line_num = [ ](auto&& hunk, auto&& line_num) noexcept { // hunk is chunk of [position in line, "*" or "nnn"] auto [line_col, ch] {hunk[0]}; // use std::optional to determine if there is a value in the positions std::optional<ValuePosition> value_position{ }; std::optional<StarPosition> star_position{ }; if (ch == '*') { star_position = StarPosition{line_num, line_col}; } else { uint64_t value{ };
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 for (auto h: hunk | vws::values) { value = (value * 10) + (h - '0'); } auto end_col{line_col - 1 + hunk.size()}; value_position = ValuePosition{line_num, line_col, end_col, value}; } return tuple(value_position, star_position); }; //------------------------------------------------------------------------------ // use currying to call extract_star_or_value with line number as argument auto extract_star_or_value = [ ](auto&& line_num) noexcept { return [line_num](auto&& hunk) noexcept { return extract_with_line_num(hunk, line_num); }; }; //------------------------------------------------------------------------------ inline constexpr auto build_vectors_fn(auto&& val_star_tup, ValStarRngs& val_star_rngs) noexcept { auto& [value_rng, star_rng] {val_star_rngs}; auto& [value_tup, star_tup] {val_star_tup}; if (value_tup) { value_rng.push_back(value_tup.value()); } if (star_tup) { star_rng.push_back(star_tup.value()); } return val_star_rngs; }; //------------------------------------------------------------------------------ constexpr auto build_vectors = [ ](ValStarRngs& val_star_rngs) noexcept { return [&val_star_rngs](auto&& val_star_tup) noexcept { return build_vectors_fn(val_star_tup, val_star_rngs); }; }; //------------------------------------------------------------------------------ constexpr auto parse_line = [ ](auto&& val_star_rngs, auto&& numbered_lines) noexcept { auto [line_num, line] = numbered_lines; // process a line to get position of value or stars line // | enumerate // create tuple of {column, char} | chunk_by(chunk_on_digit_star) // chunk by digits or * | filter(remove_non_stars) // remove chunks that are dots | transform(extract_star_or_value(line_num)) // | transform(build_vectors(val_star_rngs)) // | mys::eval(); // eval() is a range-for in a pipeline operator
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 return val_star_rngs; }; /*----------------------------------------------------------------------------- * The next routines handle the calculation of the products and sum by walking * through the star vector. The value vector is searched for the line numbers * before, after, and the same as the star line. Then the position of the * star and value are checked for 'contact'. If two values are found they * become the products (multiplicands) and used to increase the sum. *----------------------------------------------------------------------------*/ constexpr auto drop_until_star = [ ](LineNUmber star_line) noexcept { return drop_while( // [star_line](auto&& elem) noexcept { auto [value_line, _b, _e, _v] {elem}; return value_line < std::max({ }, star_line - 1); }); }; //------------------------------------------------------------------------------ constexpr auto value_near_star = [ ](LineNUmber star_line) noexcept { return filter( // [star_line](auto&& elem) noexcept { auto [value_line, _b, _e, _v] {elem}; return (star_line == std::clamp(star_line, value_line - 1, value_line + 1)); }); }; //------------------------------------------------------------------------------ constexpr auto get_products = // [ ](StarColumn star_col, Products& products) noexcept { return // [star_col, &products](auto&& elem) noexcept { auto [_, value_begin, value_end, value] {elem}; auto clmp = rng::clamp(star_col, value_begin - 1, value_end + 1) == star_col; if (clmp) { auto& [lhs, rhs] {products};
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 if (clmp) { auto& [lhs, rhs] {products}; // lhs & rhs are optionals so can test for values with var name if (!lhs) { lhs = value; } else if (!rhs) { rhs = value; } } return products; }; }; //------------------------------------------------------------------------------ inline constexpr auto summation_fn(auto&& sum_products, auto&& star_position, auto&& values_rng) noexcept -> SumProducts { auto& [sum, products] {sum_products}; auto& [star_line, star_col] {star_position}; rng::for_each(values_rng // | drop_until_star(star_line) // | value_near_star(star_line), // get_products(star_col, products)); auto& [lhs, rhs] {products}; sum += lhs.value_or(0) * rhs.value_or(0); // aka products products = { }; return sum_products; }; //------------------------------------------------------------------------------ // use currying to call summation with values as argument constexpr auto summation = [ ](auto&& values_rng) noexcept { return [values_rng](auto&& sum_products, auto&& star_position) noexcept -> SumProducts { return summation_fn(sum_products, star_position, values_rng); }; }; //------------------------------------------------------------------------------ constexpr auto parse_lines(string_view const& data) noexcept -> ValStarRngs { auto split_enumerate{ // split('\n') // split into line | enumerate // make tuple with line number and line };
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 // parse lines to produce ranges with star position and value position ValStarRngs val_star_rngs = // fold_left(data | split_enumerate, ValStarRngs{ }, parse_line); return val_star_rngs; } //------------------------------------------------------------------------------ constexpr auto calculate_values(ValStarRngs const& val_star_rngs) noexcept -> SumType { // walk through stars range. find surrounding value lines in this range // and check if columns align with product values const auto& [values_rng, stars_rng] {val_star_rngs}; auto [sum, _] = fold_left(stars_rng, // SumProducts{{ }, {Products{ }}}, // summation(values_rng)); return sum; } //------------------------------------------------------------------------------ execFunc execute = [ ](string_view data) { ValStarRngs val_star_rngs = parse_lines(data); return calculate_values(val_star_rngs); }; //------------------------------------------------------------------------------ auto main() -> int { advent_cpp(test_data1, aoc_data, execute, 467835); // 467835 / 84907174 return 0; }
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 Answer: Your code makes very good use of ranges and views. It looks like you are using a very heavy functional programming style. This might be unfamiliar to many C++ programmers though, and it borders on overusing this style. I'll explain why in more detail below. Use of type aliases Creating type aliases helps document the use of certain types, and also makes it easier to change that type without having to search and replace through all of the code. However, you are declaring lots of them, and some of that is unnecessary. For example, why do you have both StarColumn and ValueColumn? Because you gave them different names, it implies those types might be different. But that's never the case; they are just columns in the same input. So I would declare just Column. There's also LineNUmber, which is also used in a way very similar to Column. Maybe you just need one Index type? Also, sometimes a type alias can hide important details of a type, which can confuse someone reading the code. For example, ProductType hides that it is a std::optional type. It might be better to not use a type alias in that case, even if it's a bit longer to type. There are more issues with your type aliases: Prefer creating a struct over using std::tuple Instead of creating std::tuples, create structs where possible. The main advantage is that you can give names to each member, whereas with a tuple you have to use std::get<> and remember the exact order of the tuple elements. Consider: using Index = int64_t; struct StarPosition { Index line; Index column; }; struct ValuePosition { Index line; Index begin_column; Index end_column; ValueType value; }; Note that you can still use structured bindings with structs. Naming things Some of your names are confusing or otherwise badly chosen:
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 StarRng: this is a container of star positions. A range does not have to be a container. I would name this StarPositionContainer to be very precise about what it is. Note that you could also do this: template<typename T> using Container = std::vector<T>; struct Positions { Container<ValuePosition> values; Container<StarPosition> stars; }; ValStarRngs: same as above, but you also abbreviated Value to Val. Make sure you are consistent in how you name and abbreviate things. print_val_star_vec(): first you create an alias to hide the type of container used for positions, but now you hardcode the fact that it's a vector in the name. I would name this print_value_and_star_positions(), or perhaps shorter print_positions(). summation_fn(): why put _fn at the end? You already know it is a function, and you don't put _fn at the end of the name of every other function. If it conflicts with summation, I would find another way to resolve the conflict. build_vectors_fn(): same. summation: function names should be verbs. I would name this sum or calculate_sum. chunk_on_digit_star: this function does not do any chunking itself, so it should not have chunk in its name. Also, a dot (.) is not a digit. Maybe is_not_dot_or_star() is better. remove_non_stars: the same issues. At first glance, is_not_punctuation_except_stars() might be a precise name. But it sounds very complicated. You can simplify it by avoiding the negation, and write an is_punctuation_except_stars(), and then use std::not_fn() to negate it when filtering. It's still very long, but it's better to be precise. extract_with_line_num(): extract what? I would name this extract_value_or_star_position(), or shorter extract_position(). build_vectors: again, don't add the container type to the name. Also, build a vector of what? It just adds one position, so maybe add_position()? Et cetera.
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 Unnecessary use of lambdas Named lambdas are just a complicated way of defining a function. Write a regular function instead. For example: constexpr auto is_dot_or_star(auto&& lhs, auto&& rhs) noexcept { // auto lch = get<1>(lhs); auto rch = get<1>(rhs); return lch == '*' or lch == '.' or rch == '*' or rch == '.'; }; Functions also have an advantage over named lambdas: you can overload them. So if you made summation a regular function, you could then rename summation_fn() to summation() and it would compile without problems. Overuse of auto I see auto&& used a lot. This makes everything a template that accepts any type, and will take things non-const where possible. But you know exactly what the type of everything is here, and many parameters should not be changed, and so should be const (references). Also, if you know the return type, you can specify it as well. So rather write: constexpr bool is_dot_or_star(const char lhs, const char rhs) noexcept { … }; Make use of std::variant You return a tuple of two optionals from extract_with_line_num(). However, always exactly only one of the optionals holds a value. In that case, consider using std::variant in combination with std::visit(): auto extract_value_or_star_position(auto& hunk, auto&& line_num) noexcept -> std::variant<ValuePosition, StarPosition> { auto [line_col, ch] {hunk[0]}; if (ch == '*') { return StarPosition{line_num, line_col}; } else { … return ValuePosition{line_num, line_col, end_col, value}; } } Of course you can create a type alias for the variant: using Position = std::variant<ValuePosition, StarPosition>; To "build vectors", you can then write: constexpr void add_position(Positions& positions, const StarPosition &position) noexcept { positions.stars.push_back(position); } constexpr void add_position(Positions& positions, const ValuePosition &position) noexcept { positions.values.push_back(position); }
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 constexpr Positions& add_position(Positions& positions) noexcept { return [&](const Position& value_or_star_position) noexcept { std::visit([&](auto& position) { add_position(positions, position); }); return positions; }; }; Or if you would add two push_back() member functions to Positions, one that takes a StarPosition and the other a ValuePosition, then you can just write: constexpr Positions& add_position(Positions& positions) noexcept { return [&](const Position& value_or_star_position) noexcept { std::visit([&](auto& position) { positions.push_back(position); }); return positions; }; }; Or alternatively, you could make Positions a single container holding variants: using Positions = Container<Position>; But that would just shift the problem of separating the star and value positions to another part of the code. Use of inline, constexpr, noexcept You use these keywords almost everywhere possible. It probably looks like a good thing to do, right? But they don't actually do anything in your code:
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 inline on functions is just a hint for the compiler. However, nowadays compilers will aggressively inline automatically, so in almost all cases, inline doesn't result in any change in the output of the compiler. It just adds noise to the source code, so just omit it. constexpr ensures that it is possible to evaluate a function at compile time, however it doesn't force the compiler to do that. Also, everything in your program depends on input from files, so all your functions will only ever be called at runtime. So constexpr is not doing anything for your code, and again just adds noise to the source code. noexcept doesn't make functions that don't throw to begin with more efficient in any way. It might help in some ver specific cases, for example if you have a noexcept move constructor in a class, then a vector holding objects of that class might use a more efficient method of resizing its storage. But nothing like that is happening in your code. Again, it's just adding noise. Efficiency There are several inefficiencies in your code. Consider this statement: ValStarRngs val_star_rngs = fold_left(data | split_enumerate, ValStarRngs{ }, parse_line); Basically, this loops over every line, parses it, and adds values and star positions to val_star_rngs. However, parse_line gets a ValStarRngs as input, adds some positions to it, and then returns a copy of the ValStarRngs object. So copies of vectors are made for every line you parse. That's not efficient. A much better way would be to write it like so: void parse_line(const auto& numbered_line, Positions& positions) { auto [line_num, line] = numbered_lines; for (auto& position: line | enumerate | chunk_by(chunk_on_digit_star) | filter(remove_non_stars) | transform(extract_star_or_value(line_num))) { add_position(positions, position); } } Positions parse_lines(string_view data) { Positions positions{};
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
c++, programming-challenge, functional-programming, c++23 Positions parse_lines(string_view data) { Positions positions{}; for (auto& line: data | split('\n') | enumerate) { parse_line(line, positions); } return positions; } Yes, that's a little less functional, not because of the for-loop, but because parse_line() has side-effects. However, it is much more efficient. You could make it functional again and avoid the copies, by adding a constructor to Positions that takes a range of Positions as an input, and then rewrite your code so it looks like: Positions parse_lines(string_view data) { return data | split('\n') | enumerate | parse_line | to<Positions>(); } Where to() is std::ranges::to(). And parse_line should now be a view that returns zero or more Position values for each input line. That should be possible to implement, but I'm not sure how to construct something like that with just the functionality from the standard library. The call to fold_left() in calculate_values() is fine; while technically it also passes around copies, it's not a container of variable size, and the compiler will be able to optimize those copies away. But the for_each() in summation_fn() is an issue: each time summation_fn() is called, it has to go through all value positions, drop all of them except for the few around star_line. That's a lot of wasted effort, and makes it so the complexity of your algorithm is \$O(N^2)\$. If instead you indexed your data by line, you don't need to scan-and-drop. For example: Container<Positions> positions_on_lines; This container would have one entry per line. So if you want to know the positions of all values on a given line number, you would just write positions_on_lines[line_num].values, and your algorithm would have complexity \$O(N)\$ instead.
{ "domain": "codereview.stackexchange", "id": 45445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, programming-challenge, functional-programming, c++23", "url": null }
python, file-system Title: NTFS Master File Table Parser Question: I have written a Python program to parse the Master File Table located by //?/X:/$MFT. Of course trying to open it normally will result in PermissionDenied. I got around this by open(f"//?/{drive}:", "rb"), and get the starting cluster of $MFT and read the first 1024 bytes starting at 4096 * cluster count. I wrote this program to parse all file records in $MFT and store them in memory, each file record has a length of 1024 bytes, and I am interested in their $STANDARD_INFORMATION, $ATTRIBUTE_LIST, $FILE_NAME and (non-resident) $DATA attributes, because I want to resolve file record segment addresses from D:\System Volume Information\Chkdsk\chkdskyyyymmddHHMMSS.log to absolute file paths. Because NTFS is very complex I won't bother describing how it works, I wrote all of the code entirely by myself, using this, this and this as references. The code is incomplete, but the core functionalities are implemented and working properly, I am trying to organize the resultant information better and make it use less memory, I have only parsed a select few attributes and flags because they are what I wanted, and other attributes will make the objects use more memory. I have determined that if I load all 2247424 entries in the target $MFT I can expect the program to use 3GiB 376MiB 562KiB 380B memory, and I want to make it use less memory. import re from datetime import datetime, timedelta from typing import Callable, Generator, Mapping, NamedTuple, Sequence, Set
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system SHORT_PATH = re.compile(r"^\w{6}~\d+\.\w{3}$") EPOCH = datetime(1601, 1, 1, 0, 0, 0) FILE_GOOD = ("BAAD", "FILE") UNITS = ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB") BOOT_SECTOR = ( (0, 3, "assembly", 0), (3, 11, "OEM_ID", 0), (11, 13, "bytes/sector", 1), (13, 14, "sectors/cluster", 1), (21, 22, "media_descriptor", 0), (24, 26, "sectors/track", 1), (26, 28, "heads", 1), (28, 32, "hidden_sectors", 1), (40, 48, "total_sectors", 1), (48, 56, "$MFT_cluster", 1), (56, 64, "$MFTMirr_cluster", 1), (64, 65, "FRS_length", 1), (72, 80, "volume_serial_number", 1), (84, 510, "bootstrap_code", 0), (510, 512, "end-of-sector", 0), ) ATTRDEF_FLAGS = ((2, "Indexed"), (64, "Resident"), (128, "Non-Resident")) ATTRIBUTE_TYPES = { 16: "$STANDARD_INFORMATION", 32: "$ATTRIBUTE_LIST", 48: "$FILE_NAME", 64: "$OBJECT_ID", 80: "$SECURITY_DESCRIPTOR", 96: "$VOLUME_NAME", 112: "$VOLUME_INFORMATION", 128: "$DATA", 144: "$INDEX_ROOT", 160: "$INDEX_ALLOCATION", 176: "$BITMAP", 192: "$REPARSE_POINT", 208: "$EA_INFORMATION", 224: "$EA", 256: "$LOGGED_UTILITY_STREAM", } FILE_PERMISSIONS = (1, 2, 4, 32) HEADER_FLAGS = (1, 2) class Record_Header(NamedTuple): Written: int Hardlinks: int Record_Size: int Base_Record: int Record_ID: int In_Use: bool Directory: bool class NonResident_Attribute(NamedTuple): Type: str Real_Size: int Name: str Data_Runs: tuple class Resident_Attribute(NamedTuple): Type: str Name: str Attribute: NamedTuple class File_Permissions(NamedTuple): Read_Only: bool Hidden: bool System: bool Archive: bool class Standard_Information(NamedTuple): File_Created: datetime File_Modified: datetime Record_Changed: datetime Last_Access: datetime File_Permissions: File_Permissions
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system class Attribute_List_Entry(NamedTuple): Type: int Base_Record: int Name: str class FileName(NamedTuple): Parent_Record: int Allocated_Size: int Real_Size: int Name: str class File_Record(NamedTuple): Header: Record_Header Attributes: tuple def parse_file_permissions(data: bytes) -> File_Permissions: flag = parse_little_endian(data) return File_Permissions(*(bool(flag & bit) for bit in FILE_PERMISSIONS)) def parse_NTFS_timestamp(data: bytes) -> datetime: return EPOCH + timedelta(seconds=int.from_bytes(data, "little") * 1e-7) def parse_sined_little_endian(data: bytes) -> int: return ( -1 * (1 + sum((b ^ 0xFF) * (1 << i * 8) for i, b in enumerate(data))) if data[-1] & 128 else int.from_bytes(data, "little") ) def parse_little_endian(data: bytes) -> int: return int.from_bytes(data, "little") def get_attribute_name(data: bytes) -> str: return ATTRIBUTE_TYPES[parse_little_endian(data)] FILE_RECORD_HEADER = ( (16, 18, parse_little_endian), (18, 20, parse_little_endian), (24, 28, parse_little_endian), (32, 38, parse_little_endian), (44, 48, parse_little_endian), ) NONRESIDENT_HEADER = ( (0, 4, get_attribute_name), (48, 56, parse_little_endian), ) A1_STANDARD_INFORMATION = ( (0, 8, parse_NTFS_timestamp), (8, 16, parse_NTFS_timestamp), (16, 24, parse_NTFS_timestamp), (24, 32, parse_NTFS_timestamp), (32, 36, parse_file_permissions), ) A2_ATTRIBUTE_LIST = ( (0, 4, get_attribute_name), (16, 22, parse_little_endian), ) A3_FILENAME = ( (0, 6, parse_little_endian), (40, 48, parse_little_endian), (48, 56, parse_little_endian), ) def parse_standard_information(data: bytes) -> Standard_Information: return Standard_Information( *(func(data[start:end]) for start, end, func in A1_STANDARD_INFORMATION) )
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system def parse_attribute_list_gen(data: bytes) -> Generator[Attribute_List_Entry, None, None]: while len(data) > 26: offset = 26 + 2 * data[6] yield Attribute_List_Entry( *(func(data[start:end]) for start, end, func in A2_ATTRIBUTE_LIST), data[26:offset:2].decode(), ) data = data[((offset + 7) >> 3) << 3 :] def parse_attribute_list(data: bytes) -> tuple: return tuple(parse_attribute_list_gen(data)) def parse_filename(data: bytes) -> FileName: name = data[66 : 66 + 2 * data[64]] try: name = name.decode("utf8").replace("\x00", "") except UnicodeDecodeError: name = name.decode("utf-16-le").replace("\x00", "") return FileName(*(func(data[start:end]) for start, end, func in A3_FILENAME), name) def parse_record_header(data: bytes) -> Record_Header: flag = parse_little_endian(data[22:24]) return Record_Header( *(func(data[start:end]) for start, end, func in FILE_RECORD_HEADER), flag & 1, flag & 2, ) def ignore(): pass ATTRIBUTE_PARSERS = { "$STANDARD_INFORMATION": parse_standard_information, "$ATTRIBUTE_LIST": parse_attribute_list, "$FILE_NAME": parse_filename, "$DATA": ignore, } def format_size(length: int) -> str: string = "" i = 0 while length and i < 10: chunk = length & 1023 length >>= 10 if chunk: string = f"{chunk}{UNITS[i]} {string}" i += 1 if length: string = f"{length}QiB {string}" return string.rstrip()
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system i += 1 if length: string = f"{length}QiB {string}" return string.rstrip() def process_boot_sector(data: dict) -> None: data["raw_size"] = size = data["bytes/sector"] * data["total_sectors"] data["readable_size"] = format_size(size) data["bytes/cluster"] = cluster = data["bytes/sector"] * data["sectors/cluster"] data["$MFT_index"] = data["$MFT_cluster"] * cluster frs_length = data["FRS_length"] if frs_length < 128: data["FRS_length"] = frs_length * cluster else: data["FRS_length"] = 1 << (256 - frs_length) def open_partition(drive: str) -> dict: partition = open(f"//?/{drive}:", "rb") sector = partition.read(512) decoded = {} for start, end, name, little in BOOT_SECTOR: data = sector[start:end] if little: data = int.from_bytes(data, "little") decoded[name] = data process_boot_sector(decoded) partition.seek(0) return { "handle": partition, "info": decoded, } def decode_attrdef_name(data: bytes) -> str: return bytes(b for b in data if b).decode("utf8") def decode_attrdef_flags(data: bytes) -> list: flag = int.from_bytes(data, "little") return [name for bit, name in ATTRDEF_FLAGS if flag & bit] def parse_attrdef(data: bytes) -> dict: result = {} while data[0]: result[parse_little_endian(data[128:132])] = decode_attrdef_name(data[:128]) data = data[160:] return result def preprocess_file_record(data: bytes) -> bytes: if data[:4] != b"FILE": raise ValueError("File record is corrupt") token = data[48:50] if token != data[510:512] or token != data[1022:1024]: raise ValueError("File record is corrupt") update_sequence = data[50:54] return data[:510] + update_sequence[:2] + data[512:1022] + update_sequence[2:]
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system def parse_data_runs(data: bytes) -> Generator[tuple, None, None]: while (size := data[0]) and len(data) > 2: count = (size & 15) + 1 first = (size >> 4) + count cluster_count = parse_little_endian(data[1:count]) starting_cluster = parse_little_endian(data[count:first]) data = data[first:] yield (starting_cluster, cluster_count) def parse_nonresident(data: bytes, limit: int) -> list: name_offset = parse_little_endian(data[10:12]) offset = parse_little_endian(data[32:34]) name = data[name_offset:offset:2].decode() if data[9] else "" return NonResident_Attribute( *(func(data[start:end]) for start, end, func in NONRESIDENT_HEADER), name, tuple(parse_data_runs(data[offset:limit])), ) def parse_resident( data: bytes, attribute_type: str, parser: Callable ) -> Resident_Attribute: length = parse_little_endian(data[16:20]) name_offset = parse_little_endian(data[10:12]) offset = parse_little_endian(data[20:22]) name = data[name_offset:offset:2].decode() if data[9] else "" return Resident_Attribute( attribute_type, name, parser(data[offset : offset + length]), ) def parse_record_attributes(data: bytes) -> Generator: data = data[56:] while data[:4] != b"\xff\xff\xff\xff": length = parse_little_endian(data[4:8]) attribute_type = get_attribute_name(data[:4]) if func := ATTRIBUTE_PARSERS.get(attribute_type): if data[8]: yield parse_nonresident(data, length) elif func is not ignore: attribute = parse_resident(data, attribute_type, func) if not ( attribute.Type == "$FILE_NAME" and SHORT_PATH.match(attribute.Attribute.Name) ): yield attribute data = data[length:]
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system def parse_file_record(data: bytes) -> File_Record: data = preprocess_file_record(data) return File_Record(parse_record_header(data), tuple(parse_record_attributes(data))) def get_size(obj: object) -> int: size = obj.__sizeof__() if isinstance(obj, Mapping): size += sum(get_size(k) + get_size(v) for k, v in obj.items()) elif isinstance(obj, Sequence | Set) and not isinstance(obj, str): size += sum(get_size(e) for e in obj) return size if __name__ == "__main__": partition = open_partition("D") handle = partition["handle"] info = partition["info"] frs_length = info["FRS_length"] handle.seek(info["$MFT_index"]) records = [] for _ in range(65536): data = handle.read(1024) records.append(parse_file_record(data)) print(format_size(get_size(records) // 65536))
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system Example records: In [2]: records[:16] Out[2]: [File_Record(Header=Record_Header(Written=1, Hardlinks=1, Record_Size=408, Base_Record=0, Record_ID=0, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=2301362176, Real_Size=2301362176, Name='$MFT')), NonResident_Attribute(Type='$DATA', Real_Size=2301362176, Name='', Data_Runs=((2, 561856),)))), File_Record(Header=Record_Header(Written=1, Hardlinks=1, Record_Size=344, Base_Record=0, Record_ID=1, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=4096, Real_Size=4096, Name='$MFTMirr')), NonResident_Attribute(Type='$DATA', Real_Size=4096, Name='', Data_Runs=((171046397, 1),)))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=2, Hardlinks=1, Record_Size=344, Base_Record=0, Record_ID=2, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=67108864, Real_Size=67108864, Name='$LogFile')), NonResident_Attribute(Type='$DATA', Real_Size=67108864, Name='', Data_Runs=((573699706, 16384),)))), File_Record(Header=Record_Header(Written=3, Hardlinks=1, Record_Size=416, Base_Record=0, Record_ID=3, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=0, Real_Size=0, Name='$Volume')))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=4, Hardlinks=1, Record_Size=344, Base_Record=0, Record_ID=4, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=4096, Real_Size=2560, Name='$AttrDef')), NonResident_Attribute(Type='$DATA', Real_Size=2560, Name='', Data_Runs=((165002433, 1),)))), File_Record(Header=Record_Header(Written=5, Hardlinks=1, Record_Size=768, Base_Record=0, Record_ID=5, In_Use=1, Directory=2), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2024, 1, 29, 14, 58, 44, 660774), Record_Changed=datetime.datetime(2024, 1, 29, 14, 58, 44, 660774), Last_Access=datetime.datetime(2024, 1, 29, 14, 58, 45, 661135), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=0, Real_Size=0, Name='.')))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=6, Hardlinks=1, Record_Size=344, Base_Record=0, Record_ID=6, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=122044416, Real_Size=122044128, Name='$Bitmap')), NonResident_Attribute(Type='$DATA', Real_Size=122044128, Name='', Data_Runs=((171046398, 24577), (4124482825, 5219))))), File_Record(Header=Record_Header(Written=7, Hardlinks=1, Record_Size=440, Base_Record=0, Record_ID=7, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=8192, Real_Size=8192, Name='$Boot')), NonResident_Attribute(Type='$DATA', Real_Size=8192, Name='', Data_Runs=((0, 2),)))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=8, Hardlinks=1, Record_Size=376, Base_Record=0, Record_ID=8, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=0, Real_Size=0, Name='$BadClus')), NonResident_Attribute(Type='$DATA', Real_Size=3999141965824, Name='$Bad', Data_Runs=((0, 976353019),)))), File_Record(Header=Record_Header(Written=9, Hardlinks=1, Record_Size=968, Base_Record=0, Record_ID=9, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=0, Real_Size=0, Name='$Secure')), NonResident_Attribute(Type='$DATA', Real_Size=319444, Name='$SDS', Data_Runs=((684234, 78),)))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=10, Hardlinks=1, Record_Size=408, Base_Record=0, Record_ID=10, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=131072, Real_Size=131072, Name='$UpCase')), NonResident_Attribute(Type='$DATA', Real_Size=131072, Name='', Data_Runs=((158628201, 32),)))), File_Record(Header=Record_Header(Written=11, Hardlinks=1, Record_Size=952, Base_Record=0, Record_ID=11, In_Use=1, Directory=2), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2023, 3, 13, 17, 37, 23, 724527), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))), Resident_Attribute(Type='$FILE_NAME', Name='', Attribute=FileName(Parent_Record=5, Allocated_Size=0, Real_Size=0, Name='$Extend')))),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=12, Hardlinks=0, Record_Size=288, Base_Record=0, Record_ID=12, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))),)), File_Record(Header=Record_Header(Written=13, Hardlinks=0, Record_Size=288, Base_Record=0, Record_ID=13, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))),)), File_Record(Header=Record_Header(Written=14, Hardlinks=0, Record_Size=288, Base_Record=0, Record_ID=14, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))),)),
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system File_Record(Header=Record_Header(Written=15, Hardlinks=0, Record_Size=288, Base_Record=0, Record_ID=15, In_Use=1, Directory=0), Attributes=(Resident_Attribute(Type='$STANDARD_INFORMATION', Name='', Attribute=Standard_Information(File_Created=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Modified=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Record_Changed=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), Last_Access=datetime.datetime(2021, 3, 21, 9, 41, 47, 819000), File_Permissions=File_Permissions(Read_Only=False, Hidden=True, System=True, Archive=False))),))]
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system How can I improve this program? Edit Minor oversight, in the original code $ATTRIBUTE_LIST entries won't be parsed but a generator object will be created, the data isn't stored in memory and this is unintended. I have fixed it.
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
python, file-system Answer: In UNITS you should split the IEC prefix (Mi, Gi, etc.) away from the unit B. BOOT_SECTOR is not structured enough - it's entirely unclear what those four fields are, and this could be fixed by constructing from each of those sequences a named tuple. Further, though, those seem like field offsets with names, so you should throw the whole thing away and use a proper ctypes structure definition. This pattern occurs multiple times through your code. The theme is - reduce the amount of magic-number offsets in your code, and move away from imperative decoding and toward declarative decoding. timedelta(seconds=int.from_bytes(data, "little") * 1e-7) is incorrectly using seconds and a large multiplier, when it should use microseconds and a smaller multiplier. Never write -1 *; use a unary negation - instead. parse_sined should be spelled parse_signed. More importantly, that method is doing a lot of manual bit-munging that should be deleted and replaced with proper ctypes and struct unpacking calls. In format_size, re-formatting of the style string = f'{string}' is not efficient. Ideally this would be split into two functions - one a generator yielding string fragments, and the outer function performing a join. Why would you rstrip on a string you've constructed yourself? Use of data: dict is poorly typed for a few reasons. First, don't use dict without specifying its inner types. More importantly, don't use dict at all; pass around immutable structures. "Processing" a data dictionary by mutating it after only half of it has been constructed is an anti-pattern; typical solutions are to split it into two objects, or perform construction of all of the values at once in a @classmethod. There's more, but that (especially use of ctypes) will go a long way.
{ "domain": "codereview.stackexchange", "id": 45446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file-system", "url": null }
c++, algorithm Title: Implement document processing system Question: I have to implement a class with method that takes document: struct TDocument { string url; // document identifier uint64_t pubDate; uint64_t fetchTime; string text; uint64_t firstFetchTime = 0; }; The method should return document with updated fields according to the following rules: text and fetchTime must be the same as the document with max fetchTime (take into account only documents with the same URL) pubDate must be the same as the pubDate in document with min fetchTime (take into account only documents with the same URL) firstFetchTime must be the same as the fetchTime in the document with min fetchTime (take into account only documents with the same URL) Example: Input: url="url1", pubDate=1, fetchTime=1, text="text1" url="url1", pubDate=2, fetchTime=3, text="text2" Output: url="url1", pubDate=1, fetchTime=1, text="text1", firstFetchTime=1 // for the first input line return the same document with updated firstFetchTime url="url1", pubDate=1, fetchTime=2, text="text2", firstFetchTime=1 // for the second input line update pubDate is 1 (because the should take min value among documents with the same URL My idea: is to store minFetchTime and maxFetchTime among documents with the same URL Could you please review my solution? Are there similar tasks on the LeetCode.com? Code struct TDocument { string url; uint64_t pubDate; // pubdate of the minFetchTime uint64_t fetchTime; // maxFetchTime string text; // maxFetchTime uint64_t firstFetchTime = 0; // minFetchTime }; struct UtilityDocument { UtilityDocument(string url_, uint64_t pubDate_, string text_, uint64_t firstFetchTime_, uint64_t maxFetchTime_, uint64_t minFetchTime_) : url(url_), pubDate(pubDate_), text(text_), firstFetchTime(firstFetchTime_), maxFetchTime(maxFetchTime_), minFetchTime(minFetchTime_) {} public: string url; uint64_t pubDate; string text; uint64_t firstFetchTime;
{ "domain": "codereview.stackexchange", "id": 45447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm uint64_t maxFetchTime; uint64_t minFetchTime; }; class TProcessor { public: std::shared_ptr<TDocument> Process(std::shared_ptr<TDocument> input) { if (docs_.contains(input->url)) { if (input->fetchTime > docs_[input->url]->maxFetchTime) { docs_[input->url]->maxFetchTime = input->fetchTime; docs_[input->url]->text = input->text; input->pubDate = docs_[input->url]->pubDate; input->firstFetchTime = docs_[input->url]->minFetchTime; } if (input->fetchTime < docs_[input->url]->minFetchTime) { docs_[input->url]->minFetchTime = input->fetchTime; docs_[input->url]->pubDate = input->pubDate; input->text = docs_[input->url]->text; input->fetchTime = docs_[input->url]->maxFetchTime; } } else { input->firstFetchTime = input->fetchTime; docs_[input->url] = shared_ptr<UtilityDocument>(new UtilityDocument( input->url, input->pubDate, input->text, input->firstFetchTime, input->fetchTime, // maxFetchTime input->fetchTime // minFetchTime )); } return input; }; private: unordered_map<string, std::shared_ptr<UtilityDocument>> docs_; };
{ "domain": "codereview.stackexchange", "id": 45447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm Answer: There should be some documentation, I think at least of TDocument and TProcessor.Process(). It looks tempting to have something modelling what's common to TDocument and whatever models info about all same URL TDocuments for Process() - I don't think the latter is a/one document and name it differently. Without any methods in TDocument, the question of is-a seems moot, but seeing no use of UtilityDocument.firstFetchTime, I'm unconvinced derivation helps. Far as I remember, specifying visibility public is pointless in a struct without preceding restriction. In Process(), all those repetitions of docs_[input->url] are too verbose for my taste. As 37307554 points out, not setting the doc's pubDate and firstFetchTime looks flaky, I'll extend that to text and fetchTime. /*** a TDocument keeps URL, text, publication date and time fetched * and in addition the time this URL was first fetched _when Process()ed_ */ struct TDocument { string url; // document identifier uint64_t pubDate; // processed: of doc with min fetchTime uint64_t fetchTime; // processed: of doc with max fetchTime string text; // processed: of doc with max fetchTime uint64_t firstFetchTime = 0; // processed: of doc with min fetchTime }; struct URLInfo { // for documents with same URL URLInfo(string url_, string text_, uint64_t pubDate_, uint64_t maxFetchTime_, uint64_t minFetchTime_) : url(url_), text(text_), pubDate(pubDate_), maxFetchTime(maxFetchTime_), minFetchTime(minFetchTime_) {} string url; string text; uint64_t pubDate; uint64_t maxFetchTime; uint64_t minFetchTime; };
{ "domain": "codereview.stackexchange", "id": 45447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm class TProcessor { public: /** URL info instantiated or updated as necessary; * text and fetchTime are set to the URL's text & max fetchTime; * pubDate & firstFetchTime to the URL's pubDate & min fetchTime. */ std::shared_ptr<TDocument> Process(std::shared_ptr<TDocument> input) { auto found = docs_.find(input->url); if (found != docs_.end()) { // assert(found->minFetchTime <= found->maxFetchTime) ? if (input->fetchTime > found->maxFetchTime) { found->maxFetchTime = input->fetchTime; found->text = input->text; } else if (input->fetchTime < found->minFetchTime) { found->minFetchTime = input->fetchTime; found->pubDate = input->pubDate; } // XXX what if ==? input->pubDate = found->pubDate; input->fetchTime = found->maxFetchTime; input->text = found->text; input->firstFetchTime = found->minFetchTime; } else { input->firstFetchTime = input->fetchTime; docs_[input->url] = shared_ptr<URLInfo>(new URLInfo( input->url, input->text, input->pubDate, input->fetchTime, // maxFetchTime input->fetchTime // minFetchTime )); } return input; }; private: unordered_map<string, std::shared_ptr<URLInfo>> docs_; }; Using an else if where comparing doc fetchTime and URL max/minFetchTime leads me to suspect a gap in the specification. Caveat: I didn't code C++ in earnest for decades, no modern C++, obviously.
{ "domain": "codereview.stackexchange", "id": 45447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c, json, curl Title: Fetch a Quranic Verse from the Web Question: Verse is a command-line program that allows you to retrieve specific verses from the Quran. It takes a chapter and verse number as input and provides you with the corresponding Quranic verse. Dependencies: libcurl libjansson strtoi.h: #ifndef STRTOI_H #define STRTOI_H typedef enum { STRTOI_SUCCESS, STRTOI_OVERFLOW, STRTOI_UNDERFLOW, STRTOI_INCONVERTIBLE } strtoi_errno; /** * @brief strtoi() shall convert string nptr to int out. * * @param nptr - Input string to be converted. * @param out - The converted int. * @param base - Base to interpret string in. Same range as strtol (2 to 36). * * The format is the same as strtol, except that the following are inconvertible: * * - empty string * - leading whitespace * - any trailing characters that are not part of the number * * @return Indicates if the operation succeeded, or why it failed. */ strtoi_errno strtoi(int *restrict out, const char *restrict nptr, int base); #endif /* STRTOI_H */ strtoi.c: #include "strtoi.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <limits.h> #include <ctype.h> strtoi_errno strtoi(int *restrict out, const char *restrict nptr, int base) { /* * Null string, empty string, leading whitespace? */ if (!nptr || !nptr[0] || isspace(nptr[0])) { return STRTOI_INCONVERTIBLE; } char *end_ptr; const int errno_original = errno; /* We shall restore errno to its original value before returning. */ const long int i = strtol(nptr, &end_ptr, base); errno = 0;
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl errno = 0; /* * Both checks are needed because INT_MAX == LONG_MAX is possible. */ if (i > INT_MAX || (errno == ERANGE && i == LONG_MAX)) { return STRTOI_OVERFLOW; } else if (i < INT_MIN || (errno == ERANGE && i == LONG_MIN)) { return STRTOI_UNDERFLOW; } else if (*end_ptr || nptr == end_ptr) { return STRTOI_INCONVERTIBLE; } *out = (int) i; errno = errno_original; return STRTOI_SUCCESS; } errors.h: #ifndef ERRORS_H #define ERRORS_H #include <stddef.h> #define ARRAY_CARDINALITY(x) (sizeof (x) / sizeof ((x)[0])) /* * Error codes for invalid arguments. */ enum error_codes { E_SUCCESS = 0, E_NULL_ARGV, E_INSUFFICIENT_ARGS, E_INVALID_CHAPTER, E_INVALID_VERSE, E_INVALID_RANGE, E_PARSE_ERROR, E_ENOMEM, E_UNKNOWN, E_CURL_INIT_FAILED, E_CURL_PERFORM_FAILED }; /** * @brief get_err_msg() shall retrieve the error message corresponding to the given error code. * * @param err_code - An integer respresenting the error code. * * @return A pointer to a constant string containing the error message. * If the error code is not recognized, a default "Unknown error code.\n" * message is returned. */ const char *get_err_msg(int err_code); #endif /* ERRORS_H */ errors.c: #include "errors.h" #include <assert.h>
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl #endif /* ERRORS_H */ errors.c: #include "errors.h" #include <assert.h> /* * Array of strings to map enum error types to printable string. */ static const char *const errors[] = { /* *INDENT-OFF* */ [E_NULL_ARGV] = "Error: A NULL argv[0] was passed through an exec system call.\n", [E_INSUFFICIENT_ARGS] = "Usage: verse <chapter> <verse>\n", [E_INVALID_CHAPTER] = "Error: Invalid chapter number.\n", [E_INVALID_VERSE] = "Error: Invalid verse number for the given chapter.\n", [E_INVALID_RANGE] = "Error: Chapter or verse out of valid numeric range.\n", [E_PARSE_ERROR] = "Error: Non-numeric input for chapter or verse.\n", [E_ENOMEM] = "Error: Insufficient memory.\n", [E_UNKNOWN] = "Fatal: An unknown error has arisen.\n", [E_CURL_INIT_FAILED] = "Error: curl_easy_init() failed.\n", [E_CURL_PERFORM_FAILED] = "Error: curl_easy_perform() failed.\n" /* *INDENT-ON* */ }; const char *get_err_msg(int err_code) { static_assert(ARRAY_CARDINALITY(errors) - 1 == E_CURL_PERFORM_FAILED, "The errors array and the enum must be kept in-sync!"); if (err_code >= 0 && err_code < (int) ARRAY_CARDINALITY(errors)) { return errors[err_code]; } return "Unknown error code.\n"; } webutil.h: #ifndef WEB_UTIL_H #define WEB_UTIL_H #include <stddef.h> #include <curl/curl.h> /* * A struct to hold the contents of the downloaded web page. */ struct mem_chunk { char *ptr; size_t len; };
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl /** * @brief Parses a JSON response to extract a specific verse. * * @param json_responose - A JSON response string containing verse data. * @param out - A pointer to a string where the parsed verse will be stored. * * @return An error code indicating the success or failure of the parsing process. * If successful, the parsed verse will be stored in the 'out' parameter. */ int parse_response_json(const char *restrict json_response, char **restrict out); /** * @brief A callback function for curl_easy_perform(). Stores the downloaded * web content to the mem_chunk struct as it arrives. * @param Refer to https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html for a * detailed explanation about the parameters. * @return The number of bytes read, or 0 on a memory allocation failure. */ size_t write_memory_callback(void *content, size_t size, size_t nmemb, struct mem_chunk *chunk); /** * @brief download_webpage() shall download the contents of a web page specified * by the URL using libcurl. * * @param chunk - A struct to hold the downloaded content. * @param curl - A libcurl handle for performing the download. * @param url - The URL of the web page to download. * * @return CURLE_OK on success, or a libcurl error code on failure. */ int download_webpage(const struct mem_chunk *restrict chunk, CURL * restrict curl, const char *restrict url); #endif /* WEB_UTIL_H */ web_util.c: #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 700 #endif #include "web_util.h" #include "errors.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <jansson.h> #define MAX_VERSE_SIZE 4096 int parse_response_json(const char *restrict json_response, char **restrict out) { json_error_t error; json_t *const root = json_loads(json_response, 0, &error);
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl if (root) { /* * Check if "text" exists in the JSON structure. */ const json_t *const data = json_object_get(root, "data"); const json_t *const text = json_object_get(data, "text"); if (data && text && json_is_string(text)) { *out = strdup(json_string_value(text)); } else { json_decref(root); return E_UNKNOWN; } } else { fputs(error.text, stderr); return E_UNKNOWN; } json_decref(root); return E_SUCCESS; } size_t write_memory_callback(void *content, size_t size, size_t nmemb, struct mem_chunk *chunk) { const size_t new_size = chunk->len + size * nmemb; void *const cp = realloc(chunk->ptr, new_size + 1); if (!cp) { perror("realloc()"); return 0; } chunk->ptr = cp; memcpy(chunk->ptr + chunk->len, content, size * nmemb); chunk->ptr[new_size] = '\0'; chunk->len = new_size; return size * nmemb; } int download_webpage(const struct mem_chunk *restrict chunk, CURL * restrict curl, const char *restrict url) { CURLcode ret; /* *INDENT-OFF* */ if ((ret = curl_easy_setopt(curl, CURLOPT_URL, url)) != CURLE_OK || (ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback)) != CURLE_OK || (ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk)) != CURLE_OK || (ret = curl_easy_setopt(curl, CURLOPT_USERAGENT, "Verse/1.0")) != CURLE_OK || (ret = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)) != CURLE_OK || (ret = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L)) != CURLE_OK) { return (int) ret; } /* *INDENT-ON* */ return (int) curl_easy_perform(curl); } main.c: #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #ifdef _XOPEN_SOURCE #undef _XOPEN_SOURCE #endif #define _POSIX_C_SOURCE 200819L #define _XOPEN_SOURCE 700 #include <stdio.h> #include <stdlib.h> #include <string.h>
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl #include <stdio.h> #include <stdlib.h> #include <string.h> #include "strtoi.h" #include "web_util.h" #include "errors.h" #define BASE_URL "http://api.alquran.cloud/v1/ayah/%d:%d/en.maududi" #define MAX_URL_SIZE 128 #define MAX_CHAPTER 114 #define MIN_CHAPTER 0 #define MIN_VERSE 0 #define INIT_MEM_CHUNK(address, size) \ { .ptr = address, .len = size } /* * Each entry in the table is the maximum number of verses present in its * corresponding index, which denotes the chapter number. */ static const int verse_limits[] = { 7, 286, 200, 176, 120, 165, 206, 75, 129, 109, 123, 111, 43, 52, 99, 128, 111, 110, 98, 135, 112, 78, 118, 64, 77, 227, 93, 88, 69, 60, 34, 30, 73, 54, 45, 83, 182, 88, 75, 85, 54, 53, 89, 59, 37, 35, 38, 29, 18, 45, 60, 49, 62, 55, 78, 96, 29, 22, 24, 13, 14, 11, 11, 18, 12, 12, 30, 52, 52, 44, 28, 28, 20, 56, 40, 31, 50, 40, 46, 42, 29, 19, 36, 25, 22, 17, 19, 26, 30, 20, 15, 21, 11, 8, 8, 19, 5, 8, 8, 11, 11, 8, 3, 9, 5, 4, 7, 3, 6, 3, 5, 4, 5, 6 }; static inline int check_args(int argc, const char *const *argv) { /* * Sanity check. POSIX requires the invoking process to pass a non-NULL argv[0]. */ return (!argv[0]) ? E_NULL_ARGV : (argc != 3) ? E_INSUFFICIENT_ARGS : E_SUCCESS; } static int check_input(const char *const *restrict argv, int *restrict chapter, int *restrict verse) { const int ret_1 = strtoi(chapter, argv[1], 10); const int ret_2 = strtoi(verse, argv[2], 10);
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl /* *INDENT-OFF* */ return (ret_1 == STRTOI_INCONVERTIBLE || ret_2 == STRTOI_INCONVERTIBLE) ? E_PARSE_ERROR : (ret_1 == STRTOI_UNDERFLOW || ret_2 == STRTOI_UNDERFLOW || ret_1 == STRTOI_OVERFLOW || ret_2 == STRTOI_OVERFLOW) ? E_INVALID_RANGE : (*chapter <= MIN_CHAPTER || *chapter > MAX_CHAPTER) ? E_INVALID_CHAPTER : (*verse <= MIN_VERSE || *verse > verse_limits [*chapter - 1]) ? E_INVALID_VERSE : E_SUCCESS; /* *INDENT-ON* */ } static int handle_args(int chapter, int verse) { char url[MAX_URL_SIZE]; snprintf(url, sizeof (url), BASE_URL, chapter, verse); struct mem_chunk chunk = INIT_MEM_CHUNK(0, 0); CURL *const curl = curl_easy_init(); if (!curl) { return E_CURL_INIT_FAILED; } int rc = download_webpage(&chunk, curl, url); if (rc != CURLE_OK) { curl_easy_cleanup(curl); free(chunk.ptr); return E_CURL_PERFORM_FAILED; } else { char *result = NULL; rc = parse_response_json(chunk.ptr, &result); if (rc != E_SUCCESS) { curl_easy_cleanup(curl); free(chunk.ptr); return rc; } else { printf("(%d:%d) %s\n", chapter, verse, result); } free(result); } curl_easy_cleanup(curl); curl_global_cleanup(); free(chunk.ptr); return E_SUCCESS; } int main(int argc, char **argv) { const char *const *args = (const char *const *) argv; int status = check_args(argc, args); if (status != E_SUCCESS) { fputs(get_err_msg(status), stderr); return EXIT_FAILURE; } int chapter, verse; status = check_input(args, &chapter, &verse); if (status != E_SUCCESS) { fputs(get_err_msg(status), stderr); return EXIT_FAILURE; }
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl status = handle_args(chapter, verse); if (status != E_SUCCESS) { fputs(get_err_msg(status), stderr); return EXIT_FAILURE; } return EXIT_SUCCESS; } Or you could clone this repository: verse Review Goals: General coding comments, style, etc. Does any part of my code exhibit undefined/implementation-defined behavior? Is there a better way to structure the code? Answer: Just a strtoi() review. Bug: errno setting/restoration woes. errno = 0; should be done before calling strtol(); Below code may set errno due to strtol(), yet the next line is errno = 0; and following tests like errno == ERANGE are always false. // Problem code const int errno_original = errno; const long int i = strtol(nptr, &end_ptr, base); errno = 0; // ???? if (i > INT_MAX || (errno == ERANGE && i == LONG_MAX)) { Instead, sample errno and then restore it. Use sample for later tests. // Sample fix const int errno_original = errno; errno = 0; const long int i = strtol(nptr, &end_ptr, base); int errno_sample = errno; errno = errno_original; if (i > INT_MAX || (errno_sample == ERANGE && i == LONG_MAX)) { Code does not restore errno in select cases Consider moving errno = errno_original; up near strtol() to restore errno along all code paths. Unneeded test // v------v not needed. `strtol()` handles that. // if (!nptr || !nptr[0] || isspace(nptr[0])) { if (!nptr || isspace(nptr[0])) { and re-organize tests } if (*end_ptr || nptr == end_ptr) { return STRTOI_INCONVERTIBLE; } else if (i > INT_MAX || (errno == ERANGE && i == LONG_MAX)) { return STRTOI_OVERFLOW; } else if (i < INT_MIN || (errno == ERANGE && i == LONG_MIN)) { return STRTOI_UNDERFLOW; } White space test potentially out of range is...() functions need an unsigned char value or EOF. When char is signed, code risks UB. // if (!nptr || !nptr[0] || isspace(nptr[0])) { if (!nptr || !nptr[0] || isspace((unsigned char)nptr[0])) {
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl strtoi() differs from strtol() on extremes Consider making strtoi() more strtol() like by setting *nptr in all cases like INT_MIN, INT_MAX, 0 on too low, too high or no convert. strtoi() name strtoi() is a reserved name: Function names that begin with str and a lowercase letter may be added to the declarations in the <stdlib.h> header. C11 7.31.12 1 Consider a new name, maybe str2i()? Consider STRTOI_N Creating STRTOI_N can simplify testing the function result for range. typedef enum { STRTOI_SUCCESS, STRTOI_OVERFLOW, STRTOI_UNDERFLOW, STRTOI_INCONVERTIBLE, STRTOI_N // add } strtoi_errno; Mis-comments @param base - Base to interpret string in. Same range as strtol (2 to 36). should be @param base - Base to interpret string in. Same range as strtol (0 and 2 to 36). - empty string not needed in .h exception list. base out of range? Interesting that strtoi() with its many checks does not test base. C does not specify a base check for strtol(). Unneeded else A style issue. if (i > INT_MAX || (errno == ERANGE && i == LONG_MAX)) { return STRTOI_OVERFLOW; // else not needed here. } else if (i < INT_MIN || (errno == ERANGE && i == LONG_MIN)) { return STRTOI_UNDERFLOW; } Minor: unnecessary #include <*.h> strtoi.c does not need #include <stdio.h>. Even thought this does not apply to strtoi.c, for user.h files, I strongly recommend to only include necessary #include <*.h> files. For user.c files, the issue is less important. I consider #include <*.h> files in a user.c file as not a real issue as there exist a reasonable argument to include some <*.h> to make certain the user.c code does not conflict with the unnecessary #include <*.h>. Further, the maintenance needed to only include a limit set in a user.c file is not that productive. Note: that some IDEs offer an editing option to include the minimum set. Something of a spell checker for #include. This issue is a bit of a software war and best to follow your group's coding standards.
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c, json, curl Candidate replacement (untested): str2i_error str2i(int *restrict out, const char *restrict nptr, int base) { // Maybe test out if (out == NULL) { return STR2I_INCONVERTIBLE; } if (nptr == NULL || isspace((unsigned char) nptr[0])) { *out = 0; return STR2I_INCONVERTIBLE; } if (!(base == 0 || (base >= 2 && base <= 36))) { *out = 0; return STR2I_INCONVERTIBLE; } char *end_ptr; int errno_original = errno; errno = 0; // I used value here rather than i since it is not an int. long value = strtol(nptr, &end_ptr, base); int errno_sample = errno; errno = errno_original; if (*end_ptr || nptr == end_ptr) { *out = 0; return STR2I_INCONVERTIBLE; } if (value > INT_MAX || (errno_sample == ERANGE && value == LONG_MAX)) { *out = INT_MAX; return STR2I_OVERFLOW; } if (value < INT_MIN || (errno_sample == ERANGE && value == LONG_MIN)) { *out = INT_MIN; return STR2I_UNDERFLOW; } *out = (int) value; return STR2I_SUCCESS; } Consider making a str2i() that works just like strtol(), expect for range. Example Then form your str2i_error() which uses str2i(). Easier to extend and make your str2other_error() functions. Advanced Even consider _Generic.
{ "domain": "codereview.stackexchange", "id": 45448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, json, curl", "url": null }
c++, strings, search Title: Fast search for the longest repeating substrings in large text (Rev.4) Question: This is the forth iteration of the Fast search for the longest repeating substrings in large text (Rev.3) code review. Special thanks goes to G. Sliepen who conducted all the reviews. Functional specification Having a large text and already built suffix array find the longest substrings (limited by the number of repetitions) getting benefit from already existing prefix array, if reasonable. Provide the version which would benefit from multithreading keeping the code as simple as possible. Implementation The fully functional demo (https://godbolt.org/z/5q4G4Er1x). Reservation: current implementation utilizes execution policies, so using ranges/projections/views under the question; would work if multi-threading requirement from above met. The further details make sense only as addition to aforementioned third Code Review with answer to it. Answers and comments to the questions on previous revision code review
{ "domain": "codereview.stackexchange", "id": 45449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Using C++ from early 1990th I still can’t get fully accustomed to auto keyword. Thank you for catching this, return types in Index class have mostly been reworked. One concern is replacing size_t with auto for size(). Won’t size_t more readable for the client when they see documentation on source of the header in case the implementation is separated and they see only auto size() instead of size_t size()? Just still in two minds, since Standard C++ Library mostly uses size_t, not auto for return values. On having Index as a class template and other functions not. My idea behind this is that Index (and SubstringOccurences) as well as atomic_fetch_max are good candidates for types shared across all the project, since they are quite common and can be used everywhere with different types. So, I am fine to broke the insulation (physical encapsulation) and give up to some coupling and compilation time increase. At the same time, I don’t expect other functions on my project to work with other types, so I keep them functions to isolate in C++ file. See more in my explanations Rev.3/Generalization. In case I see a second usage with another type, I will rework the to a template. Is it reasonable or there is a good reason to make them generic in advance? I just don’t want to have most of my project in header files. As a second thought, if I separate functionality across many header files and include only when necessary, the difference shouldn’t be huge. Having a second look at the usage of array adjacent_matches in both calculateAdjacents and collectRepeatingSubstrings I understood that I don’t need to clear anything at all, since the only (repetitions-1) elements I don’t use in calculateAdjacents don’t need in the collectRepeatingSubstrings. So, I removed the clearing from the calculateAdjacents and fixed the loop in the collectRepeatingSubstrings, now it runs up to adjacent_matches.size() - (repetitions - 1) element:
{ "domain": "codereview.stackexchange", "id": 45449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search std::vector<SubstringOccurences<>> collectRepeatingSubstrings(const Index<>& index, std::vector<index_t> adjacent_matches, size_t repetitions, size_t max_match_length) { std::vector<SubstringOccurences<>> result; size_t j = 1; for (size_t i = 0; i < adjacent_matches.size() - (repetitions - 1); i += j) { if (adjacent_matches[i] == max_match_length) { result.emplace_back( std::span(index.get_text().begin() + index[i], max_match_length), std::vector(&index[i], &index[i + repetitions]) ); } for (j = 1; i+j < adjacent_matches.size() && max_match_length == findMatchLengthWithOffsetInSuffixArray(index, i, j); ++j) ; } return result; } Thank you for catching this, your pinpoint on adjacent_matches usage helped a lot here not only in terms of this code, but in my view to such write-only operations. I totally agree on all your comments on the Remove responsibilities from findRepeatedSubsequences section, so for the moment I decided to stay with existing code, avoiding unnecessary overcomplication. Despite getting another function, I like your idea to extract isStrongRepetition from calculateAdjacents, it really helps to improve the code structure. Now it looks like this: bool isStrongRepetition(size_t match_length, const Index<>& index, size_t idx, size_t repetitions) { // Not more than min_repetitions times before item if (idx > 0) { size_t prev_match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, -1); if (prev_match_length == match_length) return false; } // Not more than min_repetitions times after (idx+repetitions-1) if (idx + repetitions < index.size()) { size_t next_match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, repetitions); if (next_match_length == match_length) return false; } return true; }
{ "domain": "codereview.stackexchange", "id": 45449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search if (next_match_length == match_length) return false; } return true; } // Returns found sequence(s) length size_t calculateAdjacents(const Index<>& index, std::vector<index_t>& adjacent_matches, size_t repetitions, bool strong_repetition_count) { size_t max_match_length = std::transform_reduce(std::execution::par_unseq, index.begin(), index.end() - (repetitions - 1), size_t(0), [&](size_t max_match_length, size_t match_length) -> size_t { return std::max(max_match_length, match_length); }, [&](const auto& item) -> size_t { size_t idx = &item - index.data(); size_t match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, (repetitions - 1)); if (strong_repetition_count && !isStrongRepetition(match_length, index, idx, repetitions)) { match_length = 0; } adjacent_matches[idx] = (index_t)match_length; return match_length; }); return max_match_length; } Totally agree on your comments on code size. One comment here, in my initial code (before I posted it here for review) the findMatchLength was inlined to findRepeatedSubsequences (see here, but they suggested to extract this function and journey has began). So, the very first version of the code was even shorter. Anyway, I totally agree with your summary here. Other major changes Here is the reworked version of the Index class template: template <typename LexemType=lexem_t, typename IndexType = index_t> class Index { private: const std::vector<LexemType>& text; const std::vector<IndexType>& index; public: Index(const auto& text, const auto& index) : text(text), index(index) {} auto begin() const { return index.begin(); } auto end() const { return index.end(); }
{ "domain": "codereview.stackexchange", "id": 45449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search auto begin() const { return index.begin(); } auto end() const { return index.end(); } size_t size() const { return index.size(); } auto data() const { return index.data(); } const auto& operator[] (size_t idx) const { return index[idx]; } const auto& get_text() const { return text; } }; With the same question on the table, as I had in the previous code review round; it was my homework you gave me on the second round of code review to develop the name for it (and the approach itself). Are you agree with the solution for 'Index` or you had different or better ways to do this? See more reasoning on this class in the Rev.3 / Index class. Answer: Answers to your questions One concern is replacing size_t with auto for size(). Won’t size_t more readable for the client when they see documentation on source of the header in case the implementation is separated and they see only auto size() instead of size_t size()? Just still in two minds, since Standard C++ Library mostly uses size_t, not auto for return values. You have a point, but using an explicit return type for size() but not for any of the other member functions is inconsistent. And, what if you change the type of container for index, and index.size() no longer returns a std::size_t? I see two options: Just use auto. Maybe some IDEs can even deduce the actual type and show it. Also, do you really care about the exact type? The caller can also just use auto to store the result, it doesn't need to know the exact type either. Create type aliases derived from the container type. For example: template <typename LexemType=lexem_t, typename IndexType = index_t> class Index { … const std::vector<IndexType>& index; public: using size_type = decltype(index)::size_type; … size_type size() const { return index.size(); } }; This is what the standard library does for all its containers, container adapters and many other classes.
{ "domain": "codereview.stackexchange", "id": 45449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }