Exemplo n.º 1
0
	void PathUtil::splitPath(const String& path, String& dir, String& fname, String& ext) {
		dir = path;

		fname.clear();
		ext.clear();

		size_t slen = dir.length();
		size_t len = slen;

		// find extension
		for (; len>0; len--) {
			if (dir[len-1] == L'.') {
				ext = dir.c_str() + len - 1;
				dir.resize(len-1);
				break;
			}
		}

		// find file name;
		if (len == 0) len = slen;
		for (; len>0; len--) {
			if (isDirectoryLetter(dir[len-1])) {
				fname = dir.c_str() + len;
				dir.resize(len);
				break;
			}
		}

		return;
	}
Exemplo n.º 2
0
inline bool escape3(char const* i, std::size_t n, String& s, std::size_t maxlen = 0) {
  assert(s.empty());
  if (!maxlen || maxlen > n) maxlen = n;
  if (!maxlen) return false;
  s.resize(reserve_escape3(maxlen));
  char* out = &s[0];
  char* obegin = out;
  char const* end = i + maxlen;
  for (; i < end; ++i) append_escape3(out, *i);
  s.resize(out - obegin);
  return maxlen < n;
}
Exemplo n.º 3
0
	inline String w2l(const wchar_t* wstr, size_t len) {
		String result;

		result.resize(len * AX_MB_LEN_MAX);

		size_t count = wcstombs(&result[0], &wstr[0], result.size());

		AX_ASSERT(count <= result.size());

		result.resize(count);

		return result;
	}
	String StringUtils::wideString2utf8String( const WideString& wideString )
	{
		size_t widesize = wideString.length();
		String returnString;

		if ( sizeof( wchar_t ) == 2 )
		{
			size_t utf8size = MAX_UTF8_CHAR_LENGTH * widesize + 1;
			returnString.resize( utf8size, '\0' );
			const UTF16* sourcestart = reinterpret_cast<const UTF16*>( wideString.c_str() );
			const UTF16* sourceend = sourcestart + widesize;
			UTF8* targetstart = reinterpret_cast<UTF8*>( &((returnString)[ 0 ]) );
			UTF8* thisFirstWChar = targetstart;
			UTF8* targetend = targetstart + utf8size;
			ConversionResult res = ConvertUTF16toUTF8( &sourcestart, sourceend, &targetstart, targetend, strictConversion );

			if ( res != conversionOK )
			{
				throw Exception(Exception::ERROR_WIDE_2_UTF8, String("Could not convert from wide string to UTF8."));
			}

			returnString.resize(targetstart - thisFirstWChar);
		}

		else if ( sizeof( wchar_t ) == 4 )
		{
			size_t utf8size = MAX_UTF8_CHAR_LENGTH * widesize + 1;
			returnString.resize( utf8size, '\0' );
			const UTF32* sourcestart = reinterpret_cast<const UTF32*>( wideString.c_str() );
			const UTF32* sourceend = sourcestart + widesize;
			UTF8* targetstart = reinterpret_cast<UTF8*>( &((returnString)[ 0 ]) );
			UTF8* thisFirstWChar = targetstart;
			UTF8* targetend = targetstart + utf8size;
			ConversionResult res = ConvertUTF32toUTF8( &sourcestart, sourceend, &targetstart, targetend, strictConversion );

			if ( res != conversionOK )
			{
				throw Exception(Exception::ERROR_WIDE_2_UTF8, String("Could not convert from wide string to UTF8."));
			}

			returnString.resize(targetstart - thisFirstWChar);
		}

		else
		{
			throw Exception(Exception::ERROR_WIDE_2_UTF8, String("Could not convert from wide string to UTF8."));
		}
		return returnString;
	}
Exemplo n.º 5
0
	inline String w2u(const wchar_t* wstr, size_t len) {
		String result;

		result.resize(len * AX_UTF8_LEN_MAX);
		if (sizeof(wchar_t) == sizeof(UTF16)) {
			const UTF16* srcstart = (UTF16*)&wstr[0];
			const UTF16* srcend = srcstart + len;
			UTF8* dststart = (UTF8*)&result[0];
			UTF8* dstend = dststart + result.size();
			ConversionResult cr = ConvertUTF16toUTF8(&srcstart, srcend, &dststart, dstend, strictConversion);
			result.resize(dststart - (UTF8*)&result[0]);
		}

		return result;
	}
Exemplo n.º 6
0
//////////////////////////////////////////////////////////
// PRE:  0 <= start <= end < length
// POST: RetVal == String(str[start .. end])
//
String String::substr(int start, int end) const
{ 

    String result;
    int len = length();
    if(start >= len || start < 0 )            // bound check for start
    {
        return(result);
    }
    if(end >= len || end < 0 || end < start)  // bound check for end
    {
      return(result);
    }

    if(end - start > result.capacity())
      result.resize(end-start);

    for(int i=start; i <= end; ++i)
    {
      result += str[i];             // copy values
    }
    result[end-start+1] = 0;                // null terminate

    return result;                    
}
Exemplo n.º 7
0
void NativeEditBox::textBoxClosed(int res, int length) {
	if(res == MA_TB_RES_OK) {
		MAUI_LOG("length: %d", length);
		String str;
		str.resize(length);
		sprintf(str.pointer(), "%S", mString);
		setCaption(str);
		MAUI_LOG("%S", mString);
		requestRepaint();
		// TODO: Remove commented out code.
		/*
		if(mListener != NULL) {
			mListener->nativeEditFinished();
		}
		*/		
		ListenerSet_fire(
			NativeEditBoxListener, 
			mEditBoxListeners, 
			nativeEditFinished(this, mCaption));
		
	}
	// TODO: Remove commented out code.
	//mListener = NULL;
	Environment::getEnvironment().removeTextBoxListener(this);
}
Exemplo n.º 8
0
    //---------------------------------------------------------------------
    void GpuProgramManager::loadMicrocodeCache( DataStreamPtr stream )
    {
        mMicrocodeCache.clear();

        // write the size of the array
        uint32 sizeOfArray = 0;
        stream->read(&sizeOfArray, sizeof(uint32));
        
        // loop the array and load it

        for ( uint32 i = 0 ; i < sizeOfArray ; i++ )
        {
            String nameOfShader;
            // loads the name of the shader
            uint32 stringLength  = 0;
            stream->read(&stringLength, sizeof(uint32));
            nameOfShader.resize(stringLength);              
            stream->read(&nameOfShader[0], stringLength);

            // loads the microcode
            uint32 microcodeLength = 0;
            stream->read(&microcodeLength, sizeof(uint32));     

            Microcode microcodeOfShader(OGRE_NEW MemoryDataStream(nameOfShader, microcodeLength));      
            microcodeOfShader->seek(0);
            stream->read(microcodeOfShader->getPtr(), microcodeLength);

            mMicrocodeCache.insert(make_pair(nameOfShader, microcodeOfShader));
        }

        // if cache is not modified, mark it as clean.
        mCacheDirty = false;
        
    }
Exemplo n.º 9
0
	static void cutText(String& output, Font* font, const String& text, Rect bounds)
	{
		output.clear();
		const Charset& cs = font->getCharset();
		const unsigned char *str = (const unsigned char*)text.c_str();
		int w = bounds.width;
		int x = bounds.x;
		int i = 0;
		while(*str) {
			const CharDescriptor& cd = cs.chars[*str];
			if(x+cd.xAdvance>w) {
				int numDots = 3;
				if(i<3) numDots = i;
				output.resize(i-numDots);
				memcpy(&output[0], text.c_str(), i-numDots);
				output.append("...", numDots);
				return;
			} else {
				i++;
			}
			x+=cd.xAdvance;
			str++;
		}
		output = text;
	}
	//---------------------------------------------------------------------
	void GpuProgramManager::loadMicrocodeCache( DataStreamPtr stream )
	{
		mMicrocodeCache.clear();

		// write the size of the array
		size_t sizeOfArray = 0;
		stream->read(&sizeOfArray, sizeof(size_t));
		
		// loop the array and load it

		for ( size_t i = 0 ; i < sizeOfArray ; i++ )
		{
			String nameOfShader;
			// loads the name of the shader
			size_t stringLength  = 0;
			stream->read(&stringLength, sizeof(size_t));
			nameOfShader.resize(stringLength);				
			stream->read(&nameOfShader[0], stringLength);

			// loads the microcode
			size_t microcodeLength = 0;
			stream->read(&microcodeLength, sizeof(size_t));		

			Microcode microcodeOfShader(OGRE_NEW MemoryDataStream(nameOfShader, microcodeLength)); 		
			microcodeOfShader->seek(0);
			stream->read(microcodeOfShader->getPtr(), microcodeLength);

			mMicrocodeCache.insert(make_pair(nameOfShader, microcodeOfShader));
		}
	}
Exemplo n.º 11
0
/** 
 * @brief Get folder for temporary files.
 * This function returns system temp folder.
 * @param [out] pnerr Error code if erorr happened.
 * @return Temp path, or empty string if error happened.
 * @note Temp path is cached after first call.
 * @todo Should we return NULL for error case?
 */
LPCTSTR env_GetTempPath(int * pnerr)
{
	if (strTempPath.empty())
	{
		if (GetOptionsMgr()->GetBool(OPT_USE_SYSTEM_TEMP_PATH))
		{
			int cchTempPath = GetTempPath(0, 0);
			strTempPath.resize(cchTempPath - 1);
			if (!GetTempPath(cchTempPath, &*strTempPath.begin()))
			{
				int err = GetLastError();
				if (pnerr)
					*pnerr = err;
#ifdef _DEBUG
				String sysErr = GetSysError(err); // for debugging
#endif
				return strTempPath.c_str(); // empty
			}
		}
		else
		{
			strTempPath = GetOptionsMgr()->GetString(OPT_CUSTOM_TEMP_PATH);
			if (!paths_EndsWithSlash(strTempPath.c_str()))
				strTempPath += '\\';
		}
		strTempPath = paths_GetLongPath(strTempPath.c_str());
	}
	return strTempPath.c_str();
}
//----------------------------------------------------------------------------//
bool parse_section(String::const_iterator& pos, const String::const_iterator& end,
                   String::value_type delim, String& out)
{
    const String::value_type escape('\\');
    out.resize(0);

    String::const_iterator start_iter(pos);

    for ( ; pos != end; ++pos)
    {
        if (*pos == delim)
        {
            out.append(start_iter, pos++);
            return true;
        }

        if (*pos == escape)
        {
            out.append(start_iter, pos++);

            if (pos == end)
                return false;

            start_iter = pos;
        }
    }

    out.append(start_iter, pos);
    return false;
}
Exemplo n.º 13
0
//----------------------------------------------------------------------------//
void Editbox::setMaxTextLength(size_t max_len)
{
    if (d_maxTextLen != max_len)
    {
        d_maxTextLen = max_len;

        // Trigger max length changed event
        WindowEventArgs args(this);
        onMaximumTextLengthChanged(args);

        // trim string
        if (getText().length() > d_maxTextLen)
        {
            String newText = getText();
            newText.resize(d_maxTextLen);
            setText(newText);
            onTextChanged(args);

            const MatchState state = getStringMatchState(getText());
            if (d_validatorMatchState != state)
            {
                RegexMatchStateEventArgs rms_args(this, state);
                onTextValidityChanged(rms_args);
                d_validatorMatchState = state;
            }
        }

    }

}
Exemplo n.º 14
0
Optional<String>
readFile(String& path) noexcept {
    Optional<uint64_t> size = getFileSize(path);
    if (!size) {
        return Optional<String>();
    }

    FILE* f = fopen(path.null(), "r");
    if (!f) {
        return Optional<String>();
    }

    String contents;
    contents.resize(*size);

    ssize_t read = fread(contents.data(), *size, 1, f);
    if (read != 1) {
        fclose(f);
        return Optional<String>();
    }

    fclose(f);

    return Optional<String>(move_(contents));
}
Exemplo n.º 15
0
const String& DateField::MAX_DATE_STRING() {
    static String _MAX_DATE_STRING;
    if (_MAX_DATE_STRING.empty()) {
        _MAX_DATE_STRING.resize(DATE_LEN());
        std::fill(_MAX_DATE_STRING.begin(), _MAX_DATE_STRING.end(), L'z');
    }
    return _MAX_DATE_STRING;
}
Exemplo n.º 16
0
	String w2l(const WString& wstr) {
		return w2l(wstr.c_str(), wstr.size());
#if 0
		size_t len = wstr.size();
		String result;

		result.resize(len * AX_MB_LEN_MAX);

		size_t count = wcstombs(&result[0], &wstr[0], result.size());

		AX_ASSERT(count <= result.size());

		result.resize(count);

		return result;
#endif
	}
Exemplo n.º 17
0
	String w2l(const wchar_t* wstr) {
		return w2l(wstr, wcslen(wstr));
#if 0
		size_t len = wcslen(wstr);
		String result;

		result.resize(len * AX_MB_LEN_MAX);

		size_t count = wcstombs(&result[0], wstr, len);

		AX_ASSERT(count <= result.size());

		result.resize(count);

		return result;
#endif
	}
Exemplo n.º 18
0
void Process::handleOutput(int fd, String &buffer, int &index, Signal<std::function<void(Process*)> > &signal)
{
    //printf("Process::handleOutput %d\n", fd);
    enum { BufSize = 1024, MaxSize = (1024 * 1024 * 256) };
    char buf[BufSize];
    int total = 0;
    for (;;) {
        int r;
        eintrwrap(r, ::read(fd, buf, BufSize));
        if (r == -1) {
            //printf("Process::handleOutput %d returning -1, errno %d %s\n", fd, errno, Rct::strerror().constData());
            break;
        } else if (r == 0) { // file descriptor closed, remove it
            //printf("Process::handleOutput %d returning 0\n", fd);
            if (auto eventLoop = EventLoop::eventLoop())
                eventLoop->unregisterSocket(fd);
            break;
        } else {
            //printf("Process::handleOutput in loop %d\n", fd);
            //printf("data: '%s'\n", String(buf, r).constData());
            int sz = buffer.size();
            if (sz + r > MaxSize) {
                if (sz + r - index > MaxSize) {
                    error("Process::handleOutput, buffer too big, dropping data");
                    buffer.clear();
                    index = sz = 0;
                } else {
                    sz = buffer.size() - index;
                    memmove(buffer.data(), buffer.data() + index, sz);
                    buffer.resize(sz);
                    index = 0;
                }
            }
            buffer.resize(sz + r);
            memcpy(buffer.data() + sz, buf, r);

            total += r;
        }
    }

    //printf("total data '%s'\n", buffer.nullTerminated());

    if (total)
        signal(this);
}
Exemplo n.º 19
0
 bool RussianStemmer::removeSoft(String& stemmingZone)
 {
     if ((int32_t)stemmingZone.length() > 0 && stemmingZone[stemmingZone.length() - 1] == SOFT)
     {
         stemmingZone.resize(stemmingZone.length() - 1);
         return true;
     }
         return false;
 }
Exemplo n.º 20
0
String Directory::fixPath(String path)
{
	if(path.empty()) throw Exception("Empty path");	
  	if(path.size() >= 2 && path[path.size()-1] == Separator) path.resize(path.size()-1);
#ifdef WINDOWS
	if(path.size() == 2 && path[path.size()-1] == ':') path+= Separator;
#endif
	return path;
}
Exemplo n.º 21
0
void CRhoFile::readString(String& strData){
    if ( !isOpened() )
        return;

    int nSize = size();
    strData.resize(nSize);
    nSize = fread(&strData[0], 1, nSize, m_file);
    strData[nSize] = 0;
}
Exemplo n.º 22
0
void base64LE_append_pad(String &s, Int x, char const* base64code = base64url) {
  assert(good_base64_code(base64code));
  unsigned i = s.size(), N = i + (sizeof(Int) * 4 + 2) / 3;
  s.resize(N);
  for(; i != N; ++i) {
    s[i] = base64code[x & 63];
    x >>= 6;
  }
}
Exemplo n.º 23
0
void KeywordParam::eat_separator_before(String& text) {
	if (separator_before_eat.empty()) return;
	Regex::Results result;
	if (separator_before_eat.matches(result, text)) {
		// keep only stuff before the separator
		assert(result.position() + result.size() == text.size());
		text.resize(result.position());
	}
}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
    LogLevel logLevel = LogLevel::Error;
    Path file;
    for (int i=1; i<argc; ++i) {
        if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")) {
            ++logLevel;
        } else {
            file = argv[i];
        }
    }

    setenv("LIBCLANG_NOTHREADS", "1", 0);
    signal(SIGSEGV, sigHandler);
    signal(SIGABRT, sigHandler);
    signal(SIGBUS, sigHandler);

    Flags<LogMode> logType = LogStderr;
    std::shared_ptr<SyslogCloser> closer;
    if (ClangIndexer::serverOpts() & Server::RPLogToSyslog) {
        logType |= LogSyslog;
        closer.reset(new SyslogCloser);
    }
    initLogging(argv[0], logType, logLevel);
    (void)closer;

    RTags::initMessages();
    std::shared_ptr<EventLoop> eventLoop(new EventLoop);
    eventLoop->init(EventLoop::MainEventLoop);
    String data;

    if (!file.isEmpty()) {
        data = file.readAll();
    } else {
        uint32_t size;
        if (!fread(&size, sizeof(size), 1, stdin)) {
            error() << "Failed to read from stdin";
            return 1;
        }
        data.resize(size);
        if (!fread(&data[0], size, 1, stdin)) {
            error() << "Failed to read from stdin";
            return 2;
        }
        // FILE *f = fopen("/tmp/data", "w");
        // fwrite(data.constData(), data.size(), 1, f);
        // fclose(f);
    }
    ClangIndexer indexer;
    if (!indexer.exec(data)) {
        error() << "ClangIndexer error";
        return 3;
    }

    return 0;
}
Exemplo n.º 25
0
	String w2u(const WString& wstr) {
		return w2u(wstr.c_str(), wstr.size());
#if 0
		size_t len = wstr.size();
		String result;

		result.resize(len * AX_UTF8_LEN_MAX);
		if (sizeof(wchar_t) == sizeof(UTF16)) {
			const UTF16* srcstart = (UTF16*)&wstr[0];
			const UTF16* srcend = srcstart + len;
			UTF8* dststart = (UTF8*)&result[0];
			UTF8* dstend = dststart + result.size();
			ConversionResult cr = ConvertUTF16toUTF8(&srcstart, srcend, &dststart, dstend, strictConversion);
			result.resize(dststart - (UTF8*)&result[0]);
		}

		return result;
#endif
	}
Exemplo n.º 26
0
void TimeLog::addTimeLog(const std::string &strMsg, __int64 nTimeSpan) {
    String strLog = strMsg;
    if ( strLog.size() < _MSG_WIDTH )
        strLog.resize(_MSG_WIDTH, ' ');
    strLog += "\t" + std::to_string ( nTimeSpan );
    strLog += "\t" + _stopWatch.GetLocalTimeStr();

    auto nIndex = ( _anIndex ++ ) % _SIZE;
    _vecStringTimeLog [ nIndex ] = strLog;
}
Exemplo n.º 27
0
 bool RussianStemmer::undoubleN(String& stemmingZone)
 {
     if (findEnding(stemmingZone, doubleN()) != 0)
     {
         stemmingZone.resize(stemmingZone.length() - 1);
         return true;
     }
     else
         return false;
 }
Exemplo n.º 28
0
/// NOTE: This ID is used to create part names which are then persisted in ZK and as directory names on the file system.
/// So if you want to change this method, be sure to guarantee compatibility with existing table data.
String MergeTreePartition::getID(const Block & partition_key_sample) const
{
    if (value.size() != partition_key_sample.columns())
        throw Exception("Invalid partition key size: " + toString(value.size()), ErrorCodes::LOGICAL_ERROR);

    if (value.empty())
        return "all"; /// It is tempting to use an empty string here. But that would break directory structure in ZK.

    /// In case all partition fields are represented by integral types, try to produce a human-readable ID.
    /// Otherwise use a hex-encoded hash.
    bool are_all_integral = true;
    for (const Field & field : value)
    {
        if (field.getType() != Field::Types::UInt64 && field.getType() != Field::Types::Int64)
        {
            are_all_integral = false;
            break;
        }
    }

    String result;

    if (are_all_integral)
    {
        FieldVisitorToString to_string_visitor;
        for (size_t i = 0; i < value.size(); ++i)
        {
            if (i > 0)
                result += '-';

            if (typeid_cast<const DataTypeDate *>(partition_key_sample.getByPosition(i).type.get()))
                result += toString(DateLUT::instance().toNumYYYYMMDD(DayNum(value[i].safeGet<UInt64>())));
            else
                result += applyVisitor(to_string_visitor, value[i]);

            /// It is tempting to output DateTime as YYYYMMDDhhmmss, but that would make partition ID
            /// timezone-dependent.
        }

        return result;
    }

    SipHash hash;
    FieldVisitorHash hashing_visitor(hash);
    for (const Field & field : value)
        applyVisitor(hashing_visitor, field);

    char hash_data[16];
    hash.get128(hash_data);
    result.resize(32);
    for (size_t i = 0; i < 16; ++i)
        writeHexByteLowercase(hash_data[i], &result[2 * i]);

    return result;
}
Exemplo n.º 29
0
 bool RussianStemmer::findAndRemoveEnding(String& stemmingZone, Collection<String> theEndingClass)
 {
     int32_t endingLength = findEnding(stemmingZone, theEndingClass);
     if (endingLength == 0)
         return false; // not found
     else
     {
         stemmingZone.resize(stemmingZone.length() - endingLength);
         return true; // cut the ending found
     }
 }
Exemplo n.º 30
0
String readTextFile(const String &ipath) {
	auto f = openForReading(ipath);
	if (f) {
		auto fsize = f.size();
		String ret; ret.resize(fsize);
		f.read((uint8_t *)ret.data(), fsize);
		f.close();
		return ret;
	}
	return String();
}