/* Test program for libyaml 0.1.2, ticket #123
**
** Run with "./bug123" to trigger the bug (the reader returns all in one all).
** Run with "./bug123 x" to make it split the data into two reads.
**
** Per-Erik Martin (pem@foxt.com) 2009-04-24
**
*/

#include <stdlib.h>
#include <stdio.h>
#include <yaml.h>

#define START "---\r\n"
#define REST \
    "!!Abcd\r\nefghijkl: mnopqrst\r\nuvwxyzabcd: {efgh: 'ijklmnopq'}\r\n...\r\n"
#define ALL (START REST)
#define START_LEN (sizeof(START)-1)
#define REST_LEN (sizeof(REST)-1)
#define ALL_LEN (sizeof(ALL)-1)

static int
the_reader(void *data, unsigned char *buffer, size_t size,
           size_t *size_read)
{
    static int count = 0;
    int split = *((int *)data);

    if (split)
    {                           /* Split into two reads */
        switch (count++)
        {
        case 0:
            printf("Split call 1 (good)\n");
            strncpy((char *)buffer, START, size);
            *size_read = (START_LEN > size ? size : START_LEN);
            break;
        case 1:
            printf("Split call 2 (good)\n");
            strncpy((char *)buffer, REST, size);
            *size_read = (REST_LEN > size ? size : REST_LEN);
            break;
        default:
            /* Shouldn't happen */
            printf("Split call %d (bad)\n", count);
            return 0;
        }
    }
    else
    {
        if (count++)
        {
            /* Shouldn't happen, but it does */
            printf("No-split call %d (bad)\n", count);
            return 0;
        }
        /* First call returns the entire document */
        printf("No-split call 1 (good)\n");
        strncpy((char *)buffer, ALL, size);
        *size_read = (ALL_LEN > size ? size : ALL_LEN);
    }
    return 1;
}

int
main(int argc, char **argv)
{
    yaml_document_t document;
    yaml_parser_t parser;
    int split = (argc > 1);     /* Any argument will make it split the reads */
        
    if (! yaml_parser_initialize(&parser))
    {
        fprintf(stderr, "yaml_parser_initialize() failed\n");
        exit(1);
    }
    yaml_parser_set_input(&parser, the_reader, &split);
    if (! yaml_parser_load(&parser, &document))
    {
        fprintf(stderr, "yaml_parser_load() failed\n");
        exit(1);
    }
    printf("Got it\n");
    yaml_document_delete(&document);
    yaml_parser_delete(&parser);
    exit(0);
}
