<commit_before>#include <errno.h>
#include <stdio.h>
#include <getopt.h>
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <ctime>

#include "scan.h"

using namespace std;

int main(int argc, char* argv[]) {
  unsigned int dim = 1;
  int opt;
  bool output = true;
  int mockSize = 0;
  istream_iterator<double> start, end;
  vector<double> nums;

  while ((opt = getopt(argc, argv, "nd:m:")) != -1) {
    switch (opt) {
      case 'n': // no output
        output = false;
        break;
      case 'd':
        dim = atoi(optarg);
        break;
      case 'm': // mock input, requires the number of megabytes
        mockSize = atoi(optarg);
        break;
      default: /* '?' */
        cerr << "USAGE: " << argv[0]
          << " [-d dimensionality]"
          << " [-n]"
          << endl;
        exit(EXIT_FAILURE);
    }
  }

  if (mockSize) {
    nums = vector<double>(mockSize * dim * (1 << 20));
  } else {
    start = istream_iterator<double>(cin);
    nums = vector<double>(start, end);
  }

  clock_t startTime = clock();
  parScan((void*) &nums[0],
          nums.size() / dim,
          sizeof nums[0] * dim,
          addition(dim));
  clock_t endTime = clock();

  // check if fd #3 is open, if so, write the processor time taken in seconds
  lseek(3, 0, SEEK_CUR);
  if (errno != EBADF) {
    FILE* timeOut = fdopen(3, "w");
    fprintf(timeOut, "%f",
        ((double) endTime - (double) startTime) / (double) CLOCKS_PER_SEC);
  }

  if (output) {
    for (vector<double>::size_type i = 0; i != nums.size(); ++i) {
      cout << nums[i];
      if (i % dim == dim - 1)
        cout << endl;
      else
        cout << ' ';
    }
  }

  return 0;
}

<commit_msg>don't write to fd 3 on ESPIPE<commit_after>#include <errno.h>
#include <stdio.h>
#include <getopt.h>
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <ctime>

#include <string.h>

#include "scan.h"

using namespace std;

int main(int argc, char* argv[]) {
  unsigned int dim = 1;
  int opt;
  bool output = true;
  int mockSize = 0;
  istream_iterator<double> start, end;
  vector<double> nums;

  while ((opt = getopt(argc, argv, "nd:m:")) != -1) {
    switch (opt) {
      case 'n': // no output
        output = false;
        break;
      case 'd':
        dim = atoi(optarg);
        break;
      case 'm': // mock input, requires the number of megabytes
        mockSize = atoi(optarg);
        break;
      default: /* '?' */
        cerr << "USAGE: " << argv[0]
          << " [-d dimensionality]"
          << " [-n]"
          << endl;
        exit(EXIT_FAILURE);
    }
  }

  if (mockSize) {
    nums = vector<double>(mockSize * dim * (1 << 20));
  } else {
    start = istream_iterator<double>(cin);
    nums = vector<double>(start, end);
  }

  clock_t startTime = clock();
  parScan((void*) &nums[0],
          nums.size() / dim,
          sizeof nums[0] * dim,
          addition(dim));
  clock_t endTime = clock();

  // check if fd #3 is open, if so, write the processor time taken in seconds
  lseek(3, 0, SEEK_CUR);
  if (errno != EBADF && errno != ESPIPE) {
    FILE* timeOut = fdopen(3, "w");
    fprintf(timeOut, "%f",
        ((double) endTime - (double) startTime) / (double) CLOCKS_PER_SEC);
  }

  if (output) {
    for (vector<double>::size_type i = 0; i != nums.size(); ++i) {
      cout << nums[i];
      if (i % dim == dim - 1)
        cout << endl;
      else
        cout << ' ';
    }
  }

  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_paths_internal.h"

#include <knownfolders.h>
#include <shellapi.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <windows.h>

#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/win/scoped_co_mem.h"
#include "chrome/common/chrome_constants.h"

namespace chrome {

namespace {

// Generic function to call SHGetFolderPath().
bool GetUserDirectory(int csidl_folder, base::FilePath* result) {
  // We need to go compute the value. It would be nice to support paths
  // with names longer than MAX_PATH, but the system functions don't seem
  // to be designed for it either, with the exception of GetTempPath
  // (but other things will surely break if the temp path is too long,
  // so we don't bother handling it.
  wchar_t path_buf[MAX_PATH];
  path_buf[0] = 0;
  if (FAILED(SHGetFolderPath(NULL, csidl_folder, NULL, SHGFP_TYPE_CURRENT,
                             path_buf))) {
    return false;
  }
  *result = base::FilePath(path_buf);
  return true;
}

}  // namespace

bool GetDefaultUserDataDirectory(base::FilePath* result) {
  return PathService::Get(base::DIR_LOCAL_APP_DATA, result);
}

void GetUserCacheDirectory(const base::FilePath& profile_dir,
                           base::FilePath* result) {
  // This function does more complicated things on Mac/Linux.
  *result = profile_dir;
}

bool GetUserDocumentsDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYDOCUMENTS, result);
}

// Return a default path for downloads that is safe.
// We just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
// 'downloads' is not a good idea because Chrome's UI language
// can be changed.
bool GetUserDownloadsDirectorySafe(base::FilePath* result) {
  if (!GetUserDocumentsDirectory(result))
    return false;

  *result = result->Append(L"Downloads");
  return true;
}

// On Vista and higher, use the downloads known folder. Since it can be
// relocated to point to a "dangerous" folder, callers should validate that the
// returned path is not dangerous before using it.
bool GetUserDownloadsDirectory(base::FilePath* result) {
  typedef HRESULT(WINAPI * GetKnownFolderPath)(REFKNOWNFOLDERID, DWORD, HANDLE,
                                               PWSTR*);
  GetKnownFolderPath f = reinterpret_cast<GetKnownFolderPath>(
      GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetKnownFolderPath"));
  base::win::ScopedCoMem<wchar_t> path_buf;
  if (f && SUCCEEDED(f(FOLDERID_Downloads, 0, NULL, &path_buf))) {
    *result = base::FilePath(std::wstring(path_buf));
    return true;
  }
  return GetUserDownloadsDirectorySafe(result);
}

bool GetUserMusicDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYMUSIC, result);
}

bool GetUserPicturesDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYPICTURES, result);
}

bool GetUserVideosDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYVIDEO, result);
}

bool ProcessNeedsProfileDir(const std::string& process_type) {
  // On windows we don't want subprocesses other than the browser process and
  // service processes to be able to use the profile directory because if it
  // lies on a network share the sandbox will prevent us from accessing it.

  if (process_type.empty())
    return true;

  return false;
}

}  // namespace chrome
<commit_msg>force windows above other includes<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_paths_internal.h"

#include <windows.h>

#include <knownfolders.h>
#include <shellapi.h>
#include <shlobj.h>
#include <shobjidl.h>

#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/win/scoped_co_mem.h"
#include "chrome/common/chrome_constants.h"

namespace chrome {

namespace {

// Generic function to call SHGetFolderPath().
bool GetUserDirectory(int csidl_folder, base::FilePath* result) {
  // We need to go compute the value. It would be nice to support paths
  // with names longer than MAX_PATH, but the system functions don't seem
  // to be designed for it either, with the exception of GetTempPath
  // (but other things will surely break if the temp path is too long,
  // so we don't bother handling it.
  wchar_t path_buf[MAX_PATH];
  path_buf[0] = 0;
  if (FAILED(SHGetFolderPath(NULL, csidl_folder, NULL, SHGFP_TYPE_CURRENT,
                             path_buf))) {
    return false;
  }
  *result = base::FilePath(path_buf);
  return true;
}

}  // namespace

bool GetDefaultUserDataDirectory(base::FilePath* result) {
  return PathService::Get(base::DIR_LOCAL_APP_DATA, result);
}

void GetUserCacheDirectory(const base::FilePath& profile_dir,
                           base::FilePath* result) {
  // This function does more complicated things on Mac/Linux.
  *result = profile_dir;
}

bool GetUserDocumentsDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYDOCUMENTS, result);
}

// Return a default path for downloads that is safe.
// We just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
// 'downloads' is not a good idea because Chrome's UI language
// can be changed.
bool GetUserDownloadsDirectorySafe(base::FilePath* result) {
  if (!GetUserDocumentsDirectory(result))
    return false;

  *result = result->Append(L"Downloads");
  return true;
}

// On Vista and higher, use the downloads known folder. Since it can be
// relocated to point to a "dangerous" folder, callers should validate that the
// returned path is not dangerous before using it.
bool GetUserDownloadsDirectory(base::FilePath* result) {
  typedef HRESULT(WINAPI * GetKnownFolderPath)(REFKNOWNFOLDERID, DWORD, HANDLE,
                                               PWSTR*);
  GetKnownFolderPath f = reinterpret_cast<GetKnownFolderPath>(
      GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetKnownFolderPath"));
  base::win::ScopedCoMem<wchar_t> path_buf;
  if (f && SUCCEEDED(f(FOLDERID_Downloads, 0, NULL, &path_buf))) {
    *result = base::FilePath(std::wstring(path_buf));
    return true;
  }
  return GetUserDownloadsDirectorySafe(result);
}

bool GetUserMusicDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYMUSIC, result);
}

bool GetUserPicturesDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYPICTURES, result);
}

bool GetUserVideosDirectory(base::FilePath* result) {
  return GetUserDirectory(CSIDL_MYVIDEO, result);
}

bool ProcessNeedsProfileDir(const std::string& process_type) {
  // On windows we don't want subprocesses other than the browser process and
  // service processes to be able to use the profile directory because if it
  // lies on a network share the sandbox will prevent us from accessing it.

  if (process_type.empty())
    return true;

  return false;
}

}  // namespace chrome
<|endoftext|>


<commit_before>//===--- NoMallocCheck.cpp - clang-tidy------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "NoMallocCheck.h"
#include "../utils/Matchers.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <algorithm>
#include <string>
#include <vector>

using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;

namespace clang {
namespace tidy {
namespace cppcoreguidelines {

namespace {
Matcher<FunctionDecl> hasAnyListedName(const std::string &FunctionNames) {
  const std::vector<std::string> NameList =
      utils::options::parseStringList(FunctionNames);
  return hasAnyName(std::vector<StringRef>(NameList.begin(), NameList.end()));
}
} // namespace

void NoMallocCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "Allocations", AllocList);
  Options.store(Opts, "Reallocations", ReallocList);
  Options.store(Opts, "Deallocations", DeallocList);
}

void NoMallocCheck::registerMatchers(MatchFinder *Finder) {
  // C-style memory management is only problematic in C++.
  if (!getLangOpts().CPlusPlus)
    return;

  // Registering malloc, will suggest RAII.
  Finder->addMatcher(callExpr(callee(functionDecl(hasAnyListedName(AllocList))))
                         .bind("allocation"),
                     this);

  // Registering realloc calls, suggest std::vector or std::string.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasAnyListedName(ReallocList))))
          .bind("realloc"),
      this);

  // Registering free calls, will suggest RAII instead.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasAnyListedName(DeallocList))))
          .bind("free"),
      this);
}

void NoMallocCheck::check(const MatchFinder::MatchResult &Result) {
  const CallExpr *Call = nullptr;
  StringRef Recommendation;

  if ((Call = Result.Nodes.getNodeAs<CallExpr>("allocation")))
    Recommendation = "consider a container or a smart pointer";
  else if ((Call = Result.Nodes.getNodeAs<CallExpr>("realloc")))
    Recommendation = "consider std::vector or std::string";
  else if ((Call = Result.Nodes.getNodeAs<CallExpr>("free")))
    Recommendation = "use RAII";

  assert(Call && "Unhandled binding in the Matcher");

  diag(Call->getLocStart(), "do not manage memory manually; %0")
      << Recommendation << SourceRange(Call->getLocStart(), Call->getLocEnd());
}

} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang
<commit_msg>Removed Unicode BOM.<commit_after>//===--- NoMallocCheck.cpp - clang-tidy------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "NoMallocCheck.h"
#include "../utils/Matchers.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <algorithm>
#include <string>
#include <vector>

using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;

namespace clang {
namespace tidy {
namespace cppcoreguidelines {

namespace {
Matcher<FunctionDecl> hasAnyListedName(const std::string &FunctionNames) {
  const std::vector<std::string> NameList =
      utils::options::parseStringList(FunctionNames);
  return hasAnyName(std::vector<StringRef>(NameList.begin(), NameList.end()));
}
} // namespace

void NoMallocCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "Allocations", AllocList);
  Options.store(Opts, "Reallocations", ReallocList);
  Options.store(Opts, "Deallocations", DeallocList);
}

void NoMallocCheck::registerMatchers(MatchFinder *Finder) {
  // C-style memory management is only problematic in C++.
  if (!getLangOpts().CPlusPlus)
    return;

  // Registering malloc, will suggest RAII.
  Finder->addMatcher(callExpr(callee(functionDecl(hasAnyListedName(AllocList))))
                         .bind("allocation"),
                     this);

  // Registering realloc calls, suggest std::vector or std::string.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasAnyListedName(ReallocList))))
          .bind("realloc"),
      this);

  // Registering free calls, will suggest RAII instead.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasAnyListedName(DeallocList))))
          .bind("free"),
      this);
}

void NoMallocCheck::check(const MatchFinder::MatchResult &Result) {
  const CallExpr *Call = nullptr;
  StringRef Recommendation;

  if ((Call = Result.Nodes.getNodeAs<CallExpr>("allocation")))
    Recommendation = "consider a container or a smart pointer";
  else if ((Call = Result.Nodes.getNodeAs<CallExpr>("realloc")))
    Recommendation = "consider std::vector or std::string";
  else if ((Call = Result.Nodes.getNodeAs<CallExpr>("free")))
    Recommendation = "use RAII";

  assert(Call && "Unhandled binding in the Matcher");

  diag(Call->getLocStart(), "do not manage memory manually; %0")
      << Recommendation << SourceRange(Call->getLocStart(), Call->getLocEnd());
}

} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>/** @file
 *
 *  OpenSSL socket BIO that does TCP Fast Open.
 *
 *  @section license License
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "P_Net.h"
#include "I_SocketManager.h"
#include "tscore/ink_assert.h"

#include "BIO_fastopen.h"

// For BoringSSL, which for some reason doesn't have this function.
// (In BoringSSL, sock_read() and sock_write() use the internal
// bio_fd_non_fatal_error() instead.) #1437
//
// The following is copied from
// https://github.com/openssl/openssl/blob/3befffa39dbaf2688d823fcf2bdfc07d2487be48/crypto/bio/bss_sock.c
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
#ifndef HAVE_BIO_SOCK_NON_FATAL_ERROR
int
BIO_sock_non_fatal_error(int err)
{
  switch (err) {
#if defined(OPENSSL_SYS_WINDOWS)
#if defined(WSAEWOULDBLOCK)
  case WSAEWOULDBLOCK:
#endif
#endif

#ifdef EWOULDBLOCK
#ifdef WSAEWOULDBLOCK
#if WSAEWOULDBLOCK != EWOULDBLOCK
  case EWOULDBLOCK:
#endif
#else
  case EWOULDBLOCK:
#endif
#endif

#if defined(ENOTCONN)
  case ENOTCONN:
#endif

#ifdef EINTR
  case EINTR:
#endif

#ifdef EAGAIN
#if EWOULDBLOCK != EAGAIN
  case EAGAIN:
#endif
#endif

#ifdef EPROTO
  case EPROTO:
#endif

#ifdef EINPROGRESS
  case EINPROGRESS:
#endif

#ifdef EALREADY
  case EALREADY:
#endif
    return (1);
  /* break; */
  default:
    break;
  }
  return (0);
}
#endif

static int (*fastopen_create)(BIO *) = BIO_meth_get_create(const_cast<BIO_METHOD *>(BIO_s_socket()));

static int
fastopen_destroy(BIO *bio)
{
  if (bio) {
    // We expect this BIO to not own the socket, so we must always
    // be in NOCLOSE mode.
    ink_assert(BIO_get_shutdown(bio) == BIO_NOCLOSE);
  }

  return BIO_meth_get_destroy(const_cast<BIO_METHOD *>(BIO_s_socket()))(bio);
}

static int
fastopen_bwrite(BIO *bio, const char *in, int insz)
{
  int64_t err;

  errno = 0;
  BIO_clear_retry_flags(bio);
  int fd = BIO_get_fd(bio, nullptr);
  ink_assert(fd != NO_FD);

  if (BIO_get_data(bio)) {
    // On the first write only, make a TFO request if TFO is enabled.
    // The best documentation on the behavior of the Linux API is in
    // RFC 7413. If we get EINPROGRESS it means that the SYN has been
    // sent without data and we should retry.
    const sockaddr *dst = reinterpret_cast<const sockaddr *>(BIO_get_data(bio));
    ProxyMutex *mutex   = this_ethread()->mutex.get();

    NET_INCREMENT_DYN_STAT(net_fastopen_attempts_stat);

    err = socketManager.sendto(fd, (void *)in, insz, MSG_FASTOPEN, dst, ats_ip_size(dst));
    if (err >= 0) {
      NET_INCREMENT_DYN_STAT(net_fastopen_successes_stat);
    }

    BIO_set_data(bio, nullptr);
  } else {
    err = socketManager.write(fd, (void *)in, insz);
  }

  if (err < 0) {
    errno = -err;
    if (BIO_sock_non_fatal_error(errno)) {
      BIO_set_retry_write(bio);
    }
  }

  return err < 0 ? -1 : err;
}

static int
fastopen_bread(BIO *bio, char *out, int outsz)
{
  int64_t err;

  errno = 0;
  BIO_clear_retry_flags(bio);
  int fd = BIO_get_fd(bio, nullptr);
  ink_assert(fd != NO_FD);

  // TODO: If we haven't done the fastopen, ink_abort().

  err = socketManager.read(fd, out, outsz);
  if (err < 0) {
    errno = -err;
    if (BIO_sock_non_fatal_error(errno)) {
      BIO_set_retry_write(bio);
    }
  }

  return err < 0 ? -1 : err;
}

static long
fastopen_ctrl(BIO *bio, int cmd, long larg, void *ptr)
{
  switch (cmd) {
  case BIO_C_SET_CONNECT:
    // We only support BIO_set_conn_address(), which sets a sockaddr.
    ink_assert(larg == 2);
    BIO_set_data(bio, ptr);
    return 0;
  }

  return BIO_meth_get_ctrl(const_cast<BIO_METHOD *>(BIO_s_socket()))(bio, cmd, larg, ptr);
}

#ifndef HAVE_BIO_METH_NEW
static const BIO_METHOD fastopen_methods[] = {{
  .type          = BIO_TYPE_SOCKET,
  .name          = "fastopen",
  .bwrite        = fastopen_bwrite,
  .bread         = fastopen_bread,
  .bputs         = nullptr,
  .bgets         = nullptr,
  .ctrl          = fastopen_ctrl,
  .create        = fastopen_create,
  .destroy       = fastopen_destroy,
  .callback_ctrl = nullptr,
}};
#else
static const BIO_METHOD *fastopen_methods = [] {
  BIO_METHOD *methods = BIO_meth_new(BIO_TYPE_SOCKET, "fastopen");
  BIO_meth_set_write(methods, fastopen_bwrite);
  BIO_meth_set_read(methods, fastopen_bread);
  BIO_meth_set_ctrl(methods, fastopen_ctrl);
  BIO_meth_set_create(methods, fastopen_create);
  BIO_meth_set_destroy(methods, fastopen_destroy);
  return methods;
}();
#endif

const BIO_METHOD *
BIO_s_fastopen()
{
  return fastopen_methods;
}
<commit_msg>Retry read when fastopen_bread() get non fatal error (#6841)<commit_after>/** @file
 *
 *  OpenSSL socket BIO that does TCP Fast Open.
 *
 *  @section license License
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "P_Net.h"
#include "I_SocketManager.h"
#include "tscore/ink_assert.h"

#include "BIO_fastopen.h"

// For BoringSSL, which for some reason doesn't have this function.
// (In BoringSSL, sock_read() and sock_write() use the internal
// bio_fd_non_fatal_error() instead.) #1437
//
// The following is copied from
// https://github.com/openssl/openssl/blob/3befffa39dbaf2688d823fcf2bdfc07d2487be48/crypto/bio/bss_sock.c
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
#ifndef HAVE_BIO_SOCK_NON_FATAL_ERROR
int
BIO_sock_non_fatal_error(int err)
{
  switch (err) {
#if defined(OPENSSL_SYS_WINDOWS)
#if defined(WSAEWOULDBLOCK)
  case WSAEWOULDBLOCK:
#endif
#endif

#ifdef EWOULDBLOCK
#ifdef WSAEWOULDBLOCK
#if WSAEWOULDBLOCK != EWOULDBLOCK
  case EWOULDBLOCK:
#endif
#else
  case EWOULDBLOCK:
#endif
#endif

#if defined(ENOTCONN)
  case ENOTCONN:
#endif

#ifdef EINTR
  case EINTR:
#endif

#ifdef EAGAIN
#if EWOULDBLOCK != EAGAIN
  case EAGAIN:
#endif
#endif

#ifdef EPROTO
  case EPROTO:
#endif

#ifdef EINPROGRESS
  case EINPROGRESS:
#endif

#ifdef EALREADY
  case EALREADY:
#endif
    return (1);
  /* break; */
  default:
    break;
  }
  return (0);
}
#endif

static int (*fastopen_create)(BIO *) = BIO_meth_get_create(const_cast<BIO_METHOD *>(BIO_s_socket()));

static int
fastopen_destroy(BIO *bio)
{
  if (bio) {
    // We expect this BIO to not own the socket, so we must always
    // be in NOCLOSE mode.
    ink_assert(BIO_get_shutdown(bio) == BIO_NOCLOSE);
  }

  return BIO_meth_get_destroy(const_cast<BIO_METHOD *>(BIO_s_socket()))(bio);
}

static int
fastopen_bwrite(BIO *bio, const char *in, int insz)
{
  int64_t err;

  errno = 0;
  BIO_clear_retry_flags(bio);
  int fd = BIO_get_fd(bio, nullptr);
  ink_assert(fd != NO_FD);

  if (BIO_get_data(bio)) {
    // On the first write only, make a TFO request if TFO is enabled.
    // The best documentation on the behavior of the Linux API is in
    // RFC 7413. If we get EINPROGRESS it means that the SYN has been
    // sent without data and we should retry.
    const sockaddr *dst = reinterpret_cast<const sockaddr *>(BIO_get_data(bio));
    ProxyMutex *mutex   = this_ethread()->mutex.get();

    NET_INCREMENT_DYN_STAT(net_fastopen_attempts_stat);

    err = socketManager.sendto(fd, (void *)in, insz, MSG_FASTOPEN, dst, ats_ip_size(dst));
    if (err >= 0) {
      NET_INCREMENT_DYN_STAT(net_fastopen_successes_stat);
    }

    BIO_set_data(bio, nullptr);
  } else {
    err = socketManager.write(fd, (void *)in, insz);
  }

  if (err < 0) {
    errno = -err;
    if (BIO_sock_non_fatal_error(errno)) {
      BIO_set_retry_write(bio);
    }
  }

  return err < 0 ? -1 : err;
}

static int
fastopen_bread(BIO *bio, char *out, int outsz)
{
  int64_t err;

  errno = 0;
  BIO_clear_retry_flags(bio);
  int fd = BIO_get_fd(bio, nullptr);
  ink_assert(fd != NO_FD);

  // TODO: If we haven't done the fastopen, ink_abort().

  err = socketManager.read(fd, out, outsz);
  if (err < 0) {
    errno = -err;
    if (BIO_sock_non_fatal_error(errno)) {
      BIO_set_retry_read(bio);
    }
  }

  return err < 0 ? -1 : err;
}

static long
fastopen_ctrl(BIO *bio, int cmd, long larg, void *ptr)
{
  switch (cmd) {
  case BIO_C_SET_CONNECT:
    // We only support BIO_set_conn_address(), which sets a sockaddr.
    ink_assert(larg == 2);
    BIO_set_data(bio, ptr);
    return 0;
  }

  return BIO_meth_get_ctrl(const_cast<BIO_METHOD *>(BIO_s_socket()))(bio, cmd, larg, ptr);
}

#ifndef HAVE_BIO_METH_NEW
static const BIO_METHOD fastopen_methods[] = {{
  .type          = BIO_TYPE_SOCKET,
  .name          = "fastopen",
  .bwrite        = fastopen_bwrite,
  .bread         = fastopen_bread,
  .bputs         = nullptr,
  .bgets         = nullptr,
  .ctrl          = fastopen_ctrl,
  .create        = fastopen_create,
  .destroy       = fastopen_destroy,
  .callback_ctrl = nullptr,
}};
#else
static const BIO_METHOD *fastopen_methods = [] {
  BIO_METHOD *methods = BIO_meth_new(BIO_TYPE_SOCKET, "fastopen");
  BIO_meth_set_write(methods, fastopen_bwrite);
  BIO_meth_set_read(methods, fastopen_bread);
  BIO_meth_set_ctrl(methods, fastopen_ctrl);
  BIO_meth_set_create(methods, fastopen_create);
  BIO_meth_set_destroy(methods, fastopen_destroy);
  return methods;
}();
#endif

const BIO_METHOD *
BIO_s_fastopen()
{
  return fastopen_methods;
}
<|endoftext|>


<commit_before>#include "CApplication.h"

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include <iomanip>

#include "CEventManager.h"
#include "CStateManager.h"

static GLFWwindow * window;

CApplication::CApplication()
	: StateManager(0),
	SceneManager(0),
	EventManager(0)
{}

void CApplication::setupRenderContext(std::string const & WindowTitle)
{
	if (! glfwInit())
	{
		std::cerr << "Error initializing glfw! " << std::endl;
		WaitForUser();
		exit(33);
	}

	glfwWindowHint(GLFW_RESIZABLE, false);
	if (! (window = glfwCreateWindow(WindowSize.X, WindowSize.Y, WindowTitle.c_str(), 0, 0)))
	{
		std::cerr << "Error opening glfw window! " << std::endl;
		WaitForUser();
		exit(33);
	}
	glfwMakeContextCurrent(window);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::cerr << "Error initializing glew! " << glewGetErrorString(err) << std::endl;
		WaitForUser();
		exit(33);
	}

	double const VersionNumber = std::atof((char const *)glGetString(GL_VERSION));
	if (VersionNumber < 2.0)
	{
		std::cerr << "Your OpenGL Version Number (" << std::setprecision(2) << VersionNumber <<
			") is not high enough for shaders. Please download and install the latest drivers"
			"for your graphics hardware." <<
			std::endl << std::endl;
	}

	std::cerr << "Your OpenGL Version Number: " << std::setprecision(2) << VersionNumber << std::endl << std::endl;
}

EKey const ConvertGLFWKeyCode(int const Code)
{
	if (Code >= 'A' && Code <= 'Z')
		return EKey::A + (Code - 'A');

	if (Code >= GLFW_KEY_KP_0 && Code <= GLFW_KEY_KP_9)
		return EKey::KeyPad0 + (Code - GLFW_KEY_KP_0);
	if (Code >= '0' && Code <= '9')
		return EKey::Num0 + (Code - '0');

	switch (Code)
	{

	case '[':
		return EKey::LeftBracket;
	case ']':
		return EKey::RightBracket;
	case ',':
		return EKey::Comma;
	case '.':
		return EKey::Period;
	case ';':
		return EKey::Semicolon;
	case '\'':
		return EKey::Quote;

	case GLFW_KEY_ESCAPE:
		return EKey::Escape;

	case GLFW_KEY_UP:
		return EKey::Up;
	case GLFW_KEY_LEFT:
		return EKey::Left;
	case GLFW_KEY_DOWN:
		return EKey::Down;
	case GLFW_KEY_RIGHT:
		return EKey::Right;

	case GLFW_KEY_SPACE:
		return EKey::Space;

	case GLFW_KEY_LEFT_SHIFT:
		return EKey::LeftShift;
	case GLFW_KEY_RIGHT_SHIFT:
		return EKey::RightShift;
	case GLFW_KEY_LEFT_CONTROL:
		return EKey::LeftControl;
	case GLFW_KEY_RIGHT_CONTROL:
		return EKey::RightControl;
	case GLFW_KEY_LEFT_ALT:
		return EKey::LeftAlt;
	case GLFW_KEY_RIGHT_ALT:
		return EKey::RightAlt;

	default:
		return EKey::Unknown;

	};
}

void CApplication::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods)
{
	CApplication & Application = CApplication::get();

	SKeyboardEvent KeyEvent;
	KeyEvent.Pressed = action == GLFW_PRESS;
	KeyEvent.Key = ConvertGLFWKeyCode(key);
	Application.EventManager->OnKeyboardEvent(KeyEvent);
	Application.EventManager->KeyStates[KeyEvent.Key] = KeyEvent.Pressed;
}

void CApplication::MouseButtonCallback(GLFWwindow * window, int button, int action, int mods)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Click;
	MouseEvent.Location = CApplication::get().EventManager->MouseLocation;
	MouseEvent.Pressed = action == GLFW_PRESS;

	switch (button)
	{

	case GLFW_MOUSE_BUTTON_LEFT:
		MouseEvent.Button = SMouseEvent::EButton::Left;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Left] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	case GLFW_MOUSE_BUTTON_RIGHT:
		MouseEvent.Button = SMouseEvent::EButton::Right;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Right] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	case GLFW_MOUSE_BUTTON_MIDDLE:
		MouseEvent.Button = SMouseEvent::EButton::Middle;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Middle] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	default:
		break;

	}
}

void CApplication::MouseScrollCallback(GLFWwindow * window, double xoffset, double yoffset)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Scroll;
	MouseEvent.Movement = vec2d(xoffset, yoffset);
	if (CApplication::get().EventManager)
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
}

void CApplication::MouseCursorCallback(GLFWwindow * window, double xpos, double ypos)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Move;
	MouseEvent.Location = vec2d(xpos, ypos);

	if (CApplication::get().EventManager)
		CApplication::get().EventManager->MousePositionState = MouseEvent.Location;

	MouseEvent.Movement = MouseEvent.Location - CApplication::get().LastMouse;

	if (CApplication::get().EventManager)
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);

	CApplication::get().LastMouse = MouseEvent.Location;
}

void CApplication::init(vec2i const & windowSize, std::string const & WindowTitle)
{
	WindowSize = windowSize;

	setupRenderContext(WindowTitle);

	// TO DO : Engines need to be initialized at this point so that callbacks that access the eventmananger don't fail.

	glfwSetKeyCallback(window, CApplication::KeyCallback);
	glfwSetMouseButtonCallback(window, CApplication::MouseButtonCallback);
	glfwSetCursorPosCallback(window, CApplication::MouseCursorCallback);
	glfwSetScrollCallback(window, CApplication::MouseScrollCallback);
}

void CApplication::loadEngines()
{
	EventManager = new CEventManager();
	StateManager = new CStateManager();
	SceneManager = new CSceneManager(WindowSize);
}

CApplication & CApplication::get()
{
	static CApplication SingletonInstance;

	return SingletonInstance;
}

CEventManager & CApplication::getEventManager()
{
	return * EventManager;
}

CStateManager & CApplication::getStateManager()
{
	return * StateManager;
}

CSceneManager & CApplication::getSceneManager()
{
	return * SceneManager;
}

void CApplication::skipElapsedTime()
{
	Time0 = glfwGetTime();
}

void CApplication::updateTime()
{
	Time1 = glfwGetTime();
	ElapsedTime = /*min(0.1, */(Time1 - Time0);//);
	RunTime += ElapsedTime;
	Time0 = Time1;
}

void CApplication::run()
{
	Running = true;

	Time0 = glfwGetTime();

	RunTime = ElapsedTime = 0.f;

	glfwMakeContextCurrent(window);

	while (Running && ! glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		/*sf::Event Event;
		while (App->pollEvent(Event))
		{
			EventManager->OnSFMLEvent(Event);
			switch (Event.type)
			{

			case sf::Event::Closed:
				Running = false;
				break;

			case sf::Event::Resized:
				{

					SWindowResizedEvent WindowEvent;
					WindowEvent.Size.X = Event.size.width;
					WindowEvent.Size.Y = Event.size.height;
					WindowSize = WindowEvent.Size;
					EventManager->OnWindowResized(WindowEvent);
					SceneManager->OnWindowResized(WindowSize);

					App->setView(sf::View(sf::FloatRect(0, 0, (float) Event.size.width, (float) Event.size.height)));

					break;

				}
			} // switch (Event.type)
		} // while (SDL_PollEvent(& Event))*/

		updateTime();

		EventManager->OnGameTickStart((f32) ElapsedTime);
		EventManager->OnGameTickEnd((f32) ElapsedTime);

		EventManager->OnRenderStart((f32) ElapsedTime);
		EventManager->OnRenderEnd((f32) ElapsedTime);

		StateManager->doStateChange();

	} // while (Running)

	StateManager->shutDown();
	glfwTerminate();
}

f64 CApplication::getElapsedTime() const
{
	return ElapsedTime;
}

f64 CApplication::getRunTime() const
{
	return RunTime;
}

float const CApplication::getAspectRatio()
{
	return (float) WindowSize.X / (float) WindowSize.Y;
}

vec2i const & CApplication::getWindowSize() const
{
	return WindowSize;
}

bool CApplication::isShuttingDown() const
{
	return ! Running;
}

void CApplication::close()
{
	Running = false;
}

void CApplication::swapBuffers()
{
	glfwSwapBuffers(window);
}
<commit_msg>+ Fixed key press events being released<commit_after>#include "CApplication.h"

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include <iomanip>

#include "CEventManager.h"
#include "CStateManager.h"

static GLFWwindow * window;

CApplication::CApplication()
	: StateManager(0),
	SceneManager(0),
	EventManager(0)
{}

void CApplication::setupRenderContext(std::string const & WindowTitle)
{
	if (! glfwInit())
	{
		std::cerr << "Error initializing glfw! " << std::endl;
		WaitForUser();
		exit(33);
	}

	glfwWindowHint(GLFW_RESIZABLE, false);
	if (! (window = glfwCreateWindow(WindowSize.X, WindowSize.Y, WindowTitle.c_str(), 0, 0)))
	{
		std::cerr << "Error opening glfw window! " << std::endl;
		WaitForUser();
		exit(33);
	}
	glfwMakeContextCurrent(window);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::cerr << "Error initializing glew! " << glewGetErrorString(err) << std::endl;
		WaitForUser();
		exit(33);
	}

	double const VersionNumber = std::atof((char const *) glGetString(GL_VERSION));
	if (VersionNumber < 2.0)
	{
		std::cerr << "Your OpenGL Version Number (" << std::setprecision(2) << VersionNumber <<
			") is not high enough for shaders. Please download and install the latest drivers"
			"for your graphics hardware." <<
			std::endl << std::endl;
	}

	std::cerr << "Your OpenGL Version Number: " << std::setprecision(2) << VersionNumber << std::endl << std::endl;
}

EKey const ConvertGLFWKeyCode(int const Code)
{
	if (Code >= 'A' && Code <= 'Z')
		return EKey::A + (Code - 'A');

	if (Code >= GLFW_KEY_KP_0 && Code <= GLFW_KEY_KP_9)
		return EKey::KeyPad0 + (Code - GLFW_KEY_KP_0);
	if (Code >= '0' && Code <= '9')
		return EKey::Num0 + (Code - '0');

	switch (Code)
	{

	case '[':
		return EKey::LeftBracket;
	case ']':
		return EKey::RightBracket;
	case ',':
		return EKey::Comma;
	case '.':
		return EKey::Period;
	case ';':
		return EKey::Semicolon;
	case '\'':
		return EKey::Quote;

	case GLFW_KEY_ESCAPE:
		return EKey::Escape;

	case GLFW_KEY_UP:
		return EKey::Up;
	case GLFW_KEY_LEFT:
		return EKey::Left;
	case GLFW_KEY_DOWN:
		return EKey::Down;
	case GLFW_KEY_RIGHT:
		return EKey::Right;

	case GLFW_KEY_SPACE:
		return EKey::Space;

	case GLFW_KEY_LEFT_SHIFT:
		return EKey::LeftShift;
	case GLFW_KEY_RIGHT_SHIFT:
		return EKey::RightShift;
	case GLFW_KEY_LEFT_CONTROL:
		return EKey::LeftControl;
	case GLFW_KEY_RIGHT_CONTROL:
		return EKey::RightControl;
	case GLFW_KEY_LEFT_ALT:
		return EKey::LeftAlt;
	case GLFW_KEY_RIGHT_ALT:
		return EKey::RightAlt;

	default:
		return EKey::Unknown;

	};
}

void CApplication::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods)
{
	CApplication & Application = CApplication::get();

	SKeyboardEvent KeyEvent;
	KeyEvent.Pressed = action != GLFW_RELEASE;
	KeyEvent.Key = ConvertGLFWKeyCode(key);
	Application.EventManager->OnKeyboardEvent(KeyEvent);
	Application.EventManager->KeyStates[KeyEvent.Key] = KeyEvent.Pressed;
}

void CApplication::MouseButtonCallback(GLFWwindow * window, int button, int action, int mods)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Click;
	MouseEvent.Location = CApplication::get().EventManager->MouseLocation;
	MouseEvent.Pressed = action == GLFW_PRESS;

	switch (button)
	{

	case GLFW_MOUSE_BUTTON_LEFT:
		MouseEvent.Button = SMouseEvent::EButton::Left;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Left] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	case GLFW_MOUSE_BUTTON_RIGHT:
		MouseEvent.Button = SMouseEvent::EButton::Right;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Right] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	case GLFW_MOUSE_BUTTON_MIDDLE:
		MouseEvent.Button = SMouseEvent::EButton::Middle;
		CApplication::get().EventManager->MouseStates[SMouseEvent::EButton::Middle] = MouseEvent.Pressed;
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
		break;

	default:
		break;

	}
}

void CApplication::MouseScrollCallback(GLFWwindow * window, double xoffset, double yoffset)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Scroll;
	MouseEvent.Movement = vec2d(xoffset, yoffset);
	if (CApplication::get().EventManager)
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);
}

void CApplication::MouseCursorCallback(GLFWwindow * window, double xpos, double ypos)
{
	SMouseEvent MouseEvent;
	MouseEvent.Type = SMouseEvent::EType::Move;
	MouseEvent.Location = vec2d(xpos, ypos);

	if (CApplication::get().EventManager)
		CApplication::get().EventManager->MousePositionState = MouseEvent.Location;

	MouseEvent.Movement = MouseEvent.Location - CApplication::get().LastMouse;

	if (CApplication::get().EventManager)
		CApplication::get().EventManager->OnMouseEvent(MouseEvent);

	CApplication::get().LastMouse = MouseEvent.Location;
}

void CApplication::init(vec2i const & windowSize, std::string const & WindowTitle)
{
	WindowSize = windowSize;

	setupRenderContext(WindowTitle);

	// TO DO : Engines need to be initialized at this point so that callbacks that access the eventmananger don't fail.

	glfwSetKeyCallback(window, CApplication::KeyCallback);
	glfwSetMouseButtonCallback(window, CApplication::MouseButtonCallback);
	glfwSetCursorPosCallback(window, CApplication::MouseCursorCallback);
	glfwSetScrollCallback(window, CApplication::MouseScrollCallback);
}

void CApplication::loadEngines()
{
	EventManager = new CEventManager();
	StateManager = new CStateManager();
	SceneManager = new CSceneManager(WindowSize);
}

CApplication & CApplication::get()
{
	static CApplication SingletonInstance;

	return SingletonInstance;
}

CEventManager & CApplication::getEventManager()
{
	return * EventManager;
}

CStateManager & CApplication::getStateManager()
{
	return * StateManager;
}

CSceneManager & CApplication::getSceneManager()
{
	return * SceneManager;
}

void CApplication::skipElapsedTime()
{
	Time0 = glfwGetTime();
}

void CApplication::updateTime()
{
	Time1 = glfwGetTime();
	ElapsedTime = /*min(0.1, */(Time1 - Time0);//);
	RunTime += ElapsedTime;
	Time0 = Time1;
}

void CApplication::run()
{
	Running = true;

	Time0 = glfwGetTime();

	RunTime = ElapsedTime = 0.f;

	glfwMakeContextCurrent(window);

	while (Running && ! glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		/*sf::Event Event;
		while (App->pollEvent(Event))
		{
			EventManager->OnSFMLEvent(Event);
			switch (Event.type)
			{

			case sf::Event::Closed:
				Running = false;
				break;

			case sf::Event::Resized:
				{

					SWindowResizedEvent WindowEvent;
					WindowEvent.Size.X = Event.size.width;
					WindowEvent.Size.Y = Event.size.height;
					WindowSize = WindowEvent.Size;
					EventManager->OnWindowResized(WindowEvent);
					SceneManager->OnWindowResized(WindowSize);

					App->setView(sf::View(sf::FloatRect(0, 0, (float) Event.size.width, (float) Event.size.height)));

					break;

				}
			} // switch (Event.type)
		} // while (SDL_PollEvent(& Event))*/

		updateTime();

		EventManager->OnGameTickStart((f32) ElapsedTime);
		EventManager->OnGameTickEnd((f32) ElapsedTime);

		EventManager->OnRenderStart((f32) ElapsedTime);
		EventManager->OnRenderEnd((f32) ElapsedTime);

		StateManager->doStateChange();

	} // while (Running)

	StateManager->shutDown();
	glfwTerminate();
}

f64 CApplication::getElapsedTime() const
{
	return ElapsedTime;
}

f64 CApplication::getRunTime() const
{
	return RunTime;
}

float const CApplication::getAspectRatio()
{
	return (float) WindowSize.X / (float) WindowSize.Y;
}

vec2i const & CApplication::getWindowSize() const
{
	return WindowSize;
}

bool CApplication::isShuttingDown() const
{
	return ! Running;
}

void CApplication::close()
{
	Running = false;
}

void CApplication::swapBuffers()
{
	glfwSwapBuffers(window);
}
<|endoftext|>


<commit_before>#include "drake/systems/framework/primitives/constant_source.h"

#include <memory>
#include <stdexcept>
#include <string>

#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/system_input.h"

#include "gtest/gtest.h"

using Eigen::Vector2d;
using std::make_unique;

namespace drake {
namespace systems {
namespace {

class ConstantSourceTest : public ::testing::Test {
 protected:
  void SetUp() override {
    source_ = make_unique<ConstantSource<double>>(kConstantSource_);
    context_ = source_->CreateDefaultContext();
    output_ = source_->AllocateOutput(*context_);
    input_ = make_unique<BasicVector<double>>(3 /* length */);
  }

  // TODO(amcastro-tri): Create a diagram with a ConstantVectorSource feeding
  // the input of the ConstantSource system.
  static std::unique_ptr<FreestandingInputPort<double>> MakeInput(
      std::unique_ptr<BasicVector<double>> data) {
    return make_unique<FreestandingInputPort<double>>(std::move(data));
  }

  const Vector2d kConstantSource_{2.0, 1.5};
  std::unique_ptr<ConstantSource<double>> source_;
  std::unique_ptr<ContextBase<double>> context_;
  std::unique_ptr<SystemOutput<double>> output_;
  std::unique_ptr<BasicVector<double>> input_;
};

TEST_F(ConstantSourceTest, OutputTest) {
  // TODO(amcastro-tri): we should be able to ask:
  // source_->num_of_input_ports().
  ASSERT_EQ(0, context_->get_num_input_ports());
  // TODO(amcastro-tri): we should be able to ask:
  // source_->num_of_output_ports().
  ASSERT_EQ(1, output_->get_num_ports());

  source_->EvalOutput(*context_, output_.get());

  // TODO(amcastro-tri): we should be able to ask something like:
  // auto& source_->get_output_vector(context, 0);
  // to directly get an Eigen expression.
  const BasicVector<double>* output_vector =
      dynamic_cast<const BasicVector<double>*>(
          output_->get_port(0).get_vector_data());
  ASSERT_NE(nullptr, output_vector);
  EXPECT_EQ(kConstantSource_, output_vector->get_value());
}

// Tests that inputs cannot be set for a ConstantSource.
TEST_F(ConstantSourceTest, ShouldNotBePossibleToConnectInputs) {
  EXPECT_THROW(context_->SetInputPort(0, MakeInput(std::move(input_))),
               std::out_of_range);
}

// Tests that ConstantSource allocates no state variables in the context_.
TEST_F(ConstantSourceTest, ConstantSourceIsStateless) {
  EXPECT_EQ(nullptr, context_->get_state().continuous_state);
}

}  // namespace
}  // namespace systems
}  // namespace drake
<commit_msg>Replaces EXPECT_EQ with isApprox<commit_after>#include "drake/systems/framework/primitives/constant_source.h"

#include <memory>
#include <stdexcept>
#include <string>

#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/system_input.h"

#include "gtest/gtest.h"

using Eigen::Vector2d;
using std::make_unique;

namespace drake {
namespace systems {
namespace {

class ConstantSourceTest : public ::testing::Test {
 protected:
  void SetUp() override {
    source_ = make_unique<ConstantSource<double>>(kConstantSource_);
    context_ = source_->CreateDefaultContext();
    output_ = source_->AllocateOutput(*context_);
    input_ = make_unique<BasicVector<double>>(3 /* length */);
  }

  // TODO(amcastro-tri): Create a diagram with a ConstantVectorSource feeding
  // the input of the ConstantSource system.
  static std::unique_ptr<FreestandingInputPort<double>> MakeInput(
      std::unique_ptr<BasicVector<double>> data) {
    return make_unique<FreestandingInputPort<double>>(std::move(data));
  }

  const Vector2d kConstantSource_{2.0, 1.5};
  std::unique_ptr<ConstantSource<double>> source_;
  std::unique_ptr<ContextBase<double>> context_;
  std::unique_ptr<SystemOutput<double>> output_;
  std::unique_ptr<BasicVector<double>> input_;
};

TEST_F(ConstantSourceTest, OutputTest) {
  // TODO(amcastro-tri): we should be able to ask:
  // source_->num_of_input_ports().
  ASSERT_EQ(0, context_->get_num_input_ports());
  // TODO(amcastro-tri): we should be able to ask:
  // source_->num_of_output_ports().
  ASSERT_EQ(1, output_->get_num_ports());

  source_->EvalOutput(*context_, output_.get());

  // TODO(amcastro-tri): we should be able to ask something like:
  // auto& source_->get_output_vector(context, 0);
  // to directly get an Eigen expression.
  const BasicVector<double>* output_vector =
      dynamic_cast<const BasicVector<double>*>(
          output_->get_port(0).get_vector_data());
  ASSERT_NE(nullptr, output_vector);
  EXPECT_TRUE(kConstantSource_.isApprox(output_vector->get_value(),
                                        Eigen::NumTraits<double>::epsilon()));
}

// Tests that inputs cannot be set for a ConstantSource.
TEST_F(ConstantSourceTest, ShouldNotBePossibleToConnectInputs) {
  EXPECT_THROW(context_->SetInputPort(0, MakeInput(std::move(input_))),
               std::out_of_range);
}

// Tests that ConstantSource allocates no state variables in the context_.
TEST_F(ConstantSourceTest, ConstantSourceIsStateless) {
  EXPECT_EQ(nullptr, context_->get_state().continuous_state);
}

}  // namespace
}  // namespace systems
}  // namespace drake
<|endoftext|>


<commit_before>//
// Created by Andy Chase on 5/10/16.
//

#include <math.h>
#include "globals.h"
#include "agents.h"
#include "randf.h"
#include <iostream>

void GrainDeer(GrainState *grainState) {
    int nextNumDeer;
    while (grainState->year <= 2021) {
        nextNumDeer = grainState->numDeer;
        // The Carrying Capacity of the graindeer is the number of inches of height of the grain.
        int capacity = (int) floor(grainState->height);
        // If the number of graindeer exceeds this value at the end of a month, decrease the number of graindeer by one.
        if (capacity < grainState->numDeer)
            nextNumDeer--;
            // If the number of graindeer is less than this value at the end of a month,
            // increase the number of graindeer by one.
        else if (capacity > grainState->numDeer)
            nextNumDeer++;

        // DoneComputing barrier:
#pragma omp barrier
        grainState->numDeer = nextNumDeer;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Grain(GrainState *grainState) {
    float nextHeight;
    struct GrainState nextState;
    while (grainState->year <= 2021) {
        nextHeight = grainState->height;
        nextState = CalcTempAndPrecip(grainState);
        // Each month you will need to figure out how much the grain grows.
        // If conditions are good, it will grow by GRAIN_GROWS_PER_MONTH.
        // If conditions are not good, it won't.

        // You know how good conditions are by seeing how close you are to an ideal temperature (°F)
        // and precipitation (inches).
        // Do this by computing a Temperature Factor and a Precipitation Factor like this:
        float midTemp = (grainState->temp + nextState.temp) / 2;
        float midPrecip = (grainState->precip + nextState.precip) / 2;
        float tempFactor = exp(exp2(-(grainState->temp - midTemp / 10)));

        float precipFactor = exp(exp2(-(grainState->precip - midPrecip / 10)));

        // You then use tempFactor and precipFactor like this:
        nextHeight += tempFactor * precipFactor * GRAIN_GROWS_PER_MONTH;
        nextHeight -= (float) grainState->numDeer * ONE_DEER_EATS_PER_MONTH;
        //Be sure to clamp NowHeight against zero.
        nextHeight = max(nextHeight, 0.0f);

        // DoneComputing barrier:
#pragma omp barrier
        grainState->height = nextHeight;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Watcher(GrainState *grainState) {
    struct GrainState nextState;
    while (grainState->year <= 2021) {
        // compute a temporary next-value for this quantity based on the current state of the simulation:
        nextState = CalcTempAndPrecip(grainState);

        // DoneComputing barrier:
#pragma omp barrier
        ;

        // DoneAssigning barrier:
#pragma omp barrier
        std::cout <<
        "Year: " << nextState.year << "\n" <<
        "Month:" << nextState.month << "\n" <<
        "Precip: " << nextState.precip << "\n" <<
        "Temp: " << nextState.temp << "\n" <<
        "Height: " << nextState.height << "\n" <<
        "NumDeer: " << nextState.numDeer << "\n\n";
        grainState->temp = nextState.temp;
        grainState->precip = nextState.precip;
        grainState->month = nextState.month;
        grainState->year = nextState.year;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Disease(GrainState *grainState) {
    while (grainState->year <= 2021) {
        // compute a temporary next-value for this quantity based on the current state of the simulation:
        ;

        // DoneComputing barrier:
#pragma omp barrier
        ;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

struct GrainState CalcTempAndPrecip(struct GrainState *grainState) {
    struct GrainState nextState = *grainState;
    float ang = (float) ((30. * (float) grainState->month + 15.) * (M_PI / 180.f));

    float temp = AVG_TEMP - AMP_TEMP * cos(ang);
    nextState.temp = temp + Ranf(-RANDOM_TEMP, RANDOM_TEMP);

    float precip = AVG_PRECIP_PER_MONTH + AMP_PRECIP_PER_MONTH * sin(ang);
    nextState.precip = precip + Ranf(-RANDOM_PRECIP, RANDOM_PRECIP);
    if (nextState.precip < 0.)
        nextState.precip = 0.f;
    if (nextState.month > 11) {
        nextState.month = 0;
        nextState.year++;
    } else {
        nextState.month++;
    }

    return nextState;
}
<commit_msg>Convert results to csv format<commit_after>//
// Created by Andy Chase on 5/10/16.
//

#include <math.h>
#include "globals.h"
#include "agents.h"
#include "randf.h"
#include <iostream>

void GrainDeer(GrainState *grainState) {
    int nextNumDeer;
    while (grainState->year <= 2021) {
        nextNumDeer = grainState->numDeer;
        // The Carrying Capacity of the graindeer is the number of inches of height of the grain.
        int capacity = (int) floor(grainState->height);
        // If the number of graindeer exceeds this value at the end of a month, decrease the number of graindeer by one.
        if (capacity < grainState->numDeer)
            nextNumDeer--;
            // If the number of graindeer is less than this value at the end of a month,
            // increase the number of graindeer by one.
        else if (capacity > grainState->numDeer)
            nextNumDeer++;

        // DoneComputing barrier:
#pragma omp barrier
        grainState->numDeer = nextNumDeer;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Grain(GrainState *grainState) {
    float nextHeight;
    struct GrainState nextState;
    while (grainState->year <= 2021) {
        nextHeight = grainState->height;
        nextState = CalcTempAndPrecip(grainState);
        // Each month you will need to figure out how much the grain grows.
        // If conditions are good, it will grow by GRAIN_GROWS_PER_MONTH.
        // If conditions are not good, it won't.

        // You know how good conditions are by seeing how close you are to an ideal temperature (°F)
        // and precipitation (inches).
        // Do this by computing a Temperature Factor and a Precipitation Factor like this:
        float midTemp = (grainState->temp + nextState.temp) / 2;
        float midPrecip = (grainState->precip + nextState.precip) / 2;
        float tempFactor = exp(exp2(-(grainState->temp - midTemp / 10)));

        float precipFactor = exp(exp2(-(grainState->precip - midPrecip / 10)));

        // You then use tempFactor and precipFactor like this:
        nextHeight += tempFactor * precipFactor * GRAIN_GROWS_PER_MONTH;
        nextHeight -= (float) grainState->numDeer * ONE_DEER_EATS_PER_MONTH;
        //Be sure to clamp NowHeight against zero.
        nextHeight = max(nextHeight, 0.0f);

        // DoneComputing barrier:
#pragma omp barrier
        grainState->height = nextHeight;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Watcher(GrainState *grainState) {
    struct GrainState nextState;
    std::cout <<
    "Year" << "," <<
    "Month" << "," <<
    "Precip" << "," <<
    "Temp" << "," <<
    "Height" << "," <<
    "NumDeer" << "\n";

    while (grainState->year <= 2021) {
        // compute a temporary next-value for this quantity based on the current state of the simulation:
        nextState = CalcTempAndPrecip(grainState);

        // DoneComputing barrier:
#pragma omp barrier
        ;

        // DoneAssigning barrier:
#pragma omp barrier
        std::cout <<
        nextState.year << "," <<
        nextState.month << "," <<
        nextState.precip << "," <<
        nextState.temp << "," <<
        nextState.height << "," <<
        nextState.numDeer << "\n";

        grainState->temp = nextState.temp;
        grainState->precip = nextState.precip;
        grainState->month = nextState.month;
        grainState->year = nextState.year;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

void Disease(GrainState *grainState) {
    while (grainState->year <= 2021) {
        // compute a temporary next-value for this quantity based on the current state of the simulation:
        ;

        // DoneComputing barrier:
#pragma omp barrier
        ;

        // DoneAssigning barrier:
#pragma omp barrier
        ;

        // DonePrinting barrier:
#pragma omp barrier
        ;
    }
}

struct GrainState CalcTempAndPrecip(struct GrainState *grainState) {
    struct GrainState nextState = *grainState;
    float ang = (float) ((30. * (float) grainState->month + 15.) * (M_PI / 180.f));

    float temp = AVG_TEMP - AMP_TEMP * cos(ang);
    nextState.temp = temp + Ranf(-RANDOM_TEMP, RANDOM_TEMP);

    float precip = AVG_PRECIP_PER_MONTH + AMP_PRECIP_PER_MONTH * sin(ang);
    nextState.precip = precip + Ranf(-RANDOM_PRECIP, RANDOM_PRECIP);
    if (nextState.precip < 0.)
        nextState.precip = 0.f;
    if (nextState.month > 11) {
        nextState.month = 0;
        nextState.year++;
    } else {
        nextState.month++;
    }

    return nextState;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"

#include <string>

#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/window_list.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "brightray/browser/brightray_paths.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "net/ssl/ssl_cert_request_info.h"

namespace atom {

Browser::Browser()
    : is_quiting_(false),
      is_ready_(false),
      is_shutdown_(false),
      process_notify_callback_set_(false) {
  WindowList::AddObserver(this);
}

Browser::~Browser() {
  WindowList::RemoveObserver(this);
}

// static
Browser* Browser::Get() {
  return AtomBrowserMainParts::Get()->browser();
}

void Browser::Quit() {
  if (is_quiting_)
    return;

  is_quiting_ = HandleBeforeQuit();
  if (!is_quiting_)
    return;

  atom::WindowList* window_list = atom::WindowList::GetInstance();
  if (window_list->size() == 0)
    NotifyAndShutdown();

  window_list->CloseAllWindows();
}

void Browser::Shutdown() {
  if (is_shutdown_)
    return;

  is_shutdown_ = true;
  is_quiting_ = true;

  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnQuit());
  base::MessageLoop::current()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
}

std::string Browser::GetVersion() const {
  if (version_override_.empty()) {
    std::string version = GetExecutableFileVersion();
    if (!version.empty())
      return version;
  }

  return version_override_;
}

void Browser::SetVersion(const std::string& version) {
  version_override_ = version;
}

std::string Browser::GetName() const {
  if (name_override_.empty()) {
    std::string name = GetExecutableFileProductName();
    if (!name.empty())
      return name;
  }

  return name_override_;
}

void Browser::SetName(const std::string& name) {
  name_override_ = name;

#if defined(OS_WIN)
  SetAppUserModelID(name);
#endif
}

bool Browser::OpenFile(const std::string& file_path) {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnOpenFile(&prevent_default, file_path));

  return prevent_default;
}

void Browser::OpenURL(const std::string& url) {
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnOpenURL(url));
}

void Browser::Activate(bool has_visible_windows) {
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnActivate(has_visible_windows));
}

void Browser::WillFinishLaunching() {
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWillFinishLaunching());
}

void Browser::DidFinishLaunching() {
  is_ready_ = true;
  process_singleton_->Unlock();
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnFinishLaunching());
}

void Browser::ClientCertificateSelector(
    content::WebContents* web_contents,
    net::SSLCertRequestInfo* cert_request_info,
    scoped_ptr<content::ClientCertificateDelegate> delegate) {
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnSelectCertificate(web_contents,
                                        cert_request_info,
                                        delegate.Pass()));
}

void Browser::NotifyAndShutdown() {
  if (is_shutdown_)
    return;

  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWillQuit(&prevent_default));

  if (prevent_default) {
    is_quiting_ = false;
    return;
  }

  process_singleton_->Cleanup();
  Shutdown();
}

bool Browser::HandleBeforeQuit() {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnBeforeQuit(&prevent_default));

  return !prevent_default;
}

void Browser::InitializeSingleInstance() {
  base::FilePath userDir;
  PathService::Get(brightray::DIR_USER_DATA, &userDir);

  auto no_refcount_this = base::Unretained(this);
  process_singleton_.reset(new AtomProcessSingleton(
    userDir,
    base::Bind(&Browser::OnProcessSingletonNotification, no_refcount_this)));

  process_notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
}

ProcessSingleton::NotifyResult Browser::GetSingleInstanceResult() {
  LOG(ERROR) << "Process Notify Result: " << process_notify_result_;
  return process_notify_result_;
}

void Browser::SetSingleInstanceCallback(
    ProcessSingleton::NotificationCallback callback) {
  process_notify_callback_ = callback;
  process_notify_callback_set_ = true;
}

void Browser::OnWindowCloseCancelled(NativeWindow* window) {
  if (is_quiting_)
    // Once a beforeunload handler has prevented the closing, we think the quit
    // is cancelled too.
    is_quiting_ = false;
}

void Browser::OnWindowAllClosed() {
  if (is_quiting_)
    NotifyAndShutdown();
  else
    FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed());
}

bool Browser::OnProcessSingletonNotification(
    const base::CommandLine& command_line,
    const base::FilePath& current_directory) {
  if (process_notify_callback_set_) {
    return process_notify_callback_.Run(command_line, current_directory);
  } else {
    return true;    // We'll handle this, not a different process
  }
}

}  // namespace atom
<commit_msg>Since setting up process_singleton is now conditional, its cleanup / unlock must be too<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"

#include <string>

#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/window_list.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "brightray/browser/brightray_paths.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "net/ssl/ssl_cert_request_info.h"

namespace atom {

Browser::Browser()
    : is_quiting_(false),
      is_ready_(false),
      is_shutdown_(false),
      process_notify_callback_set_(false) {
  WindowList::AddObserver(this);
}

Browser::~Browser() {
  WindowList::RemoveObserver(this);
}

// static
Browser* Browser::Get() {
  return AtomBrowserMainParts::Get()->browser();
}

void Browser::Quit() {
  if (is_quiting_)
    return;

  is_quiting_ = HandleBeforeQuit();
  if (!is_quiting_)
    return;

  atom::WindowList* window_list = atom::WindowList::GetInstance();
  if (window_list->size() == 0)
    NotifyAndShutdown();

  window_list->CloseAllWindows();
}

void Browser::Shutdown() {
  if (is_shutdown_)
    return;

  is_shutdown_ = true;
  is_quiting_ = true;

  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnQuit());
  base::MessageLoop::current()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
}

std::string Browser::GetVersion() const {
  if (version_override_.empty()) {
    std::string version = GetExecutableFileVersion();
    if (!version.empty())
      return version;
  }

  return version_override_;
}

void Browser::SetVersion(const std::string& version) {
  version_override_ = version;
}

std::string Browser::GetName() const {
  if (name_override_.empty()) {
    std::string name = GetExecutableFileProductName();
    if (!name.empty())
      return name;
  }

  return name_override_;
}

void Browser::SetName(const std::string& name) {
  name_override_ = name;

#if defined(OS_WIN)
  SetAppUserModelID(name);
#endif
}

bool Browser::OpenFile(const std::string& file_path) {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnOpenFile(&prevent_default, file_path));

  return prevent_default;
}

void Browser::OpenURL(const std::string& url) {
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnOpenURL(url));
}

void Browser::Activate(bool has_visible_windows) {
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnActivate(has_visible_windows));
}

void Browser::WillFinishLaunching() {
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWillFinishLaunching());
}

void Browser::DidFinishLaunching() {
  is_ready_ = true;

  if (process_notify_callback_set_) {
    process_singleton_->Unlock();
  }

  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnFinishLaunching());
}

void Browser::ClientCertificateSelector(
    content::WebContents* web_contents,
    net::SSLCertRequestInfo* cert_request_info,
    scoped_ptr<content::ClientCertificateDelegate> delegate) {
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnSelectCertificate(web_contents,
                                        cert_request_info,
                                        delegate.Pass()));
}

void Browser::NotifyAndShutdown() {
  if (is_shutdown_)
    return;

  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWillQuit(&prevent_default));

  if (prevent_default) {
    is_quiting_ = false;
    return;
  }

  if (process_notify_callback_set_) {
    process_singleton_->Cleanup();
  }

  Shutdown();
}

bool Browser::HandleBeforeQuit() {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(BrowserObserver,
                    observers_,
                    OnBeforeQuit(&prevent_default));

  return !prevent_default;
}

void Browser::InitializeSingleInstance() {
  base::FilePath userDir;
  PathService::Get(brightray::DIR_USER_DATA, &userDir);

  auto no_refcount_this = base::Unretained(this);
  process_singleton_.reset(new AtomProcessSingleton(
    userDir,
    base::Bind(&Browser::OnProcessSingletonNotification, no_refcount_this)));

  process_notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();

  if (is_ready_) {
    process_singleton_->Unlock();
  }
}

ProcessSingleton::NotifyResult Browser::GetSingleInstanceResult() {
  LOG(ERROR) << "Process Notify Result: " << process_notify_result_;
  return process_notify_result_;
}

void Browser::SetSingleInstanceCallback(
    ProcessSingleton::NotificationCallback callback) {
  process_notify_callback_ = callback;
  process_notify_callback_set_ = true;
}

void Browser::OnWindowCloseCancelled(NativeWindow* window) {
  if (is_quiting_)
    // Once a beforeunload handler has prevented the closing, we think the quit
    // is cancelled too.
    is_quiting_ = false;
}

void Browser::OnWindowAllClosed() {
  if (is_quiting_)
    NotifyAndShutdown();
  else
    FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed());
}

bool Browser::OnProcessSingletonNotification(
    const base::CommandLine& command_line,
    const base::FilePath& current_directory) {
  if (process_notify_callback_set_) {
    return process_notify_callback_.Run(command_line, current_directory);
  } else {
    return true;    // We'll handle this, not a different process
  }
}

}  // namespace atom
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Executive.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Executive.h"

#include <boost/timer.hpp>
#include <libdevcore/CommonIO.h>
#include <libevm/VMFactory.h>
#include <libevm/VM.h>
#include "Interface.h"
#include "State.h"
#include "ExtVM.h"
#include "Precompiled.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

#define ETH_VMTRACE 1

u256 Executive::gasUsed() const
{
	return m_t.gas() - m_endGas;
}

bool Executive::setup(bytesConstRef _rlp)
{
	// Entry point for a user-executed transaction.
	m_t = Transaction(_rlp);

	m_sender = m_t.sender();

	// Avoid invalid transactions.
	auto nonceReq = m_s.transactionsFrom(m_sender);
	if (m_t.nonce() != nonceReq)
	{
		clog(StateDetail) << "Invalid Nonce: Require" << nonceReq << " Got" << m_t.nonce();
		BOOST_THROW_EXCEPTION(InvalidNonce(nonceReq, m_t.nonce()));
	}

	// Check gas cost is enough.
	auto gasCost = Interface::txGas(m_t.data());

	if (m_t.gas() < gasCost)
	{
		clog(StateDetail) << "Not enough gas to pay for the transaction: Require >" << gasCost << " Got" << m_t.gas();
		BOOST_THROW_EXCEPTION(OutOfGas() << RequirementError((bigint)gasCost, (bigint)m_t.gas()));
	}

	u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice();

	// Avoid unaffordable transactions.
	if (m_s.balance(m_sender) < cost)
	{
		clog(StateDetail) << "Not enough cash: Require >" << cost << " Got" << m_s.balance(m_sender);
		BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((bigint)cost, (bigint)m_s.balance(m_sender)));
	}

	u256 startGasUsed = m_s.gasUsed();
	if (startGasUsed + m_t.gas() > m_s.m_currentBlock.gasLimit)
	{
		clog(StateDetail) << "Too much gas used in this block: Require <" << (m_s.m_currentBlock.gasLimit - startGasUsed) << " Got" << m_t.gas();
		BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(m_s.m_currentBlock.gasLimit - startGasUsed), (bigint)m_t.gas()));
	}

	// Increment associated nonce for sender.
	m_s.noteSending(m_sender);

	// Pay...
	clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
	m_s.subBalance(m_sender, cost);

	if (m_t.isCreation())
		return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_sender);
	else
		return call(m_t.receiveAddress(), m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_sender);
}

bool Executive::call(Address _receiveAddress, Address _codeAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress)
{
	m_isCreation = false;
//	cnote << "Transferring" << formatBalance(_value) << "to receiver.";
	m_s.addBalance(_receiveAddress, _value);

	auto it = !(_codeAddress & ~h160(0xffffffff)) ? precompiled().find((unsigned)(u160)_codeAddress) : precompiled().end();
	if (it != precompiled().end())
	{
		bigint g = it->second.gas(_data);
		if (_gas < g)
		{
			m_endGas = 0;
			m_excepted = true;
		}
		else
		{
			m_endGas = (u256)(_gas - g);
			m_precompiledOut = it->second.exec(_data);
			m_out = &m_precompiledOut;
		}
	}
	else if (m_s.addressHasCode(_codeAddress))
	{
		m_vm = VMFactory::create(_gas);
		bytes const& c = m_s.code(_codeAddress);
		m_ext = make_shared<ExtVM>(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_depth);
	}
	else
		m_endGas = _gas;
	return !m_ext;
}

bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
{
	m_isCreation = true;

	// We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since
	// we delete it explicitly if we decide we need to revert.
	m_newAddress = right160(sha3(rlpList(_sender, m_s.transactionsFrom(_sender) - 1)));

	// Set up new account...
	m_s.m_cache[m_newAddress] = Account(m_s.balance(m_newAddress) + _endowment, Account::ContractConception);

	// Execute _init.
	m_vm = VMFactory::create(_gas);
	m_ext = make_shared<ExtVM>(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_depth);
	return _init.empty();
}

OnOpFunc Executive::simpleTrace()
{
	return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, VM* voidVM, ExtVMFace const* voidExt)
	{
		ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
		VM& vm = *voidVM;

		ostringstream o;
		o << endl << "    STACK" << endl;
		for (auto i: vm.stack())
			o << (h256)i << endl;
		o << "    MEMORY" << endl << memDump(vm.memory());
		o << "    STORAGE" << endl;
		for (auto const& i: ext.state().storage(ext.myAddress))
			o << showbase << hex << i.first << ": " << i.second << endl;
		dev::LogOutputStream<VMTraceChannel, false>(true) << o.str();
		dev::LogOutputStream<VMTraceChannel, false>(false) << " | " << dec << ext.depth << " | " << ext.myAddress << " | #" << steps << " | " << hex << setw(4) << setfill('0') << vm.curPC() << " : " << instructionInfo(inst).name << " | " << dec << vm.gas() << " | -" << dec << gasCost << " | " << newMemSize << "x32" << " ]";
	};
}

bool Executive::go(OnOpFunc const& _onOp)
{
	if (m_vm)
	{
#if ETH_TIMED_EXECUTIONS
		boost::timer t;
#endif
		try
		{
			m_out = m_vm->go(*m_ext, _onOp);
			m_endGas = m_vm->gas();

			if (m_isCreation)
			{
				if (m_out.size() * c_createDataGas <= m_endGas)
					m_endGas -= m_out.size() * c_createDataGas;
				else
					m_out.reset();
				m_s.m_cache[m_newAddress].setCode(m_out);
			}
		}
		catch (StepsDone const&)
		{
			return false;
		}
		catch (VMException const& _e)
		{
			clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
			m_endGas = 0;
			m_excepted = true;
			m_ext->revert();
		}
		catch (Exception const& _e)
		{
			// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
			cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e);
		}
		catch (std::exception const& _e)
		{
			// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
			cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what();
		}
#if ETH_TIMED_EXECUTIONS
		cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas);
#endif
	}
	return true;
}

/*u256 Executive::gas() const
{
	return m_vm ? m_vm->gas() : m_endGas;
}*/

void Executive::finalize(OnOpFunc const&)
{
	// SSTORE refunds.
	m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds);

	//	cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")";
	m_s.addBalance(m_sender, m_endGas * m_t.gasPrice());

	u256 feesEarned = (m_t.gas() - m_endGas) * m_t.gasPrice();
//	cnote << "Transferring" << formatBalance(gasSpent) << "to miner.";
	m_s.addBalance(m_s.m_currentBlock.coinbaseAddress, feesEarned);

	// Suicides...
	if (m_ext)
		for (auto a: m_ext->sub.suicides)
			m_s.m_cache[a].kill();

	// Logs
	m_logs = m_ext->sub.logs;
}
<commit_msg>Minor fix for finalize.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Executive.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Executive.h"

#include <boost/timer.hpp>
#include <libdevcore/CommonIO.h>
#include <libevm/VMFactory.h>
#include <libevm/VM.h>
#include "Interface.h"
#include "State.h"
#include "ExtVM.h"
#include "Precompiled.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

#define ETH_VMTRACE 1

u256 Executive::gasUsed() const
{
	return m_t.gas() - m_endGas;
}

bool Executive::setup(bytesConstRef _rlp)
{
	// Entry point for a user-executed transaction.
	m_t = Transaction(_rlp);

	m_sender = m_t.sender();

	// Avoid invalid transactions.
	auto nonceReq = m_s.transactionsFrom(m_sender);
	if (m_t.nonce() != nonceReq)
	{
		clog(StateDetail) << "Invalid Nonce: Require" << nonceReq << " Got" << m_t.nonce();
		BOOST_THROW_EXCEPTION(InvalidNonce(nonceReq, m_t.nonce()));
	}

	// Check gas cost is enough.
	auto gasCost = Interface::txGas(m_t.data());

	if (m_t.gas() < gasCost)
	{
		clog(StateDetail) << "Not enough gas to pay for the transaction: Require >" << gasCost << " Got" << m_t.gas();
		BOOST_THROW_EXCEPTION(OutOfGas() << RequirementError((bigint)gasCost, (bigint)m_t.gas()));
	}

	u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice();

	// Avoid unaffordable transactions.
	if (m_s.balance(m_sender) < cost)
	{
		clog(StateDetail) << "Not enough cash: Require >" << cost << " Got" << m_s.balance(m_sender);
		BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((bigint)cost, (bigint)m_s.balance(m_sender)));
	}

	u256 startGasUsed = m_s.gasUsed();
	if (startGasUsed + m_t.gas() > m_s.m_currentBlock.gasLimit)
	{
		clog(StateDetail) << "Too much gas used in this block: Require <" << (m_s.m_currentBlock.gasLimit - startGasUsed) << " Got" << m_t.gas();
		BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(m_s.m_currentBlock.gasLimit - startGasUsed), (bigint)m_t.gas()));
	}

	// Increment associated nonce for sender.
	m_s.noteSending(m_sender);

	// Pay...
	clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
	m_s.subBalance(m_sender, cost);

	if (m_t.isCreation())
		return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_sender);
	else
		return call(m_t.receiveAddress(), m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_sender);
}

bool Executive::call(Address _receiveAddress, Address _codeAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress)
{
	m_isCreation = false;
//	cnote << "Transferring" << formatBalance(_value) << "to receiver.";
	m_s.addBalance(_receiveAddress, _value);

	auto it = !(_codeAddress & ~h160(0xffffffff)) ? precompiled().find((unsigned)(u160)_codeAddress) : precompiled().end();
	if (it != precompiled().end())
	{
		bigint g = it->second.gas(_data);
		if (_gas < g)
		{
			m_endGas = 0;
			m_excepted = true;
		}
		else
		{
			m_endGas = (u256)(_gas - g);
			m_precompiledOut = it->second.exec(_data);
			m_out = &m_precompiledOut;
		}
	}
	else if (m_s.addressHasCode(_codeAddress))
	{
		m_vm = VMFactory::create(_gas);
		bytes const& c = m_s.code(_codeAddress);
		m_ext = make_shared<ExtVM>(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_depth);
	}
	else
		m_endGas = _gas;
	return !m_ext;
}

bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
{
	m_isCreation = true;

	// We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since
	// we delete it explicitly if we decide we need to revert.
	m_newAddress = right160(sha3(rlpList(_sender, m_s.transactionsFrom(_sender) - 1)));

	// Set up new account...
	m_s.m_cache[m_newAddress] = Account(m_s.balance(m_newAddress) + _endowment, Account::ContractConception);

	// Execute _init.
	m_vm = VMFactory::create(_gas);
	m_ext = make_shared<ExtVM>(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_depth);
	return _init.empty();
}

OnOpFunc Executive::simpleTrace()
{
	return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, VM* voidVM, ExtVMFace const* voidExt)
	{
		ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
		VM& vm = *voidVM;

		ostringstream o;
		o << endl << "    STACK" << endl;
		for (auto i: vm.stack())
			o << (h256)i << endl;
		o << "    MEMORY" << endl << memDump(vm.memory());
		o << "    STORAGE" << endl;
		for (auto const& i: ext.state().storage(ext.myAddress))
			o << showbase << hex << i.first << ": " << i.second << endl;
		dev::LogOutputStream<VMTraceChannel, false>(true) << o.str();
		dev::LogOutputStream<VMTraceChannel, false>(false) << " | " << dec << ext.depth << " | " << ext.myAddress << " | #" << steps << " | " << hex << setw(4) << setfill('0') << vm.curPC() << " : " << instructionInfo(inst).name << " | " << dec << vm.gas() << " | -" << dec << gasCost << " | " << newMemSize << "x32" << " ]";
	};
}

bool Executive::go(OnOpFunc const& _onOp)
{
	if (m_vm)
	{
#if ETH_TIMED_EXECUTIONS
		boost::timer t;
#endif
		try
		{
			m_out = m_vm->go(*m_ext, _onOp);
			m_endGas = m_vm->gas();

			if (m_isCreation)
			{
				if (m_out.size() * c_createDataGas <= m_endGas)
					m_endGas -= m_out.size() * c_createDataGas;
				else
					m_out.reset();
				m_s.m_cache[m_newAddress].setCode(m_out);
			}
		}
		catch (StepsDone const&)
		{
			return false;
		}
		catch (VMException const& _e)
		{
			clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
			m_endGas = 0;
			m_excepted = true;
			m_ext->revert();
		}
		catch (Exception const& _e)
		{
			// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
			cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e);
		}
		catch (std::exception const& _e)
		{
			// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
			cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what();
		}
#if ETH_TIMED_EXECUTIONS
		cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas);
#endif
	}
	return true;
}

/*u256 Executive::gas() const
{
	return m_vm ? m_vm->gas() : m_endGas;
}*/

void Executive::finalize(OnOpFunc const&)
{
	// SSTORE refunds.
	if (m_ext)
		m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds);

	//	cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")";
	m_s.addBalance(m_sender, m_endGas * m_t.gasPrice());

	u256 feesEarned = (m_t.gas() - m_endGas) * m_t.gasPrice();
//	cnote << "Transferring" << formatBalance(gasSpent) << "to miner.";
	m_s.addBalance(m_s.m_currentBlock.coinbaseAddress, feesEarned);

	// Suicides...
	if (m_ext)
		for (auto a: m_ext->sub.suicides)
			m_s.m_cache[a].kill();

	// Logs
	m_logs = m_ext->sub.logs;
}
<|endoftext|>


<commit_before>/*
 * RawStorage.cpp
 *
 * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.
 */

#include "vislib/RawStorage.h"

#include <stdexcept>

#include "vislib/assert.h"
#include "vislib/memutils.h"
#include "vislib/Trace.h"

/*
 * vislib::RawStorage::RawStorage
 */
vislib::RawStorage::RawStorage(const SIZE_T size) : data(NULL), size(size) {
    this->EnforceSize(this->size);
}

/*
 * vislib::RawStorage::RawStorage
 */
vislib::RawStorage::RawStorage(const RawStorage& rhs)
        : data(NULL), size(rhs.size) {
    if (this->size > 0) {
        this->EnforceSize(this->size);
        ::memcpy(this->data, rhs.data, this->size);
    }
}

/*
 * vislib::RawStorage::~RawStorage
 */
vislib::RawStorage::~RawStorage(void) {
    SAFE_FREE(this->data);
}

/*
 * vislib::RawStorage::AssertSize
 */
bool vislib::RawStorage::AssertSize(const SIZE_T size, const bool keepContent) {
    if (this->size < size) {
        this->EnforceSize(size, keepContent);
        return true;

    } else {
        return false;
    }
}

/*
 * vislib::RawStorage::EnforceSize
 */
void vislib::RawStorage::EnforceSize(const SIZE_T size,
                                     const bool keepContent) {

    if ((this->size = size) > 0) {

        if (keepContent) {
            TRACE(Trace::LEVEL_INFO, "RawStorage::AssertSize reallocates %u "
                "bytes.\n", this->size);
            this->data = ::realloc(this->data, this->size);

        } else {
            TRACE(Trace::LEVEL_INFO, "RawStorage::AssertSize allocates %u "
                "bytes.\n", this->size);
            SAFE_FREE(this->data);
            this->data = ::malloc(this->size);
        }

        if (this->data == NULL) {
            this->size = 0;
            throw std::bad_alloc();
        }

    } /* end if ((this->size = size) > 0) */
}

/*
 * vislib::RawStorage::operator =
 */
vislib::RawStorage& vislib::RawStorage::operator =(const RawStorage& rhs) {
    if (this != &rhs) {
        this->EnforceSize(rhs.size);
        ::memcpy(this->data, rhs.data, rhs.size);

        ASSERT(this->size == rhs.size);
    }

    return *this;
}

/*
 * vislib::RawStorage::operator ==
 */
bool vislib::RawStorage::operator ==(const RawStorage& rhs) const {
    if (this != &rhs) {
        return (::memcmp(this->data, rhs.data, this->size) == 0);
    } else {
        return true;
    }
}
<commit_msg>Trace-Level changed to LEVEL_VL_INFO.<commit_after>/*
 * RawStorage.cpp
 *
 * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.
 */

#include "vislib/RawStorage.h"

#include <stdexcept>

#include "vislib/assert.h"
#include "vislib/memutils.h"
#include "vislib/Trace.h"

/*
 * vislib::RawStorage::RawStorage
 */
vislib::RawStorage::RawStorage(const SIZE_T size) : data(NULL), size(size) {
    this->EnforceSize(this->size);
}

/*
 * vislib::RawStorage::RawStorage
 */
vislib::RawStorage::RawStorage(const RawStorage& rhs)
        : data(NULL), size(rhs.size) {
    if (this->size > 0) {
        this->EnforceSize(this->size);
        ::memcpy(this->data, rhs.data, this->size);
    }
}

/*
 * vislib::RawStorage::~RawStorage
 */
vislib::RawStorage::~RawStorage(void) {
    SAFE_FREE(this->data);
}

/*
 * vislib::RawStorage::AssertSize
 */
bool vislib::RawStorage::AssertSize(const SIZE_T size, const bool keepContent) {
    if (this->size < size) {
        this->EnforceSize(size, keepContent);
        return true;

    } else {
        return false;
    }
}

/*
 * vislib::RawStorage::EnforceSize
 */
void vislib::RawStorage::EnforceSize(const SIZE_T size,
                                     const bool keepContent) {

    if ((this->size = size) > 0) {

        if (keepContent) {
            TRACE(Trace::LEVEL_VL_INFO, "RawStorage::AssertSize reallocates %u "
                "bytes.\n", this->size);
            this->data = ::realloc(this->data, this->size);

        } else {
            TRACE(Trace::LEVEL_VL_INFO, "RawStorage::AssertSize allocates %u "
                "bytes.\n", this->size);
            SAFE_FREE(this->data);
            this->data = ::malloc(this->size);
        }

        if (this->data == NULL) {
            this->size = 0;
            throw std::bad_alloc();
        }

    } /* end if ((this->size = size) > 0) */
}

/*
 * vislib::RawStorage::operator =
 */
vislib::RawStorage& vislib::RawStorage::operator =(const RawStorage& rhs) {
    if (this != &rhs) {
        this->EnforceSize(rhs.size);
        ::memcpy(this->data, rhs.data, rhs.size);

        ASSERT(this->size == rhs.size);
    }

    return *this;
}

/*
 * vislib::RawStorage::operator ==
 */
bool vislib::RawStorage::operator ==(const RawStorage& rhs) const {
    if (this != &rhs) {
        return (::memcmp(this->data, rhs.data, this->size) == 0);
    } else {
        return true;
    }
}
<|endoftext|>