Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utils: improve string methods #168

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

LAGonauta
Copy link

@LAGonauta LAGonauta commented Feb 17, 2025

This is a first of multiple PRs with fixes and some changes. I am cherry-picking changes from my multiple-changes branch.

This PR:

  1. Fix 2 KiB memory leak in the Log method
  2. Adds Narrow to Wide and Wide to Narrow method using codecvt

Instead of fixing the current implementation, I am migrating to C++ RAII style. I find it is easier to reason about.
Additionally, I understand that codecvt got deprecated in C++17, and will be removed in C++... 26 I think. But its interface is so much easier to use than MultiByteToWideChar and WideCharToMultiByte. I can modify the code to those Windows APIs if you prefer, though.
I do not modify the other implementation files to properly use the new methods yet, but that PR will come if this is approved.

Summary by CodeRabbit

  • New Features

    • Introduced flexible logging inputs and enhanced string conversion utilities for improved message handling.
  • Refactor

    • Streamlined logging and conversion processes to boost reliability, efficiency, and exception safety.
  • Chores

    • Updated build settings to adopt modern C++ standards across all configurations.

Copy link

coderabbitai bot commented Feb 17, 2025

Walkthrough

The changes update logging and string conversion utilities in the Utils namespace. Function signatures in both Utils.cpp and Utils.hpp have been modified to use std::string_view and const char* for safer, more efficient logging. New helper functions for converting between narrow and wide strings have been added, and mutex locking is now managed with std::unique_lock for exception safety. Additionally, the project file has been updated with C++17 settings, including new preprocessor definitions to silence deprecated header warnings and the addition of a language standard property.

Changes

File(s) Change Summary
Utils.cpp, Utils.hpp Updated logging: replaced LOG_LINES macro with a constexpr variable; modified Log() signature to use std::string_view and added an overload for const char*. Added helper functions NarrowToWideString and WideToNarrowString for string conversions; updated conversion functions for safety.
...moonlight-xbox-dx.vcxproj Modified preprocessor definitions to include _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING; added <LanguageStandard>stdcpp17</LanguageStandard> for multiple build configurations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Logger
    participant Conversion
    participant Mutex
    Client->>Logger: Call Log(message)
    Logger->>Mutex: Acquire lock with std::unique_lock
    Logger->>Conversion: Convert message via NarrowToWideString
    Conversion-->>Logger: Return wide string
    Logger->>PlatformLogging: Forward converted message for logging
    Mutex-->>Logger: Release lock
Loading

Poem

I'm a happy rabbit with a coding beat,
Hopping through changes both fast and neat.
From narrow to wide, my code's in tune,
Locks and logs under a modern moon.
In a C++17 garden where my projects bloom,
I hop with joy, banishing coding gloom!
🐰💻 Hop on, dear coder, let changes resume!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (12)
Utils.cpp (3)

4-10: Note on deprecated header usage.
The <codecvt> header is deprecated in C++17. Using it is acceptable for now but consider migrating to a more modern approach (e.g., Windows APIs MultiByteToWideChar/WideCharToMultiByte or other libraries) to ensure longer-term support.


24-28: Use safer formatting to avoid potential buffer overruns.
Although vsprintf_s is safer than vsprintf, consider switching to vsnprintf_s or checking the return value to reduce any residual risk if the log message exceeds 2047 characters.

- vsprintf_s(message.data(), message.size() - 1, fmt, list);
+ vsnprintf_s(message.data(), message.size(), _TRUNCATE, fmt, list);

74-78: Converting from wide to UTF-8 via <codecvt> is valid but deprecated.
Consider future-proofing by migrating off <codecvt>—especially since you’ve already added the suppression macro for deprecation warnings.

Utils.hpp (1)

36-37: Centralizing encoding conversions.
Introducing WideToNarrowString and NarrowToWideString clarifies the encoding workflow. Consider gradually phasing out <codecvt> if you need longer-term support.

moonlight-xbox-dx.vcxproj (8)

152-153: Suppressing <codecvt> deprecation for ARM Debug.
This resolves compilation warnings but does not address the root cause of deprecation. Consider replacing <codecvt> in future.


167-168: Suppressing <codecvt> deprecation for ARM Release.
Same note as with Debug configuration: explore alternate conversions to remove the suppression macro.


182-183: Suppressing <codecvt> deprecation for ARM64 Debug.
Consistency maintained across all configurations. Replacing <codecvt> eventually will remove the need for repeated suppression macros.


197-198: Suppressing <codecvt> deprecation for ARM64 Release.
Same rationale applies: consider migrating to modern string conversion APIs.


212-213: Suppressing <codecvt> deprecation for Win32 Debug.
Keep caution: these macros might hide legitimate warnings if you switch to a non-deprecated method in the future.


227-228: Suppressing <codecvt> deprecation for Win32 Release.
Again, consistent approach, but a thorough replacement of <codecvt> remains advisable.


242-243: Suppressing <codecvt> deprecation for x64 Debug.
Your code remains portable for now, but note that <codecvt> might be removed in a future standard.


257-258: Suppressing <codecvt> deprecation for x64 Release.
Same recommendation applies: consider a more future-proof approach than std::wstring_convert.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4edf77e and 435882c.

📒 Files selected for processing (3)
  • Utils.cpp (2 hunks)
  • Utils.hpp (1 hunks)
  • moonlight-xbox-dx.vcxproj (8 hunks)
🔇 Additional comments (7)
Utils.cpp (5)

48-52: Overloading with const char* is a good approach.
This implementation routes const char* logs into the main std::string_view overload, which helps avoid code duplication.


58-64: Null handling is consistent and safe.
Returning nullptr appropriately mirrors a null input to avoid throwing an exception. This is a good defensive pattern in interop methods.


66-68: Efficient conversion from std::string to Platform::String^.
The call to NarrowToWideString is straightforward, ensuring minimal overhead for the conversion.


70-73: Direct conversion to UTF-8.
Using WideToNarrowString for converting Platform::String^ to std::string centralizes logic and prevents duplicate code paths.


79-82: Symmetrical approach for string conversions.
Using NarrowToWideString in tandem with WideToNarrowString is consistent and helps reduce confusion around Unicode conversions.

Utils.hpp (2)

29-30: Good overload design for Log.
Having both Log(const char* msg) and Log(const std::string_view& msg) maximizes convenience and consistency.


33-33: Changing to const char* is a safer interface.
Preventing callers from modifying the buffer is beneficial for function clarity and correctness.

Comment on lines +31 to +46
void Log(const std::string_view& msg) {
try {
if (fmt == nullptr || fmt == NULL)return;
int len = strlen(fmt) + 1;
wchar_t* stringBuf = (wchar_t*)malloc(sizeof(wchar_t) * len);
if (stringBuf == NULL)return;
mbstowcs(stringBuf, fmt, len);
std::wstring string(stringBuf);
logMutex.lock();
if (logLines.size() == LOG_LINES)logLines.erase(logLines.begin());
logLines.push_back(string);
logMutex.unlock();
OutputDebugStringA(fmt);
std::wstring string = NarrowToWideString(msg);
{
std::unique_lock<std::mutex> lk(logMutex);
if (logLines.size() == LOG_LINES) {
logLines.erase(logLines.begin());
}
logLines.push_back(string);
}
OutputDebugString(string.c_str());
}
catch (...){
catch (...) {

}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid catching and ignoring all exceptions silently.
Swallowing exceptions completely may mask underlying issues. Log or otherwise handle exceptions within the catch block to ensure you can diagnose errors when they happen (e.g., logging error details).

try {
    ...
}
catch (...) {
- // currently doing nothing
+ // Possible improvement:
+ OutputDebugString(L"An exception occurred in Log()\n");
}

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant