<commit_before>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/compiler/Dialect/HAL/Target/LLVM/Builtins/Device.h"

#include "iree/builtins/device/bin/libdevice.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "mlir/Support/LLVM.h"

namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {

static const iree_file_toc_t *lookupDeviceFile(StringRef filename) {
  for (size_t i = 0; i < iree_builtins_libdevice_size(); ++i) {
    const auto &file_toc = iree_builtins_libdevice_create()[i];
    if (filename == file_toc.name) return &file_toc;
  }
  return nullptr;
}

static const iree_file_toc_t *lookupDeviceFile(
    llvm::TargetMachine *targetMachine) {
  const auto &triple = targetMachine->getTargetTriple();

  // NOTE: other arch-specific checks go here.

  if (triple.isWasm()) {
    // TODO(benvanik): feature detect simd and such.
    // auto features = targetMachine->getTargetFeatureString();
    if (triple.isArch32Bit()) {
      return lookupDeviceFile("libdevice_wasm32_generic.bc");
    } else if (triple.isArch64Bit()) {
      return lookupDeviceFile("libdevice_wasm64_generic.bc");
    }
  }

  // Fallback path using the generic wasm variants as they are largely
  // machine-agnostic.
  if (triple.isArch32Bit()) {
    return lookupDeviceFile("libdevice_wasm32_generic.bc");
  } else if (triple.isArch64Bit()) {
    return lookupDeviceFile("libdevice_wasm64_generic.bc");
  } else {
    return nullptr;
  }
}

// TODO(benvanik): move to a common file so we can reuse it.
static void overridePlatformGlobal(llvm::Module &module, StringRef globalName,
                                   uint32_t newValue) {
  // NOTE: the global will not be defined if it is not used in the module.
  auto *globalValue = module.getNamedGlobal(globalName);
  if (!globalValue) return;
  globalValue->setLinkage(llvm::GlobalValue::PrivateLinkage);
  globalValue->setDSOLocal(true);
  globalValue->setConstant(true);
  globalValue->setInitializer(
      llvm::ConstantInt::get(globalValue->getValueType(), APInt(32, newValue)));
}

llvm::Expected<std::unique_ptr<llvm::Module>> loadDeviceBitcode(
    llvm::TargetMachine *targetMachine, llvm::LLVMContext &context) {
  // Find a bitcode file for the current architecture.
  const auto *file = lookupDeviceFile(targetMachine);
  if (!file) {
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "no matching architecture bitcode file");
  }

  // Load the generic bitcode file contents.
  llvm::MemoryBufferRef bitcodeBufferRef(
      llvm::StringRef(file->data, file->size), file->name);
  auto bitcodeModuleValue = llvm::parseBitcodeFile(bitcodeBufferRef, context);
  if (!bitcodeModuleValue) return bitcodeModuleValue;
  auto bitcodeModule = std::move(bitcodeModuleValue.get());

  // Inject target-specific flags.
  overridePlatformGlobal(*bitcodeModule, "libdevice_platform_example_flag", 0u);

  return bitcodeModule;
}

}  // namespace HAL
}  // namespace IREE
}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Fix compile GCC error (#7862)<commit_after>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/compiler/Dialect/HAL/Target/LLVM/Builtins/Device.h"

#include "iree/builtins/device/bin/libdevice.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "mlir/Support/LLVM.h"

namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {

static const iree_file_toc_t *lookupDeviceFile(StringRef filename) {
  for (size_t i = 0; i < iree_builtins_libdevice_size(); ++i) {
    const auto &file_toc = iree_builtins_libdevice_create()[i];
    if (filename == file_toc.name) return &file_toc;
  }
  return nullptr;
}

static const iree_file_toc_t *lookupDeviceFile(
    llvm::TargetMachine *targetMachine) {
  const auto &triple = targetMachine->getTargetTriple();

  // NOTE: other arch-specific checks go here.

  if (triple.isWasm()) {
    // TODO(benvanik): feature detect simd and such.
    // auto features = targetMachine->getTargetFeatureString();
    if (triple.isArch32Bit()) {
      return lookupDeviceFile("libdevice_wasm32_generic.bc");
    } else if (triple.isArch64Bit()) {
      return lookupDeviceFile("libdevice_wasm64_generic.bc");
    }
  }

  // Fallback path using the generic wasm variants as they are largely
  // machine-agnostic.
  if (triple.isArch32Bit()) {
    return lookupDeviceFile("libdevice_wasm32_generic.bc");
  } else if (triple.isArch64Bit()) {
    return lookupDeviceFile("libdevice_wasm64_generic.bc");
  } else {
    return nullptr;
  }
}

// TODO(benvanik): move to a common file so we can reuse it.
static void overridePlatformGlobal(llvm::Module &module, StringRef globalName,
                                   uint32_t newValue) {
  // NOTE: the global will not be defined if it is not used in the module.
  auto *globalValue = module.getNamedGlobal(globalName);
  if (!globalValue) return;
  globalValue->setLinkage(llvm::GlobalValue::PrivateLinkage);
  globalValue->setDSOLocal(true);
  globalValue->setConstant(true);
  globalValue->setInitializer(
      llvm::ConstantInt::get(globalValue->getValueType(), APInt(32, newValue)));
}

llvm::Expected<std::unique_ptr<llvm::Module>> loadDeviceBitcode(
    llvm::TargetMachine *targetMachine, llvm::LLVMContext &context) {
  // Find a bitcode file for the current architecture.
  const auto *file = lookupDeviceFile(targetMachine);
  if (!file) {
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "no matching architecture bitcode file");
  }

  // Load the generic bitcode file contents.
  llvm::MemoryBufferRef bitcodeBufferRef(
      llvm::StringRef(file->data, file->size), file->name);
  auto bitcodeModuleValue = llvm::parseBitcodeFile(bitcodeBufferRef, context);
  if (!bitcodeModuleValue) return bitcodeModuleValue;
  auto bitcodeModule = std::move(bitcodeModuleValue.get());

  // Inject target-specific flags.
  overridePlatformGlobal(*bitcodeModule, "libdevice_platform_example_flag", 0u);

  return std::move(bitcodeModule);
}

}  // namespace HAL
}  // namespace IREE
}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>//! @Alan
//! Exercise 11.14:
//! Extend the map of children to their family name that you wrote for the
//! exercises in § 11.2.1 (p. 424) by having the vector store a pair that
//! holds a child’s name and birthday.
//!
//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

int main()
{
    //! define a map as required.
    std::map<std::string, std::vector<std::pair<std::string,std::string>>>
            famlies_map;
    //! declare three strings to store the input
    std::string lastName, childName, birthday;

    while([&](){//!   a lambda to read lastName and check if should quit

          std::cout << "last name:\n";
          std::cin >> lastName;

          return lastName != "@q";
}())
    {
        while([&](){//!   a lambda to read child name and birthday and check if should quit
              std::cout << "child's name:\n";
              std::cin  >> childName;
              std::cout << "his birthday:\n";
              std::cin  >> birthday;

              return childName != "@q" && birthday != "@q";
    }())
        {
            famlies_map[lastName].push_back({childName, birthday});
            //!        ^^^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^
            //!  use lastName as the key    create a pair using {}.
        }
    }

    //! print the content.
    for(const auto &e : famlies_map)
    {
        std::cout << e.first <<":\n";

        for (const auto &l : e.second)
        {
            std::cout << l.first << " "
                      << l.second << " ";
        }
    }

    return 0;
}
<commit_msg>Update ex11_14.cpp<commit_after>//! @Alan
//! Exercise 11.14:
//! Extend the map of children to their family name that you wrote for the
//! exercises in § 11.2.1 (p. 424) by having the vector store a pair that
//! holds a child’s name and birthday.
//!
//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

int main()
{
    //! define a map as required.
    std::map<std::string, std::vector<std::pair<std::string,std::string>>>
            famlies_map;
    //! declare three strings to store the input
    std::string lastName, childName, birthday;

    while([&](){//!   a lambda to read lastName and check if should quit

          std::cout << "last name:\n";
          std::cin >> lastName;

          return lastName != "@q";
}())
    {
        while([&](){//!   a lambda to read child name and birthday and check if should quit
              std::cout << "child's name:\n";
              std::cin  >> childName;
              std::cout << "his birthday:\n";
              std::cin  >> birthday;

              return childName != "@q" && birthday != "@q";
    }())
        {
            famlies_map[lastName].push_back({childName, birthday});
            //!        ^^^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^
            //!  use lastName as the key    create a pair using {}.
        }
    }

    //! print the content.
    for(const auto &e : famlies_map)
    {
        std::cout << e.first <<":\n";

        for (const auto &l : e.second)
        {
            std::cout << l.first << " "
                      << l.second << " ";
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "picodbc.h"
#include <iostream>

using namespace std;

template<class T>
void show(picodbc::result results)
{
    const short columns = results.columns();
    long rows_displayed = 0;

    cout << "\nDisplaying " << results.affected_rows() << " rows (" << results.rowset_size() << " at a time):" << endl;

    cout << "row\t";
    for(short i = 0; i < columns; ++i)
        cout << results.column_name(i) << "\t";
    cout << endl;

    while(results.next())
    {
        const unsigned long rows = results.rows();
        for(unsigned long row = 0; row < rows; ++row)
        {
            cout << rows_displayed++ << "\t";
            for(short col = 0; col < columns; ++col)
            {
                if(results.is_null(col, row))
                    cout << "(null)";
                else
                    cout << "(" << results.get<T>(col, row) << ")";
                cout << "\t";
            }
            cout << endl;
        }
    }
}

int main()
{
    // const char* connection_string = "A Data Source Connection String";
    // #define EXAMPLE_TABLE "public.example_table"
    const char* connection_string = "Driver=vertica;Servername=sandbox03;Port=5433;Database=vertica01;UserName=dbadmin;Password=;";
    #define EXAMPLE_TABLE "public.amytest"

    try
    {
        // Establishing connections
        picodbc::connection connection(connection_string);
        // or picodbc::connection connection(connection_string, timeout_seconds);
        // or picodbc::connection connection("data source name", "username", "password");
        // or picodbc::connection connection("data source name", "username", "password", timeout_seconds);
        cout << "Connected with driver " << connection.driver_name() << endl;

        picodbc::statement statement;
        picodbc::result results;

        // Direct execution
        results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";");
        show<string>(results);

        // Direct execution, bulk fetching 2 rows at a time
        results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";", 2);
        show<string>(results);

        // Binding parameters
        statement.prepare(connection, "select * from " EXAMPLE_TABLE " where cast(a as float) = ?;");
        statement.bind_parameter(0, 1.0);

        results = statement.execute();
        show<string>(results);

        // Transactions
        {
            picodbc::transaction transaction(connection);
            statement.execute_direct(connection, "delete from " EXAMPLE_TABLE " where true;");
            // transaction will be rolled back if we don't call transaction.commit()
        }

        // The resources used by connection and statement are cleaned up automatically or
        // you can explicitly call statement.close() and/or connection.disconnect().
    }
    catch(const exception& e)
    {
        cerr << "exception: " << e.what() << endl;
    }
}<commit_msg>Removed testing code.<commit_after>#include "picodbc.h"
#include <iostream>

using namespace std;

template<class T>
void show(picodbc::result results)
{
    const short columns = results.columns();
    long rows_displayed = 0;

    cout << "\nDisplaying " << results.affected_rows() << " rows (" << results.rowset_size() << " at a time):" << endl;

    cout << "row\t";
    for(short i = 0; i < columns; ++i)
        cout << results.column_name(i) << "\t";
    cout << endl;

    while(results.next())
    {
        const unsigned long rows = results.rows();
        for(unsigned long row = 0; row < rows; ++row)
        {
            cout << rows_displayed++ << "\t";
            for(short col = 0; col < columns; ++col)
            {
                if(results.is_null(col, row))
                    cout << "(null)";
                else
                    cout << "(" << results.get<T>(col, row) << ")";
                cout << "\t";
            }
            cout << endl;
        }
    }
}

int main()
{
    const char* connection_string = "A Data Source Connection String";
    #define EXAMPLE_TABLE "public.example_table"

    try
    {
        // Establishing connections
        picodbc::connection connection(connection_string);
        // or picodbc::connection connection(connection_string, timeout_seconds);
        // or picodbc::connection connection("data source name", "username", "password");
        // or picodbc::connection connection("data source name", "username", "password", timeout_seconds);
        cout << "Connected with driver " << connection.driver_name() << endl;

        picodbc::statement statement;
        picodbc::result results;

        // Direct execution
        results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";");
        show<string>(results);

        // Direct execution, bulk fetching 2 rows at a time
        results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";", 2);
        show<string>(results);

        // Binding parameters
        statement.prepare(connection, "select * from " EXAMPLE_TABLE " where cast(a as float) = ?;");
        statement.bind_parameter(0, 1.0);

        results = statement.execute();
        show<string>(results);

        // Transactions
        {
            picodbc::transaction transaction(connection);
            statement.execute_direct(connection, "delete from " EXAMPLE_TABLE " where true;");
            // transaction will be rolled back if we don't call transaction.commit()
        }

        // The resources used by connection and statement are cleaned up automatically or
        // you can explicitly call statement.close() and/or connection.disconnect().
    }
    catch(const exception& e)
    {
        cerr << "exception: " << e.what() << endl;
    }
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: htags.cpp,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:54:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

/* NAME
 * PURPOSE
 *
 * NOTES
 *
 * HISTORY
 *        frog - Aug 6, 1998: Created.
 */

#include "precompile.h"

#ifdef __GNUG__
#pragma implementation "htags.h"
#endif

#include <string.h>

#include "hwplib.h"
#include "hwpfile.h"
#include "htags.h"
#include "himgutil.h"

bool HyperText::Read(HWPFile & hwpf)
{
    hwpf.Read1b(filename, 256);
    hwpf.Read2b(bookmark, 16);
    hwpf.Read1b(macro, 325);
    hwpf.Read1b(&type, 1);
    hwpf.Read1b(reserve, 3);
    if( type == 2 )
    {
        for( int i = 1; i < 256; i++)
        {
            filename[i-1] = filename[i];
            if( filename[i] == 0 )
                break;
        }
    }
    return true;
}

EmPicture::EmPicture(int tsize):size(tsize - 32)
{
    if (size <= 0)
        data = 0;
    else
        data = new uchar[size];
}
#ifdef WIN32
#define unlink _unlink
#endif
EmPicture::~EmPicture(void)
{
// clear temporary image file
    char *fname = (char *) GetEmbImgname(this);

    if (fname && access(fname, 0) == 0)
        unlink(fname);
    if (data)
        delete[]data;
};

bool EmPicture::Read(HWPFile & hwpf)
{
    if (size <= 0)
        return false;
    hwpf.Read1b(name, 16);
    hwpf.Read1b(type, 16);
    name[0] = 'H';
    name[1] = 'W';
    name[2] = 'P';
    if (hwpf.ReadBlock(data, size) == 0)
        return false;
    return true;
}

OlePicture::OlePicture(int tsize)
{
    size = tsize - 4;
    if (size <= 0)
        return;
#ifdef WIN32
     pis = 0L;
#else
     pis = new char[size];
#endif
};

OlePicture::~OlePicture(void)
{
#ifdef WIN32
     if( pis )
          pis->Release();
#else
     delete[] pis;
#endif
};

#define FILESTG_SIGNATURE_NORMAL 0xF8995568

bool OlePicture::Read(HWPFile & hwpf)
{
    if (size <= 0)
        return false;

// We process only FILESTG_SIGNATURE_NORMAL.
    hwpf.Read4b(&signature, 1);
    if (signature != FILESTG_SIGNATURE_NORMAL)
        return false;
#ifdef WIN32
     char *data;
     data = new char[size];
     if( data == 0 || hwpf.ReadBlock(data,size) == 0 )
          return false;
     FILE *fp;
     char tname[200];
     wchar_t wtname[200];
     tmpnam(tname);
     if (0 == (fp = fopen(tname, "wb")))
          return false;
     fwrite(data, size, 1, fp);
     fclose(fp);
     MultiByteToWideChar(CP_ACP, 0, tname, -1, wtname, 200);
     if( StgOpenStorage(wtname, NULL,
                     STGM_READWRITE|STGM_SHARE_EXCLUSIVE|STGM_TRANSACTED,
                     NULL, 0, &pis) != S_OK ) {
          pis = 0;
          unlink(tname);
          return false;
     }
     unlink(tname);
     delete [] data;
#else
    if (pis == 0 || hwpf.ReadBlock(pis, size) == 0)
        return false;
#endif

    return true;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.42); FILE MERGED 2008/03/28 15:36:39 rt 1.3.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: htags.cpp,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

/* NAME
 * PURPOSE
 *
 * NOTES
 *
 * HISTORY
 *        frog - Aug 6, 1998: Created.
 */

#include "precompile.h"

#ifdef __GNUG__
#pragma implementation "htags.h"
#endif

#include <string.h>

#include "hwplib.h"
#include "hwpfile.h"
#include "htags.h"
#include "himgutil.h"

bool HyperText::Read(HWPFile & hwpf)
{
    hwpf.Read1b(filename, 256);
    hwpf.Read2b(bookmark, 16);
    hwpf.Read1b(macro, 325);
    hwpf.Read1b(&type, 1);
    hwpf.Read1b(reserve, 3);
    if( type == 2 )
    {
        for( int i = 1; i < 256; i++)
        {
            filename[i-1] = filename[i];
            if( filename[i] == 0 )
                break;
        }
    }
    return true;
}

EmPicture::EmPicture(int tsize):size(tsize - 32)
{
    if (size <= 0)
        data = 0;
    else
        data = new uchar[size];
}
#ifdef WIN32
#define unlink _unlink
#endif
EmPicture::~EmPicture(void)
{
// clear temporary image file
    char *fname = (char *) GetEmbImgname(this);

    if (fname && access(fname, 0) == 0)
        unlink(fname);
    if (data)
        delete[]data;
};

bool EmPicture::Read(HWPFile & hwpf)
{
    if (size <= 0)
        return false;
    hwpf.Read1b(name, 16);
    hwpf.Read1b(type, 16);
    name[0] = 'H';
    name[1] = 'W';
    name[2] = 'P';
    if (hwpf.ReadBlock(data, size) == 0)
        return false;
    return true;
}

OlePicture::OlePicture(int tsize)
{
    size = tsize - 4;
    if (size <= 0)
        return;
#ifdef WIN32
     pis = 0L;
#else
     pis = new char[size];
#endif
};

OlePicture::~OlePicture(void)
{
#ifdef WIN32
     if( pis )
          pis->Release();
#else
     delete[] pis;
#endif
};

#define FILESTG_SIGNATURE_NORMAL 0xF8995568

bool OlePicture::Read(HWPFile & hwpf)
{
    if (size <= 0)
        return false;

// We process only FILESTG_SIGNATURE_NORMAL.
    hwpf.Read4b(&signature, 1);
    if (signature != FILESTG_SIGNATURE_NORMAL)
        return false;
#ifdef WIN32
     char *data;
     data = new char[size];
     if( data == 0 || hwpf.ReadBlock(data,size) == 0 )
          return false;
     FILE *fp;
     char tname[200];
     wchar_t wtname[200];
     tmpnam(tname);
     if (0 == (fp = fopen(tname, "wb")))
          return false;
     fwrite(data, size, 1, fp);
     fclose(fp);
     MultiByteToWideChar(CP_ACP, 0, tname, -1, wtname, 200);
     if( StgOpenStorage(wtname, NULL,
                     STGM_READWRITE|STGM_SHARE_EXCLUSIVE|STGM_TRANSACTED,
                     NULL, 0, &pis) != S_OK ) {
          pis = 0;
          unlink(tname);
          return false;
     }
     unlink(tname);
     delete [] data;
#else
    if (pis == 0 || hwpf.ReadBlock(pis, size) == 0)
        return false;
#endif

    return true;
}
<|endoftext|>


<commit_before>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "UtilDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "vtlib/core/TerrainScene.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------

// WDR: event table for UtilDlg

BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
	EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()

UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	UtilDialogFunc( this, TRUE );

	m_pChoice = GetStructtype();
}

// WDR: handler implementations for UtilDlg

void UtilDlg::OnStructType( wxCommandEvent &event )
{
	TransferDataFromWindow();
	g_App.SetRouteOptions(m_pChoice->GetStringSelection().mb_str());
	g_App.start_new_fence();
}

void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddValidator(ID_STRUCTTYPE, &m_iType);

	m_iType = 0;

	vtContentManager &mng = vtGetContent();

	m_pChoice->Clear();
	for (unsigned int i = 0; i < mng.NumItems(); i++)
	{
		vtString str;
		vtItem *item = mng.GetItem(i);
		if (item->GetValueString("type", str))
		{
			if (str == "utility pole")
				m_pChoice->Append(wxString::FromAscii(item->m_name));
		}
	}

	TransferDataToWindow();

	g_App.SetRouteOptions(m_pChoice->GetStringSelection().mb_str());
}

<commit_msg>unicode fix<commit_after>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "UtilDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "vtlib/core/TerrainScene.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"

#include "vtui/wxString2.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------

// WDR: event table for UtilDlg

BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
	EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()

UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	UtilDialogFunc( this, TRUE );

	m_pChoice = GetStructtype();
}

// WDR: handler implementations for UtilDlg

void UtilDlg::OnStructType( wxCommandEvent &event )
{
	TransferDataFromWindow();
	wxString2 val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions(val.mb_str());
	g_App.start_new_fence();
}

void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddValidator(ID_STRUCTTYPE, &m_iType);

	m_iType = 0;

	vtContentManager &mng = vtGetContent();

	m_pChoice->Clear();
	for (unsigned int i = 0; i < mng.NumItems(); i++)
	{
		vtString str;
		vtItem *item = mng.GetItem(i);
		if (item->GetValueString("type", str))
		{
			if (str == "utility pole")
				m_pChoice->Append(wxString::FromAscii(item->m_name));
		}
	}

	TransferDataToWindow();

	wxString2 val = m_pChoice->GetStringSelection();
	g_App.SetRouteOptions(val.mb_str());
}

<|endoftext|>


<commit_before>/*
** File Name: utility.hpp
** Author:    Aditya Ramesh
** Date:      07/01/2014
** Contact:   _@adityaramesh.com
*/

#ifndef ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#define ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3

#include <ccbase/utility/accessors.hpp>
#include <ccbase/utility/bitmask_enum.hpp>
#include <ccbase/utility/bytes.hpp>

#endif
<commit_msg>Fixed wrong header name.<commit_after>/*
** File Name: utility.hpp
** Author:    Aditya Ramesh
** Date:      07/01/2014
** Contact:   _@adityaramesh.com
*/

#ifndef ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#define ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3

#include <ccbase/utility/accessors.hpp>
#include <ccbase/utility/enum_bitmask.hpp>
#include <ccbase/utility/bytes.hpp>

#endif
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief int type definition and macros
	@author MITSUNARI Shigeo(@herumi)
*/

#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
	#define CYBOZU_DEFINED_INTXX
	typedef __int64 int64_t;
	typedef unsigned __int64 uint64_t;
	typedef unsigned int uint32_t;
	typedef int int32_t;
	typedef unsigned short uint16_t;
	typedef short int16_t;
	typedef unsigned char uint8_t;
	typedef signed char int8_t;
#else
	#include <stdint.h>
#endif

#ifdef _MSC_VER
	#ifndef CYBOZU_DEFINED_SSIZE_T
		#define CYBOZU_DEFINED_SSIZE_T
		#ifdef _WIN64
			typedef int64_t ssize_t;
		#else
			typedef int32_t ssize_t;
		#endif
	#endif
#else
	#include <unistd.h> // for ssize_t
#endif

#ifndef CYBOZU_ALIGN
	#ifdef _MSC_VER
		#define CYBOZU_ALIGN(x) __declspec(align(x))
	#else
		#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
	#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
	#ifdef _MSC_VER
		#define CYBOZU_FORCE_INLINE __forceinline
	#else
		#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
	#endif
#endif
#ifndef CYBOZU_UNUSED
	#ifdef __GNUC__
		#define CYBOZU_UNUSED __attribute__((unused))
	#else
		#define CYBOZU_UNUSED
	#endif
#endif
#ifndef CYBOZU_ALLOCA
	#ifdef _MSC_VER
		#include <malloc.h>
		#define CYBOZU_ALLOCA(x) _malloca(x)
	#else
		#define CYBOZU_ALLOCA(x) __builtin_alloca(x)
	#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
	#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
	#if defined(_MSC_VER) && (_MSC_VER < 1900)
		#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
	#else
		#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
	#endif
#endif

// LLONG_MIN in limits.h is not defined in some env.
#define CYBOZU_LLONG_MIN (-9223372036854775807ll-1)

#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#define CYBOZU_CPP_VERSION_CPP14 3
#define CYBOZU_CPP_VERSION_CPP17 4

#ifdef __GNUC__
	#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
	#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif

#if (__cplusplus >= 201703)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP17
#elif (__cplusplus >= 201402)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP14
#elif (__cplusplus >= 201103) || (defined(_MSC_VER) && _MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
	#if defined(_MSC_VER) && (_MSC_VER <= 1600)
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
	#else
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
	#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && (defined(__GLIBCXX__) &&__GLIBCXX__ >= 20070719)) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif

#ifdef CYBOZU_USE_BOOST
	#define CYBOZU_NAMESPACE_STD boost
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
	#define CYBOZU_NAMESPACE_STD std::tr1
	#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
	#define CYBOZU_NAMESPACE_TR1_END }
#else
	#define CYBOZU_NAMESPACE_STD std
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#endif

#ifndef CYBOZU_OS_BIT
	#if defined(_WIN64) || defined(__x86_64__) || defined(__AARCH64EL__) || defined(__EMSCRIPTEN__)
		#define CYBOZU_OS_BIT 64
	#else
		#define CYBOZU_OS_BIT 32
	#endif
#endif

#ifndef CYBOZU_HOST
	#define CYBOZU_HOST_UNKNOWN 0
	#define CYBOZU_HOST_INTEL 1
	#define CYBOZU_HOST_ARM 2
	#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
		#define CYBOZU_HOST CYBOZU_HOST_INTEL
	#elif defined(__arm__) || defined(__AARCH64EL__)
		#define CYBOZU_HOST CYBOZU_HOST_ARM
	#else
		#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
	#endif
#endif

#ifndef CYBOZU_ENDIAN
	#define CYBOZU_ENDIAN_UNKNOWN 0
	#define CYBOZU_ENDIAN_LITTLE 1
	#define CYBOZU_ENDIAN_BIG 2
	#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && (defined(__ARM_EABI__) || defined(__AARCH64EL__))
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#else
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
	#endif
#endif

#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
	#define CYBOZU_NOEXCEPT noexcept
	#define CYBOZU_NULLPTR nullptr
#else
	#define CYBOZU_NOEXCEPT throw()
	#define CYBOZU_NULLPTR 0
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<commit_msg>check LP64 and s390x<commit_after>#pragma once
/**
	@file
	@brief int type definition and macros
	@author MITSUNARI Shigeo(@herumi)
*/

#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
	#define CYBOZU_DEFINED_INTXX
	typedef __int64 int64_t;
	typedef unsigned __int64 uint64_t;
	typedef unsigned int uint32_t;
	typedef int int32_t;
	typedef unsigned short uint16_t;
	typedef short int16_t;
	typedef unsigned char uint8_t;
	typedef signed char int8_t;
#else
	#include <stdint.h>
#endif

#ifdef _MSC_VER
	#ifndef CYBOZU_DEFINED_SSIZE_T
		#define CYBOZU_DEFINED_SSIZE_T
		#ifdef _WIN64
			typedef int64_t ssize_t;
		#else
			typedef int32_t ssize_t;
		#endif
	#endif
#else
	#include <unistd.h> // for ssize_t
#endif

#ifndef CYBOZU_ALIGN
	#ifdef _MSC_VER
		#define CYBOZU_ALIGN(x) __declspec(align(x))
	#else
		#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
	#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
	#ifdef _MSC_VER
		#define CYBOZU_FORCE_INLINE __forceinline
	#else
		#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
	#endif
#endif
#ifndef CYBOZU_UNUSED
	#ifdef __GNUC__
		#define CYBOZU_UNUSED __attribute__((unused))
	#else
		#define CYBOZU_UNUSED
	#endif
#endif
#ifndef CYBOZU_ALLOCA
	#ifdef _MSC_VER
		#include <malloc.h>
		#define CYBOZU_ALLOCA(x) _malloca(x)
	#else
		#define CYBOZU_ALLOCA(x) __builtin_alloca(x)
	#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
	#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
	#if defined(_MSC_VER) && (_MSC_VER < 1900)
		#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
	#else
		#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
	#endif
#endif

// LLONG_MIN in limits.h is not defined in some env.
#define CYBOZU_LLONG_MIN (-9223372036854775807ll-1)

#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#define CYBOZU_CPP_VERSION_CPP14 3
#define CYBOZU_CPP_VERSION_CPP17 4

#ifdef __GNUC__
	#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
	#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif

#if (__cplusplus >= 201703)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP17
#elif (__cplusplus >= 201402)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP14
#elif (__cplusplus >= 201103) || (defined(_MSC_VER) && _MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
	#if defined(_MSC_VER) && (_MSC_VER <= 1600)
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
	#else
		#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
	#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && (defined(__GLIBCXX__) &&__GLIBCXX__ >= 20070719)) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
	#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif

#ifdef CYBOZU_USE_BOOST
	#define CYBOZU_NAMESPACE_STD boost
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
	#define CYBOZU_NAMESPACE_STD std::tr1
	#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
	#define CYBOZU_NAMESPACE_TR1_END }
#else
	#define CYBOZU_NAMESPACE_STD std
	#define CYBOZU_NAMESPACE_TR1_BEGIN
	#define CYBOZU_NAMESPACE_TR1_END
#endif

#ifndef CYBOZU_OS_BIT
	#if defined(_WIN64) || defined(__x86_64__) || defined(__AARCH64EL__) || defined(__EMSCRIPTEN__) || defined(__LP64__)
		#define CYBOZU_OS_BIT 64
	#else
		#define CYBOZU_OS_BIT 32
	#endif
#endif

#ifndef CYBOZU_HOST
	#define CYBOZU_HOST_UNKNOWN 0
	#define CYBOZU_HOST_INTEL 1
	#define CYBOZU_HOST_ARM 2
	#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
		#define CYBOZU_HOST CYBOZU_HOST_INTEL
	#elif defined(__arm__) || defined(__AARCH64EL__)
		#define CYBOZU_HOST CYBOZU_HOST_ARM
	#else
		#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
	#endif
#endif

#ifndef CYBOZU_ENDIAN
	#define CYBOZU_ENDIAN_UNKNOWN 0
	#define CYBOZU_ENDIAN_LITTLE 1
	#define CYBOZU_ENDIAN_BIG 2
	#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && (defined(__ARM_EABI__) || defined(__AARCH64EL__))
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
	#elif defined(__s390x__)
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_BIG
	#else
		#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
	#endif
#endif

#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
	#define CYBOZU_NOEXCEPT noexcept
	#define CYBOZU_NULLPTR nullptr
#else
	#define CYBOZU_NOEXCEPT throw()
	#define CYBOZU_NULLPTR 0
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<|endoftext|>


<commit_before>#ifndef _litesql_sqlast_hpp_
#define _litesql_sqlast_hpp_
#include "litesql/sql.hpp"
namespace litesql {
    namespace sql {

        class Translator;

        /** Abstract syntax tree node */
        class AST {
        public:
            virtual ~AST() {}
            virtual std::string toString() const=0;
            virtual SQL* translate(Translator& t) = 0;
        };

        /** Raw SQL-injection */
        class Raw {
        public:
            virtual void accept(Visitor& v);
        };

        /** SQL SELECT statement */
        class Select : public Stmt {
        public:
            virtual void accept(Visitor& v);
        };

        /** SELECT result set field or expression */
        class Result : public AST {
        public:
            virtual void accept(Visitor& v);
        };

        /** FROM-expression in SELECT-clause */
        class Sources : public AST {
        public:
            virtual void accept(Visitor& v);
        };

        /** Single FROM-source in SELECT-clause */
        class FromSource : public AST {
        };

        /** FROM (table)-expression in SELECT-clause */
        class FromTable : public FromSource {
        };

        /** FROM (select)-expression in SELECT-clause */
        class FromSelect : public FromSource {
        };

        /** Base class for joins */
        class Join : public AST {
        };

        /** CROSS JOIN */
        class CrossJoin : public Join {
        };

        /** INNER JOIN _ ON _ */
        class InnerJoin : public Join {
        };

        /** LEFT OUTER JOIN _ ON _ */
        class LeftOuterJoin : public Join {
        };

        /** RIGHT OUTER JOIN _ ON _ */
        class RightOuterJoin : public Join {
        };

        /** FULL OUTER JOIN _ ON _ */
        class FullOuterJoin : public Join {
        };

        /** Base class for compound operations */
        class CompoundOp : public AST {
        };

        /** UNION SELECT _ */
        class Union : public CompoundOp {
        };

        /** INTERSECT SELECT _ */
        class Intersect : public CompoundOp {
        };

        /** EXCEPT SELECT _ */
        class Except : public CompoundOp {
        };

        /** ORDER BY-part of SELECT-statement */
        class OrderBy : public AST {

        };

        /** Base class for expressions */
        class Expr : public AST {
        };

        /** Base class for unary operator expressions */
        class UnOp : public Expr {

        };

        /** NOT (_) */
        class Not : public UnOp {
        };

        /** -(_) */
        class UnaryMinus : public UnOp {
        };

        /** Base class for binary operator expressions */
        class BinOp : public Expr {
        };

        /** _ = _ */
        class Eq : public BinOp {
        };

        /** _ <> _ */
        class Neq : public BinOp {
        };

        /** _ < _ */
        class Lt : public BinOp {
        };

        /** _ <= _ */
        class LtEq : public BinOp {
        };

        /** _ > _ */
        class Gt : public BinOp {
        };

        /** _ >= _ */
        class GtEq : public BinOp {
        };

        /** (_) OR (_) */
        class Or : public BinOp {
        };

        /** (_) AND (_) */
        class And : public BinOp {
        };

        /** _ LIKE _ */
        class Like : public BinOp {
        };

        /** _ REGEXP _ */
        class RegExp : public BinOp {
        };

        /** _ IS NULL */
        class IsNull : public BinOp {
        };

        /** _ IN (_) */
        class In : public BinOp {
        };

        /** _ || _ */
        class Concat : public BinOp {
        };

        /** _ % _ */
        class Mod : public BinOp {
        };

        /** _ / _ */
        class Div : public BinOp {
        };

        /** _ * _ */
        class Mul : public BinOp {
        };

        /** _ + _ */
        class Add : public BinOp {
        };

        /** _ - _ */
        class Sub : public BinOp {
        };

        /** Converts a list of values to a list expression */
        class List : public BinOp {
        };

        /** Converts a value (int, string, whatever) to an expression */
        class ValueExpr : public Expr {
        };

        /** Value of a field of the result set-expression */
        class FieldExpr : public Expr {
        };

        /** The sequence used in the INSERT-operation */
        class FromSequence : public AST {
        };

        /** Atomic multi-table insert that will assign rows with
            same new unique identifier to multiple tables */
        class Insert : public Stmt {
        };

        /** Insertion to one table */
        class ToTable : public AST {
        };

        /** Assignment to a field */
        class Assign : public AST {
        };

        /** UPDATE statement */
        class Update : public Stmt {
        };

        /** DELETE statement */
        class Delete : public Stmt {
        };

        /** CREATE TABLE statement */
        class CreateTable : public Stmt {
        };

        /** DROP TABLE statement */
        class DropTable : public Stmt {
        };

        /** Field definition to be used in CREATE table statement */
        class Field : public AST {
        };

        /** Base class for field constraints */
        class FieldConstraint : public AST {
        };

        /** NOT NULL constraint for a field */
        class FieldNotNull : public FieldConstraint {
        };

        /** PRIMARY KEY constraint for a field */
        class FieldPrimaryKey : public FieldConstraint {
        };

        /** UNIQUE constraint for a field */
        class FieldUnique : public FieldConstraint {
        };

        /** CHECK constraint for a field */
        class FieldCheck : public FieldConstraint {
        };

        /** DEFAULT value for a field */
        class FieldDefault : public FieldConstraint {
        };

        /** FOREIGN KEY reference for a field */
        class FieldReference : public FieldConstraint {
        };

        /** Base class for actions */
        class Action : public AST {
        };

        /** CASCADE action (when a referenced row is deleted) */
        class Cascade : public Action {
        };

        /** SET NULL action (when a referenced row is deleted) */
        class SetNull : public Action {
        };

        /** Base class for table specific constraints */
        class TableConstraint : public AST {
        };

        /** multiple field PRIMARY KEY constraint */
        class TablePrimaryKey : public TableConstraint {
        };

        /** CREATE INDEX statement */
        class CreateIndex : public Stmt {
        };

        /** DROP INDEX statement */
        class DropIndex : public Stmt {
        };

        /** AST translator base class */
        class Translator {
        public:
            virtual SQL* trnsRaw(Raw*);
            virtual SQL* trnsSelect(Select*);
            virtual SQL* trnsResult(Result*);
            virtual SQL* trnsSources(Sources*);
            virtual SQL* trnsFromSource(FromSource*);
            virtual SQL* trnsFromSelect(FromSelect*);
            virtual SQL* trnsCrossJoin(CrossJoin*);
            virtual SQL* trnsInnerJoin(InnerJoin*);
            virtual SQL* trnsLeftOuterJoin(LeftOuterJoin*);
            virtual SQL* trnsRightOuterJoin(RightOuterJoin*);
            virtual SQL* trnsFullOuterJoin(FullOuterJoin*);
            virtual SQL* trnsUnion(Union*);
            virtual SQL* trnsIntersect(Intersect*);
            virtual SQL* trnsExcept(Except*);
            virtual SQL* trnsOrderBy(OrderBy*);
            virtual SQL* trnsNot(Not*);
            virtual SQL* trnsUnaryMinus(UnaryMinus*);
            virtual SQL* trnsEq(Eq*);
            virtual SQL* trnsNeq(Neq*);
            virtual SQL* trnsLt(Lt*);
            virtual SQL* trnsLtEq(LtEq*);
            virtual SQL* trnsGt(Gt*);
            virtual SQL* trnsGtEq(GtEq*);
            virtual SQL* trnsOr(Or*);
            virtual SQL* trnsAnd(And*);
            virtual SQL* trnsLike(Like*);
            virtual SQL* trnsRegExp(RegExp*);
            virtual SQL* trnsIsNull(IsNull*);
            virtual SQL* trnsIn(In*);
            virtual SQL* trnsConcat(Concat*);
            virtual SQL* trnsMod(Mod*);
            virtual SQL* trnsDiv(Div*);
            virtual SQL* trnsMul(Mul*);
            virtual SQL* trnsAdd(Add*);
            virtual SQL* trnsSub(Sub*);
            virtual SQL* trnsList(List*);
            virtual SQL* trnsValueExpr(ValueExpr*);
            virtual SQL* trnsFieldExpr(FieldExpr*);
            virtual SQL* trnsFromSequence(FromSequence*);
            virtual SQL* trnsInsert(Insert*);
            virtual SQL* trnsToTable(ToTable*);
            virtual SQL* trnsAssign(Assign*);
            virtual SQL* trnsUpdate(Update*);
            virtual SQL* trnsDelete(Delete*);
            virtual SQL* trnsCreateTable(CreateTable*);
            virtual SQL* trnsDropTable(DropTable*);
            virtual SQL* trnsField(Field*);
            virtual SQL* trnsFieldConstraint(FieldConstraint*);
            virtual SQL* trnsFieldPrimaryKey(FieldPrimaryKey*);
            virtual SQL* trnsFieldUnique(FieldUnique*);
            virtual SQL* trnsFieldCheck(FieldCheck*);
            virtual SQL* trnsFieldDefault(FieldDefault*);
            virtual SQL* trnsFieldReference(FieldReference*);
            virtual SQL* trnsCascade(Cascade*);
            virtual SQL* trnsSetNull(SetNull*);
            virtual SQL* trnsTablePrimaryKey(TablePrimaryKey*);
            virtual SQL* trnsCreateIndex(CreateIndex*);
            virtual SQL* trnsDropIndex(DropIndex*);
        };

    }
}

#endif

<commit_msg>translate methods<commit_after>#ifndef _litesql_sqlast_hpp_
#define _litesql_sqlast_hpp_
#include "litesql/sql.hpp"
namespace litesql {
    namespace ast {

        class Raw;
        class Select;
        class Result;
        class Sources;
        class FromSource;
        class FromSelect;
        class CrossJoin;
        class InnerJoin;
        class LeftOuterJoin;
        class RightOuterJoin;
        class FullOuterJoin;
        class Union;
        class Intersect;
        class Except;
        class OrderBy;
        class Not;
        class UnaryMinus;
        class Eq;
        class Neq;
        class Lt;
        class LtEq;
        class Gt;
        class GtEq;
        class Or;
        class And;
        class Like;
        class RegExp;
        class IsNull;
        class In;
        class Concat;
        class Mod;
        class Div;
        class Mul;
        class Add;
        class Sub;
        class List;
        class ValueExpr;
        class FieldExpr;
        class FromSequence;
        class Insert;
        class ToTable;
        class Assign;
        class Update;
        class Delete;
        class CreateTable;
        class DropTable;
        class Field;
        class FieldConstraint;
        class FieldPrimaryKey;
        class FieldUnique;
        class FieldCheck;
        class FieldDefault;
        class FieldReference;
        class Cascade;
        class SetNull;
        class TablePrimaryKey;
        class CreateIndex;
        class DropIndex;

        /** AST translator base class */
        class Translator {
        public:
            virtual ~Translator() {}
            virtual sql::SQL* translateRaw(Raw*)=0;
            virtual sql::SQL* translateSelect(Select*)=0;
            virtual sql::SQL* translateResult(Result*)=0;
            virtual sql::SQL* translateSources(Sources*)=0;
            virtual sql::SQL* translateFromSource(FromSource*)=0;
            virtual sql::SQL* translateFromSelect(FromSelect*)=0;
            virtual sql::SQL* translateCrossJoin(CrossJoin*)=0;
            virtual sql::SQL* translateInnerJoin(InnerJoin*)=0;
            virtual sql::SQL* translateLeftOuterJoin(LeftOuterJoin*)=0;
            virtual sql::SQL* translateRightOuterJoin(RightOuterJoin*)=0;
            virtual sql::SQL* translateFullOuterJoin(FullOuterJoin*)=0;
            virtual sql::SQL* translateUnion(Union*)=0;
            virtual sql::SQL* translateIntersect(Intersect*)=0;
            virtual sql::SQL* translateExcept(Except*)=0;
            virtual sql::SQL* translateOrderBy(OrderBy*)=0;
            virtual sql::SQL* translateNot(Not*)=0;
            virtual sql::SQL* translateUnaryMinus(UnaryMinus*)=0;
            virtual sql::SQL* translateEq(Eq*)=0;
            virtual sql::SQL* translateNeq(Neq*)=0;
            virtual sql::SQL* translateLt(Lt*)=0;
            virtual sql::SQL* translateLtEq(LtEq*)=0;
            virtual sql::SQL* translateGt(Gt*)=0;
            virtual sql::SQL* translateGtEq(GtEq*)=0;
            virtual sql::SQL* translateOr(Or*)=0;
            virtual sql::SQL* translateAnd(And*)=0;
            virtual sql::SQL* translateLike(Like*)=0;
            virtual sql::SQL* translateRegExp(RegExp*)=0;
            virtual sql::SQL* translateIsNull(IsNull*)=0;
            virtual sql::SQL* translateIn(In*)=0;
            virtual sql::SQL* translateConcat(Concat*)=0;
            virtual sql::SQL* translateMod(Mod*)=0;
            virtual sql::SQL* translateDiv(Div*)=0;
            virtual sql::SQL* translateMul(Mul*)=0;
            virtual sql::SQL* translateAdd(Add*)=0;
            virtual sql::SQL* translateSub(Sub*)=0;
            virtual sql::SQL* translateList(List*)=0;
            virtual sql::SQL* translateValueExpr(ValueExpr*)=0;
            virtual sql::SQL* translateFieldExpr(FieldExpr*)=0;
            virtual sql::SQL* translateFromSequence(FromSequence*)=0;
            virtual sql::SQL* translateInsert(Insert*)=0;
            virtual sql::SQL* translateToTable(ToTable*)=0;
            virtual sql::SQL* translateAssign(Assign*)=0;
            virtual sql::SQL* translateUpdate(Update*)=0;
            virtual sql::SQL* translateDelete(Delete*)=0;
            virtual sql::SQL* translateCreateTable(CreateTable*)=0;
            virtual sql::SQL* translateDropTable(DropTable*)=0;
            virtual sql::SQL* translateField(Field*)=0;
            virtual sql::SQL* translateFieldConstraint(FieldConstraint*)=0;
            virtual sql::SQL* translateFieldPrimaryKey(FieldPrimaryKey*)=0;
            virtual sql::SQL* translateFieldUnique(FieldUnique*)=0;
            virtual sql::SQL* translateFieldCheck(FieldCheck*)=0;
            virtual sql::SQL* translateFieldDefault(FieldDefault*)=0;
            virtual sql::SQL* translateFieldReference(FieldReference*)=0;
            virtual sql::SQL* translateCascade(Cascade*)=0;
            virtual sql::SQL* translateSetNull(SetNull*)=0;
            virtual sql::SQL* translateTablePrimaryKey(TablePrimaryKey*)=0;
            virtual sql::SQL* translateCreateIndex(CreateIndex*)=0;
            virtual sql::SQL* translateDropIndex(DropIndex*)=0;
        };

        /** Abstract syntax tree node */
        class AST {
        public:
            virtual ~AST() {}
            virtual std::string toString() const=0;
            virtual sql::SQL* translate(Translator& t) = 0;
        };

        /** AST base template which generates
          a translate method */
        template <class Base, class T>
        class ASTBase : public Base {
        public:
            virtual sql::SQL* translate(Translator& translator) {
                return translator.translate(reinterpret_cast<T*>(this));
            }
        };

        /** Raw sql::SQL-injection */
        class Raw : public ASTBase<AST, Raw> {
        public:
        };

        /** sql::SQL SELECT statement */
        class Select : public ASTBase<Stmt, Raw> {
        public:
        };

        /** SELECT result set field or expression */
        class Result : public ASTBase<AST, Result> {
        public:
        };

        /** FROM-expression in SELECT-clause */
        class Sources : public ASTBase<AST, Sources> {
        public:
        };

        /** Single FROM-source in SELECT-clause */
        class FromSource : public AST {
        };

        /** FROM (table)-expression in SELECT-clause */
        class FromTable : public ASTBase<FromSource, FromTable> {
        };

        /** FROM (select)-expression in SELECT-clause */
        class FromSelect : public ASTBase<FromSource, FromSelect> {
        };

        /** Base class for joins */
        class Join : public AST {
        };

        /** CROSS JOIN */
        class CrossJoin : public ASTBase<Join, CrossJoin> {
        };

        /** INNER JOIN _ ON _ */
        class InnerJoin : public ASTBase<Join, InnerJoin> {
        };

        /** LEFT OUTER JOIN _ ON _ */
        class LeftOuterJoin : public ASTBase<Join, LeftOuterJoin> {
        };

        /** RIGHT OUTER JOIN _ ON _ */
        class RightOuterJoin : public ASTBase<Join, RightOuterJoin> {
        };

        /** FULL OUTER JOIN _ ON _ */
        class FullOuterJoin : public ASTBase<Join, FullOuterJoin> {
        };

        /** Base class for compound operations */
        class CompoundOp : public AST {
        };

        /** UNION SELECT _ */
        class Union : public ASTBase<CompoundOp, Union> {
        };

        /** INTERSECT SELECT _ */
        class Intersect : public ASTBase<CompoundOp, Intersect> {
        };

        /** EXCEPT SELECT _ */
        class Except : public ASTBase<CompoundOp, Except> {
        };

        /** ORDER BY-part of SELECT-statement */
        class OrderBy : public ASTBase<AST, OrderBy> {

        };

        /** Base class for expressions */
        class Expr : public AST {
        };

        /** Base class for unary operator expressions */
        class UnOp : public Expr {

        };

        /** NOT (_) */
        class Not : public ASTBase<UnOp, Not> {
        };

        /** -(_) */
        class UnaryMinus : public ASTBase<UnOp, UnaryMinus> {
        };

        /** Base class for binary operator expressions */
        class BinOp : public Expr {
        };

        /** _ = _ */
        class Eq : public ASTBase<BinOp, Eq> {
        };

        /** _ <> _ */
        class Neq : public ASTBase<BinOp, Neq> {
        };

        /** _ < _ */
        class Lt : public ASTBase<BinOp, Lt> {
        };

        /** _ <= _ */
        class LtEq : public ASTBase<BinOp, LtEq> {
        };

        /** _ > _ */
        class Gt : public ASTBase<BinOp, Gt> {
        };

        /** _ >= _ */
        class GtEq : public ASTBase<BinOp, GtEq> {
        };

        /** (_) OR (_) */
        class Or : public ASTBase<BinOp, Or> {
        };

        /** (_) AND (_) */
        class And : public ASTBase<BinOp, And> {
        };

        /** _ LIKE _ */
        class Like : public ASTBase<BinOp, Like> {
        };

        /** _ REGEXP _ */
        class RegExp : public ASTBase<BinOp, RegExp> {
        };

        /** _ IS NULL */
        class IsNull : public ASTBase<BinOp, IsNull> {
        };

        /** _ IN (_) */
        class In : public ASTBase<BinOp, In> {
        };

        /** _ || _ */
        class Concat : public ASTBase<BinOp, Concat> {
        };

        /** _ % _ */
        class Mod : public ASTBase<BinOp, Mod> {
        };

        /** _ / _ */
        class Div : public ASTBase<BinOp, Div> {
        };

        /** _ * _ */
        class Mul : public ASTBase<BinOp, Mul> {
        };

        /** _ + _ */
        class Add : public ASTBase<BinOp, Add> {
        };

        /** _ - _ */
        class Sub : public ASTBase<BinOp, Sub> {
        };

        /** Converts a list of values to a list expression */
        class List : public ASTBase<BinOp, List> {
        };

        /** Converts a value (int, string, whatever) to an expression */
        class ValueExpr : public ASTBase<BinOp, ValueExpr> {
        };

        /** Value of a field of the result set-expression */
        class FieldExpr : public ASTBase<BinOp, FieldExpr> {
        };

        /** The sequence used in the INSERT-operation */
        class FromSequence : public ASTBase<Ast, FromSequence> {
        };

        /** Atomic multi-table insert that will assign rows with
            same new unique identifier to multiple tables */
        class Insert : public ASTBase<Stmt, Insert> {
        };

        /** Insertion to one table */
        class ToTable : public ASTBase<AST, ToTable> {
        };

        /** Assignment to a field */
        class Assign : public ASTBase<AST, Assign> {
        };

        /** UPDATE statement */
        class Update : public ASTBase<Stmt, Update> {
        };

        /** DELETE statement */
        class Delete : public ASTBase<Stmt, Delete> {
        };

        /** CREATE TABLE statement */
        class CreateTable : public ASTBase<Stmt, CreateTable> {
        };

        /** DROP TABLE statement */
        class DropTable : public ASTBase<Stmt, DropTable> {
        };

        /** Field definition to be used in CREATE table statement */
        class Field : public ASTBase<AST, Field> {
        };

        /** Base class for field constraints */
        class FieldConstraint : public ASTBase<AST, FieldConstraint> {
        };

        /** NOT NULL constraint for a field */
        class FieldNotNull : public ASTBase<FieldConstraint, FieldNotNull> {
        };

        /** PRIMARY KEY constraint for a field */
        class FieldPrimaryKey : public ASTBase<FieldConstraint, FieldPrimaryKey> {
        };

        /** UNIQUE constraint for a field */
        class FieldUnique : public ASTBase<FieldConstraint, FieldUnique> {
        };

        /** CHECK constraint for a field */
        class FieldCheck : public ASTBase<FieldConstraint, FieldCheck> {
        };

        /** DEFAULT value for a field */
        class FieldDefault : public ASTBase<FieldConstraint, FieldDefault> {
        };

        /** FOREIGN KEY reference for a field */
        class FieldReference : public ASTBase<FieldConstraint, FieldReference> {
        };

        /** Base class for actions */
        class Action : public AST {
        };

        /** CASCADE action (when a referenced row is deleted) */
        class Cascade : public ASTBase<Action, Cascade> {
        };

        /** SET NULL action (when a referenced row is deleted) */
        class SetNull : public ASTBase<Action, SetNull> {
        };

        /** Base class for table specific constraints */
        class TableConstraint : public AST {
        };

        /** multiple field PRIMARY KEY constraint */
        class TablePrimaryKey : public ASTBase<TableConstraint,
                                               TablePrimaryKey> {
        };

        /** CREATE INDEX statement */
        class CreateIndex : public ASTBase<Stmt, CreateIndex> {
        };

        /** DROP INDEX statement */
        class DropIndex : public ASTBase<Stmt, DropIndex> {
        };

    }
}

#endif

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP

#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>

extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}

namespace mapnik {

static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    std::streamsize request_size = size;
    if (static_cast<tsize_t>(request_size) != size)
        return static_cast<tsize_t>(-1);
    out->write(reinterpret_cast<const char*>(buf), size);

    if( static_cast<std::streamsize>(pos) == -1 )
    {
        return size;
    }
    else
    {
        return static_cast<tsize_t>(out->tellp()-pos);
    }
}

static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);

    if( out->fail() )
        return static_cast<toff_t>(-1);

    if( static_cast<std::streamsize>(out->tellp()) == -1)
        return static_cast< toff_t >( 0 );

    switch(whence)
    {
    case SEEK_SET:
        out->seekp(off, std::ios_base::beg);
        break;
    case SEEK_CUR:
        out->seekp(off, std::ios_base::cur);
        break;
    case SEEK_END:
        out->seekp(off, std::ios_base::end);
        break;
    }
    // grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
    std::ios::pos_type pos = out->tellp();
    // second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size

    if( out->fail() || static_cast<std::streamoff>(off) != pos)
    {
        std::ios::iostate old_state;
        std::ios::pos_type  origin;
        old_state = out->rdstate();
        // reset the fail bit or else tellp() won't work below
        out->clear(out->rdstate() & ~std::ios::failbit);
        switch( whence )
        {
        case SEEK_SET:
        default:
            origin = 0L;
            break;
        case SEEK_CUR:
            origin = out->tellp();
            break;
        case SEEK_END:
            out->seekp(0, std::ios::end);
            origin = out->tellp();
            break;
        }
        // restore original stream state
        out->clear(old_state);

        // only do something if desired seek position is valid
        if( (static_cast<uint64_t>(origin) + off) > 0L)
        {
            uint64_t num_fill;
            // clear the fail bit
            out->clear(out->rdstate() & ~std::ios::failbit);
            // extend the stream to the expected size
            out->seekp(0, std::ios::end);
            num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
            for( uint64_t i = 0; i < num_fill; ++i)
                out->put('\0');

            // retry the seek
            out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
        }
    }
    return static_cast<toff_t>(out->tellp());
}

static inline int tiff_close_proc(thandle_t fd)
{
    std::ostream* out = (std::ostream*)fd;
    out->flush();
    return 0;
}

static inline toff_t tiff_size_proc(thandle_t fd)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    out->seekp(0, std::ios::end);
    std::ios::pos_type len = out->tellp();
    out->seekp(pos);
    return static_cast<toff_t>(len);
}

static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
    return 0;
}

static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}

static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
    return 0;
}

struct tiff_config
{
    tiff_config()
        : compression(COMPRESSION_ADOBE_DEFLATE),
        zlevel(4),
        scanline(false) {}

    int compression;
    int zlevel;
    bool scanline;
};

struct tag_setter : public mapnik::util::static_visitor<>
{
    tag_setter(TIFF * output, tiff_config & config)
        : output_(output),
          config_(config) {}

    template <typename T>
    void operator() (T const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - unknown image type provided");
    }

    inline void operator() (image_data_rgba8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
        uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
        TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray32f const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
        }
    }
    inline void operator() (image_data_gray16 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_null const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - Null image provided");
    }

    private:
        TIFF * output_;
        tiff_config config_;
};

void set_tiff_config(TIFF* output, tiff_config & config)
{
    // Set some constant tiff information that doesn't vary based on type of data
    // or image size
    TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    // Set the compression for the TIFF
    TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);

    if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
    {
        // Set the zip level for the compression
        // http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
        // Changes the time spent trying to compress
        TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
    }
}

template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
    const int width = image.width();
    const int height = image.height();

    TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
                                "wm",
                                (thandle_t)&file,
                                tiff_dummy_read_proc,
                                tiff_write_proc,
                                tiff_seek_proc,
                                tiff_close_proc,
                                tiff_size_proc,
                                tiff_dummy_map_proc,
                                tiff_dummy_unmap_proc);
    if (! output)
    {
        throw ImageWriterException("Could not write TIFF");
    }

    TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
    TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
    TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);

    set_tiff_config(output, config);

    // Set tags that vary based on the type of data being provided.
    tag_setter set(output, config);
    set(image);
    //util::apply_visitor(set, image);

    // If the image is greater then 8MB uncompressed, then lets use scanline rather then
    // tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
    // a multiple of 16, if they are not we will use scanline.
    if (image.getSize() > 8 * 32 * 1024 * 1024
            || width % 16 != 0
            || height % 16 != 0
            || config.scanline)
    {
        // Process Scanline
        TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);

        int next_scanline = 0;
        while (next_scanline < height)
        {
            TIFFWriteScanline(output, const_cast<typename T2::pixel_type*>(image.getRow(next_scanline)), next_scanline, 0);
            ++next_scanline;
        }
    }
    else
    {
        TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
        TIFFSetField(output, TIFFTAG_TILELENGTH, height);
        TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
        // Process as tiles
        TIFFWriteTile(output, const_cast<typename T2::pixel_type*>(image.getData()), 0, 0, 0, 0);
    }
    // TODO - handle palette images
    // std::vector<mapnik::rgb> const& palette

    //  unsigned short r[256], g[256], b[256];
    //  for (int i = 0; i < (1 << 24); ++i)
    //  {
    //  r[i] = (unsigned short)palette[i * 3 + 0] << 8;
    //  g[i] = (unsigned short)palette[i * 3 + 1] << 8;
    //  b[i] = (unsigned short)palette[i * 3 + 2] << 8;
    //  }
    //  TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    //  TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);

    RealTIFFClose(output);
}

}

#endif // MAPNIK_TIFF_IO_HPP
<commit_msg>Revert "avoid allocating memory"<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP

#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>

extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}

namespace mapnik {

static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    std::streamsize request_size = size;
    if (static_cast<tsize_t>(request_size) != size)
        return static_cast<tsize_t>(-1);
    out->write(reinterpret_cast<const char*>(buf), size);

    if( static_cast<std::streamsize>(pos) == -1 )
    {
        return size;
    }
    else
    {
        return static_cast<tsize_t>(out->tellp()-pos);
    }
}

static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);

    if( out->fail() )
        return static_cast<toff_t>(-1);

    if( static_cast<std::streamsize>(out->tellp()) == -1)
        return static_cast< toff_t >( 0 );

    switch(whence)
    {
    case SEEK_SET:
        out->seekp(off, std::ios_base::beg);
        break;
    case SEEK_CUR:
        out->seekp(off, std::ios_base::cur);
        break;
    case SEEK_END:
        out->seekp(off, std::ios_base::end);
        break;
    }
    // grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
    std::ios::pos_type pos = out->tellp();
    // second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size

    if( out->fail() || static_cast<std::streamoff>(off) != pos)
    {
        std::ios::iostate old_state;
        std::ios::pos_type  origin;
        old_state = out->rdstate();
        // reset the fail bit or else tellp() won't work below
        out->clear(out->rdstate() & ~std::ios::failbit);
        switch( whence )
        {
        case SEEK_SET:
        default:
            origin = 0L;
            break;
        case SEEK_CUR:
            origin = out->tellp();
            break;
        case SEEK_END:
            out->seekp(0, std::ios::end);
            origin = out->tellp();
            break;
        }
        // restore original stream state
        out->clear(old_state);

        // only do something if desired seek position is valid
        if( (static_cast<uint64_t>(origin) + off) > 0L)
        {
            uint64_t num_fill;
            // clear the fail bit
            out->clear(out->rdstate() & ~std::ios::failbit);
            // extend the stream to the expected size
            out->seekp(0, std::ios::end);
            num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
            for( uint64_t i = 0; i < num_fill; ++i)
                out->put('\0');

            // retry the seek
            out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
        }
    }
    return static_cast<toff_t>(out->tellp());
}

static inline int tiff_close_proc(thandle_t fd)
{
    std::ostream* out = (std::ostream*)fd;
    out->flush();
    return 0;
}

static inline toff_t tiff_size_proc(thandle_t fd)
{
    std::ostream* out = reinterpret_cast<std::ostream*>(fd);
    std::ios::pos_type pos = out->tellp();
    out->seekp(0, std::ios::end);
    std::ios::pos_type len = out->tellp();
    out->seekp(pos);
    return static_cast<toff_t>(len);
}

static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
    return 0;
}

static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}

static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
    return 0;
}

struct tiff_config
{
    tiff_config()
        : compression(COMPRESSION_ADOBE_DEFLATE),
        zlevel(4),
        scanline(false) {}

    int compression;
    int zlevel;
    bool scanline;
};

struct tag_setter : public mapnik::util::static_visitor<>
{
    tag_setter(TIFF * output, tiff_config & config)
        : output_(output),
          config_(config) {}

    template <typename T>
    void operator() (T const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - unknown image type provided");
    }

    inline void operator() (image_data_rgba8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
        uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
        TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray32f const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
        }
    }
    inline void operator() (image_data_gray16 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_gray8 const&) const
    {
        TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
        TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
        TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
        TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
        if (config_.compression == COMPRESSION_DEFLATE
                || config_.compression == COMPRESSION_ADOBE_DEFLATE
                || config_.compression == COMPRESSION_LZW)
        {
            TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);

        }
    }
    inline void operator() (image_data_null const&) const
    {
        // Assume this would be null type
        throw ImageWriterException("Could not write TIFF - Null image provided");
    }

    private:
        TIFF * output_;
        tiff_config config_;
};

void set_tiff_config(TIFF* output, tiff_config & config)
{
    // Set some constant tiff information that doesn't vary based on type of data
    // or image size
    TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    // Set the compression for the TIFF
    TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);

    if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
    {
        // Set the zip level for the compression
        // http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
        // Changes the time spent trying to compress
        TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
    }
}

template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
    const int width = image.width();
    const int height = image.height();

    TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
                                "wm",
                                (thandle_t)&file,
                                tiff_dummy_read_proc,
                                tiff_write_proc,
                                tiff_seek_proc,
                                tiff_close_proc,
                                tiff_size_proc,
                                tiff_dummy_map_proc,
                                tiff_dummy_unmap_proc);
    if (! output)
    {
        throw ImageWriterException("Could not write TIFF");
    }

    TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
    TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
    TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);

    set_tiff_config(output, config);

    // Set tags that vary based on the type of data being provided.
    tag_setter set(output, config);
    set(image);
    //util::apply_visitor(set, image);

    // If the image is greater then 8MB uncompressed, then lets use scanline rather then
    // tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
    // a multiple of 16, if they are not we will use scanline.
    if (image.getSize() > 8 * 32 * 1024 * 1024
            || width % 16 != 0
            || height % 16 != 0
            || config.scanline)
    {
        // Process Scanline
        TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);

        int next_scanline = 0;
        typename T2::pixel_type * row = reinterpret_cast<typename T2::pixel_type*>(::operator new(image.getRowSize()));

        while (next_scanline < height)
        {
            memcpy(row, image.getRow(next_scanline), image.getRowSize());
            //typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
            TIFFWriteScanline(output, row, next_scanline, 0);
            ++next_scanline;
        }
        ::operator delete(row);
    }
    else
    {
        TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
        TIFFSetField(output, TIFFTAG_TILELENGTH, height);
        TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
        // Process as tiles
        typename T2::pixel_type * image_data = reinterpret_cast<typename T2::pixel_type*>(::operator new(image.getSize()));
        memcpy(image_data, image.getData(), image.getSize());
        //typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
        TIFFWriteTile(output, image_data, 0, 0, 0, 0);
        ::operator delete(image_data);
    }
    // TODO - handle palette images
    // std::vector<mapnik::rgb> const& palette

    //  unsigned short r[256], g[256], b[256];
    //  for (int i = 0; i < (1 << 24); ++i)
    //  {
    //  r[i] = (unsigned short)palette[i * 3 + 0] << 8;
    //  g[i] = (unsigned short)palette[i * 3 + 1] << 8;
    //  b[i] = (unsigned short)palette[i * 3 + 2] << 8;
    //  }
    //  TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    //  TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);

    RealTIFFClose(output);
}

}

#endif // MAPNIK_TIFF_IO_HPP
<|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>

#include <circular_iterator.hpp>

namespace helene
{
template <class T,
          std::size_t Size,
          template <class, class, std::size_t> class StoragePolicy>
class sliding_window
    : public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
    typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
        storage_policy;

public:
    static const std::size_t size = Size;

    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef circular_iterator<T*> iterator;
    typedef circular_iterator<const T*> const_iterator;

public:
    sliding_window()
        : storage_policy(),
          head_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::begin()),
          tail_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::end())
    {
    }

    template <class Iterator>
    sliding_window(Iterator first, Iterator last) : sliding_window()
    {
        for(; first != last; ++first, ++head_, ++tail_)
        {
            *head_ = *first;
        }
    }

    void
    push_back(const T& value)
    {
        *tail_ = value;
        ++tail_;
        ++head_;
    }

    void
    push_back(const T& value, size_type n)
    {
        std::fill_n(tail_, n, value);
        tail_ += n;
        head_ += n;
    }

    void
    push_front(const T& value)
    {
        --head_;
        *head_ = value;
        --tail_;
    }

    reference
    front()
    {
        return *head_;
    }

    const_reference
    front() const
    {
        return *head_;
    }

    reference
    back()
    {
        return *(tail_ - 1);
    }

    const_reference
    back() const
    {
        return *(tail_ - 1);
    }

    reference operator[](size_type n)
    {
        return head_[n];
    }

    const_reference operator[](size_type n) const
    {
        return head_[n];
    }

    iterator
    begin()
    {
        return head_;
    }

    iterator
    end()
    {
        return tail_;
    }

private:
    iterator head_;
    iterator tail_;
};

template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
    stack_storage() : buffer_{}
    {
    }

    T*
    begin()
    {
        return buffer_;
    }

    T*
    end()
    {
        return buffer_ + Size;
    }

protected:
    T buffer_[Size];
};

template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
    static_heap_storage() : buffer_(new T[Size]{})
    {
    }

    T*
    begin()
    {
        return buffer_.get();
    }

    T*
    end()
    {
        return buffer_.get() + Size;
    }

protected:
    std::unique_ptr<T[]> buffer_;
};

template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;

template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;

namespace detail
{
struct runtime_ratio
{
    runtime_ratio() : num(1), den(1)
    {
    }

    template <std::intmax_t Num, std::intmax_t Denom>
    constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
    {
    }

    std::intmax_t num;
    std::intmax_t den;
};

template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
    return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}

template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
    return rhs * lhs;
}

template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
    return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail

template <class KeyType,
          class ValueType,
          std::size_t Size,
          class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
    sliding_window_map() = default;
    template <std::intmax_t Num, std::intmax_t Denom>
    sliding_window_map(std::ratio<Num, Denom>)
        : sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
    {
    }

    std::pair<KeyType, KeyType>
    extent() const
    {
        return std::make_pair(origin_, origin_ + Size * precision_);
    }

    ////////////////////////////////////////////////////////////////////////////
    // map like interface
    ValueType&
    at(KeyType k)
    {
        const auto index = index_of_key(k);
        const Compare c;
        if(c(index, 0) || (!c(index, Size)))
        {
            throw std::out_of_range("Key outside of current window");
        }

        return sliding_buffer_[index];
    }

private:
    std::size_t
    index_of_key(KeyType k)
    {
        return (k - origin_) / precision_;
    }

private:
    static_heap_sliding_window<ValueType, Size> sliding_buffer_;
    KeyType origin_;
    detail::runtime_ratio precision_;
};
} // namespace helene
<commit_msg>Add constructor to sliding_window taking initializer_list. 	modified:   include/sliding_window.hpp<commit_after>#pragma once

#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>

#include <circular_iterator.hpp>

namespace helene
{
template <class T,
          std::size_t Size,
          template <class, class, std::size_t> class StoragePolicy>
class sliding_window
    : public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
    typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
        storage_policy;

public:
    static const std::size_t size = Size;

    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef circular_iterator<T*> iterator;
    typedef circular_iterator<const T*> const_iterator;

public:
    sliding_window()
        : storage_policy(),
          head_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::begin()),
          tail_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::end())
    {
    }

    template <class Iterator>
    sliding_window(Iterator first, Iterator last) : sliding_window()
    {
        for(; first != last; ++first, ++head_, ++tail_)
        {
            *head_ = *first;
        }
    }

    sliding_window(std::initializer_list<T> il)
        : sliding_window(il.begin(), il.end())
    {
    }

    void
    push_back(const T& value)
    {
        *tail_ = value;
        ++tail_;
        ++head_;
    }

    void
    push_back(const T& value, size_type n)
    {
        std::fill_n(tail_, n, value);
        tail_ += n;
        head_ += n;
    }

    void
    push_front(const T& value)
    {
        --head_;
        *head_ = value;
        --tail_;
    }

    reference
    front()
    {
        return *head_;
    }

    const_reference
    front() const
    {
        return *head_;
    }

    reference
    back()
    {
        return *(tail_ - 1);
    }

    const_reference
    back() const
    {
        return *(tail_ - 1);
    }

    reference operator[](size_type n)
    {
        return head_[n];
    }

    const_reference operator[](size_type n) const
    {
        return head_[n];
    }

    iterator
    begin()
    {
        return head_;
    }

    iterator
    end()
    {
        return tail_;
    }

private:
    iterator head_;
    iterator tail_;
};

template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
    stack_storage() : buffer_{}
    {
    }

    T*
    begin()
    {
        return buffer_;
    }

    T*
    end()
    {
        return buffer_ + Size;
    }

protected:
    T buffer_[Size];
};

template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
    static_heap_storage() : buffer_(new T[Size]{})
    {
    }

    T*
    begin()
    {
        return buffer_.get();
    }

    T*
    end()
    {
        return buffer_.get() + Size;
    }

protected:
    std::unique_ptr<T[]> buffer_;
};

template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;

template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;

namespace detail
{
struct runtime_ratio
{
    runtime_ratio() : num(1), den(1)
    {
    }

    template <std::intmax_t Num, std::intmax_t Denom>
    constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
    {
    }

    std::intmax_t num;
    std::intmax_t den;
};

template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
    return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}

template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
    return rhs * lhs;
}

template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
    return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail

template <class KeyType,
          class ValueType,
          std::size_t Size,
          class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
    sliding_window_map() = default;
    template <std::intmax_t Num, std::intmax_t Denom>
    sliding_window_map(std::ratio<Num, Denom>)
        : sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
    {
    }

    std::pair<KeyType, KeyType>
    extent() const
    {
        return std::make_pair(origin_, origin_ + Size * precision_);
    }

    ////////////////////////////////////////////////////////////////////////////
    // map like interface
    ValueType&
    at(KeyType k)
    {
        const auto index = index_of_key(k);
        const Compare c;
        if(c(index, 0) || (!c(index, Size)))
        {
            throw std::out_of_range("Key outside of current window");
        }

        return sliding_buffer_[index];
    }

private:
    std::size_t
    index_of_key(KeyType k)
    {
        return (k - origin_) / precision_;
    }

private:
    static_heap_sliding_window<ValueType, Size> sliding_buffer_;
    KeyType origin_;
    detail::runtime_ratio precision_;
};
} // namespace helene
<|endoftext|>


<commit_before>/*!
    \file thread.inl
    \brief Thread abstraction inline implementation
    \author Ivan Shynkarenka
    \date 27.01.2016
    \copyright MIT License
*/

namespace CppCommon {

template <class Fn, class... Args>
inline std::thread Thread::Start(Fn&& fn, Args&&... args)
{
    return std::thread([=]()
    {
        // Setup exception handler for the new thread
        ExceptionsHandler::SetupThread();

        // Call the base thread function
        fn(args...);
    });
}

} // namespace CppCommon
<commit_msg>Bugfix<commit_after>/*!
    \file thread.inl
    \brief Thread abstraction inline implementation
    \author Ivan Shynkarenka
    \date 27.01.2016
    \copyright MIT License
*/

namespace CppCommon {

template <class Fn, class... Args>
inline std::thread Thread::Start(Fn&& fn, Args&&... args)
{
    return std::thread([fn = fn, args...]()
    {
        // Setup exception handler for the new thread
        ExceptionsHandler::SetupThread();

        // Call the base thread function
        fn(std::move(args)...);
    });
}

} // namespace CppCommon
<|endoftext|>