int test_main( int , char* [] )
{
   test_named_subexpressions(char(0));
   test_named_subexpressions(wchar_t(0));
   return 0;
}
bool WandReadEncryptedField(std::string::iterator &buffer,
                            std::string::iterator &buffer_end,
                            base::string16 &result,
                            binary_string *master_password = NULL) {
  uint32_t len = 0;
  uint32_t iv_len=0;
  uint32_t data_len=0;
  binary_string iv;
  binary_string in_data;
  binary_string out_data;

  if (!WandReadUint32(buffer, buffer_end, len))
    return false;
  if (len == 0)
    return true;
  if (len < 8)
    return false;

  if (!WandReadUint32(buffer, buffer_end, iv_len))
    return false;
  if (iv_len == 0 || !WandReadVector(buffer, buffer_end, iv, iv_len))
    return false;

  if (!WandReadUint32(buffer, buffer_end, data_len))
    return false;
  if (len != 8+iv_len+data_len)
    return false;
  if (data_len == 0 || !WandReadVector(buffer, buffer_end, in_data, data_len))
    return false;

  if (master_password && !master_password->empty()) {
    if (!DecryptMasterPasswordKeys(*master_password, iv, in_data, out_data) ||
        !ValidatePasswordBlock(*master_password, iv,
                               "Opera Email Password Verification", out_data))
      return false;
  } else {
    base::MD5Digest res1, res2;

    base::MD5Context ctx;

    base::MD5Init(&ctx);
    base::MD5Update(&ctx, base::StringPiece((char *) OperaObfuscationPass,
                                            sizeof(OperaObfuscationPass)));
    base::MD5Update(&ctx, iv);
    base::MD5Final(&res1, &ctx);

    base::MD5Init(&ctx);
    base::MD5Update(&ctx, base::StringPiece((char *) res1.a, sizeof(res1.a)));
    base::MD5Update(&ctx, base::StringPiece((char *) OperaObfuscationPass,
                                            sizeof(OperaObfuscationPass)));
    base::MD5Update(&ctx, iv);
    base::MD5Final(&res2, &ctx);

    std::string key;
    key.append((char *) res1.a, sizeof(res1.a));
    key.append((char *) res2.a, 3*8-sizeof(res2.a));

    scoped_ptr<crypto::SymmetricKey> dec_key(
          crypto::SymmetricKey::Import(crypto::SymmetricKey::DES_EDE3, key));

    crypto::Encryptor decryptor;
    if(!decryptor.Init(dec_key.get(), crypto::Encryptor::CBC,
          base::StringPiece((char *) res2.a+8, 8)))
      return true;

    if(!decryptor.Decrypt(in_data, &out_data))
      return false;
  }
  result.clear();
  for (binary_string::iterator it = out_data.begin(); it < out_data.end();) {
    unsigned char c01 = *it;
    it++;
    uint16_t b1 = uint16_t(c01);
    if (it >= out_data.end())
      return false;
    unsigned char c02 = *it;
    it++;
    uint16_t b2 = uint16_t(c02);

    uint16_t c1 = b1 | (b2 << 8);

    if (c1 == 0 && it == out_data.end())
      break;

    result.push_back(wchar_t(c1));
  }

  // TODO bigendian vs littleendian
  return true;
}
Пример #3
0
INT ReplaceHtmlEntities(std::basic_string<TCHAR>& htmlText)
{
	INT replaces = 0;
	size_t startPos = htmlText.find(L"&", 0);
	while (startPos != std::wstring::npos)
	{
		size_t nextEndPos = htmlText.find(L";", startPos + 1);
		if (nextEndPos == std::wstring::npos)
		{
			//=== Last &... wasn't an entity & we ve found EOF
			break;
		}
		BOOL bEntityIsValid = TRUE;
		size_t nextStartPos = htmlText.find(L"&", startPos + 1);
		if (nextStartPos != std::wstring::npos)
		{
			if (nextStartPos < nextEndPos)
			{
				//=== We ve found &..&..; pattern which is illegal
				bEntityIsValid = FALSE;
			}
		}
		if (bEntityIsValid)
			bEntityIsValid = ((nextEndPos - startPos) <= 8);
		if (bEntityIsValid)
		{
			wchar_t repVal = 0;
			LPCTSTR entityStart = &htmlText[startPos+1];
			if (*entityStart/*htmlText[startPos+1]*/ == '#')
			{
				//=== It is a int entity
				TCHAR intbf[10];
				INT copyChars = (INT) min(nextEndPos - startPos - 2, 9);
				_tcsncpy(intbf, &htmlText[startPos+2], copyChars);
				intbf[copyChars] = 0;
				INT val = _wtoi(intbf);
				if (val > 0 && val < 0xFFFE)
					repVal = wchar_t(val);
			}
			else
			{
				//=== It is a string entity
				//=== Check the ISO88591 entities
				for (int i = 0; i < sizeof(ISO88591_Entities)/sizeof(LPCTSTR); i++)
				{
					if (_tcsncmp(ISO88591_Entities[i], entityStart, _tcslen(ISO88591_Entities[i])) == 0)
					{
						repVal = (wchar_t) (i + 160);
						break;
					}
				}

				//=== Check the "other" mapped entities
				if (repVal == 0)
				{
					for (int i = 0; i < sizeof(strentity2wchar_t)/sizeof(HtmlStringEntityMap); i++)
					{
						if (_tcsncmp(strentity2wchar_t[i].html, entityStart, _tcslen(strentity2wchar_t[i].html)) == 0)
						{
							repVal = strentity2wchar_t[i].res;
							break;
						}
					}
				}
			}
			if (repVal != 0)
			{
				htmlText.erase(startPos + 1, nextEndPos - startPos);
				htmlText[startPos] = repVal;
				replaces++;
			}
			nextStartPos = htmlText.find(L"&", startPos + 1);
		}
		startPos = nextStartPos;

	}
	//for (int i = 0; i < sizeof(html2text)/sizeof(HtmlEntityMap); i++)
	//	replaces += replace(htmlText, html2text[i].html, html2text[i].text);
	return replaces;
}
Пример #4
0
void get_en_image(pcl::PointCloud<pcl::PointXYZ> &cloud)
{
    char flag = 'g';
    int i = 0;
    while(flag != 'q')
    {
        ostringstream conv;
        conv << i;
        cout<<"Capturing new calibration image from the ensenso stereo vision camera."<<endl;
        ///Read the Ensenso stereo cameras:
        try {
            // Initialize NxLib and enumerate cameras
            nxLibInitialize(true);

            // Reference to the first camera in the node BySerialNo
            NxLibItem root;
            NxLibItem camera = root[itmCameras][itmBySerialNo][0];

            // Open the Ensenso
            NxLibCommand open(cmdOpen);
            open.parameters()[itmCameras] = camera[itmSerialNumber].asString();
            open.execute();

            // Capture an image
            NxLibCommand (cmdCapture).execute();

            // Stereo matching task
            NxLibCommand (cmdComputeDisparityMap).execute ();

            // Convert disparity map into XYZ data for each pixel
            NxLibCommand (cmdComputePointMap).execute ();

            // Get info about the computed point map and copy it into a std::vector
            double timestamp;
            std::vector<float> pointMap;
            int width, height;
            camera[itmImages][itmRaw][itmLeft].getBinaryDataInfo (0, 0, 0, 0, 0, &timestamp);  // Get raw image timestamp
            camera[itmImages][itmPointMap].getBinaryDataInfo (&width, &height, 0, 0, 0, 0);
            camera[itmImages][itmPointMap].getBinaryData (pointMap, 0);

            // Copy point cloud and convert in meters
            //cloud.header.stamp = getPCLStamp (timestamp);
            cloud.resize (height * width);
            cloud.width = width;
            cloud.height = height;
            cloud.is_dense = false;

            // Copy data in point cloud (and convert milimeters in meters)
            for (size_t i = 0; i < pointMap.size (); i += 3)
            {
              cloud.points[i / 3].x = pointMap[i] / 1000.0;
              cloud.points[i / 3].y = pointMap[i + 1] / 1000.0;
              cloud.points[i / 3].z = pointMap[i + 2] / 1000.0;
            }

            NxLibCommand (cmdRectifyImages).execute();

            // Save images
            NxLibCommand saveImage(cmdSaveImage);
            //   raw left
            saveImage.parameters()[itmNode] = camera[itmImages][itmRaw][itmLeft].path;
            saveImage.parameters()[itmFilename] = "calib_en/raw_left" + conv.str()+".png";
            saveImage.execute();
            //   raw right
            /*saveImage.parameters()[itmNode] = camera[itmImages][itmRaw][itmRight].path;
            saveImage.parameters()[itmFilename] = "calib_en/raw_right.png";
            saveImage.execute();
            //   rectified left
            saveImage.parameters()[itmNode] = camera[itmImages][itmRectified][itmLeft].path;
            saveImage.parameters()[itmFilename] = "calib_en/rectified_left.png";
            saveImage.execute();
            //   rectified right
            saveImage.parameters()[itmNode] = camera[itmImages][itmRectified][itmRight].path;
            saveImage.parameters()[itmFilename] = "calib_en/rectified_right.png";
            saveImage.execute();*/
        } catch (NxLibException& e) { // Display NxLib API exceptions, if any
            printf("An NxLib API error with code %d (%s) occurred while accessing item %s.\n", e.getErrorCode(), e.getErrorText().c_str(), e.getItemPath().c_str());
            if (e.getErrorCode() == NxLibExecutionFailed) printf("/Execute:\n%s\n", NxLibItem(itmExecute).asJson(true).c_str());
        }
        /*catch (NxLibException &ex)
        {
            ensensoExceptionHandling (ex, "grabSingleCloud");
        }*/
        catch (...) { // Display other exceptions
            printf("Something, somewhere went terribly wrong!\n");
        }

        /*cout<<"Plug in the RGB camera and press any key to continue."<<endl;
        cin.ignore();
        cin.get();*/
        cout<<"Capturing new calibration image from the ensenso RGB camera."<<endl;

        ///Read the IDS RGB Camera attached to the Ensenso stereo camera
        HIDS hCam = 0;
        printf("Success-Code: %d\n",IS_SUCCESS);
        //Kamera öffnen
        INT nRet = is_InitCamera (&hCam, NULL);
        printf("Status Init %d\n",nRet);

        //Pixel-Clock setzen
        UINT nPixelClockDefault = 9;
        nRet = is_PixelClock(hCam, IS_PIXELCLOCK_CMD_SET,
                            (void*)&nPixelClockDefault,
                            sizeof(nPixelClockDefault));

        printf("Status is_PixelClock %d\n",nRet);

        //Farbmodus der Kamera setzen
        //INT colorMode = IS_CM_CBYCRY_PACKED;
        INT colorMode = IS_CM_BGR8_PACKED;

        nRet = is_SetColorMode(hCam,colorMode);
        printf("Status SetColorMode %d\n",nRet);

        UINT formatID = 4;
        //Bildgröße einstellen -> 2592x1944
        nRet = is_ImageFormat(hCam, IMGFRMT_CMD_SET_FORMAT, &formatID, 4);
        printf("Status ImageFormat %d\n",nRet);

        //Speicher für Bild alloziieren
        char* pMem = NULL;
        int memID = 0;
        nRet = is_AllocImageMem(hCam, 1280, 1024, 24, &pMem, &memID);
        printf("Status AllocImage %d\n",nRet);

        //diesen Speicher aktiv setzen
        nRet = is_SetImageMem(hCam, pMem, memID);
        printf("Status SetImageMem %d\n",nRet);

        //Bilder im Kameraspeicher belassen
        INT displayMode = IS_SET_DM_DIB;
        nRet = is_SetDisplayMode (hCam, displayMode);
        printf("Status displayMode %d\n",nRet);

        //Bild aufnehmen
        nRet = is_FreezeVideo(hCam, IS_WAIT);
        printf("Status is_FreezeVideo %d\n",nRet);

        //Bild aus dem Speicher auslesen und als Datei speichern
        String path = "./calib_en/snap_BGR"+conv.str()+".png";
        std::wstring widepath;
        for(int i = 0; i < path.length(); ++i)
          widepath += wchar_t (path[i] );

        IMAGE_FILE_PARAMS ImageFileParams;
        ImageFileParams.pwchFileName = &widepath[0];
        ImageFileParams.pnImageID = NULL;
        ImageFileParams.ppcImageMem = NULL;
        ImageFileParams.nQuality = 0;
        ImageFileParams.nFileType = IS_IMG_PNG;

        nRet = is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, (void*) &ImageFileParams, sizeof(ImageFileParams));
        printf("Status is_ImageFile %d\n",nRet);

        //Kamera wieder freigeben
        is_ExitCamera(hCam);
        cout<<"To quit capturing calibration images, choose q. Else, choose any other letter."<<endl;
        cin >> flag;
        i++;
    }
}
Пример #5
0
// Create the specified control, optionally providing properties to initialise
// it with and a name.
HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl,
    LPCWSTR szCodebase, IBindCtx *pBindContext)
{
    TRACE_METHOD(CControlSite::Create);

    m_CLSID = clsid;
    m_ParameterList = pl;

    // See if security policy will allow the control to be hosted
    if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid))
    {
        return E_FAIL;
    }

    // See if object is script safe
    BOOL checkForObjectSafety = FALSE;
    if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly)
    {
        BOOL bClassExists = FALSE;
        BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
        if (!bClassExists && szCodebase)
        {
            // Class doesn't exist, so allow code below to fetch it
        }
        else if (!bIsSafe)
        {
            // The class is not flagged as safe for scripting, so
            // we'll have to create it to ask it if its safe.
            checkForObjectSafety = TRUE;
        }
    }

    // Create the object
    CComPtr<IUnknown> spObject;
    HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
    if (SUCCEEDED(hr) && checkForObjectSafety)
    {
        // Assume scripting via IDispatch
        if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)))
        {
            return E_FAIL;
        }
        // Drop through, success!
    }

    // Do we need to download the control?
    if (FAILED(hr) && szCodebase)
    {
        wchar_t *szURL = NULL;

        // Test if the code base ends in #version=a,b,c,d
        DWORD dwFileVersionMS = 0xffffffff;
        DWORD dwFileVersionLS = 0xffffffff;
        const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#'));
        if (szHash)
        {
            if (wcsnicmp(szHash, L"#version=", 9) == 0)
            {
                int a, b, c, d;
                if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4)
                {
                    dwFileVersionMS = MAKELONG(b,a);
                    dwFileVersionLS = MAKELONG(d,c);
                }
            }
            szURL = _wcsdup(szCodebase);
            // Terminate at the hash mark
            if (szURL)
                szURL[szHash - szCodebase] = wchar_t('\0');
        }
        else
        {
            szURL = _wcsdup(szCodebase);
        }
        if (!szURL)
            return E_OUTOFMEMORY;

        CComPtr<IBindCtx> spBindContext; 
        CComPtr<IBindStatusCallback> spBindStatusCallback;
        CComPtr<IBindStatusCallback> spOldBSC;

        // Create our own bind context or use the one provided?
        BOOL useInternalBSC = FALSE;
        if (!pBindContext)
        {
            useInternalBSC = TRUE;
            hr = CreateBindCtx(0, &spBindContext);
            if (FAILED(hr))
            {
                free(szURL);
                return hr;
            }
            spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this);
            hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0);
            if (FAILED(hr))
            {
                free(szURL);
                return hr;
            }
        }
        else
        {
            spBindContext = pBindContext;
        }

        hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS,
            NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown, (void **) &m_spObject);
        
        free(szURL);
        
        // Handle the internal binding synchronously so the object exists
        // or an error code is available when the method returns.
        if (useInternalBSC)
        {
            if (MK_S_ASYNCHRONOUS == hr)
            {
                m_bBindingInProgress = TRUE;
                m_hrBindResult = E_FAIL;

                // Spin around waiting for binding to complete
                HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
                while (m_bBindingInProgress)
                {
                    MSG msg;
                    // Process pending messages
                    while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
                    {
                        if (!::GetMessage(&msg, NULL, 0, 0))
                        {
                            m_bBindingInProgress = FALSE;
                            break;
                        }
                        ::TranslateMessage(&msg);
                        ::DispatchMessage(&msg);
                    }
                    if (!m_bBindingInProgress)
                        break;
                    // Sleep for a bit or the next msg to appear
                    ::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS);
                }
                ::CloseHandle(hFakeEvent);

                // Set the result
                hr = m_hrBindResult;
            }

            // Destroy the bind status callback & context
            if (spBindStatusCallback)
            {
                RevokeBindStatusCallback(spBindContext, spBindStatusCallback);
                spBindContext.Release();
            }
        }
    }

    if (spObject)
        m_spObject = spObject;

    return hr;
}
Пример #6
0
  HexState operator() (const char*& Ptr, llvm::raw_ostream& Stream,
                       bool ForceHex) {
    // Block allocate the next chunk
    if (!(m_Buf.size() % kBufSize))
      m_Buf.reserve(m_Buf.size() + kBufSize);

    HexState State = kText;
    const char* const Start = Ptr;
    char32_t Char;
    if (m_Utf8) {
      Char = utf8::next(Ptr);
      if (Ptr > m_End) {
        // Invalid/bad encoding: dump the remaining as hex
        Ptr = Start;
        while (Ptr < m_End)
          Stream << "\\x" << llvm::format_hex_no_prefix(uint8_t(*Ptr++), 2);
        m_HexRun = true;
        return kHex;
      }
    } else
      Char = (*Ptr++ & 0xff);

    // Assume more often than not -regular- strings are printed
    if (LLVM_UNLIKELY(!isPrintable(Char, m_Loc))) {
      m_HexRun = false;
      if (LLVM_UNLIKELY(ForceHex || !std::isspace(wchar_t(Char), m_Loc))) {
        if (Char > 0xffff)
          Stream << "\\U" << llvm::format_hex_no_prefix(uint32_t(Char), 8);
        else if (Char > 0xff)
          Stream << "\\u" << llvm::format_hex_no_prefix(uint16_t(Char), 4);
        else if (Char) {
          Stream << "\\x" << llvm::format_hex_no_prefix(uint8_t(Char), 2);
          m_HexRun = true;
          return kHex;
        } else
          Stream << "\\0";
        return kText;
      }

      switch (Char) {
        case '\b': Stream << "\\b"; return kEsc;
        // \r isn't so great on Unix, what about Windows?
        case '\r': Stream << "\\r"; return kEsc;
        default: break;
      }
      State = kEsc;
    }

    if (m_HexRun) {
      // If the last print was a hex code, and this is now a char that could
      // be interpreted as a continuation of that hex-sequence, close out
      // the string and use concatenation. {'\xea', 'B'} -> "\xea" "B"
      m_HexRun = false;
      if (std::isxdigit(wchar_t(Char), m_Loc))
        Stream << "\" \"";
    }
    if (m_Utf8)
      Stream << llvm::StringRef(Start, Ptr-Start);
    else
      Stream << char(Char);
    return State;
  }
Пример #7
0
surface textbox::add_text_line(const wide_string& text, const SDL_Color& color)
{
	line_height_ = font::get_max_height(font_size);

	if(char_y_.empty()) {
		char_y_.push_back(0);
	} else {
		char_y_.push_back(char_y_.back() + line_height_);
	}

	char_x_.push_back(0);

	// Re-calculate the position of each glyph. We approximate this by asking the
	// width of each substring, but this is a flawed assumption which won't work with
	// some more complex scripts (that is, RTL languages). This part of the work should
	// actually be done by the font-rendering system.
	std::string visible_string;
	wide_string wrapped_text;

	wide_string::const_iterator backup_itor = text.end();

	wide_string::const_iterator itor = text.begin();
	while(itor != text.end()) {
		//If this is a space, save copies of the current state so we can roll back
		if(char(*itor) == ' ') {
			backup_itor = itor;
		}
		visible_string.append(utils::wchar_to_string(*itor));

		if(char(*itor) == '\n') {
			backup_itor = text.end();
			visible_string = "";
		}

		int w = font::line_width(visible_string, font_size);

		if(wrap_ && w >= inner_location().w) {
			if(backup_itor != text.end()) {
				int backup = itor - backup_itor;
				itor = backup_itor + 1;
				if(backup > 0) {
					char_x_.erase(char_x_.end()-backup, char_x_.end());
					char_y_.erase(char_y_.end()-backup, char_y_.end());
					wrapped_text.erase(wrapped_text.end()-backup, wrapped_text.end());
				}
			}
			backup_itor = text.end();
			wrapped_text.push_back(wchar_t('\n'));
			char_x_.push_back(0);
			char_y_.push_back(char_y_.back() + line_height_);
			visible_string = "";
		} else {
			wrapped_text.push_back(*itor);
			char_x_.push_back(w);
			char_y_.push_back(char_y_.back() + (char(*itor) == '\n' ? line_height_ : 0));
			++itor;
		}
	}

	const std::string s = utils::wstring_to_string(wrapped_text);
	const surface res(font::get_rendered_text(s, font_size, color));

	return res;
}
Пример #8
0
void TestUTF8 (void)
{
    cout << "Generating Unicode characters ";
    vector<wchar_t> srcChars;
    srcChars.resize (0xFFFF);
    iota (srcChars.begin(), srcChars.end(), 0);
    cout << size_t(srcChars[0]) << " - " << size_t(srcChars.back()) << endl;

    cout << "Encoding to utf8." << endl;
    string encoded;
    encoded.reserve (srcChars.size() * 4);
    copy (srcChars, utf8out (back_inserter(encoded)));
    const char c_ProperEncoding[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    if (encoded.compare (encoded.begin(), encoded.begin() + VectorSize(c_ProperEncoding), VectorRange(c_ProperEncoding))) {
	cout << "Encoding failed: ";
	for (string::const_iterator i = encoded.begin(); i != encoded.begin() + VectorSize(c_ProperEncoding); ++ i)
	    cout << uint32_t(*i);
	cout << endl;
    }

    cout << "Decoding back." << endl;
    vector<wchar_t> decChars;
    assert( decChars.size() == 0 );
    Widen (encoded, decChars);

    cout << "Comparing." << endl;
    cout << "src = " << srcChars.size();
    cout << " chars, encoded = " << encoded.size();
    cout << " chars, decoded = " << decChars.size() << endl;
    size_t nDiffs = 0;
    for (uoff_t i = 0; i < min (srcChars.size(), decChars.size()); ++ i) {
	if (srcChars[i] != decChars[i]) {
	    cout << uint32_t(srcChars[i]) << " != " << uint32_t(decChars[i]) << endl;
	    ++ nDiffs;
	}
    }
    cout << nDiffs << " differences between src and decoded." << endl;

    cout << "Testing wide character string::insert" << endl;
    string ws ("1234567890", 10);

    ws.insert (0, wchar_t(1234));
    ws.insert (3, wchar_t(2345));
    const wchar_t c_WChars[2] = { 3456, 4567 };
    ws.insert (3, VectorRange(c_WChars), 2);
    ws.insert (ws.utf_length(), wchar_t(5678));
    cout << "Values[" << ws.utf_length() << "]:";
    for (string::utf8_iterator j = ws.utf8_begin(); j < ws.utf8_end(); ++ j)
	cout << ' ' << (uint32_t) *j;
    cout << endl;

    cout << "Character offsets:";
    for (string::utf8_iterator k = ws.utf8_begin(); k < ws.utf8_end(); ++ k)
	cout << ' ' << distance (ws.begin(), k.base());
    cout << endl;

    cout << "Erasing character " << ws.utf_length() - 1 << ": ";
    ws.erase (ws.utf_length() - 1);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;

    cout << "Erasing characters 3-5: ";
    ws.erase (3, 2);
    Widen (ws, decChars);
    DumpWchars (decChars);
    cout << endl;
}
Пример #9
0
//! Breaks the single text line.
void StaticText::breakText()
{
	if (!WordWrap)
		return;

	BrokenText.clear();

	IGUISkin* skin = Environment->getSkin();
	IGUIFont* font = getActiveFont();
	if (!font)
		return;

	LastBreakFont = font;

	EnrichedString line;
	EnrichedString word;
	EnrichedString whitespace;
	s32 size = cText.size();
	s32 length = 0;
	s32 elWidth = RelativeRect.getWidth();
	if (Border)
		elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X);
	wchar_t c;

	//std::vector<irr::video::SColor> colors;

	// We have to deal with right-to-left and left-to-right differently
	// However, most parts of the following code is the same, it's just
	// some order and boundaries which change.
	if (!RightToLeft)
	{
		// regular (left-to-right)
		for (s32 i=0; i<size; ++i)
		{
			c = cText.getString()[i];
			bool lineBreak = false;

			if (c == L'\r') // Mac or Windows breaks
			{
				lineBreak = true;
				//if (Text[i+1] == L'\n') // Windows breaks
				//{
				//	Text.erase(i+1);
				//	--size;
				//}
				c = '\0';
			}
			else if (c == L'\n') // Unix breaks
			{
				lineBreak = true;
				c = '\0';
			}

			bool isWhitespace = (c == L' ' || c == 0);
			if ( !isWhitespace )
			{
				// part of a word
				//word += c;
				word.addChar(cText, i);
			}

			if ( isWhitespace || i == (size-1))
			{
				if (word.size())
				{
					// here comes the next whitespace, look if
					// we must break the last word to the next line.
					const s32 whitelgth = font->getDimension(whitespace.c_str()).Width;
					//const std::wstring sanitized = removeEscapes(word.c_str());
					const s32 wordlgth = font->getDimension(word.c_str()).Width;

					if (wordlgth > elWidth)
					{
						// This word is too long to fit in the available space, look for
						// the Unicode Soft HYphen (SHY / 00AD) character for a place to
						// break the word at
						int where = core::stringw(word.c_str()).findFirst( wchar_t(0x00AD) );
						if (where != -1)
						{
							EnrichedString first = word.substr(0, where);
							EnrichedString second = word.substr(where, word.size() - where);
							first.addCharNoColor(L'-');
							BrokenText.push_back(line + first);
							const s32 secondLength = font->getDimension(second.c_str()).Width;

							length = secondLength;
							line = second;
						}
						else
						{
							// No soft hyphen found, so there's nothing more we can do
							// break to next line
							if (length)
								BrokenText.push_back(line);
							length = wordlgth;
							line = word;
						}
					}
					else if (length && (length + wordlgth + whitelgth > elWidth))
					{
						// break to next line
						BrokenText.push_back(line);
						length = wordlgth;
						line = word;
					}
					else
					{
						// add word to line
						line += whitespace;
						line += word;
						length += whitelgth + wordlgth;
					}

					word.clear();
					whitespace.clear();
				}

				if ( isWhitespace && c != 0)
				{
					whitespace.addChar(cText, i);
				}

				// compute line break
				if (lineBreak)
				{
					line += whitespace;
					line += word;
					BrokenText.push_back(line);
					line.clear();
					word.clear();
					whitespace.clear();
					length = 0;
				}
			}
		}

		line += whitespace;
		line += word;
		BrokenText.push_back(line);
	}
	else
	{
		// right-to-left
		for (s32 i=size; i>=0; --i)
		{
			c = cText.getString()[i];
			bool lineBreak = false;

			if (c == L'\r') // Mac or Windows breaks
			{
				lineBreak = true;
				//if ((i>0) && Text[i-1] == L'\n') // Windows breaks
				//{
				//	Text.erase(i-1);
				//	--size;
				//}
				c = '\0';
			}
			else if (c == L'\n') // Unix breaks
			{
				lineBreak = true;
				c = '\0';
			}

			if (c==L' ' || c==0 || i==0)
			{
				if (word.size())
				{
					// here comes the next whitespace, look if
					// we must break the last word to the next line.
					const s32 whitelgth = font->getDimension(whitespace.c_str()).Width;
					const s32 wordlgth = font->getDimension(word.c_str()).Width;

					if (length && (length + wordlgth + whitelgth > elWidth))
					{
						// break to next line
						BrokenText.push_back(line);
						length = wordlgth;
						line = word;
					}
					else
					{
						// add word to line
						line = whitespace + line;
						line = word + line;
						length += whitelgth + wordlgth;
					}

					word.clear();
					whitespace.clear();
				}

				if (c != 0)
				//	whitespace = core::stringw(&c, 1) + whitespace;
				whitespace = cText.substr(i, 1) + whitespace;

				// compute line break
				if (lineBreak)
				{
					line = whitespace + line;
					line = word + line;
					BrokenText.push_back(line);
					line.clear();
					word.clear();
					whitespace.clear();
					length = 0;
				}
			}
			else
			{
				// yippee this is a word..
				//word = core::stringw(&c, 1) + word;
				word = cText.substr(i, 1) + word;
			}
		}

		line = whitespace + line;
		line = word + line;
		BrokenText.push_back(line);
	}
}
Пример #10
0
//-----------------------------------------------------------------------------
int mglParser::ParseDef(std::wstring &str)
{
	if(!skip() && !str.compare(0,3,L"def") && (str[6]==' ' || str[6]=='\t'))
	{
		int res = 1;	mreal d;
		PutArg(str,true);
		const std::wstring s = mgl_trim_ws(str.substr(7));
		if(!str.compare(3,3,L"ine"))
		{
			int nn = s[1]<='9' ? s[1]-'0' : (s[1]>='a' ? s[1]-'a'+10:-1);
			if(s[0]=='$' && nn>=0 && nn<='z'-'a'+10)
			{
				AddParam(nn, mgl_trim_ws(s.substr(2)).c_str());	return 1;
			}
		}
		if(!str.compare(3,3,L"num"))
		{
			int nn = s[1]<='9' ? s[1]-'0' : (s[1]>='a' ? s[1]-'a'+10:-1);
			if(s[0]=='$' && nn>=0 && nn<='z'-'a'+10)
			{
				res = 0;
				HMDT dd = mglFormulaCalc(mgl_trim_ws(s.substr(2)), this, DataList);
				d = dd->a[0];	delete dd;
				char buf[32];	snprintf(buf,32,"%g",d);
				buf[31] = 0;	AddParam(nn, buf);
			}
			return res+1;
		}
		if(!str.compare(3,3,L"chr"))
		{
			int nn = s[1]<='9' ? s[1]-'0' : (s[1]>='a' ? s[1]-'a'+10:-1);
			if(s[0]=='$' && nn>=0 && nn<='z'-'a'+10)
			{
				res = 0;
				HMDT dd = mglFormulaCalc(mgl_trim_ws(s.substr(2)), this, DataList);
				d=dd->a[0];	delete dd;
				wchar_t buf[2]={0,0};	buf[0] = wchar_t(d);	AddParam(nn, buf);
			}
			return res+1;
		}
	}
	if(!skip() && !str.compare(0,3,L"ask") && (str[3]==' ' || str[3]=='\t'))
	{
		PutArg(str,true);
		std::wstring s = mgl_trim_ws(str.substr(4));
		int nn = s[1]<='9' ? s[1]-'0' : (s[1]>='a' ? s[1]-'a'+10:-1);
		if(s[0]=='$' && nn>=0 && nn<='z'-'a'+10)
		{
			s = mgl_trim_ws(s.substr(2));
			if(s[0]=='\'')	s=s.substr(1,s.length()-2);
			if(mgl_ask_func)
			{
				static wchar_t res[1024];
				mgl_ask_func(s.c_str(),res);
				if(*res)	AddParam(nn, res);
			}
			return mgl_ask_func?1:2;
		}
		else	return 2;
	}
	if(!skip() && !str.compare(0,3,L"for") && (str[3]==' ' || str[3]=='\t'))
	{
		size_t i;
		for(i=4;str[i]<=' ';i++);
		// if command have format 'for $N ...' then change it to 'for N ...'
		if(str[i]=='$' && str[i+1]>='0' && str[i+1]<='9')	str[i] = ' ';
		if(str[i]=='$' && str[i+1]>='a' && str[i+1]<='z')	str[i] = ' ';
	}
	return 0;
}
Пример #11
0
// RUN: %clang_cc1 -triple i386-mingw32 -fsyntax-only -pedantic -verify %s
// RUN: %clang_cc1 -fshort-wchar -fsyntax-only -pedantic -verify %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -pedantic -verify %s
// expected-no-diagnostics

// Check that short wchar_t is unsigned, and that regular wchar_t is not.
int test[(wchar_t(-1)<wchar_t(0)) == (sizeof(wchar_t) == 4) ?1:-1];
Пример #12
0
void gdbmiStringFormat::format(std::ostream &str) const
{
    const std::string::size_type size = m_s.size();
    for (std::string::size_type i = 0; i < size; ++i)
        formatGdbmiChar(str, wchar_t(m_s.at(i)));
}
Пример #13
0
bool open_object(const std::string& path_or_url)
{
#if defined(_X11) || defined(__APPLE__)

#ifndef __APPLE__
	LOG_DU << "open_object(): on X11, will use xdg-open\n";
	const char launcher[] = "xdg-open";
#else
	LOG_DU << "open_object(): on OS X, will use open\n";
	const char launcher[] = "open";
#endif

	int child_status = 0;
	const pid_t child = fork();

	if(child == -1) {
		ERR_DU << "open_object(): fork() failed\n";
		return false;
	} else if(child == 0) {
		execlp(launcher, launcher, path_or_url.c_str(), reinterpret_cast<char*>(NULL));
		_exit(1); // This shouldn't happen.
	} else if(waitpid(child, &child_status, 0) == -1) {
		ERR_DU << "open_object(): waitpid() failed\n";
		return false;
	}

	if(child_status) {
		if(WIFEXITED(child_status)) {
			ERR_DU << "open_object(): " << launcher << " returned "
			       << WEXITSTATUS(child_status) << '\n';
		} else {
			ERR_DU << "open_object(): " << launcher << " failed\n";
		}

		return false;
	}

	return true;

#elif defined(_WIN32)

	LOG_DU << "open_object(): on Win32, will use ShellExecute()\n";

	utf16::string u16path = unicode_cast<utf16::string>(path_or_url);
	u16path.push_back(wchar_t(0)); // Make wpath NULL-terminated

	const ptrdiff_t res = reinterpret_cast<ptrdiff_t>(ShellExecute(NULL, L"open", &u16path.front(), NULL, NULL, SW_SHOW));
	if(res <= 32) {
		ERR_DU << "open_object(): ShellExecute() failed (" << res << ")\n";
		return false;
	}

	return true;

#else

	(void)(path_or_url); // silence gcc's -Wunused-parameter
	ERR_DU << "open_object(): unsupported platform\n";
	return false;

#endif
}
Пример #14
0
bool JsonSerializer::input(String &str)
{
	const String fieldDelimiters = ",:]}";
	
	str.clear();
	
	char chr;
	if(!mStream->get(chr)) return false;
	while(Stream::BlankCharacters.contains(chr))
		if(!mStream->get(chr)) return false;
	
	if(fieldDelimiters.contains(chr))
	{
		if(chr == '}' || chr == ']')
		{
			do {
				if(!mStream->get(chr)) 
					return false;
			}
			while(Stream::BlankCharacters.contains(chr));
		}
		return false;
	}
		
	// Special case: read map or array in string
	if(chr == '{' || chr == '[')
	{
		char opening = chr;
		char closing;
		if(opening ==  '{') closing = '}';
		else closing = ']';
		
		int count = 1;
		str+= chr;
		while(count)
		{
			AssertIO(mStream->get(chr));
			str+= chr;
			
			if(chr == opening) ++count;
			else if(chr == closing) --count;
		}
		
		do {
			if(!mStream->get(chr)) 
				return true;
		}
		while(Stream::BlankCharacters.contains(chr));
		
		AssertIO(fieldDelimiters.contains(chr));
		return true;
	}
		
	bool quotes = (chr == '\'' || chr == '\"');
	
	String delimiters;
	if(quotes)
	{
		delimiters = String(chr);
		AssertIO(mStream->get(chr));
	}
	else {
		str+= chr;
		delimiters = Stream::BlankCharacters;
		delimiters+=fieldDelimiters;
		if(!mStream->get(chr)) return true;
	}

	while(!delimiters.contains(chr))
	{
		if(chr == '\\')
		{
			AssertIO(mStream->get(chr));
			switch(chr)
			{
			case 'b': 	chr = '\b';	break;
			case 'f': 	chr = '\f';	break;
			case 'n': 	chr = '\n';	break;
			case 'r': 	chr = '\r';	break;
			case 't': 	chr = '\t';	break;
			case 'u':
			{
				String tmp;
				AssertIO(mStream->read(tmp, 4));
				
				unsigned u = 0;
				tmp.hexaMode(true);
				tmp >> u;

				wchar_t wstr[2];
				wstr[0] = wchar_t(u);
				wstr[1] = 0;
				
				str+= String(wstr);
				chr = 0;
				break;
			}
			default: 
				if(isalpha(chr) || isdigit(chr)) 
					chr = 0; // unknown escape sequence
				break;
			}
		}

		if(chr) str+= chr;
		if(!mStream->get(chr))
		{
			if(quotes) throw IOException();
			else break;
		}
	}
Пример #15
0
void Font::LoadFontPageSettings( FontPageSettings &cfg, IniFile &ini, const CString &sTexturePath, const CString &sPageName, CString sChars )
{
	cfg.m_sTexturePath = sTexturePath;

	/* If we have any characters to map, add them. */
	for( unsigned n=0; n<sChars.size(); n++ )
	{
		char c = sChars[n];
		cfg.CharToGlyphNo[c] = n;
	}
	int iNumFramesWide, iNumFramesHigh;
	RageTexture::GetFrameDimensionsFromFileName( sTexturePath, &iNumFramesWide, &iNumFramesHigh );
	int iNumFrames = iNumFramesWide * iNumFramesHigh;
	
	ini.RenameKey("Char Widths", "main");

//	LOG->Trace("Loading font page '%s' settings from page name '%s'",
//		TexturePath.c_str(), sPageName.c_str());
	
	ini.GetValue( sPageName, "DrawExtraPixelsLeft", cfg.m_iDrawExtraPixelsLeft );
	ini.GetValue( sPageName, "DrawExtraPixelsRight", cfg.m_iDrawExtraPixelsRight );
	ini.GetValue( sPageName, "AddToAllWidths", cfg.m_iAddToAllWidths );
	ini.GetValue( sPageName, "ScaleAllWidthsBy", cfg.m_fScaleAllWidthsBy );
	ini.GetValue( sPageName, "LineSpacing", cfg.m_iLineSpacing );
	ini.GetValue( sPageName, "Top", cfg.m_iTop );
	ini.GetValue( sPageName, "Baseline", cfg.m_iBaseline );
	ini.GetValue( sPageName, "DefaultWidth", cfg.m_iDefaultWidth );
	ini.GetValue( sPageName, "AdvanceExtraPixels", cfg.m_iAdvanceExtraPixels );
	ini.GetValue( sPageName, "TextureHints", cfg.m_sTextureHints );

	/* Iterate over all keys. */
	const XNode* pNode = ini.GetChild( sPageName );
	if( pNode )
	{
		FOREACH_CONST_Attr( pNode, pAttr )
		{
			CString sName = pAttr->m_sName;
			const CString &sValue = pAttr->m_sValue;

			sName.MakeUpper();

			/* If val is an integer, it's a width, eg. "10=27". */
			if( IsAnInt(sName) )
			{
				cfg.m_mapGlyphWidths[atoi(sName)] = atoi( sValue );
				continue;
			}

			/* "map codepoint=frame" maps a char to a frame. */
			if( sName.substr(0, 4) == "MAP " )
			{
				/*
				 * map CODEPOINT=frame. CODEPOINT can be
				 * 1. U+hexval
				 * 2. an alias ("oq")
				 * 3. a game type followed by a game alias, eg "pump menuleft"
				 * 4. a character in quotes ("X")
				 *
				 * map 1=2 is the same as
				 * range unicode #1-1=2
				 */
				CString sCodepoint = sName.substr(4); /* "CODEPOINT" */
			
				const Game* pGame = NULL;

				if( sCodepoint.find_first_of(' ') != sCodepoint.npos )
				{
					/* There's a space; the first word should be a game type. Split it. */
					unsigned pos = sCodepoint.find_first_of( ' ' );
					CString gamename = sCodepoint.substr( 0, pos );
					sCodepoint = sCodepoint.substr( pos+1 );

					pGame = GameManager::StringToGameType(gamename);

					if( pGame == NULL )
					{
						LOG->Warn( "Font definition '%s' uses unknown game type '%s'",
							ini.GetPath().c_str(), gamename.c_str() );
						continue;
					}
				}

				wchar_t c;
				if( sCodepoint.substr(0, 2) == "U+" && IsHexVal(sCodepoint.substr(2)) )
					sscanf( sCodepoint.substr(2).c_str(), "%x", &c );
				else if( sCodepoint.size() > 0 &&
						utf8_get_char_len(sCodepoint[0]) == int(sCodepoint.size()) )
				{
					c = utf8_get_char( sCodepoint.c_str() );
					if(c == wchar_t(-1))
						LOG->Warn("Font definition '%s' has an invalid value '%s'.",
							ini.GetPath().c_str(), sName.c_str() );
				}
				else if( !FontCharAliases::GetChar(sCodepoint, c) )
				{
					LOG->Warn("Font definition '%s' has an invalid value '%s'.",
						ini.GetPath().c_str(), sName.c_str() );
					continue;
				}

				cfg.CharToGlyphNo[c] = atoi( sValue );

				continue;
			}

			if( sName.substr(0, 6) == "RANGE " )
			{
				/*
				 * range CODESET=first_frame or
				 * range CODESET #start-end=first_frame
				 * eg
				 * range CP1252=0       (default for 256-frame fonts)
				 * range ASCII=0        (default for 128-frame fonts)
				 *
				 * (Start and end are in hex.)
				 *
				 * Map two high-bit portions of ISO-8859- to one font:
				 * range ISO-8859-2 #80-FF=0
				 * range ISO-8859-3 #80-FF=128
				 *
				 * Map hiragana to 0-84:
				 * range Unicode #3041-3094=0
				 */
				vector<CString> asMatches;
				static Regex parse("^RANGE ([A-Z\\-]+)( ?#([0-9A-F]+)-([0-9A-F]+))?$");
				bool bMatch = parse.Compare( sName, asMatches );
				
				ASSERT( asMatches.size() == 4 ); /* 4 parens */

				if( !bMatch || asMatches[0].empty() )
					RageException::Throw("Font definition '%s' has an invalid range '%s': parse error",
						ini.GetPath().c_str(), sName.c_str() );
				
				/* We must have either 1 match (just the codeset) or 4 (the whole thing). */

				int iCount = -1;
				int iFirst = 0;
				if( !asMatches[2].empty() )
				{
					sscanf( asMatches[2].c_str(), "%x", &iFirst );
					int iLast;
					sscanf( asMatches[3].c_str(), "%x", &iLast );
					if( iLast < iFirst )
						RageException::Throw("Font definition '%s' has an invalid range '%s': %i < %i.",
							ini.GetPath().c_str(), sName.c_str(), iLast < iFirst );

					iCount = iLast - iFirst + 1;
				}

				CString sRet = cfg.MapRange( asMatches[0], iFirst, atoi(sValue), iCount );
				if( !sRet.empty() )
					RageException::Throw( "Font definition '%s' has an invalid range '%s': %s.",
						ini.GetPath().c_str(), sName.c_str(), sRet.c_str() );

				continue;
			}

			if( sName.substr(0, 5) == "LINE " )
			{
				/* line ROW=CHAR1CHAR2CHAR3CHAR4
				 * eg.
				 * line 0=ABCDEFGH
				 *
				 * This lets us assign characters very compactly and readably. */

				CString sRowStr = sName.substr(5);
				ASSERT( IsAnInt(sRowStr) );
				const int iRow = atoi( sRowStr.c_str() );
				const int iFirstFrame = iRow * iNumFramesWide;

				if( iRow > iNumFramesHigh )
					RageException::Throw( "The font definition \"%s\" tries to assign line %i, but the font is only %i characters high",
						ini.GetPath().c_str(), iFirstFrame, iNumFramesHigh );

				/* Decode the string. */
				const wstring wdata( CStringToWstring(sValue) );

				if( int(wdata.size()) > iNumFramesWide )
					RageException::Throw( "The font definition \"%s\" assigns %i characters to row %i (\"%ls\"), but the font only has %i characters wide",
						ini.GetPath().c_str(), wdata.size(), iRow, wdata.c_str(), iNumFramesWide );

				for( unsigned i = 0; i < wdata.size(); ++i )
					cfg.CharToGlyphNo[wdata[i]] = iFirstFrame+i;
			}
		}
	}
Пример #16
0
UINT pathDepth(LPCWSTR path){
	UINT i = 0;
	for (; path[i]; path[i] == wchar_t('/') ? ++i : (UINT)++path);
	return i;
}
Пример #17
0
std::wstring GetMainPartOfName(std::wstring wname, uint32 declension)
{
    // supported only Cyrillic cases
    if (wname.size() < 1 || !isCyrillicCharacter(wname[0]) || declension > 5)
        return wname;

    // Important: end length must be <= MAX_INTERNAL_PLAYER_NAME-MAX_PLAYER_NAME (3 currently)

    static wchar_t const a_End[]    = { wchar_t(1), wchar_t(0x0430), wchar_t(0x0000)};
    static wchar_t const o_End[]    = { wchar_t(1), wchar_t(0x043E), wchar_t(0x0000)};
    static wchar_t const ya_End[]   = { wchar_t(1), wchar_t(0x044F), wchar_t(0x0000)};
    static wchar_t const ie_End[]   = { wchar_t(1), wchar_t(0x0435), wchar_t(0x0000)};
    static wchar_t const i_End[]    = { wchar_t(1), wchar_t(0x0438), wchar_t(0x0000)};
    static wchar_t const yeru_End[] = { wchar_t(1), wchar_t(0x044B), wchar_t(0x0000)};
    static wchar_t const u_End[]    = { wchar_t(1), wchar_t(0x0443), wchar_t(0x0000)};
    static wchar_t const yu_End[]   = { wchar_t(1), wchar_t(0x044E), wchar_t(0x0000)};
    static wchar_t const oj_End[]   = { wchar_t(2), wchar_t(0x043E), wchar_t(0x0439), wchar_t(0x0000)};
    static wchar_t const ie_j_End[] = { wchar_t(2), wchar_t(0x0435), wchar_t(0x0439), wchar_t(0x0000)};
    static wchar_t const io_j_End[] = { wchar_t(2), wchar_t(0x0451), wchar_t(0x0439), wchar_t(0x0000)};
    static wchar_t const o_m_End[]  = { wchar_t(2), wchar_t(0x043E), wchar_t(0x043C), wchar_t(0x0000)};
    static wchar_t const io_m_End[] = { wchar_t(2), wchar_t(0x0451), wchar_t(0x043C), wchar_t(0x0000)};
    static wchar_t const ie_m_End[] = { wchar_t(2), wchar_t(0x0435), wchar_t(0x043C), wchar_t(0x0000)};
    static wchar_t const soft_End[] = { wchar_t(1), wchar_t(0x044C), wchar_t(0x0000)};
    static wchar_t const j_End[]    = { wchar_t(1), wchar_t(0x0439), wchar_t(0x0000)};

    static wchar_t const* const dropEnds[6][8] =
    {
        { &a_End[1],  &o_End[1],    &ya_End[1],   &ie_End[1],  &soft_End[1], &j_End[1],    NULL,       NULL },
        { &a_End[1],  &ya_End[1],   &yeru_End[1], &i_End[1],   NULL,         NULL,         NULL,       NULL },
        { &ie_End[1], &u_End[1],    &yu_End[1],   &i_End[1],   NULL,         NULL,         NULL,       NULL },
        { &u_End[1],  &yu_End[1],   &o_End[1],    &ie_End[1],  &soft_End[1], &ya_End[1],   &a_End[1],  NULL },
        { &oj_End[1], &io_j_End[1], &ie_j_End[1], &o_m_End[1], &io_m_End[1], &ie_m_End[1], &yu_End[1], NULL },
        { &ie_End[1], &i_End[1],    NULL,         NULL,        NULL,         NULL,         NULL,       NULL }
    };

    for (wchar_t const * const* itr = &dropEnds[declension][0]; *itr; ++itr)
    {
        size_t len = size_t((*itr)[-1]);                    // get length from string size field

        if (wname.substr(wname.size() - len, len) == *itr)
            return wname.substr(0, wname.size() - len);
    }

    return wname;
}
Пример #18
0
int main(int, char**) {
    int failed = 0;

    // Basic AMQP types
    RUN_TEST(failed, simple_type_test(null()));
    RUN_TEST(failed, simple_type_test(false));
    RUN_TEST(failed, simple_type_test(uint8_t(42)));
    RUN_TEST(failed, simple_type_test(int8_t(-42)));
    RUN_TEST(failed, simple_type_test(uint16_t(4242)));
    RUN_TEST(failed, simple_type_test(int16_t(-4242)));
    RUN_TEST(failed, simple_type_test(uint32_t(4242)));
    RUN_TEST(failed, simple_type_test(int32_t(-4242)));
    RUN_TEST(failed, simple_type_test(uint64_t(4242)));
    RUN_TEST(failed, simple_type_test(int64_t(-4242)));
    RUN_TEST(failed, simple_type_test(wchar_t('X')));
    RUN_TEST(failed, simple_type_test(float(1.234)));
    RUN_TEST(failed, simple_type_test(double(11.2233)));
    RUN_TEST(failed, simple_type_test(timestamp(1234)));
    RUN_TEST(failed, simple_type_test(make_fill<decimal32>(0)));
    RUN_TEST(failed, simple_type_test(make_fill<decimal64>(0)));
    RUN_TEST(failed, simple_type_test(make_fill<decimal128>(0)));
    RUN_TEST(failed, simple_type_test(uuid::copy("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff")));
    RUN_TEST(failed, simple_type_test(std::string("xxx")));
    RUN_TEST(failed, simple_type_test(symbol("aaa")));
    RUN_TEST(failed, simple_type_test(binary("aaa")));

    // Native int type that may map differently per platform to uint types.
    RUN_TEST(failed, simple_type_test(char(42)));
    RUN_TEST(failed, simple_type_test(short(42)));
    RUN_TEST(failed, simple_type_test(int(42)));
    RUN_TEST(failed, simple_type_test(long(42)));

    RUN_TEST(failed, simple_type_test(static_cast<signed char>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<signed short>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<signed int>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<signed long>(42)));

    RUN_TEST(failed, simple_type_test(static_cast<unsigned char>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<unsigned short>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<unsigned int>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<unsigned long>(42)));

#if PN_CPP_HAS_LONG_LONG_TYPE
    RUN_TEST(failed, simple_type_test(static_cast<long long>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<signed long long>(42)));
    RUN_TEST(failed, simple_type_test(static_cast<unsigned long long>(42)));
#endif

    // value and scalar types, more tests in value_test and scalar_test.
    RUN_TEST(failed, simple_type_test(value("foo")));
    RUN_TEST(failed, value v(23); simple_type_test(v));
    RUN_TEST(failed, simple_type_test(scalar(23)));
    RUN_TEST(failed, simple_type_test(annotation_key(42)));
    RUN_TEST(failed, simple_type_test(message_id(42)));

    // Make sure we reject uncodable types
    RUN_TEST(failed, (uncodable_type_test<std::pair<int, float> >()));
    RUN_TEST(failed, (uncodable_type_test<std::pair<scalar, value> >()));
    RUN_TEST(failed, (uncodable_type_test<std::basic_string<wchar_t> >()));
    RUN_TEST(failed, (uncodable_type_test<internal::data>()));
    RUN_TEST(failed, (uncodable_type_test<pn_data_t*>()));

    return failed;
}