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

#include "chrome/test/webdriver/webdriver_key_converter.h"

#include "base/utf_string_conversions.h"
#include "chrome/common/automation_constants.h"

namespace {

// TODO(kkania): Use this in KeyMap.
// Ordered list of all the key codes corresponding to special WebDriver keys.
// These WebDriver keys are defined in the Unicode Private Use Area.
// http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/value
const ui::KeyboardCode kSpecialWebDriverKeys[] = {
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_HELP,
    ui::VKEY_BACK,
    ui::VKEY_TAB,
    ui::VKEY_CLEAR,
    ui::VKEY_RETURN,
    ui::VKEY_RETURN,
    ui::VKEY_SHIFT,
    ui::VKEY_CONTROL,
    ui::VKEY_MENU,
    ui::VKEY_PAUSE,
    ui::VKEY_ESCAPE,
    ui::VKEY_SPACE,
    ui::VKEY_PRIOR,    // page up
    ui::VKEY_NEXT,     // page down
    ui::VKEY_END,
    ui::VKEY_HOME,
    ui::VKEY_LEFT,
    ui::VKEY_UP,
    ui::VKEY_RIGHT,
    ui::VKEY_DOWN,
    ui::VKEY_INSERT,
    ui::VKEY_DELETE,
    ui::VKEY_OEM_1,     // semicolon
    ui::VKEY_OEM_PLUS,  // equals
    ui::VKEY_NUMPAD0,
    ui::VKEY_NUMPAD1,
    ui::VKEY_NUMPAD2,
    ui::VKEY_NUMPAD3,
    ui::VKEY_NUMPAD4,
    ui::VKEY_NUMPAD5,
    ui::VKEY_NUMPAD6,
    ui::VKEY_NUMPAD7,
    ui::VKEY_NUMPAD8,
    ui::VKEY_NUMPAD9,
    ui::VKEY_MULTIPLY,
    ui::VKEY_ADD,
    ui::VKEY_OEM_COMMA,
    ui::VKEY_SUBTRACT,
    ui::VKEY_DECIMAL,
    ui::VKEY_DIVIDE,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_F1,
    ui::VKEY_F2,
    ui::VKEY_F3,
    ui::VKEY_F4,
    ui::VKEY_F5,
    ui::VKEY_F6,
    ui::VKEY_F7,
    ui::VKEY_F8,
    ui::VKEY_F9,
    ui::VKEY_F10,
    ui::VKEY_F11,
    ui::VKEY_F12};

const char16 kWebDriverNullKey = 0xE000U;
const char16 kWebDriverShiftKey = 0xE008U;
const char16 kWebDriverControlKey = 0xE009U;
const char16 kWebDriverAltKey = 0xE00AU;
const char16 kWebDriverCommandKey = 0xE03DU;

// Returns whether the given key is a WebDriver key modifier.
bool IsModifierKey(char16 key) {
  switch (key) {
    case kWebDriverShiftKey:
    case kWebDriverControlKey:
    case kWebDriverAltKey:
    case kWebDriverCommandKey:
      return true;
    default:
      return false;
  }
}

// Gets the key code associated with |key|, if it is a special WebDriver key.
// Returns whether |key| is a special WebDriver key. If true, |key_code| will
// be set.
bool KeyCodeFromSpecialWebDriverKey(char16 key, ui::KeyboardCode* key_code) {
  int index = static_cast<int>(key) - 0xE000U;
  bool is_special_key = index >= 0 &&
      index < static_cast<int>(arraysize(kSpecialWebDriverKeys));
  if (is_special_key)
    *key_code = kSpecialWebDriverKeys[index];
  return is_special_key;
}

// Converts a character to the key code and modifier set that would
// produce the character using the given keyboard layout.
bool ConvertCharToKeyCode(
    char16 key, ui::KeyboardCode* key_code, int *necessary_modifiers) {
#if defined(OS_WIN)
  short vkey_and_modifiers = ::VkKeyScanW(key);
  bool translated = vkey_and_modifiers != -1 &&
                    LOBYTE(vkey_and_modifiers) != -1 &&
                    HIBYTE(vkey_and_modifiers) != -1;
  if (translated) {
    *key_code = static_cast<ui::KeyboardCode>(LOBYTE(vkey_and_modifiers));
    *necessary_modifiers = HIBYTE(vkey_and_modifiers);
  }
  return translated;
#else
  // TODO(kkania): Implement.
  return false;
#endif
}

// Returns the character that would be produced from the given key code and
// modifier set, or "" if no character would be produced.
std::string ConvertKeyCodeToText(ui::KeyboardCode key_code, int modifiers) {
#if defined(OS_WIN)
  UINT scan_code = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
  BYTE keyboard_state[256];
  ::GetKeyboardState(keyboard_state);
  if (modifiers & automation::kShiftKeyMask)
    keyboard_state[VK_SHIFT] |= 0x80;
  wchar_t chars[5];
  int code = ::ToUnicode(key_code, scan_code, keyboard_state, chars, 4, 0);
  if (code <= 0) {
    return "";
  } else {
    std::string text;
    WideToUTF8(chars, code, &text);
    return text;
  }
#else
  // TODO(kkania): Implement
  return "";
#endif
}

}  // namespace

namespace webdriver {

WebKeyEvent CreateKeyDownEvent(ui::KeyboardCode key_code, int modifiers) {
  return WebKeyEvent(automation::kRawKeyDownType, key_code, "", "", modifiers);
}

WebKeyEvent CreateKeyUpEvent(ui::KeyboardCode key_code, int modifiers) {
  return WebKeyEvent(automation::kKeyUpType, key_code, "", "", modifiers);
}

WebKeyEvent CreateCharEvent(const std::string& unmodified_text,
                            const std::string& modified_text,
                            int modifiers) {
  return WebKeyEvent(automation::kCharType,
                     ui::VKEY_UNKNOWN,
                     unmodified_text,
                     modified_text,
                     modifiers);
}

void ConvertKeysToWebKeyEvents(const string16& client_keys,
                               std::vector<WebKeyEvent>* key_events) {
  // Add an implicit NULL character to the end of the input to depress all
  // modifiers.
  string16 keys = client_keys;
  keys.push_back(kWebDriverNullKey);

  int sticky_modifiers = 0;
  for (size_t i = 0; i < keys.size(); ++i) {
    char16 key = keys[i];

    if (key == kWebDriverNullKey) {
      // Release all modifier keys and clear |stick_modifiers|.
      if (sticky_modifiers & automation::kShiftKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_SHIFT, 0));
      if (sticky_modifiers & automation::kControlKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_CONTROL, 0));
      if (sticky_modifiers & automation::kAltKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_MENU, 0));
      if (sticky_modifiers & automation::kMetaKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_COMMAND, 0));
      sticky_modifiers = 0;
      continue;
    }
    if (IsModifierKey(key)) {
      // Press or release the modifier, and adjust |sticky_modifiers|.
      bool modifier_down = false;
      ui::KeyboardCode key_code;
      if (key == kWebDriverShiftKey) {
        sticky_modifiers ^= automation::kShiftKeyMask;
        modifier_down = sticky_modifiers & automation::kShiftKeyMask;
        key_code = ui::VKEY_SHIFT;
      } else if (key == kWebDriverControlKey) {
        sticky_modifiers ^= automation::kControlKeyMask;
        modifier_down = sticky_modifiers & automation::kControlKeyMask;
        key_code = ui::VKEY_CONTROL;
      } else if (key == kWebDriverAltKey) {
        sticky_modifiers ^= automation::kAltKeyMask;
        modifier_down = sticky_modifiers & automation::kAltKeyMask;
        key_code = ui::VKEY_MENU;
      } else if (key == kWebDriverCommandKey) {
        sticky_modifiers ^= automation::kMetaKeyMask;
        modifier_down = sticky_modifiers & automation::kMetaKeyMask;
        key_code = ui::VKEY_COMMAND;
      }
      if (modifier_down)
        key_events->push_back(CreateKeyDownEvent(key_code, sticky_modifiers));
      else
        key_events->push_back(CreateKeyUpEvent(key_code, sticky_modifiers));
      continue;
    }

    ui::KeyboardCode key_code = ui::VKEY_UNKNOWN;
    std::string unmodified_text, modified_text;
    int all_modifiers = sticky_modifiers;

    bool is_special_key = KeyCodeFromSpecialWebDriverKey(key, &key_code);
    if (is_special_key && key_code == ui::VKEY_UNKNOWN) {
      LOG(ERROR) << "Unknown WebDriver key: " << static_cast<int>(key);
      continue;
    }
    if (!is_special_key) {
      int necessary_modifiers = 0;
      ConvertCharToKeyCode(key, &key_code, &necessary_modifiers);
      all_modifiers |= necessary_modifiers;
    }
    if (key_code != ui::VKEY_UNKNOWN) {
      unmodified_text = ConvertKeyCodeToText(key_code, 0);
      modified_text = ConvertKeyCodeToText(key_code, all_modifiers);
    }
    if (!is_special_key && (unmodified_text.empty() || modified_text.empty())) {
      // Do a best effort and use the raw key we were given.
      LOG(WARNING) << "No translation for key code. Code point: "
                   << static_cast<int>(key);
      if (unmodified_text.empty())
        unmodified_text = UTF16ToUTF8(keys.substr(i, 1));
      if (modified_text.empty())
        modified_text = UTF16ToUTF8(keys.substr(i, 1));
    }

    // Create the key events.
    bool need_shift_key =
        all_modifiers & automation::kShiftKeyMask &&
        !(sticky_modifiers & automation::kShiftKeyMask);
    if (need_shift_key) {
      key_events->push_back(
          CreateKeyDownEvent(ui::VKEY_SHIFT, sticky_modifiers));
    }

    key_events->push_back(CreateKeyDownEvent(key_code, all_modifiers));
    if (unmodified_text.length() || modified_text.length()) {
      key_events->push_back(
          CreateCharEvent(unmodified_text, modified_text, all_modifiers));
    }
    key_events->push_back(CreateKeyUpEvent(key_code, all_modifiers));

    if (need_shift_key) {
      key_events->push_back(
          CreateKeyUpEvent(ui::VKEY_SHIFT, sticky_modifiers));
    }
  }
}

}  // namespace webdriver
<commit_msg>Fix build warning from uninitialized variable. BUG=none TEST=none TBR=jleyba Review URL: http://codereview.chromium.org/6473019<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/webdriver/webdriver_key_converter.h"

#include "base/utf_string_conversions.h"
#include "chrome/common/automation_constants.h"

namespace {

// TODO(kkania): Use this in KeyMap.
// Ordered list of all the key codes corresponding to special WebDriver keys.
// These WebDriver keys are defined in the Unicode Private Use Area.
// http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/value
const ui::KeyboardCode kSpecialWebDriverKeys[] = {
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_HELP,
    ui::VKEY_BACK,
    ui::VKEY_TAB,
    ui::VKEY_CLEAR,
    ui::VKEY_RETURN,
    ui::VKEY_RETURN,
    ui::VKEY_SHIFT,
    ui::VKEY_CONTROL,
    ui::VKEY_MENU,
    ui::VKEY_PAUSE,
    ui::VKEY_ESCAPE,
    ui::VKEY_SPACE,
    ui::VKEY_PRIOR,    // page up
    ui::VKEY_NEXT,     // page down
    ui::VKEY_END,
    ui::VKEY_HOME,
    ui::VKEY_LEFT,
    ui::VKEY_UP,
    ui::VKEY_RIGHT,
    ui::VKEY_DOWN,
    ui::VKEY_INSERT,
    ui::VKEY_DELETE,
    ui::VKEY_OEM_1,     // semicolon
    ui::VKEY_OEM_PLUS,  // equals
    ui::VKEY_NUMPAD0,
    ui::VKEY_NUMPAD1,
    ui::VKEY_NUMPAD2,
    ui::VKEY_NUMPAD3,
    ui::VKEY_NUMPAD4,
    ui::VKEY_NUMPAD5,
    ui::VKEY_NUMPAD6,
    ui::VKEY_NUMPAD7,
    ui::VKEY_NUMPAD8,
    ui::VKEY_NUMPAD9,
    ui::VKEY_MULTIPLY,
    ui::VKEY_ADD,
    ui::VKEY_OEM_COMMA,
    ui::VKEY_SUBTRACT,
    ui::VKEY_DECIMAL,
    ui::VKEY_DIVIDE,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_UNKNOWN,
    ui::VKEY_F1,
    ui::VKEY_F2,
    ui::VKEY_F3,
    ui::VKEY_F4,
    ui::VKEY_F5,
    ui::VKEY_F6,
    ui::VKEY_F7,
    ui::VKEY_F8,
    ui::VKEY_F9,
    ui::VKEY_F10,
    ui::VKEY_F11,
    ui::VKEY_F12};

const char16 kWebDriverNullKey = 0xE000U;
const char16 kWebDriverShiftKey = 0xE008U;
const char16 kWebDriverControlKey = 0xE009U;
const char16 kWebDriverAltKey = 0xE00AU;
const char16 kWebDriverCommandKey = 0xE03DU;

// Returns whether the given key is a WebDriver key modifier.
bool IsModifierKey(char16 key) {
  switch (key) {
    case kWebDriverShiftKey:
    case kWebDriverControlKey:
    case kWebDriverAltKey:
    case kWebDriverCommandKey:
      return true;
    default:
      return false;
  }
}

// Gets the key code associated with |key|, if it is a special WebDriver key.
// Returns whether |key| is a special WebDriver key. If true, |key_code| will
// be set.
bool KeyCodeFromSpecialWebDriverKey(char16 key, ui::KeyboardCode* key_code) {
  int index = static_cast<int>(key) - 0xE000U;
  bool is_special_key = index >= 0 &&
      index < static_cast<int>(arraysize(kSpecialWebDriverKeys));
  if (is_special_key)
    *key_code = kSpecialWebDriverKeys[index];
  return is_special_key;
}

// Converts a character to the key code and modifier set that would
// produce the character using the given keyboard layout.
bool ConvertCharToKeyCode(
    char16 key, ui::KeyboardCode* key_code, int *necessary_modifiers) {
#if defined(OS_WIN)
  short vkey_and_modifiers = ::VkKeyScanW(key);
  bool translated = vkey_and_modifiers != -1 &&
                    LOBYTE(vkey_and_modifiers) != -1 &&
                    HIBYTE(vkey_and_modifiers) != -1;
  if (translated) {
    *key_code = static_cast<ui::KeyboardCode>(LOBYTE(vkey_and_modifiers));
    *necessary_modifiers = HIBYTE(vkey_and_modifiers);
  }
  return translated;
#else
  // TODO(kkania): Implement.
  return false;
#endif
}

// Returns the character that would be produced from the given key code and
// modifier set, or "" if no character would be produced.
std::string ConvertKeyCodeToText(ui::KeyboardCode key_code, int modifiers) {
#if defined(OS_WIN)
  UINT scan_code = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
  BYTE keyboard_state[256];
  ::GetKeyboardState(keyboard_state);
  if (modifiers & automation::kShiftKeyMask)
    keyboard_state[VK_SHIFT] |= 0x80;
  wchar_t chars[5];
  int code = ::ToUnicode(key_code, scan_code, keyboard_state, chars, 4, 0);
  if (code <= 0) {
    return "";
  } else {
    std::string text;
    WideToUTF8(chars, code, &text);
    return text;
  }
#else
  // TODO(kkania): Implement
  return "";
#endif
}

}  // namespace

namespace webdriver {

WebKeyEvent CreateKeyDownEvent(ui::KeyboardCode key_code, int modifiers) {
  return WebKeyEvent(automation::kRawKeyDownType, key_code, "", "", modifiers);
}

WebKeyEvent CreateKeyUpEvent(ui::KeyboardCode key_code, int modifiers) {
  return WebKeyEvent(automation::kKeyUpType, key_code, "", "", modifiers);
}

WebKeyEvent CreateCharEvent(const std::string& unmodified_text,
                            const std::string& modified_text,
                            int modifiers) {
  return WebKeyEvent(automation::kCharType,
                     ui::VKEY_UNKNOWN,
                     unmodified_text,
                     modified_text,
                     modifiers);
}

void ConvertKeysToWebKeyEvents(const string16& client_keys,
                               std::vector<WebKeyEvent>* key_events) {
  // Add an implicit NULL character to the end of the input to depress all
  // modifiers.
  string16 keys = client_keys;
  keys.push_back(kWebDriverNullKey);

  int sticky_modifiers = 0;
  for (size_t i = 0; i < keys.size(); ++i) {
    char16 key = keys[i];

    if (key == kWebDriverNullKey) {
      // Release all modifier keys and clear |stick_modifiers|.
      if (sticky_modifiers & automation::kShiftKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_SHIFT, 0));
      if (sticky_modifiers & automation::kControlKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_CONTROL, 0));
      if (sticky_modifiers & automation::kAltKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_MENU, 0));
      if (sticky_modifiers & automation::kMetaKeyMask)
        key_events->push_back(CreateKeyUpEvent(ui::VKEY_COMMAND, 0));
      sticky_modifiers = 0;
      continue;
    }
    if (IsModifierKey(key)) {
      // Press or release the modifier, and adjust |sticky_modifiers|.
      bool modifier_down = false;
      ui::KeyboardCode key_code = ui::VKEY_UNKNOWN;
      if (key == kWebDriverShiftKey) {
        sticky_modifiers ^= automation::kShiftKeyMask;
        modifier_down = sticky_modifiers & automation::kShiftKeyMask;
        key_code = ui::VKEY_SHIFT;
      } else if (key == kWebDriverControlKey) {
        sticky_modifiers ^= automation::kControlKeyMask;
        modifier_down = sticky_modifiers & automation::kControlKeyMask;
        key_code = ui::VKEY_CONTROL;
      } else if (key == kWebDriverAltKey) {
        sticky_modifiers ^= automation::kAltKeyMask;
        modifier_down = sticky_modifiers & automation::kAltKeyMask;
        key_code = ui::VKEY_MENU;
      } else if (key == kWebDriverCommandKey) {
        sticky_modifiers ^= automation::kMetaKeyMask;
        modifier_down = sticky_modifiers & automation::kMetaKeyMask;
        key_code = ui::VKEY_COMMAND;
      } else {
        NOTREACHED();
      }
      if (modifier_down)
        key_events->push_back(CreateKeyDownEvent(key_code, sticky_modifiers));
      else
        key_events->push_back(CreateKeyUpEvent(key_code, sticky_modifiers));
      continue;
    }

    ui::KeyboardCode key_code = ui::VKEY_UNKNOWN;
    std::string unmodified_text, modified_text;
    int all_modifiers = sticky_modifiers;

    bool is_special_key = KeyCodeFromSpecialWebDriverKey(key, &key_code);
    if (is_special_key && key_code == ui::VKEY_UNKNOWN) {
      LOG(ERROR) << "Unknown WebDriver key: " << static_cast<int>(key);
      continue;
    }
    if (!is_special_key) {
      int necessary_modifiers = 0;
      ConvertCharToKeyCode(key, &key_code, &necessary_modifiers);
      all_modifiers |= necessary_modifiers;
    }
    if (key_code != ui::VKEY_UNKNOWN) {
      unmodified_text = ConvertKeyCodeToText(key_code, 0);
      modified_text = ConvertKeyCodeToText(key_code, all_modifiers);
    }
    if (!is_special_key && (unmodified_text.empty() || modified_text.empty())) {
      // Do a best effort and use the raw key we were given.
      LOG(WARNING) << "No translation for key code. Code point: "
                   << static_cast<int>(key);
      if (unmodified_text.empty())
        unmodified_text = UTF16ToUTF8(keys.substr(i, 1));
      if (modified_text.empty())
        modified_text = UTF16ToUTF8(keys.substr(i, 1));
    }

    // Create the key events.
    bool need_shift_key =
        all_modifiers & automation::kShiftKeyMask &&
        !(sticky_modifiers & automation::kShiftKeyMask);
    if (need_shift_key) {
      key_events->push_back(
          CreateKeyDownEvent(ui::VKEY_SHIFT, sticky_modifiers));
    }

    key_events->push_back(CreateKeyDownEvent(key_code, all_modifiers));
    if (unmodified_text.length() || modified_text.length()) {
      key_events->push_back(
          CreateCharEvent(unmodified_text, modified_text, all_modifiers));
    }
    key_events->push_back(CreateKeyUpEvent(key_code, all_modifiers));

    if (need_shift_key) {
      key_events->push_back(
          CreateKeyUpEvent(ui::VKEY_SHIFT, sticky_modifiers));
    }
  }
}

}  // namespace webdriver
<|endoftext|>


<commit_before>#ifndef FILE_PARALLELTOP
#define FILE_PARALLELTOP

#include <meshing.hpp>

extern int ntasks;

class ParallelMeshTopology
{
  const Mesh & mesh;

  // number of local elements, vertices, points (?), edges, faces
  int ne, nv, np, ned, nfa;

  // number of local segments and surface elements
  int nseg, nsurfel;

  // number of global elements, vertices, ???,  faces
  int neglob, nvglob;
  int nparel;
  int nfaglob;

  /**
     mapping from local to distant vertex number
     each row of the table corresponds to one vertex
     each row contains a list of pairs (procnr, dist_vnum)
   */
  TABLE<int,PointIndex::BASE> loc2distvert;
  TABLE<int,0> loc2distedge, loc2distface, loc2distel;
  TABLE<int,0> loc2distsegm, loc2distsurfel;

  BitArray * isexchangeface, * isexchangevert, * isexchangeedge, * isexchangeel;

  BitArray isghostedge, isghostface;

  bool coarseupdate;
  int overlap;

public:

  ParallelMeshTopology (const Mesh & amesh);
  ~ParallelMeshTopology ();

  /// set number of local vertices, reset sizes of loc2dist_vert, isexchangevert...
  void SetNV ( int anv );
  void SetNE ( int ane );
  void SetNSE ( int anse );
  void SetNSegm ( int anseg );

  void Reset ();

  void SetLoc2Glob_Vert   ( int locnum, int globnum ) { loc2distvert[locnum][0] = globnum; }
  void SetLoc2Glob_VolEl  ( int locnum, int globnum ) { loc2distel[locnum-1][0] = globnum; }
  void SetLoc2Glob_SurfEl ( int locnum, int globnum ) { loc2distsurfel[locnum-1][0] = globnum; }
  void SetLoc2Glob_Segm   ( int locnum, int globnum ) { loc2distsegm[locnum-1][0] = globnum; }

  int GetLoc2Glob_Vert  ( int locnum ) const { return loc2distvert[locnum][0]; }
  int GetLoc2Glob_VolEl ( int locnum ) const { return loc2distel[locnum-1][0]; }

  void GetVertNeighbours ( int vnum, Array<int> & dests ) const;

  int Glob2Loc_SurfEl ( int globnum );
  int Glob2Loc_VolEl ( int globnum );
  int Glob2Loc_Segm ( int globnum );
  int Glob2Loc_Vert ( int globnum );

  int GetNDistantPNums ( int locpnum ) const        { return loc2distvert[locpnum].Size() / 2 + 1; }
  int GetNDistantFaceNums ( int locfacenum ) const  { return loc2distface[locfacenum-1].Size() / 2 + 1; }
  int GetNDistantEdgeNums ( int locedgenum ) const  { return loc2distedge[locedgenum-1].Size() / 2 + 1; }
  int GetNDistantElNums ( int locelnum ) const      { return loc2distel[locelnum-1].Size() / 2 + 1; }

  int GetDistantPNum ( int proc, int locpnum ) const;
  int GetDistantEdgeNum ( int proc, int locedgenum ) const;
  int GetDistantFaceNum ( int proc, int locedgenum ) const;
  int GetDistantElNum ( int proc, int locelnum ) const;

  int GetDistantPNums ( int locpnum, int * distpnums ) const;
  int GetDistantEdgeNums ( int locedgenum, int * distedgenums ) const;
  int GetDistantFaceNums ( int locedgenum, int * distfacenums ) const;
  int GetDistantElNums ( int locelnum, int * distfacenums ) const;

  void Print() const;

  void SetExchangeFace ( int fnr )      { isexchangeface->Set( (fnr-1)*(ntasks+1) ); }
  void SetExchangeVert ( int vnum )     { isexchangevert->Set( (vnum-1)*(ntasks+1) ); }
  void SetExchangeElement ( int elnum ) { isexchangeel->Set((elnum-1)*(ntasks+1) ); }
  void SetExchangeEdge ( int ednum )    { isexchangeedge->Set ((ednum-1)*(ntasks+1)); }

  // fuer diese Fkts  kann man ja O(N) - bitarrays lassen
  bool IsExchangeVert ( PointIndex vnum ) const
  {
    return loc2distvert[vnum].Size() > 1;
    // return isexchangevert->Test((vnum-1)*(ntasks+1));
  }

  bool IsExchangeEdge ( int ednum ) const
  {
    /*
    if ( isexchangeedge->Test( (ednum-1)*(ntasks+1) )  !=
	 ( loc2distedge[ednum-1].Size() > 1)  )
      {
	cerr << "isexedge differs, id = " << id << ", ednum = " << ednum << endl;
      }
    */
    // return loc2distedge[ednum-1].Size() > 1;
    int i = (ednum-1)*(ntasks+1);
    return isexchangeedge->Test(i);
  }

  bool IsExchangeFace ( int fnum ) const
  {
    /*
    if ( isexchangeface->Test( (fnum-1)*(ntasks+1) )  !=
	 ( loc2distface[fnum-1].Size() > 1)  )
      {
	cerr << "it differs, id = " << id << ", fnum = " << fnum << endl;
      }
    */
    // nur hier funktioniert's so nicht ???? (JS)
    // return loc2distface[fnum-1].Size() > 1;
    return isexchangeface->Test( (fnum-1)*(ntasks+1) );
  }

  bool IsExchangeElement ( int elnum ) const
  {
    // return loc2distel[elnum-1].Size() > 1;
    return isexchangeel->Test((elnum-1)*(ntasks+1));
  }

  bool IsExchangeSEl ( int selnum ) const
  {
    return loc2distsurfel[selnum-1].Size() > 1;
  }

  void  SetExchangeFace (int dest, int fnr )
  {
    // isexchangeface->Set((fnr-1)*(ntasks+1) + (dest+1));
  }

  void  SetExchangeVert (int dest, int vnum )
  {
    // isexchangevert->Set((vnum-1)*(ntasks+1) + (dest+1) );
  }

  void  SetExchangeElement (int dest, int vnum )
  {
    isexchangeel->Set( (vnum-1)*(ntasks+1) + (dest+1) );
  }

  void  SetExchangeEdge (int dest, int ednum )
  {
    // isexchangeedge->Set ( (ednum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeVert (int dest, int vnum ) const
  {
    FlatArray<int> exchange = loc2distvert[vnum];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;
    // return isexchangevert->Test((vnum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeEdge (int dest, int ednum ) const
  {
    FlatArray<int> exchange = loc2distedge[ednum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;

    // return isexchangeedge->Test((ednum-1)*(ntasks+1) + (dest+1));
  }

  bool IsExchangeFace (int dest, int fnum ) const
  {
    FlatArray<int> exchange = loc2distface[fnum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;

    // return isexchangeface->Test((fnum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeElement (int dest, int elnum ) const
  {
    // das geht auch nicht
    /*
    FlatArray<int> exchange = loc2distel[elnum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;
    */
    return isexchangeel->Test((elnum-1)*(ntasks+1) + (dest+1));
  }

  int Overlap() const
  { return overlap; }

  int IncreaseOverlap ()
  { overlap++; return overlap; }

  void Update();

  void UpdateCoarseGrid();
  void UpdateCoarseGridOverlap();
  void UpdateRefinement ();
  void UpdateTopology ();
  void UpdateExchangeElements();

  void UpdateCoarseGridGlobal();

  const bool DoCoarseUpdate() const
  { return !coarseupdate; }

  void SetDistantFaceNum ( int dest, int locnum, int distnum );
  void SetDistantPNum ( int dest, int locnum, int distnum );
  void SetDistantEdgeNum ( int dest, int locnum, int distnum );
  void SetDistantEl ( int dest, int locnum, int distnum );
  void SetDistantSurfEl ( int dest, int locnum, int distnum );
  void SetDistantSegm ( int dest, int locnum, int distnum );

  bool IsGhostEl ( int elnum ) const   { return mesh.VolumeElement(elnum).IsGhost(); }
  bool IsGhostFace ( int fanum ) const { return isghostface.Test(fanum-1); }
  bool IsGhostEdge ( int ednum ) const { return isghostedge.Test(ednum-1); }
  bool IsGhostVert ( int pnum ) const  { return mesh.Point(pnum).IsGhost(); }

//    inline void SetGhostVert ( const int pnum )
//    { isghostvert.Set(pnum-1); }

  void SetGhostEdge ( int ednum )
  { isghostedge.Set(ednum-1); }

  void ClearGhostEdge ( int ednum )
  { isghostedge.Clear(ednum-1); }

  void SetGhostFace ( int fanum )
  { isghostface.Set(fanum-1); }

  void ClearGhostFace ( int fanum )
  { isghostface.Clear(fanum-1); }

  bool IsElementInPartition ( int elnum, int dest ) const
  {
    return IsExchangeElement ( dest, elnum);
  }

  void SetElementInPartition ( int elnum, int dest )
  {
    SetExchangeElement ( dest, elnum );
  }

  void SetNVGlob ( int anvglob )   { nvglob = anvglob; }
  void SetNEGlob ( int aneglob )   { neglob = aneglob; }

  int GetNVGlob ()  { return nvglob; }
  int GetNEGlob ()  { return neglob; }
};

#endif
<commit_msg>paralleparallell<commit_after>#ifndef FILE_PARALLELTOP
#define FILE_PARALLELTOP

#include <meshing.hpp>

extern int ntasks;

class ParallelMeshTopology
{
  const Mesh & mesh;

  // number of local elements, vertices, points (?), edges, faces
  int ne, nv, np, ned, nfa;

  // number of local segments and surface elements
  int nseg, nsurfel;

  // number of global elements, vertices, ???,  faces
  int neglob, nvglob;
  int nparel;
  int nfaglob;

  /**
     mapping from local to distant vertex number
     each row of the table corresponds to one vertex
     each row contains a list of pairs (procnr, dist_vnum)
   */
  TABLE<int,PointIndex::BASE> loc2distvert;
  TABLE<int,0> loc2distedge, loc2distface, loc2distel;
  TABLE<int,0> loc2distsegm, loc2distsurfel;

  BitArray * isexchangeface, * isexchangevert, * isexchangeedge, * isexchangeel;

  BitArray isghostedge, isghostface;

  bool coarseupdate;
  int overlap;

public:

  ParallelMeshTopology (const Mesh & amesh);
  ~ParallelMeshTopology ();

  /// set number of local vertices, reset sizes of loc2dist_vert, isexchangevert...
  void SetNV ( int anv );
  void SetNE ( int ane );
  void SetNSE ( int anse );
  void SetNSegm ( int anseg );

  void Reset ();

  void SetLoc2Glob_Vert   ( int locnum, int globnum ) { loc2distvert[locnum][0] = globnum; }
  void SetLoc2Glob_VolEl  ( int locnum, int globnum ) { loc2distel[locnum-1][0] = globnum; }
  void SetLoc2Glob_SurfEl ( int locnum, int globnum ) { loc2distsurfel[locnum-1][0] = globnum; }
  void SetLoc2Glob_Segm   ( int locnum, int globnum ) { loc2distsegm[locnum-1][0] = globnum; }

  int GetLoc2Glob_Vert  ( int locnum ) const { return loc2distvert[locnum][0]; }
  int GetLoc2Glob_VolEl ( int locnum ) const { return loc2distel[locnum-1][0]; }

  void GetVertNeighbours ( int vnum, Array<int> & dests ) const;

  int Glob2Loc_SurfEl ( int globnum );
  int Glob2Loc_VolEl ( int globnum );
  int Glob2Loc_Segm ( int globnum );
  int Glob2Loc_Vert ( int globnum );

  int GetNDistantPNums ( int locpnum ) const        { return loc2distvert[locpnum].Size() / 2 + 1; }
  int GetNDistantFaceNums ( int locfacenum ) const  { return loc2distface[locfacenum-1].Size() / 2 + 1; }
  int GetNDistantEdgeNums ( int locedgenum ) const  { return loc2distedge[locedgenum-1].Size() / 2 + 1; }
  int GetNDistantElNums ( int locelnum ) const      { return loc2distel[locelnum-1].Size() / 2 + 1; }

  int GetDistantPNum ( int proc, int locpnum ) const;
  int GetDistantEdgeNum ( int proc, int locedgenum ) const;
  int GetDistantFaceNum ( int proc, int locedgenum ) const;
  int GetDistantElNum ( int proc, int locelnum ) const;

  int GetDistantPNums ( int locpnum, int * distpnums ) const;
  int GetDistantEdgeNums ( int locedgenum, int * distedgenums ) const;
  int GetDistantFaceNums ( int locedgenum, int * distfacenums ) const;
  int GetDistantElNums ( int locelnum, int * distfacenums ) const;

  void Print() const;

  void SetExchangeFace ( int fnr )      { isexchangeface->Set( (fnr-1)*(ntasks+1) ); }
  void SetExchangeVert ( int vnum )     { isexchangevert->Set( (vnum-1)*(ntasks+1) ); }
  void SetExchangeElement ( int elnum ) { isexchangeel->Set((elnum-1)*(ntasks+1) ); }
  void SetExchangeEdge ( int ednum )    { isexchangeedge->Set ((ednum-1)*(ntasks+1)); }

  // fuer diese Fkts  kann man ja O(N) - bitarrays lassen
  bool IsExchangeVert ( PointIndex vnum ) const
  {
    return loc2distvert[vnum].Size() > 1;
    // return isexchangevert->Test((vnum-1)*(ntasks+1));
  }

  bool IsExchangeEdge ( int ednum ) const
  {
    /*
    if ( isexchangeedge->Test( (ednum-1)*(ntasks+1) )  !=
	 ( loc2distedge[ednum-1].Size() > 1)  )
      {
	cerr << "isexedge differs, id = " << id << ", ednum = " << ednum << endl;
      }
    */
    // return loc2distedge[ednum-1].Size() > 1;
    int i = (ednum-1)*(ntasks+1);
    return isexchangeedge->Test(i);
  }

  bool IsExchangeFace ( int fnum ) const
  {
    /*
    if ( isexchangeface->Test( (fnum-1)*(ntasks+1) )  !=
	 ( loc2distface[fnum-1].Size() > 1)  )
      {
	cerr << "it differs, id = " << id << ", fnum = " << fnum << endl;
      }
    */
    // nur hier funktioniert's so nicht ???? (JS)
    // return loc2distface[fnum-1].Size() > 1;
    return isexchangeface->Test( (fnum-1)*(ntasks+1) );
  }

  bool IsExchangeElement ( int elnum ) const
  {
    // return loc2distel[elnum-1].Size() > 1;
    return isexchangeel->Test((elnum-1)*(ntasks+1));
  }

  bool IsExchangeSEl ( int selnum ) const
  {
    return loc2distsurfel[selnum-1].Size() > 1;
  }

  void  SetExchangeFace (int dest, int fnr )
  {
    // isexchangeface->Set((fnr-1)*(ntasks+1) + (dest+1));
  }

  void  SetExchangeVert (int dest, int vnum )
  {
    // isexchangevert->Set((vnum-1)*(ntasks+1) + (dest+1) );
  }

  void  SetExchangeElement (int dest, int vnum )
  {
    isexchangeel->Set( (vnum-1)*(ntasks+1) + (dest+1) );
  }

  void  SetExchangeEdge (int dest, int ednum )
  {
    // isexchangeedge->Set ( (ednum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeVert (int dest, int vnum ) const
  {
    FlatArray<int> exchange = loc2distvert[vnum];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;
    // return isexchangevert->Test((vnum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeEdge (int dest, int ednum ) const
  {
    FlatArray<int> exchange = loc2distedge[ednum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;

    // return isexchangeedge->Test((ednum-1)*(ntasks+1) + (dest+1));
  }

  bool IsExchangeFace (int dest, int fnum ) const
  {
    FlatArray<int> exchange = loc2distface[fnum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;

    // return isexchangeface->Test((fnum-1)*(ntasks+1) + (dest+1) );
  }

  bool IsExchangeElement (int dest, int elnum ) const
  {
    // das geht auch nicht
    /*
    FlatArray<int> exchange = loc2distel[elnum-1];
    for (int i = 1; i < exchange.Size(); i += 2)
      if (exchange[i] == dest) return true;
    return false;
    */
    return isexchangeel->Test((elnum-1)*(ntasks+1) + (dest+1));
  }

  int Overlap() const
  { return overlap; }

  int IncreaseOverlap ()
  { overlap++; return overlap; }

  void Update();

  void UpdateCoarseGrid();
  void UpdateCoarseGridOverlap();
  void UpdateRefinement ();
  void UpdateTopology ();
  void UpdateExchangeElements();

  void UpdateCoarseGridGlobal();

  bool DoCoarseUpdate() const
  { return !coarseupdate; }

  void SetDistantFaceNum ( int dest, int locnum, int distnum );
  void SetDistantPNum ( int dest, int locnum, int distnum );
  void SetDistantEdgeNum ( int dest, int locnum, int distnum );
  void SetDistantEl ( int dest, int locnum, int distnum );
  void SetDistantSurfEl ( int dest, int locnum, int distnum );
  void SetDistantSegm ( int dest, int locnum, int distnum );

  bool IsGhostEl ( int elnum ) const   { return mesh.VolumeElement(elnum).IsGhost(); }
  bool IsGhostFace ( int fanum ) const { return isghostface.Test(fanum-1); }
  bool IsGhostEdge ( int ednum ) const { return isghostedge.Test(ednum-1); }
  bool IsGhostVert ( int pnum ) const  { return mesh.Point(pnum).IsGhost(); }

//    inline void SetGhostVert ( const int pnum )
//    { isghostvert.Set(pnum-1); }

  void SetGhostEdge ( int ednum )
  { isghostedge.Set(ednum-1); }

  void ClearGhostEdge ( int ednum )
  { isghostedge.Clear(ednum-1); }

  void SetGhostFace ( int fanum )
  { isghostface.Set(fanum-1); }

  void ClearGhostFace ( int fanum )
  { isghostface.Clear(fanum-1); }

  bool IsElementInPartition ( int elnum, int dest ) const
  {
    return IsExchangeElement ( dest, elnum);
  }

  void SetElementInPartition ( int elnum, int dest )
  {
    SetExchangeElement ( dest, elnum );
  }

  void SetNVGlob ( int anvglob )   { nvglob = anvglob; }
  void SetNEGlob ( int aneglob )   { neglob = aneglob; }

  int GetNVGlob ()  { return nvglob; }
  int GetNEGlob ()  { return neglob; }
};

#endif
<|endoftext|>


<commit_before>#include "bytecode.hpp"
#include "value.hpp"

#include <cstddef>
#include <cstdint>
#include <cstring>

using namespace slakken;
using namespace slakken::bytecode;

std::size_t const_pool::root_count() const {
  return size();
}

value const* const_pool::root_at(std::size_t index) const {
  return operator[](index);
}

decode_eof_error::decode_eof_error()
  : decode_error("unexpected eof") {
}

decode_const_type_error::decode_const_type_error()
  : decode_error("invalid constant type") {
}

decode_const_range_error::decode_const_range_error()
  : decode_error("constant index out of range") {
}

decode_opcode_error::decode_opcode_error()
  : decode_error("invalid opcode") {
}

namespace {
  template<typename T>
  T decode(char const*& begin, char const* end) {
    if (sizeof(T) > static_cast<std::size_t>(end - begin)) {
      throw decode_eof_error();
    }
    T result;
    std::memcpy(&result, begin, sizeof(T));
    begin += sizeof(T);
    return result;
  }

  void decode_array_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    auto length = decode<std::uint32_t>(begin, end);
    std::vector<value const*> elements;
    for (decltype(length) i = 0; i < length; ++i) {
      auto element_index = decode<std::uint32_t>(begin, end);
      if (element_index >= consts.size()) {
        throw decode_const_range_error();
      }
      elements.push_back(consts[element_index]);
    }
    consts.push_back(&alloc.alloc_array(elements.data(), elements.size()));
  }

  void decode_atom_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    auto length = decode<std::uint32_t>(begin, end);
    if (length > end - begin) {
      throw decode_eof_error();
    }
    consts.push_back(&alloc.alloc_atom(begin, length));
    begin += length;
  }

  void decode_float_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    static_assert(sizeof(double) == 8, "sizeof(double) must be 8");
    auto value = decode<double>(begin, end);
    consts.push_back(&alloc.alloc_float(value));
  }
}

void slakken::bytecode::decode_const_pool(const_pool& consts, alloc& alloc, char const* binary, std::size_t binary_size) {
  for (auto begin = binary, end = binary + binary_size; begin != end;) {
    switch (*begin++) {
    case 0x00:
      decode_array_constant(consts, alloc, begin, end);
      break;
    case 0x01:
      decode_atom_constant(consts, alloc, begin, end);
      break;
    case 0x02:
      decode_float_constant(consts, alloc, begin, end);
      break;
    default:
      throw decode_const_type_error();
    }
  }
}

std::vector<instruction> slakken::bytecode::decode_instructions(function_map const& functions, const_pool const& consts, char const* binary, std::size_t binary_size) {
  std::vector<instruction> insts;
  for (auto begin = binary, end = binary + binary_size; begin != end;) {
#include "../build/decode.inc"
    throw decode_opcode_error();
  }
  return insts;
}
<commit_msg>Use std::generate instead of for loop when parsing array constants<commit_after>#include "bytecode.hpp"
#include "value.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <vector>

using namespace slakken;
using namespace slakken::bytecode;

std::size_t const_pool::root_count() const {
  return size();
}

value const* const_pool::root_at(std::size_t index) const {
  return operator[](index);
}

decode_eof_error::decode_eof_error()
  : decode_error("unexpected eof") {
}

decode_const_type_error::decode_const_type_error()
  : decode_error("invalid constant type") {
}

decode_const_range_error::decode_const_range_error()
  : decode_error("constant index out of range") {
}

decode_opcode_error::decode_opcode_error()
  : decode_error("invalid opcode") {
}

namespace {
  template<typename T>
  T decode(char const*& begin, char const* end) {
    if (sizeof(T) > static_cast<std::size_t>(end - begin)) {
      throw decode_eof_error();
    }
    T result;
    std::memcpy(&result, begin, sizeof(T));
    begin += sizeof(T);
    return result;
  }

  void decode_array_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    auto length = decode<std::uint32_t>(begin, end);
    std::vector<value const*> elements(length);
    std::generate(elements.begin(), elements.end(), [&] {
      auto element_index = decode<std::uint32_t>(begin, end);
      if (element_index >= consts.size()) {
        throw decode_const_range_error();
      }
      return consts[element_index];
    });
    consts.push_back(&alloc.alloc_array(elements.data(), elements.size()));
  }

  void decode_atom_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    auto length = decode<std::uint32_t>(begin, end);
    if (length > end - begin) {
      throw decode_eof_error();
    }
    consts.push_back(&alloc.alloc_atom(begin, length));
    begin += length;
  }

  void decode_float_constant(const_pool& consts, alloc& alloc, char const*& begin, char const* end) {
    static_assert(sizeof(double) == 8, "sizeof(double) must be 8");
    auto value = decode<double>(begin, end);
    consts.push_back(&alloc.alloc_float(value));
  }
}

void slakken::bytecode::decode_const_pool(const_pool& consts, alloc& alloc, char const* binary, std::size_t binary_size) {
  for (auto begin = binary, end = binary + binary_size; begin != end;) {
    switch (*begin++) {
    case 0x00:
      decode_array_constant(consts, alloc, begin, end);
      break;
    case 0x01:
      decode_atom_constant(consts, alloc, begin, end);
      break;
    case 0x02:
      decode_float_constant(consts, alloc, begin, end);
      break;
    default:
      throw decode_const_type_error();
    }
  }
}

std::vector<instruction> slakken::bytecode::decode_instructions(function_map const& functions, const_pool const& consts, char const* binary, std::size_t binary_size) {
  std::vector<instruction> insts;
  for (auto begin = binary, end = binary + binary_size; begin != end;) {
#include "../build/decode.inc"
    throw decode_opcode_error();
  }
  return insts;
}
<|endoftext|>


<commit_before>#include "pyBackendWrapper.hpp"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

using namespace nervana;
using namespace std;

pyBackendWrapper::pyBackendWrapper(PyObject* pBackend,
                                   std::shared_ptr<nervana::interface::config> dtm_config,
                                   std::shared_ptr<nervana::interface::config> tgt_config,
                                   int batchSize)
: _dtm_config(dtm_config), _tgt_config(tgt_config), _batchSize(batchSize), _pBackend(pBackend)
{
    if (_pBackend == NULL) {
        throw std::runtime_error("Python Backend object does not exist");
    }

    Py_INCREF(_pBackend);
    _f_consume = PyObject_GetAttrString(_pBackend, "consume");

    if (!PyCallable_Check(_f_consume)) {
        throw std::runtime_error("Backend 'consume' function does not exist or is not callable");
    }

    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    PyOS_sighandler_t sighandler = PyOS_getsig(SIGINT);
    import_array();
    PyOS_setsig(SIGINT, sighandler);
    PyGILState_Release(gstate);

    _host_dlist = initPyList();
    _host_tlist = initPyList();
    _dev_dlist  = initPyList();
    _dev_tlist  = initPyList();
}

PyObject* pyBackendWrapper::initPyList(int length)
{
    PyObject* pylist = PyList_New(length);
    for (int i=0; i<length; ++i) {
        Py_INCREF(Py_None);
        if (PyList_SetItem(pylist, i, Py_None) != 0) {
            throw std::runtime_error("Error initializing list");
        }
    }
    return pylist;
}

pyBackendWrapper::~pyBackendWrapper()
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    Py_XDECREF(_host_dlist);
    Py_XDECREF(_host_tlist);
    Py_XDECREF(_dev_dlist);
    Py_XDECREF(_dev_tlist);
    Py_XDECREF(_f_consume);
    Py_XDECREF(_pBackend);
    PyGILState_Release(gstate);

}

bool pyBackendWrapper::use_pinned_memory()
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    bool result = false;
    PyObject *pinned_mem = PyObject_GetAttrString(_pBackend, "use_pinned_mem");
    if (pinned_mem != NULL) {
        if (PyObject_IsTrue(pinned_mem)) {
            result = true;
        }
        Py_DECREF(pinned_mem);
    }
    PyGILState_Release(gstate);
    return result;
}

// Copy to device.
void pyBackendWrapper::call_backend_transfer(buffer_out_array &outBuf, int bufIdx)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    wrap_buffer_pool(_host_dlist, outBuf[0], bufIdx, _dtm_config);
    wrap_buffer_pool(_host_tlist, outBuf[1], bufIdx, _tgt_config);

    PyObject* dArgs  = Py_BuildValue("iOO", bufIdx, _host_dlist, _dev_dlist);

    if (dArgs == NULL) {
        throw std::runtime_error("Unable to build args");
    }
    PyObject* dRes = PyObject_CallObject(_f_consume, dArgs);
    Py_XDECREF(dArgs);
    Py_XDECREF(dRes);

    PyObject* tArgs  = Py_BuildValue("iOO", bufIdx, _host_tlist, _dev_tlist);
    PyObject* tRes = PyObject_CallObject(_f_consume, tArgs);
    if (!tRes) {
        PyErr_Print();
    }
    Py_XDECREF(tArgs);
    Py_XDECREF(tRes);
    PyGILState_Release(gstate);

}

PyObject* pyBackendWrapper::get_dtm_tgt_pair(int bufIdx)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    PyObject *dItem = PyList_GetItem(_dev_dlist, bufIdx);
    PyObject *hItem = PyList_GetItem(_dev_tlist, bufIdx);
    if (dItem == NULL || hItem == NULL) {
        throw std::runtime_error("Bad Index");
    }

    PyObject* dtm_tgt_pair = Py_BuildValue("OO", dItem, hItem);
    PyGILState_Release(gstate);
    return dtm_tgt_pair;
}

void pyBackendWrapper::wrap_buffer_pool(PyObject *list, buffer_out *buf, int bufIdx,
                                        const shared_ptr<nervana::interface::config> &cfg)
{
    PyObject *hdItem = PyList_GetItem(list, bufIdx);

    if (hdItem == NULL) {
        throw std::runtime_error("Bad Index");
    }
    if (hdItem != Py_None) {
        return;
    }

    // For now, we will collapse everything into two dimensions
    int all_dims = std::accumulate(cfg->get_shape().begin(),
                                   cfg->get_shape().end(),
                                   1, std::multiplies<uint32_t>());
    int nd = 2;
    npy_intp dims[2] = {_batchSize, all_dims};

    PyObject *p_array = PyArray_SimpleNewFromData(nd, dims, cfg->get_type().np_type,buf->data());
    if (p_array == NULL) {
        throw std::runtime_error("Unable to wrap buffer pool in as python object");
    }

    if (PyList_SetItem(list, bufIdx, p_array) != 0) {
        throw std::runtime_error("Unable to add python array to list");
    }
}

<commit_msg>fix strides on numpy array generated in pyBackendWrapper and sent to backend.consume<commit_after>#include "pyBackendWrapper.hpp"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

using namespace nervana;
using namespace std;

pyBackendWrapper::pyBackendWrapper(PyObject* pBackend,
                                   std::shared_ptr<nervana::interface::config> dtm_config,
                                   std::shared_ptr<nervana::interface::config> tgt_config,
                                   int batchSize)
: _dtm_config(dtm_config), _tgt_config(tgt_config), _batchSize(batchSize), _pBackend(pBackend)
{
    if (_pBackend == NULL) {
        throw std::runtime_error("Python Backend object does not exist");
    }

    Py_INCREF(_pBackend);
    _f_consume = PyObject_GetAttrString(_pBackend, "consume");

    if (!PyCallable_Check(_f_consume)) {
        throw std::runtime_error("Backend 'consume' function does not exist or is not callable");
    }

    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    PyOS_sighandler_t sighandler = PyOS_getsig(SIGINT);
    import_array();
    PyOS_setsig(SIGINT, sighandler);
    PyGILState_Release(gstate);

    _host_dlist = initPyList();
    _host_tlist = initPyList();
    _dev_dlist  = initPyList();
    _dev_tlist  = initPyList();
}

PyObject* pyBackendWrapper::initPyList(int length)
{
    PyObject* pylist = PyList_New(length);
    for (int i=0; i<length; ++i) {
        Py_INCREF(Py_None);
        if (PyList_SetItem(pylist, i, Py_None) != 0) {
            throw std::runtime_error("Error initializing list");
        }
    }
    return pylist;
}

pyBackendWrapper::~pyBackendWrapper()
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    Py_XDECREF(_host_dlist);
    Py_XDECREF(_host_tlist);
    Py_XDECREF(_dev_dlist);
    Py_XDECREF(_dev_tlist);
    Py_XDECREF(_f_consume);
    Py_XDECREF(_pBackend);
    PyGILState_Release(gstate);

}

bool pyBackendWrapper::use_pinned_memory()
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    bool result = false;
    PyObject *pinned_mem = PyObject_GetAttrString(_pBackend, "use_pinned_mem");
    if (pinned_mem != NULL) {
        if (PyObject_IsTrue(pinned_mem)) {
            result = true;
        }
        Py_DECREF(pinned_mem);
    }
    PyGILState_Release(gstate);
    return result;
}

// Copy to device.
void pyBackendWrapper::call_backend_transfer(buffer_out_array &outBuf, int bufIdx)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    wrap_buffer_pool(_host_dlist, outBuf[0], bufIdx, _dtm_config);
    wrap_buffer_pool(_host_tlist, outBuf[1], bufIdx, _tgt_config);

    PyObject* dArgs  = Py_BuildValue("iOO", bufIdx, _host_dlist, _dev_dlist);

    if (dArgs == NULL) {
        throw std::runtime_error("Unable to build args");
    }
    PyObject* dRes = PyObject_CallObject(_f_consume, dArgs);
    Py_XDECREF(dArgs);
    Py_XDECREF(dRes);

    PyObject* tArgs  = Py_BuildValue("iOO", bufIdx, _host_tlist, _dev_tlist);
    PyObject* tRes = PyObject_CallObject(_f_consume, tArgs);
    if (!tRes) {
        PyErr_Print();
    }
    Py_XDECREF(tArgs);
    Py_XDECREF(tRes);
    PyGILState_Release(gstate);

}

PyObject* pyBackendWrapper::get_dtm_tgt_pair(int bufIdx)
{
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    PyObject *dItem = PyList_GetItem(_dev_dlist, bufIdx);
    PyObject *hItem = PyList_GetItem(_dev_tlist, bufIdx);
    if (dItem == NULL || hItem == NULL) {
        throw std::runtime_error("Bad Index");
    }

    PyObject* dtm_tgt_pair = Py_BuildValue("OO", dItem, hItem);
    PyGILState_Release(gstate);
    return dtm_tgt_pair;
}

void pyBackendWrapper::wrap_buffer_pool(PyObject *list, buffer_out *buf, int bufIdx,
                                        const shared_ptr<nervana::interface::config> &cfg)
{
    PyObject *hdItem = PyList_GetItem(list, bufIdx);

    if (hdItem == NULL) {
        throw std::runtime_error("Bad Index");
    }
    if (hdItem != Py_None) {
        return;
    }

    // For now, we will collapse everything into two dimensions
    int all_dims = std::accumulate(cfg->get_shape().begin(),
                                   cfg->get_shape().end(),
                                   1, std::multiplies<uint32_t>());
    int nd = 2;
    npy_intp dims[2] = {_batchSize, all_dims};

    PyObject *p_array = PyArray_SimpleNewFromData(nd, dims, cfg->get_type().np_type, buf->data());

    // update strides.  not sure why this isn't happening correctly
    // inside PyArray_SimpleNewFromData
    npy_intp* strides = PyArray_STRIDES((PyArrayObject*)p_array);
    strides[1] *= dims[0];

    if (p_array == NULL) {
        throw std::runtime_error("Unable to wrap buffer pool in as python object");
    }

    if (PyList_SetItem(list, bufIdx, p_array) != 0) {
        throw std::runtime_error("Unable to add python array to list");
    }
}

<|endoftext|>


<commit_before>// RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
// RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete,alpha.cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

typedef __typeof__(sizeof(int)) size_t;
extern "C" void *malloc(size_t);
int *global;

//------------------
// check for leaks
//------------------

//----- Standard non-placement operators
void testGlobalOpNew() {
  void *p = operator new(0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalOpNewArray() {
  void *p = operator new[](0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNewExpr() {
  int *p = new int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNewExprArray() {
  int *p = new int[0];
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Standard nothrow placement operators
void testGlobalNoThrowPlacementOpNewBeforeOverload() {
  void *p = operator new(0, std::nothrow);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNoThrowPlacementExprNewBeforeOverload() {
  int *p = new(std::nothrow) int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Standard pointer placement operators
void testGlobalPointerPlacementNew() {
  int i;

  void *p1 = operator new(0, &i); // no warn

  void *p2 = operator new[](0, &i); // no warn

  int *p3 = new(&i) int; // no warn

  int *p4 = new(&i) int[0]; // no warn
}

//----- Other cases
void testNewMemoryIsInHeap() {
  int *p = new int;
  if (global != p) // condition is always true as 'p' wraps a heap region that
                   // is different from a region wrapped by 'global'
    global = p; // pointer escapes
}

struct PtrWrapper {
  int *x;

  PtrWrapper(int *input) : x(input) {}
};

void testNewInvalidationPlacement(PtrWrapper *w) {
  // Ensure that we don't consider this a leak.
  new (w) PtrWrapper(new int); // no warn
}

//---------------
// other checks
//---------------

class SomeClass {
public:
  void f(int *p);
};

void f(int *p1, int *p2 = 0, int *p3 = 0);
void g(SomeClass &c, ...);

void testUseFirstArgAfterDelete() {
  int *p = new int;
  delete p;
  f(p); // expected-warning{{Use of memory after it is freed}}
}

void testUseMiddleArgAfterDelete(int *p) {
  delete p;
  f(0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseLastArgAfterDelete(int *p) {
  delete p;
  f(0, 0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseRefArgAfterDelete(SomeClass &c) {
  delete &c;
  g(c); // expected-warning{{Use of memory after it is freed}}
}

void testVariadicArgAfterDelete() {
  SomeClass c;
  int *p = new int;
  delete p;
  g(c, 0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseMethodArgAfterDelete(int *p) {
  SomeClass *c = new SomeClass;
  delete p;
  c->f(p); // expected-warning{{Use of memory after it is freed}}
}

void testUseThisAfterDelete() {
  SomeClass *c = new SomeClass;
  delete c;
  c->f(0); // expected-warning{{Use of memory after it is freed}}
}

void testDeleteAlloca() {
  int *p = (int *)__builtin_alloca(sizeof(int));
  delete p; // expected-warning{{Memory allocated by alloca() should not be deallocated}}
}

void testDoubleDelete() {
  int *p = new int;
  delete p;
  delete p; // expected-warning{{Attempt to free released memory}}
}

void testExprDeleteArg() {
  int i;
  delete &i; // expected-warning{{Argument to 'delete' is the address of the local variable 'i', which is not memory allocated by 'new'}}
}

void testExprDeleteArrArg() {
  int i;
  delete[] &i; // expected-warning{{Argument to 'delete[]' is the address of the local variable 'i', which is not memory allocated by 'new[]'}}
}

void testAllocDeallocNames() {
  int *p = new(std::nothrow) int[1];
  delete[] (++p); // expected-warning{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
}

//--------------------------------
// Test escape of newed const pointer. Note, a const pointer can be deleted.
//--------------------------------
struct StWithConstPtr {
  const int *memp;
};
void escape(const int &x);
void escapeStruct(const StWithConstPtr &x);
void escapePtr(const StWithConstPtr *x);
void escapeVoidPtr(const void *x);

void testConstEscape() {
  int *p = new int(1);
  escape(*p);
} // no-warning

void testConstEscapeStruct() {
  StWithConstPtr *St = new StWithConstPtr();
  escapeStruct(*St);
} // no-warning

void testConstEscapeStructPtr() {
  StWithConstPtr *St = new StWithConstPtr();
  escapePtr(St);
} // no-warning

void testConstEscapeMember() {
  StWithConstPtr St;
  St.memp = new int(2);
  escapeVoidPtr(St.memp);
} // no-warning

void testConstEscapePlacementNew() {
  int *x = (int *)malloc(sizeof(int));
  void *y = new (x) int;
  escapeVoidPtr(y);
} // no-warning
<commit_msg>[analyzer] +Testcase: several used-after-free args passed to a function.<commit_after>// RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
// RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete,alpha.cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

typedef __typeof__(sizeof(int)) size_t;
extern "C" void *malloc(size_t);
int *global;

//------------------
// check for leaks
//------------------

//----- Standard non-placement operators
void testGlobalOpNew() {
  void *p = operator new(0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalOpNewArray() {
  void *p = operator new[](0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNewExpr() {
  int *p = new int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNewExprArray() {
  int *p = new int[0];
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Standard nothrow placement operators
void testGlobalNoThrowPlacementOpNewBeforeOverload() {
  void *p = operator new(0, std::nothrow);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testGlobalNoThrowPlacementExprNewBeforeOverload() {
  int *p = new(std::nothrow) int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Standard pointer placement operators
void testGlobalPointerPlacementNew() {
  int i;

  void *p1 = operator new(0, &i); // no warn

  void *p2 = operator new[](0, &i); // no warn

  int *p3 = new(&i) int; // no warn

  int *p4 = new(&i) int[0]; // no warn
}

//----- Other cases
void testNewMemoryIsInHeap() {
  int *p = new int;
  if (global != p) // condition is always true as 'p' wraps a heap region that
                   // is different from a region wrapped by 'global'
    global = p; // pointer escapes
}

struct PtrWrapper {
  int *x;

  PtrWrapper(int *input) : x(input) {}
};

void testNewInvalidationPlacement(PtrWrapper *w) {
  // Ensure that we don't consider this a leak.
  new (w) PtrWrapper(new int); // no warn
}

//---------------
// other checks
//---------------

class SomeClass {
public:
  void f(int *p);
};

void f(int *p1, int *p2 = 0, int *p3 = 0);
void g(SomeClass &c, ...);

void testUseFirstArgAfterDelete() {
  int *p = new int;
  delete p;
  f(p); // expected-warning{{Use of memory after it is freed}}
}

void testUseMiddleArgAfterDelete(int *p) {
  delete p;
  f(0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseLastArgAfterDelete(int *p) {
  delete p;
  f(0, 0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseSeveralArgsAfterDelete(int *p) {
  delete p;
  f(p, p, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseRefArgAfterDelete(SomeClass &c) {
  delete &c;
  g(c); // expected-warning{{Use of memory after it is freed}}
}

void testVariadicArgAfterDelete() {
  SomeClass c;
  int *p = new int;
  delete p;
  g(c, 0, p); // expected-warning{{Use of memory after it is freed}}
}

void testUseMethodArgAfterDelete(int *p) {
  SomeClass *c = new SomeClass;
  delete p;
  c->f(p); // expected-warning{{Use of memory after it is freed}}
}

void testUseThisAfterDelete() {
  SomeClass *c = new SomeClass;
  delete c;
  c->f(0); // expected-warning{{Use of memory after it is freed}}
}

void testDeleteAlloca() {
  int *p = (int *)__builtin_alloca(sizeof(int));
  delete p; // expected-warning{{Memory allocated by alloca() should not be deallocated}}
}

void testDoubleDelete() {
  int *p = new int;
  delete p;
  delete p; // expected-warning{{Attempt to free released memory}}
}

void testExprDeleteArg() {
  int i;
  delete &i; // expected-warning{{Argument to 'delete' is the address of the local variable 'i', which is not memory allocated by 'new'}}
}

void testExprDeleteArrArg() {
  int i;
  delete[] &i; // expected-warning{{Argument to 'delete[]' is the address of the local variable 'i', which is not memory allocated by 'new[]'}}
}

void testAllocDeallocNames() {
  int *p = new(std::nothrow) int[1];
  delete[] (++p); // expected-warning{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
}

//--------------------------------
// Test escape of newed const pointer. Note, a const pointer can be deleted.
//--------------------------------
struct StWithConstPtr {
  const int *memp;
};
void escape(const int &x);
void escapeStruct(const StWithConstPtr &x);
void escapePtr(const StWithConstPtr *x);
void escapeVoidPtr(const void *x);

void testConstEscape() {
  int *p = new int(1);
  escape(*p);
} // no-warning

void testConstEscapeStruct() {
  StWithConstPtr *St = new StWithConstPtr();
  escapeStruct(*St);
} // no-warning

void testConstEscapeStructPtr() {
  StWithConstPtr *St = new StWithConstPtr();
  escapePtr(St);
} // no-warning

void testConstEscapeMember() {
  StWithConstPtr St;
  St.memp = new int(2);
  escapeVoidPtr(St.memp);
} // no-warning

void testConstEscapePlacementNew() {
  int *x = (int *)malloc(sizeof(int));
  void *y = new (x) int;
  escapeVoidPtr(y);
} // no-warning
<|endoftext|>


<commit_before>#include "aquila/global.h"
#include "aquila/tools/TextPlot.h"
#include "UnitTest++/UnitTest++.h"
#include <cstddef>

SUITE(TextPlot)
{
    TEST(DefaultTitle)
    {
        Aquila::TextPlot plot;
        CHECK_EQUAL(plot.getTitle(), "Data plot");
    }

    TEST(CustomTitle)
    {
        Aquila::TextPlot plot;
        plot.setTitle("My plot");
        CHECK_EQUAL(plot.getTitle(), "My plot");
    }

    TEST(DefaultSize)
    {
        Aquila::TextPlot plot;
        CHECK_EQUAL(plot.getWidth(), 64);
        CHECK_EQUAL(plot.getHeight(), 16);
    }

    TEST(CustomSize)
    {
        Aquila::TextPlot plot;
        plot.setSize(80, 12);
        CHECK_EQUAL(plot.getWidth(), 80);
        CHECK_EQUAL(plot.getHeight(), 12);
    }
}
<commit_msg>Added u suffixes for unsigned integers.<commit_after>#include "aquila/global.h"
#include "aquila/tools/TextPlot.h"
#include "UnitTest++/UnitTest++.h"
#include <cstddef>

SUITE(TextPlot)
{
    TEST(DefaultTitle)
    {
        Aquila::TextPlot plot;
        CHECK_EQUAL(plot.getTitle(), "Data plot");
    }

    TEST(CustomTitle)
    {
        Aquila::TextPlot plot;
        plot.setTitle("My plot");
        CHECK_EQUAL(plot.getTitle(), "My plot");
    }

    TEST(DefaultSize)
    {
        Aquila::TextPlot plot;
        CHECK_EQUAL(plot.getWidth(), 64u);
        CHECK_EQUAL(plot.getHeight(), 16u);
    }

    TEST(CustomSize)
    {
        Aquila::TextPlot plot;
        plot.setSize(80, 12);
        CHECK_EQUAL(plot.getWidth(), 80u);
        CHECK_EQUAL(plot.getHeight(), 12u);
    }
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: 2014年11月28日
 *      Author: nemo
 */

#include <iostream>
#include <string>
#include <regex>
#include <sstream>

#include "src/libNovelChapterParser.h"

using namespace std;

int main(int argc, char* argv[])
{
	NovelChapterParser novelParser;
	//TODO Load RegExp from file.
	novelParser.setRegularExp("楔.*子.*");
	novelParser.setRegularExp("第[0-9]+章.*");
	novelParser.setRegularExp("第[零一二三四五六七八九十百千零壹貳參肆伍陸柒捌玖拾佰仟]+章.*");

	novelParser.parseChapter();

//	try
//	{
//		stringstream tmpSS;
//
//		regex reg("第[0-9]+章.*");
//		std::string s = "第1365章 神魔遮天 QQ 第1366章 GG \n第1367章 GG惹";
//
//		smatch mat;
//		std::cout << "Matched: " << regex_search(s, mat, reg) << std::endl;
//
//		cout << *(mat.begin()) << endl;
//
//
//		ssub_match prefix = mat.prefix();
//		std::string str_prefix(prefix.first, prefix.second);
//		std::cout << "Prefix: " << str_prefix << std::endl;
//		std::cout << "Length: " << prefix.length() << std::endl;
//
//	}
//	catch (const regex_error& e)
//	{
//		std::cout << "Error: " << e.what() << std::endl;
//	}

	return 0;
}
<commit_msg>Rearrange the order of regular expression.<commit_after>/*
 * main.cpp
 *
 *  Created on: 2014年11月28日
 *      Author: nemo
 */

#include <iostream>
#include <string>
#include <regex>
#include <sstream>

#include "src/libNovelChapterParser.h"

using namespace std;

int main(int argc, char* argv[])
{
	NovelChapterParser novelParser;
	//TODO Load RegExp from file.
	novelParser.setRegularExp("第[0-9]+章.*");
	novelParser.setRegularExp("第[零一二三四五六七八九十百千零壹貳參肆伍陸柒捌玖拾佰仟]+章.*");
	novelParser.setRegularExp("楔.*子.*");

	novelParser.parseChapter();

//	try
//	{
//		stringstream tmpSS;
//
//		regex reg("第[0-9]+章.*");
//		std::string s = "第1365章 神魔遮天 QQ 第1366章 GG \n第1367章 GG惹";
//
//		smatch mat;
//		std::cout << "Matched: " << regex_search(s, mat, reg) << std::endl;
//
//		cout << *(mat.begin()) << endl;
//
//
//		ssub_match prefix = mat.prefix();
//		std::string str_prefix(prefix.first, prefix.second);
//		std::cout << "Prefix: " << str_prefix << std::endl;
//		std::cout << "Length: " << prefix.length() << std::endl;
//
//	}
//	catch (const regex_error& e)
//	{
//		std::cout << "Error: " << e.what() << std::endl;
//	}

	return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <test/bootstrapfixture.hxx>

#include "MColumnAlias.hxx"
#include "MQueryHelper.hxx"
#include "MConnection.hxx"

#include <com/sun/star/sdbc/XDriver.hpp>

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;

namespace connectivity { namespace mork {

class MorkDriverTest: public test::BootstrapFixture
{
public:
    MorkDriverTest() : test::BootstrapFixture(false, false) {};

    void checkAcceptsURL(Reference< XDriver> xDriver, const char* url, bool expected);
    void test_metadata();
    void test_select_default_all();
    void test_select_list_table_joe_doe_5();

    virtual void setUp() SAL_OVERRIDE;
    virtual void tearDown() SAL_OVERRIDE;

    CPPUNIT_TEST_SUITE(MorkDriverTest);

    CPPUNIT_TEST(test_metadata);
    CPPUNIT_TEST(test_select_default_all);
    CPPUNIT_TEST(test_select_list_table_joe_doe_5);
    CPPUNIT_TEST_SUITE_END();

private:
    Reference<XInterface> m_xMorkComponent;
    Reference<XConnection> m_xConnection;
};

void MorkDriverTest::checkAcceptsURL(Reference< XDriver> xDriver, const char* url, bool expected)
{
    bool res = xDriver->acceptsURL(OUString::createFromAscii(url));
    if (res != expected)
    {
        CPPUNIT_ASSERT_MESSAGE("wrong URL outcome!", true);
    }
}

void MorkDriverTest::setUp()
{
    test::BootstrapFixture::setUp();
    m_xMorkComponent = getMultiServiceFactory()->createInstance("com.sun.star.comp.sdbc.MorkDriver");
    CPPUNIT_ASSERT_MESSAGE("no mork component!", m_xMorkComponent.is());

    // is this the best way to pass test file through URL?
    // may be take a custom Sequence< PropertyValue > route?
    OUString url = "sdbc:address:thunderbird:unittest:" +
        getPathFromSrc("/connectivity/qa/connectivity/mork/abook_10_john_does.mab");

    Sequence< PropertyValue > info;
    Reference< XDriver> xDriver(m_xMorkComponent, UNO_QUERY);
    if (!xDriver.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot connect to mork driver!", xDriver.is());
    }

    // bad
    checkAcceptsURL(xDriver, "sdbc:address:macab",        false);
    checkAcceptsURL(xDriver, "sdbc:mozab:ldap:",          false);
    checkAcceptsURL(xDriver, "sdbc:mozab:outlook:",       false);
    checkAcceptsURL(xDriver, "sdbc:mozab:outlookexp:",    false);

    // good
    checkAcceptsURL(xDriver, "sdbc:mozab:mozilla:",       true);
    checkAcceptsURL(xDriver, "sdbc:mozab:thunderbird:",   true);
    checkAcceptsURL(xDriver, "sdbc:address:mozilla:",     true);
    checkAcceptsURL(xDriver, "sdbc:address:thunderbird:", true);

    m_xConnection = xDriver->connect(url, info);
    if (!m_xConnection.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot connect to address book data soure!", m_xConnection.is());
    }
}

void MorkDriverTest::tearDown()
{
// how to make dispose() work?
// Reference< com::sun::star::lang::XComponent >( m_xMorkComponent, UNO_QUERY_THROW )->dispose();
    test::BootstrapFixture::tearDown();
}

void MorkDriverTest::test_metadata()
{
    Reference< XDatabaseMetaData > xDatabaseMetaData = m_xConnection->getMetaData();
    if (!xDatabaseMetaData.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot retrieve meta data!", xDatabaseMetaData.is());
    }

    const Any catalog;
    const OUString schemaPattern = "%";
    const OUString tableNamePattern = "%";
    const Sequence< OUString > types;

    Reference< XResultSet > xResultSet =
        xDatabaseMetaData->getTables(catalog, schemaPattern, tableNamePattern, types);
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot retrieve tables!", xResultSet.is());
    }

    // TODO: how to access that result set and check the tables?
    // it should be 3 tables inside: AddressBook, does_5 and does_10
}

void MorkDriverTest::test_select_default_all()
{
    const OUString sql = "select \"E-mail\" from \"AddressBook\" ORDER BY \"E-mail\"";
    Reference< XPreparedStatement > xStatement = m_xConnection->prepareStatement(sql);
    if (!xStatement.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot create prepared statement!", xStatement.is());
    }

    Reference< XResultSet > xResultSet = xStatement->executeQuery();
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot execure sql statement!", xResultSet.is());
    }

    Reference< XRow > xDelegatorRow(xResultSet, UNO_QUERY);
    if (!xDelegatorRow.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot extract row from result set!", xDelegatorRow.is());
    }

    bool result = xResultSet->first();
    CPPUNIT_ASSERT_MESSAGE("fetch first row failed!", result);
    OUString mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("first row is not john@doe.org!", mail.equalsAscii("john@doe.org"));

    result = xResultSet->next();
    CPPUNIT_ASSERT_MESSAGE("fetch second row failed!", result);
    mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("second row is not john@doe10.org!", mail.equalsAscii("john@doe10.org"));

    result = xResultSet->last();
    CPPUNIT_ASSERT_MESSAGE("fetch last row failed!", result);
    mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("last row is not john@doe9.org!", mail.equalsAscii("john@doe9.org"));
}

void MorkDriverTest::test_select_list_table_joe_doe_5()
{
    const OUString sql = "select \"E-mail\" from \"does_5\" where \"E-mail\" LIKE '%doe5.org' ";
    Reference< XPreparedStatement > xStatement = m_xConnection->prepareStatement(sql);
    if (!xStatement.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot create prepared statement!", xStatement.is());
    }

    Reference< XResultSet > xResultSet = xStatement->executeQuery();
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot execure sql statement!", xResultSet.is());
    }

    Reference< XRow > xDelegatorRow(xResultSet, UNO_QUERY);
    if (!xDelegatorRow.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot extract row from result set!", xDelegatorRow.is());
    }

    bool result = xResultSet->first();
    CPPUNIT_ASSERT_MESSAGE("fetch first row failed!", result);
    OUString mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("last row is not john@doe5.org!", mail.equalsAscii("john@doe5.org"));
}

CPPUNIT_TEST_SUITE_REGISTRATION(MorkDriverTest);

}}

CPPUNIT_PLUGIN_IMPLEMENT();
<commit_msg>Fix leaks in test code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <test/bootstrapfixture.hxx>

#include "MColumnAlias.hxx"
#include "MQueryHelper.hxx"
#include "MConnection.hxx"

#include <com/sun/star/sdbc/XDriver.hpp>

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;

namespace connectivity { namespace mork {

class MorkDriverTest: public test::BootstrapFixture
{
public:
    MorkDriverTest() : test::BootstrapFixture(false, false) {};

    void checkAcceptsURL(Reference< XDriver> xDriver, const char* url, bool expected);
    void test_metadata();
    void test_select_default_all();
    void test_select_list_table_joe_doe_5();

    virtual void setUp() SAL_OVERRIDE;
    virtual void tearDown() SAL_OVERRIDE;

    CPPUNIT_TEST_SUITE(MorkDriverTest);

    CPPUNIT_TEST(test_metadata);
    CPPUNIT_TEST(test_select_default_all);
    CPPUNIT_TEST(test_select_list_table_joe_doe_5);
    CPPUNIT_TEST_SUITE_END();

private:
    Reference<XInterface> m_xMorkComponent;
    Reference<XConnection> m_xConnection;
};

void MorkDriverTest::checkAcceptsURL(Reference< XDriver> xDriver, const char* url, bool expected)
{
    bool res = xDriver->acceptsURL(OUString::createFromAscii(url));
    if (res != expected)
    {
        CPPUNIT_ASSERT_MESSAGE("wrong URL outcome!", true);
    }
}

void MorkDriverTest::setUp()
{
    test::BootstrapFixture::setUp();
    m_xMorkComponent = getMultiServiceFactory()->createInstance("com.sun.star.comp.sdbc.MorkDriver");
    CPPUNIT_ASSERT_MESSAGE("no mork component!", m_xMorkComponent.is());

    // is this the best way to pass test file through URL?
    // may be take a custom Sequence< PropertyValue > route?
    OUString url = "sdbc:address:thunderbird:unittest:" +
        getPathFromSrc("/connectivity/qa/connectivity/mork/abook_10_john_does.mab");

    Sequence< PropertyValue > info;
    Reference< XDriver> xDriver(m_xMorkComponent, UNO_QUERY);
    if (!xDriver.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot connect to mork driver!", xDriver.is());
    }

    // bad
    checkAcceptsURL(xDriver, "sdbc:address:macab",        false);
    checkAcceptsURL(xDriver, "sdbc:mozab:ldap:",          false);
    checkAcceptsURL(xDriver, "sdbc:mozab:outlook:",       false);
    checkAcceptsURL(xDriver, "sdbc:mozab:outlookexp:",    false);

    // good
    checkAcceptsURL(xDriver, "sdbc:mozab:mozilla:",       true);
    checkAcceptsURL(xDriver, "sdbc:mozab:thunderbird:",   true);
    checkAcceptsURL(xDriver, "sdbc:address:mozilla:",     true);
    checkAcceptsURL(xDriver, "sdbc:address:thunderbird:", true);

    m_xConnection = xDriver->connect(url, info);
    if (!m_xConnection.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot connect to address book data soure!", m_xConnection.is());
    }
}

void MorkDriverTest::tearDown()
{
// how to make dispose() work?
// Reference< com::sun::star::lang::XComponent >( m_xMorkComponent, UNO_QUERY_THROW )->dispose();
    m_xConnection->close();
    test::BootstrapFixture::tearDown();
}

void MorkDriverTest::test_metadata()
{
    Reference< XDatabaseMetaData > xDatabaseMetaData = m_xConnection->getMetaData();
    if (!xDatabaseMetaData.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot retrieve meta data!", xDatabaseMetaData.is());
    }

    const Any catalog;
    const OUString schemaPattern = "%";
    const OUString tableNamePattern = "%";
    const Sequence< OUString > types;

    Reference< XResultSet > xResultSet =
        xDatabaseMetaData->getTables(catalog, schemaPattern, tableNamePattern, types);
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot retrieve tables!", xResultSet.is());
    }

    // TODO: how to access that result set and check the tables?
    // it should be 3 tables inside: AddressBook, does_5 and does_10
}

void MorkDriverTest::test_select_default_all()
{
    const OUString sql = "select \"E-mail\" from \"AddressBook\" ORDER BY \"E-mail\"";
    Reference< XPreparedStatement > xStatement = m_xConnection->prepareStatement(sql);
    if (!xStatement.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot create prepared statement!", xStatement.is());
    }

    Reference< XResultSet > xResultSet = xStatement->executeQuery();
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot execure sql statement!", xResultSet.is());
    }

    Reference< XRow > xDelegatorRow(xResultSet, UNO_QUERY);
    if (!xDelegatorRow.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot extract row from result set!", xDelegatorRow.is());
    }

    bool result = xResultSet->first();
    CPPUNIT_ASSERT_MESSAGE("fetch first row failed!", result);
    OUString mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("first row is not john@doe.org!", mail.equalsAscii("john@doe.org"));

    result = xResultSet->next();
    CPPUNIT_ASSERT_MESSAGE("fetch second row failed!", result);
    mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("second row is not john@doe10.org!", mail.equalsAscii("john@doe10.org"));

    result = xResultSet->last();
    CPPUNIT_ASSERT_MESSAGE("fetch last row failed!", result);
    mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("last row is not john@doe9.org!", mail.equalsAscii("john@doe9.org"));

    css::uno::Reference<css::sdbc::XCloseable>(
        xStatement, css::uno::UNO_QUERY_THROW)->close();
}

void MorkDriverTest::test_select_list_table_joe_doe_5()
{
    const OUString sql = "select \"E-mail\" from \"does_5\" where \"E-mail\" LIKE '%doe5.org' ";
    Reference< XPreparedStatement > xStatement = m_xConnection->prepareStatement(sql);
    if (!xStatement.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot create prepared statement!", xStatement.is());
    }

    Reference< XResultSet > xResultSet = xStatement->executeQuery();
    if (!xResultSet.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot execure sql statement!", xResultSet.is());
    }

    Reference< XRow > xDelegatorRow(xResultSet, UNO_QUERY);
    if (!xDelegatorRow.is())
    {
        CPPUNIT_ASSERT_MESSAGE("cannot extract row from result set!", xDelegatorRow.is());
    }

    bool result = xResultSet->first();
    CPPUNIT_ASSERT_MESSAGE("fetch first row failed!", result);
    OUString mail = xDelegatorRow->getString(1);
    CPPUNIT_ASSERT_MESSAGE("last row is not john@doe5.org!", mail.equalsAscii("john@doe5.org"));

    css::uno::Reference<css::sdbc::XCloseable>(
        xStatement, css::uno::UNO_QUERY_THROW)->close();
}

CPPUNIT_TEST_SUITE_REGISTRATION(MorkDriverTest);

}}

CPPUNIT_PLUGIN_IMPLEMENT();
<|endoftext|>


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

using namespace connectivity;
//**************************************************************
//************ Class: java.io.InputStream
//**************************************************************

jclass java_io_InputStream::theClass = 0;
java_io_InputStream::java_io_InputStream( JNIEnv * pEnv, jobject myObj )
    : java_lang_Object( pEnv, myObj )
{
    SDBThreadAttach::addRef();
}
java_io_InputStream::~java_io_InputStream()
{
    SDBThreadAttach::releaseRef();
}

jclass java_io_InputStream::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/io/InputStream" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_io_InputStream::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

sal_Int32 SAL_CALL java_io_InputStream::readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    return readBytes(aData,nMaxBytesToRead);
}

void SAL_CALL java_io_InputStream::skipBytes( sal_Int32 nBytesToSkip ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "(I)I";
        static const char * cMethodName = "skip";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallIntMethod( object, mID,nBytesToSkip);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
}

sal_Int32 SAL_CALL java_io_InputStream::available(  ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    jboolean out(sal_False);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "()Z";
        static const char * cMethodName = "available";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallBooleanMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
    return out;
}
void SAL_CALL java_io_InputStream::closeInput(  ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "()V";
        static const char * cMethodName = "close";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            t.pEnv->CallVoidMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
}
// -----------------------------------------------------
sal_Int32 SAL_CALL java_io_InputStream::readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    if ( aData.getLength() < nBytesToRead )
        throw ::com::sun::star::io::BufferSizeExceededException();
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jbyteArray pByteArray = t.pEnv->NewByteArray(nBytesToRead);
        static const char * cSignature = "([BII)I";
        static const char * cMethodName = "read";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallIntMethod( object, mID, pByteArray, 0, nBytesToRead );
            if ( !out )
                ThrowSQLException(t.pEnv,*this);
            if(out > 0)
            {
                jboolean p = sal_False;
                memcpy(aData.getArray(),t.pEnv->GetByteArrayElements(pByteArray,&p),out);
            }
        }
        t.pEnv->DeleteLocalRef((jbyteArray)pByteArray);
    } //t.pEnv
    return out;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.10.60); FILE MERGED 2006/09/01 17:22:20 kaib 1.10.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: InputStream.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:47:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_JAVA_IO_INPUTSTREAM_HXX_
#include "java/io/InputStream.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
//**************************************************************
//************ Class: java.io.InputStream
//**************************************************************

jclass java_io_InputStream::theClass = 0;
java_io_InputStream::java_io_InputStream( JNIEnv * pEnv, jobject myObj )
    : java_lang_Object( pEnv, myObj )
{
    SDBThreadAttach::addRef();
}
java_io_InputStream::~java_io_InputStream()
{
    SDBThreadAttach::releaseRef();
}

jclass java_io_InputStream::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/io/InputStream" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_io_InputStream::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

sal_Int32 SAL_CALL java_io_InputStream::readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    return readBytes(aData,nMaxBytesToRead);
}

void SAL_CALL java_io_InputStream::skipBytes( sal_Int32 nBytesToSkip ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "(I)I";
        static const char * cMethodName = "skip";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallIntMethod( object, mID,nBytesToSkip);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
}

sal_Int32 SAL_CALL java_io_InputStream::available(  ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    jboolean out(sal_False);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "()Z";
        static const char * cMethodName = "available";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallBooleanMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
    return out;
}
void SAL_CALL java_io_InputStream::closeInput(  ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        static const char * cSignature = "()V";
        static const char * cMethodName = "close";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            t.pEnv->CallVoidMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
        }
    } //t.pEnv
}
// -----------------------------------------------------
sal_Int32 SAL_CALL java_io_InputStream::readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
{
    if ( aData.getLength() < nBytesToRead )
        throw ::com::sun::star::io::BufferSizeExceededException();
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jbyteArray pByteArray = t.pEnv->NewByteArray(nBytesToRead);
        static const char * cSignature = "([BII)I";
        static const char * cMethodName = "read";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallIntMethod( object, mID, pByteArray, 0, nBytesToRead );
            if ( !out )
                ThrowSQLException(t.pEnv,*this);
            if(out > 0)
            {
                jboolean p = sal_False;
                memcpy(aData.getArray(),t.pEnv->GetByteArrayElements(pByteArray,&p),out);
            }
        }
        t.pEnv->DeleteLocalRef((jbyteArray)pByteArray);
    } //t.pEnv
    return out;
}

<|endoftext|>