setop-0.1/0000755000175000017500000000000012732746302012100 5ustar storchstorchsetop-0.1/Makefile0000644000175000017500000000134412716324610013536 0ustar storchstorchPROGNAME := setop .PHONY: all, clean CXXFLAGS += -std=c++11 -O3 LIBS += -lboost_program_options -lboost_regex SOURCES = src/main.cpp # where to put executable and manpage on 'make install' BIN ?= $(DESTDIR)/usr/bin HELP ?= $(DESTDIR)/usr/share/man/man1 all: $(PROGNAME) man $(PROGNAME): $(SOURCES) $(CXX) $(CXXFLAGS) $(SOURCES) $(LDFLAGS) $(LIBS) -o $(PROGNAME) clean: @echo "Clean." -rm -f $(PROGNAME) -rm -f $(PROGNAME).1 install: $(PROGNAME) man install -d $(BIN) $(HELP) install $(PROGNAME) $(BIN) install $(PROGNAME).1 $(HELP) man: $(PROGNAME) help2man -n "make set of strings from input" -N -L en_US.UTF-8 ./$(PROGNAME) | gzip > $(PROGNAME).1 # not needed: #documentation: $(SOURCES) doxyconfig # doxygen doxyconfig setop-0.1/TODO0000644000175000017500000000157512702162431012570 0ustar storchstorch==== TODO ==== - move options into description; or: options with hints, after that description - rework output of --help by using another format ================= POSSIBLE FEATURES ================= - query "pairwise disjoint" - option reversed output - string comparison based on local preferences (LC_ALL??) instead of just default - query power set - give out cartesian product of input sets - give out minimum or maximum of output set - new line character not OS specific (std::ifstream::open(..., std::ios::binary)) ============== OPEN QUESTIONS ============== - Set difference: Allow only two inputs? - Should option --ignore-case affect the regular expressions used in --input-separator and --input-element? - How to connect parameters to their corresponding options: --superset=filename, --superset filename; -p=filename, -p filename? - What possible features should be discarded? setop-0.1/README0000644000175000017500000000347312717644135012773 0ustar storchstorchGeneral Information =================== This is the first version of setop. setop is a small console program for parsing input files and streams for string elements and applying several set operations and special queries. setop is written from scratch in C++ with extensive use of the std and the boost library. It is developed under and mainly for Linux, but has no OS specific limitations. Installation ============ setop requires boost >= 1.54, actually libboost-program-options-dev and libboost-regex-dev, and a nearly full C++11 support from the compiler. Simple install procedure: % make [ Become root if necessary ] % make install Otherwise, if you only want to compile, just type: % make setop Or otherwise, if you want to compile “manually”, try something like: % g++ src/main.cpp -o setop -lboost_program_options -lboost_regex -std=c++11 -O3 Usage ===== For information on how to use setop, just type % setop -h or % man setop after installing. Packaging for Debian ==================== You can use the files in the directory debian for creating a deb file by applying the following steps: # at first, download the sources from Github # after that, unpack them and move them into a directory with name setop-0.1 % unzip setop-master.zip % mv setop-master setop-0.1 # gzip sources in Debian convention % tar -zcvf setop_0.1.orig.tar.gz setop-0.1 --exclude setop-0.1/debian # build package % cd setop-0.1 % dpkg-buildpackage -sa -us -uc # or otherwise, if you even want to sign it % dpkg-buildpackage -sa % cd .. # now you can install, distribute, and/or test the package (become root if necessary) % dpkg -i setop_0.1-1_amd64.deb # or if you want, you can upload it to Debian % dput mentors setop_0.1-1_amd64.changes setop-0.1/COPYING0000664000175000017500000004325412732744076013153 0ustar storchstorch GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. setop-0.1/src/0000755000175000017500000000000012732740316012666 5ustar storchstorchsetop-0.1/src/main.cpp0000644000175000017500000006144412732740315014326 0ustar storchstorch/* setop -- apply set operations to several input files and print resulting set to standard output Copyright (C) 2015 Frank Stähr, GPL v2 or later This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You can find a copy of the GNU General Public License at . */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include /** \file \brief Program for parsing input files and streams for string elements and applying several set operations and special queries \details For details how to use the program start it with -h and see help text. \author Frank Stähr \date Oct., 1st, 2015 */ #define PROGRAM_NAME "setop" ///< official name of program #define PROGRAM_VERSION "0.1" ///< version of setop /** \brief used when query has negative result (e. g. element not part of input), but program flow has no (other) error */ #define EXIT_QUERY_NEGATIVE 3 #if ((EXIT_QUERY_NEGATIVE == EXIT_SUCCESS) || (EXIT_QUERY_NEGATIVE == EXIT_FAILURE)) #error Macro EXIT_QUERY_NEGATIVE must not be equal to EXIT_SUCCESS or to EXIT_FAILURE. #endif /** \brief initial size for buffer when input file is read and parsed by regular expression for element search \details effect of this variable is practically unmeasurable, so just take a nice value of form 2^n, at least it should be much bigger than expected size of elements */ #define INITIAL_BUFFERSIZE 4096 /** \brief all possible commutative set operations */ enum class SetConcat : unsigned char { UNION, INTERSECTION, SYM_DIFFERENCE }; /** \brief types of different return possibilities for program */ enum class SetQuery : unsigned char { RETURN_SET, CARDINALITY, ISEMPTY, SUBSET, SUPERSET, CONTAINS_ELEMENT, SET_EQUALITY }; typedef std::string element_t; ///< basic type of element in sets, must base on character type char typedef std::function el_comp_t; ///< type of function for comparing elements /** \brief basic type for sets \details a hash set would be faster, but - even with 1,000,000 elements only about with factor 1.7 or 1.8 (depending on several other influences) - no advantage in memory saving - output is not sorted (at least one more option necessary for letting user to decide if this is acceptable) - much more source code (sorted/unsorted output; overhead for case-insensitive hash function etc.) */ typedef std::set set_t; /** \brief Encapsulates all options for reading and parsing input streams. */ class InputOptions { public: el_comp_t element_comp; ///< comparator for set elements (e. g. case-insensitive comparison) bool include_empty_elements; ///< empty input elements are included instead of ignored boost::regex input_element_regex; ///< regular expression describing an input element (use boost instead of std because match_partial is needed) boost::regex input_separator_regex; ///< regular expression describing an input separator std::string output_separator; ///< string elements shall be separated with in output std::string trim_characters; ///< list of characters that shall be ignored in element at begin and end } input_opts; /** \brief Parses escape sequences like \\n and \\t to “real” characters (e. g. .\\'\\\\\\" gets .'\\") \details Escape sequences \\', \\", \?, \\\\, \\f, \\n, \\r, \\t, \\v are supported. \param escape_seq sequence to unescape \note There should be a std or boost library for a simple task like unescaping, but it seems that there isn’t (yet). Replace this function in the future if possible. \throws std::invalid_argument */ std::string unescape_sequence(std::string const& escape_seq) { std::map const escape_characters = { { '\'', '\'' }, { '\"', '\"' }, { '?', '?' }, { '\\', '\\' }, { 'f', '\f' }, { 'n', '\n' }, { 'r', '\r' }, { 't', '\t' }, { 'v', '\v' } }; std::string result; for (auto curr_char = escape_seq.begin(); curr_char != escape_seq.end(); ++curr_char) { if (*curr_char == '\\') { if (++curr_char == escape_seq.end()) throw std::invalid_argument("Parsing failed: Backslash at end of \"" + escape_seq + "\" is invalid."); auto second_char = escape_characters.find(*curr_char); if (second_char != escape_characters.end()) result.push_back(second_char->second); else throw std::invalid_argument(std::string("Parsing failed: ") + "Escape sequence \"\\" + *curr_char + "\" in argument \"" + escape_seq + "\" is not supported."); } else { result.push_back(*curr_char); } } return result; } /** \brief Returns all elements from file as a set. \param filename name of input file with elements to parse */ set_t file_to_set(std::string const& filename) { set_t result(input_opts.element_comp); // set input stream (can be std::cin) std::ifstream inputfile; if (filename != "-") { inputfile.open(filename); if (!inputfile) throw std::runtime_error("Input file " + filename + " could not be opened."); } std::istream& inputstream = (filename == "-" ? std::cin : inputfile); // lambda for running adjust_element and inserting it right after (according to options) auto adjust_and_insert_element = [&result](element_t el_str, bool check_element_regex = false) { if (!check_element_regex || input_opts.input_element_regex.empty() || boost::regex_match(el_str.begin(), el_str.end(), input_opts.input_element_regex, boost::match_default)) { boost::trim_if(el_str, boost::is_any_of(input_opts.trim_characters)); if (!el_str.empty() || input_opts.include_empty_elements) result.insert(std::move(el_str)); } }; // FIRST METHOD: parse input according to list of delimiter characters // this would be faster, but only about 30 %, and it would assume a check if regex input_separator is convertible to list of possible delimiters /* if (!input_opts.input_separators.empty()) { element_t curr_element; if (input_opts.input_separators == "\n") { while (std::getline(inputstream, curr_element)) { adjust_and_insert_element(std::move(curr_element)); curr_element = ""; } } else { char c; bool word_active = true; while (inputstream.get(c)) { if (input_opts.input_separators.find(c) != std::string::npos) { if (word_active) { adjust_and_insert_element(std::move(curr_element)); curr_element = ""; word_active = false; } } else { word_active = true; curr_element.push_back(c); } } if (word_active) adjust_and_insert_element(std::move(curr_element)); } } */ // SECOND METHOD: parse input according to regular expression describing an element or a separator bool use_separator_regex = input_opts.input_element_regex.empty(); boost::regex const& regex = (use_separator_regex ? input_opts.input_separator_regex : input_opts.input_element_regex); std::size_t buffersize = INITIAL_BUFFERSIZE; std::size_t used_buffer = 0; // use unique pointer instead of "plain" pointer so that there is no memory leak in case of exception std::unique_ptr buffer(new char[buffersize]); do { inputstream.read(buffer.get() + used_buffer, buffersize - used_buffer); char const* const buffer_end = buffer.get() + used_buffer + inputstream.gcount(); char const* buffer_handled_until = buffer.get(); // the whole following thing could be much easier by using a bidirectional input iterator here, but: // do not do this because input "file" could be a named pipe, stream or similar (no backwards iterating would be possible!) // so you have to manage the buffer (and release parts of it) yourself // for a more efficient solution (hopefully in the near future) see boost::cregex_iterator curr_match(buffer.get(), buffer_end, regex, boost::match_default | boost::match_partial); // add element to set when ... while (curr_match != boost::cregex_iterator() && curr_match->begin()->matched && // ... match is a full match and ... (!inputstream || // ... when file is at end or ... // (see next line) when match does not touch end of buffer (otherwise element could be longer, e. g. partial match) !boost::regex_match(curr_match->begin()->first, buffer_end, regex, boost::match_default | boost::match_partial))) { if (use_separator_regex) { adjust_and_insert_element(element_t(buffer_handled_until, curr_match->begin()->first), true); buffer_handled_until = curr_match->begin()->second; } else { adjust_and_insert_element(curr_match->str()); } ++curr_match; } if (!use_separator_regex) // the last match is always a partial match except full match touches buffer end (or buffer is empty) // so mark begin of last match as new begin of buffer when filling it up in next round of do-while-loop buffer_handled_until = (curr_match != boost::cregex_iterator() ? curr_match->begin()->first : buffer_end); used_buffer = buffer_end - buffer_handled_until; if (buffer_handled_until == buffer.get()) { // if current element fills the whole buffer, buffer is too small and thus doubled buffersize *= 2; std::unique_ptr new_buffer(new char[buffersize]); std::memmove(new_buffer.get(), buffer_handled_until, used_buffer); buffer = std::move(new_buffer); } else { // move the rest of new element (buffer_handled_until) to beginning of buffer and mark it as used std::memmove(buffer.get(), buffer_handled_until, used_buffer); } } while (inputstream); if (use_separator_regex && used_buffer > 0) adjust_and_insert_element(element_t(buffer.get(), used_buffer), true); return result; } /** \brief Prints complete error message to console (std::cerr) including hint, that this is an error. \param error_message error message without new line at end \return Exit code EXIT_FAILURE (normally 1) */ inline int print_error(std::string const& error_message) { std::cerr << "Error: " << error_message << "\n"; return EXIT_FAILURE; } /** \brief Main function of program: Take command line options and arguments and execute output. \throws std::runtime_error */ int execute_setop(int argc, char* argv[]) { // needed variables, mainly options and arguments from command line bool quiet, verbose, ignore_case; element_t element_to_check; std::string subset_filename, superset_filename, equal_filename, element_format, separator_format; std::vector input_filenames, setdifference_filenames; // PARSE COMMAND LINE namespace po = boost::program_options; // po::options_description visible_options("Allowed options"); po::options_description visible_options("Options"); visible_options.add_options() ("help", "produce this help message and exit") ("version", "output name and version") ("quiet", po::bool_switch(&quiet)->default_value(false), "suppress all output messages in case of special queries (e. g. when check if element is contained in set)") ("verbose", po::bool_switch(&verbose)->default_value(false), "always use output messages in case of special queries (i. e. also output message on success)") ("ignore-case,C", po::bool_switch(&ignore_case)->default_value(false), "handle input elements case-insensitive") ("include-empty", po::bool_switch(&input_opts.include_empty_elements)->default_value(false), "don’t ignore empty elements (these can come from empty lines, trimming, etc.)") ("input-separator,n", po::value(&separator_format), "describe the form of an input separator as regular expression in ECMAScript syntax; " "default is new line (if --input-element is not given); don’t forget to include the new line character \\n when you set the input separator manually, when desired!") ("input-element,l", po::value(&element_format), "describe the form of input elements as regular expression in ECMAScript syntax") ("output-separator,o", po::value(&input_opts.output_separator)->default_value("\\n"), "string for separating output elements; escape sequences are allowed") ("trim,t", po::value(&input_opts.trim_characters), "trim all given characters at beginning and end of elements (escape sequences allowed)") ("union,u", "unite all given input sets (default)") ("intersection,i", "unite all given input sets") ("symmetric-difference,s", "build symmetric difference for all given input sets") ("difference,d", po::value(&setdifference_filenames)->composing(), "subtract all elements in given file from output set") ("count,#", "just output number of (different) elements, don’t list them") ("is-empty", "check if resulting set is empty") ("contains,c", po::value(&element_to_check), "check if given element is contained in set") ("equal,e", po::value(&equal_filename), "check set equality, i. e. check if output corresponds with content of file") ("subset,b", po::value(&subset_filename), "check if content of file is subset of output set") ("superset,p", po::value(&superset_filename), "check if content of file is superset of output set"); po::options_description invisible_options("Invisible options"); invisible_options.add_options()("inputfile", po::value(&input_filenames)->composing(), ""); po::options_description all_options("All options"); all_options.add(invisible_options).add(visible_options); po::variables_map opt_map; po::positional_options_description arguments; arguments.add("inputfile", -1); try { po::parsed_options parsed = po::command_line_parser(argc, argv).options(all_options).positional(arguments).run(); po::store(parsed, opt_map); po::notify(opt_map); } catch (po::error const& poexc) { return print_error(std::string("Failed to process command line parameters: ") + poexc.what() + "\nTry calling the program with --help."); } if (opt_map.count("help")) { std::cout << "Apply set operations like union, intersection, or set difference to input files " "and print resulting set (sorted and with unique string elements) to standard output or give answer to special queries like number of elements.\n\n" "Usage: " PROGRAM_NAME " [-h] [--quiet | --verbose] [-C] [--include-empty] [-n insepar | -l elregex] [-o outsepar] [-t trimchars] " "[-u|i|s] [inputfilename]* [-d filename]* " "[-# | --is-empty | -c element | -e filename | -b filename | -p filename]\n\n" << visible_options << "No input filename or \"-\" is equal to reading from standard input.\n\n" << "\nThe sequence of events of " PROGRAM_NAME " is as follows:\n" "At first, all input files are parsed and combined according to one of the options -u, -i, or -s. " "After that, all inputs from option -d are parsed and removed from result of first step. " "Finally, the desired output is printed to screen: " "the set itself, or its number of elements, or a comparison to another set (option -e), etc.\n\n" "By default each line of an input stream is considered to be an element, you can change this by defining regular expressions " "within the options --input-separator or --input-element. When using both, the input stream is first split according to the separator " "and after that filtered by the desired input element form. " "After finding the elements they are finally trimmed according to the argument given with --trim.\n" "The option -C lets you treat Word and WORD equal, only the first occurrence of all input streams is considered. " "Note that -C does not affect the regular expressions used in --input-separator and --input-element.\n\n" "When describing strings and characters for the output separator or for the option --trim you can use escape sequences like " R"(\t, \n, \" and \'. )" "But be aware that some of these sequences " R"((especially \\ and \"))" " might be interpreted by your shell before passing the string to " PROGRAM_NAME ". In that case you have to use " R"(\\\\ respectively \\\" just for describing a \ or a ". )" "You can check your shell’s behavior with\n" R"(echo "\\ and \"")" "\n\n" "Special boolean queries (e. g. check if element is contained in set) don’t return anything in case of success except their exit code EXIT_SUCCESS (" << std::to_string(EXIT_SUCCESS) << "). In case the query is unsuccessful (e. g. element not contained in set) the exit code is guaranteed " << "to be unequal to EXIT_SUCCESS and to EXIT_FAILURE (" << std::to_string(EXIT_FAILURE) << "). (Here it is " << std::to_string(EXIT_QUERY_NEGATIVE) << ".) This way, " PROGRAM_NAME " can be used in the shell.\n\n" "Examples:\n" PROGRAM_NAME R"( -c ":fooBAR-:" --trim ":-\t" -C -d B.txt A.txt)" "\n\t" "case-insensitive check if element \"foobar\" is contained in A minus B\n" PROGRAM_NAME R"( A.txt - -i B.txt --input-element "\d+")" "\n\t" "output intersection of console, A, and B, where elements are recognized as strings of digits with at least one character; " "i. e. elements are non-negative integers\n" PROGRAM_NAME " -s A.txt B.txt --input-separator [[:space:]-]" "\n\t" "find all elements contained in A *or* B, not both, where a whitespace" R"( (i. e. \v \t \n \r \f or space) )" "or a minus is interpreted as a separator between elements\n"; return EXIT_SUCCESS; } if (opt_map.count("version")) { std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << std::endl; return EXIT_SUCCESS; } // CHECK PLAUSIBILITY OF INPUT OPTIONS AND ARGUMENTS AND HANDLE THESE OPTIONS if (quiet & verbose) { std::cerr << "Warning: Only one of the options quiet and verbose is allowed. Both ignored.\n"; quiet = verbose = false; } if (opt_map.count("union") + opt_map.count("intersection") + opt_map.count("symmetric-difference") > 1) return print_error("Only one of the set operations union, intersection, and symmetric difference must be used."); SetConcat set_concat_type = opt_map.count("intersection") ? SetConcat::INTERSECTION : opt_map.count("symmetric-difference") ? SetConcat::SYM_DIFFERENCE : SetConcat::UNION; if (opt_map.count("count") + opt_map.count("is-empty") + opt_map.count("subset") + opt_map.count("superset") + opt_map.count("contains") + opt_map.count("equal") > 1) return print_error("Only one of the options count, is-empty, subset, superset, contains, and equal is allowed."); SetQuery set_query_type = opt_map.count("count") ? SetQuery::CARDINALITY : opt_map.count("is-empty") ? SetQuery::ISEMPTY : opt_map.count("subset") ? SetQuery::SUBSET : opt_map.count("superset") ? SetQuery::SUPERSET : opt_map.count("contains") ? SetQuery::CONTAINS_ELEMENT : opt_map.count("equal") ? SetQuery::SET_EQUALITY : SetQuery::RETURN_SET; // parse escape sequences of trim characters and output separator to "real" characters (e. g. ".\'\\" gets ".'\") try { input_opts.trim_characters = unescape_sequence(input_opts.trim_characters); input_opts.output_separator = unescape_sequence(input_opts.output_separator); } catch (std::invalid_argument const& e) { return print_error(e.what()); } // check if regexes are ok // separator "\n" is default when nothing else is given if (element_format.empty() && separator_format.empty()) separator_format = "\\n"; bool error_in_element_regex = true; try { boost::regex::flag_type regex_flags = boost::regex_constants::ECMAScript | boost::regex_constants::optimize /*| (ignore_case ? boost::regex_constants::icase : 0)*/; if (!element_format.empty()) input_opts.input_element_regex = boost::regex(element_format, regex_flags); error_in_element_regex = false; if (!separator_format.empty()) input_opts.input_separator_regex = boost::regex(separator_format, regex_flags); } catch (boost::regex_error) { return print_error("\"" + (error_in_element_regex ? element_format : separator_format) + "\" is not a valid regular expression."); } // handle case-insensitive if (ignore_case) input_opts.element_comp = std::bind( boost::algorithm::ilexicographical_compare, std::placeholders::_1, std::placeholders::_2, std::locale() ); else input_opts.element_comp = boost::algorithm::lexicographical_compare; // use console as input when no file given if (input_filenames.empty()) input_filenames.push_back("-"); // PROCESS CALCULATIONS IN THREE STEPS // STEP 1/3: execute all commutative set operations (union, intersection, symmetric difference) set_t output_set(input_opts.element_comp); for (auto curr_fn_it = input_filenames.cbegin(); curr_fn_it != input_filenames.cend(); ++curr_fn_it) { set_t curr_set = file_to_set(*curr_fn_it); if (curr_fn_it == input_filenames.cbegin()) // if it is the first input stream { output_set = std::move(curr_set); } else { switch (set_concat_type) { case SetConcat::UNION: output_set.insert(curr_set.begin(), curr_set.end()); break; case SetConcat::INTERSECTION: { set_t intersect(input_opts.element_comp); for (element_t const& el : output_set) if (curr_set.find(el) != curr_set.end()) intersect.insert(el); output_set = std::move(intersect); break; } case SetConcat::SYM_DIFFERENCE: for (element_t const& el : curr_set) { set_t::const_iterator it = output_set.find(el); if (it != output_set.end()) output_set.erase(it); else output_set.insert(el); } } } } // STEP 2/3: execute all set differences, that is erase all desired elements from current output set for (std::string const& filename : setdifference_filenames) { set_t curr_diff = file_to_set(filename); for (element_t const& el : curr_diff) output_set.erase(el); } // STEP 3/3: calculate output depending on set query // print success and failure messages from query and return exit code of program auto answer_query = [quiet, verbose](bool success, std::string success_msg, std::string unsuccess_msg) -> int { if (success) { if (verbose) std::cout << success_msg; return EXIT_SUCCESS; } else { if (!quiet) std::cout << unsuccess_msg; return EXIT_QUERY_NEGATIVE; } }; switch (set_query_type) { case SetQuery::RETURN_SET: for (element_t const& el : output_set) std::cout << el << input_opts.output_separator; return EXIT_SUCCESS; case SetQuery::CARDINALITY: std::cout << output_set.size() << "\n"; return EXIT_SUCCESS; case SetQuery::ISEMPTY: return answer_query( output_set.empty(), "Resulting set is empty.\n", "Resulting set is not empty.\n"); case SetQuery::CONTAINS_ELEMENT: boost::trim_if(element_to_check, boost::is_any_of(input_opts.trim_characters)); return answer_query( output_set.find(element_to_check) != output_set.end(), "\"" + element_to_check + "\" is contained in set.\n", "Input does not contain element \"" + element_to_check + "\".\n"); case SetQuery::SET_EQUALITY: return answer_query( file_to_set(equal_filename) == output_set, "Resulting set is equal to input \"" + equal_filename + "\".\n", "Resulting set is not equal to input \"" + equal_filename + "\".\n"); case SetQuery::SUBSET: { set_t set_to_check = file_to_set(subset_filename); return answer_query( std::all_of(set_to_check.begin(), set_to_check.end(), [&output_set](element_t const& str) { return output_set.find(str) != output_set.end(); }), "\"" + subset_filename + "\" is a subset.\n", "\"" + subset_filename + "\" is not a subset.\n"); } case SetQuery::SUPERSET: { set_t set_to_check = file_to_set(superset_filename); return answer_query( std::all_of(output_set.begin(), output_set.end(), [&set_to_check](element_t const& str) { return set_to_check.find(str) != set_to_check.end(); }), "\"" + superset_filename + "\" is a superset.\n", "\"" + superset_filename + "\" is not a superset.\n"); } default: // never happens because all cases are handled above return EXIT_FAILURE; } } /** \brief Executes execute_setop, but handles all possible general exceptions. */ int main(int argc, char* argv[]) { int exit_code; try { exit_code = execute_setop(argc, argv); } // too much complexity or stack overflow in ++regex_iterator // input file could not be read catch (std::runtime_error const& rt_exc) { return print_error(rt_exc.what()); } // no more memory for more elements, or one element is too large because of faulty regular expression catch (std::bad_alloc const&) { return print_error("Not enough memory available. Input data could be too large, or input element or separator regex could be erroneous."); } #ifndef _DEBUG catch (std::exception const& exc) { return print_error(exc.what()); } catch (...) { return print_error("Unknown error occurred."); } #endif return exit_code; }