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

  Program:   Visualization Toolkit
  Module:    vtkXMLParser.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkXMLParser.h"
#include "vtkObjectFactory.h"

#include "expat.h"
#include <ctype.h>
#include <sys/stat.h>

vtkCxxRevisionMacro(vtkXMLParser, "1.13");
vtkStandardNewMacro(vtkXMLParser);

//----------------------------------------------------------------------------
vtkXMLParser::vtkXMLParser()
{
  this->Stream            = 0;
  this->Parser            = 0;
  this->FileName          = 0;
  this->InputString       = 0;
  this->InputStringLength = 0;
}

//----------------------------------------------------------------------------
vtkXMLParser::~vtkXMLParser()
{
  this->SetStream(0);
  this->SetFileName(0);
}

//----------------------------------------------------------------------------
void vtkXMLParser::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  if(this->Stream)
    {
    os << indent << "Stream: " << this->Stream << "\n";
    }
  else
    {
    os << indent << "Stream: (none)\n";
    }
  os << indent << "FileName: " << (this->FileName? this->FileName : "(none)")
     << "\n";
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse(const char* inputString)
{
  this->InputString = inputString;
  this->InputStringLength = -1;
  int result = this->vtkXMLParser::Parse();
  this->InputString = 0;
  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse(const char* inputString, unsigned int length)
{
  this->InputString = inputString;
  this->InputStringLength = length;
  int result = this->vtkXMLParser::Parse();
  this->InputString = 0;
  this->InputStringLength = -1;
  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse()
{
  // Select source of XML
  ifstream ifs;
  if ( !this->InputString && !this->Stream && this->FileName )
    {
    // If it is file, open it and set the appropriate stream
    struct stat fs;
    if (stat(this->FileName, &fs) != 0)
      {
      vtkErrorMacro("Cannot open XML file: " << this->FileName);
      return 0;
      }
#ifdef _WIN32
    ifs.open(this->FileName, ios::binary | ios::in);
#else
    ifs.open(this->FileName, ios::in);
#endif
    if ( !ifs )
      {
      vtkErrorMacro("Cannot open XML file: " << this->FileName);
      return 0;
      }
    this->Stream = &ifs;
    }

  // Create the expat XML parser.
  this->Parser = XML_ParserCreate(0);
  XML_SetElementHandler(this->Parser,
                        &vtkXMLParserStartElement,
                        &vtkXMLParserEndElement);
  XML_SetCharacterDataHandler(this->Parser,
                              &vtkXMLParserCharacterDataHandler);
  XML_SetUserData(this->Parser, this);

  // Parse the input.
  int result = this->ParseXML();

  if(result)
    {
    // Tell the expat XML parser about the end-of-input.
    if(!XML_Parse(this->Parser, "", 0, 1))
      {
      this->ReportXmlParseError();
      result = 0;
      }
    }

  // Clean up the parser.
  XML_ParserFree(this->Parser);
  this->Parser = 0;

  // If the source was a file, reset the stream
  if ( this->Stream == &ifs )
    {
    this->Stream = 0;
    }

  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::InitializeParser()
{
  // Create the expat XML parser.
  this->Parser = XML_ParserCreate(0);
  XML_SetElementHandler(this->Parser,
                        &vtkXMLParserStartElement,
                        &vtkXMLParserEndElement);
  XML_SetCharacterDataHandler(this->Parser,
                              &vtkXMLParserCharacterDataHandler);
  XML_SetUserData(this->Parser, this);
  this->ParseError = 0;
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseChunk(const char* inputString, unsigned int length)
{
  int res;
  res = this->ParseBuffer(inputString, length);
  if ( res == 0 )
    {
    this->ParseError = 1;
    }
  return res;
}

//----------------------------------------------------------------------------
int vtkXMLParser::CleanupParser()
{
  int result = !this->ParseError;
  if(result)
    {
    // Tell the expat XML parser about the end-of-input.
    if(!XML_Parse(this->Parser, "", 0, 1))
      {
      this->ReportXmlParseError();
      result = 0;
      }
    }

  // Clean up the parser.
  XML_ParserFree(this->Parser);
  this->Parser = 0;

  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseXML()
{
  // Parsing of message
  if ( this->InputString )
    {
    if ( this->InputStringLength >= 0 )
      {
      return this->ParseBuffer(this->InputString, this->InputStringLength);
      }
    else
      {
      return this->ParseBuffer(this->InputString);
      }
    }

  // Make sure we have input.
  if(!this->Stream)
    {
    vtkErrorMacro("Parse() called with no Stream set.");
    return 0;
    }

  // Default stream parser just reads a block at a time.
  istream& in = *(this->Stream);
  const int bufferSize = 4096;
  char buffer[bufferSize];

  // Read in the stream and send its contents to the XML parser.  This
  // read loop is very sensitive on certain platforms with slightly
  // broken stream libraries (like HPUX).  Normally, it is incorrect
  // to not check the error condition on the fin.read() before using
  // the data, but the fin.gcount() will be zero if an error occurred.
  // Therefore, the loop should be safe everywhere.
  while(!this->ParsingComplete() && in)
    {
    in.read(buffer, bufferSize);
    if(in.gcount())
      {
      if(!this->ParseBuffer(buffer, in.gcount()))
        {
        return 0;
        }
      }
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParsingComplete()
{
  // Default behavior is to parse to end of stream.
  return 0;
}

//----------------------------------------------------------------------------
void vtkXMLParser::StartElement(const char *name,
                                const char ** vtkNotUsed(atts))
{
  this->ReportUnknownElement(name);
}

//----------------------------------------------------------------------------
void vtkXMLParser::EndElement(const char * vtkNotUsed(name))
{
}

//----------------------------------------------------------------------------
void vtkXMLParser::CharacterDataHandler(const char* vtkNotUsed(inData),
                                        int vtkNotUsed(inLength))
{
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportStrayAttribute(const char* element, const char* attr,
                                        const char* value)
{
  vtkWarningMacro("Stray attribute in XML stream: Element " << element
                  << " has " << attr << "=\"" << value << "\"");
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportMissingAttribute(const char* element,
                                          const char* attr)
{
  vtkErrorMacro("Missing attribute in XML stream: Element " << element
                << " is missing " << attr);
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportBadAttribute(const char* element, const char* attr,
                                      const char* value)
{
  vtkErrorMacro("Bad attribute value in XML stream: Element " << element
                << " has " << attr << "=\"" << value << "\"");
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportUnknownElement(const char* element)
{
  vtkErrorMacro("Unknown element in XML stream: " << element);
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportXmlParseError()
{
  vtkErrorMacro("Error parsing XML in stream at line "
                << XML_GetCurrentLineNumber(this->Parser)
                << ": " << XML_ErrorString(XML_GetErrorCode(this->Parser)));
}

//----------------------------------------------------------------------------
unsigned long vtkXMLParser::GetXMLByteIndex()
{
  return XML_GetCurrentByteIndex(this->Parser);
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseBuffer(const char* buffer, unsigned int count)
{
  // Pass the buffer to the expat XML parser.
  if(!XML_Parse(this->Parser, buffer, count, 0))
    {
    this->ReportXmlParseError();
    return 0;
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseBuffer(const char* buffer)
{
  return this->ParseBuffer(buffer, static_cast<int>(strlen(buffer)));
}

//----------------------------------------------------------------------------
int vtkXMLParser::IsSpace(char c)
{
  return isspace(c);
}

//----------------------------------------------------------------------------
void vtkXMLParserStartElement(void* parser, const char *name,
                              const char **atts)
{
  // Begin element handler that is registered with the XML_Parser.
  // This just casts the user data to a vtkXMLParser and calls
  // StartElement.
  static_cast<vtkXMLParser*>(parser)->StartElement(name, atts);
}

//----------------------------------------------------------------------------
void vtkXMLParserEndElement(void* parser, const char *name)
{
  // End element handler that is registered with the XML_Parser.  This
  // just casts the user data to a vtkXMLParser and calls EndElement.
  static_cast<vtkXMLParser*>(parser)->EndElement(name);
}

//----------------------------------------------------------------------------
void vtkXMLParserCharacterDataHandler(void* parser, const char* data,
                                      int length)
{
  // Character data handler that is registered with the XML_Parser.
  // This just casts the user data to a vtkXMLParser and calls
  // CharacterDataHandler.
  static_cast<vtkXMLParser*>(parser)->CharacterDataHandler(data, length);
}
<commit_msg>Add more error checking<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLParser.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkXMLParser.h"
#include "vtkObjectFactory.h"

#include "expat.h"
#include <ctype.h>
#include <sys/stat.h>

vtkCxxRevisionMacro(vtkXMLParser, "1.14");
vtkStandardNewMacro(vtkXMLParser);

//----------------------------------------------------------------------------
vtkXMLParser::vtkXMLParser()
{
  this->Stream            = 0;
  this->Parser            = 0;
  this->FileName          = 0;
  this->InputString       = 0;
  this->InputStringLength = 0;
  this->ParseError        = 0;
}

//----------------------------------------------------------------------------
vtkXMLParser::~vtkXMLParser()
{
  this->SetStream(0);
  this->SetFileName(0);
}

//----------------------------------------------------------------------------
void vtkXMLParser::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  if(this->Stream)
    {
    os << indent << "Stream: " << this->Stream << "\n";
    }
  else
    {
    os << indent << "Stream: (none)\n";
    }
  os << indent << "FileName: " << (this->FileName? this->FileName : "(none)")
     << "\n";
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse(const char* inputString)
{
  this->InputString = inputString;
  this->InputStringLength = -1;
  int result = this->vtkXMLParser::Parse();
  this->InputString = 0;
  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse(const char* inputString, unsigned int length)
{
  this->InputString = inputString;
  this->InputStringLength = length;
  int result = this->vtkXMLParser::Parse();
  this->InputString = 0;
  this->InputStringLength = -1;
  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::Parse()
{
  // Select source of XML
  ifstream ifs;
  if ( !this->InputString && !this->Stream && this->FileName )
    {
    // If it is file, open it and set the appropriate stream
    struct stat fs;
    if (stat(this->FileName, &fs) != 0)
      {
      vtkErrorMacro("Cannot open XML file: " << this->FileName);
      return 0;
      }
#ifdef _WIN32
    ifs.open(this->FileName, ios::binary | ios::in);
#else
    ifs.open(this->FileName, ios::in);
#endif
    if ( !ifs )
      {
      vtkErrorMacro("Cannot open XML file: " << this->FileName);
      return 0;
      }
    this->Stream = &ifs;
    }

  // Create the expat XML parser.
  this->Parser = XML_ParserCreate(0);
  XML_SetElementHandler(this->Parser,
                        &vtkXMLParserStartElement,
                        &vtkXMLParserEndElement);
  XML_SetCharacterDataHandler(this->Parser,
                              &vtkXMLParserCharacterDataHandler);
  XML_SetUserData(this->Parser, this);

  // Parse the input.
  int result = this->ParseXML();

  if(result)
    {
    // Tell the expat XML parser about the end-of-input.
    if(!XML_Parse(this->Parser, "", 0, 1))
      {
      this->ReportXmlParseError();
      result = 0;
      }
    }

  // Clean up the parser.
  XML_ParserFree(this->Parser);
  this->Parser = 0;

  // If the source was a file, reset the stream
  if ( this->Stream == &ifs )
    {
    this->Stream = 0;
    }

  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::InitializeParser()
{
  if ( this->Parser )
    {
    vtkErrorMacro("Parser already initialized");
    this->ParseError = 1;
    return 0;
    }
  // Create the expat XML parser.
  this->Parser = XML_ParserCreate(0);
  XML_SetElementHandler(this->Parser,
                        &vtkXMLParserStartElement,
                        &vtkXMLParserEndElement);
  XML_SetCharacterDataHandler(this->Parser,
                              &vtkXMLParserCharacterDataHandler);
  XML_SetUserData(this->Parser, this);
  this->ParseError = 0;
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseChunk(const char* inputString, unsigned int length)
{
  if ( !this->Parser )
    {
    vtkErrorMacro("Parser not initialized");
    this->ParseError = 1;
    return 0;
    }
  int res;
  res = this->ParseBuffer(inputString, length);
  if ( res == 0 )
    {
    this->ParseError = 1;
    }
  return res;
}

//----------------------------------------------------------------------------
int vtkXMLParser::CleanupParser()
{
  if ( !this->Parser )
    {
    vtkErrorMacro("Parser not initialized");
    this->ParseError = 1;
    return 0;
    }
  int result = !this->ParseError;
  if(result)
    {
    // Tell the expat XML parser about the end-of-input.
    if(!XML_Parse(this->Parser, "", 0, 1))
      {
      this->ReportXmlParseError();
      result = 0;
      }
    }

  // Clean up the parser.
  XML_ParserFree(this->Parser);
  this->Parser = 0;

  return result;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseXML()
{
  // Parsing of message
  if ( this->InputString )
    {
    if ( this->InputStringLength >= 0 )
      {
      return this->ParseBuffer(this->InputString, this->InputStringLength);
      }
    else
      {
      return this->ParseBuffer(this->InputString);
      }
    }

  // Make sure we have input.
  if(!this->Stream)
    {
    vtkErrorMacro("Parse() called with no Stream set.");
    return 0;
    }

  // Default stream parser just reads a block at a time.
  istream& in = *(this->Stream);
  const int bufferSize = 4096;
  char buffer[bufferSize];

  // Read in the stream and send its contents to the XML parser.  This
  // read loop is very sensitive on certain platforms with slightly
  // broken stream libraries (like HPUX).  Normally, it is incorrect
  // to not check the error condition on the fin.read() before using
  // the data, but the fin.gcount() will be zero if an error occurred.
  // Therefore, the loop should be safe everywhere.
  while(!this->ParsingComplete() && in)
    {
    in.read(buffer, bufferSize);
    if(in.gcount())
      {
      if(!this->ParseBuffer(buffer, in.gcount()))
        {
        return 0;
        }
      }
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParsingComplete()
{
  // Default behavior is to parse to end of stream.
  return 0;
}

//----------------------------------------------------------------------------
void vtkXMLParser::StartElement(const char *name,
                                const char ** vtkNotUsed(atts))
{
  this->ReportUnknownElement(name);
}

//----------------------------------------------------------------------------
void vtkXMLParser::EndElement(const char * vtkNotUsed(name))
{
}

//----------------------------------------------------------------------------
void vtkXMLParser::CharacterDataHandler(const char* vtkNotUsed(inData),
                                        int vtkNotUsed(inLength))
{
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportStrayAttribute(const char* element, const char* attr,
                                        const char* value)
{
  vtkWarningMacro("Stray attribute in XML stream: Element " << element
                  << " has " << attr << "=\"" << value << "\"");
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportMissingAttribute(const char* element,
                                          const char* attr)
{
  vtkErrorMacro("Missing attribute in XML stream: Element " << element
                << " is missing " << attr);
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportBadAttribute(const char* element, const char* attr,
                                      const char* value)
{
  vtkErrorMacro("Bad attribute value in XML stream: Element " << element
                << " has " << attr << "=\"" << value << "\"");
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportUnknownElement(const char* element)
{
  vtkErrorMacro("Unknown element in XML stream: " << element);
}

//----------------------------------------------------------------------------
void vtkXMLParser::ReportXmlParseError()
{
  vtkErrorMacro("Error parsing XML in stream at line "
                << XML_GetCurrentLineNumber(this->Parser)
                << ": " << XML_ErrorString(XML_GetErrorCode(this->Parser)));
}

//----------------------------------------------------------------------------
unsigned long vtkXMLParser::GetXMLByteIndex()
{
  return XML_GetCurrentByteIndex(this->Parser);
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseBuffer(const char* buffer, unsigned int count)
{
  // Pass the buffer to the expat XML parser.
  if(!XML_Parse(this->Parser, buffer, count, 0))
    {
    this->ReportXmlParseError();
    return 0;
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkXMLParser::ParseBuffer(const char* buffer)
{
  return this->ParseBuffer(buffer, static_cast<int>(strlen(buffer)));
}

//----------------------------------------------------------------------------
int vtkXMLParser::IsSpace(char c)
{
  return isspace(c);
}

//----------------------------------------------------------------------------
void vtkXMLParserStartElement(void* parser, const char *name,
                              const char **atts)
{
  // Begin element handler that is registered with the XML_Parser.
  // This just casts the user data to a vtkXMLParser and calls
  // StartElement.
  static_cast<vtkXMLParser*>(parser)->StartElement(name, atts);
}

//----------------------------------------------------------------------------
void vtkXMLParserEndElement(void* parser, const char *name)
{
  // End element handler that is registered with the XML_Parser.  This
  // just casts the user data to a vtkXMLParser and calls EndElement.
  static_cast<vtkXMLParser*>(parser)->EndElement(name);
}

//----------------------------------------------------------------------------
void vtkXMLParserCharacterDataHandler(void* parser, const char* data,
                                      int length)
{
  // Character data handler that is registered with the XML_Parser.
  // This just casts the user data to a vtkXMLParser and calls
  // CharacterDataHandler.
  static_cast<vtkXMLParser*>(parser)->CharacterDataHandler(data, length);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

# include  "priv.h"
# include  "nex_data.h"
# include  <cassert>

int print_logic_gate(FILE*fd, ivl_net_logic_t net)
{
      int rc = 0;

	// Do not handle logic gate widths.
      assert(ivl_logic_width(net) == 1);

      ivl_nexus_t nex_out = ivl_logic_pin(net,0);
      blif_nex_data_t*ned_out = blif_nex_data_t::get_nex_data(nex_out);

      assert(ned_out->get_width() == 1);

      fprintf(fd, ".names");
      for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1) {
	    ivl_nexus_t nex = ivl_logic_pin(net,idx);
	    blif_nex_data_t*ned = blif_nex_data_t::get_nex_data(nex);
 	    fprintf(fd, " %s", ned->get_name());
      }

      fprintf(fd, " %s", ned_out->get_name());
      fprintf(fd, "\n");

      switch (ivl_logic_type(net)) {
	  case IVL_LO_AND:
	    for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)
		  fprintf(fd, "1");
	    fprintf(fd, " 1\n");
	    break;
	  case IVL_LO_OR:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "1- 1\n");
	    fprintf(fd, "-1 1\n");
	    break;
	  case IVL_LO_XOR:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "10 1\n");
	    fprintf(fd, "01 1\n");
	    break;
	  default:
	    fprintf(fd, "# ERROR: Logic type not handled\n");
	    rc += 1;
	    break;
      }

      return rc;
}
<commit_msg>Add some more basic logic gates to blif target.<commit_after>/*
 * Copyright (c) 2013 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

# include  "priv.h"
# include  "nex_data.h"
# include  <cassert>

int print_logic_gate(FILE*fd, ivl_net_logic_t net)
{
      int rc = 0;

	// Do not handle logic gate widths.
      assert(ivl_logic_width(net) == 1);

      ivl_nexus_t nex_out = ivl_logic_pin(net,0);
      blif_nex_data_t*ned_out = blif_nex_data_t::get_nex_data(nex_out);

      assert(ned_out->get_width() == 1);

      fprintf(fd, ".names");
      for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1) {
	    ivl_nexus_t nex = ivl_logic_pin(net,idx);
	    blif_nex_data_t*ned = blif_nex_data_t::get_nex_data(nex);
 	    fprintf(fd, " %s", ned->get_name());
      }

      fprintf(fd, " %s", ned_out->get_name());
      fprintf(fd, "\n");

      switch (ivl_logic_type(net)) {
	  case IVL_LO_AND:
	    for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)
		  fprintf(fd, "1");
	    fprintf(fd, " 1\n");
	    break;
	  case IVL_LO_OR:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "1- 1\n");
	    fprintf(fd, "-1 1\n");
	    break;
	  case IVL_LO_XOR:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "10 1\n");
	    fprintf(fd, "01 1\n");
	    break;

	  case IVL_LO_NAND:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "0- 1\n");
	    fprintf(fd, "-0 1\n");
	    break;
	  case IVL_LO_NOR:
	    for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)
		  fprintf(fd, "0");
	    fprintf(fd, " 1\n");
	    break;
	  case IVL_LO_XNOR:
	    assert(ivl_logic_pins(net)==3);
	    fprintf(fd, "00 1\n");
	    fprintf(fd, "11 1\n");
	    break;

	  case IVL_LO_BUF:
	    assert(ivl_logic_pins(net)==2);
	    fprintf(fd, "1 1\n");
	    break;
	  case IVL_LO_NOT:
	    assert(ivl_logic_pins(net)==2);
	    fprintf(fd, "0 1\n");
	    break;

	  default:
	    fprintf(fd, "# ERROR: Logic type %d not handled\n", ivl_logic_type(net));
	    rc += 1;
	    break;
      }

      return rc;
}
<|endoftext|>


<commit_before>#include "builders/terrain/TerraGenerator.hpp"
#include "math/Mesh.hpp"
#include "math/Vector2.hpp"

using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::math;
using namespace utymap::utils;

using namespace std::placeholders;

namespace {
    /// Tolerance for meshing
    const double AreaTolerance = 1000;
    const double Scale = 1E7;

    const std::string TerrainMeshName = "terrain";
    const std::string ColorNoiseFreqKey = "color-noise-freq";
    const std::string EleNoiseFreqKey = "ele-noise-freq";
    const std::string GradientKey = "color";

    const std::string TextureIndexKey = "texture-index";
    const std::string TextureTypeKey = "texture-type";
    const std::string TextureScaleKey = "texture-scale";

    const std::string MaxAreaKey = "max-area";
    const std::string HeightOffsetKey = "height-offset";
    const std::string LayerPriorityKey = "layer-priority";
    const std::string MeshNameKey = "mesh-name";
    const std::string MeshExtrasKey = "mesh-extras";
    const std::string GridCellSize = "grid-cell-size";

    const std::unordered_map<std::string, TerraExtras::ExtrasFunc> ExtrasFuncs =
    {
        { "forest", std::bind(&TerraExtras::addForest, _1, _2) },
        { "water", std::bind(&TerraExtras::addWater, _1, _2) },
    };
};

TerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :
    context_(context),
    style_(style),
    foregroundClipper_(foregroundClipper),
    backGroundClipper_(),
    mesh_(TerrainMeshName),
    rect_(context.boundingBox.minPoint.longitude,
          context.boundingBox.minPoint.latitude,
          context.boundingBox.maxPoint.longitude,
          context.boundingBox.maxPoint.latitude)
{
}

void TerraGenerator::addRegion(const std::string& type, std::unique_ptr<Region> region)
{
    layers_[type].push(std::move(region));
}

void TerraGenerator::generate(Path& tileRect)
{
    double size = style_.getValue(GridCellSize,
        context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude,
        context_.boundingBox.center());
    splitter_.setParams(Scale, size);

    buildLayers();
    buildBackground(tileRect);

    context_.meshCallback(mesh_);
}

/// process all found layers.
void TerraGenerator::buildLayers()
{
    // 1. process layers: regions with shared properties.
    std::stringstream ss(style_.getString(LayerPriorityKey));
    while (ss.good()) {
        std::string name;
        getline(ss, name, ',');
        auto layer = layers_.find(name);
        if (layer != layers_.end()) {
            buildFromRegions(layer->second, createRegionContext(style_, name + "-"));
            layers_.erase(layer);
        }
    }

    // 2. Process the rest: each region has already its own properties.
    for (auto& layer : layers_)
        while (!layer.second.empty()) {
            auto& region = layer.second.top();
            buildFromPaths(region->points, *region->context);
            layer.second.pop();
        }
}

/// process the rest area.
void TerraGenerator::buildBackground(Path& tileRect)
{
    backGroundClipper_.AddPath(tileRect, ptSubject, true);
    Paths background;
    backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);
    backGroundClipper_.Clear();

    if (!background.empty())
        populateMesh(background, createRegionContext(style_, ""));
}

TerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const
{
    double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;

    MeshBuilder::GeometryOptions geometryOptions(
            style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),
            style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),
            std::numeric_limits<double>::lowest(), // no fixed elevation
            style.getValue(prefix + HeightOffsetKey, quadKeyWidth),
            false, // no flip
            false, // no back side
            1      // no new vertices on boundaries
        );

    auto textureIndex = static_cast<std::uint16_t>(style.getValue(prefix + TextureIndexKey));
    auto textureRegion = context_.styleProvider
            .getTexture(textureIndex, style.getString(prefix + TextureTypeKey))
            .random(0);   // TODO use seed for randomization
    double scale = style.getValue(prefix + TextureScaleKey);

    MeshBuilder::AppearanceOptions appearanceOptions(
            context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),
            style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),
            textureIndex,
            textureRegion,
            scale > 0 ? scale :1
        );

    return RegionContext(style, prefix, geometryOptions, appearanceOptions);
}

void TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)
{
    // merge all regions together
    Clipper clipper;
    while (!regions.empty()) {
        clipper.AddPaths(regions.top()->points, ptSubject, true);
        regions.pop();
    }

    Paths result;
    clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);

    buildFromPaths(result, regionContext);
}

void TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)
{
    Paths solution;
    foregroundClipper_.AddPaths(paths, ptSubject, true);
    foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);
    foregroundClipper_.moveSubjectToClip();

    populateMesh(solution, regionContext);
}

void TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)
{
    ClipperLib::SimplifyPolygons(paths);
    ClipperLib::CleanPolygons(paths);

    bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 1E-8;
    // calculate approximate size of overall points
    double size = 0;
    for (std::size_t i = 0; i < paths.size(); ++i)
        size += paths[i].size() * 1.5;

    Polygon polygon(static_cast<std::size_t>(size));
    for (const Path& path : paths) {
        double area = ClipperLib::Area(path);
        bool isHole = area < 0;
        if (std::abs(area) < AreaTolerance)
            continue;

        backGroundClipper_.AddPath(path, ptClip, true);

        Points points = restorePoints(path);
        if (isHole)
            polygon.addHole(points);
        else
            polygon.addContour(points);

        if (hasHeightOffset)
            processHeightOffset(points, regionContext);
    }

    if (!polygon.points.empty())
        fillMesh(polygon, regionContext);
}

/// restores mesh points from clipper points and injects new ones according to grid.
TerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const
{
    auto lastItemIndex = path.size() - 1;
    Points points;
    points.reserve(path.size());
    for (int i = 0; i <= lastItemIndex; i++)
        splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);

    return std::move(points);
}

void TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)
{
    std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);
    if (!meshName.empty()) {
        Mesh polygonMesh(meshName);
        TerraExtras::Context extrasContext(polygonMesh, regionContext.style);
        context_.meshBuilder.addPolygon(polygonMesh,
                                        polygon,
                                        regionContext.geometryOptions,
                                        regionContext.appearanceOptions);
        context_.meshBuilder.writeTextureMappingInfo(polygonMesh, regionContext.appearanceOptions);

        addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);
        context_.meshCallback(polygonMesh);
    }
    else {
        TerraExtras::Context extrasContext(mesh_, regionContext.style);
        context_.meshBuilder.addPolygon(mesh_,
                                        polygon,
                                        regionContext.geometryOptions,
                                        regionContext.appearanceOptions);
        context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);

        addExtrasIfNecessary(mesh_, extrasContext, regionContext);
    }
}

void TerraGenerator::addExtrasIfNecessary(Mesh& mesh,
                                          TerraExtras::Context& extrasContext,
                                          const RegionContext& regionContext) const
{
    std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);
    if (meshExtras.empty())
        return;

    ExtrasFuncs.at(meshExtras)(context_, extrasContext);
}

void TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)
{
    // do not use elevation noise for height offset.
    auto newGeometryOptions = regionContext.geometryOptions;
    newGeometryOptions.eleNoiseFreq = 0;

    for (std::size_t i = 0; i < points.size(); ++i) {
        Vector2 p1 = points[i];
        Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];

        // check whether two points are on cell rect
        if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))
            continue;

        context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);
    }
}
<commit_msg>core: fix static analyzer warning<commit_after>#include "builders/terrain/TerraGenerator.hpp"
#include "math/Mesh.hpp"
#include "math/Vector2.hpp"

using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::mapcss;
using namespace utymap::math;
using namespace utymap::utils;

using namespace std::placeholders;

namespace {
    /// Tolerance for meshing
    const double AreaTolerance = 1000;
    const double Scale = 1E7;

    const std::string TerrainMeshName = "terrain";
    const std::string ColorNoiseFreqKey = "color-noise-freq";
    const std::string EleNoiseFreqKey = "ele-noise-freq";
    const std::string GradientKey = "color";

    const std::string TextureIndexKey = "texture-index";
    const std::string TextureTypeKey = "texture-type";
    const std::string TextureScaleKey = "texture-scale";

    const std::string MaxAreaKey = "max-area";
    const std::string HeightOffsetKey = "height-offset";
    const std::string LayerPriorityKey = "layer-priority";
    const std::string MeshNameKey = "mesh-name";
    const std::string MeshExtrasKey = "mesh-extras";
    const std::string GridCellSize = "grid-cell-size";

    const std::unordered_map<std::string, TerraExtras::ExtrasFunc> ExtrasFuncs =
    {
        { "forest", std::bind(&TerraExtras::addForest, _1, _2) },
        { "water", std::bind(&TerraExtras::addWater, _1, _2) },
    };
};

TerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :
    context_(context),
    style_(style),
    foregroundClipper_(foregroundClipper),
    backGroundClipper_(),
    mesh_(TerrainMeshName),
    rect_(context.boundingBox.minPoint.longitude,
          context.boundingBox.minPoint.latitude,
          context.boundingBox.maxPoint.longitude,
          context.boundingBox.maxPoint.latitude)
{
}

void TerraGenerator::addRegion(const std::string& type, std::unique_ptr<Region> region)
{
    layers_[type].push(std::move(region));
}

void TerraGenerator::generate(Path& tileRect)
{
    double size = style_.getValue(GridCellSize,
        context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude,
        context_.boundingBox.center());
    splitter_.setParams(Scale, size);

    buildLayers();
    buildBackground(tileRect);

    context_.meshCallback(mesh_);
}

/// process all found layers.
void TerraGenerator::buildLayers()
{
    // 1. process layers: regions with shared properties.
    std::stringstream ss(style_.getString(LayerPriorityKey));
    while (ss.good()) {
        std::string name;
        getline(ss, name, ',');
        auto layer = layers_.find(name);
        if (layer != layers_.end()) {
            buildFromRegions(layer->second, createRegionContext(style_, name + "-"));
            layers_.erase(layer);
        }
    }

    // 2. Process the rest: each region has already its own properties.
    for (auto& layer : layers_)
        while (!layer.second.empty()) {
            auto& region = layer.second.top();
            buildFromPaths(region->points, *region->context);
            layer.second.pop();
        }
}

/// process the rest area.
void TerraGenerator::buildBackground(Path& tileRect)
{
    backGroundClipper_.AddPath(tileRect, ptSubject, true);
    Paths background;
    backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);
    backGroundClipper_.Clear();

    if (!background.empty())
        populateMesh(background, createRegionContext(style_, ""));
}

TerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const
{
    double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;

    MeshBuilder::GeometryOptions geometryOptions(
            style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),
            style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),
            std::numeric_limits<double>::lowest(), // no fixed elevation
            style.getValue(prefix + HeightOffsetKey, quadKeyWidth),
            false, // no flip
            false, // no back side
            1      // no new vertices on boundaries
        );

    auto textureIndex = static_cast<std::uint16_t>(style.getValue(prefix + TextureIndexKey));
    auto textureRegion = context_.styleProvider
            .getTexture(textureIndex, style.getString(prefix + TextureTypeKey))
            .random(0);   // TODO use seed for randomization
    double scale = style.getValue(prefix + TextureScaleKey);

    MeshBuilder::AppearanceOptions appearanceOptions(
            context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),
            style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),
            textureIndex,
            textureRegion,
            scale > 0 ? scale :1
        );

    return RegionContext(style, prefix, geometryOptions, appearanceOptions);
}

void TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)
{
    // merge all regions together
    Clipper clipper;
    while (!regions.empty()) {
        clipper.AddPaths(regions.top()->points, ptSubject, true);
        regions.pop();
    }

    Paths result;
    clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);

    buildFromPaths(result, regionContext);
}

void TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)
{
    Paths solution;
    foregroundClipper_.AddPaths(paths, ptSubject, true);
    foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);
    foregroundClipper_.moveSubjectToClip();

    populateMesh(solution, regionContext);
}

void TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)
{
    ClipperLib::SimplifyPolygons(paths);
    ClipperLib::CleanPolygons(paths);

    bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 0;
    // calculate approximate size of overall points
    double size = 0;
    for (std::size_t i = 0; i < paths.size(); ++i)
        size += paths[i].size() * 1.5;

    Polygon polygon(static_cast<std::size_t>(size));
    for (const Path& path : paths) {
        double area = ClipperLib::Area(path);
        bool isHole = area < 0;
        if (std::abs(area) < AreaTolerance)
            continue;

        backGroundClipper_.AddPath(path, ptClip, true);

        Points points = restorePoints(path);
        if (isHole)
            polygon.addHole(points);
        else
            polygon.addContour(points);

        if (hasHeightOffset)
            processHeightOffset(points, regionContext);
    }

    if (!polygon.points.empty())
        fillMesh(polygon, regionContext);
}

/// restores mesh points from clipper points and injects new ones according to grid.
TerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const
{
    auto lastItemIndex = path.size() - 1;
    Points points;
    points.reserve(path.size());
    for (int i = 0; i <= lastItemIndex; i++)
        splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);

    return std::move(points);
}

void TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)
{
    std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);
    if (!meshName.empty()) {
        Mesh polygonMesh(meshName);
        TerraExtras::Context extrasContext(polygonMesh, regionContext.style);
        context_.meshBuilder.addPolygon(polygonMesh,
                                        polygon,
                                        regionContext.geometryOptions,
                                        regionContext.appearanceOptions);
        context_.meshBuilder.writeTextureMappingInfo(polygonMesh, regionContext.appearanceOptions);

        addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);
        context_.meshCallback(polygonMesh);
    }
    else {
        TerraExtras::Context extrasContext(mesh_, regionContext.style);
        context_.meshBuilder.addPolygon(mesh_,
                                        polygon,
                                        regionContext.geometryOptions,
                                        regionContext.appearanceOptions);
        context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);

        addExtrasIfNecessary(mesh_, extrasContext, regionContext);
    }
}

void TerraGenerator::addExtrasIfNecessary(Mesh& mesh,
                                          TerraExtras::Context& extrasContext,
                                          const RegionContext& regionContext) const
{
    std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);
    if (meshExtras.empty())
        return;

    ExtrasFuncs.at(meshExtras)(context_, extrasContext);
}

void TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)
{
    // do not use elevation noise for height offset.
    auto newGeometryOptions = regionContext.geometryOptions;
    newGeometryOptions.eleNoiseFreq = 0;

    for (std::size_t i = 0; i < points.size(); ++i) {
        Vector2 p1 = points[i];
        Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];

        // check whether two points are on cell rect
        if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))
            continue;

        context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);
    }
}
<|endoftext|>


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

#pragma once

#include "onnx2trt.hpp"

#include <list>
#include <unordered_map>

namespace onnx2trt {

class ImporterContext final : public IImporterContext {
  nvinfer1::INetworkDefinition* _network;
  nvinfer1::ILogger* _logger;
  std::list<UniqueOwnable> _owned_plugin_instances;
  std::list<std::vector<uint8_t>> _temp_bufs;
  std::unordered_map<std::string, nvinfer1::ITensor*>  _user_inputs;
  std::unordered_map<std::string, nvinfer1::ITensor**> _user_outputs;
  std::unordered_map<std::string, int64_t> _opsets;
public:
  ImporterContext(nvinfer1::INetworkDefinition* network,
                  nvinfer1::ILogger* logger)
    : _network(network), _logger(logger) {}
  virtual nvinfer1::INetworkDefinition* network() override { return _network; }
  nvinfer1::ILogger& logger() { return *_logger; }
  virtual ShapedWeights createTempWeights(ShapedWeights::DataType type,
                                          nvinfer1::Dims shape) override {
    ShapedWeights weights(type, nullptr, shape);
    _temp_bufs.push_back(std::vector<uint8_t>(weights.size_bytes()));
    weights.values = _temp_bufs.back().data();
    return weights;
  }
  virtual nvinfer1::IPluginLayer* addPlugin(Plugin* plugin,
                                            std::vector<nvinfer1::ITensor*> const& inputs) override {
    // Note: Plugins are wrapped here to make them work with
    // onnx2trt::PluginFactory.
    auto* wrapped_plugin = new TypeSerializingPlugin(plugin);
    _owned_plugin_instances.emplace_back(wrapped_plugin);
#if NV_TENSORRT_MAJOR < 4
    return _network->addPlugin(inputs.data(), inputs.size(), *wrapped_plugin);
#else
    return _network->addPluginExt(inputs.data(), inputs.size(), *wrapped_plugin);
#endif
  }
  bool setUserInput(const char* name, nvinfer1::ITensor* input) {
    _user_inputs[name] = input;
    return true;
  }
  bool setUserOutput(const char* name, nvinfer1::ITensor** output) {
    _user_outputs[name] = output;
    return true;
  }
  nvinfer1::ITensor* getUserInput(const char* name) {
    if( !_user_inputs.count(name) ) {
      return nullptr;
    } else {
      return _user_inputs.at(name);
    }
  }
  nvinfer1::ITensor** getUserOutput(const char* name) {
    if( !_user_outputs.count(name) ) {
      return nullptr;
    } else {
      return _user_outputs.at(name);
    }
  }
  std::unordered_map<std::string, nvinfer1::ITensor**> const& getUserOutputs() const {
	  return _user_outputs;
  }
  void clearOpsets() { _opsets.clear(); }
  void addOpset(std::string domain, int64_t version) {
    _opsets.emplace(domain, version);
  }
  virtual int64_t getOpsetVersion(const char* domain="") const override {
    assert(_opsets.count(domain));
    return _opsets.at(domain);
  }
};

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

#pragma once

#include "onnx2trt.hpp"

#include <list>
#include <unordered_map>

namespace onnx2trt {

class ImporterContext final : public IImporterContext {
  nvinfer1::INetworkDefinition* _network;
  nvinfer1::ILogger* _logger;
  std::list<UniqueOwnable> _owned_plugin_instances;
  std::list<std::vector<uint8_t>> _temp_bufs;
  std::unordered_map<std::string, nvinfer1::ITensor*>  _user_inputs;
  std::unordered_map<std::string, nvinfer1::ITensor**> _user_outputs;
  std::unordered_map<std::string, int64_t> _opsets;
public:
  ImporterContext(nvinfer1::INetworkDefinition* network,
                  nvinfer1::ILogger* logger)
    : _network(network), _logger(logger) {}
  virtual nvinfer1::INetworkDefinition* network() override { return _network; }
  nvinfer1::ILogger& logger() { return *_logger; }
  virtual ShapedWeights createTempWeights(ShapedWeights::DataType type,
                                          nvinfer1::Dims shape) override {
    ShapedWeights weights(type, nullptr, shape);
    _temp_bufs.push_back(std::vector<uint8_t>(weights.size_bytes()));
    weights.values = _temp_bufs.back().data();
    return weights;
  }
  virtual nvinfer1::IPluginLayer* addPlugin(Plugin* plugin,
                                            std::vector<nvinfer1::ITensor*> const& inputs) override {
    // Note: Plugins are wrapped here to make them work with
    // onnx2trt::PluginFactory.
    auto* wrapped_plugin = new TypeSerializingPlugin(plugin);
    _owned_plugin_instances.emplace_back(wrapped_plugin);
#if NV_TENSORRT_MAJOR < 4
    return _network->addPlugin(inputs.data(), inputs.size(), *wrapped_plugin);
#else
    return _network->addPluginExt(inputs.data(), inputs.size(), *wrapped_plugin);
#endif
  }
  bool setUserInput(const char* name, nvinfer1::ITensor* input) {
    _user_inputs[name] = input;
    return true;
  }
  bool setUserOutput(const char* name, nvinfer1::ITensor** output) {
    _user_outputs[name] = output;
    return true;
  }
  nvinfer1::ITensor* getUserInput(const char* name) {
    if( !_user_inputs.count(name) ) {
      return nullptr;
    } else {
      return _user_inputs.at(name);
    }
  }
  nvinfer1::ITensor** getUserOutput(const char* name) {
    if( !_user_outputs.count(name) ) {
      return nullptr;
    } else {
      return _user_outputs.at(name);
    }
  }
  std::unordered_map<std::string, nvinfer1::ITensor**> const& getUserOutputs() const {
	  return _user_outputs;
  }
  void clearOpsets() { _opsets.clear(); }
  void addOpset(std::string domain, int64_t version) {
    _opsets.emplace(domain, version);
  }
  virtual int64_t getOpsetVersion(const char* domain="") const override {
    if (_opsets.empty()) {
      return 1;
    } else if (_opsets.size() == 1) {
      return _opsets.begin()->second;
    } else {
      assert(_opsets.count(domain));
      return _opsets.at(domain);
    }
  }
};

} // namespace onnx2trt
<|endoftext|>


<commit_before>#ifndef UNDERLYING_FUNCTIONALITIES_HPP
#define UNDERLYING_FUNCTIONALITIES_HPP

#include "crtp.hpp"
#include "named_type_impl.hpp"

#include <functional>
#include <memory>

#if FLUENT_HOSTED == 1
#   include <iostream>
#endif

// C++17 constexpr additions
#if FLUENT_CPP17_PRESENT
#    define FLUENT_CONSTEXPR17 constexpr
#else
#    define FLUENT_CONSTEXPR17
#endif

namespace fluent
{

template <typename T>
struct PreIncrementable : crtp<T, PreIncrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T& operator++()
    {
        ++this->underlying().get();
        return this->underlying();
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PostIncrementable : crtp<T, PostIncrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T operator++(int)
    {
        return T(this->underlying().get()++);
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PreDecrementable : crtp<T, PreDecrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T& operator--()
    {
        --this->underlying().get();
        return this->underlying();
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PostDecrementable : crtp<T, PostDecrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T operator--(int)
    {
        return T( this->underlying().get()-- );
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct BinaryAddable : crtp<T, BinaryAddable>
{
    FLUENT_NODISCARD constexpr T operator+(T const& other) const
    {
        return T(this->underlying().get() + other.get());
    }
    FLUENT_CONSTEXPR17 T& operator+=(T const& other)
    {
        this->underlying().get() += other.get();
        return this->underlying();
    }
};

template <typename T>
struct UnaryAddable : crtp<T, UnaryAddable>
{
    FLUENT_NODISCARD constexpr T operator+() const
    {
        return T(+this->underlying().get());
    }
};

template <typename T>
struct Addable : BinaryAddable<T>, UnaryAddable<T>
{
    using BinaryAddable<T>::operator+;
    using UnaryAddable<T>::operator+;
};

template <typename T>
struct BinarySubtractable : crtp<T, BinarySubtractable>
{
    FLUENT_NODISCARD constexpr T operator-(T const& other) const
    {
        return T(this->underlying().get() - other.get());
    }
    FLUENT_CONSTEXPR17 T& operator-=(T const& other)
    {
        this->underlying().get() -= other.get();
        return this->underlying();
    }
};

template <typename T>
struct UnarySubtractable : crtp<T, UnarySubtractable>
{
    FLUENT_NODISCARD constexpr T operator-() const
    {
        return T(-this->underlying().get());
    }
};

template <typename T>
struct Subtractable : BinarySubtractable<T>, UnarySubtractable<T>
{
    using UnarySubtractable<T>::operator-;
    using BinarySubtractable<T>::operator-;
};

template <typename T>
struct Multiplicable : crtp<T, Multiplicable>
{
    FLUENT_NODISCARD constexpr T operator*(T const& other) const
    {
        return T(this->underlying().get() * other.get());
    }
    FLUENT_CONSTEXPR17 T& operator*=(T const& other)
    {
        this->underlying().get() *= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Divisible : crtp<T, Divisible>
{
    FLUENT_NODISCARD constexpr T operator/(T const& other) const
    {
        return T(this->underlying().get() / other.get());
    }
    FLUENT_CONSTEXPR17 T& operator/=(T const& other)
    {
        this->underlying().get() /= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Modulable : crtp<T, Modulable>
{
    FLUENT_NODISCARD constexpr T operator%(T const& other) const
    {
        return T(this->underlying().get() % other.get());
    }
    FLUENT_CONSTEXPR17 T& operator%=(T const& other)
    {
        this->underlying().get() %= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseInvertable : crtp<T, BitWiseInvertable>
{
    FLUENT_NODISCARD constexpr T operator~() const
    {
        return T(~this->underlying().get());
    }
};

template <typename T>
struct BitWiseAndable : crtp<T, BitWiseAndable>
{
    FLUENT_NODISCARD constexpr T operator&(T const& other) const
    {
        return T(this->underlying().get() & other.get());
    }
    FLUENT_CONSTEXPR17 T& operator&=(T const& other)
    {
        this->underlying().get() &= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseOrable : crtp<T, BitWiseOrable>
{
    FLUENT_NODISCARD constexpr T operator|(T const& other) const
    {
        return T(this->underlying().get() | other.get());
    }
    FLUENT_CONSTEXPR17 T& operator|=(T const& other)
    {
        this->underlying().get() |= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseXorable : crtp<T, BitWiseXorable>
{
    FLUENT_NODISCARD constexpr T operator^(T const& other) const
    {
        return T(this->underlying().get() ^ other.get());
    }
    FLUENT_CONSTEXPR17 T& operator^=(T const& other)
    {
        this->underlying().get() ^= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseLeftShiftable : crtp<T, BitWiseLeftShiftable>
{
    FLUENT_NODISCARD constexpr T operator<<(T const& other) const
    {
        return T(this->underlying().get() << other.get());
    }
    FLUENT_CONSTEXPR17 T& operator<<=(T const& other)
    {
        this->underlying().get() <<= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseRightShiftable : crtp<T, BitWiseRightShiftable>
{
    FLUENT_NODISCARD constexpr T operator>>(T const& other) const
    {
        return T(this->underlying().get() >> other.get());
    }
    FLUENT_CONSTEXPR17 T& operator>>=(T const& other)
    {
        this->underlying().get() >>= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Comparable : crtp<T, Comparable>
{
    FLUENT_NODISCARD constexpr bool operator<(T const& other) const
    {
        return this->underlying().get() < other.get();
    }
    FLUENT_NODISCARD constexpr bool operator>(T const& other) const
    {
        return other.get() < this->underlying().get();
    }
    FLUENT_NODISCARD constexpr bool operator<=(T const& other) const
    {
        return !(other.get() < this->underlying().get());
    }
    FLUENT_NODISCARD constexpr bool operator>=(T const& other) const
    {
        return !(*this < other);
    }
// On Visual Studio before 19.22, you cannot define constexpr with friend function
// See: https://stackoverflow.com/a/60400110
#if defined(_MSC_VER) && _MSC_VER < 1922
    FLUENT_NODISCARD constexpr bool operator==(T const& other) const
    {
        return !(*this < other) && !(other.get() < this->underlying().get());
    }
#else
    FLUENT_NODISCARD friend constexpr bool operator==(Comparable<T> const& self, T const& other)
    {
        return !(self < other) && !(other.get() < self.underlying().get());
    }
#endif
    FLUENT_NODISCARD constexpr bool operator!=(T const& other) const
    {
        return !(*this == other);
    }
};

template< typename T >
struct Dereferencable;

template< typename T, typename Parameter, template< typename > class ... Skills >
struct Dereferencable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, Dereferencable>
{
    FLUENT_NODISCARD constexpr T& operator*() &
    {
        return this->underlying().get();
    }
    FLUENT_NODISCARD constexpr std::remove_reference_t<T> const& operator*() const &
    {
        return this->underlying().get();
    }
};

template <typename Destination>
struct ImplicitlyConvertibleTo
{
    template <typename T>
    struct templ : crtp<T, templ>
    {
        FLUENT_NODISCARD constexpr operator Destination() const
        {
            return this->underlying().get();
        }
    };
};

template <typename T>
struct Printable : crtp<T, Printable>
{
    static constexpr bool is_printable = true;

    void print(std::ostream& os) const
    {
        os << this->underlying().get();
    }
};

#if FLUENT_HOSTED == 1
    template <typename T, typename Parameter, template <typename> class... Skills>
    typename std::enable_if<NamedType<T, Parameter, Skills...>::is_printable, std::ostream&>::type
    operator<<(std::ostream& os, NamedType<T, Parameter, Skills...> const& object)
    {
        object.print(os);
        return os;
    }
#endif

template <typename T>
struct Hashable
{
    static constexpr bool is_hashable = true;
};

template <typename NamedType_>
struct FunctionCallable;

template <typename T, typename Parameter, template <typename> class... Skills>
struct FunctionCallable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, FunctionCallable>
{
    FLUENT_NODISCARD constexpr operator T const&() const
    {
        return this->underlying().get();
    }
    FLUENT_NODISCARD constexpr operator T&()
    {
        return this->underlying().get();
    }
};

template <typename NamedType_>
struct MethodCallable;

template <typename T, typename Parameter, template <typename> class... Skills>
struct MethodCallable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, MethodCallable>
{
    FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t<T> const* operator->() const
    {
        return std::addressof(this->underlying().get());
    }
    FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t<T>* operator->()
    {
        return std::addressof(this->underlying().get());
    }
};

template <typename NamedType_>
struct Callable
    : FunctionCallable<NamedType_>
    , MethodCallable<NamedType_>
{
};

template <typename T>
struct Arithmetic
    : PreIncrementable<T>
    , PostIncrementable<T>
    , PreDecrementable<T>
    , PostDecrementable<T>
    , Addable<T>
    , Subtractable<T>
    , Multiplicable<T>
    , Divisible<T>
    , Modulable<T>
    , BitWiseInvertable<T>
    , BitWiseAndable<T>
    , BitWiseOrable<T>
    , BitWiseXorable<T>
    , BitWiseLeftShiftable<T>
    , BitWiseRightShiftable<T>
    , Comparable<T>
    , Printable<T>
    , Hashable<T>
{
};

} // namespace fluent

namespace std
{
template <typename T, typename Parameter, template <typename> class... Skills>
struct hash<fluent::NamedType<T, Parameter, Skills...>>
{
    using NamedType = fluent::NamedType<T, Parameter, Skills...>;
    using checkIfHashable = typename std::enable_if<NamedType::is_hashable, void>::type;

    size_t operator()(fluent::NamedType<T, Parameter, Skills...> const& x) const noexcept
    {
        static_assert(noexcept(std::hash<T>()(x.get())), "hash fuction should not throw");

        return std::hash<T>()(x.get());
    }
};

} // namespace std

#endif
<commit_msg>Work around gcc bug with ambiguous post/pre-increment.<commit_after>#ifndef UNDERLYING_FUNCTIONALITIES_HPP
#define UNDERLYING_FUNCTIONALITIES_HPP

#include "crtp.hpp"
#include "named_type_impl.hpp"

#include <functional>
#include <memory>

#if FLUENT_HOSTED == 1
#   include <iostream>
#endif

// C++17 constexpr additions
#if FLUENT_CPP17_PRESENT
#    define FLUENT_CONSTEXPR17 constexpr
#else
#    define FLUENT_CONSTEXPR17
#endif

namespace fluent
{

template <typename T>
struct PreIncrementable : crtp<T, PreIncrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T& operator++()
    {
        ++this->underlying().get();
        return this->underlying();
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PostIncrementable : crtp<T, PostIncrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T operator++(int)
    {
        return T(this->underlying().get()++);
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PreDecrementable : crtp<T, PreDecrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T& operator--()
    {
        --this->underlying().get();
        return this->underlying();
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct PostDecrementable : crtp<T, PostDecrementable>
{
    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN

    FLUENT_CONSTEXPR17 T operator--(int)
    {
        return T( this->underlying().get()-- );
    }

    IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END
};

template <typename T>
struct BinaryAddable : crtp<T, BinaryAddable>
{
    FLUENT_NODISCARD constexpr T operator+(T const& other) const
    {
        return T(this->underlying().get() + other.get());
    }
    FLUENT_CONSTEXPR17 T& operator+=(T const& other)
    {
        this->underlying().get() += other.get();
        return this->underlying();
    }
};

template <typename T>
struct UnaryAddable : crtp<T, UnaryAddable>
{
    FLUENT_NODISCARD constexpr T operator+() const
    {
        return T(+this->underlying().get());
    }
};

template <typename T>
struct Addable : BinaryAddable<T>, UnaryAddable<T>
{
    using BinaryAddable<T>::operator+;
    using UnaryAddable<T>::operator+;
};

template <typename T>
struct BinarySubtractable : crtp<T, BinarySubtractable>
{
    FLUENT_NODISCARD constexpr T operator-(T const& other) const
    {
        return T(this->underlying().get() - other.get());
    }
    FLUENT_CONSTEXPR17 T& operator-=(T const& other)
    {
        this->underlying().get() -= other.get();
        return this->underlying();
    }
};

template <typename T>
struct UnarySubtractable : crtp<T, UnarySubtractable>
{
    FLUENT_NODISCARD constexpr T operator-() const
    {
        return T(-this->underlying().get());
    }
};

template <typename T>
struct Subtractable : BinarySubtractable<T>, UnarySubtractable<T>
{
    using UnarySubtractable<T>::operator-;
    using BinarySubtractable<T>::operator-;
};

template <typename T>
struct Multiplicable : crtp<T, Multiplicable>
{
    FLUENT_NODISCARD constexpr T operator*(T const& other) const
    {
        return T(this->underlying().get() * other.get());
    }
    FLUENT_CONSTEXPR17 T& operator*=(T const& other)
    {
        this->underlying().get() *= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Divisible : crtp<T, Divisible>
{
    FLUENT_NODISCARD constexpr T operator/(T const& other) const
    {
        return T(this->underlying().get() / other.get());
    }
    FLUENT_CONSTEXPR17 T& operator/=(T const& other)
    {
        this->underlying().get() /= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Modulable : crtp<T, Modulable>
{
    FLUENT_NODISCARD constexpr T operator%(T const& other) const
    {
        return T(this->underlying().get() % other.get());
    }
    FLUENT_CONSTEXPR17 T& operator%=(T const& other)
    {
        this->underlying().get() %= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseInvertable : crtp<T, BitWiseInvertable>
{
    FLUENT_NODISCARD constexpr T operator~() const
    {
        return T(~this->underlying().get());
    }
};

template <typename T>
struct BitWiseAndable : crtp<T, BitWiseAndable>
{
    FLUENT_NODISCARD constexpr T operator&(T const& other) const
    {
        return T(this->underlying().get() & other.get());
    }
    FLUENT_CONSTEXPR17 T& operator&=(T const& other)
    {
        this->underlying().get() &= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseOrable : crtp<T, BitWiseOrable>
{
    FLUENT_NODISCARD constexpr T operator|(T const& other) const
    {
        return T(this->underlying().get() | other.get());
    }
    FLUENT_CONSTEXPR17 T& operator|=(T const& other)
    {
        this->underlying().get() |= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseXorable : crtp<T, BitWiseXorable>
{
    FLUENT_NODISCARD constexpr T operator^(T const& other) const
    {
        return T(this->underlying().get() ^ other.get());
    }
    FLUENT_CONSTEXPR17 T& operator^=(T const& other)
    {
        this->underlying().get() ^= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseLeftShiftable : crtp<T, BitWiseLeftShiftable>
{
    FLUENT_NODISCARD constexpr T operator<<(T const& other) const
    {
        return T(this->underlying().get() << other.get());
    }
    FLUENT_CONSTEXPR17 T& operator<<=(T const& other)
    {
        this->underlying().get() <<= other.get();
        return this->underlying();
    }
};

template <typename T>
struct BitWiseRightShiftable : crtp<T, BitWiseRightShiftable>
{
    FLUENT_NODISCARD constexpr T operator>>(T const& other) const
    {
        return T(this->underlying().get() >> other.get());
    }
    FLUENT_CONSTEXPR17 T& operator>>=(T const& other)
    {
        this->underlying().get() >>= other.get();
        return this->underlying();
    }
};

template <typename T>
struct Comparable : crtp<T, Comparable>
{
    FLUENT_NODISCARD constexpr bool operator<(T const& other) const
    {
        return this->underlying().get() < other.get();
    }
    FLUENT_NODISCARD constexpr bool operator>(T const& other) const
    {
        return other.get() < this->underlying().get();
    }
    FLUENT_NODISCARD constexpr bool operator<=(T const& other) const
    {
        return !(other.get() < this->underlying().get());
    }
    FLUENT_NODISCARD constexpr bool operator>=(T const& other) const
    {
        return !(*this < other);
    }
// On Visual Studio before 19.22, you cannot define constexpr with friend function
// See: https://stackoverflow.com/a/60400110
#if defined(_MSC_VER) && _MSC_VER < 1922
    FLUENT_NODISCARD constexpr bool operator==(T const& other) const
    {
        return !(*this < other) && !(other.get() < this->underlying().get());
    }
#else
    FLUENT_NODISCARD friend constexpr bool operator==(Comparable<T> const& self, T const& other)
    {
        return !(self < other) && !(other.get() < self.underlying().get());
    }
#endif
    FLUENT_NODISCARD constexpr bool operator!=(T const& other) const
    {
        return !(*this == other);
    }
};

template< typename T >
struct Dereferencable;

template< typename T, typename Parameter, template< typename > class ... Skills >
struct Dereferencable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, Dereferencable>
{
    FLUENT_NODISCARD constexpr T& operator*() &
    {
        return this->underlying().get();
    }
    FLUENT_NODISCARD constexpr std::remove_reference_t<T> const& operator*() const &
    {
        return this->underlying().get();
    }
};

template <typename Destination>
struct ImplicitlyConvertibleTo
{
    template <typename T>
    struct templ : crtp<T, templ>
    {
        FLUENT_NODISCARD constexpr operator Destination() const
        {
            return this->underlying().get();
        }
    };
};

template <typename T>
struct Printable : crtp<T, Printable>
{
    static constexpr bool is_printable = true;

    void print(std::ostream& os) const
    {
        os << this->underlying().get();
    }
};

#if FLUENT_HOSTED == 1
    template <typename T, typename Parameter, template <typename> class... Skills>
    typename std::enable_if<NamedType<T, Parameter, Skills...>::is_printable, std::ostream&>::type
    operator<<(std::ostream& os, NamedType<T, Parameter, Skills...> const& object)
    {
        object.print(os);
        return os;
    }
#endif

template <typename T>
struct Hashable
{
    static constexpr bool is_hashable = true;
};

template <typename NamedType_>
struct FunctionCallable;

template <typename T, typename Parameter, template <typename> class... Skills>
struct FunctionCallable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, FunctionCallable>
{
    FLUENT_NODISCARD constexpr operator T const&() const
    {
        return this->underlying().get();
    }
    FLUENT_NODISCARD constexpr operator T&()
    {
        return this->underlying().get();
    }
};

template <typename NamedType_>
struct MethodCallable;

template <typename T, typename Parameter, template <typename> class... Skills>
struct MethodCallable<NamedType<T, Parameter, Skills...>> : crtp<NamedType<T, Parameter, Skills...>, MethodCallable>
{
    FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t<T> const* operator->() const
    {
        return std::addressof(this->underlying().get());
    }
    FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t<T>* operator->()
    {
        return std::addressof(this->underlying().get());
    }
};

template <typename NamedType_>
struct Callable
    : FunctionCallable<NamedType_>
    , MethodCallable<NamedType_>
{
};

template <typename T>
struct Arithmetic
    : PreIncrementable<T>
    , PostIncrementable<T>
    , PreDecrementable<T>
    , PostDecrementable<T>
    , Addable<T>
    , Subtractable<T>
    , Multiplicable<T>
    , Divisible<T>
    , Modulable<T>
    , BitWiseInvertable<T>
    , BitWiseAndable<T>
    , BitWiseOrable<T>
    , BitWiseXorable<T>
    , BitWiseLeftShiftable<T>
    , BitWiseRightShiftable<T>
    , Comparable<T>
    , Printable<T>
    , Hashable<T>
{
    using PostIncrementable<T>::operator++;
    using PreIncrementable<T>::operator++;
    using PostDecrementable<T>::operator--;
    using PreDecrementable<T>::operator--;
};

} // namespace fluent

namespace std
{
template <typename T, typename Parameter, template <typename> class... Skills>
struct hash<fluent::NamedType<T, Parameter, Skills...>>
{
    using NamedType = fluent::NamedType<T, Parameter, Skills...>;
    using checkIfHashable = typename std::enable_if<NamedType::is_hashable, void>::type;

    size_t operator()(fluent::NamedType<T, Parameter, Skills...> const& x) const noexcept
    {
        static_assert(noexcept(std::hash<T>()(x.get())), "hash fuction should not throw");

        return std::hash<T>()(x.get());
    }
};

} // namespace std

#endif
<|endoftext|>


<commit_before>/*
 * RingBufferSubHistory.h
 *
 *  Created on: 20.05.2016
 *      Author: hartung
 */

#ifndef INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_
#define INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_

#include "Stdafx.hpp"
#include "BasicTypedefs.hpp"
#include "synchronization/HistoryEntry.hpp"
#include "synchronization/Interpolation.hpp"

namespace Synchronization
{

    class RingBufferSubHistory
    {
     public:

        size_type size() const;

        real_type getNewestTime() const;

        FMI::ValueCollection interpolate(const real_type & time);

        FMI::ValueCollection operator[](const real_type & time);

        const Interpolation& getInterpolation() const;

        friend class AbstractDataHistory;

    private:
        size_type _curIndex;
        size_type _lastInsertedElem;
        std::vector<HistoryEntry> _entries;
        Interpolation _interpolation;

        size_type _numAddedElems;

        RingBufferSubHistory() = delete;

        RingBufferSubHistory(const Interpolation & interpolation,
                const FMI::ValueCollection & bufferScheme, size_type size = 300);

        bool_type insert(const HistoryEntry & in);

        size_type deleteOlderThan(const HistoryEntry & in);

        tuple<size_type,size_type> checkValidEntries() const;
    };

} /* namespace Synchronization */

#endif /* INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_ */
<commit_msg>Apply code style<commit_after>/*
 * RingBufferSubHistory.h
 *
 *  Created on: 20.05.2016
 *      Author: hartung
 */

#ifndef INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_
#define INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_

#include "Stdafx.hpp"
#include "BasicTypedefs.hpp"
#include "synchronization/HistoryEntry.hpp"
#include "synchronization/Interpolation.hpp"

namespace Synchronization
{

    class RingBufferSubHistory
    {
     public:

        size_type size() const;

        real_type getNewestTime() const;

        FMI::ValueCollection interpolate(const real_type & time);

        FMI::ValueCollection operator[](const real_type & time);

        const Interpolation& getInterpolation() const;

        friend class AbstractDataHistory;

     private:
        size_type _curIndex;
        size_type _lastInsertedElem;
        std::vector<HistoryEntry> _entries;
        Interpolation _interpolation;

        size_type _numAddedElems;

        RingBufferSubHistory() = delete;

        RingBufferSubHistory(const Interpolation & interpolation, const FMI::ValueCollection & bufferScheme,
                             size_type size = 300);

        bool_type insert(const HistoryEntry & in);

        size_type deleteOlderThan(const HistoryEntry & in);

        /**
         * Check, if _numAddedElems is greater than 1 and returns ...
         * Otherwise, an exception is thrown.
         */
        tuple<size_type, size_type> checkValidEntries() const;
    };

} /* namespace Synchronization */

#endif /* INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_ */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: canvasgraphichelper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-17 15:23:50 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _CPPCANVAS_CANVASGRAPHICHELPER_HXX
#define _CPPCANVAS_CANVASGRAPHICHELPER_HXX

#include <com/sun/star/rendering/RenderState.hpp>
#include <basegfx/polygon/b2dpolypolygon.hxx>

#include <cppcanvas/canvasgraphic.hxx>

#include <boost/optional.hpp>

namespace com { namespace sun { namespace star { namespace rendering
{
    class  XGraphicDevice;
} } } }

/* Definition of CanvasGraphicHelper class */

namespace cppcanvas
{

    namespace internal
    {

        class CanvasGraphicHelper : public virtual CanvasGraphic
        {
        public:
            CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas );

            // CanvasGraphic implementation
            virtual void                             setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );
            virtual ::basegfx::B2DHomMatrix          getTransformation() const;
            virtual void                             setClip( const ::basegfx::B2DPolyPolygon& rClipPoly );
            virtual void                             setClip();
            virtual ::basegfx::B2DPolyPolygon const* getClip() const;
            virtual void                             setRGBAColor( Color::IntSRGBA );
            virtual Color::IntSRGBA                  getRGBAColor() const;
            virtual void                             setCompositeOp( CompositeOp aOp );
            virtual CompositeOp                      getCompositeOp() const;

        protected:
            // for our clients
            // ===============
            CanvasSharedPtr                                                                 getCanvas() const;
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > getGraphicDevice() const;
            const ::com::sun::star::rendering::RenderState&                                 getRenderState() const;

        private:
            mutable ::com::sun::star::rendering::RenderState                                maRenderState;

            boost::optional<basegfx::B2DPolyPolygon>                                        maClipPolyPolygon;
            CanvasSharedPtr                                                                 mpCanvas;
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > mxGraphicDevice;
        };

    }
}

#endif /* _CPPCANVAS_CANVASGRAPHICHELPER_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/03/31 13:07:07 rt 1.6.22.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: canvasgraphichelper.hxx,v $
 * $Revision: 1.7 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _CPPCANVAS_CANVASGRAPHICHELPER_HXX
#define _CPPCANVAS_CANVASGRAPHICHELPER_HXX

#include <com/sun/star/rendering/RenderState.hpp>
#include <basegfx/polygon/b2dpolypolygon.hxx>

#include <cppcanvas/canvasgraphic.hxx>

#include <boost/optional.hpp>

namespace com { namespace sun { namespace star { namespace rendering
{
    class  XGraphicDevice;
} } } }

/* Definition of CanvasGraphicHelper class */

namespace cppcanvas
{

    namespace internal
    {

        class CanvasGraphicHelper : public virtual CanvasGraphic
        {
        public:
            CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas );

            // CanvasGraphic implementation
            virtual void                             setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );
            virtual ::basegfx::B2DHomMatrix          getTransformation() const;
            virtual void                             setClip( const ::basegfx::B2DPolyPolygon& rClipPoly );
            virtual void                             setClip();
            virtual ::basegfx::B2DPolyPolygon const* getClip() const;
            virtual void                             setRGBAColor( Color::IntSRGBA );
            virtual Color::IntSRGBA                  getRGBAColor() const;
            virtual void                             setCompositeOp( CompositeOp aOp );
            virtual CompositeOp                      getCompositeOp() const;

        protected:
            // for our clients
            // ===============
            CanvasSharedPtr                                                                 getCanvas() const;
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > getGraphicDevice() const;
            const ::com::sun::star::rendering::RenderState&                                 getRenderState() const;

        private:
            mutable ::com::sun::star::rendering::RenderState                                maRenderState;

            boost::optional<basegfx::B2DPolyPolygon>                                        maClipPolyPolygon;
            CanvasSharedPtr                                                                 mpCanvas;
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > mxGraphicDevice;
        };

    }
}

#endif /* _CPPCANVAS_CANVASGRAPHICHELPER_HXX */
<|endoftext|>