<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.


   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.
*/

/**
  \file    RAWConverter.cpp
  \author  <NAME>
           SCI Institute
           University of Utah
  \date    December 2008
*/
#include "Basics/StdDefines.h"
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <list>
#include "3rdParty/bzip2/bzlib.h"

#include "RAWConverter.h"
#include "Basics/nonstd.h"
#include "Basics/SysTools.h"
#include "Basics/SystemInfo.h"
#include "IO/gzio.h"
#include "UVF/Histogram1DDataBlock.h"
#include "UVF/Histogram2DDataBlock.h"
#include "UVF/MaxMinDataBlock.h"
#include "UVF/RasterDataBlock.h"
#include "UVF/KeyValuePairDataBlock.h"
#include "UVF/TOCBlock.h"
#include "UVF/UVF.h"
#include "TuvokIOError.h"
#include "Quantize.h"

using namespace std;
using namespace tuvok;

// holds UVF data blocks, because they cannot be deleted until the UVF file is
// written.
struct TimestepBlocks {
  std::shared_ptr<TOCBlock> tocblock;
  std::shared_ptr<RasterDataBlock> rdb;

  std::shared_ptr<MaxMinDataBlock> maxmin;
  std::shared_ptr<Histogram2DDataBlock> hist2d;
};

namespace {
  template<typename Target>
  void change_endianness(unsigned char* buffer,
                         size_t bytes_read) {
    Target* buf = reinterpret_cast<Target*>(buffer);
    const size_t N = bytes_read / sizeof(Target);
    std::transform(buf, buf+N, buf, EndianConvert::Swap<Target>);
  }
}

static std::string convert_endianness(const std::string& strFilename,
                                      const std::string& strTempDir,
                                      uint64_t iHeaderSkip,
                                      size_t iComponentSize,
                                      size_t in_core_size)
{
  using namespace tuvok::io;
  if(iComponentSize != 16 && iComponentSize != 32 && iComponentSize != 64) {
    T_ERROR("Unable to endian convert anything but 16-, 32-, and 64-bit data"
            "  (input data is %d-bit).", iComponentSize);
    return "";
  }

  LargeRAWFile WrongEndianData(strFilename, iHeaderSkip);
  WrongEndianData.Open(false);

  if(!WrongEndianData.IsOpen()) {
    T_ERROR("Unable to open source file '%s'", strFilename.c_str());
    throw DSOpenFailed(strFilename.c_str(), "Unable to open source file",
                       __FILE__, __LINE__);
  }

  const std::string tmp_file = strTempDir + SysTools::GetFilename(strFilename) +
                               ".endianness";
  LargeRAWFile ConvertedEndianData(tmp_file);
  ConvertedEndianData.Create();

  if(!ConvertedEndianData.IsOpen()) {
    WrongEndianData.Close();
    throw DSOpenFailed(tmp_file.c_str(), "Unable to create file",
                       __FILE__, __LINE__);
  }
  MESSAGE("Performing endianness conversion ...");

  uint64_t byte_length = WrongEndianData.GetCurrentSize();
  size_t buffer_size = std::min<size_t>(static_cast<size_t>(byte_length),
                                        static_cast<size_t>(in_core_size));
  uint64_t bytes_converted = 0;

  std::shared_ptr<unsigned char> buffer(
    new unsigned char[buffer_size],
    nonstd::DeleteArray<unsigned char>()
  );

  while(bytes_converted < byte_length) {
    using namespace boost;
    size_t bytes_read = WrongEndianData.ReadRAW(buffer.get(), buffer_size);
    switch(iComponentSize) {
      case 16: change_endianness<uint16_t>(buffer.get(), bytes_read); break;
      case 32: change_endianness<float>(buffer.get(), bytes_read); break;
      case 64: change_endianness<double>(buffer.get(), bytes_read); break;
    }
    size_t bytes_written = ConvertedEndianData.WriteRAW(buffer.get(),
                                                        bytes_read);
    if(bytes_read != bytes_written) {
      WrongEndianData.Close();
      ConvertedEndianData.Close();
      remove(tmp_file.c_str());
      throw IOException("Write failed during endianness conversion.", __FILE__,
                        __LINE__);
    }
    bytes_converted += static_cast<uint64_t>(bytes_written);

    MESSAGE("Performing endianness conversion"
            "\n%i%% complete",
            int(float(bytes_converted) / float(byte_length)*100.0f));
  }
  WrongEndianData.Close();
  ConvertedEndianData.Close();

  return tmp_file;
}

// A TempFile is an RAII LargeRAWFile, which deletes itself when it
// goes out of scope.  There shouldn't be any need to explicitly delete
// it, but you can do so early with the 'Delete' call, if desired.
class TempFile : public LargeRAWFile {
public:
  TempFile(const std::string& filename) : LargeRAWFile(filename, 0) {}
  virtual ~TempFile() {
    MESSAGE("Deleting temporary file %s", this->GetFilename().c_str());
    Close();
    Delete();
  }
};

static std::shared_ptr<KeyValuePairDataBlock> metadata(
  const string& strDesc, const string& strSource,
  bool bLittleEndian, bool bSigned, bool bIsFloat,
  size_t iComponentSize,
  KVPairs* pKVPairs
)
{
  std::shared_ptr<KeyValuePairDataBlock> meta =
    std::shared_ptr<KeyValuePairDataBlock>(new KeyValuePairDataBlock());

  if(!strSource.empty()) { meta->AddPair("Data Source", strSource); }
  if(!strDesc.empty()) { meta->AddPair("Description", strDesc); }

  if(bLittleEndian) {
    meta->AddPair("Source Endianness", "little");
  } else {
    meta->AddPair("Source Endianness", "big");
  }

  if(bIsFloat) {
    meta->AddPair("Source Type", "float");
  } else {
    if(bSigned) {<commit_msg>Rely on the TempFile in Basics.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.


   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.
*/

/**
  \file    RAWConverter.cpp
  \author  <NAME>
           SCI Institute
           University of Utah
  \date    December 2008
*/
#include "Basics/StdDefines.h"
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <list>
#include "3rdParty/bzip2/bzlib.h"

#include "RAWConverter.h"
#include "Basics/nonstd.h"
#include "Basics/SysTools.h"
#include "Basics/SystemInfo.h"
#include "IO/gzio.h"
#include "UVF/Histogram1DDataBlock.h"
#include "UVF/Histogram2DDataBlock.h"
#include "UVF/MaxMinDataBlock.h"
#include "UVF/RasterDataBlock.h"
#include "UVF/KeyValuePairDataBlock.h"
#include "UVF/TOCBlock.h"
#include "UVF/UVF.h"
#include "TuvokIOError.h"
#include "Quantize.h"

using namespace std;
using namespace tuvok;

// holds UVF data blocks, because they cannot be deleted until the UVF file is
// written.
struct TimestepBlocks {
  std::shared_ptr<TOCBlock> tocblock;
  std::shared_ptr<RasterDataBlock> rdb;

  std::shared_ptr<MaxMinDataBlock> maxmin;
  std::shared_ptr<Histogram2DDataBlock> hist2d;
};

namespace {
  template<typename Target>
  void change_endianness(unsigned char* buffer,
                         size_t bytes_read) {
    Target* buf = reinterpret_cast<Target*>(buffer);
    const size_t N = bytes_read / sizeof(Target);
    std::transform(buf, buf+N, buf, EndianConvert::Swap<Target>);
  }
}

static std::string convert_endianness(const std::string& strFilename,
                                      const std::string& strTempDir,
                                      uint64_t iHeaderSkip,
                                      size_t iComponentSize,
                                      size_t in_core_size)
{
  using namespace tuvok::io;
  if(iComponentSize != 16 && iComponentSize != 32 && iComponentSize != 64) {
    T_ERROR("Unable to endian convert anything but 16-, 32-, and 64-bit data"
            "  (input data is %d-bit).", iComponentSize);
    return "";
  }

  LargeRAWFile WrongEndianData(strFilename, iHeaderSkip);
  WrongEndianData.Open(false);

  if(!WrongEndianData.IsOpen()) {
    T_ERROR("Unable to open source file '%s'", strFilename.c_str());
    throw DSOpenFailed(strFilename.c_str(), "Unable to open source file",
                       __FILE__, __LINE__);
  }

  const std::string tmp_file = strTempDir + SysTools::GetFilename(strFilename) +
                               ".endianness";
  LargeRAWFile ConvertedEndianData(tmp_file);
  ConvertedEndianData.Create();

  if(!ConvertedEndianData.IsOpen()) {
    WrongEndianData.Close();
    throw DSOpenFailed(tmp_file.c_str(), "Unable to create file",
                       __FILE__, __LINE__);
  }
  MESSAGE("Performing endianness conversion ...");

  uint64_t byte_length = WrongEndianData.GetCurrentSize();
  size_t buffer_size = std::min<size_t>(static_cast<size_t>(byte_length),
                                        static_cast<size_t>(in_core_size));
  uint64_t bytes_converted = 0;

  std::shared_ptr<unsigned char> buffer(
    new unsigned char[buffer_size],
    nonstd::DeleteArray<unsigned char>()
  );

  while(bytes_converted < byte_length) {
    using namespace boost;
    size_t bytes_read = WrongEndianData.ReadRAW(buffer.get(), buffer_size);
    switch(iComponentSize) {
      case 16: change_endianness<uint16_t>(buffer.get(), bytes_read); break;
      case 32: change_endianness<float>(buffer.get(), bytes_read); break;
      case 64: change_endianness<double>(buffer.get(), bytes_read); break;
    }
    size_t bytes_written = ConvertedEndianData.WriteRAW(buffer.get(),
                                                        bytes_read);
    if(bytes_read != bytes_written) {
      WrongEndianData.Close();
      ConvertedEndianData.Close();
      remove(tmp_file.c_str());
      throw IOException("Write failed during endianness conversion.", __FILE__,
                        __LINE__);
    }
    bytes_converted += static_cast<uint64_t>(bytes_written);

    MESSAGE("Performing endianness conversion"
            "\n%i%% complete",
            int(float(bytes_converted) / float(byte_length)*100.0f));
  }
  WrongEndianData.Close();
  ConvertedEndianData.Close();

  return tmp_file;
}

static std::shared_ptr<KeyValuePairDataBlock> metadata(
  const string& strDesc, const string& strSource,
  bool bLittleEndian, bool bSigned, bool bIsFloat,
  size_t iComponentSize,
  KVPairs* pKVPairs
)
{
  std::shared_ptr<KeyValuePairDataBlock> meta =
    std::shared_ptr<KeyValuePairDataBlock>(new KeyValuePairDataBlock());

  if(!strSource.empty()) { meta->AddPair("Data Source", strSource); }
  if(!strDesc.empty()) { meta->AddPair("Description", strDesc); }

  if(bLittleEndian) {
    meta->AddPair("Source Endianness", "little");
  } else {
    meta->AddPair("Source Endianness", "big");
  }

  if(bIsFloat) {
    meta->AddPair("Source Type", "float");
  } else {
    if(bSigned) {
{'fraction_non_alphanumeric': 0.10503937007874016, 'fraction_numerical': 0.007480314960629921, 'mean_word_length': 3.3706125258086717, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 64, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '605588', 'n_tokens_mistral': 3983, 'n_tokens_neox': 3784, 'n_words': 1040}