<commit_before>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  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, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

/* $Id$ */

// INCLUDE/*{{{*/

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

/*}}}*/

std::string &generateErrorText(/*{{{*/
    gloox::ConnectionError connectionError,
    gloox::StreamError streamError,
    const std::string &streamErrorText,
    gloox::AuthenticationError authError)
{
    std::string text;

    switch (connectionError) {
    case gloox::ConnNoError:
        break;
    case gloox::ConnStreamError: {
        text = "A stream error occured: ";
        switch (streamError) {
        case gloox::StreamErrorUndefined:
            text += "Undefined/unknown error.";
            break;
        case gloox::StreamErrorBadFormat:
            text += "The entity has sent XML that cannot be processed.";
            break;
        case gloox::StreamErrorBadNamespacePrefix:
            text += "The entity has sent a namespace prefix that is "
                    "unsupported, or has sent no namespace prefix on an "
                    "element that requires such a prefix.";
            break;
        case gloox::StreamErrorConflict:
            text += "The server is closing the active stream for this "
                    "entity because a new stream has been initiated that "
                    "conflicts with the existing stream.";
            break;
        case gloox::StreamErrorConnectionTimeout:
            text += "The entity has not generated any traffic over the "
                    "stream for some period of time.";
            break;
        case gloox::StreamErrorHostGone:
            text += "The value of the 'to' attribute provided by the "
                    "initiating entity in the stream header corresponds to "
                    "a hostname that is no longer hosted by the server.";
            break;
        case gloox::StreamErrorHostUnknown:
            text += "The value of the 'to' attribute provided by the "
                    "initiating entity in the stream header does not "
                    "correspond to a hostname that is hosted by the "
                    "server.";
            break;
        case gloox::StreamErrorImproperAddressing:
            text += "A stanza sent between two servers lacks a 'to' or "
                    "'from' attribute.";
            break;
        case gloox::StreamErrorInternalServerError:
            text += "The server has experienced a misconfiguration or an "
                    "otherwise-undefined internal error that prevents it "
                    "from servicing the stream.";
            break;
        case gloox::StreamErrorInvalidFrom:
            text += "The JID or hostname provided in a 'from' address does "
                    "not match an authorized JID or validated domain "
                    "negotiated between servers via SASL or dialback, or "
                    "between a client and a server via authentication and "
                    "resource binding.";
            break;
        case gloox::StreamErrorInvalidId:
            text += "The stream ID or dialback ID is invalid or does not "
                    "match an ID previously provided.";
            break;
        case gloox::StreamErrorInvalidNamespace:
            text += "The streams namespace name is something other than "
                    "\"http://etherx.jabber.org/streams\" or the dialback "
                    "namespace name is something other than "
                    "\"jabber:server:dialback\".";
            break;
        case gloox::StreamErrorInvalidXml:
            text += "The entity has sent invalid XML over the stream to a "
                    "server that performs validation.";
            break;
        case gloox::StreamErrorNotAuthorized:
            text += "The entity has attempted to send data before the "
                    "stream has been authenticated, or otherwise is not "
                    "authorized to perform an action related to stream "
                    "negotiation.";
            break;
        case gloox::StreamErrorPolicyViolation:
            text += "The entity has violated some local service policy.";
            break;
        case gloox::StreamErrorRemoteConnectionFailed:
            text += "The server is unable to properly connect to a remote "
                    "entity that is required for authentication or "
                    "authorization.";
            break;
        case gloox::StreamErrorResourceConstraint:
            text += "The server lacks the system resources necessary to "
                    "service the stream.";
            break;
        case gloox::StreamErrorRestrictedXml:
            text += "The entity has attempted to send restricted XML "
                    "features.";
            break;
        case gloox::StreamErrorSeeOtherHost:
            text += "The server will not provide service to the initiating "
                    "entity but is redirecting traffic to another host.";
            break;
        case gloox::StreamErrorSystemShutdown:
            text += "The server is being shut down and all active streams "
                    "are being closed.";
            break;
        case gloox::StreamErrorUndefinedCondition:
            text += "The error condition is not one of those defined by "
                    "the other conditions in this list.";
            break;
        case gloox::StreamErrorUnsupportedEncoding:
            text += "The initiating entity has encoded the stream in an "
                    "encoding that is not supported by the server.";
            break;
        case gloox::StreamErrorUnsupportedStanzaType:
            text += "The initiating entity has sent a first-level child of "
                    "the stream that is not supported by the server.";
            break;
        case gloox::StreamErrorUnsupportedVersion:
            text += "The initiating entity specifies a version of XMPP "
                    "that is not supported by the server.";
            break;
        case gloox::StreamErrorXmlNotWellFormed:
            text += "The initiating entity has sent XML that is not "
                    "well-formed.";
            break;
        default:
            text += "Unknown error.";
        break;
        }
        if (!streamErrorText.empty())
            text += " (Addition information: " + streamErrorText + ")";
    }
    case gloox::ConnStreamVersionError:
        text = "The incoming stream's version is not supported.";
        break;
    case gloox::ConnStreamClosed:
        text = "The stream has been closed by the server.";
        break;
    case gloox::ConnProxyAuthRequired:
        text = "The HTTP/SOCKS5 proxy requires authentication.";
        break;
    case gloox::ConnProxyAuthFailed:
        text = "The HTTP/SOCKS5 proxy authentication failed.";
        break;
    case gloox::ConnProxyNoSupportedAuth:
        text = "The HTTP/SOCKS5 proxy requires an unsupported auth "
               "mechanism.";
        break;
    case gloox::ConnIoError:
        text = "An I/O error occured.";
        break;
    case gloox::ConnParseError:
        text = "An XML parse error occured.";
        break;
    case gloox::ConnConnectionRefused:
        text = "The connection was refused by the server (on the socket "
               "level).";
        break;
    case gloox::ConnDnsError:
        text = "Resolving the server's hostname failed.";
        break;
    case gloox::ConnOutOfMemory:
        text = "Out of memory.";
        break;
    case gloox::ConnNoSupportedAuth:
        text = "The auth mechanisms the server offers are not supported "
               "or the server offered no auth mechanisms at all.";
        break;
    case gloox::ConnTlsFailed:
        text = "The server's certificate could not be verified or the TLS "
               "handshake did not complete successfully.";
        break;
    case gloox::ConnTlsNotAvailable:
        text = "The server doesn't offer TLS.";
        break;
    case gloox::ConnCompressionFailed:
        text = "Negotiating or initializing compression failed.";
        break;
    case gloox::ConnAuthenticationFailed:
        text = "Authentication failed: ";
        switch (authError) {
        case gloox::AuthErrorUndefined:
            text += "Error condition unknown.";
            break;
        case gloox::SaslAborted:
            text += "The receiving entity acknowledges an abort sent by "
                    "the initiating entity.";
            break;
        case gloox::SaslIncorrectEncoding:
            text += "The data provided by the initiating entity could not "
                    "be processed because the [BASE64] encoding is "
                    "incorrect.";
            break;
        case gloox::SaslInvalidAuthzid:
            text += "The authzid provided by the initiating entity is "
                    "invalid, either because it is incorrectly formatted "
                    "or because the initiating entity does not have "
                    "permissions to authorize that ID.";
            break;
        case gloox::SaslInvalidMechanism:
            text += "The initiating entity did not provide a mechanism or "
                    "requested a mechanism that is not supported by the "
                    "receiving entity.";
            break;
        case gloox::SaslMalformedRequest:
            text += "The request is malformed.";
            break;
        case gloox::SaslMechanismTooWeak:
            text += "The mechanism requested by the initiating entity is "
                    "weaker than server policy permits for that initiating "
                    "entity.";
            break;
        case gloox::SaslNotAuthorized:
            text += "The authentication failed because the initiating "
                    "entity did not provide valid credentials.";
            break;
        case gloox::SaslTemporaryAuthFailure:
            text += "The authentication failed because of a temporary "
                    "error condition within the receiving entity.";
            break;
        case gloox::NonSaslConflict:
            text += "Resource conflict.";
            break;
        case gloox::NonSaslNotAcceptable:
            text += "Required Information not provided.";
            break;
        case gloox::NonSaslNotAuthorized:
            text += "Incorrect credentials.";
            break;
        default:
            text += "Unknown error.";
        }
        break;
    case gloox::ConnUserDisconnected:
        // The user (or higher-level protocol) requested a disconnect.
        break;
    case gloox::ConnNotConnected:
        text = "There is no active connection.";
        break;
    default:
        text = "An unknown error occured.";
    }
}/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<commit_msg>Fix: generateErrorText return<commit_after>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  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, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

/* $Id$ */

// INCLUDE/*{{{*/

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

/*}}}*/

std::string &generateErrorText(/*{{{*/
    gloox::ConnectionError connectionError,
    gloox::StreamError streamError,
    const std::string &streamErrorText,
    gloox::AuthenticationError authError)
{
    static std::string text;

    switch (connectionError) {
    case gloox::ConnNoError:
        break;
    case gloox::ConnStreamError: {
        text = "A stream error occured: ";
        switch (streamError) {
        case gloox::StreamErrorUndefined:
            text += "Undefined/unknown error.";
            break;
        case gloox::StreamErrorBadFormat:
            text += "The entity has sent XML that cannot be processed.";
            break;
        case gloox::StreamErrorBadNamespacePrefix:
            text += "The entity has sent a namespace prefix that is "
                    "unsupported, or has sent no namespace prefix on an "
                    "element that requires such a prefix.";
            break;
        case gloox::StreamErrorConflict:
            text += "The server is closing the active stream for this "
                    "entity because a new stream has been initiated that "
                    "conflicts with the existing stream.";
            break;
        case gloox::StreamErrorConnectionTimeout:
            text += "The entity has not generated any traffic over the "
                    "stream for some period of time.";
            break;
        case gloox::StreamErrorHostGone:
            text += "The value of the 'to' attribute provided by the "
                    "initiating entity in the stream header corresponds to "
                    "a hostname that is no longer hosted by the server.";
            break;
        case gloox::StreamErrorHostUnknown:
            text += "The value of the 'to' attribute provided by the "
                    "initiating entity in the stream header does not "
                    "correspond to a hostname that is hosted by the "
                    "server.";
            break;
        case gloox::StreamErrorImproperAddressing:
            text += "A stanza sent between two servers lacks a 'to' or "
                    "'from' attribute.";
            break;
        case gloox::StreamErrorInternalServerError:
            text += "The server has experienced a misconfiguration or an "
                    "otherwise-undefined internal error that prevents it "
                    "from servicing the stream.";
            break;
        case gloox::StreamErrorInvalidFrom:
            text += "The JID or hostname provided in a 'from' address does "
                    "not match an authorized JID or validated domain "
                    "negotiated between servers via SASL or dialback, or "
                    "between a client and a server via authentication and "
                    "resource binding.";
            break;
        case gloox::StreamErrorInvalidId:
            text += "The stream ID or dialback ID is invalid or does not "
                    "match an ID previously provided.";
            break;
        case gloox::StreamErrorInvalidNamespace:
            text += "The streams namespace name is something other than "
                    "\"http://etherx.jabber.org/streams\" or the dialback "
                    "namespace name is something other than "
                    "\"jabber:server:dialback\".";
            break;
        case gloox::StreamErrorInvalidXml:
            text += "The entity has sent invalid XML over the stream to a "
                    "server that performs validation.";
            break;
        case gloox::StreamErrorNotAuthorized:
            text += "The entity has attempted to send data before the "
                    "stream has been authenticated, or otherwise is not "
                    "authorized to perform an action related to stream "
                    "negotiation.";
            break;
        case gloox::StreamErrorPolicyViolation:
            text += "The entity has violated some local service policy.";
            break;
        case gloox::StreamErrorRemoteConnectionFailed:
            text += "The server is unable to properly connect to a remote "
                    "entity that is required for authentication or "
                    "authorization.";
            break;
        case gloox::StreamErrorResourceConstraint:
            text += "The server lacks the system resources necessary to "
                    "service the stream.";
            break;
        case gloox::StreamErrorRestrictedXml:
            text += "The entity has attempted to send restricted XML "
                    "features.";
            break;
        case gloox::StreamErrorSeeOtherHost:
            text += "The server will not provide service to the initiating "
                    "entity but is redirecting traffic to another host.";
            break;
        case gloox::StreamErrorSystemShutdown:
            text += "The server is being shut down and all active streams "
                    "are being closed.";
            break;
        case gloox::StreamErrorUndefinedCondition:
            text += "The error condition is not one of those defined by "
                    "the other conditions in this list.";
            break;
        case gloox::StreamErrorUnsupportedEncoding:
            text += "The initiating entity has encoded the stream in an "
                    "encoding that is not supported by the server.";
            break;
        case gloox::StreamErrorUnsupportedStanzaType:
            text += "The initiating entity has sent a first-level child of "
                    "the stream that is not supported by the server.";
            break;
        case gloox::StreamErrorUnsupportedVersion:
            text += "The initiating entity specifies a version of XMPP "
                    "that is not supported by the server.";
            break;
        case gloox::StreamErrorXmlNotWellFormed:
            text += "The initiating entity has sent XML that is not "
                    "well-formed.";
            break;
        default:
            text += "Unknown error.";
        break;
        }
        if (!streamErrorText.empty())
            text += " (Addition information: " + streamErrorText + ")";
    }
    case gloox::ConnStreamVersionError:
        text = "The incoming stream's version is not supported.";
        break;
    case gloox::ConnStreamClosed:
        text = "The stream has been closed by the server.";
        break;
    case gloox::ConnProxyAuthRequired:
        text = "The HTTP/SOCKS5 proxy requires authentication.";
        break;
    case gloox::ConnProxyAuthFailed:
        text = "The HTTP/SOCKS5 proxy authentication failed.";
        break;
    case gloox::ConnProxyNoSupportedAuth:
        text = "The HTTP/SOCKS5 proxy requires an unsupported auth "
               "mechanism.";
        break;
    case gloox::ConnIoError:
        text = "An I/O error occured.";
        break;
    case gloox::ConnParseError:
        text = "An XML parse error occured.";
        break;
    case gloox::ConnConnectionRefused:
        text = "The connection was refused by the server (on the socket "
               "level).";
        break;
    case gloox::ConnDnsError:
        text = "Resolving the server's hostname failed.";
        break;
    case gloox::ConnOutOfMemory:
        text = "Out of memory.";
        break;
    case gloox::ConnNoSupportedAuth:
        text = "The auth mechanisms the server offers are not supported "
               "or the server offered no auth mechanisms at all.";
        break;
    case gloox::ConnTlsFailed:
        text = "The server's certificate could not be verified or the TLS "
               "handshake did not complete successfully.";
        break;
    case gloox::ConnTlsNotAvailable:
        text = "The server doesn't offer TLS.";
        break;
    case gloox::ConnCompressionFailed:
        text = "Negotiating or initializing compression failed.";
        break;
    case gloox::ConnAuthenticationFailed:
        text = "Authentication failed: ";
        switch (authError) {
        case gloox::AuthErrorUndefined:
            text += "Error condition unknown.";
            break;
        case gloox::SaslAborted:
            text += "The receiving entity acknowledges an abort sent by "
                    "the initiating entity.";
            break;
        case gloox::SaslIncorrectEncoding:
            text += "The data provided by the initiating entity could not "
                    "be processed because the [BASE64] encoding is "
                    "incorrect.";
            break;
        case gloox::SaslInvalidAuthzid:
            text += "The authzid provided by the initiating entity is "
                    "invalid, either because it is incorrectly formatted "
                    "or because the initiating entity does not have "
                    "permissions to authorize that ID.";
            break;
        case gloox::SaslInvalidMechanism:
            text += "The initiating entity did not provide a mechanism or "
                    "requested a mechanism that is not supported by the "
                    "receiving entity.";
            break;
        case gloox::SaslMalformedRequest:
            text += "The request is malformed.";
            break;
        case gloox::SaslMechanismTooWeak:
            text += "The mechanism requested by the initiating entity is "
                    "weaker than server policy permits for that initiating "
                    "entity.";
            break;
        case gloox::SaslNotAuthorized:
            text += "The authentication failed because the initiating "
                    "entity did not provide valid credentials.";
            break;
        case gloox::SaslTemporaryAuthFailure:
            text += "The authentication failed because of a temporary "
                    "error condition within the receiving entity.";
            break;
        case gloox::NonSaslConflict:
            text += "Resource conflict.";
            break;
        case gloox::NonSaslNotAcceptable:
            text += "Required Information not provided.";
            break;
        case gloox::NonSaslNotAuthorized:
            text += "Incorrect credentials.";
            break;
        default:
            text += "Unknown error.";
        }
        break;
    case gloox::ConnUserDisconnected:
        // The user (or higher-level protocol) requested a disconnect.
        break;
    case gloox::ConnNotConnected:
        text = "There is no active connection.";
        break;
    default:
        text = "An unknown error occured.";
    }
    return text;
}/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2006 by Lukáš Lalinský
    email                : lalinsky@gmail.com

    copyright            : (C) 2004 by Allan Sandfeld Jensen
    email                : kde@carewolf.org
                           (original MPC implementation)
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevector.h>
#include <tdebug.h>
#include <id3v2tag.h>

#include "aifffile.h"

using namespace TagLib;

class RIFF::AIFF::File::FilePrivate
{
public:
  FilePrivate() :
    properties(0),
    tag(0)
  {

  }

  ~FilePrivate()
  {
    delete properties;
    delete tag;
  }

  Properties *properties;
  ID3v2::Tag *tag;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

RIFF::AIFF::File::File(FileName file, bool readProperties,
                       Properties::ReadStyle propertiesStyle) : RIFF::File(file, BigEndian)
{
  d = new FilePrivate;
  if(isOpen())
    read(readProperties, propertiesStyle);
}

RIFF::AIFF::File::~File()
{
  delete d;
}

ID3v2::Tag *RIFF::AIFF::File::tag() const
{
  return d->tag;
}

RIFF::AIFF::Properties *RIFF::AIFF::File::audioProperties() const
{
  return d->properties;
}

bool RIFF::AIFF::File::save()
{
  if(readOnly()) {
    debug("RIFF::AIFF::File::save() -- File is read only.");
    return false;
  }

  setChunkData("ID3 ", d->tag->render());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void RIFF::AIFF::File::read(bool readProperties, Properties::ReadStyle propertiesStyle)
{
  for(uint i = 0; i < chunkCount(); i++) {
    if(chunkName(i) == "ID3 ")
      d->tag = new ID3v2::Tag(this, chunkOffset(i));
    else if(chunkName(i) == "COMM" && readProperties)
      d->properties = new Properties(chunkData(i), propertiesStyle);
  }

  if(!d->tag)
    d->tag = new ID3v2::Tag;
}
<commit_msg>wrong copyright<commit_after>/***************************************************************************
    copyright            : (C) 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevector.h>
#include <tdebug.h>
#include <id3v2tag.h>

#include "aifffile.h"

using namespace TagLib;

class RIFF::AIFF::File::FilePrivate
{
public:
  FilePrivate() :
    properties(0),
    tag(0)
  {

  }

  ~FilePrivate()
  {
    delete properties;
    delete tag;
  }

  Properties *properties;
  ID3v2::Tag *tag;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

RIFF::AIFF::File::File(FileName file, bool readProperties,
                       Properties::ReadStyle propertiesStyle) : RIFF::File(file, BigEndian)
{
  d = new FilePrivate;
  if(isOpen())
    read(readProperties, propertiesStyle);
}

RIFF::AIFF::File::~File()
{
  delete d;
}

ID3v2::Tag *RIFF::AIFF::File::tag() const
{
  return d->tag;
}

RIFF::AIFF::Properties *RIFF::AIFF::File::audioProperties() const
{
  return d->properties;
}

bool RIFF::AIFF::File::save()
{
  if(readOnly()) {
    debug("RIFF::AIFF::File::save() -- File is read only.");
    return false;
  }

  setChunkData("ID3 ", d->tag->render());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void RIFF::AIFF::File::read(bool readProperties, Properties::ReadStyle propertiesStyle)
{
  for(uint i = 0; i < chunkCount(); i++) {
    if(chunkName(i) == "ID3 ")
      d->tag = new ID3v2::Tag(this, chunkOffset(i));
    else if(chunkName(i) == "COMM" && readProperties)
      d->properties = new Properties(chunkData(i), propertiesStyle);
  }

  if(!d->tag)
    d->tag = new ID3v2::Tag;
}
<|endoftext|>


<commit_before>#ifndef CALLBACK_HPP
#define CALLBACK_HPP

#include "noncopyable.hpp"

#include <type_traits>
#include <cstring>

struct callback_t : private noncopyable_t
{
    enum {INTERNAL_STORAGE_SIZE = 64};

    template <typename T>
    callback_t(T &&object)
    {
        typedef typename std::remove_reference<T>::type unref_type;

        const size_t alignment = std::alignment_of<unref_type>::value;

        static_assert(sizeof(unref_type) + alignment < INTERNAL_STORAGE_SIZE,
                      "functional object don't fit into internal storage");

        m_object_ptr = new (m_storage + alignment) unref_type(std::forward<T>(object));
        m_method_ptr = &method_stub<unref_type>;
        m_delete_ptr = &delete_stub<unref_type>;
    }

    callback_t(callback_t &&o)
    {
        move_from_other(o);
    }

    callback_t & operator=(callback_t &&o)
    {
        move_from_other(o);
        return *this;
    }

    ~callback_t()
    {
        if (m_delete_ptr)
        {
            (*m_delete_ptr)(m_object_ptr);
        }
    }

    void operator()() const
    {
        if (m_method_ptr)
        {
            (*m_method_ptr)(m_object_ptr);
        }
    }

private:
    char m_storage[INTERNAL_STORAGE_SIZE];

    void *m_object_ptr = m_storage;

    typedef void (*method_type)(void *);

    method_type m_method_ptr = nullptr;
    method_type m_delete_ptr = nullptr;

    void move_from_other(callback_t &o)
    {
        size_t o_alignment = o.m_method_ptr - o.m_storage;
        m_object_ptr = m_storage + o_alignment;
        m_method_ptr = o.m_method_ptr;
        m_delete_ptr = o.m_delete_ptr;

        memcpy(m_storage, o.m_storage, INTERNAL_STORAGE_SIZE);

        o.m_method_ptr = nullptr;
        o.m_delete_ptr = nullptr;
    }

    template <class T>
    static void method_stub(void *object_ptr)
    {
        static_cast<T *>(object_ptr)->operator()();
    }

    template <class T>
    static void delete_stub(void *object_ptr)
    {
        static_cast<T *>(object_ptr)->~T();
    }
};

#endif // CALLBACK_HPP
<commit_msg>brackets<commit_after>#ifndef CALLBACK_HPP
#define CALLBACK_HPP

#include "noncopyable.hpp"

#include <type_traits>
#include <cstring>

template <size_t STORAGE_SIZE = 32>
struct callback_t : private noncopyable_t
{
    template <typename T>
    callback_t(T &&object)
    {
        typedef typename std::remove_reference<T>::type unref_type;

        const size_t alignment = std::alignment_of<unref_type>::value;

        static_assert(sizeof(unref_type) + alignment < STORAGE_SIZE,
                      "functional object don't fit into internal storage");

        m_object_ptr = new (m_storage + alignment) unref_type(std::forward<T>(object));
        m_method_ptr = &method_stub<unref_type>;
        m_delete_ptr = &delete_stub<unref_type>;
    }

    callback_t(callback_t &&o)
    {
        move_from_other(o);
    }

    callback_t & operator=(callback_t &&o)
    {
        move_from_other(o);
        return *this;
    }

    ~callback_t()
    {
        if (m_delete_ptr) {
            (*m_delete_ptr)(m_object_ptr);
        }
    }

    void operator()() const
    {
        if (m_method_ptr) {
            (*m_method_ptr)(m_object_ptr);
        }
    }

private:
    char m_storage[STORAGE_SIZE];

    void *m_object_ptr = m_storage;

    typedef void (*method_type)(void *);

    method_type m_method_ptr = nullptr;
    method_type m_delete_ptr = nullptr;

    void move_from_other(callback_t &o)
    {
        const size_t o_alignment = o.m_method_ptr - o.m_storage;
        m_object_ptr = m_storage + o_alignment;
        m_method_ptr = o.m_method_ptr;
        m_delete_ptr = o.m_delete_ptr;

        memcpy(m_storage, o.m_storage, STORAGE_SIZE);

        o.m_method_ptr = nullptr;
        o.m_delete_ptr = nullptr;
    }

    template <class T>
    static void method_stub(void *object_ptr)
    {
        static_cast<T *>(object_ptr)->operator()();
    }

    template <class T>
    static void delete_stub(void *object_ptr)
    {
        static_cast<T *>(object_ptr)->~T();
    }
};

#endif // CALLBACK_HPP
<|endoftext|>


<commit_before>// @(#)root/tmva $\Id$
// Author: Andreas Hoecker, Peter Speckmayer

/**********************************************************************************
 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis       *
 * Package: TMVA                                                                  *
 * Class  : MetricEuler                                                         *
 * Web    : http://tmva.sourceforge.net                                           *
 *                                                                                *
 * Description:                                                                   *
 *      Implementation                                                            *
 *                                                                                *
 * Authors (alphabetical):                                                        *
 *      Peter Speckmayer <speckmay@mail.cern.ch> - CERN, Switzerland              *
 *                                                                                *
 * Copyright (c) 2005:                                                            *
 *      CERN, Switzerland                                                         *
 *      MPI-K Heidelberg, Germany                                                 *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without             *
 * modification, are permitted according to the terms listed in LICENSE           *
 * (http://tmva.sourceforge.net/LICENSE)                                          *
 **********************************************************************************/

//_______________________________________________________________________
//
// interface for a metric
//
//_______________________________________________________________________

#include "TMVA/MetricEuler.h"

ClassImp(TMVA::MetricEuler)

//_______________________________________________________________________
TMVA::MetricEuler::MetricEuler()
   : IMetric()
{
   // constructor
}

//_______________________________________________________________________
Double_t TMVA::MetricEuler::Distance( std::vector<Double_t>& pointA, std::vector<Double_t>& pointB )
{
   Double_t distance = 0.0;
   Double_t val = 0.0;
   std::vector<Double_t>::iterator itA;
   std::vector<Double_t>::iterator itB;
   if( fParameters == NULL ){
      itA = pointA.begin();
      for( itB = pointB.begin(); itB != pointB.end(); itB++ ){
         if( itA == pointA.end() ){
            break;
         }
         val = (*itA)-(*itB);
         distance += pow( val, 2 );
         itA++;
      }
   }else{
      std::vector<Double_t>::iterator itPar;
      itA   = pointA.begin();
      itPar = fParameters->begin();
      for( itB = pointB.begin(); itB != pointB.end(); itB++ ){
         if( itA == pointA.end() ){
            break;
         }
         if( itPar == fParameters->end() ){
            break;
         }
         val = (*itPar)*( (*itA)-(*itB) );
         distance += pow( val, 2 );
         itA++;
         itPar++;
      }
      if( itA != pointA.end() ){
         distance *= pow( (*itA),2 );
      }
   }
   return sqrt( distance );
}

<commit_msg>From Lorenzo: Fix for MacOS<commit_after>// @(#)root/tmva $\Id$
// Author: Andreas Hoecker, Peter Speckmayer

/**********************************************************************************
 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis       *
 * Package: TMVA                                                                  *
 * Class  : MetricEuler                                                         *
 * Web    : http://tmva.sourceforge.net                                           *
 *                                                                                *
 * Description:                                                                   *
 *      Implementation                                                            *
 *                                                                                *
 * Authors (alphabetical):                                                        *
 *      Peter Speckmayer <speckmay@mail.cern.ch> - CERN, Switzerland              *
 *                                                                                *
 * Copyright (c) 2005:                                                            *
 *      CERN, Switzerland                                                         *
 *      MPI-K Heidelberg, Germany                                                 *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without             *
 * modification, are permitted according to the terms listed in LICENSE           *
 * (http://tmva.sourceforge.net/LICENSE)                                          *
 **********************************************************************************/

//_______________________________________________________________________
//
// interface for a metric
//
//_______________________________________________________________________

#include "TMVA/MetricEuler.h"
#include <cmath>

ClassImp(TMVA::MetricEuler)

//_______________________________________________________________________
TMVA::MetricEuler::MetricEuler()
   : IMetric()
{
   // constructor
}

//_______________________________________________________________________
Double_t TMVA::MetricEuler::Distance( std::vector<Double_t>& pointA, std::vector<Double_t>& pointB )
{
   Double_t distance = 0.0;
   Double_t val = 0.0;
   std::vector<Double_t>::iterator itA;
   std::vector<Double_t>::iterator itB;
   if( fParameters == NULL ){
      itA = pointA.begin();
      for( itB = pointB.begin(); itB != pointB.end(); itB++ ){
         if( itA == pointA.end() ){
            break;
         }
         val = (*itA)-(*itB);
         distance += std::pow( val, 2 );
         itA++;
      }
   }else{
      std::vector<Double_t>::iterator itPar;
      itA   = pointA.begin();
      itPar = fParameters->begin();
      for( itB = pointB.begin(); itB != pointB.end(); itB++ ){
         if( itA == pointA.end() ){
            break;
         }
         if( itPar == fParameters->end() ){
            break;
         }
         val = (*itPar)*( (*itA)-(*itB) );
         distance += std::pow( val, 2 );
         itA++;
         itPar++;
      }
      if( itA != pointA.end() ){
         distance *= std::pow( (*itA),2 );
      }
   }
   return sqrt( distance );
}

<|endoftext|>


<commit_before><commit_msg>add missing include<commit_after><|endoftext|>


<commit_before>/**
 *Licensed to the Apache Software Foundation (ASF) under one
 *or more contributor license agreements.  See the NOTICE file
 *distributed with this work for additional information
 *regarding copyright ownership.  The ASF licenses this file
 *to you 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.
 */

#include <sstream>
#include <arpa/inet.h>

#include <pubsub_wire_v2_protocol_common.h>

#include "gtest/gtest.h"

#include "pubsub_wire_v2_protocol_impl.h"
#include "celix_byteswap.h"
#include <cstring>

class WireProtocolV2Test : public ::testing::Test {
public:
    WireProtocolV2Test() = default;
    ~WireProtocolV2Test() override = default;

};

TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeHeader_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    pubsub_protocol_message_t message;
    message.header.msgId = 1;
    message.header.seqNr = 4;
    message.header.msgMajorVersion = 0;
    message.header.msgMinorVersion = 0;
    message.header.payloadSize = 2;
    message.header.metadataSize = 3;
    message.header.payloadPartSize = 4;
    message.header.payloadOffset = 2;
    message.header.isLastSegment = 1;
    message.header.convertEndianess = 1;

    void *headerData = nullptr;
    size_t headerLength = 0;
    celix_status_t status = pubsubProtocol_wire_v2_encodeHeader(nullptr, &message, &headerData, &headerLength);

    unsigned char exp[40];
    uint32_t s = bswap_32(0xABBADEAF);
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x04000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));
    uint32_t pps = 0x04000000;
    memcpy(exp+28, &pps, sizeof(uint32_t));
    uint32_t ppo = 0x02000000;
    memcpy(exp+32, &ppo, sizeof(uint32_t));
    uint32_t ils = 0x01000000;
    memcpy(exp+36, &ils, sizeof(uint32_t));

    ASSERT_EQ(status, CELIX_SUCCESS);
    ASSERT_EQ(40, headerLength);
    for (int i = 0; i < 40; i++) {
        ASSERT_EQ(((unsigned char*) headerData)[i], exp[i]);
    }

    pubsubProtocol_wire_v2_destroy(wireprotocol);
    free(headerData);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = bswap_32(0xABBADEAF);
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));
    uint32_t pps = 0x04000000;
    memcpy(exp+28, &pps, sizeof(uint32_t));
    uint32_t ppo = 0x02000000;
    memcpy(exp+32, &ppo, sizeof(uint32_t));
    uint32_t ils = 0x01000000;
    memcpy(exp+36, &ils, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_SUCCESS, status);
    ASSERT_EQ(1, message.header.msgId);
    ASSERT_EQ(8, message.header.seqNr);
    ASSERT_EQ(0, message.header.msgMajorVersion);
    ASSERT_EQ(0, message.header.msgMinorVersion);
    ASSERT_EQ(2, message.header.payloadSize);
    ASSERT_EQ(3, message.header.metadataSize);
    ASSERT_EQ(4, message.header.payloadPartSize);
    ASSERT_EQ(2, message.header.payloadOffset);
    ASSERT_EQ(1, message.header.isLastSegment);
    ASSERT_EQ(1, message.header.convertEndianess);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectSync_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = 0xBAABABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectVersion_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = 0xABBADEAF;
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x02000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeFooter_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    pubsub_protocol_message_t message;

    void *footerData = nullptr;
    size_t footerLength = 0;
    celix_status_t status = pubsubProtocol_wire_v2_encodeFooter(nullptr, &message, &footerData, &footerLength);

    unsigned char exp[4];
    uint32_t s = 0xDEAFABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    ASSERT_EQ(status, CELIX_SUCCESS);
    ASSERT_EQ(4, footerLength);
    for (int i = 0; i < 4; i++) {
        ASSERT_EQ(((unsigned char*) footerData)[i], exp[i]);
    }
    pubsubProtocol_wire_v2_destroy(wireprotocol);
    free(footerData);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[4];
    uint32_t s = 0xDEAFABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message);

    ASSERT_EQ(CELIX_SUCCESS, status);
    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_IncorrectSync_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[4];
    uint32_t s = 0xABBADEAF;
    memcpy(exp, &s, sizeof(uint32_t));
    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message);
    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}<commit_msg>Fix wire_v2 unit test<commit_after>/**
 *Licensed to the Apache Software Foundation (ASF) under one
 *or more contributor license agreements.  See the NOTICE file
 *distributed with this work for additional information
 *regarding copyright ownership.  The ASF licenses this file
 *to you 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.
 */

#include <sstream>
#include <arpa/inet.h>

#include <pubsub_wire_v2_protocol_common.h>

#include "gtest/gtest.h"

#include "pubsub_wire_v2_protocol_impl.h"
#include "celix_byteswap.h"
#include <cstring>

class WireProtocolV2Test : public ::testing::Test {
public:
    WireProtocolV2Test() = default;
    ~WireProtocolV2Test() override = default;

};

TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeHeader_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    pubsub_protocol_message_t message;
    message.header.msgId = 1;
    message.header.seqNr = 4;
    message.header.msgMajorVersion = 0;
    message.header.msgMinorVersion = 0;
    message.header.payloadSize = 2;
    message.header.metadataSize = 3;
    message.header.payloadPartSize = 4;
    message.header.payloadOffset = 2;
    message.header.isLastSegment = 1;
    message.header.convertEndianess = 1;

    void *headerData = nullptr;
    size_t headerLength = 0;
    celix_status_t status = pubsubProtocol_wire_v2_encodeHeader(nullptr, &message, &headerData, &headerLength);

    unsigned char exp[40];
    uint32_t s = bswap_32(0xABBADEAF);
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x04000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));
    uint32_t pps = 0x04000000;
    memcpy(exp+28, &pps, sizeof(uint32_t));
    uint32_t ppo = 0x02000000;
    memcpy(exp+32, &ppo, sizeof(uint32_t));
    uint32_t ils = 0x01000000;
    memcpy(exp+36, &ils, sizeof(uint32_t));

    ASSERT_EQ(status, CELIX_SUCCESS);
    ASSERT_EQ(40, headerLength);
    for (int i = 0; i < 40; i++) {
        ASSERT_EQ(((unsigned char*) headerData)[i], exp[i]);
    }

    pubsubProtocol_wire_v2_destroy(wireprotocol);
    free(headerData);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = bswap_32(0xABBADEAF);
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));
    uint32_t pps = 0x04000000;
    memcpy(exp+28, &pps, sizeof(uint32_t));
    uint32_t ppo = 0x02000000;
    memcpy(exp+32, &ppo, sizeof(uint32_t));
    uint32_t ils = 0x01000000;
    memcpy(exp+36, &ils, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_SUCCESS, status);
    ASSERT_EQ(1, message.header.msgId);
    ASSERT_EQ(8, message.header.seqNr);
    ASSERT_EQ(0, message.header.msgMajorVersion);
    ASSERT_EQ(0, message.header.msgMinorVersion);
    ASSERT_EQ(2, message.header.payloadSize);
    ASSERT_EQ(3, message.header.metadataSize);
    ASSERT_EQ(4, message.header.payloadPartSize);
    ASSERT_EQ(2, message.header.payloadOffset);
    ASSERT_EQ(1, message.header.isLastSegment);
    ASSERT_EQ(1, message.header.convertEndianess);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectSync_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = 0xBAABABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x01000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeHeader_IncorrectVersion_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[40];
    uint32_t s = 0xABBADEAF;
    memcpy(exp, &s, sizeof(uint32_t));
    uint32_t e = 0x02000000;
    memcpy(exp+4, &e, sizeof(uint32_t));
    uint32_t m = 0x01000000;
    memcpy(exp+8, &m, sizeof(uint32_t));
    uint32_t seq = 0x08000000;
    memcpy(exp+12, &seq, sizeof(uint32_t));
    uint32_t v = 0x00000000;
    memcpy(exp+16, &v, sizeof(uint32_t));
    uint32_t ps = 0x02000000;
    memcpy(exp+20, &ps, sizeof(uint32_t));
    uint32_t ms = 0x03000000;
    memcpy(exp+24, &ms, sizeof(uint32_t));

    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeHeader(nullptr, exp, 40, &message);

    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_EncodeFooter_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    pubsub_protocol_message_t message;
    message.header.convertEndianess = 0;

    void *footerData = nullptr;
    size_t footerLength = 0;
    celix_status_t status = pubsubProtocol_wire_v2_encodeFooter(nullptr, &message, &footerData, &footerLength);

    unsigned char exp[4];
    uint32_t s = 0xDEAFABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    ASSERT_EQ(status, CELIX_SUCCESS);
    ASSERT_EQ(4, footerLength);
    for (int i = 0; i < 4; i++) {
        ASSERT_EQ(((unsigned char*) footerData)[i], exp[i]);
    }
    pubsubProtocol_wire_v2_destroy(wireprotocol);
    free(footerData);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[4];
    uint32_t s = 0xDEAFABBA;
    memcpy(exp, &s, sizeof(uint32_t));
    pubsub_protocol_message_t message;
    message.header.convertEndianess = 0;
    celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message);

    ASSERT_EQ(CELIX_SUCCESS, status);
    pubsubProtocol_wire_v2_destroy(wireprotocol);
}

TEST_F(WireProtocolV2Test, WireProtocolV2Test_DecodeFooter_IncorrectSync_Test) { // NOLINT(cert-err58-cpp)
    pubsub_protocol_wire_v2_t *wireprotocol;
    pubsubProtocol_wire_v2_create(&wireprotocol);

    unsigned char exp[4];
    uint32_t s = 0xABBADEAF;
    memcpy(exp, &s, sizeof(uint32_t));
    pubsub_protocol_message_t message;

    celix_status_t status = pubsubProtocol_wire_v2_decodeFooter(nullptr, exp, 4, &message);
    ASSERT_EQ(CELIX_ILLEGAL_ARGUMENT, status);

    pubsubProtocol_wire_v2_destroy(wireprotocol);
}<|endoftext|>


<commit_before>#include <stx/algorithm/MinMax.h>
#include <gtest/gtest.h>

TEST(Min, BasicFirst)
{
	int x = 0;
	auto& result = stx::Min(x, 1);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Min, BasicSecond)
{
	int x = 0;
	auto& result = stx::Min(1, x);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Min, Stable)
{
	int x = 0;
	int y = 0;
	auto& result = stx::Min(x, y);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, BasicFirst)
{
	int x = 0;
	auto& result = stx::Max(x, -1);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, BasicSecond)
{
	int x = 0;
	auto& result = stx::Max(-1, x);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, Stable)
{
	int x = 0;
	int y = 0;
	auto& result = stx::Max(x, y);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

<commit_msg>added some tests for min/max|element methods<commit_after>#include <stx/algorithm/MinMax.h>
#include <gtest/gtest.h>
#include <vector>

TEST(Min, BasicFirst)
{
	int x = 0;
	auto& result = stx::Min(x, 1);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Min, BasicSecond)
{
	int x = 0;
	auto& result = stx::Min(1, x);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Min, Stable)
{
	int x = 0;
	int y = 0;
	auto& result = stx::Min(x, y);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, BasicFirst)
{
	int x = 0;
	auto& result = stx::Max(x, -1);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, BasicSecond)
{
	int x = 0;
	auto& result = stx::Max(-1, x);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(Max, Stable)
{
	int x = 0;
	int y = 0;
	auto& result = stx::Max(x, y);

	EXPECT_EQ(0, result);
	EXPECT_EQ(&x, &result);
}

TEST(MinElement, Empty)
{
	std::vector<int> v;
	auto result = stx::MinElement(v.begin(), v.end());

	EXPECT_EQ(v.end(), result);
}

TEST(MinElement, Basic)
{
	std::vector<int> v = { 1, 2, 1, 3 };
	auto result = stx::MinElement(v.begin(), v.end());

	EXPECT_EQ(v.begin(), result);
}

TEST(MaxElement, Empty)
{
	std::vector<int> v;
	auto result = stx::MaxElement(v.begin(), v.end());

	EXPECT_EQ(v.end(), result);
}

TEST(MaxElement, Basic)
{
	std::vector<int> v = { 1, 2, 3, 3 };
	auto result = stx::MaxElement(v.begin(), v.end());

	EXPECT_EQ(v.end() - 2, result);
}

<|endoftext|>


<commit_before>#include <tightdb.hpp>
#include <gperftools/profiler.h>
#include <unistd.h>
#include <wait.h>

// benchmark - requires linux and links with google-pprof

using namespace tightdb;

int main(int argc, char* argv [])
{
    int spawns = 0;
    if (argc != 4) {
        printf("Arguments: profile_name num_processes reads_per_write\n");
        return 0;
    }
    spawns = atoi(argv[2]);
    const int reads_per_write = atoi(argv[3]);
    int pid = 0;
    for (int i=0; i < spawns - 1; i++) {
        pid = fork();
        if (pid == 0) {
            spawns = 0;
            break;
        }
    }
    srand(time(NULL));
    if (spawns) {
        char name[100];
        sprintf(name,"%s_%s_%s.prof", argv[1], argv[2], argv[3]);
        if (strcmp("0", argv[1]))
            ProfilerStart(name);
    }
    {
        SharedGroup db("parallel_benchmark.tightdb", true, SharedGroup::durability_Async);

        for (size_t round = 0; round < 20; ++round) {

            for (size_t i = 0; i < 1000000; ++i) {
                if (reads_per_write != 0 && (i % reads_per_write) == 0)
                {
                    WriteTransaction trx(db);

                    TableRef t = trx.get_table("test");

                    size_t key = rand() % 1000000;
                    size_t ndx = t->lower_bound_int(0, key);

                    StringData str = t->get_string(1, ndx);
                    t->set_string(1, ndx, str);
                    trx.commit();
                }
                else {
                    ReadTransaction trx(db);

                    ConstTableRef t = trx.get_table("test");

                    size_t key = rand() % 1000000;
                    size_t ndx = t->lower_bound_int(0, key);

                    StringData str = t->get_string(1, ndx);
                    const char* s = str.data();
                }
            }
        }
    }
    if (spawns)
        if (strcmp("0", argv[1]))
            ProfilerStop();
    while (spawns > 1) {
        int status = 0;
        wait(&status); // wait for child to complete
        spawns--;
    }

    return 0;
}
<commit_msg>increased benchmark focus on transaction overhead<commit_after>#include <tightdb.hpp>
#include <gperftools/profiler.h>
#include <unistd.h>
#include <wait.h>

// benchmark - requires linux and links with google-pprof

using namespace tightdb;

int main(int argc, char* argv [])
{
    int spawns = 0;
    if (argc != 4) {
        printf("Arguments: profile_name num_processes reads_per_write\n");
        return 0;
    }
    spawns = atoi(argv[2]);
    const int reads_per_write = atoi(argv[3]);
    int pid = 0;
    for (int i=0; i < spawns - 1; i++) {
        pid = fork();
        if (pid == 0) {
            spawns = 0;
            break;
        }
    }
    srand(time(NULL));
    if (spawns) {
        char name[100];
        sprintf(name,"%s_%s_%s.prof", argv[1], argv[2], argv[3]);
        if (strcmp("0", argv[1]))
            ProfilerStart(name);
    }
    {
        SharedGroup db("parallel_benchmark.tightdb", true, SharedGroup::durability_Async);

        for (size_t round = 0; round < 20; ++round) {

            for (size_t i = 0; i < 1000000; ++i) {
                if (reads_per_write != 0 && (i % reads_per_write) == 0)
                {
                    WriteTransaction trx(db);

                    TableRef t = trx.get_table("test");

                    size_t ndx = rand() % 1000000;

                    int v = t->get_int(0, ndx);
                    t->set_int(0, ndx, v + 1);
                    trx.commit();
                }
                else {
                    ReadTransaction trx(db);

                    ConstTableRef t = trx.get_table("test");

                    size_t ndx = rand() % 1000000;
                    volatile int v;
                    v = t->get_int(0, ndx);
                    (void) v;
                }
            }
        }
    }
    if (spawns)
        if (strcmp("0", argv[1]))
            ProfilerStop();
    while (spawns > 1) {
        int status = 0;
        wait(&status); // wait for child to complete
        spawns--;
    }

    return 0;
}
<|endoftext|>


<commit_before>// local includes
#include "augment_sparsity_on_interface.h"

// libMesh includes
#include "libmesh/elem.h"

using namespace libMesh;

AugmentSparsityOnInterface::AugmentSparsityOnInterface(MeshBase & mesh,
                                                       boundary_id_type crack_boundary_lower,
                                                       boundary_id_type crack_boundary_upper) :
  _mesh(mesh),
  _crack_boundary_lower(crack_boundary_lower),
  _crack_boundary_upper(crack_boundary_upper),
  _initialized(false)
{
  this->mesh_reinit();
}

const ElementSideMap & AugmentSparsityOnInterface::get_lower_to_upper() const
{
  libmesh_assert(this->_initialized);
  return _lower_to_upper;
}

void AugmentSparsityOnInterface::mesh_reinit ()
{
  this->_initialized = true;

  // Loop over all elements (not just local elements) to make sure we find
  // "neighbor" elements on opposite sides of the crack.

  MeshBase::const_element_iterator       el     = _mesh.active_elements_begin();
  const MeshBase::const_element_iterator end_el = _mesh.active_elements_end();

  // Map from (elem, side) to centroid
  std::map< std::pair<const Elem *, unsigned char>, Point> lower_centroids;
  std::map< std::pair<const Elem *, unsigned char>, Point> upper_centroids;

  for ( ; el != end_el; ++el)
    {
      const Elem * elem = *el;

      {
        for (unsigned char side=0; side<elem->n_sides(); side++)
          if (elem->neighbor_ptr(side) == libmesh_nullptr)
            {
              if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_lower))
                {
                  UniquePtr<const Elem> side_elem = elem->build_side_ptr(side);

                  lower_centroids[std::make_pair(elem, side)] = side_elem->centroid();
                }
            }
      }

      {
        for (unsigned char side=0; side<elem->n_sides(); side++)
          if (elem->neighbor_ptr(side) == libmesh_nullptr)
            {
              if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_upper))
                {
                  UniquePtr<const Elem> side_elem = elem->build_side_ptr(side);

                  upper_centroids[std::make_pair(elem, side)] = side_elem->centroid();
                }
            }
      }
    }
  std::size_t n_lower_centroids = lower_centroids.size();
  std::size_t n_upper_centroids = upper_centroids.size();
  libmesh_assert(n_lower_centroids == n_upper_centroids);

  // Clear _lower_to_upper. This map will be used for matrix assembly later on.
  _lower_to_upper.clear();

  // Clear _upper_to_lower. This map will be used for element ghosting
  // on distributed meshes, communication send_list construction in
  // parallel, and sparsity calculations
  _upper_to_lower.clear();

  // We do an N^2 search to find elements with matching centroids. This could be optimized,
  // e.g. by first sorting the centroids based on their (x,y,z) location.
  {
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it     = lower_centroids.begin();
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it_end = lower_centroids.end();
    for ( ; it != it_end; ++it)
      {
        Point lower_centroid = it->second;

        // find centroid in upper_centroids
        std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it     = upper_centroids.begin();
        std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end();

        Real min_distance = std::numeric_limits<Real>::max();
        for ( ; inner_it != inner_it_end; ++inner_it)
          {
            Point upper_centroid = inner_it->second;

            Real distance = (upper_centroid - lower_centroid).norm();
            if (distance < min_distance)
              {
                min_distance = distance;
                _lower_to_upper[it->first] = inner_it->first.first;
              }
          }

        // We should've found matching elements on either side of the crack by now
        libmesh_assert_less(min_distance, TOLERANCE);

        // fill up the inverse map
        const Elem * elem     = it->first.first;
        const Elem * neighbor = _lower_to_upper[it->first];
        _upper_to_lower[neighbor] = elem;
      }
  }
}

void AugmentSparsityOnInterface::operator()
  (const MeshBase::const_element_iterator & range_begin,
   const MeshBase::const_element_iterator & range_end,
   processor_id_type p,
   map_type & coupled_elements)
{
  libmesh_assert(this->_initialized);

  const CouplingMatrix * const null_mat = libmesh_nullptr;

  for (MeshBase::const_element_iterator elem_it = range_begin;
       elem_it != range_end; ++elem_it)
    {
      const Elem * const elem = *elem_it;

      if (elem->processor_id() != p)
        coupled_elements.insert (std::make_pair(elem, null_mat));

      for (unsigned int side=0; side<elem->n_sides(); side++)
        if (elem->neighbor_ptr(side) == libmesh_nullptr)
          {
            ElementSideMap::const_iterator ltu_it =
              _lower_to_upper.find(std::make_pair(elem, side));
            if (ltu_it != _lower_to_upper.end())
              {
                const Elem * neighbor = ltu_it->second;
                if (neighbor->processor_id() != p)
                  coupled_elements.insert (std::make_pair(neighbor, null_mat));
              }
          }

      ElementMap::const_iterator utl_it =
        _upper_to_lower.find(elem);
      if (utl_it != _upper_to_lower.end())
        {
          const Elem * neighbor = utl_it->second;
          if (neighbor->processor_id() != p)
            coupled_elements.insert (std::make_pair(neighbor, null_mat));
        }

    }
}
<commit_msg>Handle crack lookup reinit on distributed meshes<commit_after>// local includes
#include "augment_sparsity_on_interface.h"

// libMesh includes
#include "libmesh/elem.h"

using namespace libMesh;

AugmentSparsityOnInterface::AugmentSparsityOnInterface(MeshBase & mesh,
                                                       boundary_id_type crack_boundary_lower,
                                                       boundary_id_type crack_boundary_upper) :
  _mesh(mesh),
  _crack_boundary_lower(crack_boundary_lower),
  _crack_boundary_upper(crack_boundary_upper),
  _initialized(false)
{
  this->mesh_reinit();
}

const ElementSideMap & AugmentSparsityOnInterface::get_lower_to_upper() const
{
  libmesh_assert(this->_initialized);
  return _lower_to_upper;
}

void AugmentSparsityOnInterface::mesh_reinit ()
{
  this->_initialized = true;

  // Loop over all elements (not just local elements) to make sure we find
  // "neighbor" elements on opposite sides of the crack.

  MeshBase::const_element_iterator       el     = _mesh.active_elements_begin();
  const MeshBase::const_element_iterator end_el = _mesh.active_elements_end();

  // Map from (elem, side) to centroid
  std::map< std::pair<const Elem *, unsigned char>, Point> lower_centroids;
  std::map< std::pair<const Elem *, unsigned char>, Point> upper_centroids;

  for ( ; el != end_el; ++el)
    {
      const Elem * elem = *el;

      {
        for (unsigned char side=0; side<elem->n_sides(); side++)
          if (elem->neighbor_ptr(side) == libmesh_nullptr)
            {
              if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_lower))
                {
                  UniquePtr<const Elem> side_elem = elem->build_side_ptr(side);

                  lower_centroids[std::make_pair(elem, side)] = side_elem->centroid();
                }
            }
      }

      {
        for (unsigned char side=0; side<elem->n_sides(); side++)
          if (elem->neighbor_ptr(side) == libmesh_nullptr)
            {
              if (_mesh.get_boundary_info().has_boundary_id(elem, side, _crack_boundary_upper))
                {
                  UniquePtr<const Elem> side_elem = elem->build_side_ptr(side);

                  upper_centroids[std::make_pair(elem, side)] = side_elem->centroid();
                }
            }
      }
    }

  // If we're doing a reinit on a distributed mesh then we may not see
  // all the centroids, or even a matching number of centroids.
  // std::size_t n_lower_centroids = lower_centroids.size();
  // std::size_t n_upper_centroids = upper_centroids.size();
  // libmesh_assert(n_lower_centroids == n_upper_centroids);

  // Clear _lower_to_upper. This map will be used for matrix assembly later on.
  _lower_to_upper.clear();

  // Clear _upper_to_lower. This map will be used for element ghosting
  // on distributed meshes, communication send_list construction in
  // parallel, and sparsity calculations
  _upper_to_lower.clear();

  // We do an N^2 search to find elements with matching centroids. This could be optimized,
  // e.g. by first sorting the centroids based on their (x,y,z) location.
  {
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it     = lower_centroids.begin();
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator it_end = lower_centroids.end();
    for ( ; it != it_end; ++it)
      {
        Point lower_centroid = it->second;

        // find closest centroid in upper_centroids
        Real min_distance = std::numeric_limits<Real>::max();

        std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it     = upper_centroids.begin();
        std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end();

        for ( ; inner_it != inner_it_end; ++inner_it)
          {
            Point upper_centroid = inner_it->second;

            Real distance = (upper_centroid - lower_centroid).norm();
            if (distance < min_distance)
              {
                min_distance = distance;
                _lower_to_upper[it->first] = inner_it->first.first;
              }
          }

	// For pairs with local elements, we should have found a
	// matching pair by now.
        const Elem * elem     = it->first.first;
        const Elem * neighbor = _lower_to_upper[it->first];
        if (min_distance < TOLERANCE)
          {
            // fill up the inverse map
            _upper_to_lower[neighbor] = elem;
          }
        else
          {
            libmesh_assert_not_equal_to(elem->processor_id(), _mesh.processor_id());
	    // This must have a false positive; a remote element would
	    // have been closer.
	    _lower_to_upper.erase(it->first);
          }
      }

    // Let's make sure we didn't miss any upper elements either
#ifndef NDEBUG
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it     = upper_centroids.begin();
    std::map< std::pair<const Elem *, unsigned char>, Point>::iterator inner_it_end = upper_centroids.end();

    for ( ; inner_it != inner_it_end; ++inner_it)
      {
        const Elem * neighbor = inner_it->first.first;
        if (neighbor->processor_id() != _mesh.processor_id())
          continue;
        ElementMap::const_iterator utl_it =
          _upper_to_lower.find(neighbor);
        libmesh_assert(utl_it != _upper_to_lower.end());
      }
#endif
  }
}

void AugmentSparsityOnInterface::operator()
  (const MeshBase::const_element_iterator & range_begin,
   const MeshBase::const_element_iterator & range_end,
   processor_id_type p,
   map_type & coupled_elements)
{
  libmesh_assert(this->_initialized);

  const CouplingMatrix * const null_mat = libmesh_nullptr;

  for (MeshBase::const_element_iterator elem_it = range_begin;
       elem_it != range_end; ++elem_it)
    {
      const Elem * const elem = *elem_it;

      if (elem->processor_id() != p)
        coupled_elements.insert (std::make_pair(elem, null_mat));

      for (unsigned int side=0; side<elem->n_sides(); side++)
        if (elem->neighbor_ptr(side) == libmesh_nullptr)
          {
            ElementSideMap::const_iterator ltu_it =
              _lower_to_upper.find(std::make_pair(elem, side));
            if (ltu_it != _lower_to_upper.end())
              {
                const Elem * neighbor = ltu_it->second;
                if (neighbor->processor_id() != p)
                  coupled_elements.insert (std::make_pair(neighbor, null_mat));
              }
          }

      ElementMap::const_iterator utl_it =
        _upper_to_lower.find(elem);
      if (utl_it != _upper_to_lower.end())
        {
          const Elem * neighbor = utl_it->second;
          if (neighbor->processor_id() != p)
            coupled_elements.insert (std::make_pair(neighbor, null_mat));
        }

    }
}
<|endoftext|>