preprocess.hpp (2579B)
1 #ifndef _C4_YML_PREPROCESS_HPP_ 2 #define _C4_YML_PREPROCESS_HPP_ 3 4 /** @file preprocess.hpp Functions for preprocessing YAML prior to parsing. */ 5 6 /** @defgroup Preprocessors Preprocessor functions 7 * 8 * These are the existing preprocessors: 9 * 10 * @code{.cpp} 11 * size_t preprocess_json(csubstr json, substr buf) 12 * size_t preprocess_rxmap(csubstr json, substr buf) 13 * @endcode 14 */ 15 16 #ifndef _C4_YML_COMMON_HPP_ 17 #include "./common.hpp" 18 #endif 19 #include <c4/substr.hpp> 20 21 22 namespace c4 { 23 namespace yml { 24 25 namespace detail { 26 using Preprocessor = size_t(csubstr, substr); 27 template<Preprocessor PP, class CharContainer> 28 substr preprocess_into_container(csubstr input, CharContainer *out) 29 { 30 // try to write once. the preprocessor will stop writing at the end of 31 // the container, but will process all the input to determine the 32 // required container size. 33 size_t sz = PP(input, to_substr(*out)); 34 // if the container size is not enough, resize, and run again in the 35 // resized container 36 if(sz > out->size()) 37 { 38 out->resize(sz); 39 sz = PP(input, to_substr(*out)); 40 } 41 return to_substr(*out).first(sz); 42 } 43 } // namespace detail 44 45 46 //----------------------------------------------------------------------------- 47 48 /** @name preprocess_rxmap 49 * Convert flow-type relaxed maps (with implicit bools) into strict YAML 50 * flow map. 51 * 52 * @code{.yaml} 53 * {a, b, c, d: [e, f], g: {a, b}} 54 * # is converted into this: 55 * {a: 1, b: 1, c: 1, d: [e, f], g: {a, b}} 56 * @endcode 57 58 * @note this is NOT recursive - conversion happens only in the top-level map 59 * @param rxmap A relaxed map 60 * @param buf output buffer 61 * @param out output container 62 */ 63 64 //@{ 65 66 /** Write into a given output buffer. This function is safe to call with 67 * empty or small buffers; it won't write beyond the end of the buffer. 68 * 69 * @return the number of characters required for output 70 */ 71 RYML_EXPORT size_t preprocess_rxmap(csubstr rxmap, substr buf); 72 73 74 /** Write into an existing container. It is resized to contained the output. 75 * @return a substr of the container 76 * @overload preprocess_rxmap */ 77 template<class CharContainer> 78 substr preprocess_rxmap(csubstr rxmap, CharContainer *out) 79 { 80 return detail::preprocess_into_container<preprocess_rxmap>(rxmap, out); 81 } 82 83 84 /** Create a container with the result. 85 * @overload preprocess_rxmap */ 86 template<class CharContainer> 87 CharContainer preprocess_rxmap(csubstr rxmap) 88 { 89 CharContainer out; 90 preprocess_rxmap(rxmap, &out); 91 return out; 92 } 93 94 //@} 95 96 } // namespace yml 97 } // namespace c4 98 99 #endif /* _C4_YML_PREPROCESS_HPP_ */