<commit_before>//----------------------------------------------------------------------------
/// \file  list.ipp
//----------------------------------------------------------------------------
/// \brief Implementation of the list member functions.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-09-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

***** END LICENSE BLOCK *****
*/
#pragma once

#include <eixx/marshal/endian.hpp>
#include <eixx/marshal/visit_to_string.hpp>
#include <eixx/marshal/visit_encode_size.hpp>
#include <eixx/marshal/visit_encoder.hpp>
#include <eixx/marshal/visit_subst.hpp>
#include <ei.h>

namespace eixx    {
namespace marshal {

template <class Alloc>
void list<Alloc>::init(const eterm<Alloc>* items, size_t N, const Alloc& alloc) {
    size_t n = N > 0 ? N : 1;
    m_blob = new blob_t(sizeof(header_t) + n*sizeof(cons_t), alloc);

    header_t* l_header      = header();
    cons_t*   hd            = l_header->head;

    l_header->initialized   = true;
    l_header->alloc_size    = n;
    l_header->size          = N;

    for(auto p = items, end = items+N; p != end; ++p, ++hd) {
        BOOST_ASSERT(p->initialized());
        new (&hd->node) eterm<Alloc>(*p);
        hd->next = hd+1;
    }

    if (N == 0)
        l_header->tail = NULL;
    else {
        l_header->tail = hd-1;
        l_header->tail->next = NULL;
    }
}

template <class Alloc>
list<Alloc>::list(const cons_t* a_head, int a_len, const Alloc& alloc)
    throw (err_bad_argument) : base_t(alloc)
{
    unsigned int alloc_size;

    if (a_len >= 0) {
        alloc_size = a_len;
    } else if (a_len == -1) {
        a_len = 0;
        for (const cons_t* p = a_head; p; p = p->next)
            a_len++;
        alloc_size = a_len;
    } else
        throw err_bad_argument("List of negative length!");

    // If this is an empty list - no allocation is needed
    if (alloc_size == 0) {
        m_blob = empty_list();
        return;
    }

    m_blob = new blob_t(sizeof(header_t) + alloc_size*sizeof(cons_t), alloc);
    header_t* l_header      = header();
    l_header->initialized   = true;
    l_header->alloc_size    = alloc_size;
    l_header->size          = alloc_size;
    if (alloc_size == 0)
        l_header->tail = NULL;
    else {
        cons_t* p = l_header->head;
        l_header->tail = &p[alloc_size-1];
        for (; a_head; p++, a_head = a_head->next) {
            new (&p->node) eterm<Alloc>(a_head->node);
            p->next = p+1;
        }
        l_header->tail->next = NULL;
    }
}

template <class Alloc>
list<Alloc>::list(const char *buf, int& idx, size_t size, const Alloc& a_alloc)
    throw(err_decode_exception) : base_t(a_alloc)
{
    int arity;
    if (ei_decode_list_header(buf, &idx, &arity) < 0)
        err_decode_exception("Error decoding list header", idx);

    // If this is an empty list - no allocation is needed
    if (arity == 0) {
        m_blob = empty_list();
        return;
    }

    m_blob = new blob_t(sizeof(header_t) + arity*sizeof(cons_t), a_alloc);
    header_t* l_header = header();
    l_header->initialized = true;
    l_header->alloc_size  = arity;
    l_header->size        = arity;

    cons_t* hd = l_header->head;
    for (cons_t* end = hd+arity; hd != end; ++hd) {
        eterm<Alloc> et(buf, idx, size, a_alloc);
        new (&hd->node) eterm<Alloc>(et);
        hd->next = hd+1;
    }
    if (arity == 0) {
        l_header->tail = NULL;
    } else {
        l_header->tail = hd-1;
        l_header->tail->next = NULL;
        if (*(buf+idx) != ERL_NIL_EXT)
            throw err_decode_exception("Not a NIL list!", idx);
        idx++;
    }
    BOOST_ASSERT((size_t)idx <= size);
}

template <class Alloc>
void list<Alloc>::encode(char* buf, int& idx, size_t size) const
{
    BOOST_ASSERT(initialized());
    char* s = buf + idx;
    if (empty()) {
        put8(s,ERL_NIL_EXT);
    } else {
        put8(s,ERL_LIST_EXT);
        const header_t* l_header = header();
        put32be(s,l_header->size);
        idx += 5;
        for(const cons_t* p = l_header->head; p; p = p->next) {
            visit_eterm_encoder visitor(buf, idx, size);
            visitor.apply_visitor(p->node);
        }
        s = buf + idx;
        put8(s,ERL_NIL_EXT);
    }
    idx++;
    BOOST_ASSERT((size_t)idx <= size);
}

template <class Alloc>
list<Alloc> list<Alloc>::tail(size_t idx) const throw(err_bad_argument)
{
    const header_t* l_header = header();
    const cons_t* p = l_header->head;
    int len = (int)l_header->size - (int)idx - 1;
    if (len < 0)
        throw err_bad_argument("List too short");
    for (size_t i=0; i <= idx; i++)
        p = p->next;
    list<Alloc> l(p, len, this->get_allocator());
    return l;
}

template <class Alloc>
void list<Alloc>::push_back(const eterm<Alloc>& a)
{
    BOOST_ASSERT(a.initialized());
    if (unlikely(!m_blob)) {
        m_blob = new blob_t(sizeof(header_t) + sizeof(cons_t), this->get_allocator());
        header_t* hd = header();
        hd->initialized = false;
        hd->tail = hd->head;
        hd->size = 1;
        hd->alloc_size = 1;
        cons_t* p = hd->tail;
        p->node.set(a);
        p->next = NULL;
        return;
    }
    BOOST_ASSERT(!initialized());
    header_t* hd = header();
    bool has_space = hd->size < hd->alloc_size;
    cons_t* p = has_space ? &hd->head[hd->size] : this->get_t_allocator().allocate(1);
    new (&p->node) eterm<Alloc>(a);
    p->next  = NULL;
    if (likely(hd->size > 0))
        hd->tail->next = p;
    hd->tail = p;
    hd->size++;
}

template <class Alloc>
bool list<Alloc>::subst(eterm<Alloc>& out, const varbind<Alloc>* binding) const
    throw (err_unbound_variable)
{
    // We check if any contained term changes.
    bool changed = false;
    const header_t* l_header = header();

    if (l_header->size == 0)
        return false;

    Alloc alloc = this->get_allocator();
    list<Alloc> l_new(l_header->size, alloc);

    for (const cons_t* p=l_header->head; p; p = p->next) {
        eterm<Alloc> l_ele;
        visit_eterm_subst<Alloc> visitor(l_ele, binding);
        if (!visitor.apply_visitor(p->node))
            l_new.push_back(p->node);
        else {
            changed = true;
            l_new.push_back(l_ele);
        }
    }

    if (!changed)
        return false;

    // If changed, return the new list
    l_new.close();
    out = l_new;
    return true;
}

template <class Alloc>
bool list<Alloc>::match(const eterm<Alloc>& pattern, varbind<Alloc>* binding) const
    throw (err_invalid_term, err_unbound_variable)
{
    switch (pattern.type()) {
        case VAR:  return pattern.match(eterm<Alloc>(*this), binding);
        case LIST: break;
        default:   return false;
    }

    const list<Alloc>& pl = pattern.to_list();
    if (unlikely(!initialized() || !pl.initialized()))
        throw err_invalid_term("List not initialized!");

    const header_t* l_header = header();
    // Do a quick check on the size.
    if (l_header->size != pl.length())
        return false;

    const_iterator it1  = begin(), it2  = pl.begin(),
                   end1 = end(),   end2 = pl.end();
    for (; it1 != end1 && it2 != end2; ++it1, ++it2)
        if (!it1->match(*it2, binding))
            return false;

    BOOST_ASSERT(it1 == end1 && it2 == end2);
    return true;
}

template <class Alloc>
std::ostream& list<Alloc>::dump(std::ostream& out, const varbind<Alloc>* vars) const
{
    out << '[';
    const cons_t* hd = empty() ? NULL : header()->head;
    for(const cons_t* p = hd; p; p = p->next) {
        out << (p != hd ? "," : "");
        const visit_eterm_stringify<Alloc> visitor(out, vars);
        visitor.apply_visitor(p->node);
    }
    return out << ']';
}

} // namespace marshal
} // namespace eixx
<commit_msg>Fix bug - uninitialized cons node field<commit_after>//----------------------------------------------------------------------------
/// \file  list.ipp
//----------------------------------------------------------------------------
/// \brief Implementation of the list member functions.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-09-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

***** END LICENSE BLOCK *****
*/
#pragma once

#include <eixx/marshal/endian.hpp>
#include <eixx/marshal/visit_to_string.hpp>
#include <eixx/marshal/visit_encode_size.hpp>
#include <eixx/marshal/visit_encoder.hpp>
#include <eixx/marshal/visit_subst.hpp>
#include <ei.h>

namespace eixx    {
namespace marshal {

template <class Alloc>
void list<Alloc>::init(const eterm<Alloc>* items, size_t N, const Alloc& alloc) {
    size_t n = N > 0 ? N : 1;
    m_blob = new blob_t(sizeof(header_t) + n*sizeof(cons_t), alloc);

    header_t* l_header      = header();
    cons_t*   hd            = l_header->head;

    l_header->initialized   = true;
    l_header->alloc_size    = n;
    l_header->size          = N;

    for(auto p = items, end = items+N; p != end; ++p, ++hd) {
        BOOST_ASSERT(p->initialized());
        new (&hd->node) eterm<Alloc>(*p);
        hd->next = hd+1;
    }

    if (N == 0)
        l_header->tail = NULL;
    else {
        l_header->tail = hd-1;
        l_header->tail->next = NULL;
    }
}

template <class Alloc>
list<Alloc>::list(const cons_t* a_head, int a_len, const Alloc& alloc)
    throw (err_bad_argument) : base_t(alloc)
{
    unsigned int alloc_size;

    if (a_len >= 0) {
        alloc_size = a_len;
    } else if (a_len == -1) {
        a_len = 0;
        for (const cons_t* p = a_head; p; p = p->next)
            a_len++;
        alloc_size = a_len;
    } else
        throw err_bad_argument("List of negative length!");

    // If this is an empty list - no allocation is needed
    if (alloc_size == 0) {
        m_blob = empty_list();
        return;
    }

    m_blob = new blob_t(sizeof(header_t) + alloc_size*sizeof(cons_t), alloc);
    header_t* l_header      = header();
    l_header->initialized   = true;
    l_header->alloc_size    = alloc_size;
    l_header->size          = alloc_size;
    if (alloc_size == 0)
        l_header->tail = NULL;
    else {
        cons_t* p = l_header->head;
        l_header->tail = &p[alloc_size-1];
        for (; a_head; p++, a_head = a_head->next) {
            new (&p->node) eterm<Alloc>(a_head->node);
            p->next = p+1;
        }
        l_header->tail->next = NULL;
    }
}

template <class Alloc>
list<Alloc>::list(const char *buf, int& idx, size_t size, const Alloc& a_alloc)
    throw(err_decode_exception) : base_t(a_alloc)
{
    int arity;
    if (ei_decode_list_header(buf, &idx, &arity) < 0)
        err_decode_exception("Error decoding list header", idx);

    // If this is an empty list - no allocation is needed
    if (arity == 0) {
        m_blob = empty_list();
        return;
    }

    m_blob = new blob_t(sizeof(header_t) + arity*sizeof(cons_t), a_alloc);
    header_t* l_header = header();
    l_header->initialized = true;
    l_header->alloc_size  = arity;
    l_header->size        = arity;

    cons_t* hd = l_header->head;
    for (cons_t* end = hd+arity; hd != end; ++hd) {
        eterm<Alloc> et(buf, idx, size, a_alloc);
        new (&hd->node) eterm<Alloc>(et);
        hd->next = hd+1;
    }
    if (arity == 0) {
        l_header->tail = NULL;
    } else {
        l_header->tail = hd-1;
        l_header->tail->next = NULL;
        if (*(buf+idx) != ERL_NIL_EXT)
            throw err_decode_exception("Not a NIL list!", idx);
        idx++;
    }
    BOOST_ASSERT((size_t)idx <= size);
}

template <class Alloc>
void list<Alloc>::encode(char* buf, int& idx, size_t size) const
{
    BOOST_ASSERT(initialized());
    char* s = buf + idx;
    if (empty()) {
        put8(s,ERL_NIL_EXT);
    } else {
        put8(s,ERL_LIST_EXT);
        const header_t* l_header = header();
        put32be(s,l_header->size);
        idx += 5;
        for(const cons_t* p = l_header->head; p; p = p->next) {
            visit_eterm_encoder visitor(buf, idx, size);
            visitor.apply_visitor(p->node);
        }
        s = buf + idx;
        put8(s,ERL_NIL_EXT);
    }
    idx++;
    BOOST_ASSERT((size_t)idx <= size);
}

template <class Alloc>
list<Alloc> list<Alloc>::tail(size_t idx) const throw(err_bad_argument)
{
    const header_t* l_header = header();
    const cons_t* p = l_header->head;
    int len = (int)l_header->size - (int)idx - 1;
    if (len < 0)
        throw err_bad_argument("List too short");
    for (size_t i=0; i <= idx; i++)
        p = p->next;
    list<Alloc> l(p, len, this->get_allocator());
    return l;
}

template <class Alloc>
void list<Alloc>::push_back(const eterm<Alloc>& a)
{
    BOOST_ASSERT(a.initialized());
    if (unlikely(!m_blob)) {
        m_blob = new blob_t(sizeof(header_t) + sizeof(cons_t), this->get_allocator());
        header_t* hd = header();
        hd->initialized = false;
        hd->tail = hd->head;
        hd->size = 1;
        hd->alloc_size = 1;
        cons_t* p = hd->tail;
        new (&p->node) eterm<Alloc>(a);
        p->next = NULL;
        return;
    }
    BOOST_ASSERT(!initialized());
    header_t* hd = header();
    bool has_space = hd->size < hd->alloc_size;
    cons_t* p = has_space ? &hd->head[hd->size] : this->get_t_allocator().allocate(1);
    new (&p->node) eterm<Alloc>(a);
    p->next  = NULL;
    if (likely(hd->size > 0))
        hd->tail->next = p;
    hd->tail = p;
    hd->size++;
}

template <class Alloc>
bool list<Alloc>::subst(eterm<Alloc>& out, const varbind<Alloc>* binding) const
    throw (err_unbound_variable)
{
    // We check if any contained term changes.
    bool changed = false;
    const header_t* l_header = header();

    if (l_header->size == 0)
        return false;

    Alloc alloc = this->get_allocator();
    list<Alloc> l_new(l_header->size, alloc);

    for (const cons_t* p=l_header->head; p; p = p->next) {
        eterm<Alloc> l_ele;
        visit_eterm_subst<Alloc> visitor(l_ele, binding);
        if (!visitor.apply_visitor(p->node))
            l_new.push_back(p->node);
        else {
            changed = true;
            l_new.push_back(l_ele);
        }
    }

    if (!changed)
        return false;

    // If changed, return the new list
    l_new.close();
    out = l_new;
    return true;
}

template <class Alloc>
bool list<Alloc>::match(const eterm<Alloc>& pattern, varbind<Alloc>* binding) const
    throw (err_invalid_term, err_unbound_variable)
{
    switch (pattern.type()) {
        case VAR:  return pattern.match(eterm<Alloc>(*this), binding);
        case LIST: break;
        default:   return false;
    }

    const list<Alloc>& pl = pattern.to_list();
    if (unlikely(!initialized() || !pl.initialized()))
        throw err_invalid_term("List not initialized!");

    const header_t* l_header = header();
    // Do a quick check on the size.
    if (l_header->size != pl.length())
        return false;

    const_iterator it1  = begin(), it2  = pl.begin(),
                   end1 = end(),   end2 = pl.end();
    for (; it1 != end1 && it2 != end2; ++it1, ++it2)
        if (!it1->match(*it2, binding))
            return false;

    BOOST_ASSERT(it1 == end1 && it2 == end2);
    return true;
}

template <class Alloc>
std::ostream& list<Alloc>::dump(std::ostream& out, const varbind<Alloc>* vars) const
{
    out << '[';
    const cons_t* hd = empty() ? NULL : header()->head;
    for(const cons_t* p = hd; p; p = p->next) {
        out << (p != hd ? "," : "");
        const visit_eterm_stringify<Alloc> visitor(out, vars);
        visitor.apply_visitor(p->node);
    }
    return out << ']';
}

} // namespace marshal
} // namespace eixx
<|endoftext|>


<commit_before>#ifndef EVENT_PAGE_HPP_
#define EVENT_PAGE_HPP_

#include "memory_page.h"

#include <ostream>

// BLOCK_SIZE == 4084 (4096-12) => Max unique objects == 127 / page

template < class EVT, class OBJ >
class EventPage {
public:
    typedef EVT event_t;
    typedef OBJ object_t;

    struct event_node {
        event_t *       p_event;
        event_node *    next;
        event_node( event_t * e = NULL, event_node * n = NULL ) : p_event(e), next(n) {}
    };

    struct object_node {
        object_t        object_id;
        event_node *    enode;
    };

    typedef std::pair< object_node *, event_node * > next_event_t;

    EventPage() {}

    unsigned short getFreeSpace() const {
        return (m_page.header.free_end - m_page.header.free_start);
    }

    bool isFull() const {
        static const offset_t buffer_zone_size = sizeof(object_node) + sizeof( event_node );
        return getFreeSpace() < buffer_zone_size;
    }

    bool addEvent( const event_t * e, const object_t & object_id ) {
        offset_t n_free_start = m_page.header.free_start;
        offset_t n_free_end = m_page.header.free_end - sizeof( event_node );

        if( n_free_start >= n_free_end ) return false;  // page full

        object_node * obj = findObject( object_id );

        if( obj == NULL ) {
            // object does not exist on current page
            n_free_start += sizeof( object_node );
        }

        bool res = (n_free_start < n_free_end); // is there sufficient space to schedule event?
        if( res ) {
            // sufficient space to add event to page

            event_node * nevt = reinterpret_cast< event_node * >(&m_page.block[ n_free_end ]);
            nevt->p_event = e;

            if( obj == NULL ) {
                obj = reinterpret_cast< object_node * >(&m_page.block[m_page.header.free_start]);

                obj->object_id = object_id;
                m_page.header.free_start = n_free_start;

                nevt->next = BLOCK_SIZE;
            } else {
                // object already exists
                //
                nevt->next = obj->event_offset;
            }
            obj->event_offset = n_free_end;

            m_page.header.free_start = n_free_start;
            m_page.header.free_end = n_free_end;
        }

        return res;
    }

    void reset() {
        m_page.header.free_start = 0;
        m_page.header.free_end = BLOCK_SIZE;
    }

    void dump( std::ostream & out ) {}

protected:
    object_node * findObject( const object_t & object_id ) {
        if( m_page.header.free_start != 0 ) {
            object_node * fstart = reinterpret_cast< object_node *>( &m_page.block[m_page.header.free_start]);
            object_node * obj = reinterpret_cast< object_node *>(m_page.block);
            do {
                if( obj->object_id == object_id ) {
                    // consider swapping obj with start of the object node list
                    return obj;
                }
                obj++;
            } while( obj < fstart );

        }
        return NULL;
    }

    memory_page m_page;

    std::pair< object_node *, event_node * > m_cur_pair;
};
#endif  // EVENT_PAGE_HPP_
<commit_msg>Modified Event Page to make use of memory page header with pointers<commit_after>#ifndef EVENT_PAGE_HPP_
#define EVENT_PAGE_HPP_

#include "memory_page.h"

#include <ostream>

template < class EVT, class OBJ >
class EventPage {
public:
    typedef EVT event_t;
    typedef OBJ object_t;

    struct event_node {
        event_t *   p_event;
//        offset_t    next;
        event_node * next;
    };

    struct object_node {
        object_t object_id;
//        offset_t event_offset;
        event_node * enode;
    };

    typedef std::pair< object_node *, event_node * > next_event_t;

    EventPage() {}

    size_t getFreeSpace() const {
        return (m_page.header.free_end - m_page.header.free_start);
    }

    bool isFull() const {
        static const size_t buffer_zone_size = sizeof(object_node) + sizeof( event_node );
        return getFreeSpace() < buffer_zone_size;
    }

    bool addEvent( event_t * e, const object_t & object_id ) {
        if( isFull() ) return false;  // page full

        char * n_free_start = m_page.header.free_start;
        char * n_free_end = m_page.header.free_end - sizeof( event_node );

        object_node * obj = findObject( object_id );

        if( obj == NULL ) {
            // object does not exist on current page
            n_free_start += sizeof( object_node );
        }

        bool res = (n_free_start < n_free_end); // is there sufficient space to schedule event?
        if( res ) {
            // sufficient space to add event to page

            event_node * nevt = reinterpret_cast< event_node * >(n_free_end);
            nevt->p_event = e;

            if( obj == NULL ) {
                obj = reinterpret_cast< object_node * >(m_page.header.free_start);

                obj->object_id = object_id;

                nevt->next = NULL;
            } else {
                // object already exists
                //
                nevt->next = obj->enode;
            }
            obj->enode = nevt;

            m_page.header.free_start = n_free_start;
            m_page.header.free_end = n_free_end;
        }

        return res;
    }

    void reset() {
        m_page.clear();
    }

    void dump( std::ostream & out ) {
        out << "Object Node Size: " << sizeof(object_node) << "\n";
        out << "Event Node Size: " << sizeof(event_node) << "\n";

        if( m_page.header.free_start != m_page.block ) {
            object_node * onode = reinterpret_cast< object_node * >( m_page.block );
            void * stop = m_page.header.free_start;
            do {
                out << onode->object_id << ":\n";

                if( onode->enode != NULL ) {
                    event_node * enode = onode->enode;
                    do {
                        out << ((unsigned long) enode) << ":" << *(enode->p_event) << ",";
                        enode = enode->next;
                    } while( enode != NULL );
                    out << "\n";
                } else {
                    out << "Has no events\n";
                }
                onode++;
            } while( onode < stop );
        } else {
            out << "Page is empty\n";
        }
    }

protected:
    object_node * findObject( const object_t & object_id ) {
        if( m_page.header.free_start != m_page.block ) {
            object_node * obj = reinterpret_cast< object_node *>(m_page.block);
            object_node * stop = reinterpret_cast< object_node *>( m_page.header.free_start);
            do {
                if( obj->object_id == object_id ) {
                    // consider swapping obj with start of the object node list
                    return obj;
                }
                obj++;
            } while( obj < stop );

        }
        return NULL;
    }

    memory_page m_page;

    std::pair< object_node *, event_node * > m_cur_pair;
};
#endif  // EVENT_PAGE_HPP_
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2008 by Jason Ansel                                     *
 *   jansel@csail.mit.edu                                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "dynamictask.h"
#include "jasm.h"
#include "jtunable.h"

#include <pthread.h>

//#define PBCC_SEQUENTIAL
#define INLINE_NULL_TASKS

#define MIN_NUM_WORKERS  0
#define MAX_NUM_WORKERS  512
#define MIN_INLINE_TASK_SIZE  64
#define MAX_INLINE_TASK_SIZE  65536

JTUNABLE(tunerNumOfWorkers,   8, MIN_NUM_WORKERS, MAX_NUM_WORKERS);
JTUNABLE(tunerInlineTaskSize, 1024, MIN_INLINE_TASK_SIZE, MAX_INLINE_TASK_SIZE);

namespace hecura {

DynamicScheduler *DynamicTask::scheduler = NULL;
size_t            DynamicTask::firstSize = 0;
size_t            DynamicTask::maxSize   = 0;

DynamicTask::DynamicTask()
{
  // when this task is created, no other thread would touch it
  // so no lock for numOfPredecessor update
  state = S_NEW;
  numOfPredecessor = 0;

#ifndef PBCC_SEQUENTIAL
  // allocate scheduler when the first task is created
  if(scheduler == NULL) {
    scheduler = new DynamicScheduler();
    scheduler->startWorkerThreads(tunerNumOfWorkers);
  }
#endif
}

#ifdef PBCC_SEQUENTIAL
void DynamicTask::enqueue() { run();}
#else
void DynamicTask::enqueue()
{
  int preds;
  {
    JLOCKSCOPE(lock);
    preds=numOfPredecessor;
    if(preds==0)
      state=S_READY;
    else
      state=S_PENDING;
  }
  if(preds==0){
    inlineOrEnqueueTask();
  }
}
#endif // PBCC_SEQUENTIAL

#ifdef PBCC_SEQUENTIAL
void DynamicTask::dependsOn(const DynamicTaskPtr &that){}
#else
void DynamicTask::dependsOn(const DynamicTaskPtr &that)
{
  if(!that) return;
  JASSERT(that!=this).Text("task cant depend on itself");
  JASSERT(state==S_NEW)(state).Text(".dependsOn must be called before enqueue()");
  that->lock.lock();
  if(that->state == S_CONTINUED){
    that->lock.unlock();
    dependsOn(that->continuation);
  }else if(that->state != S_COMPLETE){
    that->dependents.push_back(this);
    {
      JLOCKSCOPE(lock);
      numOfPredecessor++;
    }
    that->lock.unlock();
  }else{
    that->lock.unlock();
  }
#ifdef VERBOSE
    printf("thread %d: task %p depends on task %p counter: %d\n", pthread_self(), this, that.asPtr(), numOfPredecessor);
#endif
}
#endif // PBCC_SEQUENTIAL

void hecura::DynamicTask::decrementPredecessors(){
  bool shouldEnqueue = false;
  {
    JLOCKSCOPE(lock);
    if(--numOfPredecessor==0 && state==S_PENDING){
      state = S_READY;
      shouldEnqueue = true;
    }
  }
  if(shouldEnqueue){
    inlineOrEnqueueTask();
  }
}

void hecura::DynamicTask::runWrapper(){
  JASSERT(state==S_READY && numOfPredecessor==0)(state)(numOfPredecessor);
  continuation = run();

  std::vector<DynamicTaskPtr> tmp;

  {
    JLOCKSCOPE(lock);
    dependents.swap(tmp);
    if(continuation) state = S_CONTINUED;
    else             state = S_COMPLETE;
  }

  if(continuation){
#ifdef VERBOSE
    JTRACE("task complete, continued")(tmp.size());
#endif
    {
      JLOCKSCOPE(continuation->lock);
      if(continuation->dependents.empty()){
        //swap is faster than insert
        continuation->dependents.swap(tmp);
      }else{
        continuation->dependents.insert(continuation->dependents.end(), tmp.begin(), tmp.end());
      }
    }
    continuation->enqueue();
  }else{
    #ifdef VERBOSE
    if(!isNullTask()) JTRACE("task complete")(tmp.size());
    #endif
    std::vector<DynamicTaskPtr>::iterator it;
    for(it = tmp.begin(); it != tmp.end(); ++it) {
      (*it)->decrementPredecessors();
    }
  }
}

#ifdef PBCC_SEQUENTIAL
void DynamicTask::waitUntilComplete() {}
#else
void DynamicTask::waitUntilComplete()
{
  bool ready = false;
  lock.lock();
  while(state != S_COMPLETE && state!= S_CONTINUED) {
    lock.unlock();
    // get a task for execution
    scheduler->popAndRunOneTask(false);
    lock.lock();
  }
  lock.unlock();
  if(state == S_CONTINUED)
    continuation->waitUntilComplete();
}
#endif // PBCC_SEQUENTIAL

///
/// check if the task should be enqueued of inlined
/// heuristics to check if task should be inlined
/// 1. fixed task size threshold
/// 2. function of input size
/// 3. function of max task size
/// 4. number of items in queue
/// 5. mix of above
bool DynamicTask::inlineTask()
{
  size_t taskSize = size();
  // if too small, inline
  if(isNullTask() || taskSize < tunerInlineTaskSize)
    return true;

  // if large task, do not inline
//   if(maxSize  < taskSize) {
//     maxSize   = taskSize;
//     return false;
//   }

  // if no tasks in queue, do not inline
  // this is to increase parallelism
//   if(scheduler->empty())
//     return false;

  // if task size is very small relative to max task, inline
//   if(taskSize < (maxSize >> 8))
//     return true;

  return false;
}

void DynamicTask::inlineOrEnqueueTask()
{
#ifdef INLINE_NULL_TASKS
  if(inlineTask()){
//     static __thread int inlineCount=0;
//     if(inlineCount<100){
//      ++inlineCount;
//      runWrapper(); //dont bother enqueuing just run it
//      --inlineCount;
//     }else{
      //push it in local queue
      DynamicScheduler::myThreadLocalQueue().push_back(this);
//     }
  }else
#endif
  {
    scheduler->enqueue(this);
  }
}

}
<commit_msg>Change min inlinetasksize to 1<commit_after>/***************************************************************************
 *   Copyright (C) 2008 by Jason Ansel                                     *
 *   jansel@csail.mit.edu                                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "dynamictask.h"
#include "jasm.h"
#include "jtunable.h"

#include <pthread.h>

//#define PBCC_SEQUENTIAL
#define INLINE_NULL_TASKS

#define MIN_NUM_WORKERS  0
#define MAX_NUM_WORKERS  512
#define MIN_INLINE_TASK_SIZE  1
#define MAX_INLINE_TASK_SIZE  65536

JTUNABLE(tunerNumOfWorkers,   8, MIN_NUM_WORKERS, MAX_NUM_WORKERS);
JTUNABLE(tunerInlineTaskSize, 1024, MIN_INLINE_TASK_SIZE, MAX_INLINE_TASK_SIZE);

namespace hecura {

DynamicScheduler *DynamicTask::scheduler = NULL;
size_t            DynamicTask::firstSize = 0;
size_t            DynamicTask::maxSize   = 0;

DynamicTask::DynamicTask()
{
  // when this task is created, no other thread would touch it
  // so no lock for numOfPredecessor update
  state = S_NEW;
  numOfPredecessor = 0;

#ifndef PBCC_SEQUENTIAL
  // allocate scheduler when the first task is created
  if(scheduler == NULL) {
    scheduler = new DynamicScheduler();
    scheduler->startWorkerThreads(tunerNumOfWorkers);
  }
#endif
}

#ifdef PBCC_SEQUENTIAL
void DynamicTask::enqueue() { run();}
#else
void DynamicTask::enqueue()
{
  int preds;
  {
    JLOCKSCOPE(lock);
    preds=numOfPredecessor;
    if(preds==0)
      state=S_READY;
    else
      state=S_PENDING;
  }
  if(preds==0){
    inlineOrEnqueueTask();
  }
}
#endif // PBCC_SEQUENTIAL

#ifdef PBCC_SEQUENTIAL
void DynamicTask::dependsOn(const DynamicTaskPtr &that){}
#else
void DynamicTask::dependsOn(const DynamicTaskPtr &that)
{
  if(!that) return;
  JASSERT(that!=this).Text("task cant depend on itself");
  JASSERT(state==S_NEW)(state).Text(".dependsOn must be called before enqueue()");
  that->lock.lock();
  if(that->state == S_CONTINUED){
    that->lock.unlock();
    dependsOn(that->continuation);
  }else if(that->state != S_COMPLETE){
    that->dependents.push_back(this);
    {
      JLOCKSCOPE(lock);
      numOfPredecessor++;
    }
    that->lock.unlock();
  }else{
    that->lock.unlock();
  }
#ifdef VERBOSE
    printf("thread %d: task %p depends on task %p counter: %d\n", pthread_self(), this, that.asPtr(), numOfPredecessor);
#endif
}
#endif // PBCC_SEQUENTIAL

void hecura::DynamicTask::decrementPredecessors(){
  bool shouldEnqueue = false;
  {
    JLOCKSCOPE(lock);
    if(--numOfPredecessor==0 && state==S_PENDING){
      state = S_READY;
      shouldEnqueue = true;
    }
  }
  if(shouldEnqueue){
    inlineOrEnqueueTask();
  }
}

void hecura::DynamicTask::runWrapper(){
  JASSERT(state==S_READY && numOfPredecessor==0)(state)(numOfPredecessor);
  continuation = run();

  std::vector<DynamicTaskPtr> tmp;

  {
    JLOCKSCOPE(lock);
    dependents.swap(tmp);
    if(continuation) state = S_CONTINUED;
    else             state = S_COMPLETE;
  }

  if(continuation){
#ifdef VERBOSE
    JTRACE("task complete, continued")(tmp.size());
#endif
    {
      JLOCKSCOPE(continuation->lock);
      if(continuation->dependents.empty()){
        //swap is faster than insert
        continuation->dependents.swap(tmp);
      }else{
        continuation->dependents.insert(continuation->dependents.end(), tmp.begin(), tmp.end());
      }
    }
    continuation->enqueue();
  }else{
    #ifdef VERBOSE
    if(!isNullTask()) JTRACE("task complete")(tmp.size());
    #endif
    std::vector<DynamicTaskPtr>::iterator it;
    for(it = tmp.begin(); it != tmp.end(); ++it) {
      (*it)->decrementPredecessors();
    }
  }
}

#ifdef PBCC_SEQUENTIAL
void DynamicTask::waitUntilComplete() {}
#else
void DynamicTask::waitUntilComplete()
{
  bool ready = false;
  lock.lock();
  while(state != S_COMPLETE && state!= S_CONTINUED) {
    lock.unlock();
    // get a task for execution
    scheduler->popAndRunOneTask(false);
    lock.lock();
  }
  lock.unlock();
  if(state == S_CONTINUED)
    continuation->waitUntilComplete();
}
#endif // PBCC_SEQUENTIAL

///
/// check if the task should be enqueued of inlined
/// heuristics to check if task should be inlined
/// 1. fixed task size threshold
/// 2. function of input size
/// 3. function of max task size
/// 4. number of items in queue
/// 5. mix of above
bool DynamicTask::inlineTask()
{
  size_t taskSize = size();
  // if too small, inline
  if(isNullTask() || taskSize < tunerInlineTaskSize)
    return true;

  // if large task, do not inline
//   if(maxSize  < taskSize) {
//     maxSize   = taskSize;
//     return false;
//   }

  // if no tasks in queue, do not inline
  // this is to increase parallelism
//   if(scheduler->empty())
//     return false;

  // if task size is very small relative to max task, inline
//   if(taskSize < (maxSize >> 8))
//     return true;

  return false;
}

void DynamicTask::inlineOrEnqueueTask()
{
#ifdef INLINE_NULL_TASKS
  if(inlineTask()){
//     static __thread int inlineCount=0;
//     if(inlineCount<100){
//      ++inlineCount;
//      runWrapper(); //dont bother enqueuing just run it
//      --inlineCount;
//     }else{
      //push it in local queue
      DynamicScheduler::myThreadLocalQueue().push_back(this);
//     }
  }else
#endif
  {
    scheduler->enqueue(this);
  }
}

}
<|endoftext|>


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

#pragma once

#include "etl/impl/cublas/cuda.hpp"

namespace etl {

#ifdef ETL_CUDA
template<typename T>
using gpu_handler = impl::cuda::cuda_memory<T>;
#else
template<typename>
using gpu_handler = int;
#endif

/*!
 * \brief Wrapper for opaque memory.
 *
 * This is used to give direct memory access to any expressions
 * without showing the complete type, acting as a form of type
 * erasure
 */
template <typename T, std::size_t D>
struct opaque_memory {
    static constexpr std::size_t n_dimensions = D; ///< The number of dimensions

    using value_type        = T;                    ///< The type of value
    using memory_type       = T*;                   ///< The type of memory
    using const_memory_type = std::add_const_t<T>*; ///< The type of const memory

private:
    T* memory;                             ///< The memory pointer
    const std::size_t etl_size;            ///< The full size of the matrix
    const std::array<std::size_t, D> dims; ///< The dimensions of the matrix
    gpu_handler<T>& _gpu_memory_handler;   ///< The GPU memory handler
    const order storage_order;             ///< The storage order

public:
    /*!
     * \brief Create a new opaque memory
     * \param memory The pointer to memory
     * \param size The size of the memory
     * \param dims The dimensions
     * \param handler The GPU memory handler
     * \param storage_order The Storage order
     */
    opaque_memory(const T* memory, std::size_t size, const std::array<std::size_t, D>& dims, const gpu_handler<T>& handler, order storage_order)
            : memory(const_cast<T*>(memory)),
              etl_size(size),
              dims(dims),
              _gpu_memory_handler(const_cast<gpu_handler<T>&>(handler)),
              storage_order(storage_order) {
        //Nothing else to init
    }

    /*!
     * \brief Returns the handler for GPU memory
     * \return a reference to the GPU memory handler
     */
    gpu_handler<T>& get_gpu_handler() noexcept {
        return _gpu_memory_handler;
    }

#ifdef ETL_CUDA
private:
    /*!
     * \brief Allocate memory on the GPU for the expression
     */
    void gpu_allocate_impl() const {
        cpp_assert(!is_gpu_allocated(), "Trying to allocate already allocated GPU memory");

        _gpu_memory_handler = impl::cuda::cuda_allocate_only<T>(etl_size);

        inc_counter("gpu:allocate");
    }

    /*!
     * \brief Copy back from the CPU to the GPU
     */
    void cpu_to_gpu() const {
        cpp_assert(is_gpu_allocated(), "Cannot copy to unallocated GPU memory");
        cpp_assert(!_gpu_memory_handler.gpu_up_to_date, "Copy must only be done if necessary");
        cpp_assert(_gpu_memory_handler.cpu_up_to_date, "Copy from invalid memory!");

        auto* gpu_ptr = gpu_memory();
        auto* cpu_ptr = memory;

        cuda_check(cudaMemcpy(
            const_cast<std::remove_const_t<value_type>*>(gpu_ptr),
            const_cast<std::remove_const_t<value_type>*>(cpu_ptr),
            etl_size * sizeof(T), cudaMemcpyHostToDevice));

        _gpu_memory_handler.gpu_up_to_date = true;

        inc_counter("gpu:cpu_to_gpu");
    }

    /*!
     * \brief Copy back from the GPU to the expression memory.
     */
    void gpu_to_cpu() const {
        cpp_assert(is_gpu_allocated(), "Cannot copy from unallocated GPU memory()");
        cpp_assert(_gpu_memory_handler.gpu_up_to_date, "Cannot copy from invalid memory");
        cpp_assert(!_gpu_memory_handler.cpu_up_to_date, "Copy done without reason");

        auto* gpu_ptr = gpu_memory();
        auto* cpu_ptr = memory;

        cpp_assert(!std::is_const<std::remove_pointer_t<decltype(gpu_ptr)>>::value, "copy_from should not be used on const memory");
        cpp_assert(!std::is_const<value_type>::value, "copy_from should not be used on const memory");

        cuda_check(cudaMemcpy(
            const_cast<std::remove_const_t<value_type>*>(cpu_ptr),
            const_cast<std::remove_const_t<value_type>*>(gpu_ptr),
            etl_size * sizeof(T), cudaMemcpyDeviceToHost));

        _gpu_memory_handler.cpu_up_to_date = true;

        inc_counter("gpu:gpu_to_cpu");
    }

public:

    /*!
     * \brief Indicates if the expression is allocated in GPU.
     * \return true if the expression is allocated in GPU, false otherwise
     */
    bool is_gpu_allocated() const noexcept {
        return _gpu_memory_handler.is_set();
    }

    /*!
     * \brief Return GPU memory of this expression, if any.
     * \return a pointer to the GPU memory or nullptr if not allocated in GPU.
     */
    value_type* gpu_memory() const noexcept {
        return _gpu_memory_handler.get();
    }

    /*!
     * \brief Evict the expression from GPU.
     */
    void gpu_evict() const noexcept {
        if (is_gpu_allocated()) {
            _gpu_memory_handler.reset();
        }

        invalidate_gpu();
    }

    /*!
     * \brief Invalidates the CPU memory
     */
    void invalidate_cpu() const noexcept {
        _gpu_memory_handler.cpu_up_to_date = false;
    }

    /*!
     * \brief Invalidates the GPU memory
     */
    void invalidate_gpu() const noexcept {
        _gpu_memory_handler.gpu_up_to_date = false;
    }

    /*!
     * \brief Ensures that the GPU memory is allocated and that the GPU memory
     * is up to date (to undefined value).
     */
    void ensure_gpu_allocated() const {
        if (!is_gpu_allocated()) {
            gpu_allocate_impl();
        }

        _gpu_memory_handler.gpu_up_to_date = true;
    }

    /*!
     * \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
     */
    void ensure_gpu_up_to_date() const {
        // Make sure there is some memory allocate
        if (!is_gpu_allocated()) {
            gpu_allocate_impl();
        }

        if(!_gpu_memory_handler.gpu_up_to_date){
            cpu_to_gpu();
        }
    }

    /*!
     * \brief Copy back from the GPU to the expression memory if
     * necessary.
     */
    void ensure_cpu_up_to_date() const {
        if(!_gpu_memory_handler.cpu_up_to_date){
            gpu_to_cpu();
        }
    }

    void transfer_to(opaque_memory& rhs){
        rhs._gpu_memory_handler = std::move(_gpu_memory_handler);

        // The memory was transferred, not up to date anymore
        _gpu_memory_handler.gpu_up_to_date = false;

        // The target is up to date on GPU but CPU is not to date anymore
        rhs._gpu_memory_handler.gpu_up_to_date = true;
        rhs._gpu_memory_handler.cpu_up_to_date = false;
    }
#else
    /*!
     * \brief Indicates if the expression is allocated in GPU.
     * \return true if the expression is allocated in GPU, false otherwise
     */
    bool is_gpu_allocated() const noexcept {
        return false;
    }

    /*!
     * \brief Evict the expression from GPU.
     */
    void gpu_evict() const noexcept {}

    /*!
     * \brief Return GPU memory of this expression, if any.
     * \return a pointer to the GPU memory or nullptr if not allocated in GPU.
     */
    value_type* gpu_memory() const noexcept {
        return nullptr;
    }

    /*!
     * \brief Allocate memory on the GPU for the expression, only if not already allocated
     */
    void ensure_gpu_allocated() const {}

    /*!
     * \brief Copy back from the GPU to the expression memory if
     * necessary.
     */
    void ensure_gpu_up_to_date() const {}

    /*!
     * \brief Copy back from the GPU to the expression memory.
     */
    void ensure_cpu_up_to_date() const {}

    void invalidate_gpu() const {}
    void invalidate_cpu() const {}

    /*!
     * \brief Reallocate the GPU memory.
     * \param memory The new GPU memory (will be moved)
     */
    void gpu_reallocate(impl::cuda::cuda_memory<T>&& memory) {
        cpp_unused(memory);
    }

    /*!
     * \brief Release the GPU memory for another expression to use
     * \return A rvalue reference to the gpu_memory_handler.
     */
    impl::cuda::cuda_memory<T>&& gpu_release() const {}
#endif
};

} //end of namespace etl
<commit_msg>Reduce visibility<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "etl/impl/cublas/cuda.hpp"

namespace etl {

#ifdef ETL_CUDA
template<typename T>
using gpu_handler = impl::cuda::cuda_memory<T>;
#else
template<typename>
using gpu_handler = int;
#endif

/*!
 * \brief Wrapper for opaque memory.
 *
 * This is used to give direct memory access to any expressions
 * without showing the complete type, acting as a form of type
 * erasure
 */
template <typename T, std::size_t D>
struct opaque_memory {
    static constexpr std::size_t n_dimensions = D; ///< The number of dimensions

    using value_type        = T;                    ///< The type of value
    using memory_type       = T*;                   ///< The type of memory
    using const_memory_type = std::add_const_t<T>*; ///< The type of const memory

private:
    T* memory;                             ///< The memory pointer
    const std::size_t etl_size;            ///< The full size of the matrix
    const std::array<std::size_t, D> dims; ///< The dimensions of the matrix
    gpu_handler<T>& _gpu_memory_handler;   ///< The GPU memory handler
    const order storage_order;             ///< The storage order

public:
    /*!
     * \brief Create a new opaque memory
     * \param memory The pointer to memory
     * \param size The size of the memory
     * \param dims The dimensions
     * \param handler The GPU memory handler
     * \param storage_order The Storage order
     */
    opaque_memory(const T* memory, std::size_t size, const std::array<std::size_t, D>& dims, const gpu_handler<T>& handler, order storage_order)
            : memory(const_cast<T*>(memory)),
              etl_size(size),
              dims(dims),
              _gpu_memory_handler(const_cast<gpu_handler<T>&>(handler)),
              storage_order(storage_order) {
        //Nothing else to init
    }

    /*!
     * \brief Returns the handler for GPU memory
     * \return a reference to the GPU memory handler
     */
    gpu_handler<T>& get_gpu_handler() noexcept {
        return _gpu_memory_handler;
    }

#ifdef ETL_CUDA
private:
    /*!
     * \brief Allocate memory on the GPU for the expression
     */
    void gpu_allocate_impl() const {
        cpp_assert(!is_gpu_allocated(), "Trying to allocate already allocated GPU memory");

        _gpu_memory_handler = impl::cuda::cuda_allocate_only<T>(etl_size);

        inc_counter("gpu:allocate");
    }

    /*!
     * \brief Copy back from the CPU to the GPU
     */
    void cpu_to_gpu() const {
        cpp_assert(is_gpu_allocated(), "Cannot copy to unallocated GPU memory");
        cpp_assert(!_gpu_memory_handler.gpu_up_to_date, "Copy must only be done if necessary");
        cpp_assert(_gpu_memory_handler.cpu_up_to_date, "Copy from invalid memory!");

        auto* gpu_ptr = gpu_memory();
        auto* cpu_ptr = memory;

        cuda_check(cudaMemcpy(
            const_cast<std::remove_const_t<value_type>*>(gpu_ptr),
            const_cast<std::remove_const_t<value_type>*>(cpu_ptr),
            etl_size * sizeof(T), cudaMemcpyHostToDevice));

        _gpu_memory_handler.gpu_up_to_date = true;

        inc_counter("gpu:cpu_to_gpu");
    }

    /*!
     * \brief Copy back from the GPU to the expression memory.
     */
    void gpu_to_cpu() const {
        cpp_assert(is_gpu_allocated(), "Cannot copy from unallocated GPU memory()");
        cpp_assert(_gpu_memory_handler.gpu_up_to_date, "Cannot copy from invalid memory");
        cpp_assert(!_gpu_memory_handler.cpu_up_to_date, "Copy done without reason");

        auto* gpu_ptr = gpu_memory();
        auto* cpu_ptr = memory;

        cpp_assert(!std::is_const<std::remove_pointer_t<decltype(gpu_ptr)>>::value, "copy_from should not be used on const memory");
        cpp_assert(!std::is_const<value_type>::value, "copy_from should not be used on const memory");

        cuda_check(cudaMemcpy(
            const_cast<std::remove_const_t<value_type>*>(cpu_ptr),
            const_cast<std::remove_const_t<value_type>*>(gpu_ptr),
            etl_size * sizeof(T), cudaMemcpyDeviceToHost));

        _gpu_memory_handler.cpu_up_to_date = true;

        inc_counter("gpu:gpu_to_cpu");
    }

    /*!
     * \brief Indicates if the expression is allocated in GPU.
     * \return true if the expression is allocated in GPU, false otherwise
     */
    bool is_gpu_allocated() const noexcept {
        return _gpu_memory_handler.is_set();
    }

public:

    /*!
     * \brief Return GPU memory of this expression, if any.
     * \return a pointer to the GPU memory or nullptr if not allocated in GPU.
     */
    value_type* gpu_memory() const noexcept {
        return _gpu_memory_handler.get();
    }

    /*!
     * \brief Evict the expression from GPU.
     */
    void gpu_evict() const noexcept {
        if (is_gpu_allocated()) {
            _gpu_memory_handler.reset();
        }

        invalidate_gpu();
    }

    /*!
     * \brief Invalidates the CPU memory
     */
    void invalidate_cpu() const noexcept {
        _gpu_memory_handler.cpu_up_to_date = false;
    }

    /*!
     * \brief Invalidates the GPU memory
     */
    void invalidate_gpu() const noexcept {
        _gpu_memory_handler.gpu_up_to_date = false;
    }

    /*!
     * \brief Ensures that the GPU memory is allocated and that the GPU memory
     * is up to date (to undefined value).
     */
    void ensure_gpu_allocated() const {
        if (!is_gpu_allocated()) {
            gpu_allocate_impl();
        }

        _gpu_memory_handler.gpu_up_to_date = true;
    }

    /*!
     * \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
     */
    void ensure_gpu_up_to_date() const {
        // Make sure there is some memory allocate
        if (!is_gpu_allocated()) {
            gpu_allocate_impl();
        }

        if(!_gpu_memory_handler.gpu_up_to_date){
            cpu_to_gpu();
        }
    }

    /*!
     * \brief Copy back from the GPU to the expression memory if
     * necessary.
     */
    void ensure_cpu_up_to_date() const {
        if(!_gpu_memory_handler.cpu_up_to_date){
            gpu_to_cpu();
        }
    }

    void transfer_to(opaque_memory& rhs){
        rhs._gpu_memory_handler = std::move(_gpu_memory_handler);

        // The memory was transferred, not up to date anymore
        _gpu_memory_handler.gpu_up_to_date = false;

        // The target is up to date on GPU but CPU is not to date anymore
        rhs._gpu_memory_handler.gpu_up_to_date = true;
        rhs._gpu_memory_handler.cpu_up_to_date = false;
    }
#else
    /*!
     * \brief Indicates if the expression is allocated in GPU.
     * \return true if the expression is allocated in GPU, false otherwise
     */
    bool is_gpu_allocated() const noexcept {
        return false;
    }

    /*!
     * \brief Evict the expression from GPU.
     */
    void gpu_evict() const noexcept {}

    /*!
     * \brief Return GPU memory of this expression, if any.
     * \return a pointer to the GPU memory or nullptr if not allocated in GPU.
     */
    value_type* gpu_memory() const noexcept {
        return nullptr;
    }

    /*!
     * \brief Allocate memory on the GPU for the expression, only if not already allocated
     */
    void ensure_gpu_allocated() const {}

    /*!
     * \brief Copy back from the GPU to the expression memory if
     * necessary.
     */
    void ensure_gpu_up_to_date() const {}

    /*!
     * \brief Copy back from the GPU to the expression memory.
     */
    void ensure_cpu_up_to_date() const {}

    void invalidate_gpu() const {}
    void invalidate_cpu() const {}

    /*!
     * \brief Reallocate the GPU memory.
     * \param memory The new GPU memory (will be moved)
     */
    void gpu_reallocate(impl::cuda::cuda_memory<T>&& memory) {
        cpp_unused(memory);
    }

    /*!
     * \brief Release the GPU memory for another expression to use
     * \return A rvalue reference to the gpu_memory_handler.
     */
    impl::cuda::cuda_memory<T>&& gpu_release() const {}
#endif
};

} //end of namespace etl
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009-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.
 */

#ifndef LIBPORT_INSTRUMENT_HH
# define LIBPORT_INSTRUMENT_HH

# include <libport/config.h>
# include <libport/preproc.hh>

// Keep NVALGRIND and USE_VALGRIND consistent.  Prefer NVALGRIND.
// NVALGRIND overrides USE_VALGRIND.
# if defined NVALGRIND
#  undef USE_VALGRIND
# endif

// USE_VALGRIND disables Valgrind.
# if ! defined USE_VALGRIND
#  define NVALGRIND 1
# endif

# ifdef LIBPORT_HAVE_VALGRIND_VALGRIND_H
// Load these even if NVALGRIND, as it takes care itself of disabling
// itself.
#  include <valgrind/valgrind.h>
#  include <valgrind/memcheck.h>
# else
#  define RUNNING_ON_VALGRIND 0
# endif

/*-------------.
| INSTRUMENT.  |
`-------------*/

# if defined NVALGRIND
#  define INSTRUMENTFLAGS(Flags) LIBPORT_EMPTY()
# else
#  define INSTRUMENTFLAGS(Flags)					\
  const char* LIBPORT_CAT(libport_instrument, __LINE__) =		\
    "INSTRUMENTFLAGS=" __HERE__ ":" #Flags
# endif

# define INSTRUMENT_DISABLE()                   \
  INSTRUMENTFLAGS(--mode=none)

/*--------------------------------.
| Valgrind Memory Access Rights.  |
`--------------------------------*/

// These macros are used to ensure that no other part of the program can
// access the variables.  This are means to check for bad memory writes
// which are made on specific variables.
# if defined NVALGRIND
#  define MEM(Right, Addr, Size)          LIBPORT_EMPTY()
# else
#  define MEM(Right, Addr, Size)                        \
  LIBPORT_CAT(VALGRIND_MAKE_MEM_, Right) (Addr, Size)
# endif

# define POOL_CREATE(Pool, RedZone, Init)      \
  VALGRIND_CREATE_MEMPOOL(Pool, RedZone, Init)

# define POOL_ALLOC(Pool, Addr, Size)          \
  VALGRIND_MEMPOOL_ALLOC(Pool, Addr, Size)

# define POOL_FREE(Pool, Addr)			\
  VALGRIND_MEMPOOL_FREE(Pool, Addr)

# define MEM_NOACCESS(Addr, Size)  MEM(NOACCESS, Addr, Size)
# define MEM_UNDEFINED(Addr, Size) MEM(UNDEFINED, Addr, Size)
# define MEM_DEFINED(Addr, Size)   MEM(DEFINED, Addr, Size)

# define VAR_NOACCESS(Val)  MEM_NOACCESS(&Val, sizeof(Val))
# define VAR_UNDEFINED(Val) MEM_UNDEFINED(&Val, sizeof(Val))
# define VAR_DEFINED(Val)   MEM_DEFINED(&Val, sizeof(Val))

#endif
<commit_msg>Libport.Instrument: fixes.<commit_after>/*
 * Copyright (C) 2009-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.
 */

#ifndef LIBPORT_INSTRUMENT_HH
# define LIBPORT_INSTRUMENT_HH

# include <libport/config.h>
# include <libport/preproc.hh>

// Keep NVALGRIND and USE_VALGRIND consistent.  Prefer NVALGRIND.
// NVALGRIND overrides USE_VALGRIND.
# if defined NVALGRIND
#  undef USE_VALGRIND
# endif

// USE_VALGRIND disables Valgrind.
# if ! defined USE_VALGRIND
#  define NVALGRIND 1
# endif

# ifdef LIBPORT_HAVE_VALGRIND_VALGRIND_H
// Load these even if NVALGRIND, as it takes care itself of disabling
// itself.
#  include <valgrind/valgrind.h>
#  include <valgrind/memcheck.h>
# else
#  define RUNNING_ON_VALGRIND 0
# endif

/*-------------.
| INSTRUMENT.  |
`-------------*/

# if defined NVALGRIND
#  define INSTRUMENTFLAGS(Flags) LIBPORT_EMPTY
# else
#  define INSTRUMENTFLAGS(Flags)					\
  const char* LIBPORT_CAT(libport_instrument, __LINE__) =		\
    "INSTRUMENTFLAGS=" __HERE__ ":" #Flags
# endif

# define INSTRUMENT_DISABLE()                   \
  INSTRUMENTFLAGS(--mode=none)

/*--------------------------------.
| Valgrind Memory Access Rights.  |
`--------------------------------*/

// These macros are used to ensure that no other part of the program can
// access the variables.  This are means to check for bad memory writes
// which are made on specific variables.
# if defined NVALGRIND
#  define MEM(Right, Addr, Size)           LIBPORT_NOP
#  define POOL_CREATE(Pool, RedZone, Init) LIBPORT_NOP
#  define POOL_ALLOC(Pool, Addr, Size)     LIBPORT_NOP
#  define POOL_FREE(Pool, Addr)		   LIBPORT_NOP
# else
#  define MEM(Right, Addr, Size)                        \
  LIBPORT_CAT(VALGRIND_MAKE_MEM_, Right) (Addr, Size)
# define POOL_CREATE(Pool, RedZone, Init)	\
  VALGRIND_CREATE_MEMPOOL(Pool, RedZone, Init)
# define POOL_ALLOC(Pool, Addr, Size)		\
  VALGRIND_MEMPOOL_ALLOC(Pool, Addr, Size)
# define POOL_FREE(Pool, Addr)			\
  VALGRIND_MEMPOOL_FREE(Pool, Addr)
# endif

# define MEM_NOACCESS(Addr, Size)  MEM(NOACCESS, Addr, Size)
# define MEM_UNDEFINED(Addr, Size) MEM(UNDEFINED, Addr, Size)
# define MEM_DEFINED(Addr, Size)   MEM(DEFINED, Addr, Size)

# define VAR_NOACCESS(Val)  MEM_NOACCESS(&Val, sizeof(Val))
# define VAR_UNDEFINED(Val) MEM_UNDEFINED(&Val, sizeof(Val))
# define VAR_DEFINED(Val)   MEM_DEFINED(&Val, sizeof(Val))

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif

#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif

#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif

#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif

#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif

#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
	if (str == 0) return 0;
	char* tmp = (char*)malloc(strlen(str) + 1);
	if (tmp == 0) return 0;
	strcpy(tmp, str);
	return tmp;
}
#endif

// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>fix minor mingw issue<commit_after>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _MSC_VER
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif

#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif

#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif

#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif

#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif

#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
	if (str == 0) return 0;
	char* tmp = (char*)malloc(strlen(str) + 1);
	if (tmp == 0) return 0;
	strcpy(tmp, str);
	return tmp;
}
#endif

// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_DATASOURCE_HPP
#define MAPNIK_DATASOURCE_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/params.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/query.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/noncopyable.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>

// stl
#include <map>
#include <string>

namespace mapnik {

struct MAPNIK_DECL Featureset : private mapnik::noncopyable
{
    virtual feature_ptr next() = 0;
    virtual ~Featureset() {}
};

typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;

class MAPNIK_DECL datasource_exception : public std::exception
{
public:
    datasource_exception(std::string const& message)
      : message_(message)
    {
    }

    ~datasource_exception() throw()
    {
    }

    virtual const char* what() const throw()
    {
        return message_.c_str();
    }
private:
    std::string message_;
};

class MAPNIK_DECL datasource : private mapnik::noncopyable
{
public:
    enum datasource_t {
        Vector,
        Raster
    };

    enum geometry_t {
        Point = 1,
        LineString = 2,
        Polygon = 3,
        Collection = 4
    };

    datasource (parameters const& params)
       : params_(params) {}

    /*!
     * @brief Get the configuration parameters of the data source.
     *
     * These vary depending on the type of data source.
     *
     * @return The configuration parameters of the data source.
     */
    parameters const& params() const
    {
        return params_;
    }

    /*!
     * @brief Get the type of the datasource
     * @return The type of the datasource (Vector or Raster)
     */
    virtual datasource_t type() const = 0;
    virtual featureset_ptr features(query const& q) const = 0;
    virtual featureset_ptr features_at_point(coord2d const& pt, double tol = 0) const = 0;
    virtual box2d<double> envelope() const = 0;
    virtual boost::optional<geometry_t> get_geometry_type() const = 0;
    virtual layer_descriptor get_descriptor() const = 0;
    virtual ~datasource() {}
protected:
    parameters params_;
};

typedef const char * datasource_name();
typedef datasource* create_ds(parameters const& params);
typedef void destroy_ds(datasource *ds);

class datasource_deleter
{
public:
    void operator() (datasource* ds)
    {
        delete ds;
    }
};

typedef boost::shared_ptr<datasource> datasource_ptr;

#define DATASOURCE_PLUGIN(classname)                                    \
    extern "C" MAPNIK_EXP const char * datasource_name()                \
    {                                                                   \
        return classname::name();                                       \
    }                                                                   \
    extern "C"  MAPNIK_EXP datasource* create(parameters const& params) \
    {                                                                   \
        return new classname(params);                                   \
    }                                                                   \
    extern "C" MAPNIK_EXP void destroy(datasource *ds)                  \
    {                                                                   \
        delete ds;                                                      \
    }

}

#endif // MAPNIK_DATASOURCE_HPP
<commit_msg>expose nonconst access to datasource parameters<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_DATASOURCE_HPP
#define MAPNIK_DATASOURCE_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/params.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/query.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/noncopyable.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>

// stl
#include <map>
#include <string>

namespace mapnik {

struct MAPNIK_DECL Featureset : private mapnik::noncopyable
{
    virtual feature_ptr next() = 0;
    virtual ~Featureset() {}
};

typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;

class MAPNIK_DECL datasource_exception : public std::exception
{
public:
    datasource_exception(std::string const& message)
      : message_(message)
    {
    }

    ~datasource_exception() throw()
    {
    }

    virtual const char* what() const throw()
    {
        return message_.c_str();
    }
private:
    std::string message_;
};

class MAPNIK_DECL datasource : private mapnik::noncopyable
{
public:
    enum datasource_t {
        Vector,
        Raster
    };

    enum geometry_t {
        Point = 1,
        LineString = 2,
        Polygon = 3,
        Collection = 4
    };

    datasource (parameters const& params)
       : params_(params) {}

    /*!
     * @brief Get the configuration parameters of the data source.
     *
     * These vary depending on the type of data source.
     *
     * @return The configuration parameters of the data source.
     */
    parameters const& params() const
    {
        return params_;
    }

    parameters & params()
    {
        return params_;
    }

    /*!
     * @brief Get the type of the datasource
     * @return The type of the datasource (Vector or Raster)
     */
    virtual datasource_t type() const = 0;
    virtual featureset_ptr features(query const& q) const = 0;
    virtual featureset_ptr features_at_point(coord2d const& pt, double tol = 0) const = 0;
    virtual box2d<double> envelope() const = 0;
    virtual boost::optional<geometry_t> get_geometry_type() const = 0;
    virtual layer_descriptor get_descriptor() const = 0;
    virtual ~datasource() {}
protected:
    parameters params_;
};

typedef const char * datasource_name();
typedef datasource* create_ds(parameters const& params);
typedef void destroy_ds(datasource *ds);

class datasource_deleter
{
public:
    void operator() (datasource* ds)
    {
        delete ds;
    }
};

typedef boost::shared_ptr<datasource> datasource_ptr;

#define DATASOURCE_PLUGIN(classname)                                    \
    extern "C" MAPNIK_EXP const char * datasource_name()                \
    {                                                                   \
        return classname::name();                                       \
    }                                                                   \
    extern "C"  MAPNIK_EXP datasource* create(parameters const& params) \
    {                                                                   \
        return new classname(params);                                   \
    }                                                                   \
    extern "C" MAPNIK_EXP void destroy(datasource *ds)                  \
    {                                                                   \
        delete ds;                                                      \
    }

}

#endif // MAPNIK_DATASOURCE_HPP
<|endoftext|>


<commit_before>/*
 * VTUtils.hpp
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Jun 3, 2014
 */
#pragma once

#include <functional>
#include <type_traits>
#include "mockutils/VirtualOffestSelector.hpp"
#include "mockutils/union_cast.hpp"

namespace fakeit {
    class NoVirtualDtor : public std::runtime_error {
    public:
		NoVirtualDtor() :std::runtime_error("Can't mock the destructor. No virtual destructor was found") {}
    };

    class VTUtils {
    public:

#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
#endif
        template<typename C, typename R, typename ... arglist>
        static unsigned int getOffset(R (C::*vMethod)(arglist...)) {
            auto sMethod = reinterpret_cast<unsigned int (VirtualOffsetSelector::*)(int)>(vMethod);
            VirtualOffsetSelector offsetSelctor;
            return (offsetSelctor.*sMethod)(0);
        }
#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic pop
#endif
#endif

        template<typename C>
        static typename std::enable_if<std::has_virtual_destructor<C>::value, unsigned int>::type
        getDestructorOffset() {
            VirtualOffsetSelector offsetSelctor;
            union_cast<C *>(&offsetSelctor)->~C();
            return offsetSelctor.offset;
        }

        template<typename C>
        static typename std::enable_if<!std::has_virtual_destructor<C>::value, unsigned int>::type
        getDestructorOffset() {
            throw NoVirtualDtor();
        }

		template<typename C>
		static typename std::enable_if<std::has_virtual_destructor<C>::value, bool>::type
			hasVirtualDestructor() {
			return true;
		}

		template<typename C>
		static typename std::enable_if<!std::has_virtual_destructor<C>::value, bool>::type
			hasVirtualDestructor() {
			return false;
		}

        template<typename C>
        static unsigned int getVTSize() {
            struct Derrived : public C {
                virtual void endOfVt() {
                }
            };

            unsigned int vtSize = getOffset(&Derrived::endOfVt);
            return vtSize;
        }
    };

}
<commit_msg>Disable some GCC option only when available (GCC >= 8).<commit_after>/*
 * VTUtils.hpp
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Jun 3, 2014
 */
#pragma once

#include <functional>
#include <type_traits>
#include "mockutils/VirtualOffestSelector.hpp"
#include "mockutils/union_cast.hpp"

namespace fakeit {
    class NoVirtualDtor : public std::runtime_error {
    public:
		NoVirtualDtor() :std::runtime_error("Can't mock the destructor. No virtual destructor was found") {}
    };

    class VTUtils {
    public:

#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 8
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
        template<typename C, typename R, typename ... arglist>
        static unsigned int getOffset(R (C::*vMethod)(arglist...)) {
            auto sMethod = reinterpret_cast<unsigned int (VirtualOffsetSelector::*)(int)>(vMethod);
            VirtualOffsetSelector offsetSelctor;
            return (offsetSelctor.*sMethod)(0);
        }
#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 8
#pragma GCC diagnostic pop
#endif

        template<typename C>
        static typename std::enable_if<std::has_virtual_destructor<C>::value, unsigned int>::type
        getDestructorOffset() {
            VirtualOffsetSelector offsetSelctor;
            union_cast<C *>(&offsetSelctor)->~C();
            return offsetSelctor.offset;
        }

        template<typename C>
        static typename std::enable_if<!std::has_virtual_destructor<C>::value, unsigned int>::type
        getDestructorOffset() {
            throw NoVirtualDtor();
        }

		template<typename C>
		static typename std::enable_if<std::has_virtual_destructor<C>::value, bool>::type
			hasVirtualDestructor() {
			return true;
		}

		template<typename C>
		static typename std::enable_if<!std::has_virtual_destructor<C>::value, bool>::type
			hasVirtualDestructor() {
			return false;
		}

        template<typename C>
        static unsigned int getVTSize() {
            struct Derrived : public C {
                virtual void endOfVt() {
                }
            };

            unsigned int vtSize = getOffset(&Derrived::endOfVt);
            return vtSize;
        }
    };

}
<|endoftext|>