Created
January 21, 2012 23:25
-
-
Save samcragg/1654499 to your computer and use it in GitHub Desktop.
Simple parser for SVG Polgon points.
This file contains 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
#include <cstdlib> | |
#include <iostream> | |
#include <locale> | |
#include <string> | |
#include <vector> | |
bool is_whitespace(char value) | |
{ | |
// Values are defined in the SVG specification. | |
return (value == '0x9') || | |
(value == '0xD') || | |
(value == '0xA') || | |
(value == '0x20'); | |
} | |
std::size_t skip_comma(const std::string & str, std::size_t start_index) | |
{ | |
while (start_index < str.length()) | |
{ | |
if ((str[start_index] != ',') && !is_whitespace(str[start_index])) | |
{ | |
break; | |
} | |
++start_index; | |
} | |
return start_index; | |
} | |
double get_double(const std::string & str, std::size_t start_index, std::ptrdiff_t & consumed) | |
{ | |
const char * start = str.data() + start_index; | |
char * end = const_cast<char*>(start); | |
double parsed = std::strtod(start, &end); | |
consumed = end - start; | |
return parsed; | |
} | |
std::vector<double> get_points(const std::string & input) | |
{ | |
std::vector<double> output; | |
std::size_t index = 0U; | |
std::ptrdiff_t consumed = 0; | |
while (index < input.length()) | |
{ | |
double value = get_double(input, index, consumed); | |
if (consumed == 0) | |
{ | |
break; | |
} | |
output.push_back(value); | |
index = skip_comma(input, index + consumed); | |
} | |
return output; | |
} | |
// Exmaple usage | |
void display_points(const std::string & input) | |
{ | |
auto points = get_points(input); | |
std::cout << "'" << input << "' - "; | |
for (auto it = points.cbegin(); it != points.cend(); ++it) | |
{ | |
std::cout << *it << " "; | |
} | |
std::cout << "\n"; | |
} | |
int main() | |
{ | |
display_points("0, 0 -10, 0 -5, -10"); | |
display_points("0,0 -10,0 -5,-10"); | |
display_points("0,0,-10,0,-5,-10"); | |
display_points("0 0 -10 0 -5 -10"); | |
display_points("0 0-10 0-5-10"); | |
display_points("0-0-10-0-5-10"); | |
system("PAUSE"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment