<commit_before>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    bool isRectangleCover(vector<vector<int>>& rectangles) {
        enum DIR {L = 0, B = 1, R = 2, T = 3};
        int left = numeric_limits<int>::max(), bottom = numeric_limits<int>::max(),
            right = numeric_limits<int>::min(), top = numeric_limits<int>::min();
        for (const auto& rect : rectangles) {
            left = min(left, rect[L]);
            bottom = min(bottom, rect[B]);
            right = max(right, rect[R]);
            top = max(top, rect[T]);
        }

        using P = pair<pair<int, int>, int>;
        enum CORNER {LB = 1, RB = 2, LT = 4, RT = 8};
        unordered_map<int, unordered_map<int, int>> corner_count;
        vector<P> corners{{{L, B}, LB}, {{R, B}, RB}, {{L, T}, LT}, {{R, T}, RT}};
        for (const auto& rect : rectangles) {
            for (const auto& corner : corners) {
                const auto x = rect[corner.first.first];
                const auto y = rect[corner.first.second];
                if (corner_count[x][y] & corner.second) {
                    return false;
                }
                corner_count[x][y] |= corner.second;
            }
        }

        bool is_valid[16] = {false};
        is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true;
        for (auto itx = corner_count.cbegin(); itx != corner_count.cend(); ++itx) {
            const auto x = itx->first;
            for (auto ity = itx->second.cbegin(); ity != itx->second.cend(); ++ity) {
                const auto y = ity->first;
                const auto mask = ity->second;
                if ((left < x && x < right) || (bottom < y && y < top)) {
                    if (!is_valid[mask]) {
                        return false;
                    }
                }
            }
        }

        return true;
    }
};
<commit_msg>Update perfect-rectangle.cpp<commit_after>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    bool isRectangleCover(vector<vector<int>>& rectangles) {
        enum Location {L = 0, B = 1, R = 2, T = 3};
        int left = numeric_limits<int>::max(), bottom = numeric_limits<int>::max(),
            right = numeric_limits<int>::min(), top = numeric_limits<int>::min();
        for (const auto& rect : rectangles) {
            left = min(left, rect[L]);
            bottom = min(bottom, rect[B]);
            right = max(right, rect[R]);
            top = max(top, rect[T]);
        }

        using P = pair<pair<int, int>, int>;
        enum Corner {LB = 1, RB = 2, LT = 4, RT = 8};
        unordered_map<int, unordered_map<int, int>> corner_count;
        vector<P> corners{{{L, B}, LB}, {{R, B}, RB}, {{L, T}, LT}, {{R, T}, RT}};
        for (const auto& rect : rectangles) {
            for (const auto& corner : corners) {
                const auto x = rect[corner.first.first];
                const auto y = rect[corner.first.second];
                if (corner_count[x][y] & corner.second) {
                    return false;
                }
                corner_count[x][y] |= corner.second;
            }
        }

        bool is_valid[16] = {false};
        is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true;
        for (auto itx = corner_count.cbegin(); itx != corner_count.cend(); ++itx) {
            const auto x = itx->first;
            for (auto ity = itx->second.cbegin(); ity != itx->second.cend(); ++ity) {
                const auto y = ity->first;
                const auto mask = ity->second;
                if ((left < x && x < right) || (bottom < y && y < top)) {
                    if (!is_valid[mask]) {
                        return false;
                    }
                }
            }
        }

        return true;
    }
};
<|endoftext|>


<commit_before>/***************************************************************************
 *  io/fileperblock_file.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2008 Johannes Singler <singler@ira.uka.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <sstream>
#include <iomanip>
#include <stxxl/bits/io/fileperblock_file.h>
#include <stxxl/bits/io/syscall_file.h>
#include <stxxl/bits/io/mmap_file.h>

__STXXL_BEGIN_NAMESPACE

template<class base_file_type>
fileperblock_file<base_file_type>::fileperblock_file(
    const std::string & filename_prefix,
    int mode,
    int disk)
        : file(disk), filename_prefix(filename_prefix), mode(mode), disk(disk)
{
}

template<class base_file_type>
std::string fileperblock_file<base_file_type>::filename_for_block(unsigned_type offset)
{
    std::ostringstream name;
    //enough for 1 billion blocks
    name << filename_prefix << "_fpb_" << std::setw(20) << std::setfill('0') << offset;
    return name.str();
}

template<class base_file_type>
request_ptr fileperblock_file<base_file_type>::aread(
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    completion_handler on_completion)
{
    request_ptr req = new fileperblock_request<base_file_type>(this,
                                          buffer, offset, length,
                                          request::READ, on_completion);
    return req;
}

template<class base_file_type>
request_ptr fileperblock_file<base_file_type>::awrite(
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    completion_handler on_completion)
{
    request_ptr req = new fileperblock_request<base_file_type>(this,
                                          buffer, offset, length,
                                          request::WRITE, on_completion);
    return req;
}

template<class base_file_type>
void fileperblock_file<base_file_type>::delete_region(int64 offset, unsigned_type length)
{
    ::remove(filename_for_block(offset).c_str());
    STXXL_VERBOSE0("delete_region " << offset << " + " << length)
}

template<class base_file_type>
void fileperblock_file<base_file_type>::lock()
{
    // not yet implemented, maybe not needed
}

template<class base_file_type>
void fileperblock_file<base_file_type>::export_files(int64 offset, int64 length, std::string filename)
{
    std::string original(filename_for_block(offset));
    filename.insert(0, original.substr(0, original.find_last_of("/") + 1));
    ::remove(filename.c_str());
    ::rename(original.c_str(), filename.c_str());
    ::truncate(filename.c_str(), length);
}

////////////////////////////////////////////////////////////////////////////

template<class base_file_type>
fileperblock_request<base_file_type>::fileperblock_request(
    fileperblock_file<base_file_type>* f,
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    typename base_file_type::request::request_type read_or_write,
    completion_handler on_completion)
   :
    request(on_completion, f, buffer, offset, length, read_or_write),
    base_file (new base_file_type(f->filename_for_block(offset), f->mode, f->disk))
{
    base_file->set_size(length);
    base_request = new request_ptr
       (read_or_write == request::READ ?
        base_file->aread(buffer, 0, length, on_completion) :
        base_file->awrite(buffer, 0, length, on_completion));
}

template<class base_file_type>
fileperblock_request<base_file_type>::~fileperblock_request()
{
    delete base_request;
    delete base_file;
}

template<class base_file_type>
void fileperblock_request<base_file_type>::serve()
{
    (*base_request)->serve();
}

template<class base_file_type>
const char * fileperblock_request<base_file_type>::io_type()
{
    return "fileperblock";
}

template<class base_file_type>
bool fileperblock_request<base_file_type>::add_waiter(onoff_switch * sw)
{
    return (*base_request)->add_waiter(sw);
}

template<class base_file_type>
void fileperblock_request<base_file_type>::delete_waiter(onoff_switch * sw)
{
    (*base_request)->delete_waiter(sw);
}

template<class base_file_type>
void fileperblock_request<base_file_type>::wait()
{
    (*base_request)->wait();
    delete base_file;
    base_file = NULL;
}

template<class base_file_type>
bool fileperblock_request<base_file_type>::poll()
{
    bool finished = (*base_request)->poll();
    if(finished) {
        delete base_file;
        base_file = NULL;
    }
    return finished;
}

////////////////////////////////////////////////////////////////////////////

template class fileperblock_file<syscall_file>;
template class fileperblock_request<syscall_file>;

template class fileperblock_file<mmap_file>;
template class fileperblock_request<mmap_file>;

__STXXL_END_NAMESPACE
<commit_msg>Avoid unused variable warning.<commit_after>/***************************************************************************
 *  io/fileperblock_file.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2008 Johannes Singler <singler@ira.uka.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <sstream>
#include <iomanip>
#include <stxxl/bits/io/fileperblock_file.h>
#include <stxxl/bits/io/syscall_file.h>
#include <stxxl/bits/io/mmap_file.h>

__STXXL_BEGIN_NAMESPACE

template<class base_file_type>
fileperblock_file<base_file_type>::fileperblock_file(
    const std::string & filename_prefix,
    int mode,
    int disk)
        : file(disk), filename_prefix(filename_prefix), mode(mode), disk(disk)
{
}

template<class base_file_type>
std::string fileperblock_file<base_file_type>::filename_for_block(unsigned_type offset)
{
    std::ostringstream name;
    //enough for 1 billion blocks
    name << filename_prefix << "_fpb_" << std::setw(20) << std::setfill('0') << offset;
    return name.str();
}

template<class base_file_type>
request_ptr fileperblock_file<base_file_type>::aread(
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    completion_handler on_completion)
{
    request_ptr req = new fileperblock_request<base_file_type>(this,
                                          buffer, offset, length,
                                          request::READ, on_completion);
    return req;
}

template<class base_file_type>
request_ptr fileperblock_file<base_file_type>::awrite(
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    completion_handler on_completion)
{
    request_ptr req = new fileperblock_request<base_file_type>(this,
                                          buffer, offset, length,
                                          request::WRITE, on_completion);
    return req;
}

template<class base_file_type>
void fileperblock_file<base_file_type>::delete_region(int64 offset, unsigned_type length)
{
    UNUSED(length);
    ::remove(filename_for_block(offset).c_str());
    STXXL_VERBOSE0("delete_region " << offset << " + " << length)
}

template<class base_file_type>
void fileperblock_file<base_file_type>::lock()
{
    // not yet implemented, maybe not needed
}

template<class base_file_type>
void fileperblock_file<base_file_type>::export_files(int64 offset, int64 length, std::string filename)
{
    std::string original(filename_for_block(offset));
    filename.insert(0, original.substr(0, original.find_last_of("/") + 1));
    ::remove(filename.c_str());
    ::rename(original.c_str(), filename.c_str());
    ::truncate(filename.c_str(), length);
}

////////////////////////////////////////////////////////////////////////////

template<class base_file_type>
fileperblock_request<base_file_type>::fileperblock_request(
    fileperblock_file<base_file_type>* f,
    void * buffer,
    stxxl::int64 offset,
    size_t length,
    typename base_file_type::request::request_type read_or_write,
    completion_handler on_completion)
   :
    request(on_completion, f, buffer, offset, length, read_or_write),
    base_file (new base_file_type(f->filename_for_block(offset), f->mode, f->disk))
{
    base_file->set_size(length);
    base_request = new request_ptr
       (read_or_write == request::READ ?
        base_file->aread(buffer, 0, length, on_completion) :
        base_file->awrite(buffer, 0, length, on_completion));
}

template<class base_file_type>
fileperblock_request<base_file_type>::~fileperblock_request()
{
    delete base_request;
    delete base_file;
}

template<class base_file_type>
void fileperblock_request<base_file_type>::serve()
{
    (*base_request)->serve();
}

template<class base_file_type>
const char * fileperblock_request<base_file_type>::io_type()
{
    return "fileperblock";
}

template<class base_file_type>
bool fileperblock_request<base_file_type>::add_waiter(onoff_switch * sw)
{
    return (*base_request)->add_waiter(sw);
}

template<class base_file_type>
void fileperblock_request<base_file_type>::delete_waiter(onoff_switch * sw)
{
    (*base_request)->delete_waiter(sw);
}

template<class base_file_type>
void fileperblock_request<base_file_type>::wait()
{
    (*base_request)->wait();
    delete base_file;
    base_file = NULL;
}

template<class base_file_type>
bool fileperblock_request<base_file_type>::poll()
{
    bool finished = (*base_request)->poll();
    if(finished) {
        delete base_file;
        base_file = NULL;
    }
    return finished;
}

////////////////////////////////////////////////////////////////////////////

template class fileperblock_file<syscall_file>;
template class fileperblock_request<syscall_file>;

template class fileperblock_file<mmap_file>;
template class fileperblock_request<mmap_file>;

__STXXL_END_NAMESPACE
<|endoftext|>


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

#include <string>
#include <iostream>
#include <fmicpp/tools/os_util.hpp>
#include <fmicpp/fmi2/fmicpp.hpp>

using namespace std;
using namespace fmicpp::fmi2;

int main() {

    const string fmuPath = string(getenv("TEST_FMUs"))
                            + "/FMI_2.0/CoSimulation/" + getOs() +
                            "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

    import::Fmu fmu(fmuPath);

    auto md = fmu.getModelDescription().asCoSimulationFmu();
    cout << "modelIdentifier=" << md->modelIdentifier << endl;

    auto slave = fmu.asCoSimulationFmu().newInstance();
    slave->init();

    xml::ScalarVariable& var = md->getVariableByValueReference(47);

    double t = 0;
    double stop = 1.0;
    double stepSize = 1E-3;

    fmi2Real v;
    fmi2Status status;
    while ((t = slave->getSimulationTime()) <= stop) {
        status = slave->doStep(stepSize);
        if (!status == fmi2OK) {
            break;
        }
        status = slave->readReal(var.valueReference, v);
        if (status != fmi2OK) {
            break;
        }
        cout << "t=" << t << ", " << var.name << "=" << v << endl;
    }

    status = slave->terminate();
    cout << "FMU '" << fmu.getModelName() <<  "' terminated with status: " << statusToString(status) << endl;

    return 0;

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

#include <string>
#include <iostream>
#include <fmicpp/tools/os_util.hpp>
#include <fmicpp/fmi2/fmicpp.hpp>

using namespace std;
using namespace fmicpp::fmi2;

int main() {

    const string fmuPath = string(getenv("TEST_FMUs"))
                            + "/FMI_2.0/CoSimulation/" + getOs() +
                            "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

    import::Fmu fmu(fmuPath);

    auto md = fmu.getModelDescription().asCoSimulationFmu();
    cout << "modelIdentifier=" << md->modelIdentifier << endl;

    auto slave = fmu.asCoSimulationFmu().newInstance();
    slave->init();

    xml::ScalarVariable& var = md->getVariableByValueReference(47);
    cout << "Causality=" << to_string(var.causality) << ", variability=" << to_string(var.variability) << endl;

    double t = 0;
    double stop = 1.0;
    double stepSize = 1E-3;

    fmi2Real v;
    fmi2Status status;
    while ((t = slave->getSimulationTime()) <= stop) {
        status = slave->doStep(stepSize);
        if (!status == fmi2OK) {
            break;
        }
        status = slave->readReal(var.valueReference, v);
        if (status != fmi2OK) {
            break;
        }
        cout << "t=" << t << ", " << var.name << "=" << v << endl;
    }

    status = slave->terminate();
    cout << "FMU '" << fmu.getModelName() <<  "' terminated with status: " << to_string(status) << endl;

    return 0;

}<|endoftext|>


<commit_before>// bslma_usesbslmaallocator.t.cpp                                     -*-C++-*-

#include <bslma_usesbslmaallocator.h>

#include <bslma_allocator.h>
#include <bslmf_assert.h>
#include <bslmf_nestedtraitdeclaration.h>
#include <bsls_bsltestutil.h>

#include <cstdio>
#include <cstdlib>

using namespace BloombergLP;
using namespace std;
using namespace bsl;

//=============================================================================
//                             TEST PLAN
//-----------------------------------------------------------------------------
//                             Overview
//                             --------
// The component provides a meta-function for associating a trait with a type
// and detecting whether a trait is associated with a type.
// ----------------------------------------------------------------------------
//
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 2] USAGE EXAMPLE
//-----------------------------------------------------------------------------

#pragma bde_verify -TP19

//=============================================================================
//                  STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
static int testStatus = 0;

static void aSsErT(bool b, const char *s, int i) {
    if (b) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", i, s);
        if (testStatus >= 0 && testStatus <= 100) ++testStatus;
    }
}

//=============================================================================
//                       STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------

#define ASSERT       BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV

#define Q   BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P   BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_  BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLS_BSLTESTUTIL_L_  // current Line number

// ============================================================================
//                  NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT_FAIL(expr)      BSLS_ASSERTTEST_ASSERT_FAIL(expr)
#define ASSERT_PASS(expr)      BSLS_ASSERTTEST_ASSERT_PASS(expr)
#define ASSERT_SAFE_FAIL(expr) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(expr)
#define ASSERT_SAFE_PASS(expr) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(expr)

// ============================================================================
//                     GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------

//=============================================================================
//                              USAGE EXAMPLE
//-----------------------------------------------------------------------------

// Supporess some bde_verify warnings for the usage example
#pragma bde_verify push
#pragma bde_verify -FD03

class DoesNotUseAnAllocatorType {
};

///Usage
///-----
// This section illustrates intended usage of this component.
//
// Example 1: Associating the 'bslma' Allocator Trait with a Type
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to declare two types that make use of a 'bslma' allocator,
// and need to associate the 'UsesBslmaAllocator' trait with those types (so
// that they behave correctly when inserted into a 'bsl' container, for
// example).  In this example we will demonstrate two different mechanisms by
// which a trait may be associated with a type.
//
// First, we declare a type 'UsesAllocatorType1', using the
// 'BSLMF_NESTED_TRAIT_DECLARATION' macro to associate the type with the
// 'UsesBslmaAllocator' trait:
//..
    namespace xyz {

    class UsesAllocatorType1 {
        // ...
//
      public:
        // TRAITS
        BSLMF_NESTED_TRAIT_DECLARATION(UsesAllocatorType1,
                                       bslma::UsesBslmaAllocator);
        // CREATORS
        explicit UsesAllocatorType1(bslma::Allocator *basicAllocator = 0);
            // ...
//
        UsesAllocatorType1(const UsesAllocatorType1&  original,
                       bslma::Allocator              *basicAllocator = 0);
            // ...
    };
//..
// Notice that the macro declaration is performed within the scope of the class
// declaration, and must be done with public scope.
//
// Then, we declare a type 'UsesAllocatorType2', and define a specialization of
// the 'UsesBslmaAllocator' trait for 'UsesAllocatorType2' that associates the
// 'UsesBslmaAllocator' trait with the type (note that this is sometimes
// referred to as a "C++11 style" trait declaration, since it is more in
// keeping with the style of trait declarations found in the C++11 standard):
//..
    class UsesAllocatorType2 {
        // ...
//
      public:
        // CREATORS
        explicit UsesAllocatorType2(bslma::Allocator *basicAllocator = 0);
            // ...
//
        UsesAllocatorType2(const UsesAllocatorType2&  original,
                           bslma::Allocator          *basicAllocator = 0);
            // ...
    };
//
    }  // close package namespace

    namespace BloombergLP {
    namespace bslma {
//
    template <> struct UsesBslmaAllocator<xyz::UsesAllocatorType2> :
                                                                 bsl::true_type
    {};
//
    }  // close package namespace
    }  // close enterprise namespace
//..
// Notice that the specialization must be performed in the 'BloombergLP::bslma'
// namespace.

#pragma bde_verify pop
//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

namespace {

struct SniffUsesBslmaAllocatorFromConstructor
{
    SniffUsesBslmaAllocatorFromConstructor(bslma::Allocator *);     // IMPLICIT
        // Create a 'SniffUsesBslmaAllocatorFromConstructor'.
};

struct ConstructFromAnyPointer
{
    template <class TYPE>
    ConstructFromAnyPointer(TYPE *);
        // Create a 'ConstructFromAnyPointer'.
};

struct ClassUsingBslmaAllocator
{
};

struct DerivedAllocator : bslma::Allocator
{
};

struct ConvertibleToAny {
    // Type that can be converted to any type.  'DetectNestedTrait' shouldn't
    // assign it any traits.  The concern is that since
    // 'BSLMF_NESTED_TRAIT_DECLARATION' defines its own conversion operator,
    // the "convert to anything" operator shouldn't interfere with the nested
    // trait logic.

    template <class TYPE>
    operator TYPE() const { return TYPE(); }
        // Return a default constructed instance of 'TYPE'.
};

}

namespace BloombergLP {
namespace bslma {

template <>
struct UsesBslmaAllocator<ClassUsingBslmaAllocator> : bsl::true_type {};

template <>
struct UsesBslmaAllocator<ConvertibleToAny> : bsl::true_type {
    // Even though the nested trait logic is disabled by the template
    // conversion operator, the out-of-class trait specialization should still
    // work.
};

}
}

//=============================================================================
//                  CLASSES FOR TESTING USAGE EXAMPLES
//-----------------------------------------------------------------------------

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    bool verbose = argc > 2;
    bool veryVerbose = argc > 3;
    bool veryVeryVerbose = argc > 4;

    (void)veryVerbose;
    (void)veryVeryVerbose;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 2: {
        // --------------------------------------------------------------------
        // USAGE EXAMPLE
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Incorporate usage example from header into driver, remove leading
        //   comment characters, and replace 'assert' with 'ASSERT'.
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose) printf("\nUSAGE EXAMPLE"
                            "\n=============\n");

        if (verbose) printf("\nMain example usage test.\n");

        using namespace xyz;

///Example 2: Testing Whether a Types Uses a 'bslma' Allocator
///- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to test whether each of a set of different types use a
// 'bslma' allocator.
//
// Here, we use the 'UsesBslmaAllocator' template to test whether the types
// 'DoesNotUseAnAllocatorType', 'UsesAllocatorType1', and 'UsesAllocatorType2'
// (defined above) use allocators:
//..
    ASSERT(false ==
           bslma::UsesBslmaAllocator<DoesNotUseAnAllocatorType>::value);
//
    ASSERT(true  ==
           bslma::UsesBslmaAllocator<UsesAllocatorType1>::value);
//
    ASSERT(true  ==
           bslma::UsesBslmaAllocator<UsesAllocatorType2>::value);
//..
// Finally, we demonstrate that the trait can be tested at compilation time, by
// testing the trait within the context of a compile-time 'BSLMF_ASSERT':
//..
    BSLMF_ASSERT(false ==
                 bslma::UsesBslmaAllocator<DoesNotUseAnAllocatorType>::value);
//
    BSLMF_ASSERT(true  ==
                 bslma::UsesBslmaAllocator<UsesAllocatorType1>::value);
//
    BSLMF_ASSERT(true ==
                 bslma::UsesBslmaAllocator<UsesAllocatorType2>::value);
//..

      } break;
      case 1: {
        // --------------------------------------------------------------------
        // BREATHING TEST
        //
        // Concerns:
        //
        // Plan:
        //
        // Testing:
        //  BREATHING TEST
        // --------------------------------------------------------------------

        if (verbose) printf("\nBREATHING TEST"
                            "\n==============\n");

        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor const>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor volatile>::value);

        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator const>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator volatile>::value);

        ASSERT(!bslma::UsesBslmaAllocator<ConstructFromAnyPointer>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator *>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator const *>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator volatile *>::value);

        ASSERT(!bslma::UsesBslmaAllocator<DerivedAllocator *>::value);

        ASSERT(bslma::UsesBslmaAllocator<ConvertibleToAny>::value);
      } break;

      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }

    return testStatus;
}

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

#include <bslma_usesbslmaallocator.h>

#include <bslma_allocator.h>
#include <bslmf_assert.h>
#include <bslmf_nestedtraitdeclaration.h>
#include <bsls_bsltestutil.h>

#include <cstdio>
#include <cstdlib>

using namespace BloombergLP;
using namespace std;
using namespace bsl;

//=============================================================================
//                             TEST PLAN
//-----------------------------------------------------------------------------
//                             Overview
//                             --------
// The component provides a meta-function for associating a trait with a type
// and detecting whether a trait is associated with a type.
// ----------------------------------------------------------------------------
//
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 2] USAGE EXAMPLE
//-----------------------------------------------------------------------------

#pragma bde_verify -TP19

//=============================================================================
//                  STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
static int testStatus = 0;

static void aSsErT(bool b, const char *s, int i) {
    if (b) {
        printf("Error " __FILE__ "(%d): %s    (failed)\n", i, s);
        if (testStatus >= 0 && testStatus <= 100) ++testStatus;
    }
}

//=============================================================================
//                       STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------

#define ASSERT       BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT  BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV      BSLS_BSLTESTUTIL_ASSERTV

#define Q   BSLS_BSLTESTUTIL_Q   // Quote identifier literally.
#define P   BSLS_BSLTESTUTIL_P   // Print identifier and value.
#define P_  BSLS_BSLTESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLS_BSLTESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLS_BSLTESTUTIL_L_  // current Line number

// ============================================================================
//                  NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT_FAIL(expr)      BSLS_ASSERTTEST_ASSERT_FAIL(expr)
#define ASSERT_PASS(expr)      BSLS_ASSERTTEST_ASSERT_PASS(expr)
#define ASSERT_SAFE_FAIL(expr) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(expr)
#define ASSERT_SAFE_PASS(expr) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(expr)

// ============================================================================
//                     GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------

//=============================================================================
//                              USAGE EXAMPLE
//-----------------------------------------------------------------------------

// Suppress some bde_verify warnings for the usage example

#pragma bde_verify push
#pragma bde_verify -FD03  // parameter not documented warning

class DoesNotUseAnAllocatorType {
};

///Usage
///-----
// This section illustrates intended usage of this component.
//
// Example 1: Associating the 'bslma' Allocator Trait with a Type
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to declare two types that make use of a 'bslma' allocator,
// and need to associate the 'UsesBslmaAllocator' trait with those types (so
// that they behave correctly when inserted into a 'bsl' container, for
// example).  In this example we will demonstrate two different mechanisms by
// which a trait may be associated with a type.
//
// First, we declare a type 'UsesAllocatorType1', using the
// 'BSLMF_NESTED_TRAIT_DECLARATION' macro to associate the type with the
// 'UsesBslmaAllocator' trait:
//..
    namespace xyz {

    class UsesAllocatorType1 {
        // ...
//
      public:
        // TRAITS
        BSLMF_NESTED_TRAIT_DECLARATION(UsesAllocatorType1,
                                       bslma::UsesBslmaAllocator);
        // CREATORS
        explicit UsesAllocatorType1(bslma::Allocator *basicAllocator = 0);
            // ...
//
        UsesAllocatorType1(const UsesAllocatorType1&  original,
                       bslma::Allocator              *basicAllocator = 0);
            // ...
    };
//..
// Notice that the macro declaration is performed within the scope of the class
// declaration, and must be done with public scope.
//
// Then, we declare a type 'UsesAllocatorType2', and define a specialization of
// the 'UsesBslmaAllocator' trait for 'UsesAllocatorType2' that associates the
// 'UsesBslmaAllocator' trait with the type (note that this is sometimes
// referred to as a "C++11 style" trait declaration, since it is more in
// keeping with the style of trait declarations found in the C++11 standard):
//..
    class UsesAllocatorType2 {
        // ...
//
      public:
        // CREATORS
        explicit UsesAllocatorType2(bslma::Allocator *basicAllocator = 0);
            // ...
//
        UsesAllocatorType2(const UsesAllocatorType2&  original,
                           bslma::Allocator          *basicAllocator = 0);
            // ...
    };
//
    }  // close package namespace

    namespace BloombergLP {
    namespace bslma {
//
    template <> struct UsesBslmaAllocator<xyz::UsesAllocatorType2> :
                                                                 bsl::true_type
    {};
//
    }  // close package namespace
    }  // close enterprise namespace
//..
// Notice that the specialization must be performed in the 'BloombergLP::bslma'
// namespace.

#pragma bde_verify pop
//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

namespace {

struct SniffUsesBslmaAllocatorFromConstructor
{
    SniffUsesBslmaAllocatorFromConstructor(bslma::Allocator *);     // IMPLICIT
        // Create a 'SniffUsesBslmaAllocatorFromConstructor' object.
};

struct ConstructFromAnyPointer
{
    template <class TYPE>
    ConstructFromAnyPointer(TYPE *);
        // Create a 'ConstructFromAnyPointer' object.
};

struct ClassUsingBslmaAllocator
{
};

struct DerivedAllocator : bslma::Allocator
{
};

struct ConvertibleToAny {
    // Type that can be converted to any type.  'DetectNestedTrait' shouldn't
    // assign it any traits.  The concern is that since
    // 'BSLMF_NESTED_TRAIT_DECLARATION' defines its own conversion operator,
    // the "convert to anything" operator shouldn't interfere with the nested
    // trait logic.

    template <class TYPE>
    operator TYPE() const { return TYPE(); }
        // Return a default constructed object of 'TYPE'.
};

}

namespace BloombergLP {
namespace bslma {

template <>
struct UsesBslmaAllocator<ClassUsingBslmaAllocator> : bsl::true_type {};

template <>
struct UsesBslmaAllocator<ConvertibleToAny> : bsl::true_type {
    // Even though the nested trait logic is disabled by the template
    // conversion operator, the out-of-class trait specialization should still
    // work.
};

}
}

//=============================================================================
//                  CLASSES FOR TESTING USAGE EXAMPLES
//-----------------------------------------------------------------------------

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    bool verbose = argc > 2;
    bool veryVerbose = argc > 3;
    bool veryVeryVerbose = argc > 4;

    (void)veryVerbose;
    (void)veryVeryVerbose;

    printf("TEST " __FILE__ " CASE %d\n", test);

    switch (test) { case 0:  // Zero is always the leading case.
      case 2: {
        // --------------------------------------------------------------------
        // USAGE EXAMPLE
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Incorporate usage example from header into driver, remove leading
        //   comment characters, and replace 'assert' with 'ASSERT'.
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose) printf("\nUSAGE EXAMPLE"
                            "\n=============\n");

        if (verbose) printf("\nMain example usage test.\n");

        using namespace xyz;

///Example 2: Testing Whether a Types Uses a 'bslma' Allocator
///- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to test whether each of a set of different types use a
// 'bslma' allocator.
//
// Here, we use the 'UsesBslmaAllocator' template to test whether the types
// 'DoesNotUseAnAllocatorType', 'UsesAllocatorType1', and 'UsesAllocatorType2'
// (defined above) use allocators:
//..
    ASSERT(false ==
           bslma::UsesBslmaAllocator<DoesNotUseAnAllocatorType>::value);
//
    ASSERT(true  ==
           bslma::UsesBslmaAllocator<UsesAllocatorType1>::value);
//
    ASSERT(true  ==
           bslma::UsesBslmaAllocator<UsesAllocatorType2>::value);
//..
// Finally, we demonstrate that the trait can be tested at compilation time, by
// testing the trait within the context of a compile-time 'BSLMF_ASSERT':
//..
    BSLMF_ASSERT(false ==
                 bslma::UsesBslmaAllocator<DoesNotUseAnAllocatorType>::value);
//
    BSLMF_ASSERT(true  ==
                 bslma::UsesBslmaAllocator<UsesAllocatorType1>::value);
//
    BSLMF_ASSERT(true ==
                 bslma::UsesBslmaAllocator<UsesAllocatorType2>::value);
//..

      } break;
      case 1: {
        // --------------------------------------------------------------------
        // BREATHING TEST
        //
        // Concerns:
        //
        // Plan:
        //
        // Testing:
        //  BREATHING TEST
        // --------------------------------------------------------------------

        if (verbose) printf("\nBREATHING TEST"
                            "\n==============\n");

        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor const>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    SniffUsesBslmaAllocatorFromConstructor volatile>::value);

        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator const>::value);
        ASSERT(bslma::UsesBslmaAllocator<
                    ClassUsingBslmaAllocator volatile>::value);

        ASSERT(!bslma::UsesBslmaAllocator<ConstructFromAnyPointer>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator *>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator const *>::value);
        ASSERT(!bslma::UsesBslmaAllocator<bslma::Allocator volatile *>::value);

        ASSERT(!bslma::UsesBslmaAllocator<DerivedAllocator *>::value);

        ASSERT(bslma::UsesBslmaAllocator<ConvertibleToAny>::value);
      } break;

      default: {
        fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
    }

    return testStatus;
}

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


<commit_before>// Copyright 2013 Eugen Sawin <esawin@me73.com>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <vector>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <map>
#include <list>
#include <sstream>
#include <limits>
#include "../io/serialize.h"

using std::vector;
using std::unordered_map;
using std::map;
using std::unordered_set;
using std::set;
using std::string;
using std::cout;
using std::endl;
using std::stringstream;
using std::numeric_limits;

using ::testing::ElementsAre;
using ::testing::Contains;
using ::testing::Not;

using namespace flow::io;  // NOLINT

TEST(SerializeTest, pod) {
  stringstream stream;
  {
    int v = 0;
    int r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = 111291;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = -111291;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = numeric_limits<int>::max();
    for (int i = 0; i < 9; ++i) {
      Write(v--, stream);
    }
    v = numeric_limits<int>::max();
    for (int i = 0; i < 9; ++i) {
      Read(stream, &r);
      ASSERT_EQ(v--, r);
    }
  }
  {
    size_t v = 111291;
    size_t r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);
  }
}

TEST(SerializeTest, string) {
  stringstream stream;
  string v;
  string r;
  Write(v, stream);
  Read(stream, &r);
  EXPECT_EQ(v, r);

  v = "fantastic";
  r = "";
  Write(v, stream);
  Read(stream, &r);
  EXPECT_EQ(v, r);

  for (int i = 0; i < 9; ++i) {
    Write(v, stream);
  }
  for (int i = 0; i < 9; ++i) {
    r = "";
    Read(stream, &r);
    ASSERT_EQ(v, r);
  }
}

TEST(SerializeTest, vector) {
  stringstream stream;
  {
    vector<int> v;
    vector<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3, 4, 5};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = vector<int>(i, 12);
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = vector<int>(i, 12);
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, unordered_map) {
  stringstream stream;
  {
    unordered_map<int, int> v;
    unordered_map<int, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {1, 2}, {2, 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
  {
    unordered_map<string, int> v;
    unordered_map<string, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{"a", 1}, {"b", 2}, {"c", 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{"a", i}, {"b", i + 1}, {"ccc", i + 2}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{"a", i}, {"b", i + 1}, {"ccc", i + 2}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, map) {
  stringstream stream;
  {
    map<int, int> v;
    map<int, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {1, 2}, {2, 3}};
    r = {};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, unordered_set) {
  stringstream stream;
  {
    unordered_set<int> v;
    unordered_set<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, set) {
  stringstream stream;
  {
    set<int> v;
    set<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, nested) {
  stringstream stream;
  {
    vector<vector<int> > v;
    vector<vector<int> > r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {2, 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, i + 1}, {i + 2}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, i + 1}, {i + 2}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}
<commit_msg>Removed google mock include.<commit_after>// Copyright 2013 Eugen Sawin <esawin@me73.com>
#include <gtest/gtest.h>
// #include <gmock/gmock.h>
#include <vector>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <map>
#include <list>
#include <sstream>
#include <limits>
#include "../io/serialize.h"

using std::vector;
using std::unordered_map;
using std::map;
using std::unordered_set;
using std::set;
using std::string;
using std::cout;
using std::endl;
using std::stringstream;
using std::numeric_limits;

// using ::testing::ElementsAre;
// using ::testing::Contains;
// using ::testing::Not;

using namespace flow::io;  // NOLINT

TEST(SerializeTest, pod) {
  stringstream stream;
  {
    int v = 0;
    int r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = 111291;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = -111291;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = numeric_limits<int>::max();
    for (int i = 0; i < 9; ++i) {
      Write(v--, stream);
    }
    v = numeric_limits<int>::max();
    for (int i = 0; i < 9; ++i) {
      Read(stream, &r);
      ASSERT_EQ(v--, r);
    }
  }
  {
    size_t v = 111291;
    size_t r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);
  }
}

TEST(SerializeTest, string) {
  stringstream stream;
  string v;
  string r;
  Write(v, stream);
  Read(stream, &r);
  EXPECT_EQ(v, r);

  v = "fantastic";
  r = "";
  Write(v, stream);
  Read(stream, &r);
  EXPECT_EQ(v, r);

  for (int i = 0; i < 9; ++i) {
    Write(v, stream);
  }
  for (int i = 0; i < 9; ++i) {
    r = "";
    Read(stream, &r);
    ASSERT_EQ(v, r);
  }
}

TEST(SerializeTest, vector) {
  stringstream stream;
  {
    vector<int> v;
    vector<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3, 4, 5};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = vector<int>(i, 12);
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = vector<int>(i, 12);
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, unordered_map) {
  stringstream stream;
  {
    unordered_map<int, int> v;
    unordered_map<int, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {1, 2}, {2, 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
  {
    unordered_map<string, int> v;
    unordered_map<string, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{"a", 1}, {"b", 2}, {"c", 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{"a", i}, {"b", i + 1}, {"ccc", i + 2}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{"a", i}, {"b", i + 1}, {"ccc", i + 2}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, map) {
  stringstream stream;
  {
    map<int, int> v;
    map<int, int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {1, 2}, {2, 3}};
    r = {};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, 12}, {i + 1, 13}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, unordered_set) {
  stringstream stream;
  {
    unordered_set<int> v;
    unordered_set<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, set) {
  stringstream stream;
  {
    set<int> v;
    set<int> r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {0, 1, 2, 3};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {i, i + 1, i + 2};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}

TEST(SerializeTest, nested) {
  stringstream stream;
  {
    vector<vector<int> > v;
    vector<vector<int> > r;
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    v = {{0, 1}, {2, 3}};
    Write(v, stream);
    Read(stream, &r);
    EXPECT_EQ(v, r);

    for (int i = 0; i < 9; ++i) {
      v = {{i, i + 1}, {i + 2}};
      Write(v, stream);
    }
    for (int i = 0; i < 9; ++i) {
      v = {{i, i + 1}, {i + 2}};
      r = {};
      Read(stream, &r);
      ASSERT_EQ(v, r);
    }
  }
}
<|endoftext|>


<commit_before>
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no>           *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/**
 * @file   transformFCFtoSFC.C
 * @author Kalliopi.Kanaki@ift.uib.no
 * @date
 * @brief  Test macro for the AliHLTTPCHWClusterTransformComponent.cxx
 *
 *
 * This macro tests the component that does the tranformation from the HW
 * cluster format to the software cluster structure.
 * For the macro to work, the user needs to use the FilePublisher component
 * to make the input files available. The data specification has to be given
 * and the input files have to be present.
 *
 * In order for the reconstruction to work properly at the absence of raw/ folders,
 * a directory has to be specified as the input argument of the function
 * and an empty raw0 folder will be created if not present.
 *
 * The macro looks for a folder called FCFFiles by default, where the produced FCF files
 * should be (format TPC_ddlnumber.fcf). Argument number 2 can be set to look in a different
 * folder if wanted.
 *
 * In addition, since the $ALICE_ROOT/OCDB/GRP/GRP/Data entry has been removed as obsolete,
 * the user needs to produce 1 simulated event, in order to create a proper GRP entry in the
 * local folder, which will be used by the line
 *
 * rec.SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd()));
 *
 * The component runs without arguments, except for the case when we want to differentiate
 * between the FCF and the SFC output. Then the argument -change-dataId will change the
 * data Id of the FCF output.
 *
 */

void transformFCFtoSCF(const char* input="./",const char* dirName="FCFFiles"){

  if(!gSystem->AccessPathName("galice.root")){
    cerr << "Please delete file galice.root or run at a different place." << endl;
    return;
  }

  if (!input) {
    cerr << "please specify input or run without arguments" << endl;
    return;
  }

  TString inputStr;
  inputStr.Form("%s",input);
  //  if(inputStr.)

  if(inputStr.CompareTo("./") == 0){
    if(gSystem->AccessPathName("./raw0")){
      cout<<"No raw folder found, making dummy raw0 directory...."<<endl;
      gSystem->Exec("mkdir raw0");
    }
    inputStr.Form("%s/",gSystem->pwd());
  }

  if(!inputStr.EndsWith("/")){
    inputStr+="/";
  }

  TString dir;
  dir.Form("%s%s/raw0",inputStr.Data(),dirName);

  if(!dir.EndsWith("/")){
    dir+="/";
  }

  if(gSystem->AccessPathName(dir)){
    cerr << "Input directory does not exist: "<<dir.Data() << endl;
    return;
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // init the HLT system in order to define the analysis chain below
  //
  gSystem->Load("libHLTrec.so");
  AliHLTSystem* gHLT=AliHLTReconstructorBase::GetInstance();

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the analysis chain to be run
  //

  int iMinSlice = 0;
  int iMaxSlice = 35;
  int iMinPart  = 0;
  int iMaxPart  = 5;

  TString dumpOutput;
  TString FCFInput;
  TString mergerInput;
  TString allclusters;

  for(int slice=iMinSlice; slice<=iMaxSlice; slice++){

      TString trackerInput;

      for(int part=iMinPart; part<=iMaxPart; part++){

          int ddlno=768;
          if (part>1) ddlno+=72+4*slice+(part-2);
          else ddlno+=2*slice+part;

          TString file;
          file.Form("raw0/TPC_%d.fcf",ddlno);

	  if(gSystem->AccessPathName(file)){
      	    cerr << "Input file does not exist: "<< file.Data() << endl;
      	    continue;
          }

          TString publisher, fcf, dumpout;
          publisher.Form("DP_%02d_%d", slice, part);
          TString argument;
          argument.Form("-datatype 'HWCLUST1' 'TPC '  -datafile %s -dataspec 0x%02x%02x%02x%02x", file.Data(), slice, slice, part, part);

          AliHLTConfiguration pubconf(publisher.Data(), "FilePublisher", NULL, argument.Data());
          fcf.Form("FCF_%02d_%d", slice, part);

          AliHLTConfiguration hwconf(fcf.Data(), "TPCHWClusterTransform", publisher.Data(), "");

	  if(trackerInput.Length()>0) trackerInput+=" ";
          trackerInput+=fcf;
	  if(allclusters.Length()>0) allclusters+=" ";
          allclusters+=fcf;

          dumpout.Form("DUMP_%02d_%d", slice, part);

	  TString argDump, dFile;
          dFile.Form("FCF_%d.dump",ddlno);
          argDump.Form("-directory FCFClusterDump -subdir=raw -datafile %s -specfmt= -blcknofmt= -idfmt= -skip-datatype", dFile.Data());

	  AliHLTConfiguration clusDumpconf(dumpout.Data(), "TPCClusterDump", fcf.Data(), argDump.Data());

          if(dumpOutput.Length()>0) dumpOutput+=",";
          dumpOutput+=dumpout;
      }

      TString tracker;
      tracker.Form("TR_%02d", slice);
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCCATracker", trackerInput.Data(), "");

      if(mergerInput.Length()>0) mergerInput+=" ";
      mergerInput+=tracker;
  }

  AliHLTConfiguration mergerconf("globalmerger","TPCCAGlobalMerger",mergerInput.Data(),"");
  AliHLTConfiguration esdconf("ESD","GlobalEsdConverter","globalmerger","");

  TString histoInput;
  if(histoInput.Length()>0) histoInput+=" ";
  histoInput+=allclusters;
  histoInput+=" ";
  histoInput+="globalmerger";

  AliHLTConfiguration histconf("histo","TPCTrackHisto",histoInput.Data(),"");
  AliHLTConfiguration rfwconf("RFW","ROOTFileWriter","histo","-datafile FCF_trackhisto -overwrite -concatenate-events");

  //USED  AliHLTConfiguration hwconf("FCF", "TPCHWClusterTransform", FCFInput.Data(), "");
  //AliHLTConfiguration hwconf("FCF", "TPCHWClusterTransform", FCFInput.Data(), "-change-dataId");
  //USED  AliHLTConfiguration clusDumpconf("sink1", "TPCClusterDump", "FCF", "-directory FCFClusterDump -subdir=raw -datafile %s -specfmt= -blcknofmt= -idfmt= -skip-datatype");

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Init and run the reconstruction
  // All but HLT reconstruction is switched off
  //
  AliReconstruction rec;
  rec.SetInput(input);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunLocalReconstruction("HLT");
  rec.SetRunTracking("");
  rec.SetLoadAlignFromCDB(0);
  rec.SetRunQA(":");
  rec.SetFillESD("");
  rec.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  rec.SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd()));
  TString option;
  option.Form("libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so libAliHLTGlobal.so loglevel=0x7c chains=RFW,ESD,%s",dumpOutput.Data());
  rec.SetOption("HLT", option);
  rec.Run();
}
<commit_msg>-- added EsdCollector and change AliReconstruction options so that the ProcessHLTOUT function is called.<commit_after>
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no>           *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/**
 * @file   transformFCFtoSFC.C
 * @author Kalliopi.Kanaki@ift.uib.no
 * @date
 * @brief  Test macro for the AliHLTTPCHWClusterTransformComponent.cxx
 *
 *
 * This macro tests the component that does the tranformation from the HW
 * cluster format to the software cluster structure.
 * For the macro to work, the user needs to use the FilePublisher component
 * to make the input files available. The data specification has to be given
 * and the input files have to be present.
 *
 * In order for the reconstruction to work properly at the absence of raw/ folders,
 * a directory has to be specified as the input argument of the function
 * and an empty raw0 folder will be created if not present.
 *
 * The macro looks for a folder called FCFFiles by default, where the produced FCF files
 * should be (format TPC_ddlnumber.fcf). Argument number 2 can be set to look in a different
 * folder if wanted.
 *
 * In addition, since the $ALICE_ROOT/OCDB/GRP/GRP/Data entry has been removed as obsolete,
 * the user needs to produce 1 simulated event, in order to create a proper GRP entry in the
 * local folder, which will be used by the line
 *
 * rec.SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd()));
 *
 * The component runs without arguments, except for the case when we want to differentiate
 * between the FCF and the SFC output. Then the argument -change-dataId will change the
 * data Id of the FCF output.
 *
 */

void transformFCFtoSCF(const char* input="./",const char* dirName="FCFFiles"){

  if(!gSystem->AccessPathName("galice.root")){
    cerr << "Please delete file galice.root or run at a different place." << endl;
    return;
  }

  if (!input) {
    cerr << "please specify input or run without arguments" << endl;
    return;
  }

  TString inputStr;
  inputStr.Form("%s",input);
  //  if(inputStr.)

  if(inputStr.CompareTo("./") == 0){
    if(gSystem->AccessPathName("./raw0")){
      cout<<"No raw folder found, making dummy raw0 directory...."<<endl;
      gSystem->Exec("mkdir raw0");
    }
    inputStr.Form("%s/",gSystem->pwd());
  }

  if(!inputStr.EndsWith("/")){
    inputStr+="/";
  }

  TString dir;
  dir.Form("%s%s/raw0",inputStr.Data(),dirName);

  if(!dir.EndsWith("/")){
    dir+="/";
  }

  if(gSystem->AccessPathName(dir)){
    cerr << "Input directory does not exist: "<<dir.Data() << endl;
    return;
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // init the HLT system in order to define the analysis chain below
  //
  gSystem->Load("libHLTrec.so");
  AliHLTSystem* gHLT=AliHLTReconstructorBase::GetInstance();

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the analysis chain to be run
  //

  int iMinSlice = 0;
  int iMaxSlice = 35;
  int iMinPart  = 0;
  int iMaxPart  = 5;

  TString dumpOutput;
  TString FCFInput;
  TString mergerInput;
  TString allclusters;

  for(int slice=iMinSlice; slice<=iMaxSlice; slice++){

      TString trackerInput;

      for(int part=iMinPart; part<=iMaxPart; part++){

          int ddlno=768;
          if (part>1) ddlno+=72+4*slice+(part-2);
          else ddlno+=2*slice+part;

          TString file;
          file.Form("raw0/TPC_%d.fcf",ddlno);

	  if(gSystem->AccessPathName(file)){
      	    cerr << "Input file does not exist: "<< file.Data() << endl;
      	    continue;
          }

          TString publisher, fcf, dumpout;
          publisher.Form("DP_%02d_%d", slice, part);
          TString argument;
          argument.Form("-datatype 'HWCLUST1' 'TPC '  -datafile %s -dataspec 0x%02x%02x%02x%02x", file.Data(), slice, slice, part, part);

          AliHLTConfiguration pubconf(publisher.Data(), "FilePublisher", NULL, argument.Data());
          fcf.Form("FCF_%02d_%d", slice, part);

          AliHLTConfiguration hwconf(fcf.Data(), "TPCHWClusterTransform", publisher.Data(), "");

	  if(trackerInput.Length()>0) trackerInput+=" ";
          trackerInput+=fcf;
	  if(allclusters.Length()>0) allclusters+=" ";
          allclusters+=fcf;

          dumpout.Form("DUMP_%02d_%d", slice, part);

	  TString argDump, dFile;
          dFile.Form("FCF_%d.dump",ddlno);
          argDump.Form("-directory FCFClusterDump -subdir=raw -datafile %s -specfmt= -blcknofmt= -idfmt= -skip-datatype", dFile.Data());

	  AliHLTConfiguration clusDumpconf(dumpout.Data(), "TPCClusterDump", fcf.Data(), argDump.Data());

          if(dumpOutput.Length()>0) dumpOutput+=",";
          dumpOutput+=dumpout;
      }

      TString tracker;
      tracker.Form("TR_%02d", slice);
      AliHLTConfiguration trackerconf(tracker.Data(), "TPCCATracker", trackerInput.Data(), "");

      if(mergerInput.Length()>0) mergerInput+=" ";
      mergerInput+=tracker;
  }

  AliHLTConfiguration mergerconf("globalmerger","TPCCAGlobalMerger",mergerInput.Data(),"");
  AliHLTConfiguration esdconf("ESD","GlobalEsdConverter","globalmerger","");
  AliHLTConfiguration sink("esdfile", "EsdCollector", "ESD", "-directory hlt-tpc-esd");

  TString histoInput;
  if(histoInput.Length()>0) histoInput+=" ";
  histoInput+=allclusters;
  histoInput+=" ";
  histoInput+="globalmerger";

  AliHLTConfiguration histconf("histo","TPCTrackHisto",histoInput.Data(),"");
  AliHLTConfiguration rfwconf("RFW","ROOTFileWriter","histo","-datafile FCF_trackhisto -overwrite -concatenate-events");

  //USED  AliHLTConfiguration hwconf("FCF", "TPCHWClusterTransform", FCFInput.Data(), "");
  //AliHLTConfiguration hwconf("FCF", "TPCHWClusterTransform", FCFInput.Data(), "-change-dataId");
  //USED  AliHLTConfiguration clusDumpconf("sink1", "TPCClusterDump", "FCF", "-directory FCFClusterDump -subdir=raw -datafile %s -specfmt= -blcknofmt= -idfmt= -skip-datatype");

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Init and run the reconstruction
  // All but HLT reconstruction is switched off
  //

  AliReconstruction rec;
  rec.SetInput(input);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunReconstruction("HLT");
  rec.SetRunTracking("");
  rec.SetLoadAlignFromCDB(0);
  rec.SetRunQA(":");
  rec.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  rec.SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd()));
  TString option;
  option.Form("libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so libAliHLTGlobal.so loglevel=0x7c chains=RFW,ESD,esdfile,%s",dumpOutput.Data());
  rec.SetOption("HLT", option);
  rec.Run();

}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Frameworks_WebServer_Router_inl_
#define _Stroika_Frameworks_WebServer_Router_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../../Foundation/Containers/Common.h"

namespace   Stroika {
    namespace   Frameworks  {
        namespace   WebServer {

            /*
             ********************************************************************************
             ******************************** WebServer::Route ******************************
             ********************************************************************************
             */
            inline  Route::Route (const RegularExpression& verbMatch, const RegularExpression& pathMatch, const RequestHandler& handler)
                : fVerbMatch_ (verbMatch)
                , fPathMatch_ (pathMatch)
                , fHandler_ (handler)
            {
            }
            inline  Route::Route (const RegularExpression& pathMatch, const RequestHandler& handler)
                : fPathMatch_ (pathMatch)
                , fHandler_ (handler)
            {
            }
            inline  Route::Route (const function<bool(const Request&)>& requestMatcher, const RequestHandler& handler)
                : fRequestMatch_ (requestMatcher)
                , fHandler_ (handler)
            {
            }

        }
    }
}
#endif  /*_Stroika_Frameworks_WebServer_Router_inl_*/
<commit_msg>wrap new Route/ConnectionMgr stuff with !qCompilerAndStdLib_regex_Buggy; and  support new Route RequestMatch<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Frameworks_WebServer_Router_inl_
#define _Stroika_Frameworks_WebServer_Router_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../../Foundation/Containers/Common.h"

namespace   Stroika {
    namespace   Frameworks  {
        namespace   WebServer {

#if     !qCompilerAndStdLib_regex_Buggy
            /*
             ********************************************************************************
             ******************************** WebServer::Route ******************************
             ********************************************************************************
             */
            inline  Route::Route (const RegularExpression& verbMatch, const RegularExpression& pathMatch, const RequestHandler& handler)
                : fVerbMatch_ (verbMatch)
                , fPathMatch_ (pathMatch)
                , fHandler_ (handler)
            {
            }
            inline  Route::Route (const RegularExpression& pathMatch, const RequestHandler& handler)
                : fPathMatch_ (pathMatch)
                , fHandler_ (handler)
            {
            }
            inline  Route::Route (const function<bool(const Request&)>& requestMatcher, const RequestHandler& handler)
                : fRequestMatch_ (requestMatcher)
                , fHandler_ (handler)
            {
            }
#endif

        }
    }
}
#endif  /*_Stroika_Frameworks_WebServer_Router_inl_*/
<|endoftext|>


<commit_before>// ChiCheChatPanel.cpp

#include "ChiCheChatPanel.h"
#include "ChiCheClient.h"
#include "ChiCheSocket.h"
#include "ChiCheApp.h"
#include <wx/sizer.h>

using namespace ChiChe;

// Now, I suppose we could have the server maintain the chat log so that
// late joiners can see the conversation that has been taking place, but
// I'm not that motivated to put that in.  I think this is fine for now.

//=====================================================================================
ChatPanel::ChatPanel( void )
{
	outputText = nullptr;
	inputText = nullptr;
}

//=====================================================================================
/*virtual*/ ChatPanel::~ChatPanel( void )
{
}

//=====================================================================================
/*virtual*/ void ChatPanel::SetupPaneInfo( wxAuiPaneInfo& paneInfo )
{
	paneInfo.MinSize( 150, -1 );
}

//=====================================================================================
/*virtual*/ void ChatPanel::CreateControls( void )
{
	outputText = new wxRichTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1, -1 ), wxRE_MULTILINE | wxRE_READONLY );
	inputText = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1, 20 ), wxTE_PROCESS_ENTER );

	outputText->SetBackgroundColour( wxColour( 0, 0, 0 ) );
	outputText->SetForegroundColour( wxColour( 255, 255, 255 ) );

	wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL );
	boxSizer->Add( outputText, 1, wxGROW | wxALL, 0 );
	boxSizer->Add( inputText, 0, wxGROW | wxALL, 0 );

	SetSizer( boxSizer );

	Bind( wxEVT_TEXT_ENTER, &ChatPanel::OnTextEnter, this );
}

//=====================================================================================
/*virtual*/ void ChatPanel::Update( void )
{
}

//=====================================================================================
void ChatPanel::OnTextEnter( wxEvent& event )
{
	Client* client = wxGetApp().GetClient();
	if( !client )
		return;

	int color = client->GetColor();

	wxString message = inputText->GetValue();
	inputText->Clear();

	Socket::Packet outPacket;
	PackChatMessage( outPacket, message, color );

	client->GetSocket()->WritePacket( outPacket );
}

//=====================================================================================
void ChatPanel::ReceiveChatMessage( const wxString& message, int color )
{
	c3ga::vectorE3GA renderColor;
	Board::RenderColor( color, renderColor );

	unsigned char r = ( unsigned char )( renderColor.get_e1() * 255.0 );
	unsigned char g = ( unsigned char )( renderColor.get_e2() * 255.0 );
	unsigned char b = ( unsigned char )( renderColor.get_e3() * 255.0 );
	wxColour textRenderColor( r, g, b );

	wxString textColor;
	Board::ParticipantText( color, textColor );

	outputText->BeginBold();
	outputText->BeginTextColour( textRenderColor );
	outputText->WriteText( textColor + ": " );
	outputText->EndTextColour();
	outputText->EndBold();
	outputText->BeginTextColour( wxColour( 255, 255, 255 ) );
	outputText->WriteText( message );
	outputText->EndTextColour();
	outputText->Newline();
}

//=====================================================================================
/*static*/ bool ChatPanel::PackChatMessage( Socket::Packet& outPacket, const wxString& message, int color )
{
	int messageLength = message.Length();
	wxInt32* data = new wxInt32[ 1 + messageLength ];
	data[0] = color;

	for( int i = 0; i < messageLength; i++ )
		data[ i + 1 ] = message.GetChar( i );

	outPacket.Reset();
	outPacket.SetType( Socket::Packet::CHAT_MESSAGE );
	outPacket.SetData( ( wxInt8* )data );
	outPacket.SetSize( ( 1 + messageLength ) * sizeof( wxInt32 ) );
	outPacket.OwnsMemory( true );

	return true;
}

//=====================================================================================
/*static*/ bool ChatPanel::UnpackChatMessage( const Socket::Packet& inPacket, wxString& message, int& color )
{
	if( inPacket.GetType() != Socket::Packet::CHAT_MESSAGE )
		return false;

	const wxInt32* data = ( const wxInt32* )inPacket.GetData();

	if( inPacket.ByteSwap() )
		color = wxINT32_SWAP_ALWAYS( data[0] );
	else
		color = data[0];

	message = "";
	int messageLength = ( inPacket.GetSize() - 1 ) / sizeof( wxInt32 );
	for( int i = 1; i <= messageLength; i++ )
	{
		wxInt32 word = inPacket.ByteSwap() ? wxINT32_SWAP_ALWAYS( data[i] ) : data[i];
		wxUniChar uniChar( word );
		message.Append( uniChar );
	}

	return true;
}

// ChiCheChatPanel.cpp<commit_msg>fix another lame linux-only bug<commit_after>// ChiCheChatPanel.cpp

#include "ChiCheChatPanel.h"
#include "ChiCheClient.h"
#include "ChiCheSocket.h"
#include "ChiCheApp.h"
#include <wx/sizer.h>

using namespace ChiChe;

// Now, I suppose we could have the server maintain the chat log so that
// late joiners can see the conversation that has been taking place, but
// I'm not that motivated to put that in.  I think this is fine for now.

//=====================================================================================
ChatPanel::ChatPanel( void )
{
	outputText = nullptr;
	inputText = nullptr;
}

//=====================================================================================
/*virtual*/ ChatPanel::~ChatPanel( void )
{
}

//=====================================================================================
/*virtual*/ void ChatPanel::SetupPaneInfo( wxAuiPaneInfo& paneInfo )
{
	paneInfo.MinSize( 150, -1 );
}

//=====================================================================================
/*virtual*/ void ChatPanel::CreateControls( void )
{
	outputText = new wxRichTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1, -1 ), wxRE_MULTILINE | wxRE_READONLY );
	inputText = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1, 20 ), wxTE_PROCESS_ENTER );

#ifndef __LINUX__
	outputText->SetBackgroundColour( wxColour( 0, 0, 0 ) );
#endif

	wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL );
	boxSizer->Add( outputText, 1, wxGROW | wxALL, 0 );
	boxSizer->Add( inputText, 0, wxGROW | wxALL, 0 );

	SetSizer( boxSizer );

	Bind( wxEVT_TEXT_ENTER, &ChatPanel::OnTextEnter, this );
}

//=====================================================================================
/*virtual*/ void ChatPanel::Update( void )
{
}

//=====================================================================================
void ChatPanel::OnTextEnter( wxEvent& event )
{
	Client* client = wxGetApp().GetClient();
	if( !client )
		return;

	int color = client->GetColor();

	wxString message = inputText->GetValue();
	inputText->Clear();

	Socket::Packet outPacket;
	PackChatMessage( outPacket, message, color );

	client->GetSocket()->WritePacket( outPacket );
}

//=====================================================================================
void ChatPanel::ReceiveChatMessage( const wxString& message, int color )
{
	c3ga::vectorE3GA renderColor;
	Board::RenderColor( color, renderColor );

	unsigned char r = ( unsigned char )( renderColor.get_e1() * 255.0 );
	unsigned char g = ( unsigned char )( renderColor.get_e2() * 255.0 );
	unsigned char b = ( unsigned char )( renderColor.get_e3() * 255.0 );
	wxColour textRenderColor( r, g, b );

	wxString textColor;
	Board::ParticipantText( color, textColor );

	outputText->BeginBold();
	outputText->BeginTextColour( textRenderColor );
	outputText->WriteText( textColor + ": " );
	outputText->EndTextColour();
	outputText->EndBold();
#ifndef __LINUX__
	outputText->BeginTextColour( wxColour( 255, 255, 255 ) );
#else
	outputText->BeginTextColour( wxColour( 0, 0, 0 ) );
#endif
	outputText->WriteText( message );
	outputText->EndTextColour();
	outputText->Newline();
}

//=====================================================================================
/*static*/ bool ChatPanel::PackChatMessage( Socket::Packet& outPacket, const wxString& message, int color )
{
	int messageLength = message.Length();
	wxInt32* data = new wxInt32[ 1 + messageLength ];
	data[0] = color;

	for( int i = 0; i < messageLength; i++ )
		data[ i + 1 ] = message.GetChar( i );

	outPacket.Reset();
	outPacket.SetType( Socket::Packet::CHAT_MESSAGE );
	outPacket.SetData( ( wxInt8* )data );
	outPacket.SetSize( ( 1 + messageLength ) * sizeof( wxInt32 ) );
	outPacket.OwnsMemory( true );

	return true;
}

//=====================================================================================
/*static*/ bool ChatPanel::UnpackChatMessage( const Socket::Packet& inPacket, wxString& message, int& color )
{
	if( inPacket.GetType() != Socket::Packet::CHAT_MESSAGE )
		return false;

	const wxInt32* data = ( const wxInt32* )inPacket.GetData();

	if( inPacket.ByteSwap() )
		color = wxINT32_SWAP_ALWAYS( data[0] );
	else
		color = data[0];

	message = "";
	int messageLength = ( inPacket.GetSize() - 1 ) / sizeof( wxInt32 );
	for( int i = 1; i <= messageLength; i++ )
	{
		wxInt32 word = inPacket.ByteSwap() ? wxINT32_SWAP_ALWAYS( data[i] ) : data[i];
		wxUniChar uniChar( word );
		message.Append( uniChar );
	}

	return true;
}

// ChiCheChatPanel.cpp<|endoftext|>


<commit_before>/*
 * HLLib
 * Copyright (C) 2006-2010 Ryan Gregg

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

#include "HLLib.h"
#include "FileMapping.h"

using namespace HLLib;
using namespace HLLib::Mapping;

#ifdef _WIN32
CFileMapping::CFileMapping(const hlChar *lpFileName) : hFile(0), hFileMapping(0), uiMode(HL_MODE_INVALID), lpView(0), uiViewSize(0)
#else
CFileMapping::CFileMapping(const hlChar *lpFileName) : iFile(-1), uiMode(HL_MODE_INVALID), lpView(0), uiViewSize(0)
#endif
{
	this->lpFileName = new hlChar[strlen(lpFileName) + 1];
	strcpy(this->lpFileName, lpFileName);

#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);

	this->uiAllocationGranularity = SystemInfo.dwAllocationGranularity;
#else
	this->uiAllocationGranularity = static_cast<hlUInt>(getpagesize());
#endif
}

CFileMapping::~CFileMapping()
{
	this->Close();

	delete []this->lpFileName;
}

HLMappingType CFileMapping::GetType() const
{
	return HL_MAPPING_FILE;
}

const hlChar *CFileMapping::GetFileName() const
{
	return this->lpFileName;
}

hlBool CFileMapping::GetOpened() const
{
#ifdef _WIN32
	return this->hFile != 0;
#else
	return this->iFile >= 0;
#endif
}

hlUInt CFileMapping::GetMode() const
{
	return this->uiMode;
}

hlBool CFileMapping::OpenInternal(hlUInt uiMode)
{
	assert(!this->GetOpened());

#ifdef _WIN32
	DWORD dwDesiredAccess = ((uiMode & HL_MODE_READ) ? GENERIC_READ : 0) | ((uiMode & HL_MODE_WRITE) ? GENERIC_WRITE : 0);
	DWORD dwShareMode = (uiMode & HL_MODE_VOLATILE) ? FILE_SHARE_READ | FILE_SHARE_WRITE : ((uiMode & HL_MODE_READ) && !(uiMode & HL_MODE_WRITE) ? FILE_SHARE_READ : 0);
	DWORD dwCreationDisposition = (uiMode & HL_MODE_WRITE) && (uiMode & HL_MODE_CREATE) ? (bOverwriteFiles ? CREATE_ALWAYS : CREATE_NEW) : ((uiMode & HL_MODE_READ) || (uiMode & HL_MODE_WRITE) ? OPEN_EXISTING : 0);

	if(dwDesiredAccess == 0 || dwCreationDisposition == 0)
	{
		LastError.SetErrorMessageFormated("Invalid open mode (%#.8x).", uiMode);

		return hlFalse;
	}

	this->hFile = CreateFile(this->lpFileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);

	if(this->hFile == INVALID_HANDLE_VALUE)
	{
		LastError.SetSystemErrorMessage("Error opening file.");

		this->hFile = 0;
		return hlFalse;
	}

	DWORD dwProtectionMode = (uiMode & HL_MODE_WRITE) ? PAGE_READWRITE : ((uiMode & HL_MODE_READ) ? PAGE_READONLY : 0);

	this->hFileMapping = CreateFileMapping(this->hFile, NULL, dwProtectionMode, 0, 0, NULL);

	if(this->hFileMapping == 0)
	{
		LastError.SetSystemErrorMessage("Failed to create file mapping object for file.");

		return hlFalse;
	}

	// Map the whole file to memory then pass pointers to the
	// master view back instead of mapping smaller views.
	if(uiMode & HL_MODE_QUICK_FILEMAPPING)
	{
		LARGE_INTEGER liFileSize;
#ifdef _WIN64
		if(GetFileSizeEx(this->hFile, &liFileSize))
#else
		if(GetFileSizeEx(this->hFile, &liFileSize) && liFileSize.HighPart == 0)
#endif
		{
			DWORD dwDesiredAccess = ((uiMode & HL_MODE_READ) ? FILE_MAP_READ : 0) | ((uiMode & HL_MODE_WRITE) ? FILE_MAP_WRITE : 0);

			this->uiViewSize = static_cast<hlULongLong>(liFileSize.QuadPart);
			this->lpView = MapViewOfFile(this->hFileMapping, dwDesiredAccess, 0, 0, static_cast<SIZE_T>(this->uiViewSize));

			if(this->lpView == 0)
			{
				LastError.SetSystemErrorMessage("Failed to map view of file. Try disabling quick file mapping.");

				return hlFalse;
			}
		}
		else
		{
			// Cannot map more than 4 GB on x86.
			uiMode &= ~HL_MODE_QUICK_FILEMAPPING;
		}
	}
#else
	hlInt iMode;

	if((uiMode & HL_MODE_READ) && (uiMode & HL_MODE_WRITE))
	{
		iMode = O_RDWR;
	}
	else if(uiMode & HL_MODE_READ)
	{
		iMode = O_RDONLY;
	}
	else if(uiMode & HL_MODE_WRITE)
	{
		iMode = O_WRONLY;
	}

	if((uiMode & HL_MODE_WRITE) && (uiMode & HL_MODE_CREATE))
	{
		iMode |= bOverwriteFiles ? O_CREAT | O_TRUNC : O_CREAT | O_EXCL;
	}

	if((uiMode & (HL_MODE_READ | HL_MODE_WRITE)) == 0)
	{
		LastError.SetErrorMessageFormated("Invalid open mode (%#.8x).", uiMode);

		return hlFalse;
	}

	this->iFile = open(this->lpFileName, iMode | O_BINARY | O_RANDOM, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

	if(this->iFile < 0)
	{
		LastError.SetSystemErrorMessage("Error opening file.");

		this->iFile = -1;
		return hlFalse;
	}

	// Map the whole file to memory then pass pointers to the
	// master view back instead of mapping smaller views.
	if(uiMode & HL_MODE_QUICK_FILEMAPPING)
	{
		hlInt iProtection = ((uiMode & HL_MODE_READ) ? PROT_READ : 0) | ((uiMode & HL_MODE_WRITE) ? PROT_WRITE : 0);

		struct stat Stat;

		if(fstat(this->iFile, &Stat) < 0)
		{
			LastError.SetSystemErrorMessage("Error retrieving file size.");

			return hlFalse;
		}

		this->uiViewSize = (hlUInt)Stat.st_size;

		this->lpView = mmap(0, this->uiViewSize, iProtection, MAP_SHARED, this->iFile, 0);

		if(this->lpView == MAP_FAILED)
		{
			LastError.SetSystemErrorMessage("Failed to map view of file. Try disabling quick file mapping.");

			this->lpView = 0;
			return hlFalse;
		}
	}
#endif

	this->uiMode = uiMode;

	return hlTrue;
}

hlVoid CFileMapping::CloseInternal()
{
#ifdef _WIN32
	if(this->lpView != 0)
	{
		UnmapViewOfFile(this->lpView);
		this->lpView = 0;
	}

	this->uiViewSize = 0;

	if(this->hFileMapping != 0)
	{
		CloseHandle(this->hFileMapping);
		this->hFileMapping = 0;
	}

	if(this->hFile != 0)
	{
		CloseHandle(this->hFile);
		this->hFile = 0;
	}
#else
	if(this->lpView != 0)
	{
		munmap(this->lpView, this->uiViewSize);
		this->lpView = 0;
	}

	this->uiViewSize = 0;

	if(this->iFile >= 0)
	{
		close(this->iFile);
		this->iFile = -1;
	}
#endif
}

hlULongLong CFileMapping::GetMappingSize() const
{
	if(!this->GetOpened())
	{
		return 0;
	}

#ifdef _WIN32
	LARGE_INTEGER liFileSize;
	return GetFileSizeEx(this->hFile, &liFileSize) ? static_cast<hlULongLong>(liFileSize.QuadPart) : 0;
#else
	struct stat Stat;

	return fstat(this->iFile, &Stat) < 0 ? 0 : Stat.st_size;
#endif
}

hlBool CFileMapping::MapInternal(CView *&pView, hlULongLong uiOffset, hlULongLong uiLength)
{
	assert(this->GetOpened());

	if(this->lpView != 0)
	{
		if(uiOffset + uiLength > this->uiViewSize)
		{
#ifdef _WIN32
			LastError.SetErrorMessageFormated("Requested view (%I64u, %I64u) does not fit inside mapping, (%I64u, %I64u).", uiOffset, uiLength, 0ULL, this->uiViewSize);
#else
			LastError.SetErrorMessageFormated("Requested view (%llu, %llu) does not fit inside mapping, (%llu, %llu).", uiOffset, uiLength, 0ULL, this->uiViewSize);
#endif
			return hlFalse;
		}

		pView = new CView(this, (hlByte *)this->lpView, 0, this->uiViewSize, uiOffset, uiLength);
	}
	else
	{
		hlULongLong uiMappingSize = this->GetMappingSize();

		if(uiOffset + uiLength > uiMappingSize)
		{
#ifdef _WIN32
			LastError.SetErrorMessageFormated("Requested view (%I64u, %I64u) does not fit inside mapping, (%I64u, %I64u).", uiOffset, uiLength, 0ULL, this->uiViewSize);
#else
			LastError.SetErrorMessageFormated("Requested view (%llu, %llu) does not fit inside mapping, (%llu, %llu).", uiOffset, uiLength, 0ULL, this->uiViewSize);
#endif
			return hlFalse;
		}

		// Map multiples of the allocation granularity from the nearest allocation granularity
		// (for performance).
		hlULongLong uiGrainOffset = uiOffset % static_cast<hlULongLong>(this->uiAllocationGranularity);
		hlULongLong uiFileOffset = uiOffset - uiGrainOffset;
		hlULongLong uiFileLength = (((uiLength + uiGrainOffset + static_cast<hlULongLong>(this->uiAllocationGranularity) - 1) / static_cast<hlULongLong>(this->uiAllocationGranularity)) * static_cast<hlULongLong>(this->uiAllocationGranularity));

		if(uiFileOffset + uiFileLength > uiMappingSize)
		{
			uiFileLength = uiMappingSize - uiFileOffset;
		}

#ifdef _WIN32
		DWORD dwDesiredAccess = ((uiMode & HL_MODE_READ) ? FILE_MAP_READ : 0) | ((uiMode & HL_MODE_WRITE) ? FILE_MAP_WRITE : 0);

		hlVoid *lpView = MapViewOfFile(this->hFileMapping, dwDesiredAccess, static_cast<DWORD>(uiFileOffset >> 32), static_cast<DWORD>(uiFileOffset), static_cast<SIZE_T>(uiFileLength));

		if(lpView == 0)
		{
			LastError.SetSystemErrorMessage("Failed to map view of file. Try disabling file mapping.");
			return hlFalse;
		}
#else
		hlInt iProtection = ((uiMode & HL_MODE_READ) ? PROT_READ : 0) | ((uiMode & HL_MODE_WRITE) ? PROT_WRITE : 0);

		hlVoid *lpView = mmap(0, uiFileLength, iProtection, MAP_SHARED, this->iFile, uiFileOffset);

		if(this->lpView == MAP_FAILED)
		{
			LastError.SetSystemErrorMessage("Failed to map view of file. Try disabling file mapping.");
			return hlFalse;
		}
#endif

		pView = new CView(this, lpView, uiFileOffset, uiFileLength, uiGrainOffset, uiLength);
	}

	return hlTrue;
}

hlVoid CFileMapping::UnmapInternal(CView &View)
{
	assert(this->GetOpened());
	assert(View.GetMapping() == this);

	if(this->lpView == 0)
	{
#ifdef _WIN32
		UnmapViewOfFile((hlVoid *)View.GetAllocationView());
#else
		munmap((hlVoid *)View.GetAllocationView(), View.GetAllocationLength());
#endif
	}
}
<commit_msg>Delete FileMapping.cpp<commit_after><|endoftext|>