Skip to content

Commit

Permalink
windows/serialInterface: Began building a RAII helper type for intera…
Browse files Browse the repository at this point in the history
…cting with the Windows registry
  • Loading branch information
dragonmux committed Oct 31, 2023
1 parent da01575 commit ff9c82c
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/windows/serialInterface.cxx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-FileCopyrightText: 2023 1BitSquared <info@1bitsquared.com>
// SPDX-FileContributor: Written by Rachel Mant <git@dragonmux.network>
#include <substrate/console>
#include "windows/serialInterface.hxx"
#include "bmp.hxx"

using substrate::console;

[[nodiscard]] std::string serialForDevice(const usbDevice_t &device)
{
const auto serialIndex{device.serialNumberIndex()};
Expand All @@ -13,6 +16,51 @@
return handle.readStringDescriptor(serialIndex);
}

void displayError(const LSTATUS error, const std::string_view operation, const std::string_view path)
{
char *message{nullptr};
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, nullptr);
console.error("Failed to "sv, operation, ' ', path, ", got error "sv, asHex_t<8, '0'>{uint32_t(error)},
": "sv, message);
LocalFree(message);
}

struct hklmRegistryKey_t
{
private:
HKEY handle{static_cast<HKEY>(INVALID_HANDLE_VALUE)};

public:
hklmRegistryKey_t() noexcept = default;
hklmRegistryKey_t(const hklmRegistryKey_t &) = delete;
hklmRegistryKey_t operator =(const hklmRegistryKey_t &) = delete;

hklmRegistryKey_t(const std::string &path, const REGSAM permissions) :
handle
{
[&]()
{
auto keyHandle{static_cast<HKEY>(INVALID_HANDLE_VALUE)};
if (const auto result{RegOpenKeyEx(HKEY_LOCAL_MACHINE, path.c_str(), 0, permissions, &keyHandle)};
result != ERROR_SUCCESS)
{
displayError(result, "open registry key"sv, path);
return static_cast<HKEY>(INVALID_HANDLE_VALUE);
}
return keyHandle;
}()
} { }

~hklmRegistryKey_t() noexcept
{
if (handle != INVALID_HANDLE_VALUE)
RegCloseKey(handle);
}

[[nodiscard]] bool valid() const noexcept { return handle != INVALID_HANDLE_VALUE; }
};

serialInterface_t::serialInterface_t(const usbDevice_t &usbDevice)
{
}
Expand Down

0 comments on commit ff9c82c

Please sign in to comment.