void StringTrimLeftT(std::basic_string<CharType> &output)
{
	size_t check = 0;
	size_t length = output.length();
	const CharType *src = output.data();

	for (; check < length; check++)
		if (NOT_SPACE(src[check]))
			break;

	output.erase(0, check);
}
Beispiel #2
0
    std::basic_string<ToChar>
    convert(const std::basic_string<FromChar>& s, Fun fun)
    {
        std::basic_string<ToChar> result;

        mbstate_t state = {0};

        const FromChar* from = s.data();
        const FromChar* from_end = s.data() + s.size();
        // The interface of cvt is not really iterator-like, and it's
        // not possible the tell the required output size without the conversion.
        // All we can is convert data by pieces.
        while(from != from_end) {

            // std::basic_string does not provide non-const pointers to the data,
            // so converting directly into basic_string<char> is not possible.
            ToChar buffer[32];

            ToChar* to_next = buffer;
            // Need variable because boost::bind doesn't work with rvalues.
            ToChar* to_end = buffer + 32;
            std::codecvt_base::result r = 
                fun(state, from, from_end, from, buffer, to_end, to_next);

            if (r == std::codecvt_base::error)
                throw std::logic_error("character conversion failed");
            // 'partial' is not an error, it just means not all source
            // characters were converted. However, we need to check that at
            // least one new target character was produced. If not, it means
            // the source data is incomplete, and since we don't have extra
            // data to add to source, it's error.
            if (to_next == buffer)
                throw std::logic_error("character conversion failed");

            // Add converted characters
            result.append(buffer, to_next);
        }

        return result;
    }
Beispiel #3
0
const std::basic_string<Byte> out(
    const std::basic_string<CharType>& internal_str,
    const std::codecvt<CharType, Byte, mbstate_t>& codecvt)
{
  typedef std::basic_string<CharType> wstring;
  typedef std::basic_string<Byte>     string;
  typedef std::codecvt<CharType, Byte, mbstate_t> codecvt_type;

  string external_str;

  typename wstring::size_type internal_str_size = internal_str.length();
  typename wstring::size_type out_buf_size =
      static_cast<typename wstring::size_type>(codecvt.max_length()) *
          internal_str_size;

#if defined(MA_USE_CXX11_STDLIB_MEMORY)
  std::unique_ptr<Byte[]> out_buf(new Byte[out_buf_size]);
#else
  boost::scoped_array<Byte> out_buf(new Byte[out_buf_size]);
#endif

  const CharType* first_internal = internal_str.data();
  const CharType* last_internal  = first_internal + internal_str_size;
  const CharType* next_internal  = first_internal;

  Byte* first_external = out_buf.get();
  Byte* last_external  = first_external + out_buf_size;
  Byte* next_external  = first_external;

  typename codecvt_type::state_type state(0);

  typename codecvt_type::result r = codecvt.out(state,
      first_internal, last_internal, next_internal,
      first_external, last_external, next_external);

  if (codecvt_type::ok == r)
  {
    external_str.assign(first_external, next_external);
  }
  else if (codecvt_type::noconv == r)
  {
    external_str.assign(reinterpret_cast<const Byte*>(first_internal),
        reinterpret_cast<const Byte*>(last_internal));
  }
  else
  {
    boost::throw_exception(bad_conversion());
  }

  return external_str;
}
Beispiel #4
0
const std::basic_string<CharType> in(
    const std::basic_string<Byte>& external_str,
    const std::codecvt<CharType, Byte, mbstate_t>& codecvt)
{
  typedef std::basic_string<CharType> wstring;
  typedef std::basic_string<Byte>     string;
  typedef std::codecvt<CharType, Byte, mbstate_t> codecvt_type;

  typename string::size_type external_str_size = external_str.length();
  const Byte* first_external = external_str.data();
  const Byte* last_external  = first_external + external_str_size;
  const Byte* next_external  = last_external;

  wstring internal_str;

  typename codecvt_type::state_type state(0);
  typename wstring::size_type out_buf_size =
      static_cast<typename wstring::size_type>(
          codecvt.length(state, first_external, last_external,
              internal_str.max_size()));

#if defined(MA_USE_CXX11_STDLIB_MEMORY)
  detail::unique_ptr<CharType[]> out_buf(new CharType[out_buf_size]);
#else
  detail::scoped_array<CharType> out_buf(new CharType[out_buf_size]);
#endif

  CharType* first_internal = out_buf.get();
  CharType* last_internal  = first_internal + out_buf_size;
  CharType* next_internal  = first_internal;

  typename codecvt_type::result r = codecvt.in(state,
      first_external, last_external, next_external,
      first_internal, last_internal, next_internal);

  if (codecvt_type::ok != r)
  {
    boost::throw_exception(bad_conversion());
  }
  else if (codecvt_type::noconv == r)
  {
    internal_str.assign(reinterpret_cast<const CharType*>(first_external),
        reinterpret_cast<const CharType*>(last_external));
  }
  else
  {
    internal_str.assign(first_internal, last_internal);
  }

  return internal_str;
}
Beispiel #5
0
 virtual typename base::int_type
     overflow(typename base::int_type ch = base::traits_type::eof())
     {
         if (ch != base::traits_type::eof())
         {
             std::size_t n = str_.size();
             str_.push_back(static_cast<CharT>(ch));
             str_.resize(str_.capacity());
             base::setp(const_cast<CharT*>(str_.data()),
                        const_cast<CharT*>(str_.data() + str_.size()));
             base::pbump(static_cast<int>(n+1));
         }
         return ch;
     }
Beispiel #6
0
 virtual typename base::int_type
     overflow(typename base::int_type __c = base::traits_type::eof())
     {
         if (__c != base::traits_type::eof())
         {
             int n = static_cast<int>(str_.size());
             str_.push_back(static_cast<CharT>(__c));
             str_.resize(str_.capacity());
             base::setp(const_cast<CharT*>(str_.data()),
                        const_cast<CharT*>(str_.data() + str_.size()));
             base::pbump(n+1);
         }
         return __c;
     }
Beispiel #7
0
utf8string::utf8string(const std::basic_string<CHAR>& strArg) {
	// Currently no check for validity
	std::string target_enc = utf8_encoding + ignore_tag;
	std::string source_enc = get_encoding<CHAR>().c_str();
	iconv_t converter = iconv_open(target_enc.c_str(), source_enc.c_str());
	size_t inSize = (strArg.length() + 1) * sizeof (CHAR);
	size_t outSize = 6 * strArg.length() + 1; // Maximum Possible UTF-8 size
	std::vector<char> outBuf(outSize);
	char* outBufPtr = outBuf.data();
	const char* inBufPtr = reinterpret_cast<const char *>(strArg.data());
	iconv(converter, &inBufPtr, &inSize, &outBufPtr, &outSize);
	iconv_close(converter);

	m_str.assign(outBuf.data());
}
Beispiel #8
0
HGLOBAL CreateGlobalData(const std::basic_string<charT>& str)
{
	HGLOBAL data = ::GlobalAlloc(GMEM_MOVEABLE, ((str.size() + 1) * sizeof(charT)));
	if (data) 
	{
		charT* raw_data = static_cast<charT*>(::GlobalLock(data));
		if (!raw_data)
		{
			::GlobalUnlock(data);
			return nullptr;
		}
		memcpy(raw_data, str.data(), str.size() * sizeof(charT));
		raw_data[str.size()] = '\0';
		::GlobalUnlock(data);
	}
	return data;
}
Beispiel #9
0
int UsbIo::read( std::basic_string<unsigned char> & from ,int size )
{
    if ( !isOpen() )
    {
        if ( !open() )
            return -1;
    }
    from.resize( size );
    int res = libusb_control_transfer(
                  pd->handle,
                  CONTROL_REQUEST_TYPE_IN,
                  HID_GET_REPORT,
                  0, 0,
                  const_cast<unsigned char *>( from.data() ), from.size(), pd->timeout );
    if ( res < LIBUSB_SUCCESS )
    {
        close();
        return res;
    }
    return res;
}
Beispiel #10
0
int UsbIo::write( const std::basic_string<unsigned char> & to )
{
    if ( !isOpen() )
    {
        if ( !open() )
            return -1;
    }
    int res = libusb_control_transfer(
                  pd->handle,
                  CONTROL_REQUEST_TYPE_OUT,
                  HID_SET_REPORT,
                  0, 0,
                  const_cast<unsigned char *>( to.data() ), to.size(), pd->timeout );
    //return to.size();
    if ( res < LIBUSB_SUCCESS )
    {
        close();
        return res;
    }
    return res;
}
void StringTrimT(std::basic_string<CharType> &output)
{
	if (output.empty())
		return;
	size_t bound1 = 0;
	size_t bound2 = output.length();
	const CharType *src = output.data();

	for (; bound2 > 0; bound2--)
		if (NOT_SPACE(src[bound2-1]))
			break;

	for (; bound1 < bound2; bound1++)
		if (NOT_SPACE(src[bound1]))
			break;

	if (bound1 < bound2) {
		memmove((void *)src,
				src + bound1,
				sizeof(CharType) * (bound2 - bound1));
	}

	output.resize(bound2 - bound1);
}
Beispiel #12
0
string::string(std::basic_string<char16_t> const &s)
  : Impl::string_impl(s.data(), s.size()) { }
Beispiel #13
0
 basic_string_view (std::basic_string<CharT, Traits, Allocator> const& that) :
   str { that.data() },
   len { that.size() }
 { }
Beispiel #14
0
std::basic_string<Out>
codecvt(
	std::basic_string<In> const &_string,
	std::locale const &_locale,
	Function const &_function
)
{
	typedef std::basic_string<
		Out
	> return_type;

	typedef fcppt::container::raw_vector<
		Out
	> buffer_type;

	if(
		_string.empty()
	)
		return return_type();

	fcppt::codecvt_type const &conv(
		std::use_facet<
			fcppt::codecvt_type
		>(
			_locale
		)
	);

	buffer_type buf(
		_string.size()
	);

	typedef fcppt::codecvt_type::state_type state_type;

	state_type state;

	std::memset(
		&state,
		0,
		sizeof(state_type)
	);

	Out *to = buf.data();

	for(
		In const *from = _string.data(),
		*from_next = nullptr;
		; // loop forever
		from = from_next
	)
	{
		Out *to_next;

		std::codecvt_base::result const result(
			(
				conv.*_function
			)(
				state,
				from,
				fcppt::container::data_end(
					_string
				),
				from_next,
				to,
				buf.data_end(),
				to_next
			)
		);

		switch(
			result
		)
		{
		case std::codecvt_base::noconv:
			return
				return_type(
					_string.begin(),
					_string.end()
				);
		case std::codecvt_base::error:
			throw fcppt::exception(
				FCPPT_TEXT("codecvt: error!")
			);
		case std::codecvt_base::partial:
			{
				typename buffer_type::difference_type const diff(
					std::distance(
						buf.data(),
						to_next
					)
				);

				buf.resize(
					buf.size() * 2
				);

				to = buf.data() + diff;
			}
			continue;
		case std::codecvt_base::ok:
			return
				return_type(
					buf.data(),
					to_next
				);
		}

		FCPPT_ASSERT_UNREACHABLE;
	}
}
Beispiel #15
0
 void serialize(output_archive & ar, std::basic_string<Char, CharTraits,
     Allocator> & s, unsigned)
 {
     ar << s.size(); //-V128
     save_binary(ar, s.data(), s.size() * sizeof(Char));
 }
void BidiTestRunner::runTest(const std::basic_string<UChar>& input, const std::vector<int>& expectedOrder,
    const std::vector<int>& expectedLevels, bidi_test::ParagraphDirection paragraphDirection,
    const std::string& line, size_t lineNumber)
{
    if (!m_skippedCodePoints.empty()) {
        for (size_t i = 0; i < input.size(); i++) {
            if (m_skippedCodePoints.count(input[i])) {
                m_testsSkipped++;
                return;
            }
        }
    }

    m_testsRun++;

    TextRun textRun(input.data(), input.size());
    switch (paragraphDirection) {
    case bidi_test::DirectionAutoLTR:
        textRun.setDirection(determineParagraphDirectionality(textRun));
        break;
    case bidi_test::DirectionLTR:
        textRun.setDirection(LTR);
        break;
    case bidi_test::DirectionRTL:
        textRun.setDirection(RTL);
        break;
    }
    BidiResolver<TextRunIterator, BidiCharacterRun> resolver;
    resolver.setStatus(BidiStatus(textRun.direction(), textRun.directionalOverride()));
    resolver.setPositionIgnoringNestedIsolates(TextRunIterator(&textRun, 0));

    BidiRunList<BidiCharacterRun>& runs = resolver.runs();
    resolver.createBidiRunsForLine(TextRunIterator(&textRun, textRun.length()));

    std::ostringstream errorContext;
    errorContext << ", line " << lineNumber << " \"" << line << "\"";
    errorContext << " context: " << bidi_test::nameFromParagraphDirection(paragraphDirection);

    std::vector<int> actualOrder;
    std::vector<int> actualLevels;
    actualLevels.assign(input.size(), -1);
    BidiCharacterRun* run = runs.firstRun();
    while (run) {
        // Blink's UBA just makes runs, the actual ordering of the display of characters
        // is handled later in our pipeline, so we fake it here:
        bool reversed = run->reversed(false);
        ASSERT(run->stop() >= run->start());
        size_t length = run->stop() - run->start();
        for (size_t i = 0; i < length; i++) {
            int inputIndex = reversed ? run->stop() - i - 1 : run->start() + i;
            if (!isNonRenderedCodePoint(input[inputIndex]))
                actualOrder.push_back(inputIndex);
            // BidiTest.txt gives expected level data in the order of the original input.
            actualLevels[inputIndex] = run->level();
        }
        run = run->next();
    }

    if (expectedOrder.size() != actualOrder.size()) {
        m_ignoredCharFailures++;
        EXPECT_EQ(expectedOrder.size(), actualOrder.size()) << errorContext.str();
    } else if (expectedOrder != actualOrder) {
        m_orderFailures++;
        printf("ORDER %s%s\n", diffString(actualOrder, expectedOrder).c_str(), errorContext.str().c_str());
    }

    if (expectedLevels.size() != actualLevels.size()) {
        m_ignoredCharFailures++;
        EXPECT_EQ(expectedLevels.size(), actualLevels.size()) << errorContext.str();
    } else {
        for (size_t i = 0; i < expectedLevels.size(); i++) {
            // level == -1 means the level should be ignored.
            if (expectedLevels[i] == actualLevels[i] || expectedLevels[i] == -1)
                continue;

            printf("LEVELS %s%s\n", diffString(actualLevels, expectedLevels).c_str(), errorContext.str().c_str());
            m_levelFailures++;
            break;
        }
    }
    runs.deleteRuns();
}
size_t StringReplaceAllT(const std::basic_string<CharType> &find,
						 const std::basic_string<CharType> &replace,
						 std::basic_string<CharType> &output)
{
	size_t find_length = find.size();
	size_t replace_length = replace.size();
	size_t offset = 0, endpos;
	size_t target = 0, found_pos;
	size_t replaced = 0;
	CharType *data_ptr;

	if (find.empty() || output.empty())
		return 0;

	/*
	 * to avoid extra memory reallocating,
	 * we use two passes to finish the task in the case that replace.size() is greater find.size()
	 */

	if (find_length < replace_length)
	{
		/* the first pass, count all available 'find' to be replaced  */
		for (;;)
		{
			offset = output.find(find, offset);
			if (offset == std::basic_string<CharType>::npos)
				break;
			replaced++;
			offset += find_length;
		}

		if (replaced == 0)
			return 0;

		size_t newsize = output.size() + replaced * (replace_length - find_length);

		/* we apply for more memory to hold the content to be replaced */
		endpos = newsize;
		offset = newsize - output.size();
		output.resize(newsize);
		data_ptr = &output[0];

		memmove((void*)(data_ptr + offset),
				(void*)data_ptr,
				(output.size() - offset) * sizeof(CharType));
	}
	else
	{
		endpos = output.size();
		offset = 0;
		data_ptr = const_cast<CharType *>(&output[0]);
	}

	/* the second pass,  the replacement */
	while (offset < endpos)
	{
		found_pos = output.find(find, offset);
		if (found_pos != std::basic_string<CharType>::npos)
		{
			/* move the content between two targets */
			if (target != found_pos)
				memmove((void*)(data_ptr + target),
						(void*)(data_ptr + offset),
						(found_pos - offset) * sizeof(CharType));

			target += found_pos - offset;

			/* replace */
			memcpy(data_ptr + target,
				   replace.data(),
				   replace_length * sizeof(CharType));

			target += replace_length;
			offset = find_length + found_pos;
			replaced++;
		}
		else
		{
			/* ending work  */
			if (target != offset)
				memcpy((void*)(data_ptr + target),
					   (void*)(data_ptr + offset),
					   (endpos - offset) * sizeof(CharType));
			break;
		}
	}

	if (replace_length < find_length)
		output.resize(output.size() - replaced * (find_length - replace_length));

	return replaced;
}
 save(const std::basic_string<SE, ST, SA> &s) {
     std::size_t l = static_cast<std::size_t>(s.size());
     this->This()->save(l);
     save_binary(s.data(), l * sizeof(SE) / sizeof(char));
 }
Beispiel #19
0
 basic_string_ref(const std::basic_string<charT, traits, Allocator>& str)
     : ptr_(str.data()), len_(str.length()) {}
Beispiel #20
0
	/*! @brief Create a Boyer-moore string searcher from a string
	 * @param[in] s search string
	 */
	Boyer_moore_searcher(const std::basic_string<uchar>& s) {
		arr_init(s.data(), s.size());
	}
Beispiel #21
0
 explicit
 span(std::basic_string<CharT, Traits, Allocator> const& s)
     : data_(s.data())
     , size_(s.size())
 {
 }
bool AlphabeticalCompare(const std::basic_string<CharType> & lhs, const std::basic_string<CharType> & rhs)
{
    return std::use_facet< std::collate< CharType > >( std::locale() ).compare( lhs.data(), lhs.data() + lhs.size(),
		    rhs.data(), rhs.data() + rhs.size() ) == -1;
}
Beispiel #23
0
 basic_string_view(const std::basic_string<Char, Traits, Allocator>& string) noexcept :
     data_(string.data()),
     size_(string.size())
 {}
/*******************************************************************************
**
** 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();
}
Beispiel #25
0
 const_buffer(const std::basic_string<Tp,Traits, Alloc> &s)
 : m_addr(s.data()), m_len(s.size())
 {}
Beispiel #26
0
 memory_source<Element>
 make_container_source(std::basic_string<Element> const &container)
 {
     return memory_source<Element>(make_iterator_range(
         container.data(), container.data() + container.size()));
 }
Beispiel #27
0
void test ( const std::basic_string<CharT, Traits> &str ) {
    std::basic_string_view<CharT, Traits> sv1 ( str );
    assert ( sv1.size() == str.size());
    assert ( sv1.data() == str.data());
}
Beispiel #28
0
	bool operator()(const std::basic_string<Ch,Tr>& lhs,
									const std::basic_string<Ch,Tr>& rhs)
				{
					return collate_.compare(lhs.data(), lhs.data()+lhs.size(),
																	rhs.data(), rhs.data()+rhs.size()) < 0;
				}
 void save(const std::basic_string<CharType> &s)
 {
   unsigned int l = static_cast<unsigned int>(s.size());
   save(l);
   save_impl(s.data(),s.size());
 }
Beispiel #30
0
template<class Ch> inline bool startsWithIgnoreCase(const std::basic_string<Ch>& text, const std::basic_string<Ch>& prefix, ulong_t startOffset = 0)
{return startsWithIgnoreCase(text.data() + startOffset, text.length() - startOffset, prefix.data(), prefix.length());}