Created
October 23, 2018 16:24
-
-
Save arrieta/db02e8e5e20cab3558cc645f77cf5090 to your computer and use it in GitHub Desktop.
Experiments with std::string_view, argument dispatching, and stuff like that.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Experiments with string view, dispatching, and stuff like that. | |
/// J. Arrieta | |
#include <algorithm> | |
#include <iomanip> | |
#include <iostream> | |
#include <locale> | |
#include <string> | |
// POSIX only | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
// An example of what NOT to do. Globals automatically render the program thread | |
// unsafe. | |
static std::size_t gNUMBER_WIDTH{12}; | |
static std::size_t gTOTAL_SIZE{0}; | |
static std::size_t gMAX_WIDTH{0}; | |
auto size(std::string_view path) { | |
struct stat stat_buffer; | |
// An example of what NOT to do with string_view. string_view::data() will not | |
// necessarily return a pointer to a null-terminated string, so this is | |
// begging for a buffer overflow attack. | |
::stat(path.data(), &stat_buffer); | |
return stat_buffer.st_size; | |
} | |
auto show_size(std::string_view path) { | |
auto s = size(path); | |
gMAX_WIDTH = std::max(path.size(), gMAX_WIDTH); | |
gTOTAL_SIZE += s; | |
std::cout << std::setw(gNUMBER_WIDTH) << s << " " << path << "\n"; | |
} | |
int main(int argc, char* argv[]) { | |
std::cout.imbue(std::locale("")); // add comma separator to numeric output | |
// Elegant dispatching. Notice that the result of std::for_each is the | |
// function itself. In this case I choose to pass the actual program name | |
// (which is stupid). A cool use I can think of right of the bat is having the | |
// function be a state machine, and the last call is the termination trigger. | |
std::for_each(argv + 1, argv + argc, show_size)(argv[0]); | |
// Just some stupid stuff. | |
auto h = std::string(gNUMBER_WIDTH, '-') + " " + std::string(gMAX_WIDTH, '-'); | |
std::cout << h << "\n" | |
<< std::setw(gNUMBER_WIDTH) << gTOTAL_SIZE << " " | |
<< "Total bytes\n" | |
<< h << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment