Example #1
0
void IO::TrimRight(std::basic_string<charType> & str, const char* chars2remove)
{
	if (!str.empty()) {  	//trim the characters in chars2remove from the right
		std::string::size_type pos = 0;
		if (chars2remove != NULL) {
			pos = str.find_last_not_of(chars2remove);

			if (pos != std::string::npos)
				str.erase(pos+1);
			else
				str.erase( str.begin() , str.end() ); // make empty
		}
		else {       		//trim space
			pos = std::string::npos;
			for (int i = str.size()-1; i >= 0; --i) {
				if (!isspace(str[i])) {
					pos = i;
					break;
				}
			}
			if (pos != std::string::npos) {
				if (pos+1 != str.size())
					str.resize(pos+1);
			}
			else {
				str.clear();
			}
		}
	}
}
Example #2
0
		inline void copy_strtrans(std::basic_string<CharOut, std::char_traits<CharOut>, std::allocator<CharOut>>& out, const Char* in)
		{
			if (!in)
			{
				out.clear();
				return;
			}
			out.assign(_begin(in), _end(in));
		}
Example #3
0
void join(T* arr[], size_t n, T c, std::basic_string<T>& s) {
   s.clear( );

   for (int i = 0; i < n; ++i) {
      if (arr[i] != NULL)
         s += arr[i];
      if (i < n-1)
         s += c;
   }
}
Example #4
0
    void serialize(input_archive & ar, std::basic_string<Char, CharTraits,
        Allocator> & s, unsigned)
    {
        std::uint64_t size = 0;
        ar >> size; //-V128

        s.clear();
        if (s.size() < size)
            s.resize(size);

        load_binary(ar, &s[0], size * sizeof(Char));
    }
Example #5
0
    void serialize(input_archive & ar, std::basic_string<Char, CharTraits,
        Allocator> & s, unsigned)
    {
        typedef std::basic_string<Char, CharTraits, Allocator> string_type;
        typedef typename string_type::size_type size_type;
        size_type size = 0;
        ar >> size; //-V128

        s.clear();
        s.resize(size);

        load_binary(ar, &s[0], size * sizeof(Char));
    }
Example #6
0
    void IO::TrimLeft(std::basic_string<charType> & str, const char* chars2remove)
    {
        if (!str.empty())   //trim the characters in chars2remove from the left
        {
            std::string::size_type pos = 0;
            if (chars2remove != NULL)
            {
                pos = str.find_first_not_of(chars2remove);

                if (pos != std::string::npos)
                    str.erase(0,pos);
                else
                    str.erase( str.begin() , str.end() ); // make empty
            }
            else        //trim space
            {
                pos = std::string::npos;        //pos = -1
                for (size_t i = 0; i < str.size(); ++i)
                {
                    if (!isspace(str[i]))
                    {
                        pos = i;
                        break;
                    }
                }
                if (pos != std::string::npos)
                {
                    if (pos > 0)
                    {
                        size_t length = str.size() - pos;
                        for (size_t i = 0; i < length; ++i) str[i] = str[i+pos];
                        str.resize(length);
                    }
                }
                else
                {
                    str.clear();
                }
            }
        }
    }
Example #7
0
bool utfConvert(
    const std::basic_string<From>& from, std::basic_string<To>& to,
    ConversionResult(*cvtfunc)(const typename FromTrait::ArgType**, const typename FromTrait::ArgType*,
        typename ToTrait::ArgType**, typename ToTrait::ArgType*,
        ConversionFlags)
    )
{
    static_assert(sizeof(From) == sizeof(typename FromTrait::ArgType), "Error size mismatched");
    static_assert(sizeof(To) == sizeof(typename ToTrait::ArgType), "Error size mismatched");

    if (from.empty())
    {
        to.clear();
        return true;
    }

    // See: http://unicode.org/faq/utf_bom.html#gen6
    static const int most_bytes_per_character = 4;

    const size_t maxNumberOfChars = from.length(); // all UTFs at most one element represents one character.
    const size_t numberOfOut = maxNumberOfChars * most_bytes_per_character / sizeof(To);

    std::basic_string<To> working(numberOfOut, 0);

    auto inbeg = reinterpret_cast<const typename FromTrait::ArgType*>(&from[0]);
    auto inend = inbeg + from.length();


    auto outbeg = reinterpret_cast<typename ToTrait::ArgType*>(&working[0]);
    auto outend = outbeg + working.length();
    auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion);
    if (r != conversionOK)
        return false;

    working.resize(reinterpret_cast<To*>(outbeg) - &working[0]);
    to = std::move(working);

    return true;
};
Example #8
0
bool enum_file_lines::GetTString(std::vector<T>& From, std::basic_string<T>& To, eol::type& Eol, bool bBigEndian) const
{
	To.clear();

	// Обработка ситуации, когда у нас пришёл двойной \r\r, а потом не было \n.
	// В этом случаем считаем \r\r двумя MAC окончаниями строк.
	if (m_CrCr)
	{
		m_CrCr = false;
		Eol = eol::type::mac;
		return true;
	}

	auto CurrentEol = eol::type::none;
	for (const auto* ReadBufPtr = ReadPos < ReadSize? From.data() + ReadPos / sizeof(T) : nullptr; ; ++ReadBufPtr, ReadPos += sizeof(T))
	{
		if (ReadPos >= ReadSize)
		{
			if (!(SrcFile.Read(From.data(), ReadBufCount * sizeof(T), ReadSize) && ReadSize))
			{
				Eol = CurrentEol;
				return !To.empty() || CurrentEol != eol::type::none;
			}

			if (bBigEndian && sizeof(T) != 1)
			{
				swap_bytes(From.data(), From.data(), ReadSize);
			}

			ReadPos = 0;
			ReadBufPtr = From.data();
		}

		if (CurrentEol == eol::type::none)
		{
			// UNIX
			if (*ReadBufPtr == m_Eol.lf<T>())
			{
				CurrentEol = eol::type::unix;
				continue;
			}
			// MAC / Windows? / Notepad?
			else if (*ReadBufPtr == m_Eol.cr<T>())
			{
				CurrentEol = eol::type::mac;
				continue;
			}
		}
		else if (CurrentEol == eol::type::mac)
		{
			if (m_CrSeen)
			{
				m_CrSeen = false;

				// Notepad
				if (*ReadBufPtr == m_Eol.lf<T>())
				{
					CurrentEol = eol::type::bad_win;
					continue;
				}
				else
				{
					// Пришёл \r\r, а \n не пришёл, поэтому считаем \r\r двумя MAC окончаниями строк
					m_CrCr = true;
					break;
				}
			}
			else
			{
				// Windows
				if (*ReadBufPtr == m_Eol.lf<T>())
				{
					CurrentEol = eol::type::win;
					continue;
				}
				// Notepad or two MACs?
				else if (*ReadBufPtr == m_Eol.cr<T>())
				{
					m_CrSeen = true;
					continue;
				}
				else
				{
					break;
				}
			}
		}
		else
		{
			break;
		}

		To.push_back(*ReadBufPtr);
		CurrentEol = eol::type::none;
	}

	Eol = CurrentEol;
	return true;
}
Example #9
0
BOOL LastFMServices::HandShake(std::basic_string<TCHAR>& sessionID, 
							   std::basic_string<TCHAR>& nowPlayingURL, 
							   std::basic_string<TCHAR>& submissionURL)
{
	sessionID.clear();
	nowPlayingURL.clear();
	submissionURL.clear();
	if (m_username.empty() || m_MD5password.empty())
	{
		//TRACE(_T("@4 LastFMServices::HandShake. Empty Authorization.\r\n"));
		m_error = ERR_BadAuth;
		return FALSE;
	}
	SYSTEMTIME st;
	GetSystemTime(&st);
	UINT ts = SystemTime2UnixTimeStamp(st);
	LPCTSTR auth = _T("auth");
	cMD5 md5;
	CHAR authStr[100];
	_snprintf(authStr, 100, "%s%u", (LPCSTR)CT2CA(m_MD5password.c_str()), ts);


	//http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=<client-id>&v=<client-ver>&u=<user>&t=<timestamp>&a=<auth>
	TCHAR url[2000];
	_sntprintf(url, 2000, 
		_T("http://post.audioscrobbler.com/?hs=true&p=%s&c=%s&v=%s&u=%s&t=%u&a=%.32s"),
		sProtocolVer,
		sClientID,
		sClientVer,
		m_username.c_str(),
		ts,
		(LPCTSTR)CA2CT(_strlwr(md5.CalcMD5FromString(authStr))));

	TRACE(_T("About to request: '%s'\r\n"), url);
	m_state = ST_Connecting;

	std::string page;
	if (DownloadWebPage(page, m_hNet, url))
	{
		std::string delimiter = "\n";
		std::string line;
		INT pos = getToken(page, 0, delimiter, line);
		INT count = 0;
		while (pos != -1)
		{
			switch (count)
			{
			case 0:
				m_errorString = line;
				if (line == "OK")
					m_error = ERR_None;
				else if (line == "BANNED")
					m_error = ERR_Banned;
				else if (line == "BADAUTH")
					m_error = ERR_BadAuth;
				else if (line == "BADTIME")
					m_error = ERR_BadTime;
				else 
					m_error = ERR_Failed;
				break;
			case 1:
				sessionID = (LPCTSTR)CA2CT(line.c_str());
				break;
			case 2:
				nowPlayingURL = (LPCTSTR)CA2CT(line.c_str());
				break;
			case 3:
				submissionURL = (LPCTSTR)CA2CT(line.c_str());
				break;
			default:
				break;
			}
			if (m_error != ERR_None)
				break;
			count++;
			pos = getToken(page, pos, delimiter, line);
		}
		if (m_error == ERR_None)
		{
			TRACE(_T("@4 LastFMServices::HandShake. success.\r\n"));
			m_state = ST_Idle;
		}
		else
		{
			TRACE(_T("@4 LastFMServices::HandShake. fail: '%s'.\r\n"), CA2CT(GetErrorString()));
			m_state = ST_Error;
		}
	}
	else //---Download page failed
	{
		m_error = ERR_CommunicationError;
		m_state = ST_Error;
		TRACE(_T("@4 LastFMServices::HandShake. fail: Communication Error.\r\n"));
	}
	return m_state == ST_Idle;

}
/*******************************************************************************
**
** Function:        nativeNfcTag_doTransceive
**
** Description:     Send raw data to the tag; receive tag's response.
**                  e: JVM environment.
**                  o: Java object.
**                  raw: Not used.
**                  statusTargetLost: Whether tag responds or times out.
**
** Returns:         Response from tag.
**
*******************************************************************************/
static jbyteArray nativeNfcTag_doTransceive (JNIEnv* e, jobject, jbyteArray data, jboolean raw, jintArray statusTargetLost)
{
    int timeout = NfcTag::getInstance ().getTransceiveTimeout (sCurrentConnectedTargetType);
    ALOGD ("%s: enter; raw=%u; timeout = %d", __FUNCTION__, raw, timeout);
    bool waitOk = false;
    bool isNack = false;
    jint *targetLost = NULL;

    if (NfcTag::getInstance ().getActivationState () != NfcTag::Active)
    {
        if (statusTargetLost)
        {
            targetLost = e->GetIntArrayElements (statusTargetLost, 0);
            if (targetLost)
                *targetLost = 1; //causes NFC service to throw TagLostException
            e->ReleaseIntArrayElements (statusTargetLost, targetLost, 0);
        }
        ALOGD ("%s: tag not active", __FUNCTION__);
        return NULL;
    }

    NfcTag& natTag = NfcTag::getInstance ();

    // get input buffer and length from java call
    ScopedByteArrayRO bytes(e, data);
    uint8_t* buf = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&bytes[0])); // TODO: API bug; NFA_SendRawFrame should take const*!
    size_t bufLen = bytes.size();

    if (statusTargetLost)
    {
        targetLost = e->GetIntArrayElements (statusTargetLost, 0);
        if (targetLost)
            *targetLost = 0; //success, tag is still present
    }

    sSwitchBackTimer.kill ();
    ScopedLocalRef<jbyteArray> result(e, NULL);
    do
    {
        {
            SyncEventGuard g (sTransceiveEvent);
            sTransceiveRfTimeout = false;
            sWaitingForTransceive = true;
            sRxDataStatus = NFA_STATUS_OK;
            sRxDataBuffer.clear ();
            tNFA_STATUS status = NFA_SendRawFrame (buf, bufLen,
                    NFA_DM_DEFAULT_PRESENCE_CHECK_START_DELAY);
            if (status != NFA_STATUS_OK)
            {
                ALOGE ("%s: fail send; error=%d", __FUNCTION__, status);
                break;
            }
            waitOk = sTransceiveEvent.wait (timeout);
        }

        if (waitOk == false || sTransceiveRfTimeout) //if timeout occurred
        {
            ALOGE ("%s: wait response timeout", __FUNCTION__);
            if (targetLost)
                *targetLost = 1; //causes NFC service to throw TagLostException
            break;
        }

        if (NfcTag::getInstance ().getActivationState () != NfcTag::Active)
        {
            ALOGE ("%s: already deactivated", __FUNCTION__);
            if (targetLost)
                *targetLost = 1; //causes NFC service to throw TagLostException
            break;
        }

        ALOGD ("%s: response %d bytes", __FUNCTION__, sRxDataBuffer.size());

        if ((natTag.getProtocol () == NFA_PROTOCOL_T2T) &&
            natTag.isT2tNackResponse (sRxDataBuffer.data(), sRxDataBuffer.size()))
        {
            isNack = true;
        }

        if (sRxDataBuffer.size() > 0)
        {
            if (isNack)
            {
                //Some Mifare Ultralight C tags enter the HALT state after it
                //responds with a NACK.  Need to perform a "reconnect" operation
                //to wake it.
                ALOGD ("%s: try reconnect", __FUNCTION__);
                nativeNfcTag_doReconnect (NULL, NULL);
                ALOGD ("%s: reconnect finish", __FUNCTION__);
            }
            else
            {
                // marshall data to java for return
                result.reset(e->NewByteArray(sRxDataBuffer.size()));
                if (result.get() != NULL)
                {
                    e->SetByteArrayRegion(result.get(), 0, sRxDataBuffer.size(), (const jbyte *) sRxDataBuffer.data());
                }
                else
                    ALOGE ("%s: Failed to allocate java byte array", __FUNCTION__);
            } // else a nack is treated as a transceive failure to the upper layers

            sRxDataBuffer.clear();
        }
    } while (0);

    sWaitingForTransceive = false;
    if (targetLost)
        e->ReleaseIntArrayElements (statusTargetLost, targetLost, 0);

    ALOGD ("%s: exit", __FUNCTION__);
    return result.release();
}