From 9c0c8c05479e2296c6105685208f23b83bf0811e Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 16:53:47 +0100 Subject: [PATCH 1/2] Host code's types as the chapter Types asks (OIL 41) No assignment or second side effect stands in a condition any more (T-14): the hosts accept in a loop that declares what it accepted, the link finds each line end in a statement of its own, and the setup of a listener, a serial port and a WebSocket client is a named step per call. A variable stands where it is first needed, and the length field of a WebSocket frame and its payload's length are two (T-13). Conditions and sums of several parts are named steps (T-18), a range-for names its element's type (T-8), and the count of lit LEDs in DocuPictures is a uint16_t, as all 256 would wrap a byte (T-1). The control program's stroke rounds with integers as lround() did, without its double (H-7). The library and its sizes do not change. --- OIL.md | 14 ++++++++++ control/ControlDotPanel.cpp | 38 ++++++++++++++++++-------- control/ControlLink.cpp | 23 ++++++++-------- control/ControlSerialPort.cpp | 10 +++---- control/ControlStream.h | 3 +- control/ControlTcpPort.cpp | 5 ++-- control/ControlWindow.cpp | 19 +++++++------ docu/DocuPictures.cpp | 35 +++++++++++++++--------- simulator/Avr/SimulatorAvr.cpp | 3 +- simulator/Host/SimulatorSerialHost.cpp | 15 ++++++---- simulator/Host/SimulatorSocket.cpp | 12 ++++---- simulator/Host/SimulatorWebHost.cpp | 17 +++++++----- simulator/Host/SimulatorWebSocket.cpp | 38 ++++++++++++++++---------- simulator/SimulatorOptions.cpp | 7 +++-- simulator/SimulatorPanel.cpp | 2 +- 15 files changed, 151 insertions(+), 90 deletions(-) diff --git a/OIL.md b/OIL.md index d29c37c..1072068 100644 --- a/OIL.md +++ b/OIL.md @@ -1219,6 +1219,20 @@ condition of three parts in `CheckFont()` and a sum in that of `CharShiftTask()` in every variant, every example 8 bytes of flash smaller, Shutdown 12 and SerialControl 22; the same RAM. +As built for the host code: no assignment or second side effect stands in a condition any more +(T-14): the hosts accept in a loop that declares what it accepted, `ControlLink::Task()` finds +each line end in a statement of its own, and the setup of a listener, of a serial port and of a +WebSocket client is a named step per call; `SimulatorAvr` counts a bit before it compares. A +variable stands where it is first needed (T-13), the length field of a WebSocket frame and the +length of its payload are two, and a chunk is made only after the guard that may return. A +condition or sum of several parts is named steps (T-18): where a frame's payload starts and ends, +a port's text and range, how long a picture is waited for, a module's pitch in the pictures. A +range-`for` names its element's type (T-8), and the counter of lit LEDs in `DocuPictures` is a +`uint16_t`, as all 256 would wrap a byte (T-1). The control program's stroke rounds with integers +as `lround()` did, which takes its `double` (H-7). Left for the compiler that is not in the dev +container: the Windows half of the serial port declares some variables ahead, which only got +their initializers here. + ### 42 A newer avr-gcc as a cross-check `max_matrix::Byte` (41) made the examples 30 to 50 bytes of flash larger on the Uno at first, diff --git a/control/ControlDotPanel.cpp b/control/ControlDotPanel.cpp index 654e944..d67769a 100644 --- a/control/ControlDotPanel.cpp +++ b/control/ControlDotPanel.cpp @@ -12,7 +12,6 @@ #include "ControlDotPanel.h" -#include #include #include #include @@ -38,6 +37,23 @@ constexpr int kLed{14}; constexpr int kModuleGap{8}; constexpr int kMargin{6}; +/* where a stroke is between two LEDs: `step` of `steps` */ +struct StrokeStep { + int16_t step; + int16_t steps; +}; + +// Returns how far a stroke has come by `at` on its way by `delta`, in LEDs, +// rounded to the nearest, a half away from its start, as lround() rounded it +// before the double went (H-7). +int16_t GetStrokeOffset(int16_t delta, StrokeStep at) { + int32_t const travelled{static_cast(delta) * at.step}; + int32_t const half{at.steps / 2}; + int32_t const rounded{(travelled >= 0) ? ((travelled + half) / at.steps) + : -((half - travelled) / at.steps)}; + return static_cast(rounded); +} + } // namespace /* ControlDotPanel colours: the red of the common modules, and the board behind @@ -90,6 +106,7 @@ void ControlDotPanel::OnPaint(wxPaintEvent& /* event */) { wxCoord const led{FromDIP(kLed)}; wxCoord const gap{FromDIP(kModuleGap)}; wxCoord const margin{FromDIP(kMargin)}; + wxCoord const inset{(cell - led) / 2}; dc.SetBackground(wxBrush(CONTROL_DOT_PANEL_BOARD)); dc.Clear(); @@ -97,10 +114,9 @@ void ControlDotPanel::OnPaint(wxPaintEvent& /* event */) { for (uint8_t row{0}; row < max_matrix::kRowNumberOfModule; row++) { for (uint8_t column{0}; column < kControlNumberOfColumns; column++) { bool const lit{IsLit(column, row)}; - wxCoord const x{margin + (column * cell) + - ((column / max_matrix::kColumnNumberOfModule) * gap) + - ((cell - led) / 2)}; - wxCoord const y{margin + (row * cell) + ((cell - led) / 2)}; + wxCoord const gaps{(column / max_matrix::kColumnNumberOfModule) * gap}; + wxCoord const x{margin + (column * cell) + gaps + inset}; + wxCoord const y{margin + (row * cell) + inset}; if (!IsEnabled()) { dc.SetBrush(wxBrush(CONTROL_DOT_PANEL_DISABLED)); } else { @@ -160,12 +176,12 @@ void ControlDotPanel::OnMotion(wxMouseEvent& event) { int16_t const steps{ static_cast(std::max(abs(delta_column), abs(delta_row)))}; for (int16_t step{1}; step < steps; step++) { - PaintDot(static_cast( - last_column_ + - lround(static_cast(delta_column) * step / steps)), - static_cast( - last_row_ + - lround(static_cast(delta_row) * step / steps))); + StrokeStep const at{step, steps}; + auto const column_on_the_way{static_cast( + last_column_ + GetStrokeOffset(delta_column, at))}; + auto const row_on_the_way{ + static_cast(last_row_ + GetStrokeOffset(delta_row, at))}; + PaintDot(column_on_the_way, row_on_the_way); } } PaintDot(column, row); diff --git a/control/ControlLink.cpp b/control/ControlLink.cpp index 0a3f7a1..c62f37c 100644 --- a/control/ControlLink.cpp +++ b/control/ControlLink.cpp @@ -43,14 +43,13 @@ bool ControlLink::Send(std::string const& line) { // The time is compared as a difference, so that a clock that runs past 2^32 ms // keeps working. void ControlLink::AskForPicture(uint32_t now) { - uint32_t const waited{now - picture_asked_at_}; - if (!IsReady()) { return; } - if (picture_timed_ && - (waited < (picture_asked_ ? kControlLinkPictureTimeoutMs - : kControlLinkPictureIntervalMs))) { + uint32_t const waited{now - picture_asked_at_}; + uint32_t const wait_for{picture_asked_ ? kControlLinkPictureTimeoutMs + : kControlLinkPictureIntervalMs}; + if (picture_timed_ && (waited < wait_for)) { return; } if (!port_.get().Write(ControlCommand::MakePicture() + "\n")) { @@ -63,7 +62,6 @@ void ControlLink::AskForPicture(uint32_t now) { } ControlLinkLines ControlLink::Task() { - size_t end{0}; ControlLinkLines read{false, std::vector{}}; if (!port_.get().IsOpen()) { @@ -71,12 +69,15 @@ ControlLinkLines ControlLink::Task() { } read.open = port_.get().Read(received_); - while (((end = received_.find('\n')) != std::string::npos) || - (received_.size() >= kControlLinkMaxLineLength)) { - size_t const length{(end != std::string::npos) ? end - : kControlLinkMaxLineLength}; + for (;;) { + size_t const end{received_.find('\n')}; + bool const has_end{end != std::string::npos}; + if (!has_end && (received_.size() < kControlLinkMaxLineLength)) { + break; + } + size_t const length{has_end ? end : kControlLinkMaxLineLength}; std::string line = received_.substr(0, length); - received_.erase(0, (end != std::string::npos) ? (end + 1) : length); + received_.erase(0, has_end ? (end + 1) : length); if (!line.empty() && (line.back() == '\r')) { line.pop_back(); } diff --git a/control/ControlSerialPort.cpp b/control/ControlSerialPort.cpp index cdbdc2c..79453d0 100644 --- a/control/ControlSerialPort.cpp +++ b/control/ControlSerialPort.cpp @@ -142,7 +142,7 @@ bool ControlSerialPort::Write(std::string const& data) { } bool ControlSerialPort::Read(std::string& data) { - std::array chunk; + std::array chunk{}; DWORD const size = static_cast(chunk.size()); DWORD length = size; @@ -218,8 +218,8 @@ bool ControlSerialPort::Configure(uint32_t baud_rate) { termios settings{}; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): POSIX's ioctl() - bool const taken{(ioctl(descriptor_, TIOCEXCL) == 0) && - (tcgetattr(descriptor_, &settings) == 0)}; + bool const taken{ioctl(descriptor_, TIOCEXCL) == 0}; + bool const read{taken && (tcgetattr(descriptor_, &settings) == 0)}; cfmakeraw(&settings); max_matrix::Bit::SetBits(settings.c_cflag, kLocalReceive); max_matrix::Bit::ClearBits(settings.c_cflag, kTwoStopsHandshake); @@ -227,8 +227,8 @@ bool ControlSerialPort::Configure(uint32_t baud_rate) { settings.c_cc[VTIME] = 0; // glibc's cfsetspeed() takes a rate as its number as well as its B constant, // so no table maps one to the other. - return taken && (cfsetspeed(&settings, baud_rate) == 0) && - (tcsetattr(descriptor_, TCSANOW, &settings) == 0); + bool const rate_set{read && (cfsetspeed(&settings, baud_rate) == 0)}; + return rate_set && (tcsetattr(descriptor_, TCSANOW, &settings) == 0); } std::vector ControlSerialPort::List() { diff --git a/control/ControlStream.h b/control/ControlStream.h index 373ec76..1c42efe 100644 --- a/control/ControlStream.h +++ b/control/ControlStream.h @@ -47,9 +47,10 @@ class ControlStream { while (sent < data.size()) { auto const written{send_some(&data[sent], data.size() - sent)}; + bool const full{(written < 0) && would_block()}; if (written > 0) { sent += static_cast(written); - } else if ((written >= 0) || !would_block() || !wait_writable()) { + } else if (!full || !wait_writable()) { return false; } } diff --git a/control/ControlTcpPort.cpp b/control/ControlTcpPort.cpp index 86bb825..14ead84 100644 --- a/control/ControlTcpPort.cpp +++ b/control/ControlTcpPort.cpp @@ -95,11 +95,9 @@ ControlTcpPort::~ControlTcpPort() { Close(); } * only then switched to return at once, so that Read() never waits. */ bool ControlTcpPort::Open(uint16_t port) { - sockaddr_in address{}; - Close(); #ifdef _WIN32 - WSADATA winsock; + WSADATA winsock{}; if (WSAStartup(MAKEWORD(2, 2), &winsock) != 0) return false; #endif socket_ = static_cast(socket(AF_INET, SOCK_STREAM, 0)); @@ -110,6 +108,7 @@ bool ControlTcpPort::Open(uint16_t port) { #endif return false; } + sockaddr_in address{}; address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); diff --git a/control/ControlWindow.cpp b/control/ControlWindow.cpp index a8216a7..231b972 100644 --- a/control/ControlWindow.cpp +++ b/control/ControlWindow.cpp @@ -88,6 +88,15 @@ constexpr int32_t kLevelSlider{static_cast( constexpr int32_t kLogText{static_cast( static_cast(wxTE_MULTILINE) | wxTE_READONLY)}; +// The time in milliseconds of a clock that does not jump, as +// ControlLink::AskForPicture() takes it; it wraps after 49 days, which the link +// takes in its stride, as it only subtracts. +uint32_t GetMilliseconds() { + auto const since_start{std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch())}; + return static_cast(since_start.count()); +} + } // namespace /* ControlWindow colours of a connection's state */ @@ -404,18 +413,13 @@ void ControlWindow::OnListPorts(wxCommandEvent& /* event */) { * shows for its picture; only that one, as the other would answer for nothing. */ void ControlWindow::OnTimer(wxTimerEvent& /* event */) { - uint32_t const now{static_cast( - std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()) - .count())}; - Follow(board_link_, "board"); Follow(simulator_link_, "simulator"); ControlLink* const shown{GetShownLink()}; if (shown == nullptr) { return; } - shown->AskForPicture(now); + shown->AskForPicture(GetMilliseconds()); dots_->SetPicture(shown->GetPicture()); } @@ -540,8 +544,6 @@ ControlLink* ControlWindow::GetShownLink() { * only for a text that shifts. */ void ControlWindow::ShowState() { - bool const any_ready{board_link_.IsReady() || simulator_link_.IsReady()}; - /* * Enable() and SetForegroundColour() say whether they changed anything, here * and in ShowBytesLeft(), which the window does not need: it shows the state @@ -570,6 +572,7 @@ void ControlWindow::ShowState() { simulator_link_.IsReady() ? CONTROL_WINDOW_READY : wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT))); + bool const any_ready{board_link_.IsReady() || simulator_link_.IsReady()}; max_matrix::Discard(controls_->Enable(any_ready)); ShowBytesLeft(); max_matrix::Discard(speed_->Enable(any_ready && shift_->GetValue())); diff --git a/docu/DocuPictures.cpp b/docu/DocuPictures.cpp index 4a6d3ae..82e6c2e 100644 --- a/docu/DocuPictures.cpp +++ b/docu/DocuPictures.cpp @@ -42,6 +42,9 @@ constexpr int32_t kCell{28}; constexpr int32_t kPanelHeight{max_matrix::kRowNumberOfModule * kCell}; constexpr int32_t kLed{22}; constexpr int32_t kModuleGap{28}; +/* from the left edge of one module to that of the next */ +constexpr int32_t kModulePitch{(max_matrix::kColumnNumberOfModule * kCell) + + kModuleGap}; constexpr int32_t kLeft{60}; constexpr int32_t kTop{86}; constexpr int32_t kRight{120}; @@ -170,7 +173,8 @@ using PerDot = std::array, kNumberOfColumns>; /* each picture's file name and its SVG text */ -using Pictures = std::vector>; +using Picture = std::pair; +using Pictures = std::vector; /*! \brief The LED of every dot, if each lit exactly one. */ struct FoundLeds { @@ -208,7 +212,7 @@ LitLeds CountLit(uint8_t chip, uint8_t digit) { */ FoundLed FindLed() { FoundLed found{false, DocuLed{0, 0, 0}}; - uint8_t lit{0}; + uint16_t lit{0}; for (size_t chip{0}; chip < mock::chain.chips.size(); chip++) { for (uint8_t digit{0}; digit < Max7219::kNumberOfDigits; digit++) { @@ -216,7 +220,7 @@ FoundLed FindLed() { if (of_digit.count > 0) { found.led = of_digit.last; } - lit = static_cast(lit + of_digit.count); + lit = static_cast(lit + of_digit.count); } } found.found = (lit == 1); @@ -288,7 +292,7 @@ bool IsUpright(Max7219Wiring const& wiring) { * \return The name, as the README uses it, or nullptr for a wiring without one. */ char const* FindModuleName(Max7219Wiring const& wiring) { - for (auto const& named : kModuleNames) { + for (ModuleName const& named : kModuleNames) { if ((named.wiring->digits_as_rows == wiring.digits_as_rows) && (named.wiring->reversed_columns == wiring.reversed_columns) && (named.wiring->reversed_rows == wiring.reversed_rows)) { @@ -333,9 +337,7 @@ std::string GetModules() { * \return The pixels from the left. */ constexpr int32_t GetCellX(uint8_t x) { - return kLeft + - ((x / max_matrix::kColumnNumberOfModule) * - ((max_matrix::kColumnNumberOfModule * kCell) + kModuleGap)) + + return kLeft + ((x / max_matrix::kColumnNumberOfModule) * kModulePitch) + ((x % max_matrix::kColumnNumberOfModule) * kCell); } @@ -686,7 +688,7 @@ Pictures DrawPictures() { uint8_t CountUndrawn(Pictures const& pictures) { uint8_t undrawn{0}; - for (auto const& picture : pictures) { + for (Picture const& picture : pictures) { if (picture.second.empty()) { std::cerr << picture.first << ": a dot did not light exactly one LED\n"; undrawn++; @@ -705,9 +707,14 @@ uint8_t CountUndrawn(Pictures const& pictures) { uint8_t WritePictures(Pictures const& pictures, std::string const& folder) { uint8_t failed{0}; - for (auto const& picture : pictures) { + for (Picture const& picture : pictures) { std::string const path = folder + "/" + picture.first; - if (!picture.second.empty() && !(std::ofstream{path} << picture.second)) { + if (picture.second.empty()) { + continue; + } + std::ofstream file{path}; + file << picture.second; + if (!file) { std::cerr << path << " cannot be written\n"; failed++; } @@ -725,7 +732,7 @@ uint8_t WritePictures(Pictures const& pictures, std::string const& folder) { uint8_t CheckPictures(Pictures const& pictures, std::string const& folder) { uint8_t failed{0}; - for (auto const& picture : pictures) { + for (Picture const& picture : pictures) { std::string const path = folder + "/" + picture.first; SimulatorFileText const file{SimulatorFile::Read(path.c_str())}; if (!picture.second.empty() && @@ -757,8 +764,10 @@ int main(int argc, char** argv) { // NOLINT(misc-const-correctness): main() // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) std::vector const arguments(argv, argv + argc); - if ((arguments.size() != 3) || - ((arguments[1] != "--write") && (arguments[1] != "--check"))) { + bool const mode_and_folder{arguments.size() == 3}; + bool const known_mode{mode_and_folder && ((arguments[1] == "--write") || + (arguments[1] == "--check"))}; + if (!known_mode) { std::cerr << "usage: " << arguments[0] << " --write|--check FOLDER\n"; return 2; } diff --git a/simulator/Avr/SimulatorAvr.cpp b/simulator/Avr/SimulatorAvr.cpp index 8fbecb7..bd8af6c 100644 --- a/simulator/Avr/SimulatorAvr.cpp +++ b/simulator/Avr/SimulatorAvr.cpp @@ -202,7 +202,8 @@ void SimulatorAvr::OnClock(avr_irq_t* irq, uint32_t value, void* object) { max_matrix::Bit::ShiftUp(simulator->bits_, 1u)}; simulator->bits_ = max_matrix::Bit::WriteBit(shifted, 0, simulator->data_in_); - if (++simulator->bit_count_ == kBitsPerByte) { + simulator->bit_count_++; + if (simulator->bit_count_ == kBitsPerByte) { simulator->TakeByte(simulator->bits_); simulator->bit_count_ = 0; } diff --git a/simulator/Host/SimulatorSerialHost.cpp b/simulator/Host/SimulatorSerialHost.cpp index 2ecc8fc..1bc908b 100644 --- a/simulator/Host/SimulatorSerialHost.cpp +++ b/simulator/Host/SimulatorSerialHost.cpp @@ -44,12 +44,12 @@ bool SimulatorSerialHost::Begin(uint16_t port) { } std::string SimulatorSerialHost::Task() { - std::array chunk{}; std::string received; if (listener_ == kSimulatorSocketNone) { return received; } + std::array chunk{}; // The client first, so that one which has gone frees the port for the next in // the same call. @@ -69,8 +69,9 @@ std::string SimulatorSerialHost::Task() { } void SimulatorSerialHost::Send(std::string const& text) { - if ((client_ != kSimulatorSocketNone) && !text.empty() && - !SimulatorSocket::SendAll(client_, text)) { + bool const to_send{(client_ != kSimulatorSocketNone) && !text.empty()}; + + if (to_send && !SimulatorSocket::SendAll(client_, text)) { DropClient(); } } @@ -81,9 +82,11 @@ void SimulatorSerialHost::Send(std::string const& text) { * is taken rather than waiting for an answer that never comes. */ void SimulatorSerialHost::AcceptClient() { - int accepted{0}; - - while ((accepted = accept(listener_, nullptr, nullptr)) >= 0) { + for (;;) { + int const accepted{accept(listener_, nullptr, nullptr)}; + if (accepted < 0) { + break; + } if ((client_ == kSimulatorSocketNone) && SimulatorSocket::SetNonBlocking(accepted)) { client_ = accepted; diff --git a/simulator/Host/SimulatorSocket.cpp b/simulator/Host/SimulatorSocket.cpp index 207f822..6236ecf 100644 --- a/simulator/Host/SimulatorSocket.cpp +++ b/simulator/Host/SimulatorSocket.cpp @@ -38,8 +38,6 @@ bool WouldBlock() { return (errno == EAGAIN) || (errno == EWOULDBLOCK); } int SimulatorSocket::OpenListener(uint16_t port) { int const listening{socket(AF_INET, SOCK_STREAM, 0)}; - int const reuse{1}; - sockaddr_in address{}; if (listening < 0) { return kSimulatorSocketNone; @@ -48,17 +46,21 @@ int SimulatorSocket::OpenListener(uint16_t port) { // So that a restart does not wait out the last connection's TIME_WAIT; // without it the port is taken a minute longer, which bind() below then // reports. + int const reuse{1}; max_matrix::Discard( setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))); + sockaddr_in address{}; address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // the sockets API takes every address as a sockaddr // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - if ((bind(listening, reinterpret_cast(&address), - sizeof(address)) != 0) || - (listen(listening, kBacklog) != 0) || !SetNonBlocking(listening)) { + bool const bound{bind(listening, reinterpret_cast(&address), + sizeof(address)) == 0}; + bool const listens{bound && (listen(listening, kBacklog) == 0)}; + bool const ready{listens && SetNonBlocking(listening)}; + if (!ready) { Close(listening); return kSimulatorSocketNone; } diff --git a/simulator/Host/SimulatorWebHost.cpp b/simulator/Host/SimulatorWebHost.cpp index 152ed9a..38febf0 100644 --- a/simulator/Host/SimulatorWebHost.cpp +++ b/simulator/Host/SimulatorWebHost.cpp @@ -81,15 +81,18 @@ void SimulatorWebHost::Broadcast(std::string const& text) { // Answers every new connection: keeps one that became a WebSocket, as long as // there is a free slot for it, and closes every other one. void SimulatorWebHost::AcceptClients() { - int accepted{0}; - - while ((accepted = accept(listener_, nullptr, nullptr)) >= 0) { + for (;;) { + int const accepted{accept(listener_, nullptr, nullptr)}; + if (accepted < 0) { + break; + } std::string const request = ReadRequest(accepted); uint8_t const slot{FindFreeSlot()}; + bool const answered{(slot < kSimulatorWebHostMaxClients) && + AnswerRequest(accepted, request)}; + bool const kept{answered && SimulatorSocket::SetNonBlocking(accepted)}; - if ((slot < kSimulatorWebHostMaxClients) && - AnswerRequest(accepted, request) && - SimulatorSocket::SetNonBlocking(accepted)) { + if (kept) { clients_[slot] = accepted; } else { SimulatorSocket::Close(accepted); @@ -205,13 +208,13 @@ void SimulatorWebHost::DropClient(uint8_t slot) { */ std::string SimulatorWebHost::ReadRequest(int socket) { std::string request; - std::array chunk{}; // Without the timeout a silent client would stop the sketch, so its request // is not read; it gets no answer, and its connection is closed. if (!SimulatorSocket::SetReceiveTimeout(socket, kRequestTimeout)) { return request; } + std::array chunk{}; while (request.find("\r\n\r\n") == std::string::npos) { ssize_t const received{recv(socket, chunk.data(), chunk.size(), 0)}; if (received <= 0) { diff --git a/simulator/Host/SimulatorWebSocket.cpp b/simulator/Host/SimulatorWebSocket.cpp index fe762ee..e724b8b 100644 --- a/simulator/Host/SimulatorWebSocket.cpp +++ b/simulator/Host/SimulatorWebSocket.cpp @@ -90,6 +90,14 @@ SimulatorFoundText NotFound() { return SimulatorFoundText{false, std::string{}}; } +// Returns the length of 16 bits that follows the first two bytes of `frame`, +// the high byte first. +size_t ReadLength16(std::string const& frame) { + return SizeBits::Combine( + SizeBits::ShiftUp(static_cast(frame[2]), kBitsPerByte), + static_cast(frame[3])); +} + // Returns the byte at `index` of `bytes` as a number, as a char may be // negative. uint32_t GetByte(std::string const& bytes, size_t index) { @@ -139,33 +147,33 @@ SimulatorWebSocketFrame SimulatorWebSocket::DecodeFrame(std::string& buffer) { uint8_t const second_byte{static_cast(frame[1])}; size_t const mask_length{ (ByteBits::ReadBitGroup(second_byte, kMaskFlag) != 0u) ? kMaskLength : 0}; - size_t length{ByteBits::ReadBitGroup(second_byte, kLengthMask)}; - size_t offset{kHeaderLength}; + size_t const length_field{ByteBits::ReadBitGroup(second_byte, kLengthMask)}; - if (length == kLength64Bit) { + if (length_field == kLength64Bit) { /* no command is this long; dropping what arrived is better than trying to * read it */ buffer.clear(); return NoFrame(); } - if (length == kLength16Bit) { - if (frame.size() < kHeaderLength16Bit) { - return NoFrame(); - } - length = SizeBits::Combine( - SizeBits::ShiftUp(static_cast(frame[2]), kBitsPerByte), - static_cast(frame[3])); - offset = kHeaderLength16Bit; + /* a length of 126 says that the length follows in two bytes */ + bool const length_follows{length_field == kLength16Bit}; + if (length_follows && (frame.size() < kHeaderLength16Bit)) { + return NoFrame(); } - if (frame.size() < (offset + mask_length + length)) { + size_t const payload_length{length_follows ? ReadLength16(frame) + : length_field}; + size_t const mask_at{length_follows ? kHeaderLength16Bit : kHeaderLength}; + size_t const payload_at{mask_at + mask_length}; + size_t const frame_end{payload_at + payload_length}; + if (frame.size() < frame_end) { return NoFrame(); } - std::string const sent = frame.substr(offset + mask_length, length); + std::string const sent = frame.substr(payload_at, payload_length); SimulatorWebSocketFrame const decoded{ true, ByteBits::ReadBitGroup(static_cast(frame[0]), kOpcodeMask), - (mask_length > 0) ? Unmask(frame, offset, sent) : sent}; - buffer.erase(0, offset + mask_length + length); + (mask_length > 0) ? Unmask(frame, mask_at, sent) : sent}; + buffer.erase(0, frame_end); return decoded; } diff --git a/simulator/SimulatorOptions.cpp b/simulator/SimulatorOptions.cpp index 8cbc285..a691155 100644 --- a/simulator/SimulatorOptions.cpp +++ b/simulator/SimulatorOptions.cpp @@ -117,9 +117,10 @@ SimulatorOptions::Converted SimulatorOptions::ConvertToPort( /* strtoul() takes a sign and wraps "-1" round to ULONG_MAX, which the range * check then refuses */ - bool const valid{(end != text) && (*end == '\0') && (value != 0) && - (value <= kSimulatorOptionsMaxPort)}; - return Converted{valid, static_cast(value)}; + bool const whole_text{(end != text) && (*end == '\0')}; + bool const in_range{(value != 0) && (value <= kSimulatorOptionsMaxPort)}; + return Converted{whole_text && in_range, + static_cast(value)}; } /* diff --git a/simulator/SimulatorPanel.cpp b/simulator/SimulatorPanel.cpp index a4ad63c..bfca3f3 100644 --- a/simulator/SimulatorPanel.cpp +++ b/simulator/SimulatorPanel.cpp @@ -98,7 +98,7 @@ void SimulatorPanel::SetDrawn(uint32_t now) { // Finds a wiring by its name: among the names MD_MAX72XX has first, then among // DR0CR0RR0 ... DR1CR1RR1. Returns nullptr if no wiring has this name. Max7219Wiring const* SimulatorPanel::FindWiring(std::string const& name) { - for (auto const& named : kNamedWirings) { + for (NamedWiring const& named : kNamedWirings) { if (name == named.name) { return named.wiring; } From 97bc1feb32d1f389733b7f58e0efd45289256234 Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 16:53:59 +0100 Subject: [PATCH 2/2] OIL.md: 41 is #130 as well --- OIL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OIL.md b/OIL.md index 1072068..2e648bd 100644 --- a/OIL.md +++ b/OIL.md @@ -50,7 +50,7 @@ Status: `open`, `in progress`, `done`, `dropped` (with the reason in the item). | 38 | Results that must not be ignored | 36 | done | #94 | | 39 | MC/DC coverage | 34 | done | #95, #96 | | 40 | Braced initialization checked | 34 | done | #93 | -| 41 | The template's rules that review checks | 36 | in progress | #99, #100, #101, #102, #104, #105, #106, #107, #113, #115, #116, #117, #118, #121, #122, #124, #125, #126, #127, #128, #129 | +| 41 | The template's rules that review checks | 36 | in progress | #99, #100, #101, #102, #104, #105, #106, #107, #113, #115, #116, #117, #118, #121, #122, #124, #125, #126, #127, #128, #129, #130 | | 42 | A newer avr-gcc as a cross-check | 41 | done | | | 43 | Bit operations in one class, from the template | 41 | done | #109 |