Example #1
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;
}
Example #2
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;
}
Example #3
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());
	}
}
Example #4
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;
}
/// 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;
}
Example #6
0
String String::subString(int start, int end) const
{
    String sub;
    assert(end>=start && end<=_length+1 && start>=0);

    //sub._length=end-start;
    //sub.allocate(max(16,sub._length+1));
    sub.resize(end-start);
    memcpy(&sub.buf[0],&buf.getConst(start),sub._length);
    return sub;
}
Example #7
0
bool Request::addTarget(const BinaryString &target, bool finished)
{
	if(mPath.empty() || target.empty()) return false;

	String prefix = mPath;
	if(prefix.size() >= 2 && prefix[prefix.size()-1] == '/')
		prefix.resize(prefix.size()-1);

	mFinishedAfterTarget|= finished;

	return incoming(Network::Locator(prefix, "/", link()) , target);
}
Example #8
0
String String::toUpper() const
{
    String s;
    s.resize(_length);
    for (int a=0; a<_length; a++)
    {
        char c=buf.getConst(a);
        if (c>='a' && c<='z') s[a]=c-32;
        else s[a]=c;
    }
    return s;
}
Example #9
0
String String::toLower() const
{
    String s;
    int offset='A';
    s.resize(_length);
    for (int a=0; a<_length; a++)
    {
        char c=buf.getConst(a);
        if (c>='A' && c<='Z') s[a]=c+32;
        else s[a]=c;
    }
    return s;
}
Example #10
0
	String CVarRecord::generateSyncedStringRepresentation() const {
		// Replace the old value with the new.
		std::stringstream ss;

		if (cvar.getType() == sani::cvarlang::ValueType::StringVal) {
			String value;
			cvar.read(value);

			ss << value;
		} else if (cvar.getType() == sani::cvarlang::ValueType::IntVal) {
			int32 value = 0;
			cvar.read(value);

			ss << value;
		} else if (cvar.getType() == sani::cvarlang::ValueType::FloatVal) {
			float32 value = 0.0f;
			cvar.read(value);

			ss << value;
		} else if (cvar.getType() == sani::cvarlang::ValueType::DoubleVal) {
			float64 value = 0.0;
			cvar.read(value);

			ss << value;
		}

		// Create the new representation.
		const String newValue = ss.str();
		String newRepresentation = token.getLine();

		if (newValue.size() < originalValue.size()) {
			// Remove chars.
			const size_t diff = originalValue.size() - newValue.size();

			newRepresentation.erase(indexOfValue, diff);
		} else if (newValue.size() > originalValue.size()) {
			// Add chars.
			const size_t diff = newValue.size() - originalValue.size();
			
			String insertion;
			insertion.resize(diff, ' ');

			newRepresentation.insert(indexOfValue, insertion);
		}

		newRepresentation.replace(indexOfValue, newValue.size(), newValue);

		return newRepresentation;
	}
Example #11
0
bool readFile(const Path& path, String& data)
{
    FILE* f = fopen(path.nullTerminated(), "r");
    if (!f)
        return false;
    const int sz = fileSize(f);
    if (!sz) {
        data.clear();
        return true;
    }
    data.resize(sz);
    const int r = fread(data.data(), sz, 1, f);
    fclose(f);
    return (r == 1);
}
String TextIOHandler::getLine() {
	String result;
	Char buffer[2048];
	while (!feof(stdin)) {
		if (!IF_UNICODE(fgetws,fgets)(buffer, 2048, stdin)) {
			return result; // error
		}
		result += buffer;
		if (result.GetChar(result.size()-1) == _('\n')) {
			// drop newline, done
			result.resize(result.size() - 1);
			return result;
		}
	}
	return result;
}
Example #13
0
static inline String base64(const String& input)
{
#ifdef OS_Darwin
    String result;
    SecTransformRef transform = SecEncodeTransformCreate(kSecBase64Encoding, 0);
    CFDataRef sourceData = CFDataCreate(kCFAllocatorDefault,
                                        reinterpret_cast<const UInt8*>(input.constData()),
                                        input.size());
    SecTransformSetAttribute(transform, kSecTransformInputAttributeName, sourceData, 0);
    CFDataRef encodedData = static_cast<CFDataRef>(SecTransformExecute(transform, 0));
    const long len = CFDataGetLength(encodedData);
    if (len > 0) {
        result.resize(len);
        CFDataGetBytes(encodedData, CFRangeMake(0, len), reinterpret_cast<UInt8*>(result.data()));
    }
    CFRelease(encodedData);
    CFRelease(transform);
    CFRelease(sourceData);
#else
    BIO *base64_filter = BIO_new(BIO_f_base64());
    BIO_set_flags(base64_filter, BIO_FLAGS_BASE64_NO_NL);

    BIO *bio = BIO_new(BIO_s_mem());
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);

    bio = BIO_push(base64_filter, bio);

    BIO_write(bio, input.constData(), input.size());

    BIO_flush(bio);

    char *new_data;

    const long bytes_written = BIO_get_mem_data(bio, &new_data);

    String result(new_data, bytes_written);
    BIO_free_all(bio);
#endif

    return result;
}
Example #14
0
bool IndexerJob::launchProcess()
{
    static Path rp;
    if (rp.isEmpty()) {
        rp = Rct::executablePath().parentDir() + "rp";
        if (!rp.exists()) {
            rp = Rct::executablePath();
            rp.resolve();
            rp = rp.parentDir() + "rp";
        }
    }

    started = 0;
    assert(!process);
    process = new Process;
    if (!process->start(rp)) {
        error() << "Couldn't start rp" << rp << process->errorString();
        return false;
    }

    flags |= Running;

    {
        String stdinData;
        {
            Serializer serializer(stdinData);
            encode(serializer);
        }
        const int size = stdinData.size();
        String header;
        header.resize(sizeof(size));
        *reinterpret_cast<int*>(&header[0]) = size;
        process->write(header);
        process->write(stdinData);
        // error() << "Startingprocess" << (header.size() + stdinData.size()) << sourceFile;
    }
    return true;
}
Example #15
0
int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
    LogLevel logLevel = LogLevel::Error;
    Path file;
    bool logToSyslog = false;
    bool daemon = false;

    for (int i=1; i<argc; ++i) {
        if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")) {
            ++logLevel;
        } else if (!strcmp(argv[i], "--priority")) { // ignore, only for wrapping purposes
            ++i;
        } else if (!strcmp(argv[i], "--log-to-syslog")) {
            logToSyslog = true;
        } else if (!strcmp(argv[i], "--daemon")) {
            daemon = true;
        } else {
            file = argv[i];
        }
    }

    if (const char *env = getenv("TMPDIR")) { // should really always be set by rdm
        Path path = Path(env).ensureTrailingSlash();
        path += String::number(getpid());
        path.mkdir(Path::Recursive);
        setenv("TMPDIR", path.c_str(), 1);
    }
    if (!daemon)
        setenv("LIBCLANG_NOTHREADS", "1", 0);
    signal(SIGSEGV, sigHandler);
    signal(SIGABRT, sigHandler);
    signal(SIGBUS, sigHandler);
    signal(SIGALRM, [](int) {
        ClangIndexer::transition(ClangIndexer::Stopped);
    });

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

    RTags::initMessages();
    auto eventLoop = std::make_shared<EventLoop>();
    eventLoop->init(EventLoop::MainEventLoop);
    ClangIndexer indexer;
    while (true) {
        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);
        }
        if (!indexer.exec(data)) {
            error() << "ClangIndexer error";
            return 3;
        }

        if (daemon) {
            if (ClangIndexer::state() == ClangIndexer::Running) {
                printf("@FINISHED@");
                fflush(stdout);
            }
            ClangIndexer::transition(ClangIndexer::NotStarted);
        } else {
            break;
        }
    }

    return 0;
}
Example #16
0
	//-----------------------------------------------------------------------
	void CgProgram::getMicrocodeFromCache(void)
	{
		GpuProgramManager::Microcode cacheMicrocode = 
			GpuProgramManager::getSingleton().getMicrocodeFromCache(String("CG_") + mName);
		
		cacheMicrocode->seek(0);

		// get size of string
		size_t programStringSize = 0;
		cacheMicrocode->read(&programStringSize, sizeof(size_t));

		// get microcode
		mProgramString.resize(programStringSize);
		cacheMicrocode->read(&mProgramString[0], programStringSize);

		// get size of param map
		size_t parametersMapSize = 0;
		cacheMicrocode->read(&parametersMapSize, sizeof(size_t));
				
		// get params
		for(size_t i = 0 ; i < parametersMapSize ; i++)
		{
			String paramName;
			size_t stringSize = 0;
			GpuConstantDefinition def;
			
			// get string size
			cacheMicrocode->read(&stringSize, sizeof(size_t));

			// get string
			paramName.resize(stringSize);
			cacheMicrocode->read(&paramName[0], stringSize);
		
			// get def
			cacheMicrocode->read( &def, sizeof(GpuConstantDefinition));

			mParametersMap.insert(GpuConstantDefinitionMap::value_type(paramName, def));
		}

		if (mDelegate)
		{
			// get sampler register mapping
			size_t samplerMapSize = 0;
			cacheMicrocode->read(&samplerMapSize, sizeof(size_t));
			for (size_t i = 0; i < samplerMapSize; ++i)
			{
				String paramName;
				size_t stringSize = 0;
				int reg = -1;

				cacheMicrocode->read(&stringSize, sizeof(size_t));
				paramName.resize(stringSize);
				cacheMicrocode->read(&paramName[0], stringSize);
				cacheMicrocode->read(&reg, sizeof(int));
			}

			// get input/output operations type
			cacheMicrocode->read(&mInputOp, sizeof(CGenum));
			cacheMicrocode->read(&mOutputOp, sizeof(CGenum));
		}

	}
Example #17
0
	LRESULT CALLBACK WGLWindow::MessageCallback(HWND handle, UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		WGLWindow* window = Yuni::UI::WGLWindow::FindWindow(handle);

		if (!window or !::IsWindowVisible(handle))
			return ::DefWindowProc(handle, uMsg, wParam, lParam);

		switch (uMsg)
		{
			case WM_PAINT:
			{
				window->refreshAndSwap();
				break;
			}

			case WM_MOUSEMOVE:
			{
				int x = GET_X_LPARAM(lParam);
				int y = GET_Y_LPARAM(lParam);
				window->doMouseMove(x, y);
				break;
			}

			case WM_ERASEBKGND:
			{
				// Do not erase background, this prevents flickering during move / resize.
				return 0;
			}

			// Input

			case WM_KEYDOWN:
			case WM_SYSKEYDOWN:
			{
				window->doKeyDown(ConvertInputKey(wParam));
				break;
			}

			case WM_KEYUP:
			case WM_SYSKEYUP:
			{
				window->doKeyUp(ConvertInputKey(wParam));
				break;
			}

			case WM_MOUSEHOVER:
			{
				int x = GET_X_LPARAM(lParam);
				int y = GET_Y_LPARAM(lParam);
				window->doMouseHover(x, y);
				break;
			}

			case WM_MOUSELEAVE:
			{
				window->doMouseLeave();
				break;
			}

			case WM_CHAR:
			{
				int nbChar = ::WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)&wParam, 1, nullptr, 0, nullptr, nullptr);
				if (nbChar < 1)
					return 0;
				char uniChar[nbChar + 1];
				nbChar = ::WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)&wParam, 1, uniChar, nbChar, nullptr, nullptr);
				if (nbChar < 1)
					return 0;
				uniChar[nbChar] = '\0';
				String str;
				str.resize((uint)(lParam & 0xFF) * (uint)nbChar);
				str.fill((char*)uniChar);
				window->doCharInput(str);
				return 0;
			}

			case WM_LBUTTONDOWN:
			{
				window->doMouseDown(Input::IMouse::ButtonLeft);
				break;
			}

			case WM_RBUTTONDOWN:
			{
				window->doMouseDown(Input::IMouse::ButtonRight);
				break;
			}

			case WM_MBUTTONDOWN:
			{
				window->doMouseDown(Input::IMouse::ButtonMiddle);
				break;
			}

			case WM_LBUTTONUP:
			{
				window->doMouseUp(Input::IMouse::ButtonLeft);
				break;
			}

			case WM_RBUTTONUP:
			{
				window->doMouseUp(Input::IMouse::ButtonRight);
				break;
			}

			case WM_MBUTTONUP:
			{
				window->doMouseUp(Input::IMouse::ButtonMiddle);
				break;
			}

			case WM_LBUTTONDBLCLK:
			{
				window->doMouseDblClick(Input::IMouse::ButtonLeft);
				break;
			}

			case WM_RBUTTONDBLCLK:
			{
				window->doMouseDblClick(Input::IMouse::ButtonRight);
				break;
			}

			case WM_MOUSEWHEEL:
			{
				window->doMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA);
				break;
			}

			// System

			case WM_SYSCOMMAND:
			{
				switch (wParam)
				{
					case SC_SCREENSAVE:
					case SC_MONITORPOWER:
						// Ignore screen saver and monitor power economy modes.
						return 0;
					case SC_MINIMIZE:
						window->pState = wsMinimized;
						break;
					case SC_MAXIMIZE:
					{
						// int width;
						// int height;
						// ::GetClientRect(&width, &height);
						// window->resize(width, height);
						window->pState = wsMaximized;
						break;
					}
					case SC_RESTORE:
						window->pState = wsNormal;
						break;
				}
				break;
			}

			// Close

			case WM_CLOSE:
			case WM_DESTROY:
			{
				window->kill();
				return 0;
			}

			// Move / Resize

			case WM_WINDOWPOSCHANGED:
			{
				WINDOWPOS* position = (WINDOWPOS*)lParam;
				window->move(position->x, position->y);
				break;
			}

			case WM_SIZE:
			{
				window->internalResize(LOWORD(lParam), HIWORD(lParam));
				break;
			}

			case WM_SIZING:
			{
				RECT* rect = (RECT*)lParam;
				window->internalResize(rect->right - rect->left, rect->bottom - rect->top);
				break;
			}

			case WM_GETMINMAXINFO:
			{
				MINMAXINFO* mmiStruct = (MINMAXINFO*)lParam;

				POINT ptPoint;

				// Minimum width of the window
				ptPoint.x = 300;
				// Minimum height of the window
				ptPoint.y = 200;
				mmiStruct->ptMinTrackSize = ptPoint;

				// Maximum width of the window
				ptPoint.x = ::GetSystemMetrics(SM_CXMAXIMIZED);
				// Maximum height of the window
				ptPoint.y = ::GetSystemMetrics(SM_CYMAXIMIZED);
				mmiStruct->ptMaxTrackSize = ptPoint;
				break;
			}

		} // End switch

		// Pass all unhandled messages to DefWindowProc
		return ::DefWindowProc(handle, uMsg, wParam, lParam);
	}
Example #18
0
void D2Item::parse(D2Data* data)
{
  int underscore = title.indexOf('_');
  if (underscore >= 0 && title.substr(0, underscore).isDigits())
    title.cut(0, underscore + 1);

  String desc = description;
  String gidInfo;
  int gidSep = desc.lastIndexOf('$');
  if (gidSep >= 0)
  {
    gidInfo = desc.substring(gidSep + 1);
    gid = atoi(gidInfo);
    desc.resize(gidSep);
  }
  Array<String> lines;
  desc.split(lines, "\\n");
  if (!lines.length())
    return;

  int ilvlSep = lines[0].lastIndexOf('(');
  if (ilvlSep >= 0)
  {
    itemLevel = atoi(lines[0].c_str() + ilvlSep + 1);
    lines[0].resize(ilvlSep);
    lines[0].trim();
  }
  while (!strncmp(lines[0], "\\xffc", 5))
  {
    colorCode = (lines[0][5] - '0');
    lines[0].cut(0, 6);
  }
  re::Prog remover("\\\\xffc[0-9:;<]");
  for (int i = 0; i < lines.length(); i++)
    lines[i] = remover.replace(lines[i], "");

  if (desc.find(data->getLocalizedString(5203)) >= 0)
    flags |= D2Item::fEthereal;
  if (desc.find(data->getLocalizedString(3455)) >= 0)
    flags |= D2Item::fUnidentified;

  if (!(flags & D2Item::fUnidentified) && (colorCode == 2 || colorCode == 4 || colorCode == 1))
    unique = data->getUniqueItem(lines[0]);
  if (!base && lines.length() > 1 && colorCode != 0 && colorCode != 3 && colorCode != 5)
    base = data->getBaseItem(lines[1]);
  if (!base && unique)
    base = unique->base;
  if (!base)
    base = data->getBaseItem(lines[0], true);
  if (!base)
    return;

  if (!unique && (flags & D2Item::fUnidentified))
  {
    unique = data->getUniqueByBase(base, colorCode);
    if (unique)
      title = String::format("[%s] %s", unique->name, base->name);
  }

  D2ItemType* info = base->type->getInfo();
  if (info)
  {
    type = info->type;
    subType = info->subType;
    quality = info->quality;
  }
  static int colorToQuality[] = {qNormal, qNormal, qSet, qMagic, qUnique, qNormal, 0, 0, qCrafted, qRare, 0, 0, 0};
  static int qualityToType[] = {tMisc, tWhite, tWhite, tWhite, tMagic, tSet, tRare, tUnique, tCrafted};
  if (quality < 0)
  {
    if (unique)
      quality = (unique->type == 6 ? qUnique : colorToQuality[unique->type]);
    else
      quality = colorToQuality[colorCode];
  }
  if (type == tAuto)
  {
    if (unique && unique->type == 6)
      type = tRuneword;
    else
      type = qualityToType[quality];
  }

  if (colorCode == 1)
  {
    if (unique)
      colorCode = (unique->type == 2 ? 2 : 4);
    // more broken detection?
  }

  if (!title.length())
  {
    title = lines[0];
    if (quality == D2Item::qSet || quality == D2Item::qRare ||
      quality == D2Item::qCrafted || quality == D2Item::qUnique)
      title = String::format("%s %s", lines[0], base->name);
  }

  if (!base || base->type->isType("rune") || base->type->isType("gem"))
    return;

  if (sockets.length())
  {
    Array<String> jewDesc;
    gidInfo.split(jewDesc, "\n\n");
    int curJew = 1;
    for (int sox = 0; sox < sockets.length(); sox++)
    {
      D2BaseItem* soxBase = data->getBaseByCode(sockets[sox]);
      if (!soxBase)
      {
        String tname(sockets[sox]);
        if (s_isdigit(tname[tname.length() - 1]))
        {
          tname.resize(tname.length() - 1);
          soxBase = data->getBaseByCode(tname);
        }
      }
      if (!soxBase)
        socketItems.push(NULL);
      else
      {
        D2Item* sock = new D2Item;
        sock->socketParent = this;
        sock->image = sockets[sox];
        sock->base = soxBase;
        if (soxBase->type->isType("jewl") && curJew < jewDesc.length())
          sock->description = jewDesc[curJew++];
        else
        {
          sock->title = soxBase->name;
          sock->description = soxBase->gemDesc;
        }
        sock->header = String::format("%s (Socketed)", header);
        sock->parse(data);
        socketItems.push(sock);
      }
    }
  }

  D2StatData* statData = data->getStatData();
  for (int i = 0; i < lines.length(); i++)
    statData->parse(stats, lines[i]);
  statText = statData->process(this);
}