/******************************************************************** created: 2008/06/24 created: 24:6:2008 16:43 filename: d:\Projects\ServiceSpace\ServiceSpace\ServiceSpaceLib\parse.h file path: d:\Projects\ServiceSpace\ServiceSpace\ServiceSpaceLib file base: parse file ext: h author: purpose: 暂只支持窄字符 *********************************************************************/ #ifndef __UTILIB_PARSE_H__ #define __UTILIB_PARSE_H__ #include #include #include namespace utilib { inline bool __is_space(int c) { if (c < 0 || c > 255) c = 255; return 0 != isspace(c); } inline bool _is_key_elem(int c) { return isalpha(c) || isdigit(c)|| '-' == c || '_' == c; } inline void _skip_space(const char * &str) { while(__is_space(*str)) ++str; } inline void _to_key_end(const char * &str, const char * _end) { while(_is_key_elem(*str) && str < _end) ++str; } inline void _to_value_end(const char * &str, const char * _end, bool has_quot) { if (has_quot) { while(str < _end && *str != '\"') ++str; } else { while(str < _end && !__is_space(*str)) ++str; } } template int parse_kv(std::map<_string, _string> & c, const typename _string::value_type * str, int size) { const typename _string::value_type * _end = str + size; while(str < _end) { _skip_space(str); if (str >= _end) break; const char * key_beg = str; _to_key_end(str, _end); if (str >= _end) return -1; _string key(key_beg, str - key_beg); _skip_space(str); if (str >= _end) return -1; if (*str++ != '=') return -1; _skip_space(str); if (str >= _end) return -1; bool has_quot = false; if (*str == '\"') { ++str; if (str >= _end) return -1; has_quot = true; } const char * value_beg = str; _to_value_end(str, _end, has_quot); if (str > _end) return -1; _string value(value_beg, str - value_beg); c.insert(std::make_pair<_string, _string>(key, value)); if (has_quot) { if (*str != '\"') return -1; ++str; } if (str >= _end) return 0; if (*str == ';' || *str == ',' || isspace(*str)) ++str; else return -1; } return 0; } } #endif