<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 "SimpleTest.h"

#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/library/ActiveMQCPP.h>
#include <activemq/util/CMSListener.h>
#include <activemq/exceptions/ActiveMQException.h>

#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testAutoAck() {

    try {

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );

        CMSListener listener( session );

        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        consumer->setMessageListener( &listener );
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
        auto_ptr<cms::BytesMessage> bytesMessage( session->createBytesMessage() );

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            producer->send( txtMessage.get() );
        }

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            producer->send( bytesMessage.get() );
        }

        // Wait for the messages to get here
        listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );

        unsigned int numReceived = listener.getNumReceived();
        CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testClientAck() {

    try {

        cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );
        cmsProvider->reconnectSession();

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );

        CMSListener listener( session );

        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        consumer->setMessageListener( &listener );
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
        auto_ptr<cms::BytesMessage> bytesMessage( session->createBytesMessage() );

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            producer->send( txtMessage.get() );
        }

        for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
            producer->send( bytesMessage.get() );
        }

        // Wait for the messages to get here
        listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );

        unsigned int numReceived = listener.getNumReceived();
        CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerWithNullDestination() {

    try{

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );

        CMSListener listener( session );

        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        consumer->setMessageListener( &listener );
        cms::MessageProducer* producer = cmsProvider->getNoDestProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

        producer->send( cmsProvider->getDestination(), txtMessage.get() );

        // Wait for the messages to get here
        listener.asyncWaitForMessages( 1 );

        unsigned int numReceived = listener.getNumReceived();
        CPPUNIT_ASSERT( numReceived == 1 );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerSendWithNullDestination() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an InvalidDestinationException",
        producer->send( NULL, txtMessage.get() ),
        cms::InvalidDestinationException );

    producer = cmsProvider->getNoDestProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an UnsupportedOperationException",
        producer->send( NULL, txtMessage.get() ),
        cms::UnsupportedOperationException );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerSendToNonDefaultDestination() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
    auto_ptr<cms::Destination> destination( session->createTemporaryTopic() );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an UnsupportedOperationException",
        producer->send( destination.get(), txtMessage.get() ),
        cms::UnsupportedOperationException );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testSyncReceive() {

    try {

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );
        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

        // Send some text messages
        producer->send( txtMessage.get() );

        auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testSyncReceiveClientAck() {

    try {

        cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );
        cmsProvider->reconnectSession();

        // Create CMS Object for Comms
        cms::Session* session( cmsProvider->getSession() );
        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

        // Send some text messages
        producer->send( txtMessage.get() );

        auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testMultipleConnections() {

    try {

        // Create CMS Object for Comms
        auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
        auto_ptr<cms::Connection> connection1( factory->createConnection() );
        connection1->start();

        auto_ptr<cms::Connection> connection2( factory->createConnection() );
        connection2->start();

        CPPUNIT_ASSERT( connection1->getClientID() != connection2->getClientID() );

        auto_ptr<cms::Session> session1( connection1->createSession() );
        auto_ptr<cms::Session> session2( connection1->createSession() );

        auto_ptr<cms::Topic> topic( session1->createTopic( UUID::randomUUID().toString() ) );

        auto_ptr<cms::MessageConsumer> consumer1( session1->createConsumer( topic.get() ) );
        auto_ptr<cms::MessageConsumer> consumer2( session2->createConsumer( topic.get() ) );

        auto_ptr<cms::MessageProducer> producer( session2->createProducer( topic.get() ) );
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> textMessage( session2->createTextMessage() );

        // Send some text messages
        producer->send( textMessage.get() );

        auto_ptr<cms::Message> message( consumer1->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );

        message.reset( consumer2->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );

        // Clean up if we can
        consumer1->close();
        consumer2->close();
        producer->close();
        session1->close();
        session2->close();

        this->cmsProvider->destroyDestination( topic.get() );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testMultipleSessions() {
    try {

        // Create CMS Object for Comms
        auto_ptr<cms::Session> session1( cmsProvider->getConnection()->createSession() );
        auto_ptr<cms::Session> session2( cmsProvider->getConnection()->createSession() );

        auto_ptr<cms::Topic> topic( session1->createTopic( UUID::randomUUID().toString() ) );

        auto_ptr<cms::MessageConsumer> consumer1( session1->createConsumer( topic.get() ) );
        auto_ptr<cms::MessageConsumer> consumer2( session2->createConsumer( topic.get() ) );

        auto_ptr<cms::MessageProducer> producer( session2->createProducer( topic.get() ) );
        producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

        auto_ptr<cms::TextMessage> textMessage( session2->createTextMessage() );

        // Send some text messages
        producer->send( textMessage.get() );

        auto_ptr<cms::Message> message( consumer1->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );

        message.reset( consumer2->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );

        // Clean up if we can
        consumer1->close();
        consumer2->close();
        producer->close();
        session1->close();
        session2->close();

        this->cmsProvider->destroyDestination( topic.get() );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testReceiveAlreadyInQueue() {

    try {

        // Create CMS Object for Comms
        auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
        auto_ptr<cms::Connection> connection(factory->createConnection());

        auto_ptr<cms::Session> session(connection->createSession());
        auto_ptr<cms::Topic> topic(session->createTopic(UUID::randomUUID().toString()));
        auto_ptr<cms::MessageConsumer> consumer(session->createConsumer(topic.get()));
        auto_ptr<cms::MessageProducer> producer(session->createProducer(topic.get()));
        producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
        auto_ptr<cms::TextMessage> textMessage(session->createTextMessage());

        // Send some text messages
        producer->send(textMessage.get());

        Thread::sleep(250);

        connection->start();

        auto_ptr<cms::Message> message(consumer->receive(2000));
        CPPUNIT_ASSERT( message.get() != NULL );

        // Clean up if we can
        consumer->close();
        producer->close();
        session->close();

        this->cmsProvider->destroyDestination(topic.get());
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testQuickCreateAndDestroy() {

    try{

        auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
        auto_ptr<cms::Connection> connection( factory->createConnection() );
        auto_ptr<cms::Session> session( connection->createSession() );

        session.reset( NULL );
        connection.reset( NULL );

        connection.reset( factory->createConnection() );
        session.reset( connection->createSession() );
        connection->start();

        session.reset( NULL );
        connection.reset( NULL );

        for( int i = 0; i < 50; ++i ) {
            CMSProvider lcmsProvider( this->getBrokerURL() );
            lcmsProvider.getSession();
            lcmsProvider.getConsumer();
            lcmsProvider.getProducer();
        }

    } catch ( CMSException& e ) {
        e.printStackTrace();
        CPPUNIT_ASSERT( false );
    }
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testBytesMessageSendRecv() {

    try {

        // Create CMS Object for Comms
        cms::Session* session(cmsProvider->getSession());
        cms::MessageConsumer* consumer = cmsProvider->getConsumer();
        cms::MessageProducer* producer = cmsProvider->getProducer();
        producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

        auto_ptr<cms::BytesMessage> bytesMessage(session->createBytesMessage());

        bytesMessage->writeBoolean(true);
        bytesMessage->writeByte(127);
        bytesMessage->writeDouble(123456.789);
        bytesMessage->writeInt(65537);
        bytesMessage->writeString("TEST-STRING");

        // Send some text messages
        producer->send( bytesMessage.get() );

        auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
        CPPUNIT_ASSERT( message.get() != NULL );

        CPPUNIT_ASSERT_THROW_MESSAGE(
            "Should throw an ActiveMQExceptio",
            message->setStringProperty( "FOO", "BAR" ),
            cms::CMSException );

        BytesMessage* bytesMessage2 = dynamic_cast<cms::BytesMessage*>( message.get() );
        CPPUNIT_ASSERT( bytesMessage2 != NULL );
        CPPUNIT_ASSERT_THROW_MESSAGE(
            "Should throw an ActiveMQExceptio",
            bytesMessage2->writeBoolean( false ),
            cms::CMSException );

        CPPUNIT_ASSERT( bytesMessage2->readBoolean() == true );
        CPPUNIT_ASSERT( bytesMessage2->readByte() == 127 );
        CPPUNIT_ASSERT( bytesMessage2->readDouble() == 123456.789 );
        CPPUNIT_ASSERT( bytesMessage2->readInt() == 65537 );
        CPPUNIT_ASSERT( bytesMessage2->readString() == "TEST-STRING" );
    }
    AMQ_CATCH_RETHROW( ActiveMQException )
    AMQ_CATCHALL_THROW( ActiveMQException )
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testLibraryInitShutdownInit() {

    {
        this->tearDown();
        // Shutdown the ActiveMQ library
        CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::shutdownLibrary() );
    }
    {
        // Initialize the ActiveMQ library
        CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::initializeLibrary() );
        cmsProvider.reset(new util::CMSProvider(getBrokerURL()));
    }
}
<commit_msg>https://issues.apache.org/jira/browse/AMQCPP-448<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 "SimpleTest.h"

#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/library/ActiveMQCPP.h>
#include <activemq/util/CMSListener.h>
#include <activemq/exceptions/ActiveMQException.h>

#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testAutoAck() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    consumer->setMessageListener( &listener );
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
    auto_ptr<cms::BytesMessage> bytesMessage( session->createBytesMessage() );

    for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
        producer->send( txtMessage.get() );
    }

    for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
        producer->send( bytesMessage.get() );
    }

    // Wait for the messages to get here
    listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );

    unsigned int numReceived = listener.getNumReceived();
    CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testClientAck() {

    cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );
    cmsProvider->reconnectSession();

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    consumer->setMessageListener( &listener );
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
    auto_ptr<cms::BytesMessage> bytesMessage( session->createBytesMessage() );

    for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
        producer->send( txtMessage.get() );
    }

    for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {
        producer->send( bytesMessage.get() );
    }

    // Wait for the messages to get here
    listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );

    unsigned int numReceived = listener.getNumReceived();
    CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerWithNullDestination() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    consumer->setMessageListener( &listener );
    cms::MessageProducer* producer = cmsProvider->getNoDestProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

    producer->send( cmsProvider->getDestination(), txtMessage.get() );

    // Wait for the messages to get here
    listener.asyncWaitForMessages( 1 );

    unsigned int numReceived = listener.getNumReceived();
    CPPUNIT_ASSERT( numReceived == 1 );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerSendWithNullDestination() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an InvalidDestinationException",
        producer->send( NULL, txtMessage.get() ),
        cms::InvalidDestinationException );

    producer = cmsProvider->getNoDestProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an UnsupportedOperationException",
        producer->send( NULL, txtMessage.get() ),
        cms::UnsupportedOperationException );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testProducerSendToNonDefaultDestination() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );

    CMSListener listener( session );

    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );
    auto_ptr<cms::Destination> destination( session->createTemporaryTopic() );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should Throw an UnsupportedOperationException",
        producer->send( destination.get(), txtMessage.get() ),
        cms::UnsupportedOperationException );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testSyncReceive() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

    // Send some text messages
    producer->send( txtMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testSyncReceiveClientAck() {

    cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );
    cmsProvider->reconnectSession();

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> txtMessage( session->createTextMessage( "TEST MESSAGE" ) );

    // Send some text messages
    producer->send( txtMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testMultipleConnections() {

    // Create CMS Object for Comms
    auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
    auto_ptr<cms::Connection> connection1( factory->createConnection() );
    connection1->start();

    auto_ptr<cms::Connection> connection2( factory->createConnection() );
    connection2->start();

    CPPUNIT_ASSERT( connection1->getClientID() != connection2->getClientID() );

    auto_ptr<cms::Session> session1( connection1->createSession() );
    auto_ptr<cms::Session> session2( connection1->createSession() );

    auto_ptr<cms::Topic> topic( session1->createTopic( UUID::randomUUID().toString() ) );

    auto_ptr<cms::MessageConsumer> consumer1( session1->createConsumer( topic.get() ) );
    auto_ptr<cms::MessageConsumer> consumer2( session2->createConsumer( topic.get() ) );

    auto_ptr<cms::MessageProducer> producer( session2->createProducer( topic.get() ) );
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> textMessage( session2->createTextMessage() );

    // Send some text messages
    producer->send( textMessage.get() );

    auto_ptr<cms::Message> message( consumer1->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    message.reset( consumer2->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    // Clean up if we can
    consumer1->close();
    consumer2->close();
    producer->close();
    session1->close();
    session2->close();

    this->cmsProvider->destroyDestination( topic.get() );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testMultipleSessions() {

    // Create CMS Object for Comms
    auto_ptr<cms::Session> session1( cmsProvider->getConnection()->createSession() );
    auto_ptr<cms::Session> session2( cmsProvider->getConnection()->createSession() );

    auto_ptr<cms::Topic> topic( session1->createTopic( UUID::randomUUID().toString() ) );

    auto_ptr<cms::MessageConsumer> consumer1( session1->createConsumer( topic.get() ) );
    auto_ptr<cms::MessageConsumer> consumer2( session2->createConsumer( topic.get() ) );

    auto_ptr<cms::MessageProducer> producer( session2->createProducer( topic.get() ) );
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::TextMessage> textMessage( session2->createTextMessage() );

    // Send some text messages
    producer->send( textMessage.get() );

    auto_ptr<cms::Message> message( consumer1->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    message.reset( consumer2->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    // Clean up if we can
    consumer1->close();
    consumer2->close();
    producer->close();
    session1->close();
    session2->close();

    this->cmsProvider->destroyDestination( topic.get() );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testReceiveAlreadyInQueue() {

    // Create CMS Object for Comms
    auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
    auto_ptr<cms::Connection> connection(factory->createConnection());

    auto_ptr<cms::Session> session(connection->createSession());
    auto_ptr<cms::Topic> topic(session->createTopic(UUID::randomUUID().toString()));
    auto_ptr<cms::MessageConsumer> consumer(session->createConsumer(topic.get()));
    auto_ptr<cms::MessageProducer> producer(session->createProducer(topic.get()));
    producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
    auto_ptr<cms::TextMessage> textMessage(session->createTextMessage());

    // Send some text messages
    producer->send(textMessage.get());

    Thread::sleep(250);

    connection->start();

    auto_ptr<cms::Message> message(consumer->receive(2000));
    CPPUNIT_ASSERT( message.get() != NULL );

    // Clean up if we can
    consumer->close();
    producer->close();
    session->close();

    this->cmsProvider->destroyDestination(topic.get());
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testQuickCreateAndDestroy() {

    auto_ptr<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));
    auto_ptr<cms::Connection> connection( factory->createConnection() );
    auto_ptr<cms::Session> session( connection->createSession() );

    session.reset( NULL );
    connection.reset( NULL );

    connection.reset( factory->createConnection() );
    session.reset( connection->createSession() );
    connection->start();

    session.reset( NULL );
    connection.reset( NULL );

    for( int i = 0; i < 50; ++i ) {
        CMSProvider lcmsProvider( this->getBrokerURL() );
        lcmsProvider.getSession();
        lcmsProvider.getConsumer();
        lcmsProvider.getProducer();
    }
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testBytesMessageSendRecv() {

    // Create CMS Object for Comms
    cms::Session* session(cmsProvider->getSession());
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);

    auto_ptr<cms::BytesMessage> bytesMessage(session->createBytesMessage());

    bytesMessage->writeBoolean(true);
    bytesMessage->writeByte(127);
    bytesMessage->writeDouble(123456.789);
    bytesMessage->writeInt(65537);
    bytesMessage->writeString("TEST-STRING");

    // Send some text messages
    producer->send( bytesMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should throw an ActiveMQExceptio",
        message->setStringProperty( "FOO", "BAR" ),
        cms::CMSException );

    BytesMessage* bytesMessage2 = dynamic_cast<cms::BytesMessage*>( message.get() );
    CPPUNIT_ASSERT( bytesMessage2 != NULL );
    CPPUNIT_ASSERT_THROW_MESSAGE(
        "Should throw an ActiveMQExceptio",
        bytesMessage2->writeBoolean( false ),
        cms::CMSException );

    CPPUNIT_ASSERT( bytesMessage2->getBodyLength() > 0 );

    unsigned char* result = bytesMessage2->getBodyBytes();
    CPPUNIT_ASSERT( result != NULL );
    delete result;

    bytesMessage2->reset();

    CPPUNIT_ASSERT( bytesMessage2->readBoolean() == true );
    CPPUNIT_ASSERT( bytesMessage2->readByte() == 127 );
    CPPUNIT_ASSERT( bytesMessage2->readDouble() == 123456.789 );
    CPPUNIT_ASSERT( bytesMessage2->readInt() == 65537 );
    CPPUNIT_ASSERT( bytesMessage2->readString() == "TEST-STRING" );
}

////////////////////////////////////////////////////////////////////////////////
void SimpleTest::testLibraryInitShutdownInit() {

    {
        this->tearDown();
        // Shutdown the ActiveMQ library
        CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::shutdownLibrary() );
    }
    {
        // Initialize the ActiveMQ library
        CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::initializeLibrary() );
        cmsProvider.reset(new util::CMSProvider(getBrokerURL()));
    }
}
<|endoftext|>


<commit_before>#ifndef VIENNAFVM_BOUNDARY_HPP
#define VIENNAFVM_BOUNDARY_HPP

/* =========================================================================
   Copyright (c) 2012, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.
                             -----------------
               ViennaFVM - The Vienna Finite Volume Method Library
                             -----------------

   Author:     Karl Rupp                          rupp@iue.tuwien.ac.at
               (add your name here)

   License:    MIT (X11), see file LICENSE in the ViennaFEM base directory
============================================================================ */

#include "viennafvm/forwards.h"

#include "viennamath/forwards.h"
#include "viennamath/manipulation/substitute.hpp"
#include "viennamath/expression.hpp"
#include "viennadata/api.hpp"

#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/segmentation.hpp"

#include <map>

/** @file  boundary.hpp
    @brief Provide convenience routines for setting boundary conditions
*/

namespace viennafvm
{

  /** @brief Assigns a value to the quantity of all cells of the segment or mesh */
  template <typename QuantityType, typename DomainSegmentType>
  void set_dirichlet_boundary(QuantityType & quan,
                              DomainSegmentType const & seg,
                              double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_boundary_value(*cit, value);
      quan.set_boundary_type(*cit, viennafvm::BOUNDARY_DIRICHLET);
    }
  }

  /** @brief Assigns values to the quantity of all cells of the segment or mesh.
             The keys of the 'values' container must correspond to the cell IDs. */
  template <typename QuantityType, typename DomainSegmentType>
  void set_dirichlet_boundary(QuantityType                          & quan,
                              DomainSegmentType               const & seg,
                              std::map<std::size_t, double>   const & values)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_boundary_value(*cit, values.at(cit->id().get()));
      quan.set_boundary_type(*cit, viennafvm::BOUNDARY_DIRICHLET);
    }
  }

  /** @brief Adds a value to an already assigned quantity value on all cells of the segment or mesh */
  template <typename QuantityType, typename DomainSegmentType>
  void addto_dirichlet_boundary(QuantityType & quan,
                              DomainSegmentType const & seg,
                              double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      // if this cell has already been assigned a dirichlet value,
      // add the new value to the old one
      if(quan.get_boundary_type(*cit) == viennafvm::BOUNDARY_DIRICHLET)
      {
        quan.set_boundary_value(*cit, quan.get_boundary_value(*cit) + value);
      }
      // if this cell has infact not been assigend a dirichlet value,
      // simply assign the new value
      //
      else
      {
        quan.set_boundary_value(*cit, value);
        quan.set_boundary_type(*cit, viennafvm::BOUNDARY_DIRICHLET);
      }
    }
  }

  /** @brief Set the values of a quantity on all cells with a constant value */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType & quan,
                         DomainSegmentType const & seg,
                         double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, value);
    }
  }

  /** @brief Set the values of a quantity on all cells according to an externally provided values container.
             The keys of the 'values' container must correspond to the cell IDs. */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType                         & quan,
                         DomainSegmentType              const & seg,
                         std::map<std::size_t, double>  const & values)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, values.at(cit->id().get()));
    }
  }

  /** @brief Transfer the quantity values from another quantity */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType & quan,
                         DomainSegmentType const & seg,
                         QuantityType & source)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, source.get_value(*cit));
    }
  }

  /** @brief Assign the quantity based on an unary functor taking the cell id as input and returning the corresponding cell-based values */
  template <typename QuantityType, typename DomainSegmentType, typename FunctorT>
  void set_initial_value(QuantityType            & quan,
                         DomainSegmentType const & seg,
                         FunctorT                  functor)
  {
    set_initial_value(quan, seg, &functor);
  }

  /** @brief Assign the quantity based on a pointer to a unary functor taking the cell id as input and returning the corresponding cell-based values */
  template <typename QuantityType, typename DomainSegmentType, typename FunctorT>
  void set_initial_value(QuantityType            & quan,
                         DomainSegmentType const & seg,
                         FunctorT                * functor)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, (*functor)(cit->id().get()));
    }
  }

  /** @brief Tag the quantity as a solution quantity */
  template <typename QuantityType, typename DomainSegmentType>
  void set_unknown(QuantityType & quan,
                   DomainSegmentType const & seg,
                   bool set_to = true)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_unknown_mask(*cit, set_to);
    }
  }

}
#endif
<commit_msg>removed set_dirichlet_boundary(.., map)<commit_after>#ifndef VIENNAFVM_BOUNDARY_HPP
#define VIENNAFVM_BOUNDARY_HPP

/* =========================================================================
   Copyright (c) 2012, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.
                             -----------------
               ViennaFVM - The Vienna Finite Volume Method Library
                             -----------------

   Author:     Karl Rupp                          rupp@iue.tuwien.ac.at
               (add your name here)

   License:    MIT (X11), see file LICENSE in the ViennaFEM base directory
============================================================================ */

#include "viennafvm/forwards.h"

#include "viennamath/forwards.h"
#include "viennamath/manipulation/substitute.hpp"
#include "viennamath/expression.hpp"
#include "viennadata/api.hpp"

#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/segmentation.hpp"

#include <map>

/** @file  boundary.hpp
    @brief Provide convenience routines for setting boundary conditions
*/

namespace viennafvm
{

  /** @brief Assigns a value to the quantity of all cells of the segment or mesh */
  template <typename QuantityType, typename DomainSegmentType>
  void set_dirichlet_boundary(QuantityType & quan,
                              DomainSegmentType const & seg,
                              double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_boundary_value(*cit, value);
      quan.set_boundary_type(*cit, viennafvm::BOUNDARY_DIRICHLET);
    }
  }

  /** @brief Adds a value to an already assigned quantity value on all cells of the segment or mesh */
  template <typename QuantityType, typename DomainSegmentType>
  void addto_dirichlet_boundary(QuantityType & quan,
                              DomainSegmentType const & seg,
                              double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      // if this cell has already been assigned a dirichlet value,
      // add the new value to the old one
      if(quan.get_boundary_type(*cit) == viennafvm::BOUNDARY_DIRICHLET)
      {
        quan.set_boundary_value(*cit, quan.get_boundary_value(*cit) + value);
      }
      // if this cell has infact not been assigend a dirichlet value,
      // simply assign the new value
      //
      else
      {
        quan.set_boundary_value(*cit, value);
        quan.set_boundary_type(*cit, viennafvm::BOUNDARY_DIRICHLET);
      }
    }
  }

  /** @brief Set the values of a quantity on all cells with a constant value */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType & quan,
                         DomainSegmentType const & seg,
                         double value)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, value);
    }
  }

  /** @brief Set the values of a quantity on all cells according to an externally provided values container.
             The keys of the 'values' container must correspond to the cell IDs. */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType                         & quan,
                         DomainSegmentType              const & seg,
                         std::map<std::size_t, double>  const & values)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, values.at(cit->id().get()));
    }
  }

  /** @brief Transfer the quantity values from another quantity */
  template <typename QuantityType, typename DomainSegmentType>
  void set_initial_value(QuantityType & quan,
                         DomainSegmentType const & seg,
                         QuantityType & source)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, source.get_value(*cit));
    }
  }

  /** @brief Assign the quantity based on an unary functor taking the cell id as input and returning the corresponding cell-based values */
  template <typename QuantityType, typename DomainSegmentType, typename FunctorT>
  void set_initial_value(QuantityType            & quan,
                         DomainSegmentType const & seg,
                         FunctorT                  functor)
  {
    set_initial_value(quan, seg, &functor);
  }

  /** @brief Assign the quantity based on a pointer to a unary functor taking the cell id as input and returning the corresponding cell-based values */
  template <typename QuantityType, typename DomainSegmentType, typename FunctorT>
  void set_initial_value(QuantityType            & quan,
                         DomainSegmentType const & seg,
                         FunctorT                * functor)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_value(*cit, (*functor)(cit->id().get()));
    }
  }

  /** @brief Tag the quantity as a solution quantity */
  template <typename QuantityType, typename DomainSegmentType>
  void set_unknown(QuantityType & quan,
                   DomainSegmentType const & seg,
                   bool set_to = true)
  {
    typedef typename viennagrid::result_of::cell_tag<DomainSegmentType>::type CellTag;

    typedef typename viennagrid::result_of::const_element_range<DomainSegmentType, CellTag>::type  CellContainer;
    typedef typename viennagrid::result_of::iterator<CellContainer>::type                       CellIterator;

    CellContainer cells(seg);
    for (CellIterator cit  = cells.begin();
                      cit != cells.end();
                    ++cit)
    {
      quan.set_unknown_mask(*cit, set_to);
    }
  }

}
#endif
<|endoftext|>


<commit_before>//===-- StringTableBuilder.cpp - String table building utility ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/StringTableBuilder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Endian.h"

using namespace llvm;

static int compareBySuffix(const StringRef *AP, const StringRef *BP) {
  StringRef a = *AP;
  StringRef b = *BP;
  size_t sizeA = a.size();
  size_t sizeB = b.size();
  size_t len = std::min(sizeA, sizeB);
  for (size_t i = 0; i < len; ++i) {
    char ca = a[sizeA - i - 1];
    char cb = b[sizeB - i - 1];
    if (ca != cb)
      return cb - ca;
  }
  return sizeB - sizeA;
}

void StringTableBuilder::finalize(Kind kind) {
  SmallVector<StringRef, 8> Strings;
  Strings.reserve(StringIndexMap.size());

  for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i)
    Strings.push_back(i->getKey());

  array_pod_sort(Strings.begin(), Strings.end(), compareBySuffix);

  switch (kind) {
  case ELF:
  case MachO:
    // Start the table with a NUL byte.
    StringTable += '\x00';
    break;
  case WinCOFF:
    // Make room to write the table size later.
    StringTable.append(4, '\x00');
    break;
  }

  StringRef Previous;
  for (StringRef s : Strings) {
    if (kind == WinCOFF)
      assert(s.size() > COFF::NameSize && "Short string in COFF string table!");

    if (Previous.endswith(s)) {
      StringIndexMap[s] = StringTable.size() - 1 - s.size();
      continue;
    }

    StringIndexMap[s] = StringTable.size();
    StringTable += s;
    StringTable += '\x00';
    Previous = s;
  }

  switch (kind) {
  case ELF:
    break;
  case MachO:
    // Pad to multiple of 4.
    while (StringTable.size() % 4)
      StringTable += '\x00';
    break;
  case WinCOFF:
    // Write the table size in the first word.
    assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
    uint32_t size = static_cast<uint32_t>(StringTable.size());
    support::endian::write<uint32_t, support::little, support::unaligned>(
        StringTable.data(), size);
    break;
  }
}

void StringTableBuilder::clear() {
  StringTable.clear();
  StringIndexMap.clear();
}
<commit_msg>Avoid hash lookups when finalizing StringTableBuilder. NFC.<commit_after>//===-- StringTableBuilder.cpp - String table building utility ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/StringTableBuilder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Endian.h"

using namespace llvm;

static int compareBySuffix(StringMapEntry<size_t> *const *AP,
                           StringMapEntry<size_t> *const *BP) {
  StringRef a = (*AP)->first();
  StringRef b = (*BP)->first();
  size_t sizeA = a.size();
  size_t sizeB = b.size();
  size_t len = std::min(sizeA, sizeB);
  for (size_t i = 0; i < len; ++i) {
    char ca = a[sizeA - i - 1];
    char cb = b[sizeB - i - 1];
    if (ca != cb)
      return cb - ca;
  }
  return sizeB - sizeA;
}

void StringTableBuilder::finalize(Kind kind) {
  std::vector<StringMapEntry<size_t> *> Strings;
  Strings.reserve(StringIndexMap.size());
  for (StringMapEntry<size_t> &P : StringIndexMap)
    Strings.push_back(&P);

  array_pod_sort(Strings.begin(), Strings.end(), compareBySuffix);

  switch (kind) {
  case ELF:
  case MachO:
    // Start the table with a NUL byte.
    StringTable += '\x00';
    break;
  case WinCOFF:
    // Make room to write the table size later.
    StringTable.append(4, '\x00');
    break;
  }

  StringRef Previous;
  for (StringMapEntry<size_t> *P : Strings) {
    StringRef s = P->first();
    if (kind == WinCOFF)
      assert(s.size() > COFF::NameSize && "Short string in COFF string table!");

    if (Previous.endswith(s)) {
      P->second = StringTable.size() - 1 - s.size();
      continue;
    }

    P->second = StringTable.size();
    StringTable += s;
    StringTable += '\x00';
    Previous = s;
  }

  switch (kind) {
  case ELF:
    break;
  case MachO:
    // Pad to multiple of 4.
    while (StringTable.size() % 4)
      StringTable += '\x00';
    break;
  case WinCOFF:
    // Write the table size in the first word.
    assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
    uint32_t size = static_cast<uint32_t>(StringTable.size());
    support::endian::write<uint32_t, support::little, support::unaligned>(
        StringTable.data(), size);
    break;
  }
}

void StringTableBuilder::clear() {
  StringTable.clear();
  StringIndexMap.clear();
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Yasser Asmi
// Released under the MIT License (http://opensource.org/licenses/MIT)

#include "jvar.h"

#include <iostream>

using namespace jvar;

/**
 * \example func.cpp
 * This example shows how to use function objects inside variants.  Function objects
 * can contain closure/enviroment for the function object and can be called from code
 * passing in additional parameters.
 */

// Actual C++ function--it receives env and arg as Variants.
Variant convert(Variant& env, Variant& arg)
{
    Variant ret;
    ret = ((double)env["offset"] + (double)arg[0]) * (double)env["factor"];
    return ret.toFixed(2) + " " + env["toUnit"].toString();
}

// This fuction creates a function object--to do the conversion based some
// parameters.  Once created function object has all the info it needs
Variant makeConverter(Variant tounit, Variant factor, Variant offset = VNULL)
{
    Variant funcobj;

    funcobj.createFunction(convert);
    funcobj.addEnv("toUnit", tounit);
    funcobj.addEnv("factor", factor);
    funcobj.addEnv("offset", offset);

    return funcobj;
}

// This function takes as many parameters as you want to give it - it is
// variadic, like printf, but is semi-type-safe.
Variant print(Variant& env, Variant& arg)
{
    for(size_t i = 0; i < arg.length(); ++i)
    {
        std::cout << arg[i].toString() << " ";
    }
}

int main(int argc, char** argv)
{
    Variant res;

    // Make function objects

    Variant milesToKm = makeConverter("km", 1.60936);
    Variant poundsToKg = makeConverter("kg", 0.45460);
    Variant farenheitToCelsius = makeConverter("degrees-c", 0.5556, -32l);

    // Call function objects and print results

    res = milesToKm(10);
    printf("milestokm(10) = %s\n", res.toString().c_str());

    res = poundsToKg(2.5);
    printf("poundsToKg(2.5) = %s\n", res.toString().c_str());

    res = farenheitToCelsius(98);
    printf("farenheitToCelsius(98l) = %s\n", res.toString().c_str());

    // Printed:
    // milestokm(10) = 16.09 km
    // poundsToKg(2.5) = 1.14 kg
    // farenheitToCelsius(98l) = 36.67 degrees-c

    Variant multi;
    multi.createFunction(print);
    multi({"test", 2.0, 3, 4, "five", "six"});

    // Printed:
    // test 2.0 3 4 five six
}
<commit_msg>Clarified comments in func.cpp<commit_after>// Copyright (c) 2014 Yasser Asmi
// Released under the MIT License (http://opensource.org/licenses/MIT)

#include "jvar.h"

#include <iostream>

using namespace jvar;

/**
 * \example func.cpp
 * This example shows how to use function objects inside variants.  Function objects
 * can contain closure/enviroment for the function object and can be called from code
 * passing in additional parameters.
 *
 * Functions can also take as many parameters as wanted at runtime (see \ref ::print()),
 * so provide a semi-type-safe way of implementing variadic functions in C++.
 */

// Actual C++ function--it receives env and arg as Variants.
Variant convert(Variant& env, Variant& arg)
{
    Variant ret;
    ret = ((double)env["offset"] + (double)arg[0]) * (double)env["factor"];
    return ret.toFixed(2) + " " + env["toUnit"].toString();
}

// This fuction creates a function object--to do the conversion based some
// parameters.  Once created function object has all the info it needs
Variant makeConverter(Variant tounit, Variant factor, Variant offset = VNULL)
{
    Variant funcobj;

    funcobj.createFunction(convert);
    funcobj.addEnv("toUnit", tounit);
    funcobj.addEnv("factor", factor);
    funcobj.addEnv("offset", offset);

    return funcobj;
}

// This function takes as many parameters as you want to give it - it is
// variadic, like printf, but is semi-type-safe.
Variant print(Variant& env, Variant& arg)
{
    for(size_t i = 0; i < arg.length(); ++i)
    {
        std::cout << arg[i].toString() << " ";
    }
}

int main(int argc, char** argv)
{
    Variant res;

    // Make converter function objects

    Variant milesToKm = makeConverter("km", 1.60936);
    Variant poundsToKg = makeConverter("kg", 0.45460);
    Variant farenheitToCelsius = makeConverter("degrees-c", 0.5556, -32l);

    // Call converter function objects and print results

    res = milesToKm(10);
    printf("milestokm(10) = %s\n", res.toString().c_str());

    res = poundsToKg(2.5);
    printf("poundsToKg(2.5) = %s\n", res.toString().c_str());

    res = farenheitToCelsius(98);
    printf("farenheitToCelsius(98l) = %s\n", res.toString().c_str());

    // Printed:
    // milestokm(10) = 16.09 km
    // poundsToKg(2.5) = 1.14 kg
    // farenheitToCelsius(98l) = 36.67 degrees-c

    Variant printer;
    printer.createFunction(print);

    // Note the curly braces {} around the arguments.
    printer({"test", 2.0, 3, 4, "five", "six"});

    // Printed:
    // test 2.0 3 4 five six
}
<|endoftext|>


<commit_before>#pragma once

#include <set>
#include <vector>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>

#include <stdio.h>

#include "channel9.hpp"
#include "memcheck.h"
#include "bittwiddle.hpp"

namespace Channel9
{
	class GC::Semispace : protected GC
	{
	public:
		struct Data
		{
			uint32_t m_count; //number of bytes of memory in this allocation
			uint16_t m_type;
			uint16_t m_flags;

			enum {
				PINNED = 0x1000,
				FORWARD = 0x2000,
				POOL_MASK = 0x0001,
			};
			uint8_t  m_data[0]; //the actual data, 8 byte aligned

			inline Data *init(uint32_t count, uint16_t type, bool pool, bool pin){
				m_count = count;
				m_type = type;
				m_flags = (uint64_t)pool | ((uint16_t)pin << 12);
				return this;
			}
			bool pool() { return m_flags & POOL_MASK; }
			bool pinned() { return m_flags & PINNED; }
			bool forward() { return m_flags & FORWARD; }
			void set_forward() { m_flags |= FORWARD; }
			void set_pool(bool pool) { m_flags = pool | ((m_flags ^ POOL_MASK) & m_flags); }

			Data *next() const { return (Data*)((uint8_t*)(this + 1) + m_count); }
			static Data *ptr_for(const void *ptr) { return (Data*)ptr - 1; }
		};

	private:

		struct Chunk
		{
			Chunk *  m_next; //linked list of chunks
			uint32_t m_capacity; //in bytes
			uint32_t m_used;     //in bytes
			uint8_t  m_data[0];  //actual memory

			void init(uint32_t capacity)
			{
				m_next = NULL;
				m_capacity = capacity;
				m_used = 0;
				VALGRIND_CREATE_MEMPOOL(m_data, 0, false);
			}

			bool has_space(size_t size)
			{
				return m_used + size <= m_capacity;
			}
			inline Data * alloc(size_t size)
			{
				assert(has_space(size));
				Data * ret = (Data*)(m_data + m_used);
				m_used += size;
				VALGRIND_MEMPOOL_ALLOC(m_data, ret, size);
				return ret;
			}
			Data * begin() const { return (Data *) m_data; }
			Data * end()   const { return (Data *) (m_data + m_used); }
			void deadbeef()
			{
				uint32_t * i = (uint32_t *) m_data,
				         * e = (uint32_t *) (m_data + m_capacity);
				for(; i < e; ++i)
					*i = 0xDEADBEEF;
			}
		};

		static const double   GC_GROWTH_LIMIT = 1.5;
		static const uint64_t CHUNK_SIZE = (2<<20) - sizeof(Chunk) - 8; // 2mb (-8 for the malloc header)

		Chunk * m_pools[2]; //two sets of pools, each garbage collection swaps between them, active is stored in m_cur_pool
		int     m_cur_pool; //which of the two pools are we using now
		Chunk * m_cur_chunk; //which chunk are we allocating from
		bool    m_in_gc;     //are we garbage collecting now?
		uint64_t m_alloced;  //how much memory are in all pools (active or not) combined
		uint64_t m_used;     //how much memory is used by data blocks, not including the header
		uint64_t m_data_blocks; //how many data allocations are in the current pool
		uint64_t m_next_gc;  //garbage collect when m_next_gc < m_used

		std::set<GCRoot*> m_roots;
		std::vector<Data *> m_pinned_objs;

		void collect();

		uint8_t *next_slow(size_t size, size_t alloc_size, uint16_t type);
		inline uint8_t *next(size_t size, uint16_t type)// __attribute__((always_inline))
		{
			if(!m_in_gc)
				TRACE_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "Alloc %u type %x ... \n", (unsigned)size, type);

			size = ceil_power2(size, 3); //8 byte align
			size_t alloc_size = size + sizeof(Data);

			m_used += alloc_size;
			m_data_blocks++;

			if (m_cur_chunk->has_space(alloc_size))
			{
				Data * data = m_cur_chunk->alloc(alloc_size)->init(size, type, m_cur_pool, false);

				if(!m_in_gc)
					TRACE_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "fast alloc return %p\n", data->m_data);

				return data->m_data;
			} else {
				return next_slow(size, alloc_size, type);
			}
		}

		Chunk * new_chunk(size_t alloc_size = 0)
		{
			Chunk *c;
			if(alloc_size < CHUNK_SIZE)
				alloc_size = CHUNK_SIZE;

			// try to steal a chunk from the other list first
			if (!m_in_gc && (c = m_pools[!m_cur_pool]))
			{
				// if the first one is big enough, use it.
				if (c->m_capacity >= alloc_size)
				{
					m_pools[!m_cur_pool] = c->m_next;
					c->m_next = NULL;
					return c;
				} else {
					// otherwise try to find one that is.
					Chunk *prev = c;
					while (prev = c, c = c->m_next)
					{
						if (c->m_capacity >= alloc_size)
						{
							prev->m_next = c->m_next;
							c->m_next = NULL;
							return c;
						}
					}
				}
			}

			c = (Chunk *)malloc(alloc_size + sizeof(Chunk));
			c->init(alloc_size);
			VALGRIND_MAKE_MEM_NOACCESS(c->m_data, alloc_size);
			m_alloced += alloc_size;
			return c;
		}

	public:
		Semispace()
		 : m_cur_pool(0), m_in_gc(false), m_alloced(0), m_used(0), m_data_blocks(0), m_next_gc(1<<20)
		{
			m_pools[0] = new_chunk();
			m_pools[1] = NULL;

			m_cur_chunk = m_pools[m_cur_pool];
		}

		template <typename tObj> tObj *alloc(size_t extra, uint16_t type, bool pinned = false)
		{
			if(pinned)
				return alloc_pinned<tObj>(extra, type);
			else
				return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type));
		}

		template <typename tObj> tObj *alloc_small(size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }
		template <typename tObj> tObj *alloc_med  (size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }
		template <typename tObj> tObj *alloc_big  (size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }

		template <typename tObj> tObj *alloc_pinned(size_t extra, uint16_t type){
			size_t size = sizeof(tObj) + extra;
			size = ceil_power2(size, 3); //8 byte align

			Data * data = (Data*) malloc(size + sizeof(Data));
			data->init(size, type, m_cur_pool, true);
			m_pinned_objs.push_back(data);

			m_used += size;
			m_data_blocks++;

			return reinterpret_cast<tObj*>(data->m_data);
		}

		template <typename tObj>
		bool validate(tObj * from)
		{
			if(m_in_gc)
				return true;
			else
				return (Data::ptr_for(from)->pool() == m_cur_pool);
		}

		template <typename tObj>
		bool mark(tObj **from_ptr)
		{
			tObj *from = *from_ptr;
			Data * old = (Data*)(from) - 1;

			if(old->pool() == m_cur_pool){
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X already moved\n", from, old->m_type);
				return false;
			}

			if(old->pinned()){
				old->set_pool(m_cur_pool);
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X pinned, update pool, recursing\n", from, old->m_type);
				gc_scan(from);
				return false;
			}

			if(old->forward()){
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X => %p\n", from, old->m_type, (*(tObj**)from));
				*from_ptr = *(tObj**)from;
				return true;
			}

			tObj * n = (tObj*)next(old->m_count, old->m_type);
			memcpy(n, from, old->m_count);

			TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X <= %p\n", from, old->m_type, n);

			old->set_forward();
			// put the new location in the old object's space
			*(tObj**)from = n;
			// change the marked pointer
			*from_ptr = n;
			return true;
		}

		// make sure this object is ready to be read from
		template <typename tObj>
		void read_barrier(tObj * obj) { }

		// tell the GC that obj will contain a reference to the object pointed to by ptr
		template <typename tObj, typename tPtr>
		void write_barrier(tObj * obj, tPtr * ptr) { }

		// now is a valid time to stop the world
		void safe_point() {
			if(m_next_gc < m_used)
				collect();
		}

		void register_root(GCRoot *root);
		void unregister_root(GCRoot *root);
	};
}

<commit_msg>Initial memory growth allowance should be higher.<commit_after>#pragma once

#include <set>
#include <vector>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>

#include <stdio.h>

#include "channel9.hpp"
#include "memcheck.h"
#include "bittwiddle.hpp"

namespace Channel9
{
	class GC::Semispace : protected GC
	{
	public:
		struct Data
		{
			uint32_t m_count; //number of bytes of memory in this allocation
			uint16_t m_type;
			uint16_t m_flags;

			enum {
				PINNED = 0x1000,
				FORWARD = 0x2000,
				POOL_MASK = 0x0001,
			};
			uint8_t  m_data[0]; //the actual data, 8 byte aligned

			inline Data *init(uint32_t count, uint16_t type, bool pool, bool pin){
				m_count = count;
				m_type = type;
				m_flags = (uint64_t)pool | ((uint16_t)pin << 12);
				return this;
			}
			bool pool() { return m_flags & POOL_MASK; }
			bool pinned() { return m_flags & PINNED; }
			bool forward() { return m_flags & FORWARD; }
			void set_forward() { m_flags |= FORWARD; }
			void set_pool(bool pool) { m_flags = pool | ((m_flags ^ POOL_MASK) & m_flags); }

			Data *next() const { return (Data*)((uint8_t*)(this + 1) + m_count); }
			static Data *ptr_for(const void *ptr) { return (Data*)ptr - 1; }
		};

	private:

		struct Chunk
		{
			Chunk *  m_next; //linked list of chunks
			uint32_t m_capacity; //in bytes
			uint32_t m_used;     //in bytes
			uint8_t  m_data[0];  //actual memory

			void init(uint32_t capacity)
			{
				m_next = NULL;
				m_capacity = capacity;
				m_used = 0;
				VALGRIND_CREATE_MEMPOOL(m_data, 0, false);
			}

			bool has_space(size_t size)
			{
				return m_used + size <= m_capacity;
			}
			inline Data * alloc(size_t size)
			{
				assert(has_space(size));
				Data * ret = (Data*)(m_data + m_used);
				m_used += size;
				VALGRIND_MEMPOOL_ALLOC(m_data, ret, size);
				return ret;
			}
			Data * begin() const { return (Data *) m_data; }
			Data * end()   const { return (Data *) (m_data + m_used); }
			void deadbeef()
			{
				uint32_t * i = (uint32_t *) m_data,
				         * e = (uint32_t *) (m_data + m_capacity);
				for(; i < e; ++i)
					*i = 0xDEADBEEF;
			}
		};

		static const double   GC_GROWTH_LIMIT = 1.5;
		static const uint64_t CHUNK_SIZE = (2<<20) - sizeof(Chunk) - 8; // 2mb (-8 for the malloc header)

		Chunk * m_pools[2]; //two sets of pools, each garbage collection swaps between them, active is stored in m_cur_pool
		int     m_cur_pool; //which of the two pools are we using now
		Chunk * m_cur_chunk; //which chunk are we allocating from
		bool    m_in_gc;     //are we garbage collecting now?
		uint64_t m_alloced;  //how much memory are in all pools (active or not) combined
		uint64_t m_used;     //how much memory is used by data blocks, not including the header
		uint64_t m_data_blocks; //how many data allocations are in the current pool
		uint64_t m_next_gc;  //garbage collect when m_next_gc < m_used

		std::set<GCRoot*> m_roots;
		std::vector<Data *> m_pinned_objs;

		void collect();

		uint8_t *next_slow(size_t size, size_t alloc_size, uint16_t type);
		inline uint8_t *next(size_t size, uint16_t type)// __attribute__((always_inline))
		{
			if(!m_in_gc)
				TRACE_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "Alloc %u type %x ... \n", (unsigned)size, type);

			size = ceil_power2(size, 3); //8 byte align
			size_t alloc_size = size + sizeof(Data);

			m_used += alloc_size;
			m_data_blocks++;

			if (m_cur_chunk->has_space(alloc_size))
			{
				Data * data = m_cur_chunk->alloc(alloc_size)->init(size, type, m_cur_pool, false);

				if(!m_in_gc)
					TRACE_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "fast alloc return %p\n", data->m_data);

				return data->m_data;
			} else {
				return next_slow(size, alloc_size, type);
			}
		}

		Chunk * new_chunk(size_t alloc_size = 0)
		{
			Chunk *c;
			if(alloc_size < CHUNK_SIZE)
				alloc_size = CHUNK_SIZE;

			// try to steal a chunk from the other list first
			if (!m_in_gc && (c = m_pools[!m_cur_pool]))
			{
				// if the first one is big enough, use it.
				if (c->m_capacity >= alloc_size)
				{
					m_pools[!m_cur_pool] = c->m_next;
					c->m_next = NULL;
					return c;
				} else {
					// otherwise try to find one that is.
					Chunk *prev = c;
					while (prev = c, c = c->m_next)
					{
						if (c->m_capacity >= alloc_size)
						{
							prev->m_next = c->m_next;
							c->m_next = NULL;
							return c;
						}
					}
				}
			}

			c = (Chunk *)malloc(alloc_size + sizeof(Chunk));
			c->init(alloc_size);
#if !defined(NVALGRIND) // this shouldn't be necessary, but it causes a warning otherwise.
			VALGRIND_MAKE_MEM_NOACCESS(c->m_data, alloc_size);
#endif
			m_alloced += alloc_size;
			return c;
		}

	public:
		Semispace()
		 : m_cur_pool(0), m_in_gc(false), m_alloced(0), m_used(0), m_data_blocks(0), m_next_gc(1<<23)
		{
			m_pools[0] = new_chunk();
			m_pools[1] = NULL;

			m_cur_chunk = m_pools[m_cur_pool];
		}

		template <typename tObj> tObj *alloc(size_t extra, uint16_t type, bool pinned = false)
		{
			if(pinned)
				return alloc_pinned<tObj>(extra, type);
			else
				return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type));
		}

		template <typename tObj> tObj *alloc_small(size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }
		template <typename tObj> tObj *alloc_med  (size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }
		template <typename tObj> tObj *alloc_big  (size_t extra, uint16_t type){ return reinterpret_cast<tObj*>(next(sizeof(tObj) + extra, type)); }

		template <typename tObj> tObj *alloc_pinned(size_t extra, uint16_t type){
			size_t size = sizeof(tObj) + extra;
			size = ceil_power2(size, 3); //8 byte align

			Data * data = (Data*) malloc(size + sizeof(Data));
			data->init(size, type, m_cur_pool, true);
			m_pinned_objs.push_back(data);

			m_used += size;
			m_data_blocks++;

			return reinterpret_cast<tObj*>(data->m_data);
		}

		template <typename tObj>
		bool validate(tObj * from)
		{
			if(m_in_gc)
				return true;
			else
				return (Data::ptr_for(from)->pool() == m_cur_pool);
		}

		template <typename tObj>
		bool mark(tObj **from_ptr)
		{
			tObj *from = *from_ptr;
			Data * old = (Data*)(from) - 1;

			if(old->pool() == m_cur_pool){
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X already moved\n", from, old->m_type);
				return false;
			}

			if(old->pinned()){
				old->set_pool(m_cur_pool);
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X pinned, update pool, recursing\n", from, old->m_type);
				gc_scan(from);
				return false;
			}

			if(old->forward()){
				TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X => %p\n", from, old->m_type, (*(tObj**)from));
				*from_ptr = *(tObj**)from;
				return true;
			}

			tObj * n = (tObj*)next(old->m_count, old->m_type);
			memcpy(n, from, old->m_count);

			TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Move %p, type %X <= %p\n", from, old->m_type, n);

			old->set_forward();
			// put the new location in the old object's space
			*(tObj**)from = n;
			// change the marked pointer
			*from_ptr = n;
			return true;
		}

		// make sure this object is ready to be read from
		template <typename tObj>
		void read_barrier(tObj * obj) { }

		// tell the GC that obj will contain a reference to the object pointed to by ptr
		template <typename tObj, typename tPtr>
		void write_barrier(tObj * obj, tPtr * ptr) { }

		// now is a valid time to stop the world
		void safe_point() {
			if(m_next_gc < m_used)
				collect();
		}

		void register_root(GCRoot *root);
		void unregister_root(GCRoot *root);
	};
}

<|endoftext|>


<commit_before>// Copyright 2015-2017 Kuzzle
//
// 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.

#include "kuzzle.hpp"
#include "index.hpp"
#include <string>

namespace kuzzleio {

    Index::Index(Kuzzle* kuzzle) {
        _index = new kuzzle_index();
        kuzzle_new_index(_index, kuzzle->_kuzzle);
    }

    Index::Index(Kuzzle* kuzzle, kuzzle_index *index) {
      _index = index;
      kuzzle_new_index(_index, kuzzle->_kuzzle);
    }

    Index::~Index() {
        unregisterIndex(_index);
        delete(_index);
    }

    void Index::create(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_create(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::delete_(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_delete(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    std::vector<std::string> Index::mDelete(const std::vector<std::string>& indexes, query_options *options) Kuz_Throw_KuzzleException {
        char **indexesArray = new char *[indexes.size()];
        int i = 0;
        for (std::string index : indexes) {
          indexesArray[i] = const_cast<char*>(index.c_str());
          i++;
        }
        string_array_result *r = kuzzle_index_mdelete(_index, indexesArray, indexes.size(), options);

        delete[] indexesArray;
        if (r->error != NULL)
          throwExceptionFromStatus(r);

        std::vector<std::string> v;
        for (int i = 0; i < r->result_length; i++)
          v.push_back(r->result[i]);

        kuzzle_free_string_array_result(r);
        return v;
    }

    bool Index::exists(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        bool_result *r = kuzzle_index_exists(_index, const_cast<char*>(index.c_str()), options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);
        bool ret = r->result;
        kuzzle_free_bool_result(r);
        return ret;
    }

    void Index::refresh(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_refresh(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::refreshInternal(query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_refresh_internal(_index, options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::setAutoRefresh(const std::string& index, bool autoRefresh, query_options *options) Kuz_Throw_KuzzleException {
      error_result *r = kuzzle_index_set_auto_refresh(_index, const_cast<char*>(index.c_str()), autoRefresh, options);
      if (r != NULL)
          throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    bool Index::getAutoRefresh(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        bool_result *r = kuzzle_index_get_auto_refresh(_index, const_cast<char*>(index.c_str()), options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);
        bool ret = r->result;
        kuzzle_free_bool_result(r);
        return ret;
    }

    std::vector<std::string> Index::list(query_options *options) Kuz_Throw_KuzzleException {
        string_array_result *r = kuzzle_index_list(_index, options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);

        std::vector<std::string> v;
        for (int i = 0; i < r->result_length; i++)
          v.push_back(r->result[i]);

        kuzzle_free_string_array_result(r);
        return v;
    }
}
<commit_msg>remove auto<commit_after>// Copyright 2015-2017 Kuzzle
//
// 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.

#include "kuzzle.hpp"
#include "index.hpp"
#include <string>

namespace kuzzleio {

    Index::Index(Kuzzle* kuzzle) {
        _index = new kuzzle_index();
        kuzzle_new_index(_index, kuzzle->_kuzzle);
    }

    Index::Index(Kuzzle* kuzzle, kuzzle_index *index) {
      _index = index;
      kuzzle_new_index(_index, kuzzle->_kuzzle);
    }

    Index::~Index() {
        unregisterIndex(_index);
        delete(_index);
    }

    void Index::create(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_create(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::delete_(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_delete(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    std::vector<std::string> Index::mDelete(const std::vector<std::string>& indexes, query_options *options) Kuz_Throw_KuzzleException {
        char **indexesArray = new char *[indexes.size()];
        for (int i = 0; i < indexes.size(); i++) {
          indexesArray[i] = const_cast<char*>(indexes[i].c_str());
        }
        string_array_result *r = kuzzle_index_mdelete(_index, indexesArray, indexes.size(), options);

        delete[] indexesArray;
        if (r->error != NULL)
          throwExceptionFromStatus(r);

        std::vector<std::string> v;
        for (int i = 0; i < r->result_length; i++)
          v.push_back(r->result[i]);

        kuzzle_free_string_array_result(r);
        return v;
    }

    bool Index::exists(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        bool_result *r = kuzzle_index_exists(_index, const_cast<char*>(index.c_str()), options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);
        bool ret = r->result;
        kuzzle_free_bool_result(r);
        return ret;
    }

    void Index::refresh(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_refresh(_index, const_cast<char*>(index.c_str()), options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::refreshInternal(query_options *options) Kuz_Throw_KuzzleException {
        error_result *r = kuzzle_index_refresh_internal(_index, options);
        if (r != NULL)
            throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    void Index::setAutoRefresh(const std::string& index, bool autoRefresh, query_options *options) Kuz_Throw_KuzzleException {
      error_result *r = kuzzle_index_set_auto_refresh(_index, const_cast<char*>(index.c_str()), autoRefresh, options);
      if (r != NULL)
          throwExceptionFromStatus(r);
        kuzzle_free_error_result(r);
    }

    bool Index::getAutoRefresh(const std::string& index, query_options *options) Kuz_Throw_KuzzleException {
        bool_result *r = kuzzle_index_get_auto_refresh(_index, const_cast<char*>(index.c_str()), options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);
        bool ret = r->result;
        kuzzle_free_bool_result(r);
        return ret;
    }

    std::vector<std::string> Index::list(query_options *options) Kuz_Throw_KuzzleException {
        string_array_result *r = kuzzle_index_list(_index, options);
        if (r->error != NULL)
            throwExceptionFromStatus(r);

        std::vector<std::string> v;
        for (int i = 0; i < r->result_length; i++)
          v.push_back(r->result[i]);

        kuzzle_free_string_array_result(r);
        return v;
    }
}
<|endoftext|>


<commit_before>#include<iostream>
#include<math.h>
#include<stdlib.h>

using namespace std;

#define SIZE 100000
bool primeBool[SIZE];

void generatePrimeBetween(const int num1, const int num2){
	int num1new = 2;
	if ( num1 > 2)
	    num1new  = (num1/2)*2;
        int num2Range  = static_cast<int>(sqrt((double)num2));
	for(int i=num1;i<=num2;++i)
    		primeBool[i] = true;
 	for(int i=num1new;i<=num2Range;++i)
        	if(primeBool[i]==true)
                	for(int j=i*i;j<=num2;j=j+i)
                    		primeBool[j]=false;
 	for(int i=num1;i<=num2;++i)
    		if(primeBool[i] == true) cout << i << endl;
}
int main() {
	// your code goes here
	int noOfTestCases;
	scanf("%d", &noOfTestCases);
	int num1; //smaller number
	int num2; // larger number
	while (noOfTestCases--) {
		scanf("%d %d",&num1,&num2);
		generatePrimeBetween(num1, num2);
		cout << endl;
	}
	return 0;
}
<commit_msg>Update main-TLE.cpp<commit_after>#include<iostream>
#include<math.h>
#include<stdlib.h>

using namespace std;

#define SIZE 100000
bool primeBool[SIZE];

void generatePrimeBetween(const int num1, const int num2){
	int num1new = 2;
	if ( num1 > 2)
	    num1new  = (num1/2)*2;
        int num2Range  = static_cast<int>(sqrt((double)num2));
	for(int i=num1new;i<=num2;++i)
    		primeBool[i] = true;
 	for(int i=num1new;i<=num2Range;++i)
        	if(primeBool[i]==true)
                	for(int j=i*i;j<=num2;j=j+i)
                    		primeBool[j]=false;
 	for(int i=num1new;i<=num2;++i)
    		if(primeBool[i] == true) cout << i << endl;
}
int main() {
	// your code goes here
	int noOfTestCases;
	scanf("%d", &noOfTestCases);
	int num1; //smaller number
	int num2; // larger number
	while (noOfTestCases--) {
		scanf("%d %d",&num1,&num2);
		generatePrimeBetween(num1, num2);
		cout << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkOptMattesMutualInformationImageToImageMetricThreadsTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTranslationTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkMattesMutualInformationImageToImageMetric.h"

int itkOptMattesMutualInformationImageToImageMetricThreadsTest1( int argc, char* argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Missing arguments" << std::endl;
    std::cerr << "Usage " << std::endl;
    std::cerr << argv[0] << " fixedImage movingImage [verbose(1/0)]" << std::endl;
    return EXIT_FAILURE;
    }

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  const unsigned int maximumNumberOfThreads = itk::MultiThreader::GetGlobalMaximumNumberOfThreads();
  const unsigned int defaultNumberOfThreads = itk::MultiThreader::GetGlobalDefaultNumberOfThreads();

  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << " Global Maximum Number of Threads " << maximumNumberOfThreads << std::endl;
  std::cout << " Global Default Number of Threads " << defaultNumberOfThreads << std::endl;
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << std::endl;

  typedef unsigned char  PixelType;
  const unsigned int     Dimension = 2;

  typedef itk::Image< PixelType > ImageType;

  typedef itk::ImageFileReader< ImageType  > ImageReaderType;

  ImageReaderType::Pointer fixedImageReader  = ImageReaderType::New();
  ImageReaderType::Pointer movingImageReader = ImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  bool verbose = false;

  if( argc > 3 )
    {
    verbose = atoi( argv[3] );
    }

  try
    {
    fixedImageReader->Update();
    movingImageReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::NearestNeighborInterpolateImageFunction< ImageType > InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  typedef itk::MattesMutualInformationImageToImageMetric< ImageType, ImageType > MetricType;
  MetricType::Pointer metric = MetricType::New();

  typedef itk::TranslationTransform< double, Dimension >  TranformType;
  TranformType::Pointer transform = TranformType::New();

  metric->SetTransform( transform );
  metric->SetInterpolator( interpolator );
  metric->SetFixedImage( fixedImageReader->GetOutput() );
  metric->SetMovingImage( movingImageReader->GetOutput() );
  metric->SetFixedImageRegion(  fixedImageReader->GetOutput()->GetBufferedRegion()  );

  try
    {
    metric->Initialize();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
    }

  MetricType::TransformParametersType displacement( Dimension );

  displacement[0] = 17;
  displacement[1] = 19;

  std::vector< double > results;

  for( unsigned int numberOfThreads = 1; numberOfThreads < maximumNumberOfThreads; numberOfThreads++ )
    {
    metric->SetNumberOfThreads( numberOfThreads );
    metric->Initialize();
    metric->ReinitializeSeed( 76926294 );
    const double value = metric->GetValue( displacement );
    results.push_back( value );
    if( verbose )
      {
      std::cout << numberOfThreads << " : " << value << std::endl;
      }
    }

  bool testFailed = false;

  const double tolerance = 1e-7;

  for( unsigned int i = 0; i < results.size(); i++ )
    {
    for( unsigned int j = 0; j < results.size(); j++ )
      {
      const double difference = results[i] - results[j];

      if( vnl_math_abs( difference ) > tolerance )
        {
        if( verbose )
          {
          std::cerr << i << " : " << j;
          std::cerr << " Differ by " << difference;
          std::cerr << " from " << results[i];
          std::cerr << " to " << results[j];
          std::cerr << std::endl;
          }
        testFailed = true;
        }
      }
    }

  if( testFailed )
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>ENH: Comparisons are only needed with larger number of threads.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkOptMattesMutualInformationImageToImageMetricThreadsTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTranslationTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkMattesMutualInformationImageToImageMetric.h"

int itkOptMattesMutualInformationImageToImageMetricThreadsTest1( int argc, char* argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Missing arguments" << std::endl;
    std::cerr << "Usage " << std::endl;
    std::cerr << argv[0] << " fixedImage movingImage [verbose(1/0)]" << std::endl;
    return EXIT_FAILURE;
    }

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  const unsigned int maximumNumberOfThreads = itk::MultiThreader::GetGlobalMaximumNumberOfThreads();
  const unsigned int defaultNumberOfThreads = itk::MultiThreader::GetGlobalDefaultNumberOfThreads();

  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << " Global Maximum Number of Threads " << maximumNumberOfThreads << std::endl;
  std::cout << " Global Default Number of Threads " << defaultNumberOfThreads << std::endl;
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << std::endl;

  typedef unsigned char  PixelType;
  const unsigned int     Dimension = 2;

  typedef itk::Image< PixelType > ImageType;

  typedef itk::ImageFileReader< ImageType  > ImageReaderType;

  ImageReaderType::Pointer fixedImageReader  = ImageReaderType::New();
  ImageReaderType::Pointer movingImageReader = ImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  bool verbose = false;

  if( argc > 3 )
    {
    verbose = atoi( argv[3] );
    }

  try
    {
    fixedImageReader->Update();
    movingImageReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::NearestNeighborInterpolateImageFunction< ImageType > InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  typedef itk::MattesMutualInformationImageToImageMetric< ImageType, ImageType > MetricType;
  MetricType::Pointer metric = MetricType::New();

  typedef itk::TranslationTransform< double, Dimension >  TranformType;
  TranformType::Pointer transform = TranformType::New();

  metric->SetTransform( transform );
  metric->SetInterpolator( interpolator );
  metric->SetFixedImage( fixedImageReader->GetOutput() );
  metric->SetMovingImage( movingImageReader->GetOutput() );
  metric->SetFixedImageRegion(  fixedImageReader->GetOutput()->GetBufferedRegion()  );

  try
    {
    metric->Initialize();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
    }

  MetricType::TransformParametersType displacement( Dimension );

  displacement[0] = 17;
  displacement[1] = 19;

  std::vector< double > results;

  for( unsigned int numberOfThreads = 1; numberOfThreads < maximumNumberOfThreads; numberOfThreads++ )
    {
    metric->SetNumberOfThreads( numberOfThreads );
    metric->Initialize();
    metric->ReinitializeSeed( 76926294 );
    const double value = metric->GetValue( displacement );
    results.push_back( value );
    if( verbose )
      {
      std::cout << numberOfThreads << " : " << value << std::endl;
      }
    }

  bool testFailed = false;

  const double tolerance = 1e-7;

  for( unsigned int i = 0; i < results.size(); i++ )
    {
    for( unsigned int j = i; j < results.size(); j++ )
      {
      const double difference = results[i] - results[j];

      if( vnl_math_abs( difference ) > tolerance )
        {
        if( verbose )
          {
          std::cerr << i << " : " << j;
          std::cerr << " Differ by " << difference;
          std::cerr << " from " << results[i];
          std::cerr << " to " << results[j];
          std::cerr << std::endl;
          }
        testFailed = true;
        }
      }
    }

  if( testFailed )
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>test with and without "Empty string as zero" option<commit_after><|endoftext|>