<commit_before>#include <algorithm>
#include <map>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include <fj_tool/fapp.h>
#include <fjcoll.h>

using namespace std;

#include "pearson-3d.h"

bool EXTEND_MISSION=false;
int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;

float frand() {
  return rand() / float(RAND_MAX);
}

double wctime() {
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}
/*
void init() {
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        double x = double(navi.offset_x + ix)/NX;
        double y = double(navi.offset_y + iy)/NY;
        double z = double(navi.offset_z + iz)/NZ;
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        if (z > 0.49 && z < 0.51 && x > 0.4 && x < 0.6) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
}*/

typedef pair<int,pair<int,int> > Key;
void init() {
  map<Key ,double> seeds;
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        Key k (ix/16, pair<int,int>(iy/16, iz/16));
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        double s = seeds[k];
        if (s==0) {
          s = frand();
          seeds[k]=s;
        }
        if (s < 0.1 ) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
  }

void write_monitor() {
  printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);

  int global_position[6];
  global_position[0] = navi.offset_x + navi.lower_x;
  global_position[1] = navi.offset_y + navi.lower_y;
  global_position[2] = navi.offset_z + navi.lower_z;
  global_position[3] = navi.upper_x - navi.lower_x;
  global_position[4] = navi.upper_y - navi.lower_y;
  global_position[5] = navi.upper_z - navi.lower_z;
  int x_size = navi.upper_x - navi.lower_x;
  int y_size = navi.upper_y - navi.lower_y;
  int z_size = navi.upper_z - navi.lower_z;

  if (navi.offset_x + navi.lower_x < navi.upper_x) {
    char fn[256];
    sprintf(fn, "out/monitorX-%06d-%d.txt", navi.time_step, mpi_my_rank);

    FILE *fp = fopen(fn,"wb");
    fwrite(global_position, sizeof(int), 6, fp);
    {
      const int x=navi.lower_x + x_size/2;
      for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
      for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    }
    fclose(fp);
  }

  if (navi.offset_y + navi.lower_y < navi.upper_y) {
    char fn[256];
    sprintf(fn, "out/monitorY-%06d-%d.txt", navi.time_step, mpi_my_rank);

    FILE *fp = fopen(fn,"wb");
    fwrite(global_position, sizeof(int), 6, fp);
    {
      const int y=navi.lower_y + y_size/2;
      for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
      for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    }
    fclose(fp);
  }

}

int main (int argc, char **argv) {
  MPI_Init(&argc, &argv);
  Formura_Init(&navi, MPI_COMM_WORLD);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
  srand(time(NULL)+mpi_my_rank*65537);

  if (argc <= 1) {
    T_MAX=8192;
  }else{
    sscanf(argv[1], "%d",  &T_MAX);
  }
  if (argc <= 2) {
    T_MONITOR=8192;
  }else{
    sscanf(argv[2], "%d",  &T_MONITOR);
  }
  if (argc >= 4) {
    EXTEND_MISSION = true;
  }

  init();

  double t_begin = wctime(), t_end;

  int last_monitor_t = -T_MONITOR;
  for(;;){
    double t = wctime();
    bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
    if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
      printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
    }
    if(monitor_flag) {
      write_monitor();
    }
    if(monitor_flag) {
      last_monitor_t += T_MONITOR;
    }

    if (navi.time_step >= T_MAX) {
      if (EXTEND_MISSION){
        T_MAX*=2;
        T_MONITOR*=2;
      }else{
        break;
      }

    }
    if (navi.time_step == 0) {
      t_begin = wctime();
      start_collection("main");
    }

    Formura_Forward(&navi); // navi.time_step increases
    MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization

    if (navi.time_step >= T_MAX) {
      t_end = wctime();
      stop_collection("main");
    }
  }
  printf("wct = %lf sec\n",t_end - t_begin);

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
}
<commit_msg>Extended benchmark mechanisms implemented<commit_after>#include <algorithm>
#include <map>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include <fj_tool/fapp.h>
#include <fjcoll.h>

using namespace std;

#include "pearson-3d.h"

bool EXTEND_MISSION=false;
int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;

float frand() {
  return rand() / float(RAND_MAX);
}

double wctime() {
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}
/*
void init() {
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        double x = double(navi.offset_x + ix)/NX;
        double y = double(navi.offset_y + iy)/NY;
        double z = double(navi.offset_z + iz)/NZ;
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        if (z > 0.49 && z < 0.51 && x > 0.4 && x < 0.6) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
}*/

typedef pair<int,pair<int,int> > Key;
void init() {
  map<Key ,double> seeds;
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        Key k (ix/16, pair<int,int>(iy/16, iz/16));
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        double s = seeds[k];
        if (s==0) {
          s = frand();
          seeds[k]=s;
        }
        if (s < 0.1 ) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
  }

void write_monitor() {
  printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);

  int global_position[6];
  global_position[0] = navi.offset_x + navi.lower_x;
  global_position[1] = navi.offset_y + navi.lower_y;
  global_position[2] = navi.offset_z + navi.lower_z;
  global_position[3] = navi.upper_x - navi.lower_x;
  global_position[4] = navi.upper_y - navi.lower_y;
  global_position[5] = navi.upper_z - navi.lower_z;
  int x_size = navi.upper_x - navi.lower_x;
  int y_size = navi.upper_y - navi.lower_y;
  int z_size = navi.upper_z - navi.lower_z;

  if (navi.offset_x + navi.lower_x < navi.upper_x) {
    char fn[256];
    sprintf(fn, "out/monitorX-%06d-%d.txt", navi.time_step, mpi_my_rank);

    FILE *fp = fopen(fn,"wb");
    fwrite(global_position, sizeof(int), 6, fp);
    {
      const int x=navi.lower_x + x_size/2;
      for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
      for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    }
    fclose(fp);
  }

  if (navi.offset_y + navi.lower_y < navi.upper_y) {
    char fn[256];
    sprintf(fn, "out/monitorY-%06d-%d.txt", navi.time_step, mpi_my_rank);

    FILE *fp = fopen(fn,"wb");
    fwrite(global_position, sizeof(int), 6, fp);
    {
      const int y=navi.lower_y + y_size/2;
      for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
      for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    }
    fclose(fp);
  }

}

int main (int argc, char **argv) {
  MPI_Init(&argc, &argv);
  Formura_Init(&navi, MPI_COMM_WORLD);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
  srand(time(NULL)+mpi_my_rank*65537);

  if (argc <= 1) {
    T_MAX=8192;
  }else{
    sscanf(argv[1], "%d",  &T_MAX);
  }
  if (argc <= 2) {
    T_MONITOR=8192;
  }else{
    sscanf(argv[2], "%d",  &T_MONITOR);
  }
  if (argc >= 4) {
    EXTEND_MISSION = true;
  }

  init();

  double t_begin = wctime(), t_end;

  int last_monitor_t = -T_MONITOR;
  char[256] benchmark_name;
  sprintf(benchmark_name,"main");
  for(;;){
    double t = wctime();
    bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
    if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
      printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
    }
    if(monitor_flag) {
      write_monitor();
    }
    if(monitor_flag) {
      last_monitor_t += T_MONITOR;
    }

    if (navi.time_step >= T_MAX) {
      if (EXTEND_MISSION){
        T_MAX*=2;
        T_MONITOR*=2;
        sprintf(benchmark_name,"extend-%d",T_MAX);
        start_collection(benchmark_name);
      }else{
        break;
      }

    }
    if (navi.time_step == 0) {
      t_begin = wctime();
      start_collection(benchmark_name);
    }

    Formura_Forward(&navi); // navi.time_step increases
    MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization

    if (navi.time_step >= T_MAX) {
      t_end = wctime();
      stop_collection(benchmark_name);
    }
  }
  printf("wct = %lf sec\n",t_end - t_begin);

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "views/event.h"

// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)

namespace {

class KeyboardAccessTest : public UITest {
 public:
  KeyboardAccessTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  // Use the keyboard to select "New Tab" from the app menu.
  // This test depends on the fact that there is one menu and that
  // New Tab is the first item in the menu. If the menus change,
  // this test will need to be changed to reflect that.
  //
  // If alternate_key_sequence is true, use "Alt" instead of "F10" to
  // open the menu bar, and "Down" instead of "Enter" to open a menu.
  void TestMenuKeyboardAccess(bool alternate_key_sequence);

  DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};

void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());

  // Navigate to a page in the first tab, which makes sure that focus is
  // set to the browser window.
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));

  // The initial tab index should be 0.
  int tab_index = -1;
  ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
  ASSERT_EQ(0, tab_index);

  // Get the focused view ID, then press a key to activate the
  // page menu, then wait until the focused view changes.
  int original_view_id = -1;
  ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));

  base::KeyboardCode menu_key =
      alternate_key_sequence ? base::VKEY_MENU : base::VKEY_F10;
#if defined(OS_CHROMEOS)
  // Chrome OS has different function key accelerators, so we always use the
  // menu key there.
  menu_key = base::VKEY_MENU;
#endif
  ASSERT_TRUE(window->SimulateOSKeyPress(menu_key, 0));

  int new_view_id = -1;
  ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
      original_view_id, &new_view_id));

  ASSERT_TRUE(browser->StartTrackingPopupMenus());

  if (alternate_key_sequence)
    ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
  else
    ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));

  // Wait until the popup menu actually opens.
  ASSERT_TRUE(browser->WaitForPopupMenuToOpen());

  // Press DOWN to select the first item, then RETURN to select it.
  ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
  ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));

  // Wait for the new tab to appear.
  ASSERT_TRUE(browser->WaitForTabCountToBecome(2, action_timeout_ms()));

  // Make sure that the new tab index is 1.
  ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
  ASSERT_EQ(1, tab_index);
}

TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
  TestMenuKeyboardAccess(false);
}

TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true);
}

TEST_F(KeyboardAccessTest, ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser);
  ASSERT_TRUE(browser->AppendTab(GURL("data:text/html," + kBadPage)));
  int tab_count = 0;
  ASSERT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(tab_count, 2);

  int active_tab = 0;
  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));
  ASSERT_EQ(active_tab, 1);

  scoped_refptr<WindowProxy> window(browser->GetWindow());
  ASSERT_TRUE(window);
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));

#if !defined(OS_MACOSX)  // see BrowserWindowCocoa::GetCommandId
  ASSERT_TRUE(browser->ActivateTab(1));
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_F4, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
#endif
}

}  // namespace

#endif  // defined(TOOLKIT_VIEWS)
<commit_msg>Mark KeyboardAccessTest.ReserveKeyboardAccelerator as FAILS<commit_after>// Copyright (c) 2010 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 "base/keyboard_codes.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "views/event.h"

// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)

namespace {

class KeyboardAccessTest : public UITest {
 public:
  KeyboardAccessTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  // Use the keyboard to select "New Tab" from the app menu.
  // This test depends on the fact that there is one menu and that
  // New Tab is the first item in the menu. If the menus change,
  // this test will need to be changed to reflect that.
  //
  // If alternate_key_sequence is true, use "Alt" instead of "F10" to
  // open the menu bar, and "Down" instead of "Enter" to open a menu.
  void TestMenuKeyboardAccess(bool alternate_key_sequence);

  DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};

void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence) {
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());

  // Navigate to a page in the first tab, which makes sure that focus is
  // set to the browser window.
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(tab->NavigateToURL(GURL("about:")));

  // The initial tab index should be 0.
  int tab_index = -1;
  ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
  ASSERT_EQ(0, tab_index);

  // Get the focused view ID, then press a key to activate the
  // page menu, then wait until the focused view changes.
  int original_view_id = -1;
  ASSERT_TRUE(window->GetFocusedViewID(&original_view_id));

  base::KeyboardCode menu_key =
      alternate_key_sequence ? base::VKEY_MENU : base::VKEY_F10;
#if defined(OS_CHROMEOS)
  // Chrome OS has different function key accelerators, so we always use the
  // menu key there.
  menu_key = base::VKEY_MENU;
#endif
  ASSERT_TRUE(window->SimulateOSKeyPress(menu_key, 0));

  int new_view_id = -1;
  ASSERT_TRUE(window->WaitForFocusedViewIDToChange(
      original_view_id, &new_view_id));

  ASSERT_TRUE(browser->StartTrackingPopupMenus());

  if (alternate_key_sequence)
    ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
  else
    ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));

  // Wait until the popup menu actually opens.
  ASSERT_TRUE(browser->WaitForPopupMenuToOpen());

  // Press DOWN to select the first item, then RETURN to select it.
  ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_DOWN, 0));
  ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_RETURN, 0));

  // Wait for the new tab to appear.
  ASSERT_TRUE(browser->WaitForTabCountToBecome(2, action_timeout_ms()));

  // Make sure that the new tab index is 1.
  ASSERT_TRUE(browser->GetActiveTabIndex(&tab_index));
  ASSERT_EQ(1, tab_index);
}

TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
  TestMenuKeyboardAccess(false);
}

TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true);
}

// Fails, http://crbug.com/50760.
TEST_F(KeyboardAccessTest, FAILS_ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser);
  ASSERT_TRUE(browser->AppendTab(GURL("data:text/html," + kBadPage)));
  int tab_count = 0;
  ASSERT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(tab_count, 2);

  int active_tab = 0;
  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));
  ASSERT_EQ(active_tab, 1);

  scoped_refptr<WindowProxy> window(browser->GetWindow());
  ASSERT_TRUE(window);
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));

#if !defined(OS_MACOSX)  // see BrowserWindowCocoa::GetCommandId
  ASSERT_TRUE(browser->ActivateTab(1));
  ASSERT_TRUE(window->SimulateOSKeyPress(
      base::VKEY_F4, views::Event::EF_CONTROL_DOWN));
  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
#endif
}

}  // namespace

#endif  // defined(TOOLKIT_VIEWS)
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "VerifyingSemaConsumer.h"

#include "clang/AST/DeclGroup.h"
#include "clang/Sema/Sema.h"

#include "ChainedConsumer.h"

using namespace clang;

namespace cling {
  // pin the vtable here
  VerifyingSemaConsumer::~VerifyingSemaConsumer() {}

  bool VerifyingSemaConsumer::HandleTopLevelDecl(clang::DeclGroupRef DGR) {
    TransformTopLevelDecl(DGR);
    // Pull all template instantiations in, coming from the consumers.
    m_Sema->PerformPendingInstantiations();

    if (m_Sema->getDiagnostics().hasErrorOccurred()) {
      Notify();
    }
    return true;
  }

  void VerifyingSemaConsumer::ForgetSema() {
    m_Sema = 0;
  }

  void VerifyingSemaConsumer::Attach(ChainedConsumer* o) {
    // make sure that the observer is added once
    for (size_t i = 0; i < m_Observers.size(); ++i) {
      if (m_Observers[i] == o)
        return;
    }

    m_Observers.push_back(o);
  }

  void VerifyingSemaConsumer::Detach(ChainedConsumer* o) {
    for (llvm::SmallVector<ChainedConsumer*,2>::iterator I = m_Observers.begin();
         I != m_Observers.end(); ++I) {
      if ((*I) == o)
        m_Observers.erase(I);
    }
  }

  void VerifyingSemaConsumer::Notify() {
    for (size_t i = 0; i < m_Observers.size(); ++i)
      m_Observers[i]->Update(this);
  }

} // end namespace cling
<commit_msg>From David Volgyes: Terminate the loop after removal of the element.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "VerifyingSemaConsumer.h"

#include "clang/AST/DeclGroup.h"
#include "clang/Sema/Sema.h"

#include "ChainedConsumer.h"

using namespace clang;

namespace cling {
  // pin the vtable here
  VerifyingSemaConsumer::~VerifyingSemaConsumer() {}

  bool VerifyingSemaConsumer::HandleTopLevelDecl(clang::DeclGroupRef DGR) {
    TransformTopLevelDecl(DGR);
    // Pull all template instantiations in, coming from the consumers.
    m_Sema->PerformPendingInstantiations();

    if (m_Sema->getDiagnostics().hasErrorOccurred()) {
      Notify();
    }
    return true;
  }

  void VerifyingSemaConsumer::ForgetSema() {
    m_Sema = 0;
  }

  void VerifyingSemaConsumer::Attach(ChainedConsumer* o) {
    // make sure that the observer is added once
    for (size_t i = 0; i < m_Observers.size(); ++i) {
      if (m_Observers[i] == o)
        return;
    }

    m_Observers.push_back(o);
  }

  void VerifyingSemaConsumer::Detach(ChainedConsumer* o) {
    for (llvm::SmallVector<ChainedConsumer*,2>::iterator I = m_Observers.begin();
         I != m_Observers.end(); ++I) {
      if ((*I) == o) {
        m_Observers.erase(I);
        break;
      }
    }
  }

  void VerifyingSemaConsumer::Notify() {
    for (size_t i = 0; i < m_Observers.size(); ++i)
      m_Observers[i]->Update(this);
  }

} // end namespace cling
<|endoftext|>


<commit_before>#include "tinysplinecpp.h"
#include <stdexcept>
#include <cstdio>

// Surpress warning C4996 (sprintf_s).
#ifdef _MSC_VER
	#define _CRT_SECURE_NO_WARNINGS
#endif

/******************************************************************************
*                                                                             *
* DeBoorNet                                                                   *
*                                                                             *
******************************************************************************/
tinyspline::DeBoorNet::DeBoorNet()
{
	ts_deboornet_default(&net);
}

tinyspline::DeBoorNet::DeBoorNet(const tinyspline::DeBoorNet &other)
{
	tsError err = ts_deboornet_copy(&other.net, &net);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::DeBoorNet::~DeBoorNet()
{
	ts_deboornet_free(&net);
}

tinyspline::DeBoorNet & tinyspline::DeBoorNet::operator=(
	const tinyspline::DeBoorNet &other)
{
	if (&other != this) {
		tsError err = ts_deboornet_copy(&other.net, &net);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::real tinyspline::DeBoorNet::knot() const
{
	return ts_deboornet_knot(&net);
}

size_t tinyspline::DeBoorNet::index() const
{
	return ts_deboornet_index(&net);
}

size_t tinyspline::DeBoorNet::multiplicity() const
{
	return ts_deboornet_multiplicity(&net);
}

size_t tinyspline::DeBoorNet::numInsertions() const
{
	return ts_deboornet_num_insertions(&net);
}

size_t tinyspline::DeBoorNet::dimension() const
{
	return ts_deboornet_dimension(&net);
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::points() const
{
	tsReal *points = ts_deboornet_points(&net);
	if (!points)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_points = ts_deboornet_num_points(&net);
	tinyspline::real *begin = points;
	tinyspline::real *end = begin + num_points * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete points;
	return vec;
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::result() const
{
	tsReal *result = ts_deboornet_result(&net);
	if (!result)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_result = ts_deboornet_num_result(&net);
	tinyspline::real *begin = result;
	tinyspline::real *end = begin + num_result * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete result;
	return vec;
}

tsDeBoorNet * tinyspline::DeBoorNet::data()
{
	return &net;
}

/******************************************************************************
*                                                                             *
* BSpline                                                                     *
*                                                                             *
******************************************************************************/
tinyspline::BSpline::BSpline()
{
	ts_bspline_default(&spline);
}

tinyspline::BSpline::BSpline(const tinyspline::BSpline &other)
{
	tsError err = ts_bspline_copy(&other.spline, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(size_t nCtrlp, size_t dim, size_t deg,
	tinyspline::BSpline::type type)
{
	tsError err = ts_bspline_new(nCtrlp, dim, deg, type, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::~BSpline()
{
	ts_bspline_free(&spline);
}

tinyspline::BSpline & tinyspline::BSpline::operator=(
	const tinyspline::BSpline &other)
{
	if (&other != this) {
		tsError err = ts_bspline_copy(&other.spline, &spline);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::DeBoorNet tinyspline::BSpline::operator()(tinyspline::real u) const
{
	return eval(u);
}

size_t tinyspline::BSpline::degree() const
{
	return ts_bspline_degree(&spline);
}

size_t tinyspline::BSpline::order() const
{
	return ts_bspline_order(&spline);
}

size_t tinyspline::BSpline::dimension() const
{
	return ts_bspline_dimension(&spline);
}

std::vector<tinyspline::real> tinyspline::BSpline::controlPoints() const
{
	tsReal *ctrlp = ts_bspline_control_points(&spline);
	if (!ctrlp)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_ctrlp = ts_bspline_num_control_points(&spline);
	tinyspline::real *begin  = ctrlp;
	tinyspline::real *end = begin + num_ctrlp * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete ctrlp;
	return vec;
}

std::vector<tinyspline::real> tinyspline::BSpline::knots() const
{
	tsReal *knots = ts_bspline_knots(&spline);
	if (!knots)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_knots = ts_bspline_num_knots(&spline);
	tinyspline::real *begin = knots;
	tinyspline::real *end = begin + num_knots;
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete knots;
	return vec;
}

tsBSpline * tinyspline::BSpline::data()
{
	return &spline;
}

tinyspline::DeBoorNet tinyspline::BSpline::eval(tinyspline::real u) const
{
	tinyspline::DeBoorNet deBoorNet;
	tsError err = ts_bspline_eval(&spline, u, deBoorNet.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return deBoorNet;
}

void tinyspline::BSpline::setControlPoints(
	const std::vector<tinyspline::real> &ctrlp)
{
	size_t expected = ts_bspline_len_control_points(&spline);
	size_t actual = ctrlp.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_control_points(&spline, ctrlp.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::setKnots(const std::vector<tinyspline::real> &knots)
{
	size_t expected = ts_bspline_num_knots(&spline);
	size_t actual = knots.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_knots(&spline, knots.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline tinyspline::BSpline::fillKnots(tsBSplineType type,
	tinyspline::real min, tinyspline::real max) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_fill_knots(
		&spline, type, min, max, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::insertKnot(tinyspline::real u,
	size_t n) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_insert_knot(&spline, u, n, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::resize(int n, int back) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_resize(&spline, n, back, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::split(tinyspline::real u) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_split(&spline, u, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::buckle(tinyspline::real b) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_buckle(&spline, b, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::toBeziers() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_to_beziers(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::derive() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_derive(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

/******************************************************************************
*                                                                             *
* Utils                                                                       *
*                                                                             *
******************************************************************************/
tinyspline::BSpline tinyspline::Utils::interpolateCubic(
	const std::vector<tinyspline::real> *points, size_t dim)
{
	if (dim == 0)
		throw std::runtime_error(ts_enum_str(TS_DIM_ZERO));
	if (points->size() % dim != 0)
		throw std::runtime_error("#points % dim == 0 failed");
	tinyspline::BSpline bspline;
	tsError err = ts_bspline_interpolate_cubic(
		points->data(), points->size()/dim, dim, bspline.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bspline;
}

bool tinyspline::Utils::fequals(tinyspline::real x, tinyspline::real y)
{
	return ts_fequals(x, y) == 1;
}

std::string tinyspline::Utils::enum_str(tsError err)
{
	return std::string(ts_enum_str(err));
}

tsError tinyspline::Utils::str_enum(std::string str)
{
	return ts_str_enum(str.c_str());
}
<commit_msg>Use '#pragma warning(disable:4996)' to prevent MSVC error.<commit_after>#include "tinysplinecpp.h"
#include <stdexcept>
#include <cstdio>

// Surpress warning C4996 (sprintf_s).
#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif

/******************************************************************************
*                                                                             *
* DeBoorNet                                                                   *
*                                                                             *
******************************************************************************/
tinyspline::DeBoorNet::DeBoorNet()
{
	ts_deboornet_default(&net);
}

tinyspline::DeBoorNet::DeBoorNet(const tinyspline::DeBoorNet &other)
{
	tsError err = ts_deboornet_copy(&other.net, &net);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::DeBoorNet::~DeBoorNet()
{
	ts_deboornet_free(&net);
}

tinyspline::DeBoorNet & tinyspline::DeBoorNet::operator=(
	const tinyspline::DeBoorNet &other)
{
	if (&other != this) {
		tsError err = ts_deboornet_copy(&other.net, &net);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::real tinyspline::DeBoorNet::knot() const
{
	return ts_deboornet_knot(&net);
}

size_t tinyspline::DeBoorNet::index() const
{
	return ts_deboornet_index(&net);
}

size_t tinyspline::DeBoorNet::multiplicity() const
{
	return ts_deboornet_multiplicity(&net);
}

size_t tinyspline::DeBoorNet::numInsertions() const
{
	return ts_deboornet_num_insertions(&net);
}

size_t tinyspline::DeBoorNet::dimension() const
{
	return ts_deboornet_dimension(&net);
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::points() const
{
	tsReal *points = ts_deboornet_points(&net);
	if (!points)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_points = ts_deboornet_num_points(&net);
	tinyspline::real *begin = points;
	tinyspline::real *end = begin + num_points * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete points;
	return vec;
}

std::vector<tinyspline::real> tinyspline::DeBoorNet::result() const
{
	tsReal *result = ts_deboornet_result(&net);
	if (!result)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_result = ts_deboornet_num_result(&net);
	tinyspline::real *begin = result;
	tinyspline::real *end = begin + num_result * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete result;
	return vec;
}

tsDeBoorNet * tinyspline::DeBoorNet::data()
{
	return &net;
}

/******************************************************************************
*                                                                             *
* BSpline                                                                     *
*                                                                             *
******************************************************************************/
tinyspline::BSpline::BSpline()
{
	ts_bspline_default(&spline);
}

tinyspline::BSpline::BSpline(const tinyspline::BSpline &other)
{
	tsError err = ts_bspline_copy(&other.spline, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::BSpline(size_t nCtrlp, size_t dim, size_t deg,
	tinyspline::BSpline::type type)
{
	tsError err = ts_bspline_new(nCtrlp, dim, deg, type, &spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline::~BSpline()
{
	ts_bspline_free(&spline);
}

tinyspline::BSpline & tinyspline::BSpline::operator=(
	const tinyspline::BSpline &other)
{
	if (&other != this) {
		tsError err = ts_bspline_copy(&other.spline, &spline);
		if (err < 0)
			throw std::runtime_error(ts_enum_str(err));
	}
	return *this;
}

tinyspline::DeBoorNet tinyspline::BSpline::operator()(tinyspline::real u) const
{
	return eval(u);
}

size_t tinyspline::BSpline::degree() const
{
	return ts_bspline_degree(&spline);
}

size_t tinyspline::BSpline::order() const
{
	return ts_bspline_order(&spline);
}

size_t tinyspline::BSpline::dimension() const
{
	return ts_bspline_dimension(&spline);
}

std::vector<tinyspline::real> tinyspline::BSpline::controlPoints() const
{
	tsReal *ctrlp = ts_bspline_control_points(&spline);
	if (!ctrlp)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_ctrlp = ts_bspline_num_control_points(&spline);
	tinyspline::real *begin  = ctrlp;
	tinyspline::real *end = begin + num_ctrlp * dimension();
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete ctrlp;
	return vec;
}

std::vector<tinyspline::real> tinyspline::BSpline::knots() const
{
	tsReal *knots = ts_bspline_knots(&spline);
	if (!knots)
		throw std::runtime_error(ts_enum_str(TS_MALLOC));
	size_t num_knots = ts_bspline_num_knots(&spline);
	tinyspline::real *begin = knots;
	tinyspline::real *end = begin + num_knots;
	std::vector<tinyspline::real> vec =
		std::vector<tinyspline::real>(begin, end);
	delete knots;
	return vec;
}

tsBSpline * tinyspline::BSpline::data()
{
	return &spline;
}

tinyspline::DeBoorNet tinyspline::BSpline::eval(tinyspline::real u) const
{
	tinyspline::DeBoorNet deBoorNet;
	tsError err = ts_bspline_eval(&spline, u, deBoorNet.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return deBoorNet;
}

void tinyspline::BSpline::setControlPoints(
	const std::vector<tinyspline::real> &ctrlp)
{
	size_t expected = ts_bspline_len_control_points(&spline);
	size_t actual = ctrlp.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_control_points(&spline, ctrlp.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

void tinyspline::BSpline::setKnots(const std::vector<tinyspline::real> &knots)
{
	size_t expected = ts_bspline_num_knots(&spline);
	size_t actual = knots.size();
	if (expected != actual) {
		char expected_str[32];
		char actual_str[32];
		sprintf(expected_str, "%zu", expected);
		sprintf(actual_str, "%zu", actual);
		throw std::runtime_error(
			"Expected size: " + std::string(expected_str) +
			", Actual size: " + std::string(actual_str));
	}
	tsError err = ts_bspline_set_knots(&spline, knots.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
}

tinyspline::BSpline tinyspline::BSpline::fillKnots(tsBSplineType type,
	tinyspline::real min, tinyspline::real max) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_fill_knots(
		&spline, type, min, max, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::insertKnot(tinyspline::real u,
	size_t n) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_insert_knot(&spline, u, n, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::resize(int n, int back) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_resize(&spline, n, back, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::split(tinyspline::real u) const
{
	tinyspline::BSpline bs;
	size_t k;
	tsError err = ts_bspline_split(&spline, u, &bs.spline, &k);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::buckle(tinyspline::real b) const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_buckle(&spline, b, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::toBeziers() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_to_beziers(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

tinyspline::BSpline tinyspline::BSpline::derive() const
{
	tinyspline::BSpline bs;
	tsError err = ts_bspline_derive(&spline, &bs.spline);
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bs;
}

/******************************************************************************
*                                                                             *
* Utils                                                                       *
*                                                                             *
******************************************************************************/
tinyspline::BSpline tinyspline::Utils::interpolateCubic(
	const std::vector<tinyspline::real> *points, size_t dim)
{
	if (dim == 0)
		throw std::runtime_error(ts_enum_str(TS_DIM_ZERO));
	if (points->size() % dim != 0)
		throw std::runtime_error("#points % dim == 0 failed");
	tinyspline::BSpline bspline;
	tsError err = ts_bspline_interpolate_cubic(
		points->data(), points->size()/dim, dim, bspline.data());
	if (err < 0)
		throw std::runtime_error(ts_enum_str(err));
	return bspline;
}

bool tinyspline::Utils::fequals(tinyspline::real x, tinyspline::real y)
{
	return ts_fequals(x, y) == 1;
}

std::string tinyspline::Utils::enum_str(tsError err)
{
	return std::string(ts_enum_str(err));
}

tsError tinyspline::Utils::str_enum(std::string str)
{
	return ts_str_enum(str.c_str());
}
<|endoftext|>


<commit_before>#include "twister_utils.h"

#include <libtorrent/session.hpp>
#include <libtorrent/bencode.hpp>

#include <boost/foreach.hpp>

#include <stdio.h>

using namespace std;
using namespace boost;

twister_utils::twister_utils()
{
}

int load_file(std::string const& filename, std::vector<char>& v, int limit)
{
	FILE* f = fopen(filename.c_str(), "rb");
	if (f == NULL)
		return -1;
	int r = fseek(f, 0, SEEK_END);
	if (r != 0) {
		fclose(f);
		return -1;
	}
	long s = ftell(f);
	if (s < 0) {
		fclose(f);
		return -1;
	}

	if (s > limit) {
		fclose(f);
		return -2;
	}

	r = fseek(f, 0, SEEK_SET);
	if (r != 0) {
		fclose(f);
		return -1;
	}

	v.resize(s);
	if (s == 0) {
		fclose(f);
		return 0;
	}

	r = fread(&v[0], 1, v.size(), f);
	if (r < 0) {
		fclose(f);
		return -1;
	}

	fclose(f);

	if (r != s) return -3;

	return 0;
}

int save_file(std::string const& filename, std::vector<char>& v)
{
	using namespace libtorrent;

	// TODO: don't use internal file type here. use fopen()
	file f;
	error_code ec;
	if (!f.open(filename, file::write_only, ec)) return -1;
	if (ec) return -1;
	file::iovec_t b = {&v[0], v.size()};
	size_type written = f.writev(0, &b, 1, ec);
	if (written != int(v.size())) return -3;
	if (ec) return -3;
	return 0;
}

using namespace json_spirit;
using namespace libtorrent;

Value entryToJson(const entry &e)
{
    Array lst;
    Object o;
    switch( e.type() ) {
        case entry::int_t:
            return e.integer();
        case entry::string_t:
            return e.string();
        case entry::list_t:
            for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i) {
                lst.push_back( entryToJson(*i) );
            }
            return lst;
        case entry::dictionary_t:
            for (entry::dictionary_type::const_iterator i = e.dict().begin(); i != e.dict().end(); ++i) {
                o.push_back(Pair(i->first, entryToJson(i->second)));
            }
            return o;
        default:
            return string("<uninitialized>");
    }
}

entry jsonToEntry(const Value &v)
{
    entry::list_type lst;
    entry::dictionary_type dict;

    switch( v.type() ) {
        case int_type:
            return v.get_int();
        case str_type:
            return v.get_str();
        case array_type:
            for (Array::const_iterator i = v.get_array().begin(); i != v.get_array().end(); ++i) {
                lst.push_back( jsonToEntry(*i) );
            }
            return lst;
        case obj_type:
            for (Object::const_iterator i = v.get_obj().begin(); i != v.get_obj().end(); ++i) {
                dict[ i->name_ ] = jsonToEntry(i->value_);
            }
            return dict;
        default:
            return string("<uninitialized>");
    }
}

int saveUserData(std::string const& filename, std::map<std::string,UserData> const &users)
{
    entry userEntry;

    std::map<std::string,UserData>::const_iterator i;
    for (i = users.begin(); i != users.end(); ++i) {
        UserData const &data = i->second;

        entry &dataEntry = userEntry[i->first];
        entry &followingEntry = dataEntry["following"];
        BOOST_FOREACH( std::string const &n, data.m_following) {
            followingEntry.list().push_back(n);
        }

        entry &dmEntry = dataEntry["dm"];

        std::map<std::string, std::list<StoredDirectMsg> >::const_iterator j;
        for (j = data.m_directmsg.begin(); j != data.m_directmsg.end(); ++j) {
            std::list<StoredDirectMsg> const &stoDmList = j->second;

            entry &stoDmLstEntry = dmEntry[j->first];
            BOOST_FOREACH( StoredDirectMsg const &dm, stoDmList) {
                entry stoDmEntry;
                stoDmEntry["time"] = dm.m_utcTime;
                stoDmEntry["text"] = dm.m_text;
                stoDmEntry["fromMe"] = dm.m_fromMe;
                stoDmLstEntry.list().push_back(stoDmEntry);
            }
        }
    }

    std::vector<char> buf;
    bencode(std::back_inserter(buf), userEntry);

    return save_file(filename, buf);
}

int loadUserData(std::string const& filename, std::map<std::string,UserData> &users)
{
    std::vector<char> in;
    if (load_file(filename, in) == 0) {
        lazy_entry userEntry;
        error_code ec;
        if (lazy_bdecode(&in[0], &in[0] + in.size(), userEntry, ec) == 0) {
            for( int i = 0; i < userEntry.dict_size(); i++) {
                UserData data;

                const lazy_entry *dataEntry = userEntry.dict_at(i).second;
                const lazy_entry *followingEntry = dataEntry->dict_find("following");
                for( int j = 0; j < followingEntry->list_size(); j++ ) {
                    data.m_following.insert( followingEntry->list_string_value_at(j) );
                }

                const lazy_entry *dmEntry = dataEntry->dict_find("dm");
                for( int j = 0; j < dmEntry->dict_size(); j++ ) {
                    const lazy_entry *stoDmLstEntry = dmEntry->dict_at(j).second;

                    for( int k = 0; k < stoDmLstEntry->list_size(); k++ ) {
                        const lazy_entry *stoDmEntry = stoDmLstEntry->list_at(k);
                        StoredDirectMsg dm;
                        dm.m_text    = stoDmEntry->dict_find_string_value("text");
                        dm.m_utcTime = stoDmEntry->dict_find_int_value("time");
                        dm.m_fromMe  = stoDmEntry->dict_find_int_value("fromMe");
                        data.m_directmsg[dmEntry->dict_at(j).first].push_back(dm);
                    }
                }

                users[userEntry.dict_at(i).first] = data;
            }
            return 0;
        }
    }
    return -1;
}

<commit_msg>do lazy_entry type checking in loadUserData<commit_after>#include "twister_utils.h"

#include <libtorrent/session.hpp>
#include <libtorrent/bencode.hpp>

#include <boost/foreach.hpp>

#include <stdio.h>

using namespace std;
using namespace boost;

twister_utils::twister_utils()
{
}

int load_file(std::string const& filename, std::vector<char>& v, int limit)
{
	FILE* f = fopen(filename.c_str(), "rb");
	if (f == NULL)
		return -1;
	int r = fseek(f, 0, SEEK_END);
	if (r != 0) {
		fclose(f);
		return -1;
	}
	long s = ftell(f);
	if (s < 0) {
		fclose(f);
		return -1;
	}

	if (s > limit) {
		fclose(f);
		return -2;
	}

	r = fseek(f, 0, SEEK_SET);
	if (r != 0) {
		fclose(f);
		return -1;
	}

	v.resize(s);
	if (s == 0) {
		fclose(f);
		return 0;
	}

	r = fread(&v[0], 1, v.size(), f);
	if (r < 0) {
		fclose(f);
		return -1;
	}

	fclose(f);

	if (r != s) return -3;

	return 0;
}

int save_file(std::string const& filename, std::vector<char>& v)
{
	using namespace libtorrent;

	// TODO: don't use internal file type here. use fopen()
	file f;
	error_code ec;
	if (!f.open(filename, file::write_only, ec)) return -1;
	if (ec) return -1;
	file::iovec_t b = {&v[0], v.size()};
	size_type written = f.writev(0, &b, 1, ec);
	if (written != int(v.size())) return -3;
	if (ec) return -3;
	return 0;
}

using namespace json_spirit;
using namespace libtorrent;

Value entryToJson(const entry &e)
{
    Array lst;
    Object o;
    switch( e.type() ) {
        case entry::int_t:
            return e.integer();
        case entry::string_t:
            return e.string();
        case entry::list_t:
            for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i) {
                lst.push_back( entryToJson(*i) );
            }
            return lst;
        case entry::dictionary_t:
            for (entry::dictionary_type::const_iterator i = e.dict().begin(); i != e.dict().end(); ++i) {
                o.push_back(Pair(i->first, entryToJson(i->second)));
            }
            return o;
        default:
            return string("<uninitialized>");
    }
}

entry jsonToEntry(const Value &v)
{
    entry::list_type lst;
    entry::dictionary_type dict;

    switch( v.type() ) {
        case int_type:
            return v.get_int();
        case str_type:
            return v.get_str();
        case array_type:
            for (Array::const_iterator i = v.get_array().begin(); i != v.get_array().end(); ++i) {
                lst.push_back( jsonToEntry(*i) );
            }
            return lst;
        case obj_type:
            for (Object::const_iterator i = v.get_obj().begin(); i != v.get_obj().end(); ++i) {
                dict[ i->name_ ] = jsonToEntry(i->value_);
            }
            return dict;
        default:
            return string("<uninitialized>");
    }
}

int saveUserData(std::string const& filename, std::map<std::string,UserData> const &users)
{
    entry userEntry;

    std::map<std::string,UserData>::const_iterator i;
    for (i = users.begin(); i != users.end(); ++i) {
        UserData const &data = i->second;

        entry &dataEntry = userEntry[i->first];
        entry &followingEntry = dataEntry["following"];
        BOOST_FOREACH( std::string const &n, data.m_following) {
            followingEntry.list().push_back(n);
        }

        entry &dmEntry = dataEntry["dm"];

        std::map<std::string, std::list<StoredDirectMsg> >::const_iterator j;
        for (j = data.m_directmsg.begin(); j != data.m_directmsg.end(); ++j) {
            std::list<StoredDirectMsg> const &stoDmList = j->second;

            entry &stoDmLstEntry = dmEntry[j->first];
            BOOST_FOREACH( StoredDirectMsg const &dm, stoDmList) {
                entry stoDmEntry;
                stoDmEntry["time"] = dm.m_utcTime;
                stoDmEntry["text"] = dm.m_text;
                stoDmEntry["fromMe"] = dm.m_fromMe;
                stoDmLstEntry.list().push_back(stoDmEntry);
            }
        }
    }

    std::vector<char> buf;
    bencode(std::back_inserter(buf), userEntry);

    return save_file(filename, buf);
}

int loadUserData(std::string const& filename, std::map<std::string,UserData> &users)
{
    std::vector<char> in;
    if (load_file(filename, in) == 0) {
        lazy_entry userEntry;
        error_code ec;
        if (lazy_bdecode(&in[0], &in[0] + in.size(), userEntry, ec) == 0) {
            if( userEntry.type() != lazy_entry::dict_t ) goto data_error;
            for( int i = 0; i < userEntry.dict_size(); i++) {
                UserData data;

                const lazy_entry *dataEntry = userEntry.dict_at(i).second;
                const lazy_entry *followingEntry = dataEntry->dict_find("following");
                if( followingEntry->type() != lazy_entry::list_t ) goto data_error;

                for( int j = 0; j < followingEntry->list_size(); j++ ) {
                    data.m_following.insert( followingEntry->list_string_value_at(j) );
                }

                const lazy_entry *dmEntry = dataEntry->dict_find("dm");
                if( dmEntry->type() != lazy_entry::dict_t ) goto data_error;

                for( int j = 0; j < dmEntry->dict_size(); j++ ) {
                    const lazy_entry *stoDmLstEntry = dmEntry->dict_at(j).second;
                    if( stoDmLstEntry->type() != lazy_entry::list_t ) goto data_error;

                    for( int k = 0; k < stoDmLstEntry->list_size(); k++ ) {
                        const lazy_entry *stoDmEntry = stoDmLstEntry->list_at(k);
                        if( stoDmEntry->type() != lazy_entry::dict_t ) goto data_error;

                        StoredDirectMsg dm;
                        dm.m_text    = stoDmEntry->dict_find_string_value("text");
                        dm.m_utcTime = stoDmEntry->dict_find_int_value("time");
                        dm.m_fromMe  = stoDmEntry->dict_find_int_value("fromMe");
                        data.m_directmsg[dmEntry->dict_at(j).first].push_back(dm);
                    }
                }
                users[userEntry.dict_at(i).first] = data;
            }
            return 0;
        }
    }
    return -1;

data_error:
    printf("loadUserData: unexpected bencode type - user_data corrupt!\n");
    return -2;
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  NetworksProject
//
//  Created by Patrick Dang-Ho on 2017-03-12.
//  Copyright © 2017 Patrick Dang-Ho. All rights reserved.
//

#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}
<commit_msg>deleted main.cpp in task3 folder<commit_after><|endoftext|>


<commit_before>#include <QMessageBox>

#include "helpwindow.h"
#include "helpwidget.h"

#include "ui_helpwindow.h"

#include <QClipboard>
#include <QMenu>
#include <QPrintDialog>
#include <QPrinter>

HelpWindow::HelpWindow(QHelpEngine *pHelpEngine, const QUrl &pHomePage,
                       QWidget *pParent) :
    QDockWidget(pParent),
    mUi(new Ui::HelpWindow)
{
    // Set up the UI

    mUi->setupUi(this);

    // Assign an action to the different 'toolbar' buttons

    mUi->homeButton->setDefaultAction(mUi->actionHome);

    mUi->backButton->setDefaultAction(mUi->actionBack);
    mUi->forwardButton->setDefaultAction(mUi->actionForward);

    mUi->copyButton->setDefaultAction(mUi->actionCopy);

    mUi->normalSizeButton->setDefaultAction(mUi->actionNormalSize);

    mUi->zoomInButton->setDefaultAction(mUi->actionZoomIn);
    mUi->zoomOutButton->setDefaultAction(mUi->actionZoomOut);

    mUi->printButton->setDefaultAction(mUi->actionPrint);

    // Create and add the help widget

    mHelpWidget = new HelpWidget(pHelpEngine, pHomePage);

    mUi->verticalLayout->addWidget(mHelpWidget);

    // Prevent objects from being dropped on the help widget

    mHelpWidget->setAcceptDrops(false);

    // We want our own context menu for the help widget (indeed, we don't want
    // the default one which has the reload menu item and not the other actions
    // that we have in our 'toolbar', so...)

    mHelpWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    // Some connections

    connect(mHelpWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(customContextMenu(const QPoint&)));

    connect(mHelpWidget, SIGNAL(urlChanged(const QUrl&)),
            this, SLOT(newUrl(const QUrl&)));

    connect(mHelpWidget, SIGNAL(backAvailable(bool)),
            mUi->actionBack, SLOT(setEnabled(bool)));
    connect(mHelpWidget, SIGNAL(forwardAvailable(bool)),
            mUi->actionForward, SLOT(setEnabled(bool)));

    connect(mHelpWidget->page(), SIGNAL(selectionChanged()),
            this, SLOT(newSelection()));

    connect(mHelpWidget, SIGNAL(zoomLevelChanged(int)),
            this, SLOT(newZoomLevel(int)));
}

HelpWindow::~HelpWindow()
{
    // Delete the UI

    delete mUi;
}

void HelpWindow::retranslateUi()
{
    // Translate the whole window

    mUi->retranslateUi(this);

    // Make sure that the enabled state of the various actions is correct
    // (indeed, to translate everything messes things up in that respect,
    // so...)

    mUi->actionHome->setEnabled(mHelpWidget->url() != mHelpWidget->homePage());

    mUi->actionBack->setEnabled(mHelpWidget->isBackAvailable());
    mUi->actionForward->setEnabled(mHelpWidget->isForwardAvailable());

    mUi->actionCopy->setEnabled(!mHelpWidget->selectedText().isEmpty());

    mUi->actionNormalSize->setEnabled(mHelpWidget->zoomLevel() != mHelpWidget->defaultZoomLevel());

    mUi->actionZoomOut->setEnabled(mHelpWidget->zoomLevel() != mHelpWidget->minimumZoomLevel());
}

void HelpWindow::defaultSettings()
{
    // Set the default settings for the help widget

    mHelpWidget->defaultSettings();
}

void HelpWindow::gotoHomePage()
{
    // Go to the home page

    mHelpWidget->gotoHomePage();
}

int HelpWindow::defaultZoomLevel()
{
    // Return the default zoom level for the help widget

    return mHelpWidget->defaultZoomLevel();
}

void HelpWindow::setZoomLevel(const int &pZoomLevel)
{
    // Set the zoom level for the help widget

    mHelpWidget->setZoomLevel(pZoomLevel);
}

int HelpWindow::zoomLevel()
{
    // Return the current zoom level for the help widget

    return mHelpWidget->zoomLevel();
}

void HelpWindow::on_actionHome_triggered()
{
    // Go to the home page

    mHelpWidget->gotoHomePage();
}

void HelpWindow::on_actionBack_triggered()
{
    // Go to the previous help page

    mHelpWidget->back();
}

void HelpWindow::on_actionForward_triggered()
{
    // Go to the next help page

    mHelpWidget->forward();
}

void HelpWindow::on_actionCopy_triggered()
{
    // Copy the current slection to the clipboard

    QApplication::clipboard()->setText(mHelpWidget->selectedText());
}

void HelpWindow::on_actionNormalSize_triggered()
{
    // Reset the zoom level of the help page contents

    mHelpWidget->resetZoom();
}

void HelpWindow::on_actionZoomIn_triggered()
{
    // Zoom in the help page contents

    mHelpWidget->zoomIn();
}

void HelpWindow::on_actionZoomOut_triggered()
{
    // Zoom out the help page contents

    mHelpWidget->zoomOut();
}

void HelpWindow::on_actionPrint_triggered()
{
    // Retrieve the printer with which the user wants to print the help page
    // and print it, should s/he still want to go ahead with the printing

    QPrinter printer;

    QPrintDialog *dialog = new QPrintDialog(&printer);

    if ( dialog->exec() == QDialog::Accepted)
          mHelpWidget->print(&printer);
}

void HelpWindow::customContextMenu(const QPoint &pPos)
{
    // Create a custom context menu which items match the contents of our
    // 'toolbar'

    QMenu *menu = new QMenu;

    menu->addAction(mUi->actionHome);
    menu->addSeparator();
    menu->addAction(mUi->actionBack);
    menu->addAction(mUi->actionForward);
    menu->addSeparator();
    menu->addAction(mUi->actionCopy);
    menu->addSeparator();
    menu->addAction(mUi->actionNormalSize);
    menu->addSeparator();
    menu->addAction(mUi->actionZoomIn);
    menu->addAction(mUi->actionZoomOut);
    menu->addSeparator();
    menu->addAction(mUi->actionPrint);

    menu->exec(mapToGlobal(pPos));
}

void HelpWindow::newUrl(const QUrl &pNewUrl)
{
    // The help page contents has changed, so determine whether the home action
    // should now be enabled or not

    mUi->actionHome->setEnabled(pNewUrl != mHelpWidget->homePage());
}

void HelpWindow::newSelection()
{
    // The selection in the help widget has changed, so determine whether the
    // copy action should now be enabled or not

    mUi->actionCopy->setEnabled(!mHelpWidget->selectedText().isEmpty());
}

void HelpWindow::newZoomLevel(const int &pNewZoomLevel)
{
    // The help page contents has been zoomed in/out or reset, so update the
    // relevant actions

    mUi->actionNormalSize->setEnabled(pNewZoomLevel != mHelpWidget->defaultZoomLevel());

    mUi->actionZoomOut->setEnabled(pNewZoomLevel != mHelpWidget->minimumZoomLevel());
}
<commit_msg>Cleaned up src/ui/helpwindow.cpp.<commit_after>#include "helpwindow.h"
#include "helpwidget.h"

#include "ui_helpwindow.h"

#include <QClipboard>
#include <QMenu>
#include <QPrintDialog>
#include <QPrinter>

HelpWindow::HelpWindow(QHelpEngine *pHelpEngine, const QUrl &pHomePage,
                       QWidget *pParent) :
    QDockWidget(pParent),
    mUi(new Ui::HelpWindow)
{
    // Set up the UI

    mUi->setupUi(this);

    // Assign an action to the different 'toolbar' buttons

    mUi->homeButton->setDefaultAction(mUi->actionHome);

    mUi->backButton->setDefaultAction(mUi->actionBack);
    mUi->forwardButton->setDefaultAction(mUi->actionForward);

    mUi->copyButton->setDefaultAction(mUi->actionCopy);

    mUi->normalSizeButton->setDefaultAction(mUi->actionNormalSize);

    mUi->zoomInButton->setDefaultAction(mUi->actionZoomIn);
    mUi->zoomOutButton->setDefaultAction(mUi->actionZoomOut);

    mUi->printButton->setDefaultAction(mUi->actionPrint);

    // Create and add the help widget

    mHelpWidget = new HelpWidget(pHelpEngine, pHomePage);

    mUi->verticalLayout->addWidget(mHelpWidget);

    // Prevent objects from being dropped on the help widget

    mHelpWidget->setAcceptDrops(false);

    // We want our own context menu for the help widget (indeed, we don't want
    // the default one which has the reload menu item and not the other actions
    // that we have in our 'toolbar', so...)

    mHelpWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    // Some connections

    connect(mHelpWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(customContextMenu(const QPoint&)));

    connect(mHelpWidget, SIGNAL(urlChanged(const QUrl&)),
            this, SLOT(newUrl(const QUrl&)));

    connect(mHelpWidget, SIGNAL(backAvailable(bool)),
            mUi->actionBack, SLOT(setEnabled(bool)));
    connect(mHelpWidget, SIGNAL(forwardAvailable(bool)),
            mUi->actionForward, SLOT(setEnabled(bool)));

    connect(mHelpWidget->page(), SIGNAL(selectionChanged()),
            this, SLOT(newSelection()));

    connect(mHelpWidget, SIGNAL(zoomLevelChanged(int)),
            this, SLOT(newZoomLevel(int)));
}

HelpWindow::~HelpWindow()
{
    // Delete the UI

    delete mUi;
}

void HelpWindow::retranslateUi()
{
    // Translate the whole window

    mUi->retranslateUi(this);

    // Make sure that the enabled state of the various actions is correct
    // (indeed, to translate everything messes things up in that respect,
    // so...)

    mUi->actionHome->setEnabled(mHelpWidget->url() != mHelpWidget->homePage());

    mUi->actionBack->setEnabled(mHelpWidget->isBackAvailable());
    mUi->actionForward->setEnabled(mHelpWidget->isForwardAvailable());

    mUi->actionCopy->setEnabled(!mHelpWidget->selectedText().isEmpty());

    mUi->actionNormalSize->setEnabled(mHelpWidget->zoomLevel() != mHelpWidget->defaultZoomLevel());

    mUi->actionZoomOut->setEnabled(mHelpWidget->zoomLevel() != mHelpWidget->minimumZoomLevel());
}

void HelpWindow::defaultSettings()
{
    // Set the default settings for the help widget

    mHelpWidget->defaultSettings();
}

void HelpWindow::gotoHomePage()
{
    // Go to the home page

    mHelpWidget->gotoHomePage();
}

int HelpWindow::defaultZoomLevel()
{
    // Return the default zoom level for the help widget

    return mHelpWidget->defaultZoomLevel();
}

void HelpWindow::setZoomLevel(const int &pZoomLevel)
{
    // Set the zoom level for the help widget

    mHelpWidget->setZoomLevel(pZoomLevel);
}

int HelpWindow::zoomLevel()
{
    // Return the current zoom level for the help widget

    return mHelpWidget->zoomLevel();
}

void HelpWindow::on_actionHome_triggered()
{
    // Go to the home page

    mHelpWidget->gotoHomePage();
}

void HelpWindow::on_actionBack_triggered()
{
    // Go to the previous help page

    mHelpWidget->back();
}

void HelpWindow::on_actionForward_triggered()
{
    // Go to the next help page

    mHelpWidget->forward();
}

void HelpWindow::on_actionCopy_triggered()
{
    // Copy the current slection to the clipboard

    QApplication::clipboard()->setText(mHelpWidget->selectedText());
}

void HelpWindow::on_actionNormalSize_triggered()
{
    // Reset the zoom level of the help page contents

    mHelpWidget->resetZoom();
}

void HelpWindow::on_actionZoomIn_triggered()
{
    // Zoom in the help page contents

    mHelpWidget->zoomIn();
}

void HelpWindow::on_actionZoomOut_triggered()
{
    // Zoom out the help page contents

    mHelpWidget->zoomOut();
}

void HelpWindow::on_actionPrint_triggered()
{
    // Retrieve the printer with which the user wants to print the help page
    // and print it, should s/he still want to go ahead with the printing

    QPrinter printer;

    QPrintDialog *dialog = new QPrintDialog(&printer);

    if ( dialog->exec() == QDialog::Accepted)
          mHelpWidget->print(&printer);
}

void HelpWindow::customContextMenu(const QPoint &pPos)
{
    // Create a custom context menu which items match the contents of our
    // 'toolbar'

    QMenu *menu = new QMenu;

    menu->addAction(mUi->actionHome);
    menu->addSeparator();
    menu->addAction(mUi->actionBack);
    menu->addAction(mUi->actionForward);
    menu->addSeparator();
    menu->addAction(mUi->actionCopy);
    menu->addSeparator();
    menu->addAction(mUi->actionNormalSize);
    menu->addSeparator();
    menu->addAction(mUi->actionZoomIn);
    menu->addAction(mUi->actionZoomOut);
    menu->addSeparator();
    menu->addAction(mUi->actionPrint);

    menu->exec(mapToGlobal(pPos));
}

void HelpWindow::newUrl(const QUrl &pNewUrl)
{
    // The help page contents has changed, so determine whether the home action
    // should now be enabled or not

    mUi->actionHome->setEnabled(pNewUrl != mHelpWidget->homePage());
}

void HelpWindow::newSelection()
{
    // The selection in the help widget has changed, so determine whether the
    // copy action should now be enabled or not

    mUi->actionCopy->setEnabled(!mHelpWidget->selectedText().isEmpty());
}

void HelpWindow::newZoomLevel(const int &pNewZoomLevel)
{
    // The help page contents has been zoomed in/out or reset, so update the
    // relevant actions

    mUi->actionNormalSize->setEnabled(pNewZoomLevel != mHelpWidget->defaultZoomLevel());

    mUi->actionZoomOut->setEnabled(pNewZoomLevel != mHelpWidget->minimumZoomLevel());
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  udpforwarder
//
//  Created by Shakthi Prasad G S on 23/10/16.
//  Copyright © 2016 self. All rights reserved.
//

#include <iostream>
#include <string>

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <poll.h>

/* udp-repeater
 *
 * example of use
 *
 *   udp-reflector -p 6180 -l localhost -a node1.net:2222 -b node2.net:2222
 *
 * This causes udp-reflector to listen on the local matchine (port 6180;
 * you can also bind a particular local IP address with the -l flag).
 * Whenever a UDP datagram is received from a, it is re-sent to destination b
 * (specified with the -b flag), and vice versa
 *
 * To test it, run udp-repeater with appropriate arguments, set up a sink
 * to receive the datagrams somewhere, like:
 *
 *   destination1% nc -l -u 6180
 *
 * then generate some UDP datagrams to the repeater, e.g.,
 *
 *   somewhere% echo hi | nc -4 -u repeater-host 6180
 *
 * you sould see the udp datagram repeated on destination1.
 *
 * NOTE: when using nc to generate traffic, if you omit the -4 flag
 *       and use a name (such as localhost) instead of an IPv4 address
 *       nc will use an IPv6 UDP datagram, which udp-repeater does not
 *       currently accept.
 *
 */

#define BUFSZ 2000
char buf[BUFSZ];
char *ip,*prog;
int port;

int verbose;

struct sockaddr_in dest;

void usage() {
    fprintf(stderr, "usage: %s [-v] [-l <bind-addr>] "
            "-p <bindport> -s <host>[:<port>] [-S sourceport] ...\n", prog);
    exit(-1);
}

class SocketAddress
{
    struct sockaddr_in socketAddress;

    sockaddr_in getAddress(std::string address)
    {
        std::string::size_type colonpos=address.find(':');

        if(colonpos == std::string::npos){

            std::cerr <<"Unformated address"<<address<<" host:port format expected"<<std::endl;
            exit(-1);
        }

        std::string host= address.substr(0,colonpos);
        std::string port= address.substr(colonpos+1);

        sockaddr_in dest;

        dest.sin_family = AF_INET;
        dest.sin_port = htons(atoi(port.c_str()));
        struct hostent *h = gethostbyname(host.c_str());
        if (!h || !h->h_length) {
            std::cerr<< "could not resolve "<<host<<":"<< hstrerror(h_errno)<<std::endl;
            exit(-1);
        }

        memcpy(&dest.sin_addr, h->h_addr, h->h_length);
        if (dest.sin_addr.s_addr == INADDR_NONE) {
            std::cerr<< "invalid IP address for "<<host<<std::endl;
            exit(-1);
        }

        if (verbose)
            std::cerr<<"Node "<<host<<"("<<inet_ntoa(dest.sin_addr)<<":"<< atoi(port.c_str())<<")"<<std::endl;

        return dest;
    }

public:
    static int fd;

    SocketAddress()
    {}
    SocketAddress(std::string hostport)
    {
        initialized=true;
        socketAddress = getAddress(hostport);
    }

    SocketAddress(sockaddr_in addr)
    {
        initialized=true;
        socketAddress = addr;
    }

    bool operator==(const SocketAddress & bAddress) const
    {
        return socketAddress.sin_addr.s_addr  == bAddress.socketAddress.sin_addr.s_addr &&
        socketAddress.sin_port == bAddress.socketAddress.sin_port;

    }

    bool initialized = false;

    const std::string  to_string()
    {
        std::string address =inet_ntoa(socketAddress.sin_addr);
        address+=":";

        address+=std::to_string(ntohs(socketAddress.sin_port) );

        return address;

    }
    bool Send(void * buffer,size_t len)
    {

        ssize_t sc = sendto(fd, buffer, len, 0, (struct sockaddr*)&socketAddress, sizeof(&socketAddress));
        if (sc != len) {
            fprintf(stderr, "sendto %s: %s\n", inet_ntoa(socketAddress.sin_addr),
                    (sc==0)?strerror(errno):"partial write");
            exit(-1);
        }

        if(verbose>0)
            fprintf(stderr, "send %zu bytes to %s\n", len,to_string().c_str());

       return true;
    }

    static const SocketAddress ReciveAny(void * buffer,size_t & len)
    {

        struct sockaddr_in cin;
        socklen_t cin_sz = sizeof(cin);

        size_t rc = recvfrom(fd,buf,BUFSZ,0,(struct sockaddr*)&cin,&cin_sz);
        len = rc;
        SocketAddress sa(cin);

        if(verbose>0)
            fprintf(stderr, "recieved %zu bytes from %s\n", rc,sa.to_string().c_str());

        return sa;

    }

};

int SocketAddress::fd;

int main(int argc, const char** argv) {

    if(argc<2)
    {

        const char* n_argv[] = { "udpforaward", "-vp", "6008", "-l","127.0.0.1","-a",
            "127.0.0.1:60001","-B","127.0.0.1:7001"};

        const char* m_argv[] = { "udpforaward", "-vp", "7001", "-l","127.0.0.1","-1","-b","127.0.0.1:50001"};

    argv = n_argv;
#if CLIENT
    argv = m_argv;
#endif
    argc=9;

    }

     prog = strdup(argv[0]);
    char  opt;

    SocketAddress sa;
    SocketAddress sb;

    bool connecta=false,connectb=false;

    bool revieveb=false,recievea=false;

    while ( (opt = getopt(argc, (char* * const )argv, "v+l:p:a:b:A:B:12")) != -1) {
        switch (opt) {
                case 'v': verbose++; break;
                case 'l': ip = strdup(optarg); break;
                case 'p': port = atoi(optarg); break;
                case 'a': sa = SocketAddress(optarg); break;
                case 'b': sb = SocketAddress(optarg); break;

                case 'A': sa = SocketAddress(optarg); connecta=true;break;
                case 'B': sb = SocketAddress(optarg); connectb=true;break;
                case '1':  recievea=true;break;
                case '2':  revieveb=true;break;

            default: usage(); break;
        }
    }

    if (!port) usage();

    in_addr_t listen_addr;
    if (ip) {
        if ( (listen_addr = inet_addr(ip)) == INADDR_NONE) {
            fprintf(stderr,"invalid listener IP address: %s\n", ip);
            exit(-1);
        }
    } else {
        listen_addr = htonl(INADDR_ANY);
        ip = strdup("all-local-addresses");
    }
    if (verbose) fprintf(stderr, "local address: %s:%d\n", ip, port);

    /**********************************************************
     * create two IPv4/UDP sockets, for listener and repeater
     *********************************************************/
    SocketAddress::fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (SocketAddress::fd == -1 ) { fprintf(stderr,"socket error\n"); exit(-1); }

    /**********************************************************
     * internet socket address structure: our address and port
     *********************************************************/
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = listen_addr;
    sin.sin_port = htons(port);

    /**********************************************************
     * bind socket to address and port we'd like to receive on
     *********************************************************/
    if (bind(SocketAddress::fd, (struct sockaddr*)&sin, sizeof(sin)) == -1) {
        fprintf(stderr, "listen bind to %s:%d failed: %s\n", ip, port, strerror(errno));
        exit(-1);
    }

    while (true)  {

        /**********************************************************
         * uses recvfrom to get data along with client address/port
         *********************************************************/
        int random= rand();

        if(sa.initialized && connecta)
        {
            std::string testConnection="testConnection"+std::to_string(random);
            if(verbose>0)
                fprintf(stderr, "testConnection  to %s\n", sa.to_string().c_str());

            sa.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if (sb.initialized && connectb)
        {
            std::string testConnection="testConnection"+std::to_string(random);

            if(verbose>0)
                fprintf(stderr, "testConnection  to %s\n", sb.to_string().c_str());
            sb.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if(connectb||connecta)
        {
            struct pollfd pfdfd;
            int ret;

            pfdfd.fd = SocketAddress::fd; // your socket handler
            pfdfd.events = POLLIN;
            ret = poll(&pfdfd, 1, 1000); // 1 second for timeout

            if(ret == 0 || ret ==-1)
                continue;
        }

        size_t len;
        SocketAddress recivedAddress = SocketAddress::ReciveAny(buf, len);

        if(sa.initialized && sb.initialized)
        {
            if(recivedAddress == sa )
            {
                if(!recievea && !connecta)
                sb.Send(buf, len);
            }

            else if(recivedAddress == sb)
            {
                if(!revieveb && !connectb)

                sa.Send(buf, len);
            }
            else
            {
                printf("Discarding ");
            }
        }else if(sa.initialized && ! sb.initialized)
        {

            if(!(recivedAddress==sa))
            {
                sb= recivedAddress;

                if(!revieveb)
                    sa.Send(buf, len);

            }else
            {
                printf("Discarding  ");
            }

        }else if(!sa.initialized &&  sb.initialized){

            if(!(recivedAddress==sb))
            {
                sa= recivedAddress;

                if(!recievea)
                    sb.Send(buf, len);

            }else
            {
                printf("Discarding  ");
            }

        }

        else if (!sa.initialized && ! sb.initialized)
        {

            sa = recivedAddress;

        }

        if(recivedAddress == sa && connecta )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection=="testConnection")
            {
                connecta =false;
                fprintf(stderr, "connection scuccedded  to %s\n", sa.to_string().c_str());

            }

        }

        if (recivedAddress == sb && connectb)
        {
            std::string testConnection1="testConnection"+std::to_string(random);

            std::string testConnection=std::string(buf,len);
            if(testConnection==testConnection1)
            {
                fprintf(stderr, "connection scuccedded  to %s\n", sb.to_string().c_str());
                connectb =false;
            }

        }

        if(recivedAddress == sa && recievea )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection.find("testConnection")==std::string::npos)
                exit(-1);
            else
                recivedAddress.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if (recivedAddress == sb && revieveb )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection.find("testConnection")==std::string::npos)
                exit(-1);
            else
                recivedAddress.Send((void*)testConnection.c_str(), testConnection.length());

        }

    }

}<commit_msg>changed fprint to err<commit_after>//
//  main.cpp
//  udpforwarder
//
//  Created by Shakthi Prasad G S on 23/10/16.
//  Copyright © 2016 self. All rights reserved.
//

#include <iostream>
#include <string>

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <poll.h>

/* udp-repeater
 *
 * example of use
 *
 *   udp-reflector -p 6180 -l localhost -a node1.net:2222 -b node2.net:2222
 *
 * This causes udp-reflector to listen on the local matchine (port 6180;
 * you can also bind a particular local IP address with the -l flag).
 * Whenever a UDP datagram is received from a, it is re-sent to destination b
 * (specified with the -b flag), and vice versa
 *
 * To test it, run udp-repeater with appropriate arguments, set up a sink
 * to receive the datagrams somewhere, like:
 *
 *   destination1% nc -l -u 6180
 *
 * then generate some UDP datagrams to the repeater, e.g.,
 *
 *   somewhere% echo hi | nc -4 -u repeater-host 6180
 *
 * you sould see the udp datagram repeated on destination1.
 *
 * NOTE: when using nc to generate traffic, if you omit the -4 flag
 *       and use a name (such as localhost) instead of an IPv4 address
 *       nc will use an IPv6 UDP datagram, which udp-repeater does not
 *       currently accept.
 *
 */

#define BUFSZ 2000
char buf[BUFSZ];
char *ip,*prog;
int port;

int verbose;

struct sockaddr_in dest;

void usage() {
    fprintf(stderr, "usage: %s [-v] [-l <bind-addr>] "
            "-p <bindport> -s <host>[:<port>] [-S sourceport] ...\n", prog);
    exit(-1);
}

class SocketAddress
{
    struct sockaddr_in socketAddress;

    sockaddr_in getAddress(std::string address)
    {
        std::string::size_type colonpos=address.find(':');

        if(colonpos == std::string::npos){

            std::cerr <<"Unformated address"<<address<<" host:port format expected"<<std::endl;
            exit(-1);
        }

        std::string host= address.substr(0,colonpos);
        std::string port= address.substr(colonpos+1);

        sockaddr_in dest;

        dest.sin_family = AF_INET;
        dest.sin_port = htons(atoi(port.c_str()));
        struct hostent *h = gethostbyname(host.c_str());
        if (!h || !h->h_length) {
            std::cerr<< "could not resolve "<<host<<":"<< hstrerror(h_errno)<<std::endl;
            exit(-1);
        }

        memcpy(&dest.sin_addr, h->h_addr, h->h_length);
        if (dest.sin_addr.s_addr == INADDR_NONE) {
            std::cerr<< "invalid IP address for "<<host<<std::endl;
            exit(-1);
        }

        if (verbose)
            std::cerr<<"Node "<<host<<"("<<inet_ntoa(dest.sin_addr)<<":"<< atoi(port.c_str())<<")"<<std::endl;

        return dest;
    }

public:
    static int fd;

    SocketAddress()
    {}
    SocketAddress(std::string hostport)
    {
        initialized=true;
        socketAddress = getAddress(hostport);
    }

    SocketAddress(sockaddr_in addr)
    {
        initialized=true;
        socketAddress = addr;
    }

    bool operator==(const SocketAddress & bAddress) const
    {
        return socketAddress.sin_addr.s_addr  == bAddress.socketAddress.sin_addr.s_addr &&
        socketAddress.sin_port == bAddress.socketAddress.sin_port;

    }

    bool initialized = false;

    const std::string  to_string()
    {
        std::string address =inet_ntoa(socketAddress.sin_addr);
        address+=":";

        address+=std::to_string(ntohs(socketAddress.sin_port) );

        return address;

    }
    bool Send(void * buffer,size_t len)
    {

        ssize_t sc = sendto(fd, buffer, len, 0, (struct sockaddr*)&socketAddress, sizeof(&socketAddress));
        if (sc != len) {
            std::cerr<< "sendto " << inet_ntoa(socketAddress.sin_addr)<<((sc==0)?strerror(errno):"partial write");

            exit(-1);
        }

        if(verbose>0)
            std::cerr<< "sent " <<len<<" bytes to "<<to_string()<<std::endl;

       return true;
    }

    static const SocketAddress ReciveAny(void * buffer,size_t & len)
    {

        struct sockaddr_in cin;
        socklen_t cin_sz = sizeof(cin);

        size_t rc = recvfrom(fd,buf,BUFSZ,0,(struct sockaddr*)&cin,&cin_sz);
        len = rc;
        SocketAddress sa(cin);

        if(verbose>0)
            std::cerr<< "recieved "<<rc<<" bytes from " <<sa.to_string()<<std::endl;

        return sa;

    }

};

int SocketAddress::fd;

int main(int argc, const char** argv) {

    if(argc<2)
    {

        const char* n_argv[] = { "udpforaward", "-vp", "6008", "-l","127.0.0.1","-a",
            "127.0.0.1:60001","-B","127.0.0.1:7001"};
#if CLIENT

    const char* m_argv[] = { "udpforaward", "-vp", "7001", "-l","127.0.0.1","-1","-b","127.0.0.1:50001"}
    argv = m_argv;
#else
    argv = n_argv;
#endif

    argc=9;

    }

    prog = strdup(argv[0]);
    char  opt;

    SocketAddress sa;
    SocketAddress sb;

    bool connecta=false,connectb=false;

    bool revieveb=false,recievea=false;

    while ( (opt = getopt(argc, (char* * const )argv, "v+l:p:a:b:A:B:12")) != -1) {
        switch (opt) {
                case 'v': verbose++; break;
                case 'l': ip = strdup(optarg); break;
                case 'p': port = atoi(optarg); break;
                case 'a': sa = SocketAddress(optarg); break;
                case 'b': sb = SocketAddress(optarg); break;

                case 'A': sa = SocketAddress(optarg); connecta=true;break;
                case 'B': sb = SocketAddress(optarg); connectb=true;break;
                case '1':  recievea=true;break;
                case '2':  revieveb=true;break;

            default: usage(); break;
        }
    }

    if (!port) usage();

    in_addr_t listen_addr;
    if (ip) {
        if ( (listen_addr = inet_addr(ip)) == INADDR_NONE) {
            fprintf(stderr,"invalid listener IP address: %s\n", ip);
            exit(-1);
        }
    } else {
        listen_addr = htonl(INADDR_ANY);
        ip = strdup("all-local-addresses");
    }
    if (verbose) fprintf(stderr, "local address: %s:%d\n", ip, port);

    /**********************************************************
     * create two IPv4/UDP sockets, for listener and repeater
     *********************************************************/
    SocketAddress::fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (SocketAddress::fd == -1 ) { fprintf(stderr,"socket error\n"); exit(-1); }

    /**********************************************************
     * internet socket address structure: our address and port
     *********************************************************/
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = listen_addr;
    sin.sin_port = htons(port);

    /**********************************************************
     * bind socket to address and port we'd like to receive on
     *********************************************************/
    if (bind(SocketAddress::fd, (struct sockaddr*)&sin, sizeof(sin)) == -1) {
        fprintf(stderr, "listen bind to %s:%d failed: %s\n", ip, port, strerror(errno));
        exit(-1);
    }

    while (true)  {

        /**********************************************************
         * uses recvfrom to get data along with client address/port
         *********************************************************/
        int random= rand();

        if(sa.initialized && connecta)
        {
            std::string testConnection="testConnection"+std::to_string(random);
            if(verbose>0)
                fprintf(stderr, "testConnection  to %s\n", sa.to_string().c_str());

            sa.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if (sb.initialized && connectb)
        {
            std::string testConnection="testConnection"+std::to_string(random);

            if(verbose>0)
                fprintf(stderr, "testConnection  to %s\n", sb.to_string().c_str());
            sb.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if(connectb||connecta)
        {
            struct pollfd pfdfd;
            int ret;

            pfdfd.fd = SocketAddress::fd; // your socket handler
            pfdfd.events = POLLIN;
            ret = poll(&pfdfd, 1, 1000); // 1 second for timeout

            if(ret == 0 || ret ==-1)
                continue;
        }

        size_t len;
        SocketAddress recivedAddress = SocketAddress::ReciveAny(buf, len);

        if(sa.initialized && sb.initialized)
        {
            if(recivedAddress == sa )
            {
                if(!recievea && !connecta)
                sb.Send(buf, len);
            }

            else if(recivedAddress == sb)
            {
                if(!revieveb && !connectb)

                sa.Send(buf, len);
            }
            else
            {
                std::cerr<<"Discarding "<<len<<"bytes from"<<recivedAddress.to_string()<<std::endl;
            }
        }else if(sa.initialized && ! sb.initialized)
        {

            if(!(recivedAddress==sa))
            {
                sb= recivedAddress;

                if(!revieveb)
                    sa.Send(buf, len);

            }else
            {
                std::cerr<<"Discarding "<<len<<"bytes from"<<recivedAddress.to_string()<<std::endl;
            }

        }else if(!sa.initialized &&  sb.initialized){

            if(!(recivedAddress==sb))
            {
                sa= recivedAddress;

                if(!recievea)
                    sb.Send(buf, len);

            }else
            {
                printf("Discarding  ");
            }

        }

        else if (!sa.initialized && ! sb.initialized)
        {

            sa = recivedAddress;

        }

        if(recivedAddress == sa && connecta )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection=="testConnection")
            {
                connecta = false;
                std::cerr<< "connection scuccedded  to "<<sa.to_string();

            }

        }

        if (recivedAddress == sb && connectb)
        {
            std::string testConnection1="testConnection"+std::to_string(random);

            std::string testConnection=std::string(buf,len);
            if(testConnection==testConnection1)
            {
               std::cerr<< "connection scuccedded  to "<<sb.to_string();
                connectb =false;
            }

        }

        if(recivedAddress == sa && recievea )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection.find("testConnection")==std::string::npos)
                exit(-1);
            else
                recivedAddress.Send((void*)testConnection.c_str(), testConnection.length());

        }

        if (recivedAddress == sb && revieveb )
        {
            std::string testConnection=std::string(buf,len);
            if(testConnection.find("testConnection")==std::string::npos)
                exit(-1);
            else
                recivedAddress.Send((void*)testConnection.c_str(), testConnection.length());

        }

    }

}<|endoftext|>


<commit_before>/* Copyright 2017 - 2022 R. Thomas
 * Copyright 2017 - 2022 Quarkslab
 *
 * Licensed 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 <functional>
#include <numeric>

#include "mbedtls/sha256.h"

#include "LIEF/hash.hpp"

#if defined(LIEF_PE_SUPPORT)
#include "LIEF/PE/hash.hpp"
#endif

#if defined(LIEF_ELF_SUPPORT)
#include "LIEF/ELF/hash.hpp"
#endif

#if defined(LIEF_MACHO_SUPPORT)
#include "LIEF/MachO/hash.hpp"
#endif

#if defined(LIEF_OAT_SUPPORT)
#include "LIEF/OAT/hash.hpp"
#endif

#if defined(LIEF_ART_SUPPORT)
#include "LIEF/ART/hash.hpp"
#endif

#if defined(LIEF_DEX_SUPPORT)
#include "LIEF/DEX/hash.hpp"
#endif

#if defined(LIEF_VDEX_SUPPORT)
#include "LIEF/VDEX/hash.hpp"
#endif

namespace LIEF {

size_t hash(const Object& v) {
  size_t value = 0;

#if defined(LIEF_PE_SUPPORT)
  value = Hash::combine(value, Hash::hash<PE::Hash>(v));
#endif

#if defined(LIEF_ELF_SUPPORT)
  value = Hash::combine(value, Hash::hash<ELF::Hash>(v));
#endif

#if defined(LIEF_MACHO_SUPPORT)
  value = Hash::combine(value, Hash::hash<MachO::Hash>(v));
#endif

#if defined(LIEF_OAT_SUPPORT)
  value = Hash::combine(value, Hash::hash<OAT::Hash>(v));
#endif

#if defined(LIEF_ART_SUPPORT)
  value = Hash::combine(value, Hash::hash<ART::Hash>(v));
#endif

#if defined(LIEF_DEX_SUPPORT)
  value = Hash::combine(value, Hash::hash<DEX::Hash>(v));
#endif

#if defined(LIEF_VDEX_SUPPORT)
  value = Hash::combine(value, Hash::hash<VDEX::Hash>(v));
#endif

  return value;

}

size_t hash(const std::vector<uint8_t>& raw) {
  return Hash::hash(raw);
}

size_t hash(span<const uint8_t> raw) {
  return Hash::hash(raw);
}

Hash::~Hash() = default;

Hash::Hash() :
  value_{0}
{}

Hash::Hash(size_t init_value) :
  value_{init_value}
{}

Hash& Hash::process(const Object& obj) {
  Hash hasher;
  obj.accept(hasher);
  value_ = combine(value_, hasher.value());
  return *this;
}

Hash& Hash::process(size_t integer) {
  value_ = combine(value_, std::hash<size_t>{}(integer));
  return *this;
}

Hash& Hash::process(const std::string& str) {
  value_ = combine(value_, std::hash<std::string>{}(str));
  return *this;
}

Hash& Hash::process(const std::u16string& str) {
  value_ = combine(value_, std::hash<std::u16string>{}(str));
  return *this;
}

Hash& Hash::process(const std::vector<uint8_t>& raw) {
  value_ = combine(value_, Hash::hash(raw));
  return *this;
}

Hash& Hash::process(span<const uint8_t> raw) {
  value_ = combine(value_, Hash::hash(raw));
  return *this;
}

size_t Hash::value() const {
  return value_;
}

// Static methods
// ==============
size_t Hash::hash(const std::vector<uint8_t>& raw) {
  return hash(raw.data(), raw.size());
}

size_t Hash::hash(const void* raw, size_t size) {
  const auto* start = reinterpret_cast<const uint8_t*>(raw);

  std::vector<uint8_t> sha256(32, 0u);
  mbedtls_sha256(start, size, sha256.data(), 0);

  return std::accumulate(std::begin(sha256), std::end(sha256), 0u,
     [] (uint32_t v, uint8_t n) {
        size_t r = v;
        return static_cast<uint32_t>((r << sizeof(uint8_t) * 8u) | n);
     });
}

size_t Hash::hash(span<const uint8_t> raw) {
  return hash(raw.data(), raw.size());
}

}
<commit_msg>Keep the hash value on a ptr size<commit_after>/* Copyright 2017 - 2022 R. Thomas
 * Copyright 2017 - 2022 Quarkslab
 *
 * Licensed 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 <functional>
#include <numeric>

#include "mbedtls/sha256.h"

#include "LIEF/hash.hpp"

#if defined(LIEF_PE_SUPPORT)
#include "LIEF/PE/hash.hpp"
#endif

#if defined(LIEF_ELF_SUPPORT)
#include "LIEF/ELF/hash.hpp"
#endif

#if defined(LIEF_MACHO_SUPPORT)
#include "LIEF/MachO/hash.hpp"
#endif

#if defined(LIEF_OAT_SUPPORT)
#include "LIEF/OAT/hash.hpp"
#endif

#if defined(LIEF_ART_SUPPORT)
#include "LIEF/ART/hash.hpp"
#endif

#if defined(LIEF_DEX_SUPPORT)
#include "LIEF/DEX/hash.hpp"
#endif

#if defined(LIEF_VDEX_SUPPORT)
#include "LIEF/VDEX/hash.hpp"
#endif

namespace LIEF {

size_t hash(const Object& v) {
  size_t value = 0;

#if defined(LIEF_PE_SUPPORT)
  value = Hash::combine(value, Hash::hash<PE::Hash>(v));
#endif

#if defined(LIEF_ELF_SUPPORT)
  value = Hash::combine(value, Hash::hash<ELF::Hash>(v));
#endif

#if defined(LIEF_MACHO_SUPPORT)
  value = Hash::combine(value, Hash::hash<MachO::Hash>(v));
#endif

#if defined(LIEF_OAT_SUPPORT)
  value = Hash::combine(value, Hash::hash<OAT::Hash>(v));
#endif

#if defined(LIEF_ART_SUPPORT)
  value = Hash::combine(value, Hash::hash<ART::Hash>(v));
#endif

#if defined(LIEF_DEX_SUPPORT)
  value = Hash::combine(value, Hash::hash<DEX::Hash>(v));
#endif

#if defined(LIEF_VDEX_SUPPORT)
  value = Hash::combine(value, Hash::hash<VDEX::Hash>(v));
#endif

  return value;

}

size_t hash(const std::vector<uint8_t>& raw) {
  return Hash::hash(raw);
}

size_t hash(span<const uint8_t> raw) {
  return Hash::hash(raw);
}

Hash::~Hash() = default;

Hash::Hash() :
  value_{0}
{}

Hash::Hash(size_t init_value) :
  value_{init_value}
{}

Hash& Hash::process(const Object& obj) {
  Hash hasher;
  obj.accept(hasher);
  value_ = combine(value_, hasher.value());
  return *this;
}

Hash& Hash::process(size_t integer) {
  value_ = combine(value_, std::hash<size_t>{}(integer));
  return *this;
}

Hash& Hash::process(const std::string& str) {
  value_ = combine(value_, std::hash<std::string>{}(str));
  return *this;
}

Hash& Hash::process(const std::u16string& str) {
  value_ = combine(value_, std::hash<std::u16string>{}(str));
  return *this;
}

Hash& Hash::process(const std::vector<uint8_t>& raw) {
  value_ = combine(value_, Hash::hash(raw));
  return *this;
}

Hash& Hash::process(span<const uint8_t> raw) {
  value_ = combine(value_, Hash::hash(raw));
  return *this;
}

size_t Hash::value() const {
  return value_;
}

// Static methods
// ==============
size_t Hash::hash(const std::vector<uint8_t>& raw) {
  return hash(raw.data(), raw.size());
}

size_t Hash::hash(const void* raw, size_t size) {
  const auto* start = reinterpret_cast<const uint8_t*>(raw);

  std::vector<uint8_t> sha256(32, 0u);
  mbedtls_sha256(start, size, sha256.data(), 0);

  return std::accumulate(std::begin(sha256), std::end(sha256), 0llu,
     [] (size_t v, uint8_t n) {
        return (v << sizeof(uint8_t) * 8u) | n;
     });
}

size_t Hash::hash(span<const uint8_t> raw) {
  return hash(raw.data(), raw.size());
}

}
<|endoftext|>