<commit_before>#include "zip.h"

#include <algorithm>    // std::search
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

#include "../lib/miniz/miniz.h"

#include "../leanify.h"

const unsigned char Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };

size_t Zip::Leanify(size_t size_leanified /*= 0*/)
{
    depth++;
    char *p_read = fp;
    fp -= size_leanified;
    char *p_write = fp;

    std::vector<uint32_t> vector_local_header_offset;
    // Local file header
    while (memcmp(p_read, header_magic, sizeof(header_magic)) == 0)
    {
        vector_local_header_offset.push_back(p_write - fp);

        uint16_t filename_length = *(uint16_t *)(p_read + 26);

        size_t header_size = 30 + filename_length;
        // move header
        if (p_read - p_write)
        {
            memmove(p_write, p_read, header_size);
        }

        // if Extra field length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 28))
        {
            p_read += *(uint16_t *)(p_write + 28);
            *(uint16_t *)(p_write + 28) = 0;
        }

        uint32_t *crc = (uint32_t *)(p_write + 14);
        uint32_t *compressed_size = crc + 1;
        uint32_t *uncompressed_size = compressed_size + 1;

        uint32_t original_compressed_size = *compressed_size;

        uint16_t flag = *(uint16_t *)(p_write + 6);
        uint16_t compression_method = *(uint16_t *)(p_write + 8);

        std::string filename(p_write + 30, filename_length);
        // do not output filename if it is a directory
        if ((original_compressed_size || compression_method || flag & 8) && depth <= max_depth)
        {
            // output filename
            for (int i = 1; i < depth; i++)
            {
                std::cout << "-> ";
            }
            std::cout << filename << std::endl;
        }

        // From Wikipedia:
        // If bit 3 (0x08) of the general-purpose flags field is set,
        // then the CRC-32 and file sizes are not known when the header is written.
        // The fields in the local header are filled with zero,
        // and the CRC-32 and size are appended in a 12-byte structure
        // (optionally preceded by a 4-byte signature) immediately after the compressed data
        if (flag & 8)
        {
            // set this bit to 0
            *(uint16_t *)(p_write + 6) &= ~8;

            // data descriptor signature
            const unsigned char dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };
            // search for signature
            char *dd = p_read + header_size;
            while (*(uint32_t *)(dd + 8) != dd - p_read - header_size)
            {
                dd = std::search(dd + 1, fp + size + size_leanified, dd_sign, dd_sign + 4);
                if (dd == fp + size + size_leanified)
                {
                    std::cerr << "data descriptor signature not found!" << std::endl;
                    // abort
                    // zip does not have 4-byte signature preceded
                    return size;
                }
            }
            *crc = *(uint32_t *)(dd + 4);
            *compressed_size = original_compressed_size = *(uint32_t *)(dd + 8);
            *uncompressed_size = *(uint32_t *)(dd + 12);
        }

        // if compression method is not deflate or fast mode
        // then only Leanify embedded file if the method is store
        // otherwise just memmove the compressed part
        if (compression_method != 8 || is_fast)
        {
            if (compression_method == 0 && depth <= max_depth)
            {
                // method is store
                if (original_compressed_size)
                {
                    uint32_t new_size = LeanifyFile(p_read + header_size, original_compressed_size, p_read - p_write, filename);
                    p_read += header_size + original_compressed_size;
                    *compressed_size = *uncompressed_size = new_size;
                    *crc = mz_crc32(0, (unsigned char *)p_write + header_size, new_size);
                }
                else
                {
                    p_read += header_size;
                }
            }
            else
            {
                // other method, move it
                memmove(p_write + header_size, p_read + header_size, original_compressed_size);
                p_read += header_size + original_compressed_size;

            }
            p_write += header_size + *compressed_size;

        }
        else
        {
            // the method is deflate, uncompress it and recompress with zopfli

            p_read += header_size;
            p_write += header_size;

            if (*uncompressed_size)
            {
                // uncompress
                size_t s = 0;
                unsigned char *buffer = (unsigned char *)tinfl_decompress_mem_to_heap(p_read, original_compressed_size, &s, 0);

                if (!buffer ||
                    s != *uncompressed_size ||
                    *crc != mz_crc32(0, buffer, *uncompressed_size))
                {
                    std::cerr << "ZIP file corrupted!" << std::endl;
                    mz_free(buffer);
                    memmove(p_write, p_read, original_compressed_size);
                    p_read += original_compressed_size;
                    p_write += original_compressed_size;
                    continue;
                }

                // Leanify uncompressed file
                uint32_t new_uncompressed_size = s;
                // workaround of TinyXML2 not supporting xml:space="preserve"
                if (filename_length != 17 || filename != "word/document.xml")
                {
                    new_uncompressed_size = LeanifyFile(buffer, s, 0, filename);
                }

                // recompress
                unsigned char bp = 0, *out = NULL;
                size_t outsize = 0;
                ZopfliDeflate(&zopfli_options, 2, 1, buffer, new_uncompressed_size, &bp, &out, &outsize);

                if (outsize < original_compressed_size)
                {
                    p_read += original_compressed_size;
                    *crc = mz_crc32(0, buffer, new_uncompressed_size);
                    *compressed_size = outsize;
                    *uncompressed_size = new_uncompressed_size;
                    memcpy(p_write, out, outsize);
                    p_write += outsize;
                }
                else
                {
                    memmove(p_write, p_read, original_compressed_size);
                    p_write += original_compressed_size;
                    p_read += original_compressed_size;
                }
                mz_free(buffer);
                delete[] out;
            }
            else
            {
                memmove(p_write, p_read, original_compressed_size);
                p_write += original_compressed_size;
                p_read += original_compressed_size;
            }
        }

        // we don't use data descriptor, so that can save more bytes (16 per file)
        if (flag & 8)
        {
            p_read += 16;
        }
    }

    char *central_directory = p_write;
    // Central directory file header
    const unsigned char cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };
    int i = 0;
    while (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic)) == 0)
    {

        int header_size = 46 + *(uint16_t *)(p_read + 28);
        // move header
        if (p_read - p_write)
        {
            memmove(p_write, p_read, header_size);
        }

        // set bit 3 of General purpose bit flag to 0
        *(uint16_t *)(p_write + 8) &= ~8;

        // if Extra field length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 30))
        {
            p_read += *(uint16_t *)(p_write + 30);
            *(uint16_t *)(p_write + 30) = 0;
        }

        // if File comment length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 32))
        {
            p_read += *(uint16_t *)(p_write + 32);
            *(uint16_t *)(p_write + 32) = 0;
        }

        char *local_header = fp + vector_local_header_offset[i];

        // copy new CRC-32, Compressed size, Uncompressed size
        // from Local file header to Central directory file header
        memcpy(p_write + 16, local_header + 14, 12);

        // new Local file header offset
        *(uint32_t *)(p_write + 42) = vector_local_header_offset[i];

        i++;

        p_read += header_size;
        p_write += header_size;
    }

    // End of central directory record
    const unsigned char eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };
    if (memcmp(p_read, eocd_header_magic, sizeof(eocd_header_magic)))
    {
        std::cerr << "EOCD not found!" << std::endl;

    }
    if (p_read - p_write)
    {
        memmove(p_write, p_read, 12);
    }
    // central directory size
    *(uint32_t *)(p_write + 12) = p_write - central_directory;
    // central directory offset
    *(uint32_t *)(p_write + 16) = central_directory - fp;
    // set comment length to 0
    *(uint16_t *)(p_write + 20) = 0;

    // 22 is the length of EOCD
    return p_write + 22 - fp;
}

<commit_msg>ZIP: switch to store if deflate makes file larger #16<commit_after>#include "zip.h"

#include <algorithm>    // std::search
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

#include "../lib/miniz/miniz.h"

#include "../leanify.h"

const unsigned char Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };

size_t Zip::Leanify(size_t size_leanified /*= 0*/)
{
    depth++;
    char *p_read = fp;
    fp -= size_leanified;
    char *p_write = fp;

    std::vector<uint32_t> vector_local_header_offset;
    // Local file header
    while (memcmp(p_read, header_magic, sizeof(header_magic)) == 0)
    {
        vector_local_header_offset.push_back(p_write - fp);

        uint16_t filename_length = *(uint16_t *)(p_read + 26);

        size_t header_size = 30 + filename_length;
        // move header
        if (p_read - p_write)
        {
            memmove(p_write, p_read, header_size);
        }

        // if Extra field length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 28))
        {
            p_read += *(uint16_t *)(p_write + 28);
            *(uint16_t *)(p_write + 28) = 0;
        }

        uint32_t *crc = (uint32_t *)(p_write + 14);
        uint32_t *compressed_size = crc + 1;
        uint32_t *uncompressed_size = compressed_size + 1;

        uint32_t orig_comp_size = *compressed_size;

        uint16_t flag = *(uint16_t *)(p_write + 6);
        uint16_t *compression_method = (uint16_t *)(p_write + 8);

        std::string filename(p_write + 30, filename_length);
        // do not output filename if it is a directory
        if ((orig_comp_size || *compression_method || flag & 8) && depth <= max_depth)
        {
            // output filename
            for (int i = 1; i < depth; i++)
            {
                std::cout << "-> ";
            }
            std::cout << filename << std::endl;
        }

        // From Wikipedia:
        // If bit 3 (0x08) of the general-purpose flags field is set,
        // then the CRC-32 and file sizes are not known when the header is written.
        // The fields in the local header are filled with zero,
        // and the CRC-32 and size are appended in a 12-byte structure
        // (optionally preceded by a 4-byte signature) immediately after the compressed data
        if (flag & 8)
        {
            // set this bit to 0
            *(uint16_t *)(p_write + 6) &= ~8;

            // data descriptor signature
            const unsigned char dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };
            // search for signature
            char *dd = p_read + header_size;
            while (*(uint32_t *)(dd + 8) != dd - p_read - header_size)
            {
                dd = std::search(dd + 1, fp + size + size_leanified, dd_sign, dd_sign + 4);
                if (dd == fp + size + size_leanified)
                {
                    std::cerr << "data descriptor signature not found!" << std::endl;
                    // abort
                    // zip does not have 4-byte signature preceded
                    return size;
                }
            }
            *crc = *(uint32_t *)(dd + 4);
            *compressed_size = orig_comp_size = *(uint32_t *)(dd + 8);
            *uncompressed_size = *(uint32_t *)(dd + 12);
        }

        // if compression method is not deflate or fast mode
        // then only Leanify embedded file if the method is store
        // otherwise just memmove the compressed part
        if (*compression_method != 8 || is_fast)
        {
            if (*compression_method == 0 && depth <= max_depth)
            {
                // method is store
                if (orig_comp_size)
                {
                    uint32_t new_size = LeanifyFile(p_read + header_size, orig_comp_size, p_read - p_write, filename);
                    p_read += header_size + orig_comp_size;
                    *compressed_size = *uncompressed_size = new_size;
                    *crc = mz_crc32(0, (unsigned char *)p_write + header_size, new_size);
                }
                else
                {
                    p_read += header_size;
                }
            }
            else
            {
                // unsupported compression method, move it
                memmove(p_write + header_size, p_read + header_size, orig_comp_size);
                p_read += header_size + orig_comp_size;

            }
            p_write += header_size + *compressed_size;

        }
        else
        {
            // the method is deflate, uncompress it and recompress with zopfli

            p_read += header_size;
            p_write += header_size;

            if (*uncompressed_size)
            {
                // uncompress
                size_t s = 0;
                unsigned char *buffer = (unsigned char *)tinfl_decompress_mem_to_heap(p_read, orig_comp_size, &s, 0);

                if (!buffer ||
                    s != *uncompressed_size ||
                    *crc != mz_crc32(0, buffer, *uncompressed_size))
                {
                    std::cerr << "ZIP file corrupted!" << std::endl;
                    mz_free(buffer);
                    memmove(p_write, p_read, orig_comp_size);
                    p_read += orig_comp_size;
                    p_write += orig_comp_size;
                    continue;
                }

                // Leanify uncompressed file
                uint32_t new_uncomp_size = s;
                // workaround of TinyXML2 not supporting xml:space="preserve"
                if (filename_length != 17 || filename != "word/document.xml")
                {
                    new_uncomp_size = LeanifyFile(buffer, s, 0, filename);
                }

                // recompress
                unsigned char bp = 0, *out = NULL;
                size_t new_comp_size = 0;
                ZopfliDeflate(&zopfli_options, 2, 1, buffer, new_uncomp_size, &bp, &out, &new_comp_size);

                // switch to store if deflate makes file larger
                if (new_uncomp_size <= new_comp_size && new_uncomp_size <= orig_comp_size)
                {
                    *compression_method = 0;
                    *crc = mz_crc32(0, buffer, new_uncomp_size);
                    *compressed_size = new_uncomp_size;
                    *uncompressed_size = new_uncomp_size;
                    memcpy(p_write, buffer, new_uncomp_size);
                    p_write += new_uncomp_size;
                }
                else if (new_comp_size < orig_comp_size)
                {
                    *crc = mz_crc32(0, buffer, new_uncomp_size);
                    *compressed_size = new_comp_size;
                    *uncompressed_size = new_uncomp_size;
                    memcpy(p_write, out, new_comp_size);
                    p_write += new_comp_size;
                }
                else
                {
                    memmove(p_write, p_read, orig_comp_size);
                    p_write += orig_comp_size;
                }
                p_read += orig_comp_size;

                mz_free(buffer);
                delete[] out;
            }
            else
            {
                *compression_method = 0;
                *compressed_size = 0;
                p_read += orig_comp_size;
            }
        }

        // we don't use data descriptor, so that can save more bytes (16 per file)
        if (flag & 8)
        {
            p_read += 16;
        }
    }

    char *central_directory = p_write;
    // Central directory file header
    const unsigned char cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };
    int i = 0;
    while (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic)) == 0)
    {

        int header_size = 46 + *(uint16_t *)(p_read + 28);
        // move header
        if (p_read - p_write)
        {
            memmove(p_write, p_read, header_size);
        }

        // set bit 3 of General purpose bit flag to 0
        *(uint16_t *)(p_write + 8) &= ~8;

        // if Extra field length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 30))
        {
            p_read += *(uint16_t *)(p_write + 30);
            *(uint16_t *)(p_write + 30) = 0;
        }

        // if File comment length is not 0, then skip it and set it to 0
        if (*(uint16_t *)(p_write + 32))
        {
            p_read += *(uint16_t *)(p_write + 32);
            *(uint16_t *)(p_write + 32) = 0;
        }

        char *local_header = fp + vector_local_header_offset[i];

        // copy new CRC-32, Compressed size, Uncompressed size
        // from Local file header to Central directory file header
        memcpy(p_write + 16, local_header + 14, 12);

        // update compression method
        *(uint16_t *)(p_write + 10) = *(uint16_t *)(local_header + 8);

        // new Local file header offset
        *(uint32_t *)(p_write + 42) = vector_local_header_offset[i];

        i++;

        p_read += header_size;
        p_write += header_size;
    }

    // End of central directory record
    const unsigned char eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };
    if (memcmp(p_read, eocd_header_magic, sizeof(eocd_header_magic)))
    {
        std::cerr << "EOCD not found!" << std::endl;

    }
    if (p_read - p_write)
    {
        memmove(p_write, p_read, 12);
    }
    // central directory size
    *(uint32_t *)(p_write + 12) = p_write - central_directory;
    // central directory offset
    *(uint32_t *)(p_write + 16) = central_directory - fp;
    // set comment length to 0
    *(uint16_t *)(p_write + 20) = 0;

    // 22 is the length of EOCD
    return p_write + 22 - fp;
}

<|endoftext|>


<commit_before><commit_msg>Minor change to FIXME comment<commit_after><|endoftext|>


<commit_before>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_

#include <array>
#include <cstdint>

#include <snarkfront/AES_SBox.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// 5.2 Key Expansion
//

template <typename VAR, typename T, typename U, typename BITWISE>
class AES_KeyExpansion
{
public:
    typedef VAR VarType;

    typedef std::array<VAR, 16> Key128Type;
    typedef std::array<VAR, 24> Key192Type;
    typedef std::array<VAR, 32> Key256Type;

    typedef std::array<VAR, 176> Schedule128Type;
    typedef std::array<VAR, 208> Schedule192Type;
    typedef std::array<VAR, 240> Schedule256Type;

    AES_KeyExpansion() = default;

    // AES-128
    void operator() (const std::array<VAR, 16>& key,
                     std::array<VAR, 176>& w) const {
        expand(key, w);
    }

    // AES-192
    void operator() (const std::array<VAR, 24>& key,
                     std::array<VAR, 208>& w) const {
        expand(key, w);
    }

    // AES-256
    void operator() (const std::array<VAR, 32>& key,
                     std::array<VAR, 240>& w) const {
        expand(key, w);
    }

private:
    // AES-128 max (4(Nr + 1) - 1)/Nk - 1 is 10 - 1 = 9
    // AES-192 max (4(Nr + 1) - 1)/Nk - 1 is 8 - 1 = 7
    // AES-256 max (4(Nr + 1) - 1)/Nk - 1 is 7 - 1 = 6
    std::uint8_t rcon(const std::size_t i) const {
        if (i < 8) {
            // i = 0 is x^0 = 0x01 = 1 << 0
            // i = 1 is x^1 = 0x02 = 1 << 1
            // i = 2 is x^2 = 0x04 = 1 << 2
            // i = 3 is x^3 = 0x08 = 1 << 3
            // i = 4 is x^4 = 0x10 = 1 << 4
            // i = 5 is x^5 = 0x20 = 1 << 5
            // i = 6 is x^6 = 0x40 = 1 << 6
            // i = 7 is x^7 = 0x80 = 1 << 7
            return 1 << i;
        } else if (8 == i) {
            // i = 8 is x^4 + x^3 + x + 1 = 0x1b
            return 0x1b;
        } else if (9 == i) {
            // i = 9 is x^5 + x^4 + x^2 + x = 0x36
            return 0x36;
        } else {
            return 0; // should never happen
        }
    }

    // AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)
    // AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)
    // AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)
    template <std::size_t KSZ, std::size_t WSZ>
    void expand(const std::array<VAR, KSZ>& key, // 4 * Nk octets
                std::array<VAR, WSZ>& w) const   // 16 * (Nr + 1) octets
    {
        const std::size_t
            Nk = key.size() / 4,
            Nr = w.size() / 16 - 1;

        for (std::size_t i = 0; i < Nk; ++i) {
            w[4*i] = key[4*i];
            w[4*i + 1] = key[4*i + 1];
            w[4*i + 2] = key[4*i + 2];
            w[4*i + 3] = key[4*i + 3];
        }

        for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {
            std::array<VAR, 4> temp = { w[4*(i - 1)],
                                        w[4*(i - 1) + 1],
                                        w[4*(i - 1) + 2],
                                        w[4*(i - 1) + 3] };

            if (0 == i % Nk) {
                const VAR tmp = temp[0];
                temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i/Nk - 1)));
                temp[1] = m_sbox(temp[2]);
                temp[2] = m_sbox(temp[3]);
                temp[3] = m_sbox(tmp);

            } else if (Nk > 6 && 4 == i % Nk) {
                temp[0] = m_sbox(temp[0]);
                temp[1] = m_sbox(temp[1]);
                temp[2] = m_sbox(temp[2]);
                temp[3] = m_sbox(temp[3]);
            }

            w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);
            w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);
            w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);
            w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);
        }
    }

    const AES_SBox<T, U, BITWISE> m_sbox;
};

} // namespace snarkfront

#endif
<commit_msg>Delete AES_KeyExpansion.hpp<commit_after><|endoftext|>


<commit_before>#include "amici/edata.h"

#include "amici/defines.h"
#include "amici/model.h"

#include <cstring>

namespace amici {

ExpData::ExpData() : nytrue(0), nztrue(0), nt(0), nmaxevent(0) {}

ExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent)
    : ExpData(nytrue, nztrue, nt, nmaxevent,
              std::vector<realtype>(nt * nytrue),
              std::vector<realtype>(nt * nytrue),
              std::vector<realtype>(nmaxevent * nztrue),
              std::vector<realtype>(nmaxevent * nztrue))

{
}

ExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,
                 const std::vector<realtype> &my,
                 const std::vector<realtype> &sigmay,
                 const std::vector<realtype> &mz,
                 const std::vector<realtype> &sigmaz)
    : my(my), sigmay(sigmay), mz(mz), sigmaz(sigmaz),
      nytrue(nytrue), nztrue(nztrue), nt(nt), nmaxevent(nmaxevent)
{

}

ExpData::ExpData(Model const& model)
    : ExpData(model.nytrue, model.nztrue, model.nt(), model.nMaxEvent())
{
}

ExpData::ExpData(const ExpData &other)
    : ExpData(other.nytrue, other.nztrue, other.nt, other.nmaxevent,
              other.my, other.sigmay, other.mz, other.sigmaz)
{
//    std::vector<realtype> my;
//    /** standard deviation of observed data (dimension: nt x nytrue, row-major) */
//    std::vector<realtype> sigmay;

//    /** observed events (dimension: nmaxevents x nztrue, row-major) */
//    std::vector<realtype> mz;
//    /** standard deviation of observed events/roots
//     * (dimension: nmaxevents x nztrue, row-major)*/
//    std::vector<realtype> sigmaz;
}

void ExpData::setObservedData(const double *observedData) {
    /**
     * set function that copies data from input to ExpData::my
     *
     * @param observedData observed data
     */
    for (int imy = 0; imy < nytrue * nt; ++imy) {
        my.at(imy) = static_cast<const realtype>(observedData[imy]);
    }
}

void ExpData::setObservedDataStdDev(const double *observedDataStdDev) {
    /**
     * set function that copies data from input to ExpData::sigmay
     *
     * @param observedDataStdDev standard deviation of observed data
     */
    for (int imy = 0; imy < nytrue * nt; ++imy) {
        sigmay.at(imy) = static_cast<const realtype>(observedDataStdDev[imy]);
    }
}

void ExpData::setObservedEvents(const double *observedEvents) {
    /**
     * set function that copies data from input to ExpData::mz
     *
     * @param observedEvents observed event data
     */
    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {
        mz.at(imz) = static_cast<const realtype>(observedEvents[imz]);
    }
}

void ExpData::setObservedEventsStdDev(const double *observedEventsStdDev) {
    /**
     * set function that copies data from input to ExpData::sigmaz
     *
     * @param observedEventsStdDev standard deviation of observed event data
     */
    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {
        sigmaz.at(imz) = static_cast<const realtype>(observedEventsStdDev[imz]);
    }
}

ExpData::~ExpData() {
}

} // namespace amici
<commit_msg>Cleanup<commit_after>#include "amici/edata.h"

#include "amici/defines.h"
#include "amici/model.h"

#include <cstring>

namespace amici {

ExpData::ExpData() : nytrue(0), nztrue(0), nt(0), nmaxevent(0) {}

ExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent)
    : ExpData(nytrue, nztrue, nt, nmaxevent,
              std::vector<realtype>(nt * nytrue),
              std::vector<realtype>(nt * nytrue),
              std::vector<realtype>(nmaxevent * nztrue),
              std::vector<realtype>(nmaxevent * nztrue))

{
}

ExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,
                 const std::vector<realtype> &my,
                 const std::vector<realtype> &sigmay,
                 const std::vector<realtype> &mz,
                 const std::vector<realtype> &sigmaz)
    : my(my), sigmay(sigmay), mz(mz), sigmaz(sigmaz),
      nytrue(nytrue), nztrue(nztrue), nt(nt), nmaxevent(nmaxevent)
{

}

ExpData::ExpData(Model const& model)
    : ExpData(model.nytrue, model.nztrue, model.nt(), model.nMaxEvent())
{
}

ExpData::ExpData(const ExpData &other)
    : ExpData(other.nytrue, other.nztrue, other.nt, other.nmaxevent,
              other.my, other.sigmay, other.mz, other.sigmaz)
{
}

void ExpData::setObservedData(const double *observedData) {
    /**
     * set function that copies data from input to ExpData::my
     *
     * @param observedData observed data
     */
    for (int imy = 0; imy < nytrue * nt; ++imy) {
        my.at(imy) = static_cast<const realtype>(observedData[imy]);
    }
}

void ExpData::setObservedDataStdDev(const double *observedDataStdDev) {
    /**
     * set function that copies data from input to ExpData::sigmay
     *
     * @param observedDataStdDev standard deviation of observed data
     */
    for (int imy = 0; imy < nytrue * nt; ++imy) {
        sigmay.at(imy) = static_cast<const realtype>(observedDataStdDev[imy]);
    }
}

void ExpData::setObservedEvents(const double *observedEvents) {
    /**
     * set function that copies data from input to ExpData::mz
     *
     * @param observedEvents observed event data
     */
    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {
        mz.at(imz) = static_cast<const realtype>(observedEvents[imz]);
    }
}

void ExpData::setObservedEventsStdDev(const double *observedEventsStdDev) {
    /**
     * set function that copies data from input to ExpData::sigmaz
     *
     * @param observedEventsStdDev standard deviation of observed event data
     */
    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {
        sigmaz.at(imz) = static_cast<const realtype>(observedEventsStdDev[imz]);
    }
}

ExpData::~ExpData() {
}

} // namespace amici
<|endoftext|>


<commit_before>// Copyright (c) 2018 The OTS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "layout.h"

#include "fvar.h"

// OpenType Variations Common Table Formats

#define TABLE_NAME "Variations" // XXX: use individual table names

namespace {

bool ParseVariationRegionList(const ots::Font* font, const uint8_t* data, const size_t length,
                              uint16_t* regionCount) {
  ots::Buffer subtable(data, length);

  uint16_t axisCount;

  if (!subtable.ReadU16(&axisCount) ||
      !subtable.ReadU16(regionCount)) {
    return OTS_FAILURE_MSG("Failed to read variation region list header");
  }

  const ots::OpenTypeFVAR* fvar =
    static_cast<ots::OpenTypeFVAR*>(font->GetTypedTable(OTS_TAG_FVAR));
  if (!fvar) {
    return OTS_FAILURE_MSG("Required fvar table is missing");
  }
  if (axisCount != fvar->AxisCount()) {
    return OTS_FAILURE_MSG("Axis count mismatch");
  }

  for (unsigned i = 0; i < *regionCount; i++) {
    for (unsigned j = 0; j < axisCount; j++) {
      int16_t startCoord, peakCoord, endCoord;
      if (!subtable.ReadS16(&startCoord) ||
          !subtable.ReadS16(&peakCoord) ||
          !subtable.ReadS16(&endCoord)) {
        return OTS_FAILURE_MSG("Failed to read region axis coordinates");
      }
      if (startCoord > peakCoord || peakCoord > endCoord) {
        return OTS_FAILURE_MSG("Region axis coordinates out of order");
      }
      if (startCoord < -0x4000 || endCoord > 0x4000) {
        return OTS_FAILURE_MSG("Region axis coordinate out of range");
      }
      if ((peakCoord < 0 && endCoord > 0) ||
          (peakCoord > 0 && startCoord < 0)) {
        return OTS_FAILURE_MSG("Invalid region axis coordinates");
      }
    }
  }

  return true;
}

bool
ParseVariationDataSubtable(const ots::Font* font, const uint8_t* data, const size_t length,
                           const uint16_t regionCount) {
  ots::Buffer subtable(data, length);

  uint16_t itemCount;
  uint16_t shortDeltaCount;
  uint16_t regionIndexCount;

  if (!subtable.ReadU16(&itemCount) ||
      !subtable.ReadU16(&shortDeltaCount) ||
      !subtable.ReadU16(&regionIndexCount)) {
    return OTS_FAILURE_MSG("Failed to read variation data subtable header");
  }

  for (unsigned i = 0; i < regionIndexCount; i++) {
    uint16_t regionIndex;
    if (!subtable.ReadU16(&regionIndex) || regionIndex >= regionCount) {
      return OTS_FAILURE_MSG("Bad region index");
    }
  }

  if (!subtable.Skip(size_t(itemCount) * (size_t(shortDeltaCount) + size_t(regionIndexCount)))) {
    return OTS_FAILURE_MSG("Failed to read delta data");
  }

  return true;
}

} // namespace

namespace ots {

bool
ParseItemVariationStore(const Font* font, const uint8_t* data, const size_t length) {
  Buffer subtable(data, length);

  uint16_t format;
  uint32_t variationRegionListOffset;
  uint16_t itemVariationDataCount;

  if (!subtable.ReadU16(&format) ||
      !subtable.ReadU32(&variationRegionListOffset) ||
      !subtable.ReadU16(&itemVariationDataCount)) {
    return OTS_FAILURE_MSG("Failed to read item variation store header");
  }

  if (format != 1) {
    return OTS_FAILURE_MSG("Unknown item variation store format");
  }

  if (variationRegionListOffset < subtable.offset() + 4 * itemVariationDataCount ||
      variationRegionListOffset > length) {
    return OTS_FAILURE_MSG("Invalid variation region list offset");
  }

  uint16_t regionCount;
  if (!ParseVariationRegionList(font,
                                data + variationRegionListOffset,
                                length - variationRegionListOffset,
                                &regionCount)) {
    return OTS_FAILURE_MSG("Failed to parse variation region list");
  }

  for (unsigned i = 0; i < itemVariationDataCount; i++) {
    uint32_t offset;
    if (!subtable.ReadU32(&offset)) {
      return OTS_FAILURE_MSG("Failed to read variation data subtable offset");
    }
    if (offset >= length) {
      return OTS_FAILURE_MSG("Bad offset to variation data subtable");
    }
    if (!ParseVariationDataSubtable(font, data + offset, length - offset, regionCount)) {
      return OTS_FAILURE_MSG("Failed to parse variation data subtable");
    }
  }

  return true;
}

bool ParseDeltaSetIndexMap(const Font* font, const uint8_t* data, const size_t length) {
  Buffer subtable(data, length);

  uint16_t entryFormat;
  uint16_t mapCount;

  if (!subtable.ReadU16(&entryFormat) ||
      !subtable.ReadU16(&mapCount)) {
    return OTS_FAILURE_MSG("Failed to read delta set index map header");
  }

  const uint16_t MAP_ENTRY_SIZE_MASK = 0x0030;

  const uint16_t entrySize = (((entryFormat & MAP_ENTRY_SIZE_MASK) >> 4) + 1);
  if (!subtable.Skip(entrySize * mapCount)) {
    return OTS_FAILURE_MSG("Failed to read delta set index map data");
  }

  return true;
}

bool ParseVariationData(const Font* font, const uint8_t* data, size_t length,
                        size_t axisCount, size_t sharedTupleCount) {
  Buffer subtable(data, length);

  uint16_t tupleVariationCount;
  uint16_t dataOffset;
  if (!subtable.ReadU16(&tupleVariationCount) ||
      !subtable.ReadU16(&dataOffset)) {
    return OTS_FAILURE_MSG("Failed to read variation data header");
  }

  if (dataOffset > length) {
    return OTS_FAILURE_MSG("Invalid serialized data offset");
  }

  tupleVariationCount &= 0x0FFF; // mask off flags

  const uint16_t EMBEDDED_PEAK_TUPLE = 0x8000;
  const uint16_t INTERMEDIATE_REGION = 0x4000;
  const uint16_t TUPLE_INDEX_MASK    = 0x0FFF;

  for (unsigned i = 0; i < tupleVariationCount; i++) {
    uint16_t variationDataSize;
    uint16_t tupleIndex;

    if (!subtable.ReadU16(&variationDataSize) ||
        !subtable.ReadU16(&tupleIndex)) {
      return OTS_FAILURE_MSG("Failed to read tuple variation header");
    }

    if (tupleIndex & EMBEDDED_PEAK_TUPLE) {
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
      }
    }

    if (tupleIndex & INTERMEDIATE_REGION) {
      std::vector<int16_t> startTuple(axisCount);
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
        startTuple.push_back(coordinate);
      }

      std::vector<int16_t> endTuple(axisCount);
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
        endTuple.push_back(coordinate);
      }

      for (unsigned axis = 0; axis < axisCount; axis++) {
        if (startTuple[axis] > endTuple[axis]) {
          return OTS_FAILURE_MSG("Invalid intermediate range");
        }
      }
    }

    if (!(tupleIndex & EMBEDDED_PEAK_TUPLE)) {
      tupleIndex &= TUPLE_INDEX_MASK;
      if (tupleIndex >= sharedTupleCount) {
        return OTS_FAILURE_MSG("Tuple index out of range");
      }
    }
  }

  // TODO: we don't attempt to interpret the serialized data block

  return true;
}

} // namespace ots

#undef TABLE_NAME
<commit_msg>[variations] ignore VarRegionList.RegionAxisCount when RegionCount == 0<commit_after>// Copyright (c) 2018 The OTS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "layout.h"

#include "fvar.h"

// OpenType Variations Common Table Formats

#define TABLE_NAME "Variations" // XXX: use individual table names

namespace {

bool ParseVariationRegionList(const ots::Font* font, const uint8_t* data, const size_t length,
                              uint16_t* regionCount) {
  ots::Buffer subtable(data, length);

  uint16_t axisCount;

  if (!subtable.ReadU16(&axisCount) ||
      !subtable.ReadU16(regionCount)) {
    return OTS_FAILURE_MSG("Failed to read variation region list header");
  }

  if (*regionCount == 0) {
    return true;
  }

  const ots::OpenTypeFVAR* fvar =
    static_cast<ots::OpenTypeFVAR*>(font->GetTypedTable(OTS_TAG_FVAR));
  if (!fvar) {
    return OTS_FAILURE_MSG("Required fvar table is missing");
  }
  if (axisCount != fvar->AxisCount()) {
    return OTS_FAILURE_MSG("Axis count mismatch");
  }

  for (unsigned i = 0; i < *regionCount; i++) {
    for (unsigned j = 0; j < axisCount; j++) {
      int16_t startCoord, peakCoord, endCoord;
      if (!subtable.ReadS16(&startCoord) ||
          !subtable.ReadS16(&peakCoord) ||
          !subtable.ReadS16(&endCoord)) {
        return OTS_FAILURE_MSG("Failed to read region axis coordinates");
      }
      if (startCoord > peakCoord || peakCoord > endCoord) {
        return OTS_FAILURE_MSG("Region axis coordinates out of order");
      }
      if (startCoord < -0x4000 || endCoord > 0x4000) {
        return OTS_FAILURE_MSG("Region axis coordinate out of range");
      }
      if ((peakCoord < 0 && endCoord > 0) ||
          (peakCoord > 0 && startCoord < 0)) {
        return OTS_FAILURE_MSG("Invalid region axis coordinates");
      }
    }
  }

  return true;
}

bool
ParseVariationDataSubtable(const ots::Font* font, const uint8_t* data, const size_t length,
                           const uint16_t regionCount) {
  ots::Buffer subtable(data, length);

  uint16_t itemCount;
  uint16_t shortDeltaCount;
  uint16_t regionIndexCount;

  if (!subtable.ReadU16(&itemCount) ||
      !subtable.ReadU16(&shortDeltaCount) ||
      !subtable.ReadU16(&regionIndexCount)) {
    return OTS_FAILURE_MSG("Failed to read variation data subtable header");
  }

  for (unsigned i = 0; i < regionIndexCount; i++) {
    uint16_t regionIndex;
    if (!subtable.ReadU16(&regionIndex) || regionIndex >= regionCount) {
      return OTS_FAILURE_MSG("Bad region index");
    }
  }

  if (!subtable.Skip(size_t(itemCount) * (size_t(shortDeltaCount) + size_t(regionIndexCount)))) {
    return OTS_FAILURE_MSG("Failed to read delta data");
  }

  return true;
}

} // namespace

namespace ots {

bool
ParseItemVariationStore(const Font* font, const uint8_t* data, const size_t length) {
  Buffer subtable(data, length);

  uint16_t format;
  uint32_t variationRegionListOffset;
  uint16_t itemVariationDataCount;

  if (!subtable.ReadU16(&format) ||
      !subtable.ReadU32(&variationRegionListOffset) ||
      !subtable.ReadU16(&itemVariationDataCount)) {
    return OTS_FAILURE_MSG("Failed to read item variation store header");
  }

  if (format != 1) {
    return OTS_FAILURE_MSG("Unknown item variation store format");
  }

  if (variationRegionListOffset < subtable.offset() + 4 * itemVariationDataCount ||
      variationRegionListOffset > length) {
    return OTS_FAILURE_MSG("Invalid variation region list offset");
  }

  uint16_t regionCount;
  if (!ParseVariationRegionList(font,
                                data + variationRegionListOffset,
                                length - variationRegionListOffset,
                                &regionCount)) {
    return OTS_FAILURE_MSG("Failed to parse variation region list");
  }

  for (unsigned i = 0; i < itemVariationDataCount; i++) {
    uint32_t offset;
    if (!subtable.ReadU32(&offset)) {
      return OTS_FAILURE_MSG("Failed to read variation data subtable offset");
    }
    if (offset >= length) {
      return OTS_FAILURE_MSG("Bad offset to variation data subtable");
    }
    if (!ParseVariationDataSubtable(font, data + offset, length - offset, regionCount)) {
      return OTS_FAILURE_MSG("Failed to parse variation data subtable");
    }
  }

  return true;
}

bool ParseDeltaSetIndexMap(const Font* font, const uint8_t* data, const size_t length) {
  Buffer subtable(data, length);

  uint16_t entryFormat;
  uint16_t mapCount;

  if (!subtable.ReadU16(&entryFormat) ||
      !subtable.ReadU16(&mapCount)) {
    return OTS_FAILURE_MSG("Failed to read delta set index map header");
  }

  const uint16_t MAP_ENTRY_SIZE_MASK = 0x0030;

  const uint16_t entrySize = (((entryFormat & MAP_ENTRY_SIZE_MASK) >> 4) + 1);
  if (!subtable.Skip(entrySize * mapCount)) {
    return OTS_FAILURE_MSG("Failed to read delta set index map data");
  }

  return true;
}

bool ParseVariationData(const Font* font, const uint8_t* data, size_t length,
                        size_t axisCount, size_t sharedTupleCount) {
  Buffer subtable(data, length);

  uint16_t tupleVariationCount;
  uint16_t dataOffset;
  if (!subtable.ReadU16(&tupleVariationCount) ||
      !subtable.ReadU16(&dataOffset)) {
    return OTS_FAILURE_MSG("Failed to read variation data header");
  }

  if (dataOffset > length) {
    return OTS_FAILURE_MSG("Invalid serialized data offset");
  }

  tupleVariationCount &= 0x0FFF; // mask off flags

  const uint16_t EMBEDDED_PEAK_TUPLE = 0x8000;
  const uint16_t INTERMEDIATE_REGION = 0x4000;
  const uint16_t TUPLE_INDEX_MASK    = 0x0FFF;

  for (unsigned i = 0; i < tupleVariationCount; i++) {
    uint16_t variationDataSize;
    uint16_t tupleIndex;

    if (!subtable.ReadU16(&variationDataSize) ||
        !subtable.ReadU16(&tupleIndex)) {
      return OTS_FAILURE_MSG("Failed to read tuple variation header");
    }

    if (tupleIndex & EMBEDDED_PEAK_TUPLE) {
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
      }
    }

    if (tupleIndex & INTERMEDIATE_REGION) {
      std::vector<int16_t> startTuple(axisCount);
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
        startTuple.push_back(coordinate);
      }

      std::vector<int16_t> endTuple(axisCount);
      for (unsigned axis = 0; axis < axisCount; axis++) {
        int16_t coordinate;
        if (!subtable.ReadS16(&coordinate)) {
          return OTS_FAILURE_MSG("Failed to read tuple coordinate");
        }
        if (coordinate < -0x4000 || coordinate > 0x4000) {
          return OTS_FAILURE_MSG("Invalid tuple coordinate");
        }
        endTuple.push_back(coordinate);
      }

      for (unsigned axis = 0; axis < axisCount; axis++) {
        if (startTuple[axis] > endTuple[axis]) {
          return OTS_FAILURE_MSG("Invalid intermediate range");
        }
      }
    }

    if (!(tupleIndex & EMBEDDED_PEAK_TUPLE)) {
      tupleIndex &= TUPLE_INDEX_MASK;
      if (tupleIndex >= sharedTupleCount) {
        return OTS_FAILURE_MSG("Tuple index out of range");
      }
    }
  }

  // TODO: we don't attempt to interpret the serialized data block

  return true;
}

} // namespace ots

#undef TABLE_NAME
<|endoftext|>


<commit_before><commit_msg>lb_http: implement class Cancellable<commit_after><|endoftext|>


<commit_before><commit_msg>fix noise on mobile<commit_after><|endoftext|>


<commit_before>void enemy_set_destination(map_t map, entity_t *enemy, v2 dest) {
    int tiles[30][40];

    for (int j = 0; j < 30; j++) {
        for (int i = 0; i < 40; i++) {
            tiles[j][i] = (map.tile[j][i] == WALL || map.tile[j][i] == LOCK) ? -2 : -1;
        }
    }

    dest = V2(((int) dest.x)/TILE_SIZE, ((int) dest.y)/TILE_SIZE);
    //printf("dest %lf %lf\n", dest);
    //dest = dest/TILE_SIZE;

    tiles[(int) dest.y][(int) dest.x] = 0;

    v2 queue[30*40];
    int start = 0, end = 0;
    queue[end++] = dest;

    v2 enemy_pos = enemy->pos;
    while (end != start) {
        v2 cur = queue[start++];

        if (cur == enemy_pos) break;

        if (tiles[int(cur.y -1)][int(cur.x -1)] == -1) {
            tiles[int(cur.y -1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y -1);
        }
        if (tiles[int(cur.y -1)][int(cur.x)] == -1) {
            tiles[int(cur.y -1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x, cur.y -1);
        }
        if (tiles[int(cur.y -1)][int(cur.x +1)] == -1) {
            tiles[int(cur.y -1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y -1);
        }
        if (tiles[int(cur.y)][int(cur.x -1)] == -1) {
            tiles[int(cur.y)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y);
        }
        if (tiles[int(cur.y)][int(cur.x +1)] == -1) {
            tiles[int(cur.y)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y);
        }
        if (tiles[int(cur.y +1)][int(cur.x -1)] == -1) {
            tiles[int(cur.y +1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y +1);
        }
        if (tiles[int(cur.y +1)][int(cur.x)] == -1) {
            tiles[int(cur.y +1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x, cur.y +1);
        }
        if (tiles[int(cur.y +1)][int(cur.x +1)] == -1) {
            tiles[int(cur.y +1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y +1);
        }
    }

    if (enemy->enemy_data.path) {
        free(enemy->enemy_data.path);
    }
    enemy->enemy_data.path = (v2*) malloc(end*sizeof(v2));
    enemy->enemy_data.path[0] = enemy_pos/TILE_SIZE;
    enemy->enemy_data.path[0] = V2(((int) enemy_pos.x)/TILE_SIZE, ((int) enemy_pos.y)/TILE_SIZE);

    int i = 0;
    int k = 0;
    while (true) {
        v2 currentPoint = enemy->enemy_data.path[i];
        if (tiles[(int)currentPoint.y][(int) currentPoint.x] == 0) break;
        v2 min = currentPoint;

        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x)] != -2) {
                min = V2(currentPoint.x, currentPoint.y+1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x)] != -2) {
                min = V2(currentPoint.x, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y+1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y+1);
            }
        }

        enemy->enemy_data.path[++i] = min;
    }

    enemy->enemy_data.path_len = i+1;
    enemy->enemy_data.path_cur = 0;
}

void enemy_move(map_t map, entity_t *enemy, double dt) {
    enemy->previous_pos = enemy->pos;

    v2 dir = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE/2, TILE_SIZE/2) - enemy->pos;
    double mag = math_magnitude(dir);

    if (mag < 4) {
        enemy->pos = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE/2, TILE_SIZE/2);
        if (enemy->enemy_data.path_cur+1 != enemy->enemy_data.path_len) {
            enemy->enemy_data.path_cur++;
        }
        else {
            enemy_set_destination(map, enemy, enemy->enemy_data.possibleDestinations[rand()%enemy->enemy_data.possibleDestinations_len]);
        }
        return;
    }

    v2 normalized_dir = math_normalize(dir);
    dir = normalized_dir * (enemy->speed*dt);

    v2 cur_dir;
    cur_dir.x = cos(enemy->angle/(180.0f/M_PI));
    cur_dir.y = sin(enemy->angle/(180.0f/M_PI));
    float dot = normalized_dir * math_normalize(cur_dir);

#if 0
    if (dot >= 0.9999 && dot <= 1.0001) {
        enemy->pos += dir;
    } else {
        float target_angle = atan2(dir.y, dir.x);
        target_angle *= 180.0f/M_PI;

        float a = target_angle;
        if (a < 0) a += 360;
        float b = enemy->angle;
        if (b < 0) b += 360;
        float c = a - b;
        if (c < 0) c += 360;

        if (c < 180) {
            enemy->angle += enemy->enemy_data.rotation_speed * dt;
        } else {
            enemy->angle -= enemy->enemy_data.rotation_speed * dt;
        }
    }
#else
    if (dot >= 0.88 && dot <= 1.12) {
        enemy->pos += dir;
    }

    float target_angle = atan2(dir.y, dir.x);
    target_angle *= 180.0f/M_PI;

    float a = target_angle;
    if (a < 0) a += 360;
    float b = enemy->angle;
    if (b < 0) b += 360;
    float c = a - b;
    if (c < 0) c += 360;

    if (c < 180) {
        enemy->angle += enemy->enemy_data.rotation_speed * dt;
    } else {
        enemy->angle -= enemy->enemy_data.rotation_speed * dt;
    }
#endif
}
<commit_msg>Really fix enemy movement this time<commit_after>void enemy_set_destination(map_t map, entity_t *enemy, v2 dest) {
    int tiles[30][40];

    for (int j = 0; j < 30; j++) {
        for (int i = 0; i < 40; i++) {
            tiles[j][i] = (map.tile[j][i] == WALL || map.tile[j][i] == LOCK) ? -2 : -1;
        }
    }

    dest = V2(((int) dest.x)/TILE_SIZE, ((int) dest.y)/TILE_SIZE);
    //printf("dest %lf %lf\n", dest);
    //dest = dest/TILE_SIZE;

    tiles[(int) dest.y][(int) dest.x] = 0;

    v2 queue[30*40];
    int start = 0, end = 0;
    queue[end++] = dest;

    v2 enemy_pos = enemy->pos;
    while (end != start) {
        v2 cur = queue[start++];

        if (cur == enemy_pos) break;

        if (tiles[int(cur.y -1)][int(cur.x -1)] == -1) {
            tiles[int(cur.y -1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y -1);
        }
        if (tiles[int(cur.y -1)][int(cur.x)] == -1) {
            tiles[int(cur.y -1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x, cur.y -1);
        }
        if (tiles[int(cur.y -1)][int(cur.x +1)] == -1) {
            tiles[int(cur.y -1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y -1);
        }
        if (tiles[int(cur.y)][int(cur.x -1)] == -1) {
            tiles[int(cur.y)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y);
        }
        if (tiles[int(cur.y)][int(cur.x +1)] == -1) {
            tiles[int(cur.y)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y);
        }
        if (tiles[int(cur.y +1)][int(cur.x -1)] == -1) {
            tiles[int(cur.y +1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x -1, cur.y +1);
        }
        if (tiles[int(cur.y +1)][int(cur.x)] == -1) {
            tiles[int(cur.y +1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x, cur.y +1);
        }
        if (tiles[int(cur.y +1)][int(cur.x +1)] == -1) {
            tiles[int(cur.y +1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;
            queue[end++] = V2(cur.x +1, cur.y +1);
        }
    }

    if (enemy->enemy_data.path) {
        free(enemy->enemy_data.path);
    }
    enemy->enemy_data.path = (v2*) malloc(end*sizeof(v2));
    enemy->enemy_data.path[0] = enemy_pos/TILE_SIZE;
    enemy->enemy_data.path[0] = V2(((int) enemy_pos.x)/TILE_SIZE, ((int) enemy_pos.y)/TILE_SIZE);

    int i = 0;
    int k = 0;
    while (true) {
        v2 currentPoint = enemy->enemy_data.path[i];
        if (tiles[(int)currentPoint.y][(int) currentPoint.x] == 0) break;
        v2 min = currentPoint;

        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x)] != -2) {
                min = V2(currentPoint.x, currentPoint.y+1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x)] != -2) {
                min = V2(currentPoint.x, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y-1)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y-1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x-1)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x-1)] != -2) {
                min = V2(currentPoint.x-1, currentPoint.y+1);
            }
        }
        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x+1)]) {
            if (tiles[int(currentPoint.y+1)][int(currentPoint.x+1)] != -2) {
                min = V2(currentPoint.x+1, currentPoint.y+1);
            }
        }

        enemy->enemy_data.path[++i] = min;
    }

    enemy->enemy_data.path_len = i+1;
    enemy->enemy_data.path_cur = 0;
}

void enemy_move(map_t map, entity_t *enemy, double dt) {
    enemy->previous_pos = enemy->pos;

    v2 dir = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE/2, TILE_SIZE/2) - enemy->pos;
    double mag = math_magnitude(dir);

    if (mag < 4) {
        enemy->pos = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE/2, TILE_SIZE/2);
        if (enemy->enemy_data.path_cur+1 != enemy->enemy_data.path_len) {
            enemy->enemy_data.path_cur++;
        }
        else {
            enemy_set_destination(map, enemy, enemy->enemy_data.possibleDestinations[rand()%enemy->enemy_data.possibleDestinations_len]);
        }
        return;
    }

    v2 normalized_dir = math_normalize(dir);
    dir = normalized_dir * (enemy->speed*dt);

    v2 cur_dir;
    cur_dir.x = cos(enemy->angle/(180.0f/M_PI));
    cur_dir.y = sin(enemy->angle/(180.0f/M_PI));
    float dot = normalized_dir * math_normalize(cur_dir);

#if 0
    if (dot >= 0.9999 && dot <= 1.0001) {
        enemy->pos += dir;
    } else {
        float target_angle = atan2(dir.y, dir.x);
        target_angle *= 180.0f/M_PI;

        float a = target_angle;
        if (a < 0) a += 360;
        float b = enemy->angle;
        if (b < 0) b += 360;
        float c = a - b;
        if (c < 0) c += 360;

        if (c < 180) {
            enemy->angle += enemy->enemy_data.rotation_speed * dt;
        } else {
            enemy->angle -= enemy->enemy_data.rotation_speed * dt;
        }
    }
#else
    if (dot >= 0.88 && dot <= 1.12) {
        enemy->pos += dir;
    }

    if (dot <= 0.999 || dot >= 1.001) {
        float target_angle = atan2(dir.y, dir.x);
        target_angle *= 180.0f/M_PI;

        float a = target_angle;
        if (a < 0) a += 360;
        float b = enemy->angle;
        if (b < 0) b += 360;
        float c = a - b;
        if (c < 0) c += 360;

        if (c < 180) {
            enemy->angle += enemy->enemy_data.rotation_speed * dt;
            if (enemy->angle > 360) enemy->angle -= 360;
            if (enemy->angle < 0) enemy->angle += 360;
        } else {
            enemy->angle -= enemy->enemy_data.rotation_speed * dt;
            if (enemy->angle > 360) enemy->angle -= 360;
            if (enemy->angle < 0) enemy->angle += 360;
        }
    }
#endif
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/**
 ** \file binder/binder.hh
 ** \brief Definition of binder::Binder.
 */

#ifndef BINDER_BINDER_HH
# define BINDER_BINDER_HH

# include <libport/finally.hh>
# include <list>
# include <map>

# include <ast/all.hh>
# include <ast/analyzer.hh>
# include <binder/bind.hh>
# include <urbi/object/fwd.hh>

namespace binder
{

  /// Ast local variables binder.
  class Binder : public ast::Analyzer
  {
  public:
    /// \name Useful shorthands.
    /// \{
    /// Super class type.
    typedef ast::Analyzer super_type;
    /// Import rObject
    typedef urbi::object::rObject rObject;
    /// \}

    /// \name Ctor & dtor.
    /// \{
    /// Construct a \c Binder.
    Binder ();

    /// Destroy a Binder.
    virtual ~Binder ();
    /// \}

    /// Import visit from DefaultVisitor.
    using super_type::visit;

  protected:
    CONST_VISITOR_VISIT_NODES(
                              (Assignment)
                              (Call)
                              (CallMsg)
                              (Catch)
                              (Declaration)
                              (Dictionary)
                              (Do)
                              (Foreach)
                              (If)
                              (LocalDeclaration)
                              (Match)
                              (Routine)
                              (Scope)
                              (Unscope)
                              (While)
      );

    template <typename Node, typename NewNode>
    void link_to_declaration(Node input,
                             NewNode current,
                             libport::Symbol name,
                             unsigned depth);

  private:
    /// Report an error.
    void err(const ast::loc& loc, const std::string& msg);
    /// Actions to perform at exit of the innermost scope.
    typedef std::list<libport::Finally> unbind_type;
    unbind_type unbind_;

    /// Declaration * (routine_depth * scope_depth)
    typedef std::pair<ast::rLocalDeclaration,
                      std::pair<unsigned, unsigned> > binding_type;
    typedef std::list<binding_type> Bindings;
    typedef std::map<libport::Symbol, Bindings> Environment;
    /// Map of currently bound variables
    Environment env_;

    /// Whether to apply setSlot on self
    typedef std::vector<bool> set_on_self_type;
    set_on_self_type setOnSelf_;
    bool set_on_self(unsigned up = 0);

    /// \name Routine stack.
    /// \{
    /// The stack of current number of local variables, and maximum
    /// number of local variable used by the current routine.
    typedef std::list<ast::rRoutine> routine_stack_type;
    routine_stack_type routine_stack_;
    /// Helpers routines to manipulate the frame size stack
    void routine_push(ast::rRoutine f);
    void routine_pop();

    /// The routine currently defined.
    /// Cannot be called if there is none.
    ast::rRoutine routine() const;

    /// The innermost function (not closure).
    /// May return 0.
    ast::rRoutine function() const;
    /// \}

    /// Level of routine nesting.
    unsigned routine_depth_;
    /// Level of scope nesting.
    unsigned scope_depth_;
    /// Local index at the toplevel
    unsigned toplevel_index_;

    /// Register that \a var is bound in any subscope, \a being its
    /// declaration
    void bind(ast::rLocalDeclaration decl);

    /// \return 0 if the variable isn't local, or the depth in
    /// number of nested routines otherwise.
    unsigned routine_depth_get(libport::Symbol name);
    unsigned scope_depth_get(libport::Symbol name);
    ast::rLocalDeclaration decl_get(libport::Symbol name);

    /// Factored method to handle scopes.
    libport::Finally::action_type scope_open(bool set_on_self);
    void scope_close();

    /// Factored method to create updateSlot/setSlot calls.
    ast::rCall changeSlot(const ast::loc& l,
                          const ast::rExp& target,
                          libport::Symbol name,
                          libport::Symbol method,
                          ast::rConstExp value = 0);

    /// Make a lazy from \a arg.
    ast::rExp lazify(ast::rExp arg);

    /// Wether to report errors.
    bool report_errors_;
    /// How many scope to bypass when declaring variables.
    unsigned unscope_;
  };

} // namespace binder

# include <binder/binder.hxx>

#endif // !BINDER_BINDER_HH
<commit_msg>bind: use hash table.<commit_after>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/**
 ** \file binder/binder.hh
 ** \brief Definition of binder::Binder.
 */

#ifndef BINDER_BINDER_HH
# define BINDER_BINDER_HH

# include <libport/finally.hh>
# include <list>
# include <boost/unordered_map.hpp>

# include <ast/all.hh>
# include <ast/analyzer.hh>
# include <binder/bind.hh>
# include <urbi/object/fwd.hh>

namespace binder
{

  /// Ast local variables binder.
  class Binder : public ast::Analyzer
  {
  public:
    /// \name Useful shorthands.
    /// \{
    /// Super class type.
    typedef ast::Analyzer super_type;
    /// Import rObject
    typedef urbi::object::rObject rObject;
    /// \}

    /// \name Ctor & dtor.
    /// \{
    /// Construct a \c Binder.
    Binder();

    /// Destroy a Binder.
    virtual ~Binder();
    /// \}

    /// Import visit from DefaultVisitor.
    using super_type::visit;

  protected:
    CONST_VISITOR_VISIT_NODES(
                              (Assignment)
                              (Call)
                              (CallMsg)
                              (Catch)
                              (Declaration)
                              (Dictionary)
                              (Do)
                              (Foreach)
                              (If)
                              (LocalDeclaration)
                              (Match)
                              (Routine)
                              (Scope)
                              (Unscope)
                              (While)
      );

    template <typename Node, typename NewNode>
    void link_to_declaration(Node input,
                             NewNode current,
                             libport::Symbol name,
                             unsigned depth);

  private:
    /// Report an error.
    void err(const ast::loc& loc, const std::string& msg);
    /// Actions to perform at exit of the innermost scope.
    typedef std::list<libport::Finally> unbind_type;
    unbind_type unbind_;

    /// Declaration * (routine_depth * scope_depth)
    typedef std::pair<ast::rLocalDeclaration,
                      std::pair<unsigned, unsigned> > binding_type;
    typedef std::list<binding_type> Bindings;
    typedef boost::unordered_map<libport::Symbol, Bindings> Environment;
    /// Map of currently bound variables
    Environment env_;

    /// Whether to apply setSlot on self
    typedef std::vector<bool> set_on_self_type;
    set_on_self_type setOnSelf_;
    bool set_on_self(unsigned up = 0);

    /// \name Routine stack.
    /// \{
    /// The stack of current number of local variables, and maximum
    /// number of local variable used by the current routine.
    typedef std::list<ast::rRoutine> routine_stack_type;
    routine_stack_type routine_stack_;
    /// Helpers routines to manipulate the frame size stack
    void routine_push(ast::rRoutine f);
    void routine_pop();

    /// The routine currently defined.
    /// Cannot be called if there is none.
    ast::rRoutine routine() const;

    /// The innermost function (not closure).
    /// May return 0.
    ast::rRoutine function() const;
    /// \}

    /// Level of routine nesting.
    unsigned routine_depth_;
    /// Level of scope nesting.
    unsigned scope_depth_;
    /// Local index at the toplevel
    unsigned toplevel_index_;

    /// Register that \a var is bound in any subscope, \a being its
    /// declaration
    void bind(ast::rLocalDeclaration decl);

    /// \return 0 if the variable isn't local, or the depth in
    /// number of nested routines otherwise.
    unsigned routine_depth_get(libport::Symbol name);
    unsigned scope_depth_get(libport::Symbol name);
    ast::rLocalDeclaration decl_get(libport::Symbol name);

    /// Factored method to handle scopes.
    libport::Finally::action_type scope_open(bool set_on_self);
    void scope_close();

    /// Factored method to create updateSlot/setSlot calls.
    ast::rCall changeSlot(const ast::loc& l,
                          const ast::rExp& target,
                          libport::Symbol name,
                          libport::Symbol method,
                          ast::rConstExp value = 0);

    /// Make a lazy from \a arg.
    ast::rExp lazify(ast::rExp arg);

    /// Wether to report errors.
    bool report_errors_;
    /// How many scope to bypass when declaring variables.
    unsigned unscope_;
  };

} // namespace binder

# include <binder/binder.hxx>

#endif // !BINDER_BINDER_HH
<|endoftext|>


<commit_before>/*
 *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files
 *    (cURLpp), to deal in the Software without restriction,
 *    including without limitation the rights to use, copy, modify, merge,
 *    publish, distribute, sublicense, and/or sell copies of the Software,
 *    and to permit persons to whom the Software is furnished to do so,
 *    subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *    in all copies or substantial portions of the Software.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef CURLPP_HPP
#define CURLPP_HPP

#define LIBCURLPP_VERSION "0.7.0-pre1"
#define LIBCURLPP_VERSION_NUM 0x000700

#include <string>
#include <curl/curl.h>

#include "dllfct.h"

namespace cURLpp
{
   /**
    * This function takes care of initializing cURLpp ( also libcURL). If you want
    * to cleanup cURL before your application quits just call cURLpp::terminate().
    * This function should only be called once (no matter how many threads or
    * libcurl sessions that'll be used) by every application that uses libcurl,
    * it will throw a logic_error if you call it twice.
    *
    * The flags option is a bit pattern that tells  libcurl  exact what  features
    * to init, as described below. Set the desired bits by ORing the values together.
    *
    *  CURL_GLOBAL_ALL
    *  Initialize  everything  possible.  This  sets all known bits.
    *
    *  CURL_GLOBAL_SSL
    *  Initialize SSL
    *
    *  CURL_GLOBAL_WIN32
    *  Initialize  the  Win32  socket  libraries.
    *
    *  CURL_GLOBAL_NOTHING
    *  Initialise nothing extra. This sets no bit.
    *
    * NOTE: you cannot call this function twice without first terminating it first.
    * it will throw a logic_error if you do this.
    */
  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);

  /**
   * This function takes care of cleaning up cURLpp ( also libcURL). See
   * cURLpp::initialize( long flags ) for momre documentation.
   *
   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a
   * logic_error if you do this.
   */
  void CURLPPAPI terminate();

  /**
   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )
   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that
   * cURLpp is cleanup after you reached the end of scope of a specific function using
   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his
   * constructor, so you don't have to call it by yourself, when you have decided to
   * use it.
   *
   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.
   */
  class CURLPPAPI Cleanup
  {
  public:
    Cleanup();
    ~Cleanup();
  };

  /**
   * This  function  will  convert  the given input string to an URL encoded
   * string and return that as a new allocated string. All input  characters
   * that  are  not a-z, A-Z or 0-9 will be converted to their "URL escaped"
   * version (%NN where NN is a two-digit hexadecimal number).
   */
  std::string CURLPPAPI escape( const std::string& url );

  /**
   * This  function  will  convert  the  given  URL encoded input string to a
   * "plain string" and return that as a new allocated string. All input
   * characters that are URL encoded (%XX) where XX is a two-digit
   * hexadecimal number, or +) will be converted to their plain text versions
   * (up to a ? letter, no + letters to the right of a ? letter will be
   * converted).
   */
  std::string CURLPPAPI unescape( const std::string &url );

  /**
   * this is  a portable wrapper for the getenv() function, meant to emulate
   * its behaviour and provide an identical interface for all operating
   * systems libcurl builds on (including win32). Under unix operating
   * systems, there isn't any point in returning an allocated memory,
   * although other systems won't work  properly if this isn't done. The unix
   * implementation thus have to suffer slightly from the drawbacks of other
   * systems.
   */
  std::string CURLPPAPI getenv( const std::string &name );

  /**
   * Returns  a  human readable string with the version number of libcurl and
   * some of its important components  (like  OpenSSL version).
   *
   * Note:  this  returns  the  actual running lib's version, you might have
   * installed a newer lib's include files in your system  which may turn
   * your LIBCURL_VERSION #define value to differ from this result.
   */
  std::string CURLPPAPI libcurlVersion();

  /**
   * This function returns the number of  seconds  since  January 1st  1970,
   * for the date and time that the datestring parameter specifies. The now
   * parameter is there  and  should  hold the current time to allow the
   * datestring to specify relative dates/times. Read further in the date
   * string parser  section below.
   *
   * PARSING DATES AND TIMES
   * A  "date" is a string, possibly empty, containing many items separated
   * by whitespace.  The whitespace may be omitted when no  ambiguity
   * arises.  The empty string means the beginning of today (i.e., midnight).
   * Order of the  items  is  immaterial.  A date string may contain many
   * flavors of items:
   *
   * calendar date items
   * This can be specified in a number of different ways. Including
   * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72,
   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be
   * omitted, for example: 9/17 or "sep 17".
   *
   * time of the day items
   * This  string specifies the time on a given day. Syntax  supported
   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time
   * zone as well).
   *
   * time zone items
   * Specifies  international  time zone. There are a few acronyms
   * supported,  but  in  general  you   should instead  use  the specific
   * realtive time compared to UTC. Supported formats include: -1200, MST,
   * +0100.
   *
   * day of the week items
   * Specifies a day of the week. If  this  is  mentioned alone it means that
   * day of the week in the future. Days  of  the week may be spelled out in
   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their
   * first three letters, optionally followed by a period.  The special
   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'
   * or `Thurs' for `Thursday' are also allowed. A number may precede a day
   * of the week item to  move forward  supplementary  weeks.   It  is best
   * used in expression like `third monday'.   In  this  context, `last  DAY'
   * or  `next DAY' is also acceptable; they move one week before or after
   * the day  that  DAY  by itself would represent.
   *
   * relative items
   * A  relative item adjusts a date (or the current date if  none)  forward
   * or  backward.   Example   syntax includes:  "1  year",  "1  year  ago",
   * "2 days", "4 weeks". The string `tomorrow' is worth one day in the
   * future (equivalent  to  `day'),  the  string `yesterday' is worth one
   * day in the past (equivalent to `day ago').
   *
   * pure numbers
   * If the decimal number is of the form YYYYMMDD and no other calendar date
   * item appears before  it  in  the date  string,  then  YYYY is read as
   * the year, MM as the month number and DD as the day of the month, for the
   * specified calendar date.
   */
  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );

}

#endif
<commit_msg>Started the 0.7.1 development<commit_after>/*
 *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files
 *    (cURLpp), to deal in the Software without restriction,
 *    including without limitation the rights to use, copy, modify, merge,
 *    publish, distribute, sublicense, and/or sell copies of the Software,
 *    and to permit persons to whom the Software is furnished to do so,
 *    subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *    in all copies or substantial portions of the Software.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef CURLPP_HPP
#define CURLPP_HPP

#define LIBCURLPP_VERSION "0.7.1-devel"
#define LIBCURLPP_VERSION_NUM 0x000700

#include <string>
#include <curl/curl.h>

#include "dllfct.h"

namespace cURLpp
{
   /**
    * This function takes care of initializing cURLpp ( also libcURL). If you want
    * to cleanup cURL before your application quits just call cURLpp::terminate().
    * This function should only be called once (no matter how many threads or
    * libcurl sessions that'll be used) by every application that uses libcurl,
    * it will throw a logic_error if you call it twice.
    *
    * The flags option is a bit pattern that tells  libcurl  exact what  features
    * to init, as described below. Set the desired bits by ORing the values together.
    *
    *  CURL_GLOBAL_ALL
    *  Initialize  everything  possible.  This  sets all known bits.
    *
    *  CURL_GLOBAL_SSL
    *  Initialize SSL
    *
    *  CURL_GLOBAL_WIN32
    *  Initialize  the  Win32  socket  libraries.
    *
    *  CURL_GLOBAL_NOTHING
    *  Initialise nothing extra. This sets no bit.
    *
    * NOTE: you cannot call this function twice without first terminating it first.
    * it will throw a logic_error if you do this.
    */
  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);

  /**
   * This function takes care of cleaning up cURLpp ( also libcURL). See
   * cURLpp::initialize( long flags ) for momre documentation.
   *
   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a
   * logic_error if you do this.
   */
  void CURLPPAPI terminate();

  /**
   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )
   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that
   * cURLpp is cleanup after you reached the end of scope of a specific function using
   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his
   * constructor, so you don't have to call it by yourself, when you have decided to
   * use it.
   *
   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.
   */
  class CURLPPAPI Cleanup
  {
  public:
    Cleanup();
    ~Cleanup();
  };

  /**
   * This  function  will  convert  the given input string to an URL encoded
   * string and return that as a new allocated string. All input  characters
   * that  are  not a-z, A-Z or 0-9 will be converted to their "URL escaped"
   * version (%NN where NN is a two-digit hexadecimal number).
   */
  std::string CURLPPAPI escape( const std::string& url );

  /**
   * This  function  will  convert  the  given  URL encoded input string to a
   * "plain string" and return that as a new allocated string. All input
   * characters that are URL encoded (%XX) where XX is a two-digit
   * hexadecimal number, or +) will be converted to their plain text versions
   * (up to a ? letter, no + letters to the right of a ? letter will be
   * converted).
   */
  std::string CURLPPAPI unescape( const std::string &url );

  /**
   * this is  a portable wrapper for the getenv() function, meant to emulate
   * its behaviour and provide an identical interface for all operating
   * systems libcurl builds on (including win32). Under unix operating
   * systems, there isn't any point in returning an allocated memory,
   * although other systems won't work  properly if this isn't done. The unix
   * implementation thus have to suffer slightly from the drawbacks of other
   * systems.
   */
  std::string CURLPPAPI getenv( const std::string &name );

  /**
   * Returns  a  human readable string with the version number of libcurl and
   * some of its important components  (like  OpenSSL version).
   *
   * Note:  this  returns  the  actual running lib's version, you might have
   * installed a newer lib's include files in your system  which may turn
   * your LIBCURL_VERSION #define value to differ from this result.
   */
  std::string CURLPPAPI libcurlVersion();

  /**
   * This function returns the number of  seconds  since  January 1st  1970,
   * for the date and time that the datestring parameter specifies. The now
   * parameter is there  and  should  hold the current time to allow the
   * datestring to specify relative dates/times. Read further in the date
   * string parser  section below.
   *
   * PARSING DATES AND TIMES
   * A  "date" is a string, possibly empty, containing many items separated
   * by whitespace.  The whitespace may be omitted when no  ambiguity
   * arises.  The empty string means the beginning of today (i.e., midnight).
   * Order of the  items  is  immaterial.  A date string may contain many
   * flavors of items:
   *
   * calendar date items
   * This can be specified in a number of different ways. Including
   * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72,
   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be
   * omitted, for example: 9/17 or "sep 17".
   *
   * time of the day items
   * This  string specifies the time on a given day. Syntax  supported
   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time
   * zone as well).
   *
   * time zone items
   * Specifies  international  time zone. There are a few acronyms
   * supported,  but  in  general  you   should instead  use  the specific
   * realtive time compared to UTC. Supported formats include: -1200, MST,
   * +0100.
   *
   * day of the week items
   * Specifies a day of the week. If  this  is  mentioned alone it means that
   * day of the week in the future. Days  of  the week may be spelled out in
   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their
   * first three letters, optionally followed by a period.  The special
   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'
   * or `Thurs' for `Thursday' are also allowed. A number may precede a day
   * of the week item to  move forward  supplementary  weeks.   It  is best
   * used in expression like `third monday'.   In  this  context, `last  DAY'
   * or  `next DAY' is also acceptable; they move one week before or after
   * the day  that  DAY  by itself would represent.
   *
   * relative items
   * A  relative item adjusts a date (or the current date if  none)  forward
   * or  backward.   Example   syntax includes:  "1  year",  "1  year  ago",
   * "2 days", "4 weeks". The string `tomorrow' is worth one day in the
   * future (equivalent  to  `day'),  the  string `yesterday' is worth one
   * day in the past (equivalent to `day ago').
   *
   * pure numbers
   * If the decimal number is of the form YYYYMMDD and no other calendar date
   * item appears before  it  in  the date  string,  then  YYYY is read as
   * the year, MM as the month number and DD as the day of the month, for the
   * specified calendar date.
   */
  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );

}

#endif
<|endoftext|>