Example #1
0
RWConfig GameBase::buildConfig(const std::optional<RWArgConfigLayer> &args) {
    RWConfig config;
    if (args.has_value()) {
        config.setLayer(RWConfig::LAYER_ARGUMENT, *args);
    }
    auto defaultLayer = buildDefaultConfigLayer();
    config.setLayer(RWConfig::LAYER_DEFAULT, defaultLayer);

    rwfs::path configPath;
    if (args.has_value() && args->configPath.has_value()) {
        configPath = *args->configPath;
    } else {
        configPath = RWConfigParser::getDefaultConfigPath() / "openrw.ini";
    }

    if ((!args) || (args && !args->noconfig)) {
        RWConfigParser configParser{};
        auto [configLayer, parseResult] = configParser.loadFile(configPath);

        if (!parseResult.isValid()) {
            log.error("Config", "Could not read configuation file at " + configPath.string());
            throw std::runtime_error(parseResult.what());
        }
        config.unknown = parseResult.getUnknownData();
        config.setLayer(RWConfig::LAYER_CONFIGFILE, configLayer);
    }
Example #2
0
void WebSocketChannel::didReceiveSocketStreamData(SocketStreamHandle& handle, const char* data, std::optional<size_t> len)
{
    if (len)
        LOG(Network, "WebSocketChannel %p didReceiveSocketStreamData() Received %zu bytes", this, len.value());
    else
        LOG(Network, "WebSocketChannel %p didReceiveSocketStreamData() Received no bytes", this);
    Ref<WebSocketChannel> protectedThis(*this); // The client can close the channel, potentially removing the last reference.
    ASSERT(&handle == m_handle);
    if (!m_document) {
        return;
    }
    if (!len || !len.value()) {
        handle.disconnect();
        return;
    }
    if (!m_client) {
        m_shouldDiscardReceivedData = true;
        handle.disconnect();
        return;
    }
    if (m_shouldDiscardReceivedData)
        return;
    if (!appendToBuffer(data, len.value())) {
        m_shouldDiscardReceivedData = true;
        fail("Ran out of memory while receiving WebSocket data.");
        return;
    }
    while (!m_suspended && m_client && !m_buffer.isEmpty()) {
        if (!processBuffer())
            break;
    }
}
Example #3
0
void MemoryObjectStore::getAllRecords(const IDBKeyRangeData& keyRangeData, std::optional<uint32_t> count, IndexedDB::GetAllType type, IDBGetAllResult& result) const
{
    result = { type };

    uint32_t targetCount;
    if (count && count.value())
        targetCount = count.value();
    else
        targetCount = std::numeric_limits<uint32_t>::max();

    IDBKeyRangeData range = keyRangeData;
    uint32_t currentCount = 0;
    while (currentCount < targetCount) {
        IDBKeyData key = lowestKeyWithRecordInRange(range);
        if (key.isNull())
            return;

        range.lowerKey = key;
        range.lowerOpen = true;

        if (type == IndexedDB::GetAllType::Keys)
            result.addKey(WTFMove(key));
        else
            result.addValue(valueForKey(key));

        ++currentCount;
    }
}
Example #4
0
// Routine Description:
// - Remaps all of the stored items to new coordinate positions
//   based on a bulk rearrangement of row IDs and potential row width resize.
// Arguments:
// - rowMap - A map of the old row IDs to the new row IDs.
// - width - The width of the new row. Remove any items that are beyond the row width.
//         - Use nullopt if we're not resizing the width of the row, just renumbering the rows.
void UnicodeStorage::Remap(const std::map<SHORT, SHORT>& rowMap, const std::optional<SHORT> width)
{
    // Make a temporary map to hold all the new row positioning
    std::unordered_map<key_type, mapped_type> newMap;

    // Walk through every stored item.
    for (const auto& pair : _map)
    {
        // Extract the old coordinate position
        const auto oldCoord = pair.first;

        // Only try to short-circuit based on width if we were told it changed
        // by being given a new width value.
        if (width.has_value())
        {
            // Get the column ID
            const auto oldColId = oldCoord.X;

            // If the column index is at/beyond the row width, don't bother copying it to the new map.
            if (oldColId >= width.value())
            {
                continue;
            }
        }

        // Get the row ID from the position as that's what we need to remap
        const auto oldRowId = oldCoord.Y;

        // Use the mapping given to convert the old row ID to the new row ID
        const auto mapIter = rowMap.find(oldRowId);

        // If there's no mapping to a new row, don't bother copying it to the new map. The row is gone.
        if (mapIter == rowMap.end())
        {
            continue;
        }

        const auto newRowId = mapIter->second;

        // Generate a new coordinate with the same X as the old one, but a new Y value.
        const auto newCoord = COORD{ oldCoord.X, newRowId };

        // Put the adjusted coordinate into the map with the original value.
        newMap.emplace(newCoord, pair.second);
    }

    // Swap into the stored map, free the temporary when we exit.
    _map.swap(newMap);
}
Example #5
0
    std::optional<NodeIndex_t> Model::FindFirstNode(char const* name, std::optional<NodeIndex_t> const& parentNodeIndex) const
    {
        // Children are guaranteed to come after their parents, so start looking after the parent index if one is provided.
        const NodeIndex_t startIndex = parentNodeIndex ? parentNodeIndex.value() + 1 : Pbr::RootNodeIndex;
        for (const Pbr::Node& node : m_nodes)
        {
            if ((!parentNodeIndex || node.ParentNodeIndex == parentNodeIndex.value()) &&
                node.Name == name)
            {
                return node.Index;
            }
        }

        return {};
    }
Example #6
0
void CachedResource::setLoadPriority(const std::optional<ResourceLoadPriority>& loadPriority)
{
    if (loadPriority)
        m_loadPriority = loadPriority.value();
    else
        m_loadPriority = defaultPriorityForResourceType(type());
}
Example #7
0
        game_value remote_exec(const game_value &params_, sqf_string_const_ref function_, std::variant<int, object, sqf_string_const_ref_wrapper, side, group, std::reference_wrapper<const std::vector<game_value>>> targets_, std::optional<std::variant<sqf_string_const_ref_wrapper, bool, object, group>> jip_) {
            game_value targets;
            game_value jip;
            switch (targets_.index()) {
            case 0: targets = static_cast<float>(std::get<int>(targets_)); break;
            case 1: targets = std::get<object>(targets_); break;
            case 2: targets = std::get<2>(targets_).get(); break;
            case 3: targets = std::get<side>(targets_); break;
            case 4: targets = std::get<group>(targets_); break;
            case 5: targets = std::move(auto_array<game_value>({ std::get<5>(targets_).get().begin(), std::get<5>(targets_).get().end() })); break;
            }

            if (jip_.has_value()) {
                switch ((*jip_).index()) {
                case 0: jip = std::get<0>(*jip_).get(); break;
                case 1: jip = std::get<bool>(*jip_); break;
                case 2: jip = std::get<object>(*jip_); break;
                case 3: jip = std::get<group>(*jip_); break;
                }
            }
            game_value params_right = game_value({
                function_,
                targets,
                jip
            });

            return host::functions.invoke_raw_binary(__sqf::binary__remoteexec__any__array__ret__any, params_, params_right);
        }
Example #8
0
            bvres_t update() override
            {
                if(!m_done_res.has_value()){
                    m_timer.reset();
                }

                if(!m_done_res.has_value() || m_done_res.value() == BV_PENDING){
                    m_done_res.emplace(m_operation->update());
                    switch(auto op_status = m_done_res.value()){
                        case BV_ABORT:
                        case BV_PENDING:
                            {
                                return op_status;
                            }
                        case BV_FAILURE:
                        case BV_SUCCESS:
                            {
                                break;
                            }
                        default:
                            {
                                throw std::runtime_error(str_fflprintf(": Invalid node status: %d", op_status));
                            }
                    }
                }

                if(m_timer.diff_msec() > m_slowdown){
                    return m_done_res.value();
                }else{
                    return BV_PENDING;
                }
            }
Example #9
0
	static void make_vt_attributes(const FarColor& Attributes, string& Str, std::optional<FarColor> const& LastColor)
	{
		append(Str, L"\033["sv);

		if (Attributes.IsFg4Bit())
		{
			append(Str, Attributes.ForegroundColor & FOREGROUND_INTENSITY? L'9' : L'3', vt_color_index(Attributes.ForegroundColor));
		}
		else
		{
			const auto& c = Attributes.ForegroundRGBA;
			Str += format(L"38;2;{0};{1};{2}"sv, c.r, c.g, c.b);
		}

		Str += L';';

		if (Attributes.IsBg4Bit())
		{
			append(Str, Attributes.BackgroundColor & FOREGROUND_INTENSITY? L"10"sv : L"4"sv, vt_color_index(Attributes.BackgroundColor));
		}
		else
		{
			const auto& c = Attributes.BackgroundRGBA;
			Str += format(L"48;2;{0};{1};{2}"sv, c.r, c.g, c.b);
		}

		if (Attributes.Flags & FCF_FG_UNDERLINE)
		{
			if (!LastColor.has_value() || !(LastColor->Flags & FCF_FG_UNDERLINE))
				Str += L";4"sv;
		}
		else
		{
			if (LastColor.has_value() && LastColor->Flags & FCF_FG_UNDERLINE)
				Str += L";24"sv;
		}

		Str += L'm';
	}
Example #10
0
	static void make_vt_sequence(span<const FAR_CHAR_INFO> Input, string& Str, std::optional<FarColor>& LastColor)
	{
		for (const auto& i: Input)
		{
			if (!LastColor.has_value() || i.Attributes != *LastColor)
			{
				make_vt_attributes(i.Attributes, Str, LastColor);
				LastColor = i.Attributes;
			}

			Str += ReplaceControlCharacter(i.Char);
		}
	}
Example #11
0
SchedulerCPU::ProducedCommands SchedulerCPU::ExecuteNode(GraphicsTask& task, std::optional<ProducedCommands>& inherited, const FrameContextEx& context) {
	// Inherit command list, if available.
	std::unique_ptr<BasicCommandList> inheritedCommandList;
	std::unique_ptr<VolatileViewHeap> inheritedVheap;
	if (inherited) {
		inheritedCommandList = std::move(inherited->list);
		inheritedVheap = std::move(inherited->vheap);
		inherited.reset();
	}

	// Execute given node.
	auto vheap = std::make_unique<VolatileViewHeap>(context.gxApi);
	RenderContext renderContext(context.memoryManager,
								context.textureSpace,
								context.shaderManager,
								context.gxApi,
								context.commandListPool,
								context.commandAllocatorPool,
								context.scratchSpacePool,
								std::move(inheritedCommandList),
								std::move(inheritedVheap));
	renderContext.SetCommandListName(typeid(task).name());
	task.Execute(renderContext);

	// Get inherited and current list, if any.
	std::unique_ptr<BasicCommandList> currentCommandList;
	std::unique_ptr<VolatileViewHeap> currentVheap;
	renderContext.Decompose(inheritedCommandList, currentCommandList, currentVheap);

	if (inheritedCommandList) {
		inherited = ProducedCommands{ std::move(inheritedCommandList), nullptr };
	}
	else {
		inherited.reset();
	}

	return { std::move(currentCommandList), std::move(currentVheap) };
}
Example #12
0
ExceptionOr<int> CSSStyleSheet::addRule(const String& selector, const String& style, std::optional<unsigned> index)
{
    StringBuilder text;
    text.append(selector);
    text.appendLiteral(" { ");
    text.append(style);
    if (!style.isEmpty())
        text.append(' ');
    text.append('}');
    auto insertRuleResult = insertRule(text.toString(), index.value_or(length()));
    if (insertRuleResult.hasException())
        return insertRuleResult.releaseException();
    
    // As per Microsoft documentation, always return -1.
    return -1;
}
void FileBasedBenchmarkItemRunner::_parse_query_file(
    const std::filesystem::path& query_file_path, const std::optional<std::unordered_set<std::string>>& query_subset) {
  std::ifstream file(query_file_path);

  // The names of queries from, e.g., "queries/TPCH-7.sql" will be prefixed with "TPCH-7."
  const auto item_name_prefix = query_file_path.stem().string();

  std::string content{std::istreambuf_iterator<char>(file), {}};

  /**
   * A file can contain multiple SQL statements, and each statement may cover one or more lines.
   * We use the SQLParser to split up the content of the file into the individual SQL statements.
   */

  hsql::SQLParserResult parse_result;
  hsql::SQLParser::parse(content, &parse_result);
  Assert(parse_result.isValid(), create_sql_parser_error_message(content, parse_result));

  std::vector<Query> queries_in_file{parse_result.size()};

  size_t sql_string_offset{0u};
  for (auto statement_idx = size_t{0}; statement_idx < parse_result.size(); ++statement_idx) {
    const auto item_name = item_name_prefix + '.' + std::to_string(statement_idx);
    const auto statement_string_length = parse_result.getStatement(statement_idx)->stringLength;
    const auto statement_string = boost::trim_copy(content.substr(sql_string_offset, statement_string_length));
    sql_string_offset += statement_string_length;
    queries_in_file[statement_idx] = {item_name, statement_string};
  }

  // Remove ".0" from the end of the query name if there is only one file
  if (queries_in_file.size() == 1) {
    queries_in_file.front().name.erase(queries_in_file.front().name.end() - 2, queries_in_file.front().name.end());
  }

  /**
   * Add queries to _queries and _item_names, if query_subset allows it
   */
  for (const auto& query : queries_in_file) {
    if (!query_subset || query_subset->count(query.name)) {
      _queries.emplace_back(query);
    }
  }
}
Example #14
0
    // Method Description:
    // - Open a new tab. This will create the TerminalControl hosting the
    //      terminal, and add a new Tab to our list of tabs. The method can
    //      optionally be provided a profile index, which will be used to create
    //      a tab using the profile in that index.
    //      If no index is provided, the default profile will be used.
    // Arguments:
    // - profileIndex: an optional index into the list of profiles to use to
    //      initialize this tab up with.
    void App::_OpenNewTab(std::optional<int> profileIndex)
    {
        GUID profileGuid;

        if (profileIndex)
        {
            const auto realIndex = profileIndex.value();
            const auto profiles = _settings->GetProfiles();

            // If we don't have that many profiles, then do nothing.
            if (realIndex >= profiles.size())
            {
                return;
            }

            const auto& selectedProfile = profiles[realIndex];
            profileGuid = selectedProfile.GetGuid();
        }
        else
        {
            // Getting Guid for default profile
            const auto globalSettings = _settings->GlobalSettings();
            profileGuid = globalSettings.GetDefaultProfile();
        }

        TerminalSettings settings = _settings->MakeSettings(profileGuid);
        _CreateNewTabFromSettings(profileGuid, settings);

        const int tabCount = static_cast<int>(_tabs.size());
        TraceLoggingWrite(
            g_hTerminalAppProvider, // handle to TerminalApp tracelogging provider
            "TabInformation",
            TraceLoggingDescription("Event emitted upon new tab creation in TerminalApp"),
            TraceLoggingInt32(tabCount, "TabCount", "Count of tabs curently opened in TerminalApp"),
            TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
            TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
    }
Example #15
0
RefPtr<CryptoKeyRSA> CryptoKeyRSA::importJwk(CryptoAlgorithmIdentifier algorithm, std::optional<CryptoAlgorithmIdentifier> hash, JsonWebKey&& keyData, bool extractable, CryptoKeyUsageBitmap usages)
{
    if (keyData.kty != "RSA")
        return nullptr;
    if (keyData.usages && ((keyData.usages & usages) != usages))
        return nullptr;
    if (keyData.ext && !keyData.ext.value() && extractable)
        return nullptr;

    if (!keyData.n || !keyData.e)
        return nullptr;
    Vector<uint8_t> modulus;
    if (!WTF::base64URLDecode(keyData.n.value(), modulus))
        return nullptr;
    // Per RFC 7518 Section 6.3.1.1: https://tools.ietf.org/html/rfc7518#section-6.3.1.1
    if (!modulus[0])
        modulus.remove(0);
    Vector<uint8_t> exponent;
    if (!WTF::base64URLDecode(keyData.e.value(), exponent))
        return nullptr;
    if (!keyData.d) {
        // import public key
        auto publicKeyComponents = CryptoKeyDataRSAComponents::createPublic(WTFMove(modulus), WTFMove(exponent));
        // Notice: CryptoAlgorithmIdentifier::SHA_1 is just a placeholder. It should not have any effect if hash is std::nullopt.
        return CryptoKeyRSA::create(algorithm, hash.value_or(CryptoAlgorithmIdentifier::SHA_1), !!hash, *publicKeyComponents, extractable, usages);
    }

    // import private key
    Vector<uint8_t> privateExponent;
    if (!WTF::base64URLDecode(keyData.d.value(), privateExponent))
        return nullptr;
    if (!keyData.p && !keyData.q && !keyData.dp && !keyData.dp && !keyData.qi) {
        auto privateKeyComponents = CryptoKeyDataRSAComponents::createPrivate(WTFMove(modulus), WTFMove(exponent), WTFMove(privateExponent));
        // Notice: CryptoAlgorithmIdentifier::SHA_1 is just a placeholder. It should not have any effect if hash is std::nullopt.
        return CryptoKeyRSA::create(algorithm, hash.value_or(CryptoAlgorithmIdentifier::SHA_1), !!hash, *privateKeyComponents, extractable, usages);
    }

    if (!keyData.p || !keyData.q || !keyData.dp || !keyData.dq || !keyData.qi)
        return nullptr;
    CryptoKeyDataRSAComponents::PrimeInfo firstPrimeInfo;
    CryptoKeyDataRSAComponents::PrimeInfo secondPrimeInfo;
    if (!WTF::base64URLDecode(keyData.p.value(), firstPrimeInfo.primeFactor))
        return nullptr;
    if (!WTF::base64URLDecode(keyData.dp.value(), firstPrimeInfo.factorCRTExponent))
        return nullptr;
    if (!WTF::base64URLDecode(keyData.q.value(), secondPrimeInfo.primeFactor))
        return nullptr;
    if (!WTF::base64URLDecode(keyData.dq.value(), secondPrimeInfo.factorCRTExponent))
        return nullptr;
    if (!WTF::base64URLDecode(keyData.qi.value(), secondPrimeInfo.factorCRTCoefficient))
        return nullptr;
    if (!keyData.oth) {
        auto privateKeyComponents = CryptoKeyDataRSAComponents::createPrivateWithAdditionalData(WTFMove(modulus), WTFMove(exponent), WTFMove(privateExponent), WTFMove(firstPrimeInfo), WTFMove(secondPrimeInfo), { });
        // Notice: CryptoAlgorithmIdentifier::SHA_1 is just a placeholder. It should not have any effect if hash is std::nullopt.
        return CryptoKeyRSA::create(algorithm, hash.value_or(CryptoAlgorithmIdentifier::SHA_1), !!hash, *privateKeyComponents, extractable, usages);
    }

    Vector<CryptoKeyDataRSAComponents::PrimeInfo> otherPrimeInfos;
    for (auto value : keyData.oth.value()) {
        CryptoKeyDataRSAComponents::PrimeInfo info;
        if (!WTF::base64URLDecode(value.r, info.primeFactor))
            return nullptr;
        if (!WTF::base64URLDecode(value.d, info.factorCRTExponent))
            return nullptr;
        if (!WTF::base64URLDecode(value.t, info.factorCRTCoefficient))
            return nullptr;
        otherPrimeInfos.append(info);
    }

    auto privateKeyComponents = CryptoKeyDataRSAComponents::createPrivateWithAdditionalData(WTFMove(modulus), WTFMove(exponent), WTFMove(privateExponent), WTFMove(firstPrimeInfo), WTFMove(secondPrimeInfo), WTFMove(otherPrimeInfos));
    // Notice: CryptoAlgorithmIdentifier::SHA_1 is just a placeholder. It should not have any effect if hash is std::nullopt.
    return CryptoKeyRSA::create(algorithm, hash.value_or(CryptoAlgorithmIdentifier::SHA_1), !!hash, *privateKeyComponents, extractable, usages);
}
Example #16
0
        task create_simple_task(const object &unit_, sqf_string_const_ref name_, std::optional<task> parent_task_) {
            game_value params_right(parent_task_.has_value() ? game_value{ name_, *parent_task_ } : game_value{ name_ });

            return host::functions.invoke_raw_binary(__sqf::binary__createsimpletask__object__array__ret__task, unit_, params_right);
        }
Example #17
0
 void reset() override
 {
     m_done_res.reset();
     m_operation->reset();
 }
Example #18
0
		bool Element::cursorIsOver(std::optional<Vector2i> cursorPosition) const
		{
			return cursorPosition && bounds.contains(cursorPosition.value());
		}