<commit_before>#include <MailCore/MailCore.h>
#include <dirent.h>
#include <math.h>
#include <time.h>

using namespace mailcore;

static int global_failure = 0;
static int global_success = 0;

static time_t referenceDate(void)
{
    struct tm aTm;
    memset(&aTm, 0, sizeof(aTm));
    aTm.tm_sec = 0;
    aTm.tm_min = 0;
    aTm.tm_hour = 16;
    aTm.tm_mday = 31;
    aTm.tm_mon = 11;
    aTm.tm_year = 2000 - 1900;
    time_t date = mktime(&aTm);
    return date;
}

static void testMessageBuilder1(String * path)
{
    printf("testMessageBuilder1\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    builder->header()->setTo(Array::arrayWithObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>"))));
    builder->header()->setSubject(MCSTR("testMessageBuilder1"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("This is a HTML content"));
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder1.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder1 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder1 ok\n");
    global_success ++;
}

static void testMessageBuilder2(String * path)
{
    printf("testMessageBuilder2\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    Array * to = Array::array();
    to->addObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>")));
    to->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setTo(to);
    Array * cc = Array::array();
    cc->addObject(Address::addressWithRFC822String(MCSTR("Carbon Copy <dinh.viet.hoa@gmail.com>")));
    cc->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setCc(cc);
    builder->header()->setSubject(MCSTR("testMessageBuilder2"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("This is a HTML content"));
    String * attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo2.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder2.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder2 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder2 ok\n");
    global_success ++;
}

static void testMessageBuilder3(String * path)
{
    printf("testMessageBuilder3\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    Array * to = Array::array();
    to->addObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>")));
    to->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setTo(to);
    Array * cc = Array::array();
    cc->addObject(Address::addressWithRFC822String(MCSTR("Carbon Copy <dinh.viet.hoa@gmail.com>")));
    cc->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setCc(cc);
    builder->header()->setSubject(MCSTR("testMessageBuilder3"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("
This is a HTML content

"));
    String * attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo2.jpg"));
    Attachment * attachment = Attachment::attachmentWithContentsOfFile(attachmentPath);
    attachment->setContentID(MCSTR("123"));
    builder->addRelatedAttachment(attachment);
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder3.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder3 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder3 ok\n");
    global_success ++;
}

static Array * pathsInDirectory(String * directory)
{
    Array * result = Array::array();

    DIR * dir = opendir(directory->fileSystemRepresentation());
    if (dir == NULL) {
        return result;
    }

    struct dirent * ent;
    while ((ent = readdir(dir)) != NULL) {
        if (ent->d_name[0] == '.') {
            continue;
        }

        String * subpath = directory->stringByAppendingPathComponent(String::stringWithFileSystemRepresentation(ent->d_name));
        if (ent->d_type == DT_DIR) {
            result->addObjectsFromArray(pathsInDirectory(subpath));
        }
        else {
            result->addObject(subpath);
        }
    }
    closedir(dir);

    return result;
}

static void prepareHeaderForUnitTest(MessageHeader * header)
{
    time_t now = time(NULL);
    if (fabs(now - header->date()) <= 2) {
        // Date might be generated, set to known date.
        header->setDate(referenceDate());
    }
    if (fabs(header->receivedDate() - now) <= 2) {
        // Date might be generated, set to known date.
        header->setReceivedDate(referenceDate());
    }
    if (header->isMessageIDAutoGenerated()) {
        header->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    }
}

static void preparePartForUnitTest(AbstractPart * part)
{
    if (part->className()->isEqual(MCSTR("mailcore::Multipart"))) {
        Multipart * multipart = (Multipart *) part;
        for(unsigned int i = 0 ; i < multipart->parts()->count() ; i ++) {
            preparePartForUnitTest((AbstractPart *) multipart->parts()->objectAtIndex(i));
        }
    }
    else if (part->className()->isEqual(MCSTR("mailcore::MessagePart"))) {
        prepareHeaderForUnitTest(((MessagePart *) part)->header());
        preparePartForUnitTest(((MessagePart *) part)->mainPart());
    }
}

static void testMessageParser(String * path)
{
    printf("testMessageParser\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        MessageParser * parser = MessageParser::messageParserWithContentsOfFile(filename);
        prepareHeaderForUnitTest(parser->header());
        preparePartForUnitTest(parser->mainPart());
        HashMap * result = parser->serializable();
        String * expectedPath = outputPath->stringByAppendingPathComponent(filename->substringFromIndex(inputPath->length()));
        //fprintf(stderr, "expected: %s\n", MCUTF8(expectedPath));
        HashMap * expectedResult = (HashMap *) JSON::objectFromJSONData(Data::dataWithContentsOfFile(expectedPath));
        if (result->isEqual(expectedResult)) {
            success ++;
        }
        else {
            fprintf(stderr, "testMessageParser: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "expected: %s\n", MCUTF8(expectedResult));
            fprintf(stderr, "got: %s\n", MCUTF8(result));
            failure ++;
        }
    }
    if (failure > 0) {
        printf("testMessageParser ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testMessageParser ok: %i succeeded\n", success);
    global_success ++;
}

static void testCharsetDetection(String * path)
{
    printf("testCharsetDetection\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        Data * data = Data::dataWithContentsOfFile(filename);
        String * charset = data->charsetWithFilteredHTML(false);
        charset = charset->lowercaseString();
        if (!filename->lastPathComponent()->stringByDeletingPathExtension()->isEqual(charset)) {
            failure ++;
            fprintf(stderr, "testCharsetDetection: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "got: %s\n", MCUTF8(charset));
        }
        else {
            success ++;
        }
    }
    if (failure > 0) {
        printf("testCharsetDetection ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testCharsetDetection ok: %i succeeded\n", success);
    global_success ++;
}

static String * tweakDateFromSummary(String * summary) {
    Array * components = summary->componentsSeparatedByString(MCSTR("\n"));
    if (components->count() >= 4) {
        String * line = (String *) components->objectAtIndex(3);
        if (line->hasPrefix(MCSTR("Date:"))) {
            line->replaceOccurrencesOfString(MCSTR(" at "), MCSTR(" "));
        }
    }
    return components->componentsJoinedByString(MCSTR("\n"));
}

static void testSummary(String * path)
{
    printf("testSummary\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        MessageParser * parser = MessageParser::messageParserWithContentsOfFile(filename);
        prepareHeaderForUnitTest(parser->header());
        preparePartForUnitTest(parser->mainPart());
        String * str = parser->plainTextRendering();
        String * resultPath = outputPath->stringByAppendingPathComponent(filename->substringFromIndex(inputPath->length()));
        resultPath = resultPath->stringByDeletingPathExtension()->stringByAppendingString(MCSTR(".txt"));
        Data * resultData = Data::dataWithContentsOfFile(resultPath);
        if (resultData == NULL) {
            fprintf(stderr, "test %s is a well-known failing test", MCUTF8(filename));
            continue;
        }
        String * resultString = resultData->stringWithCharset("utf-8");
        str = tweakDateFromSummary(str);
        resultString = tweakDateFromSummary(resultString);

        if (!resultString->isEqual(str)) {
            failure ++;
            fprintf(stderr, "testSummary: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "got: %s\n", MCUTF8(str));
            fprintf(stderr, "expected: %s\n", MCUTF8(resultData->stringWithCharset("utf-8")));
        }
        else {
            success ++;
        }
    }
    if (failure > 0) {
        printf("testSummary ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testSummary ok: %i succeeded\n", success);
    global_success ++;
}

int main(int argc, char ** argv)
{
    tzset();

    if (argc < 2) {
        fprintf(stderr, "syntax: unittestcpp [unittestdatadir]\n");
        exit(EXIT_FAILURE);
    }

    AutoreleasePool * pool = new AutoreleasePool();

    String * path = String::stringWithUTF8Characters(argv[1]);
    printf("data path: %s\n", MCUTF8(path));

    testMessageBuilder1(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageBuilder2(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageBuilder3(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageParser(path->stringByAppendingPathComponent(MCSTR("parser")));
    testCharsetDetection(path->stringByAppendingPathComponent(MCSTR("charset-detection")));
    testSummary(path->stringByAppendingPathComponent(MCSTR("summary")));

    printf("%i tests succeeded, %i tests failed\n", global_success, global_failure);

    pool->release();

    if (global_failure > 0) {
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}<commit_msg>More tweaks on date<commit_after>#include <MailCore/MailCore.h>
#include <dirent.h>
#include <math.h>
#include <time.h>

using namespace mailcore;

static int global_failure = 0;
static int global_success = 0;

static time_t referenceDate(void)
{
    struct tm aTm;
    memset(&aTm, 0, sizeof(aTm));
    aTm.tm_sec = 0;
    aTm.tm_min = 0;
    aTm.tm_hour = 16;
    aTm.tm_mday = 31;
    aTm.tm_mon = 11;
    aTm.tm_year = 2000 - 1900;
    time_t date = mktime(&aTm);
    return date;
}

static void testMessageBuilder1(String * path)
{
    printf("testMessageBuilder1\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    builder->header()->setTo(Array::arrayWithObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>"))));
    builder->header()->setSubject(MCSTR("testMessageBuilder1"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("This is a HTML content"));
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder1.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder1 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder1 ok\n");
    global_success ++;
}

static void testMessageBuilder2(String * path)
{
    printf("testMessageBuilder2\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    Array * to = Array::array();
    to->addObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>")));
    to->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setTo(to);
    Array * cc = Array::array();
    cc->addObject(Address::addressWithRFC822String(MCSTR("Carbon Copy <dinh.viet.hoa@gmail.com>")));
    cc->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setCc(cc);
    builder->header()->setSubject(MCSTR("testMessageBuilder2"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("This is a HTML content"));
    String * attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo2.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder2.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder2 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder2 ok\n");
    global_success ++;
}

static void testMessageBuilder3(String * path)
{
    printf("testMessageBuilder3\n");
    MessageBuilder * builder = new MessageBuilder();
    builder->header()->setFrom(Address::addressWithRFC822String(MCSTR("Hoà <dinh.viet.hoa@gmail.com>")));
    Array * to = Array::array();
    to->addObject(Address::addressWithRFC822String(MCSTR("Foo Bar <dinh.viet.hoa@gmail.com>")));
    to->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setTo(to);
    Array * cc = Array::array();
    cc->addObject(Address::addressWithRFC822String(MCSTR("Carbon Copy <dinh.viet.hoa@gmail.com>")));
    cc->addObject(Address::addressWithRFC822String(MCSTR("Other Recipient <another-foobar@to-recipient.org>")));
    builder->header()->setCc(cc);
    builder->header()->setSubject(MCSTR("testMessageBuilder3"));
    builder->header()->setDate(referenceDate());
    builder->header()->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    builder->setHTMLBody(MCSTR("
This is a HTML content

"));
    String * attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo.jpg"));
    builder->addAttachment(Attachment::attachmentWithContentsOfFile(attachmentPath));
    attachmentPath = path->stringByAppendingPathComponent(MCSTR("input/photo2.jpg"));
    Attachment * attachment = Attachment::attachmentWithContentsOfFile(attachmentPath);
    attachment->setContentID(MCSTR("123"));
    builder->addRelatedAttachment(attachment);
    Array * boundaries = Array::array();
    boundaries->addObject(MCSTR("1"));
    boundaries->addObject(MCSTR("2"));
    boundaries->addObject(MCSTR("3"));
    boundaries->addObject(MCSTR("4"));
    boundaries->addObject(MCSTR("5"));
    builder->setBoundaries(boundaries);
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output/builder3.eml"));
    Data * expectedData = Data::dataWithContentsOfFile(outputPath);
    if (!builder->data()->isEqual(expectedData)) {
        printf("testMessageBuilder3 failed\n");
        fprintf(stderr, "current:\n%s\n", MCUTF8(builder->data()->stringWithCharset("utf-8")));
        fprintf(stderr, "expected:\n%s\n", MCUTF8(expectedData->stringWithCharset("utf-8")));
        global_failure ++;
        return;
    }
    printf("testMessageBuilder3 ok\n");
    global_success ++;
}

static Array * pathsInDirectory(String * directory)
{
    Array * result = Array::array();

    DIR * dir = opendir(directory->fileSystemRepresentation());
    if (dir == NULL) {
        return result;
    }

    struct dirent * ent;
    while ((ent = readdir(dir)) != NULL) {
        if (ent->d_name[0] == '.') {
            continue;
        }

        String * subpath = directory->stringByAppendingPathComponent(String::stringWithFileSystemRepresentation(ent->d_name));
        if (ent->d_type == DT_DIR) {
            result->addObjectsFromArray(pathsInDirectory(subpath));
        }
        else {
            result->addObject(subpath);
        }
    }
    closedir(dir);

    return result;
}

static void prepareHeaderForUnitTest(MessageHeader * header)
{
    time_t now = time(NULL);
    if (fabs(now - header->date()) <= 2) {
        // Date might be generated, set to known date.
        header->setDate(referenceDate());
    }
    if (fabs(header->receivedDate() - now) <= 2) {
        // Date might be generated, set to known date.
        header->setReceivedDate(referenceDate());
    }
    if (header->isMessageIDAutoGenerated()) {
        header->setMessageID(MCSTR("MyMessageID123@mail.gmail.com"));
    }
}

static void preparePartForUnitTest(AbstractPart * part)
{
    if (part->className()->isEqual(MCSTR("mailcore::Multipart"))) {
        Multipart * multipart = (Multipart *) part;
        for(unsigned int i = 0 ; i < multipart->parts()->count() ; i ++) {
            preparePartForUnitTest((AbstractPart *) multipart->parts()->objectAtIndex(i));
        }
    }
    else if (part->className()->isEqual(MCSTR("mailcore::MessagePart"))) {
        prepareHeaderForUnitTest(((MessagePart *) part)->header());
        preparePartForUnitTest(((MessagePart *) part)->mainPart());
    }
}

static void testMessageParser(String * path)
{
    printf("testMessageParser\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        MessageParser * parser = MessageParser::messageParserWithContentsOfFile(filename);
        prepareHeaderForUnitTest(parser->header());
        preparePartForUnitTest(parser->mainPart());
        HashMap * result = parser->serializable();
        String * expectedPath = outputPath->stringByAppendingPathComponent(filename->substringFromIndex(inputPath->length()));
        //fprintf(stderr, "expected: %s\n", MCUTF8(expectedPath));
        HashMap * expectedResult = (HashMap *) JSON::objectFromJSONData(Data::dataWithContentsOfFile(expectedPath));
        if (result->isEqual(expectedResult)) {
            success ++;
        }
        else {
            fprintf(stderr, "testMessageParser: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "expected: %s\n", MCUTF8(expectedResult));
            fprintf(stderr, "got: %s\n", MCUTF8(result));
            failure ++;
        }
    }
    if (failure > 0) {
        printf("testMessageParser ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testMessageParser ok: %i succeeded\n", success);
    global_success ++;
}

static void testCharsetDetection(String * path)
{
    printf("testCharsetDetection\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        Data * data = Data::dataWithContentsOfFile(filename);
        String * charset = data->charsetWithFilteredHTML(false);
        charset = charset->lowercaseString();
        if (!filename->lastPathComponent()->stringByDeletingPathExtension()->isEqual(charset)) {
            failure ++;
            fprintf(stderr, "testCharsetDetection: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "got: %s\n", MCUTF8(charset));
        }
        else {
            success ++;
        }
    }
    if (failure > 0) {
        printf("testCharsetDetection ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testCharsetDetection ok: %i succeeded\n", success);
    global_success ++;
}

static String * tweakDateFromSummary(String * summary) {
    Array * components = summary->componentsSeparatedByString(MCSTR("\n"));
    mc_foreacharray(String, line, components) {
        if (line->hasPrefix(MCSTR("Date:"))) {
            line->replaceOccurrencesOfString(MCSTR(" at "), MCSTR(" "));
        }
    }
    return components->componentsJoinedByString(MCSTR("\n"));
}

static void testSummary(String * path)
{
    printf("testSummary\n");
    String * inputPath = path->stringByAppendingPathComponent(MCSTR("input"));
    String * outputPath = path->stringByAppendingPathComponent(MCSTR("output"));
    Array * list = pathsInDirectory(inputPath);
    int failure = 0;
    int success = 0;
    mc_foreacharray(String, filename, list) {
        MessageParser * parser = MessageParser::messageParserWithContentsOfFile(filename);
        prepareHeaderForUnitTest(parser->header());
        preparePartForUnitTest(parser->mainPart());
        String * str = parser->plainTextRendering();
        String * resultPath = outputPath->stringByAppendingPathComponent(filename->substringFromIndex(inputPath->length()));
        resultPath = resultPath->stringByDeletingPathExtension()->stringByAppendingString(MCSTR(".txt"));
        Data * resultData = Data::dataWithContentsOfFile(resultPath);
        if (resultData == NULL) {
            fprintf(stderr, "test %s is a well-known failing test", MCUTF8(filename));
            continue;
        }
        String * resultString = resultData->stringWithCharset("utf-8");
        str = tweakDateFromSummary(str);
        resultString = tweakDateFromSummary(resultString);

        if (!resultString->isEqual(str)) {
            failure ++;
            fprintf(stderr, "testSummary: failed for %s\n", MCUTF8(filename));
            fprintf(stderr, "got: %s\n", MCUTF8(str));
            fprintf(stderr, "expected: %s\n", MCUTF8(resultData->stringWithCharset("utf-8")));
        }
        else {
            success ++;
        }
    }
    if (failure > 0) {
        printf("testSummary ok: %i succeeded, %i failed\n", success, failure);
        global_failure ++;
        return;
    }
    printf("testSummary ok: %i succeeded\n", success);
    global_success ++;
}

int main(int argc, char ** argv)
{
    tzset();

    if (argc < 2) {
        fprintf(stderr, "syntax: unittestcpp [unittestdatadir]\n");
        exit(EXIT_FAILURE);
    }

    AutoreleasePool * pool = new AutoreleasePool();

    String * path = String::stringWithUTF8Characters(argv[1]);
    printf("data path: %s\n", MCUTF8(path));

    testMessageBuilder1(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageBuilder2(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageBuilder3(path->stringByAppendingPathComponent(MCSTR("builder")));
    testMessageParser(path->stringByAppendingPathComponent(MCSTR("parser")));
    testCharsetDetection(path->stringByAppendingPathComponent(MCSTR("charset-detection")));
    testSummary(path->stringByAppendingPathComponent(MCSTR("summary")));

    printf("%i tests succeeded, %i tests failed\n", global_success, global_failure);

    pool->release();

    if (global_failure > 0) {
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}<|endoftext|>


<commit_before>// kbusyptr.cpp

#include "kbusyptr.h"
#include <kapp.h>
#include <qcursor.h>
#include <qtimer.h>
#include <assert.h>

//-----------------------------------------------------------------------------
KBusyPtr :: KBusyPtr ()
{
  app = KApplication::getKApplication();

  busyLevel  = 0;
  numCursors = 0;
  frameDelay = 500;
  cursorList = NULL;
  bitmapList = NULL;

  loadCursor("./pics/stopwatch.xbm","./pics/stopwatchMask.xbm");

  //connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
}

//-----------------------------------------------------------------------------
KBusyPtr :: ~KBusyPtr()
{
  if (cursorList) delete[] cursorList;
  if (bitmapList) delete[] bitmapList;
  cursorList = NULL;
  bitmapList = NULL;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: busy (void)
{
  if (busyLevel <= 0)
  {
    currentCursor = 0;
    if (!cursorList)
    {
      app->setOverrideCursor(waitCursor);
    }
    else
    {
      app->setOverrideCursor(cursorList[currentCursor]);
      start(500);
    }
  }
  busyLevel++;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: idle (void)
{
  busyLevel--;
  if (busyLevel < 0) busyLevel = 0;

  if (busyLevel <= 0)
  {
    stop();
    app->restoreOverrideCursor();
  }
}

//-----------------------------------------------------------------------------
void KBusyPtr :: timerEvent (void)
{
  if (busyLevel <= 0) return;

  if (++currentCursor >= numCursors) currentCursor = 0;

  if (cursorList)
    app->setOverrideCursor(cursorList[currentCursor], TRUE);
}

//-----------------------------------------------------------------------------
bool KBusyPtr :: loadBitmap (QBitmap& bm, const QString& filename)
{
  QString f;
  bool rc;

  if (filename[0]=='/' || filename[0]=='.')
  {
    f = filename;
  }
  else
  {
    f = app->kdedir();
    f.detach();
    f += "/share/apps/kmail/pics/";
    f += filename;
  }
  rc = bm.load(f);
  if (!rc) printf ("ERROR: cannot load bitmap %s\n", f.data());
  return rc;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: loadCursor (const char* cursorName,const char* maskName)
{
  int i, ix, iy, numX, numY, x, y;
  QBitmap map, mask;
  QBitmap cmap(16,16), cmask(16,16);

  numCursors = 0;

  if (!loadBitmap(map,cursorName)) return;
  if (!loadBitmap(mask,maskName)) return;

  numX = map.width() >> 4;
  numY = map.height() >> 4;
  numCursors = numX * numY;

  if (bitmapList) delete[] bitmapList;
  bitmapList = new QBitmap[numCursors](16,16);
  if (cursorList) delete[] cursorList;
  cursorList = new QCursor[numCursors];

  for (i=0,iy=0,y=0; iy<numY; iy++, y+=16)
  {
    for (ix=0,x=0; ix<numX; ix++, x+=16, i++)
    {
      bitBlt(&cmap, 0, 0, &map, x, y, 16, 16);
      bitBlt(&cmask, 0, 0, &mask, x, y, 16, 16);
      cursorList[i] = QCursor(cmap, cmask, 8, 8);
    }
  }
}

#include "kbusyptr.moc"
<commit_msg>added qbitmap.h<commit_after>// kbusyptr.cpp

#include "kbusyptr.h"
#include <kapp.h>
#include <qbitmap.h>
#include <qcursor.h>
#include <qtimer.h>
#include <assert.h>

//-----------------------------------------------------------------------------
KBusyPtr :: KBusyPtr ()
{
  app = KApplication::getKApplication();

  busyLevel  = 0;
  numCursors = 0;
  frameDelay = 500;
  cursorList = NULL;
  bitmapList = NULL;

  loadCursor("./pics/stopwatch.xbm","./pics/stopwatchMask.xbm");

  //connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
}

//-----------------------------------------------------------------------------
KBusyPtr :: ~KBusyPtr()
{
  if (cursorList) delete[] cursorList;
  if (bitmapList) delete[] bitmapList;
  cursorList = NULL;
  bitmapList = NULL;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: busy (void)
{
  if (busyLevel <= 0)
  {
    currentCursor = 0;
    if (!cursorList)
    {
      app->setOverrideCursor(waitCursor);
    }
    else
    {
      app->setOverrideCursor(cursorList[currentCursor]);
      start(500);
    }
  }
  busyLevel++;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: idle (void)
{
  busyLevel--;
  if (busyLevel < 0) busyLevel = 0;

  if (busyLevel <= 0)
  {
    stop();
    app->restoreOverrideCursor();
  }
}

//-----------------------------------------------------------------------------
void KBusyPtr :: timerEvent (void)
{
  if (busyLevel <= 0) return;

  if (++currentCursor >= numCursors) currentCursor = 0;

  if (cursorList)
    app->setOverrideCursor(cursorList[currentCursor], TRUE);
}

//-----------------------------------------------------------------------------
bool KBusyPtr :: loadBitmap (QBitmap& bm, const QString& filename)
{
  QString f;
  bool rc;

  if (filename[0]=='/' || filename[0]=='.')
  {
    f = filename;
  }
  else
  {
    f = app->kdedir();
    f.detach();
    f += "/share/apps/kmail/pics/";
    f += filename;
  }
  rc = bm.load(f);
  if (!rc) printf ("ERROR: cannot load bitmap %s\n", f.data());
  return rc;
}

//-----------------------------------------------------------------------------
void KBusyPtr :: loadCursor (const char* cursorName,const char* maskName)
{
  int i, ix, iy, numX, numY, x, y;
  QBitmap map, mask;
  QBitmap cmap(16,16), cmask(16,16);

  numCursors = 0;

  if (!loadBitmap(map,cursorName)) return;
  if (!loadBitmap(mask,maskName)) return;

  numX = map.width() >> 4;
  numY = map.height() >> 4;
  numCursors = numX * numY;

  if (bitmapList) delete[] bitmapList;
  bitmapList = new QBitmap[numCursors](16,16);
  if (cursorList) delete[] cursorList;
  cursorList = new QCursor[numCursors];

  for (i=0,iy=0,y=0; iy<numY; iy++, y+=16)
  {
    for (ix=0,x=0; ix<numX; ix++, x+=16, i++)
    {
      bitBlt(&cmap, 0, 0, &map, x, y, 16, 16);
      bitBlt(&cmask, 0, 0, &mask, x, y, 16, 16);
      cursorList[i] = QCursor(cmap, cmask, 8, 8);
    }
  }
}

#include "kbusyptr.moc"
<|endoftext|>


<commit_before>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "util.h"
#include "utils/hashtable_size.h"

uint64_t hash_mask {0};
unsigned char * hash_occupied {nullptr};
uint64_t * hash_values {nullptr};
unsigned int * hash_data {nullptr};

void hash_zap(const uint64_t hashtablesize)
{
  constexpr int padding {63};  // make sure our final value is >= 64 / 8
  constexpr int convert_to_bytes {8};
  memset(hash_occupied, 0, (hashtablesize + padding) / convert_to_bytes);
}

auto hash_alloc(const uint64_t amplicons) -> uint64_t
{
  constexpr int padding {63};  // make sure our final value is >= 64 / 8
  constexpr int convert_to_bytes {8};

  const uint64_t hashtablesize {compute_hashtable_size(amplicons)};
  hash_mask = hashtablesize - 1;

  hash_occupied =
    static_cast<unsigned char *>(xmalloc((hashtablesize + padding) / convert_to_bytes));

  hash_zap(hashtablesize);

  hash_values =
    static_cast<uint64_t *>(xmalloc(hashtablesize * sizeof(uint64_t)));

  hash_data = static_cast<unsigned int *>
    (xmalloc(hashtablesize * sizeof(unsigned int)));

  return hashtablesize;
}

void hash_free()
{
  xfree(hash_occupied);
  xfree(hash_values);
  xfree(hash_data);
}
<commit_msg>use new and delete rather than malloc and free<commit_after>/*
    SWARM

    Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"
#include "util.h"
#include "utils/hashtable_size.h"

uint64_t hash_mask {0};
unsigned char * hash_occupied {nullptr};
uint64_t * hash_values {nullptr};
unsigned int * hash_data {nullptr};

void hash_zap(const uint64_t hashtablesize)
{
  constexpr int padding {63};  // make sure our final value is >= 64 / 8
  constexpr int convert_to_bytes {8};
  memset(hash_occupied, 0, (hashtablesize + padding) / convert_to_bytes);
}

auto hash_alloc(const uint64_t amplicons) -> uint64_t
{
  constexpr int padding {63};  // make sure our final value is >= 64 / 8
  constexpr int convert_to_bytes {8};

  const uint64_t hashtablesize {compute_hashtable_size(amplicons)};
  hash_mask = hashtablesize - 1;

  hash_occupied = new unsigned char[(hashtablesize + padding) / convert_to_bytes] { };

  hash_zap(hashtablesize);

  hash_values =
    static_cast<uint64_t *>(xmalloc(hashtablesize * sizeof(uint64_t)));

  hash_data = static_cast<unsigned int *>
    (xmalloc(hashtablesize * sizeof(unsigned int)));

  return hashtablesize;
}

void hash_free()
{
  delete [] hash_occupied;
  hash_occupied = nullptr;
  xfree(hash_values);
  xfree(hash_data);
}
<|endoftext|>


<commit_before>#include "VirtualMachine.h"
#include "Machine.h"
#include <unistd.h>

extern "C" TVMMainEntry VMLoadModule(const char *module);
extern "C" void VMUnloadModule(void);
void fileCallback(void* calldata, int result);
void incrementTicks(void*);

volatile unsigned int ticks;

TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[])
{
  ticks = 0;
  TVMMainEntry mainFunc = VMLoadModule(argv[0]);
  MachineInitialize(machinetickms);
  MachineRequestAlarm((tickms*1000), incrementTicks, NULL);
  MachineEnableSignals();
  if (mainFunc)
  {
    mainFunc(argc, argv);
    VMUnloadModule();
    return VM_STATUS_SUCCESS;
  }

  return VM_STATUS_FAILURE;
} //VMStart

TVMStatus VMFileOpen(const char *filename, int flags, int mode, int *filedescriptor)
{
  *filedescriptor = -1; //impossible to have a negative file descriptor
  if (filename == NULL || filedescriptor == NULL)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
  //change thread state to VM_THREAD_STATE_WAITING
  MachineFileOpen(filename, flags, mode, fileCallback, (void*)filedescriptor);
  // void MachineFileOpen(const char *filename, int flags, int mode, TMachineFileCallback callback, void *calldata);
  while(*filedescriptor < 0); //wait until file is actually open
  //change thread state to VM_THREAD_STATE_READY
  return VM_STATUS_SUCCESS;
//  return VM_STATUS_FAILURE;
} // VMFileOpen

TVMStatus VMFileClose(int filedescriptor)
{
  int data = 1;

  // Make thread wait here.
  MachineFileClose(filedescriptor, fileCallback, (void*)data);
  while (data > 0); //wait until data has been altered
  // Change thread state to Stop waiting.

  if ( data < 0 )
  {
    return VM_STATUS_FAILURE;
  }//negative result is a failure

  return VM_STATUS_SUCCESS;
}

TVMStatus VMFileWrite(int filedescriptor, void *data, int *length)
{
  if (!data || !length)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
//  MachineFileWrite(filedescriptor, data, length, , );
  if(write(filedescriptor, data, *length))
  {
    return VM_STATUS_SUCCESS;
  }
  return VM_STATUS_FAILURE;
} // VMFileWrite

TVMStatus VMFileSeek(int filedescriptor, int offset, int whence, int *newoffset)
{
  // void MachineFileSeek(int fd, int offset, int whence, TMachineFileCallback callback, void *calldata);
  int no = -728;

  // Make thread wait
  MachineFileSeek(filedescriptor, offset, whence, fileCallback, (void*)&no);

  while (no == -728);
  if (newoffset)
  {
    no = *newoffset;
  }
  //make thread stop waiting

  return VM_STATUS_SUCCESS;
}//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset)

TVMStatus VMThreadSleep(TVMTick tick)
{
  ticks = 0;
  if (tick == VM_TIMEOUT_IMMEDIATE)
  {
    // the current process yields the remainder of its processing quantum to the next ready process of equal priority.
  }
  else if (tick == VM_TIMEOUT_INFINITE)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
  else
  {
    while (ticks < tick);
    //this should not just be a blind wait loop; should probably pass run time to next thread. Update later.
  } //does nothing while the number of ticks that have passed since entering this function is less than the number to sleep on

  return VM_STATUS_SUCCESS;
}

void fileCallback(void* calldata, int result)
{
//MachineFileOpen callback function
  calldata = (void*)result;
}//void fileOpen(void* calldata, int result)

void incrementTicks(void*)
{
  ticks += 1;
}//helper function for sleeping

<commit_msg>VMFileSeek() and VMFileRead() added. Compiles to run file.so, but hangs forever while opening the file.<commit_after>#include "VirtualMachine.h"
#include "Machine.h"
#include <unistd.h>

extern "C" TVMMainEntry VMLoadModule(const char *module);
extern "C" void VMUnloadModule(void);
void fileCallback(void* calldata, int result);
void incrementTicks(void*);

volatile unsigned int ticks;

TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[])
{
  ticks = 0;
  TVMMainEntry mainFunc = VMLoadModule(argv[0]);
  MachineInitialize(machinetickms);
  MachineRequestAlarm((tickms*1000), incrementTicks, NULL);
  MachineEnableSignals();
  if (mainFunc)
  {
    mainFunc(argc, argv);
    VMUnloadModule();
    return VM_STATUS_SUCCESS;
  }

  return VM_STATUS_FAILURE;
} //VMStart

TVMStatus VMFileOpen(const char *filename, int flags, int mode, int *filedescriptor)
{
  *filedescriptor = -1; //impossible to have a negative file descriptor
  if (filename == NULL || filedescriptor == NULL)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
  //change thread state to VM_THREAD_STATE_WAITING
  MachineFileOpen(filename, flags, mode, fileCallback, (void*)filedescriptor);
  // void MachineFileOpen(const char *filename, int flags, int mode, TMachineFileCallback callback, void *calldata);
  while(*filedescriptor < 0); //wait until file is actually open
  //change thread state to VM_THREAD_STATE_READY
  return VM_STATUS_SUCCESS;
//  return VM_STATUS_FAILURE;
} // VMFileOpen

TVMStatus VMFileClose(int filedescriptor)
{
  int data = 1;

  // Make thread wait here.
  MachineFileClose(filedescriptor, fileCallback, (void*)data);
  while (data > 0); //wait until data has been altered
  // Change thread state to Stop waiting.

  if ( data < 0 )
  {
    return VM_STATUS_FAILURE;
  }//negative result is a failure

  return VM_STATUS_SUCCESS;
}

TVMStatus VMFileWrite(int filedescriptor, void *data, int *length)
{
  if (!data || !length)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
//  MachineFileWrite(filedescriptor, data, length, , );
  if(write(filedescriptor, data, *length))
  {
    return VM_STATUS_SUCCESS;
  }
  return VM_STATUS_FAILURE;
} // VMFileWrite

TVMStatus VMFileSeek(int filedescriptor, int offset, int whence, int *newoffset)
{
  // void MachineFileSeek(int fd, int offset, int whence, TMachineFileCallback callback, void *calldata);
  int no = -728;

  // Make thread wait
  MachineFileSeek(filedescriptor, offset, whence, fileCallback, (void*)&no);

  while (no == -728);
  if (newoffset)
  {
    newoffset = &no;
  }
  //make thread stop waiting

  if (no < 0)
    return VM_STATUS_FAILURE;
  return VM_STATUS_SUCCESS;
}//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset)

TVMStatus VMFileRead(int filedescriptor, void *data, int *length)
{
  // void MachineFileSeek(int fd, int offset, int whence, TMachineFileCallback callback, void *calldata);
  int len = -728;

  if (!data || !length)
    return VM_STATUS_ERROR_INVALID_PARAMETER;

  // Make thread wait
  MachineFileRead(filedescriptor, data, *length, fileCallback, (void*)&len);

  while (len == -728);
  length = &len;
  //make thread stop waiting

  if (len < 0)
    return VM_STATUS_FAILURE;
  return VM_STATUS_SUCCESS;
}//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset)

TVMStatus VMThreadSleep(TVMTick tick)
{
  ticks = 0;
  if (tick == VM_TIMEOUT_IMMEDIATE)
  {
    // the current process yields the remainder of its processing quantum to the next ready process of equal priority.
  }
  else if (tick == VM_TIMEOUT_INFINITE)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
  else
  {
    while (ticks < tick);
    //this should not just be a blind wait loop; should probably pass run time to next thread. Update later.
  } //does nothing while the number of ticks that have passed since entering this function is less than the number to sleep on

  return VM_STATUS_SUCCESS;
}

void fileCallback(void* calldata, int result)
{
//MachineFileOpen callback function
  calldata = (void*)result;
}//void fileOpen(void* calldata, int result)

void incrementTicks(void*)
{
  ticks += 1;
}//helper function for sleeping

<|endoftext|>


<commit_before>#include <stack.h>
//#include <Node.hpp>
#include <catch.hpp>

SCENARIO("Stack init", "[init"){
	bool mark;
	Stack<int> stack;
	if (stack.count()!=0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

/*
SCENARIO("Tree init", "[init]") {
         Tree<int> inttree;
         bool mark=false;
         mark=inttree.input("in.txt");

	 REQUIRE(mark);
}

SCENARIO("doubleTree init", "[init]") {
	Tree<double> dtree;
	bool mark=false;
        mark=dtree.input("indouble.txt");
        REQUIRE(mark);
}
SCENARIO("Insert node","[insert]") {
	Tree<int> inttree;
	bool mark=false;
	mark=inttree.insert_node(125);
	REQUIRE(mark);
}

SCENARIO("Output tree","[output]") {
	Tree<int> inttree;
	bool mark=false;
	inttree.input("in.txt");
	mark=inttree.output(inttree.get_root());
	REQUIRE(mark);
}

SCENARIO("inorder walk","[inorder]") {
	Tree<int> inttree;
	bool mark=false;
	inttree.input("in.txt");
	mark=inttree.inorder_walk(inttree.get_root());
	REQUIRE(mark);
}

SCENARIO("inorder walkd","[inotderd]") {
	Tree<double> dtree;
	bool mark=false;
	dtree.input("indouble.txt");
	mark=dtree.inorder_walk(dtree.get_root());
	REQUIRE(mark);
}

SCENARIO("out<<","[out]") {
	bool mark;
	Tree<int> inttree;
	inttree.input("in.txt");
	TreeNode<int>* n=inttree.get_root();
	mark=true;
	try
	{
		cout<<n;
	}
	catch (Empty_tree & e)
	{
		mark=false;
	}
	REQUIRE(mark);
}

SCENARIO("Exception input","[exceptinput]") {
	bool marker=false;
	Tree<int> inttree;
	try
	{
		inttree.input("aavavasvas.txt");
	}
	catch (File_Not_Open & e)
	{
	    marker=true;
	}
	REQUIRE(marker);
}

SCENARIO("Exception out","[exceptout]") {
        bool marker=false;
	Tree<int> inttree;
	try
	{
	    inttree.output(inttree.get_root());
	}
	catch (Empty_tree & e)
	{
	    marker=true;
	}
	REQUIRE(marker);
}

SCENARIO("Delete root","[delete r ]") {
	 Tree<int> inttree;
	 inttree.input("in.txt");
	 //удаление корня
	 inttree.delete_node(inttree.get_root());
	 REQUIRE(!inttree.search(inttree.get_root(),5));
	 REQUIRE(inttree.search(inttree.get_root(),4));
	 REQUIRE(inttree.search(inttree.get_root(),2));
	 REQUIRE(inttree.search(inttree.get_root(),3));
}

SCENARIO("Delete node","[delete n]") {
	 Tree<int> inttree;
	 inttree.input("in.txt");
	 //удаление узла с левым дочерним узлом
	 TreeNode<int>* node;
	 node=inttree.find_node(inttree.get_root(),4);
	 inttree.delete_node(node);
	 REQUIRE(!inttree.search(inttree.get_root(),4));
	 REQUIRE(inttree.search(inttree.get_root(),5));
	 REQUIRE(inttree.search(inttree.get_root(),2));
	 REQUIRE(inttree.search(inttree.get_root(),3));
}

*/
<commit_msg>Update init.cpp<commit_after>#include <Stack.h>
//#include <Node.hpp>
#include <catch.hpp>

SCENARIO("Stack init", "[init"){
	bool mark;
	Stack<int> stack;
	if (stack.count()!=0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

/*
SCENARIO("Tree init", "[init]") {
         Tree<int> inttree;
         bool mark=false;
         mark=inttree.input("in.txt");

	 REQUIRE(mark);
}

SCENARIO("doubleTree init", "[init]") {
	Tree<double> dtree;
	bool mark=false;
        mark=dtree.input("indouble.txt");
        REQUIRE(mark);
}
SCENARIO("Insert node","[insert]") {
	Tree<int> inttree;
	bool mark=false;
	mark=inttree.insert_node(125);
	REQUIRE(mark);
}

SCENARIO("Output tree","[output]") {
	Tree<int> inttree;
	bool mark=false;
	inttree.input("in.txt");
	mark=inttree.output(inttree.get_root());
	REQUIRE(mark);
}

SCENARIO("inorder walk","[inorder]") {
	Tree<int> inttree;
	bool mark=false;
	inttree.input("in.txt");
	mark=inttree.inorder_walk(inttree.get_root());
	REQUIRE(mark);
}

SCENARIO("inorder walkd","[inotderd]") {
	Tree<double> dtree;
	bool mark=false;
	dtree.input("indouble.txt");
	mark=dtree.inorder_walk(dtree.get_root());
	REQUIRE(mark);
}

SCENARIO("out<<","[out]") {
	bool mark;
	Tree<int> inttree;
	inttree.input("in.txt");
	TreeNode<int>* n=inttree.get_root();
	mark=true;
	try
	{
		cout<<n;
	}
	catch (Empty_tree & e)
	{
		mark=false;
	}
	REQUIRE(mark);
}

SCENARIO("Exception input","[exceptinput]") {
	bool marker=false;
	Tree<int> inttree;
	try
	{
		inttree.input("aavavasvas.txt");
	}
	catch (File_Not_Open & e)
	{
	    marker=true;
	}
	REQUIRE(marker);
}

SCENARIO("Exception out","[exceptout]") {
        bool marker=false;
	Tree<int> inttree;
	try
	{
	    inttree.output(inttree.get_root());
	}
	catch (Empty_tree & e)
	{
	    marker=true;
	}
	REQUIRE(marker);
}

SCENARIO("Delete root","[delete r ]") {
	 Tree<int> inttree;
	 inttree.input("in.txt");
	 //удаление корня
	 inttree.delete_node(inttree.get_root());
	 REQUIRE(!inttree.search(inttree.get_root(),5));
	 REQUIRE(inttree.search(inttree.get_root(),4));
	 REQUIRE(inttree.search(inttree.get_root(),2));
	 REQUIRE(inttree.search(inttree.get_root(),3));
}

SCENARIO("Delete node","[delete n]") {
	 Tree<int> inttree;
	 inttree.input("in.txt");
	 //удаление узла с левым дочерним узлом
	 TreeNode<int>* node;
	 node=inttree.find_node(inttree.get_root(),4);
	 inttree.delete_node(node);
	 REQUIRE(!inttree.search(inttree.get_root(),4));
	 REQUIRE(inttree.search(inttree.get_root(),5));
	 REQUIRE(inttree.search(inttree.get_root(),2));
	 REQUIRE(inttree.search(inttree.get_root(),3));
}

*/
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <unordered_set>

#include "GlobalContext.hpp"
#include "VisitorUtils.hpp"
#include "SemanticalException.hpp"

#include "ast/structure_inheritance.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"

using namespace eddic;

void ast::StructureInheritancePass::apply_program(ast::SourceFile& program, bool){
    auto context = program.context;

    std::unordered_set<std::string> resolved_structures;

    while(true){
        auto start_size = resolved_structures.size();
        std::size_t structures = 0;

        for(auto& block : program.blocks){
            if(auto* ptr = boost::get<ast::struct_definition>(&block)){
                if(ptr->is_template_declaration()){
                    continue;
                }

                ++structures;

                auto type = ptr->struct_type;
                auto struct_type = context->get_struct(type);

                //If already resolved
                if(struct_type->parent_type){
                    resolved_structures.insert(type->mangle());
                    continue;
                }

                //If no parent type, already resolved
                if(!ptr->parent_type){
                    resolved_structures.insert(type->mangle());
                    continue;
                }

                auto parent_type = visit(ast::TypeTransformer(context), *ptr->parent_type);

                if(!context->struct_exists(parent_type)){
                    throw SemanticalException("The parent type is not a valid structure type", ptr->position);
                }

                if(resolved_structures.find(parent_type->mangle()) != resolved_structures.end()){
                    struct_type->parent_type = parent_type;
                    resolved_structures.insert(type->mangle());
                }
            }
        }

        if(resolved_structures.size() == start_size){
            if(resolved_structures.size() != structures){
                throw SemanticalException("Invalid inheritance tree");
            } else {
                break;
            }
        }
    }
}
<commit_msg>Retab<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <unordered_set>

#include "GlobalContext.hpp"
#include "VisitorUtils.hpp"
#include "SemanticalException.hpp"

#include "ast/structure_inheritance.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"

using namespace eddic;

void ast::StructureInheritancePass::apply_program(ast::SourceFile& program, bool){
    auto context = program.context;

    std::unordered_set<std::string> resolved_structures;

    while(true){
        auto start_size = resolved_structures.size();
        std::size_t structures = 0;

        for(auto& block : program.blocks){
            if(auto* ptr = boost::get<ast::struct_definition>(&block)){
                if(ptr->is_template_declaration()){
                    continue;
                }

                ++structures;

                auto type = ptr->struct_type;
                auto struct_type = context->get_struct(type);

                //If already resolved
                if(struct_type->parent_type){
                    resolved_structures.insert(type->mangle());
                    continue;
                }

                //If no parent type, already resolved
                if(!ptr->parent_type){
                    resolved_structures.insert(type->mangle());
                    continue;
                }

                auto parent_type = visit(ast::TypeTransformer(context), *ptr->parent_type);

                if(!context->struct_exists(parent_type)){
                    throw SemanticalException("The parent type is not a valid structure type", ptr->position);
                }

                if(resolved_structures.find(parent_type->mangle()) != resolved_structures.end()){
                    struct_type->parent_type = parent_type;
                    resolved_structures.insert(type->mangle());
                }
            }
        }

        if(resolved_structures.size() == start_size){
            if(resolved_structures.size() != structures){
                throw SemanticalException("Invalid inheritance tree");
            } else {
                break;
            }
        }
    }
}
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_STORAGE_CONTAINER_HPP
#define VIENNAGRID_STORAGE_CONTAINER_HPP

#include <vector>
#include <deque>
#include <list>
#include <set>

#include "viennagrid/meta/utils.hpp"
#include "viennagrid/storage/forwards.hpp"
#include "viennagrid/storage/hook.hpp"

namespace viennagrid
{
    namespace storage
    {
        namespace container
        {

            template<typename container_type>
            void insert(container_type & container, const typename container_type::value_type & value)
            {
                container.push_back(value);
            }

            template<typename type, typename compare, typename allocator>
            void insert(std::set<type, compare, allocator> & container, const typename std::set<type, compare, allocator>::value_type & value)
            {
                container.insert(value);
            }

            template<typename base_iterator, typename hook_tag>
            class hook_iterator_impl {};

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, pointer_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef typename std::iterator_traits<base_iterator>::value_type * value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return & base_iterator::operator*(); }
                const value_type operator* () const { return & base_iterator::operator*(); }
            };

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, iterator_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef base_iterator value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return static_cast<base_iterator>(*this); }
                const value_type operator* () const { return static_cast<base_iterator>(*this); }
            };

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, id_hook_tag> : public base_iterator
            {
            public:

                //typedef smart_id< typename std::iterator_traits<base_iterator>::value_type, base_id_type > id_type;
                //typedef typename viennagrid::storage::result_of::id<typename std::iterator_traits<base_iterator>::value_type, id_tag>::type id_type;
                typedef typename std::iterator_traits<base_iterator>::value_type::id_type id_type;

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef id_type value_type;
                typedef id_type * pointer;
                typedef id_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return base_iterator::operator*().id(); }
                const value_type operator* () const { return base_iterator::operator*().id(); }
            };

            template<typename base_iterator, typename hook_tag>
            class const_hook_iterator_impl {};

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, pointer_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef const typename std::iterator_traits<base_iterator>::value_type * value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return & base_iterator::operator*(); }
                const value_type operator* () const { return & base_iterator::operator*(); }
            };

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, iterator_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef base_iterator value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return static_cast<base_iterator>(*this); }
                const value_type operator* () const { return static_cast<base_iterator>(*this); }
            };

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, id_hook_tag> : public base_iterator
            {
            public:

                //typedef smart_id< typename std::iterator_traits<base_iterator>::value_type, base_id_type > id_type;
                //typedef typename viennagrid::storage::result_of::id<typename std::iterator_traits<base_iterator>::value_type, id_tag>::type id_type;
                typedef typename std::iterator_traits<base_iterator>::value_type::id_type id_type;

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef id_type value_type;
                typedef id_type * pointer;
                typedef id_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return base_iterator::operator*().id(); }
                const value_type operator* () const { return base_iterator::operator*().id(); }
            };

        }

        template<typename base_container__, typename hook_tag>
        class hooked_container_t : public base_container__
        {
        public:
            typedef base_container__ container_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename viennagrid::storage::hook::hook_type<container_type, hook_tag>::type hook_type;
            typedef typename viennagrid::storage::hook::const_hook_type<container_type, hook_tag>::type const_hook_type;

            value_type & dereference_hook( hook_type hook )
            {
                return *hook;
            }

            const value_type & dereference_hook( const_hook_type hook ) const
            {
                return *hook;
            }

//             const value_type & dereference_hook( const_hook_type hook )
//             {
//                 return *hook;
//             }
        };

        template<typename base_container__>
        class hooked_container_t<base_container__, id_hook_tag> : public base_container__
        {
        public:
            typedef base_container__ container_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename viennagrid::storage::hook::hook_type<container_type, id_hook_tag>::type hook_type;
            typedef typename viennagrid::storage::hook::const_hook_type<container_type, id_hook_tag>::type const_hook_type;

            typedef typename value_type::id_type id_type;
            typedef typename value_type::const_id_type const_id_type;

            value_type & dereference_hook( hook_type hook )
            {
                return *std::find_if(
                    container_type::begin(),
                    container_type::end(),
                    viennagrid::storage::id_compare<id_type>(hook)
                );
            }

            const value_type & dereference_hook( hook_type hook ) const
            {
                return *std::find_if(
                    container_type::begin(),
                    container_type::end(),
                    viennagrid::storage::id_compare<id_type>(hook)
                );

            }
        };

        template<typename base_container__, typename hook_tag>
        class container_base_t : public hooked_container_t<base_container__, hook_tag>
        {
        public:

            typedef hooked_container_t<base_container__, hook_tag> hooked_container_type;
            typedef typename hooked_container_type::container_type container_type;

            typedef typename hooked_container_type::value_type value_type;

            typedef typename hooked_container_type::pointer pointer;
            typedef typename hooked_container_type::const_pointer const_pointer;

            typedef typename hooked_container_type::reference reference;
            typedef typename hooked_container_type::const_reference const_reference;

            typedef typename hooked_container_type::iterator iterator;
            typedef typename hooked_container_type::const_iterator const_iterator;

            typedef typename hooked_container_type::hook_type hook_type;
            typedef typename hooked_container_type::const_hook_type const_hook_type;

            typedef std::pair<hook_type, bool> return_type;

            bool is_present( const value_type & element ) const
            {
                return false;
            }

            iterator find( const value_type & element ) const
            {
                return container_type::end();
            }

            return_type insert( const value_type & element )
            {
                container_type::push_back( element );
                return std::make_pair( viennagrid::storage::hook::iterator_to_hook<container_type, hook_tag>::convert(--container_type::end()), true);
            }
        };

        template<typename key, typename compare, typename allocator, typename hook_tag>
        class container_base_t<std::set<key, compare, allocator>, hook_tag> : public hooked_container_t<std::set<key, compare, allocator>, hook_tag>
        {
        public:

            typedef hooked_container_t<std::set<key, compare, allocator>, hook_tag> hooked_container_type;
            typedef typename hooked_container_type::container_type container_type;

            typedef typename hooked_container_type::value_type value_type;

            typedef typename hooked_container_type::pointer pointer;
            typedef typename hooked_container_type::const_pointer const_pointer;

            typedef typename hooked_container_type::reference reference;
            typedef typename hooked_container_type::const_reference const_reference;

            typedef typename hooked_container_type::iterator iterator;
            typedef typename hooked_container_type::const_iterator const_iterator;

            typedef typename hooked_container_type::hook_type hook_type;
            typedef typename hooked_container_type::const_hook_type const_hook_type;

            typedef std::pair<hook_type, bool> return_type;

            bool is_present( const value_type & element ) const
            {
                return container_type::find(element) != container_type::end();
            }

            typename container_type::iterator find( const value_type & element ) const
            {
                return container_type::find(element);
            }

            return_type insert( const value_type & element )
            {
                std::pair<typename container_type::iterator, bool> tmp = container_type::insert( element );
                return std::make_pair( viennagrid::storage::hook::iterator_to_hook<container_type, hook_tag>::convert(tmp.first), tmp.second);
            }
        };

        template<typename base_container__, typename hook_tag__>
        class container_t : public container_base_t<base_container__, hook_tag__>
        {
        public:

            typedef base_container__ base_container;

            typedef hook_tag__ hook_tag;
            typedef typename hook::hook_type<base_container, hook_tag>::type hook_type;
            typedef typename hook::const_hook_type<base_container, hook_tag>::type const_hook_type;
            typedef std::pair<hook_type, bool> insert_return_type;

            typedef typename base_container::value_type value_type;

            typedef container::hook_iterator_impl<typename base_container::iterator, hook_tag> hook_iterator;
            hook_iterator hook_begin() { return hook_iterator(base_container::begin()); }
            hook_iterator hook_end() { return hook_iterator(base_container::end()); }

            typedef container::const_hook_iterator_impl<typename base_container::const_iterator, hook_tag> const_hook_iterator;
            const_hook_iterator hook_begin() const { return const_hook_iterator(base_container::begin()); }
            const_hook_iterator hook_end() const { return const_hook_iterator(base_container::end()); }

            hook_type hook_at(std::size_t pos)
            {
                hook_iterator it = hook_begin();
                std::advance( it, pos );
                return *it;
            }
            const_hook_type hook_at(std::size_t pos) const
            {
                hook_iterator it = hook_begin();
                std::advance( it, pos );
                return *it;
            }

        private:
        };

        namespace result_of
        {
            template<typename value_type, typename container_tag>
            struct container;

            template<typename value_type>
            struct container<value_type, std_vector_tag>
            {
                typedef std::vector<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_deque_tag>
            {
                typedef std::deque<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_list_tag>
            {
                typedef std::list<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_set_tag>
            {
                typedef std::set<value_type> type;
            };

            template<typename value_type, typename container_tag, typename hook_tag>
            struct container<value_type, hooked_container_tag<container_tag, hook_tag> >
            {
                typedef container_t< typename container<value_type, container_tag>::type, hook_tag > type;
            };

        }

    }
}

#endif
<commit_msg>added TODO<commit_after>#ifndef VIENNAGRID_STORAGE_CONTAINER_HPP
#define VIENNAGRID_STORAGE_CONTAINER_HPP

#include <vector>
#include <deque>
#include <list>
#include <set>

#include "viennagrid/meta/utils.hpp"
#include "viennagrid/storage/forwards.hpp"
#include "viennagrid/storage/hook.hpp"

namespace viennagrid
{
    namespace storage
    {
        namespace container
        {

            template<typename container_type>
            void insert(container_type & container, const typename container_type::value_type & value)
            {
                container.push_back(value);
            }

            template<typename type, typename compare, typename allocator>
            void insert(std::set<type, compare, allocator> & container, const typename std::set<type, compare, allocator>::value_type & value)
            {
                container.insert(value);
            }

            template<typename base_iterator, typename hook_tag>
            class hook_iterator_impl {};

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, pointer_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef typename std::iterator_traits<base_iterator>::value_type * value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return & base_iterator::operator*(); }
                const value_type operator* () const { return & base_iterator::operator*(); }
            };

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, iterator_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef base_iterator value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return static_cast<base_iterator>(*this); }
                const value_type operator* () const { return static_cast<base_iterator>(*this); }
            };

            template<typename base_iterator>
            class hook_iterator_impl<base_iterator, id_hook_tag> : public base_iterator
            {
            public:

                //typedef smart_id< typename std::iterator_traits<base_iterator>::value_type, base_id_type > id_type;
                //typedef typename viennagrid::storage::result_of::id<typename std::iterator_traits<base_iterator>::value_type, id_tag>::type id_type;
                typedef typename std::iterator_traits<base_iterator>::value_type::id_type id_type;

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef id_type value_type;
                typedef id_type * pointer;
                typedef id_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return base_iterator::operator*().id(); }
                const value_type operator* () const { return base_iterator::operator*().id(); }
            };

            template<typename base_iterator, typename hook_tag>
            class const_hook_iterator_impl {};

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, pointer_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef const typename std::iterator_traits<base_iterator>::value_type * value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return & base_iterator::operator*(); }
                const value_type operator* () const { return & base_iterator::operator*(); }
            };

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, iterator_hook_tag> : public base_iterator
            {
            public:

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef base_iterator value_type;
                typedef value_type * pointer;
                typedef value_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return static_cast<base_iterator>(*this); }
                const value_type operator* () const { return static_cast<base_iterator>(*this); }
            };

            template<typename base_iterator>
            class const_hook_iterator_impl<base_iterator, id_hook_tag> : public base_iterator
            {
            public:

                //typedef smart_id< typename std::iterator_traits<base_iterator>::value_type, base_id_type > id_type;
                //typedef typename viennagrid::storage::result_of::id<typename std::iterator_traits<base_iterator>::value_type, id_tag>::type id_type;
                typedef typename std::iterator_traits<base_iterator>::value_type::id_type id_type;

                typedef typename std::iterator_traits<base_iterator>::difference_type difference_type;
                typedef id_type value_type;
                typedef id_type * pointer;
                typedef id_type & reference;
                typedef typename std::iterator_traits<base_iterator>::iterator_category iterator_category;

                const_hook_iterator_impl(base_iterator it) : base_iterator(it) {}

                value_type operator* () { return base_iterator::operator*().id(); }
                const value_type operator* () const { return base_iterator::operator*().id(); }
            };

        }

        template<typename base_container__, typename hook_tag>
        class hooked_container_t : public base_container__
        {
        public:
            typedef base_container__ container_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename viennagrid::storage::hook::hook_type<container_type, hook_tag>::type hook_type;
            typedef typename viennagrid::storage::hook::const_hook_type<container_type, hook_tag>::type const_hook_type;

            value_type & dereference_hook( hook_type hook )
            {
                return *hook;
            }

            const value_type & dereference_hook( const_hook_type hook ) const
            {
                return *hook;
            }

//             const value_type & dereference_hook( const_hook_type hook )
//             {
//                 return *hook;
//             }
        };

        template<typename base_container__>
        class hooked_container_t<base_container__, id_hook_tag> : public base_container__
        {
        public:
            typedef base_container__ container_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename viennagrid::storage::hook::hook_type<container_type, id_hook_tag>::type hook_type;
            typedef typename viennagrid::storage::hook::const_hook_type<container_type, id_hook_tag>::type const_hook_type;

            typedef typename value_type::id_type id_type;
            typedef typename value_type::const_id_type const_id_type;

            value_type & dereference_hook( hook_type hook )
            {
                // TODO: what happens if hook is not found ??
                return *std::find_if(
                    container_type::begin(),
                    container_type::end(),
                    viennagrid::storage::id_compare<id_type>(hook)
                );
            }

            const value_type & dereference_hook( hook_type hook ) const
            {
                // TODO: what happens if hook is not found ??
                return *std::find_if(
                    container_type::begin(),
                    container_type::end(),
                    viennagrid::storage::id_compare<id_type>(hook)
                );

            }
        };

        template<typename base_container__, typename hook_tag>
        class container_base_t : public hooked_container_t<base_container__, hook_tag>
        {
        public:

            typedef hooked_container_t<base_container__, hook_tag> hooked_container_type;
            typedef typename hooked_container_type::container_type container_type;

            typedef typename hooked_container_type::value_type value_type;

            typedef typename hooked_container_type::pointer pointer;
            typedef typename hooked_container_type::const_pointer const_pointer;

            typedef typename hooked_container_type::reference reference;
            typedef typename hooked_container_type::const_reference const_reference;

            typedef typename hooked_container_type::iterator iterator;
            typedef typename hooked_container_type::const_iterator const_iterator;

            typedef typename hooked_container_type::hook_type hook_type;
            typedef typename hooked_container_type::const_hook_type const_hook_type;

            typedef std::pair<hook_type, bool> return_type;

            bool is_present( const value_type & element ) const
            {
                return false;
            }

            iterator find( const value_type & element ) const
            {
                return container_type::end();
            }

            return_type insert( const value_type & element )
            {
                container_type::push_back( element );
                return std::make_pair( viennagrid::storage::hook::iterator_to_hook<container_type, hook_tag>::convert(--container_type::end()), true);
            }
        };

        template<typename key, typename compare, typename allocator, typename hook_tag>
        class container_base_t<std::set<key, compare, allocator>, hook_tag> : public hooked_container_t<std::set<key, compare, allocator>, hook_tag>
        {
        public:

            typedef hooked_container_t<std::set<key, compare, allocator>, hook_tag> hooked_container_type;
            typedef typename hooked_container_type::container_type container_type;

            typedef typename hooked_container_type::value_type value_type;

            typedef typename hooked_container_type::pointer pointer;
            typedef typename hooked_container_type::const_pointer const_pointer;

            typedef typename hooked_container_type::reference reference;
            typedef typename hooked_container_type::const_reference const_reference;

            typedef typename hooked_container_type::iterator iterator;
            typedef typename hooked_container_type::const_iterator const_iterator;

            typedef typename hooked_container_type::hook_type hook_type;
            typedef typename hooked_container_type::const_hook_type const_hook_type;

            typedef std::pair<hook_type, bool> return_type;

            bool is_present( const value_type & element ) const
            {
                return container_type::find(element) != container_type::end();
            }

            typename container_type::iterator find( const value_type & element ) const
            {
                return container_type::find(element);
            }

            return_type insert( const value_type & element )
            {
                std::pair<typename container_type::iterator, bool> tmp = container_type::insert( element );
                return std::make_pair( viennagrid::storage::hook::iterator_to_hook<container_type, hook_tag>::convert(tmp.first), tmp.second);
            }
        };

        template<typename base_container__, typename hook_tag__>
        class container_t : public container_base_t<base_container__, hook_tag__>
        {
        public:

            typedef base_container__ base_container;

            typedef hook_tag__ hook_tag;
            typedef typename hook::hook_type<base_container, hook_tag>::type hook_type;
            typedef typename hook::const_hook_type<base_container, hook_tag>::type const_hook_type;
            typedef std::pair<hook_type, bool> insert_return_type;

            typedef typename base_container::value_type value_type;

            typedef container::hook_iterator_impl<typename base_container::iterator, hook_tag> hook_iterator;
            hook_iterator hook_begin() { return hook_iterator(base_container::begin()); }
            hook_iterator hook_end() { return hook_iterator(base_container::end()); }

            typedef container::const_hook_iterator_impl<typename base_container::const_iterator, hook_tag> const_hook_iterator;
            const_hook_iterator hook_begin() const { return const_hook_iterator(base_container::begin()); }
            const_hook_iterator hook_end() const { return const_hook_iterator(base_container::end()); }

            hook_type hook_at(std::size_t pos)
            {
                hook_iterator it = hook_begin();
                std::advance( it, pos );
                return *it;
            }
            const_hook_type hook_at(std::size_t pos) const
            {
                hook_iterator it = hook_begin();
                std::advance( it, pos );
                return *it;
            }

        private:
        };

        namespace result_of
        {
            template<typename value_type, typename container_tag>
            struct container;

            template<typename value_type>
            struct container<value_type, std_vector_tag>
            {
                typedef std::vector<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_deque_tag>
            {
                typedef std::deque<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_list_tag>
            {
                typedef std::list<value_type> type;
            };

            template<typename value_type>
            struct container<value_type, std_set_tag>
            {
                typedef std::set<value_type> type;
            };

            template<typename value_type, typename container_tag, typename hook_tag>
            struct container<value_type, hooked_container_tag<container_tag, hook_tag> >
            {
                typedef container_t< typename container<value_type, container_tag>::type, hook_tag > type;
            };

        }

    }
}

#endif
<|endoftext|>


<commit_before>#include <stack.cpp>
#include <catch.hpp>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("top", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}
SCENARIO("copy", "[copy]"){
  stack<int> s;
  s.push(1);
  stack <int> a = s;
  REQUIRE(a.count()==1);
  REQUIRE(a.top()==1);
}
SCENARIO("test", "[test]"){
  stack<int> s;
  REQUIRE(s.count()==0);
}
<commit_msg>Update init.cpp<commit_after>#include <stack.cpp>
#include <catch.hpp>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("top", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}
SCENARIO("copy", "[copy]"){
  stack<int> s;
  s.push(1);
  stack <int> a = s;
  REQUIRE(a.count()==1);
  REQUIRE(a.top()==1);
}
SCENARIO("test", "[test]"){
  stack<int> s;
  REQUIRE(s.count()==0);
}
SCENARIO("empty", "[empty]"){
  stack<int> s;
  REQUIRE(s.empty()==true);
}

<|endoftext|>


<commit_before>// Intended usage:
// KWD_ARG_SET(Args) {
//   KWD_ARG(Args, string, foo);
//   KWD_ARG(Args, int, bar);
//   ...
// };
//
// ... and later ...
//
// something(Args().foo("hey").bar(3));

#define KWD_ARG_SET(set_name) class set_name

#define KWD_ARG(set_name, type, name) \
private: \
  type name##_; \
public: \
  set_name& name(type name##__) { \
    name##_ = name##__; \
    return *this; \
  } \
  type name() { return name##_; } \
private:
<commit_msg>tweaking this comment<commit_after>// Example usage:
// KWD_ARG_SET(Args) {
//   KWD_ARG(Args, string, foo);
//   KWD_ARG(Args, int, bar);
//   ...
// };
//
// ... and later ...
//
// something(Args().foo("hey").bar(3));

#define KWD_ARG_SET(set_name) class set_name

#define KWD_ARG(set_name, type, name) \
private: \
  type name##_; \
public: \
  set_name& name(type name##__) { \
    name##_ = name##__; \
    return *this; \
  } \
  type name() { return name##_; } \
private:
<|endoftext|>