| | 105 | |
| | 106 | == API == |
| | 107 | |
| | 108 | Note: the API may change drastically. You may also check the header file: |
| | 109 | http://pyyaml.org/browser/libyaml/trunk/include/yaml.h. |
| | 110 | |
| | 111 | === Parser API Synopsis === |
| | 112 | |
| | 113 | {{{ |
| | 114 | #!c |
| | 115 | #include <yaml.h> |
| | 116 | |
| | 117 | yaml_parser_t *parser; |
| | 118 | yaml_event_t *event; |
| | 119 | |
| | 120 | /* Create the Parser object. */ |
| | 121 | parser = yaml_parser_new(); |
| | 122 | |
| | 123 | /* Set a string input. */ |
| | 124 | char *input = "..."; |
| | 125 | size_t length = strlen(input); |
| | 126 | |
| | 127 | yaml_parser_set_string_input(parser, input, length); |
| | 128 | |
| | 129 | /* Set a file input. */ |
| | 130 | FILE *input = fopen("...", "rb"); |
| | 131 | |
| | 132 | yaml_parser_set_file_input(parser, input); |
| | 133 | |
| | 134 | /* Set a generic reader. */ |
| | 135 | void *ext = ...; |
| | 136 | int read_handler(void *ext, char *buffer, int size, int *length) { |
| | 137 | /* ... */ |
| | 138 | *buffer = ...; |
| | 139 | *length = ...; |
| | 140 | /* ... */ |
| | 141 | return error ? 0 : 1; |
| | 142 | } |
| | 143 | |
| | 144 | yaml_parser_set_input(parser, read_handler, ext); |
| | 145 | |
| | 146 | /* Read the event sequence. */ |
| | 147 | do { |
| | 148 | /* Get the next event. */ |
| | 149 | event = yaml_parser_get_event(parser); |
| | 150 | |
| | 151 | if (!event) goto error; |
| | 152 | |
| | 153 | /* |
| | 154 | ... |
| | 155 | Process the event. |
| | 156 | ... |
| | 157 | */ |
| | 158 | |
| | 159 | /* The application is responsible for destroing the event object. */ |
| | 160 | yaml_event_delete(event); |
| | 161 | |
| | 162 | } while(event->type != YAML_STREAM_END_EVENT); |
| | 163 | |
| | 164 | /* Destroy the Parser object. */ |
| | 165 | yaml_parser_delete(parser); |
| | 166 | |
| | 167 | /* On error. */ |
| | 168 | error: |
| | 169 | |
| | 170 | /* Error type: YAML_READER_ERROR, YAML_SCANNER_ERROR, YAML_PARSER_ERROR. */ |
| | 171 | yaml_error_t error; |
| | 172 | |
| | 173 | /* What parser was doing when the problem occured (may be NULL). */ |
| | 174 | char *context; |
| | 175 | |
| | 176 | /* The starting position of the context (valid only if context != NULL). */ |
| | 177 | yaml_mark_t context_mark; |
| | 178 | |
| | 179 | /* The problem description. */ |
| | 180 | char *problem; |
| | 181 | |
| | 182 | /* The exact position of the problematic place in the stream. */ |
| | 183 | yaml_mark_t problem_mark; |
| | 184 | |
| | 185 | /* Get the error data. */ |
| | 186 | yaml_parser_get_error(&error, &context, &context_mark, &problem, &problem_mark); |
| | 187 | |
| | 188 | /* |
| | 189 | ... |
| | 190 | Report the problem to the user. |
| | 191 | ... |
| | 192 | */ |
| | 193 | |
| | 194 | /* Destroy the Parser object. */ |
| | 195 | yaml_parser_delete(parser); |
| | 196 | }}} |