From 75d40952e36084bcfc0b7e1c0bd50bdc5bab580a Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 15:58:04 +0100 Subject: [PATCH 1/2] Host code returns its results (OIL 41, FN-8, FN-15) No function of the simulator, the control program or DocuPictures writes its result through a pointer any more. What one finds or reads it returns, with whether it did in a small struct of its own where both are needed; what the hosts receive they return, and the caller appends. A buffer that grows over many calls, an index the caller moves on, and an object a function draws on are references. SimulatorRun::SetUp() keeps its two, as it sets up the objects the tick reaches. The library and its sizes do not change. --- AGENTS.md | 5 +- OIL.md | 9 ++ control/ControlCommand.cpp | 18 +-- control/ControlCommand.h | 21 ++- control/ControlDotPanel.cpp | 26 ++-- control/ControlDotPanel.h | 7 +- control/ControlLink.cpp | 35 ++--- control/ControlLink.h | 19 ++- control/ControlPort.h | 2 +- control/ControlSerialPort.cpp | 8 +- control/ControlSerialPort.h | 2 +- control/ControlTcpPort.cpp | 4 +- control/ControlTcpPort.h | 2 +- control/ControlWindow.cpp | 8 +- docu/DocuPictures.cpp | 192 ++++++++++++++----------- simulator/Host/SimulatorSerialHost.cpp | 8 +- simulator/Host/SimulatorSerialHost.h | 9 +- simulator/Host/SimulatorWebHost.cpp | 62 ++++---- simulator/Host/SimulatorWebHost.h | 11 +- simulator/Host/SimulatorWebSocket.cpp | 89 ++++++------ simulator/Host/SimulatorWebSocket.h | 38 +++-- simulator/SimulatorFrontEnd.cpp | 2 +- simulator/SimulatorOptions.cpp | 52 ++++--- simulator/SimulatorOptions.h | 24 +++- simulator/SimulatorRun.h | 4 +- simulator/Web/SimulatorWeb.cpp | 5 +- test/ControlCommandTest.cpp | 39 +++-- test/ControlLinkTest.cpp | 35 +++-- test/ControlPortTest.cpp | 13 +- test/SimulatorSerialHostTest.cpp | 10 +- test/SimulatorWebHostTest.cpp | 2 +- test/SimulatorWebSocketTest.cpp | 75 +++++----- 32 files changed, 466 insertions(+), 370 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7bf8f9e..fb87d02 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -498,7 +498,10 @@ on the Uno. Host code whose failures no sketch sees, the simulator and `DocuPictures`, returns `bool`, `true` for success: each of its functions fails for one reason, which its `\return` names beside `false`. `Error` has no words for a port that is taken, and `std::optional` is C++17, while the -simulator is built as `gnu++11` with the library. +simulator is built as `gnu++11` with the library. A function that finds or reads something +returns it, and whether it found it, in a small struct of its own, as `SimulatorFoundText` or +`ControlPicture`, never through a pointer (FN-8); a buffer that grows over many calls, as what a +port has read, is a reference, as is an object a function draws on (FN-15). #### Layout of a source file diff --git a/OIL.md b/OIL.md index 778c612..ce8a903 100644 --- a/OIL.md +++ b/OIL.md @@ -1171,6 +1171,15 @@ makes each line from its fields in one place, the front end says a port is taken the seven `avr_irq_register_notify()` of `SimulatorAvr`, one call of simavr each, which a function of two numbers side by side, the port and the bit, would only make swappable. +As built for FN-8 and FN-15 in the host code: no function writes its result through a pointer. +What one finds or reads it returns, with whether it did in a small struct of its own where both +are needed, as the WebSocket's frames and key, the web host's path, the command line's numbers, +the control program's picture, lines and LED under the mouse, and the LEDs `DocuPictures` looks +up; what the hosts receive they return, and the caller appends. A buffer that grows over many +calls, as what a port has read, the index into the command line and the labels and picture +`DocuPictures` draws on are references. `SimulatorRun::SetUp()` keeps its two references, as it +sets up the objects the tick reaches through a plain function pointer. + ### 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/ControlCommand.cpp b/control/ControlCommand.cpp index 92c0e50..6ca0de7 100644 --- a/control/ControlCommand.cpp +++ b/control/ControlCommand.cpp @@ -53,29 +53,29 @@ std::string ControlCommand::MakePicture() { return "picture"; } // Two hex digits per column, upper case as SerialControl prints them; lower // case is taken as well. -bool ControlCommand::DecodePicture(std::string const& line, - std::vector* columns) { +ControlPicture ControlCommand::DecodePicture(std::string const& line) { static std::string const kName = "picture="; + ControlPicture picture{false, std::vector{}}; if (line.compare(0, kName.size(), kName) != 0) { - return false; + return picture; } - columns->clear(); + picture.answers_picture = true; if (line.size() != (kName.size() + (2u * static_cast(kControlNumberOfColumns)))) { - return true; + return picture; } for (size_t i{kName.size()}; i < line.size(); i += 2) { std::array const digits{{line[i], line[i + 1], '\0'}}; if ((isxdigit(static_cast(digits[0])) == 0) || (isxdigit(static_cast(digits[1])) == 0)) { - columns->clear(); - return true; + picture.columns.clear(); + return picture; } - columns->push_back( + picture.columns.push_back( static_cast(strtoul(digits.data(), nullptr, kHexBase))); } - return true; + return picture; } int32_t ControlCommand::GetBytesLeft(std::string const& line) { diff --git a/control/ControlCommand.h b/control/ControlCommand.h index 14d4e0c..e5f19bf 100644 --- a/control/ControlCommand.h +++ b/control/ControlCommand.h @@ -17,6 +17,7 @@ #include #include +#include "MaxMatrixAttributes.h" #include "MaxMatrixConfig.h" /* ControlCommand Parameter */ @@ -26,6 +27,16 @@ constexpr uint8_t kControlNumberOfModules{4}; constexpr uint8_t kControlNumberOfColumns{kControlNumberOfModules * max_matrix::kColumnNumberOfModule}; +/*! \brief A line SerialControl answered with, as + * ControlCommand::DecodePicture() reads it. */ +struct ControlPicture { + bool answers_picture; /*!< Whether the line answers `picture`. */ + /*! One byte per column as the viewer sees it, from the left, bit 0 the top + * row; empty if the picture is not one of `kControlNumberOfColumns` columns + * in hex, as from a sketch built for another chain. */ + std::vector columns; +}; + /*! * \brief The command lines of SerialControl, as the control program sends them, * and the answer to `picture`. @@ -102,14 +113,10 @@ class ControlCommand { * \brief Decodes the answer to `picture` into the columns of the panel. * * \param[in] line A line SerialControl answered with, without its line end. - * \param[out] columns One byte per column as the viewer sees it, from the - * left, bit 0 the top row; empty if the picture is not - * one of `kControlNumberOfColumns` columns in hex, as - * from a sketch built for another chain. - * \return True if `line` answers `picture`, false for any other line. + * \return Whether `line` answers `picture`, and the columns if it does. */ - static bool DecodePicture(std::string const& line, - std::vector* columns); + MAXMATRIX_NODISCARD static ControlPicture DecodePicture( + std::string const& line); /*! * \brief Returns whether SerialControl takes `line` whole. diff --git a/control/ControlDotPanel.cpp b/control/ControlDotPanel.cpp index a0bdeef..c1ad0c2 100644 --- a/control/ControlDotPanel.cpp +++ b/control/ControlDotPanel.cpp @@ -118,9 +118,9 @@ void ControlDotPanel::OnPaint(wxPaintEvent& /* event */) { * outside the panel. */ void ControlDotPanel::OnLeftDown(wxMouseEvent& event) { - Dot dot{}; + Dot const dot{GetDotAt(event.GetPosition())}; - if (!GetDotAt(event.GetPosition(), &dot)) { + if (!dot.found) { return; } uint8_t const column{dot.column}; @@ -143,12 +143,11 @@ void ControlDotPanel::OnLeftDown(wxMouseEvent& event) { * starts again at the next LED without a line to it. */ void ControlDotPanel::OnMotion(wxMouseEvent& event) { - Dot dot{}; - if (!painting_ || !event.LeftIsDown()) { return; } - if (!GetDotAt(event.GetPosition(), &dot)) { + Dot const dot{GetDotAt(event.GetPosition())}; + if (!dot.found) { on_dot_ = false; return; } @@ -202,11 +201,11 @@ bool ControlDotPanel::IsLit(uint8_t column, uint8_t row) const { } /* - * Finds the LED at `point`, in pixels of the panel, and gives it in `dot`. - * Returns false for a point in the margin or in the gap between two modules, - * which belongs to no LED. + * Finds the LED at `point`, in pixels of the panel; none for a point in the + * margin or in the gap between two modules, which belongs to no LED. */ -bool ControlDotPanel::GetDotAt(wxPoint const& point, Dot* dot) const { +ControlDotPanel::Dot ControlDotPanel::GetDotAt(wxPoint const& point) const { + Dot const none{false, 0, 0}; wxCoord const cell{FromDIP(kCell)}; wxCoord const module_width{(max_matrix::kColumnNumberOfModule * cell) + FromDIP(kModuleGap)}; @@ -216,7 +215,7 @@ bool ControlDotPanel::GetDotAt(wxPoint const& point, Dot* dot) const { if ((x < 0) || (y < 0) || (in_module >= (max_matrix::kColumnNumberOfModule * cell))) { - return false; + return none; } wxCoord const found_column{ (x / module_width * max_matrix::kColumnNumberOfModule) + @@ -224,9 +223,8 @@ bool ControlDotPanel::GetDotAt(wxPoint const& point, Dot* dot) const { wxCoord const found_row{y / cell}; if ((found_column >= kControlNumberOfColumns) || (found_row >= max_matrix::kRowNumberOfModule)) { - return false; + return none; } - dot->column = static_cast(found_column); - dot->row = static_cast(found_row); - return true; + return Dot{true, static_cast(found_column), + static_cast(found_row)}; } diff --git a/control/ControlDotPanel.h b/control/ControlDotPanel.h index f0f7a05..8fcc0be 100644 --- a/control/ControlDotPanel.h +++ b/control/ControlDotPanel.h @@ -33,9 +33,10 @@ */ class ControlDotPanel : public wxPanel { private: - /* an LED by its column and row, as GetDotAt() finds it: named members rather - * than two pointers to bytes, which a call could swap (FN-16) */ + /* the LED under a point, as GetDotAt() finds it, if there is one: named + * members, which a call cannot swap (FN-16) */ struct Dot { + bool found; uint8_t column; uint8_t row; }; @@ -58,7 +59,7 @@ class ControlDotPanel : public wxPanel { void OnCaptureLost(wxMouseCaptureLostEvent& event); void PaintDot(uint8_t column, uint8_t row); MAXMATRIX_NODISCARD bool IsLit(uint8_t column, uint8_t row) const; - bool GetDotAt(wxPoint const& point, Dot* dot) const; + MAXMATRIX_NODISCARD Dot GetDotAt(wxPoint const& point) const; public: /*! diff --git a/control/ControlLink.cpp b/control/ControlLink.cpp index a6c748a..0a3f7a1 100644 --- a/control/ControlLink.cpp +++ b/control/ControlLink.cpp @@ -62,13 +62,14 @@ void ControlLink::AskForPicture(uint32_t now) { picture_asked_at_ = now; } -bool ControlLink::Task(std::vector* lines) { +ControlLinkLines ControlLink::Task() { size_t end{0}; + ControlLinkLines read{false, std::vector{}}; if (!port_.get().IsOpen()) { - return false; + return read; } - bool const open{port_.get().Read(&received_)}; + read.open = port_.get().Read(received_); while (((end = received_.find('\n')) != std::string::npos) || (received_.size() >= kControlLinkMaxLineLength)) { @@ -79,30 +80,32 @@ bool ControlLink::Task(std::vector* lines) { if (!line.empty() && (line.back() == '\r')) { line.pop_back(); } - Take(std::move(line), lines); + if (Take(line)) { + read.lines.push_back(std::move(line)); + } } - return open; + return read; } /* - * Takes one line from SerialControl. A board that says ready has started again, - * by its reset button say, and answers no picture asked for before; it is asked - * again at the next interval. An answer to picture is never passed on, even one - * that cannot be decoded, as it would fill the log twenty times a second. + * Takes one line from SerialControl, and returns whether it is one to pass on. + * A board that says ready has started again, by its reset button say, and + * answers no picture asked for before; it is asked again at the next interval. + * An answer to picture is never passed on, even one that cannot be decoded, as + * it would fill the log twenty times a second. */ -void ControlLink::Take(std::string line, std::vector* lines) { - std::vector picture; - +bool ControlLink::Take(std::string const& line) { if (line == kControlLinkReady) { ready_ = true; picture_asked_ = false; } - if (!ControlCommand::DecodePicture(line, &picture)) { - lines->push_back(std::move(line)); - return; + ControlPicture picture{ControlCommand::DecodePicture(line)}; + if (!picture.answers_picture) { + return true; } if (picture_asked_ && !picture_stale_) { - picture_ = std::move(picture); + picture_ = std::move(picture.columns); } picture_asked_ = false; + return false; } diff --git a/control/ControlLink.h b/control/ControlLink.h index 72d55c8..b45a797 100644 --- a/control/ControlLink.h +++ b/control/ControlLink.h @@ -32,6 +32,15 @@ constexpr uint32_t kControlLinkPictureIntervalMs{50u}; * asked for again */ constexpr uint32_t kControlLinkPictureTimeoutMs{1000u}; +/*! \brief What ControlLink::Task() read. */ +struct ControlLinkLines { + /*! Whether the port is still open, or closed now or gone at its other end. */ + bool open; + /*! Every whole line that has arrived, without its line end, but an answer to + * `picture`, which ControlLink::GetPicture() returns. */ + std::vector lines; +}; + /*! * \brief The lines between the control program and one SerialControl, on a * board or in the simulator. @@ -66,7 +75,7 @@ class ControlLink { bool picture_timed_{false}; uint32_t picture_asked_at_{0}; - void Take(std::string line, std::vector* lines); + bool Take(std::string const& line); public: /*! @@ -127,13 +136,9 @@ class ControlLink { * * Call it often, from a timer: it never waits. * - * \param[out] lines Every whole line that has arrived is appended, without - * its line end, but an answer to `picture`, which - * GetPicture() returns. - * \return True while the port is open, or false once it is closed or its - * other end is gone. + * \return The lines that have arrived, and whether the port is still open. */ - bool Task(std::vector* lines); + MAXMATRIX_NODISCARD ControlLinkLines Task(); }; #endif // MAXMATRIX_CONTROL_CONTROLLINK_H_ diff --git a/control/ControlPort.h b/control/ControlPort.h index 810b3ba..36c847d 100644 --- a/control/ControlPort.h +++ b/control/ControlPort.h @@ -67,7 +67,7 @@ class ControlPort { * \return True while the port is open, or false once the other end is gone: * the cable pulled, the simulator stopped. The port is closed then. */ - virtual bool Read(std::string* data) = 0; + virtual bool Read(std::string& data) = 0; /*! \brief Closes the port, if it is open. */ virtual void Close() = 0; diff --git a/control/ControlSerialPort.cpp b/control/ControlSerialPort.cpp index 4ddc7fa..250d04b 100644 --- a/control/ControlSerialPort.cpp +++ b/control/ControlSerialPort.cpp @@ -140,7 +140,7 @@ bool ControlSerialPort::Write(std::string const& data) { return true; } -bool ControlSerialPort::Read(std::string* data) { +bool ControlSerialPort::Read(std::string& data) { std::array chunk; DWORD const size = static_cast(chunk.size()); DWORD length = size; @@ -151,7 +151,7 @@ bool ControlSerialPort::Read(std::string* data) { Close(); return false; } - data->append(chunk.data(), length); + data.append(chunk.data(), length); } return true; } @@ -261,13 +261,13 @@ bool ControlSerialPort::Write(std::string const& data) { return sent; } -bool ControlSerialPort::Read(std::string* data) { +bool ControlSerialPort::Read(std::string& data) { if (!IsOpen()) { return false; } int const descriptor{descriptor_}; bool const open{ControlStream::ReceiveAvailable( - *data, + data, [descriptor](char* bytes, size_t length) { return read(descriptor, bytes, length); }, diff --git a/control/ControlSerialPort.h b/control/ControlSerialPort.h index b5a203d..e54f79f 100644 --- a/control/ControlSerialPort.h +++ b/control/ControlSerialPort.h @@ -74,7 +74,7 @@ class ControlSerialPort final : public ControlPort { MAXMATRIX_NODISCARD bool IsOpen() const override; bool Write(std::string const& data) override; - bool Read(std::string* data) override; + bool Read(std::string& data) override; void Close() override; }; diff --git a/control/ControlTcpPort.cpp b/control/ControlTcpPort.cpp index abb5e43..a9c5f99 100644 --- a/control/ControlTcpPort.cpp +++ b/control/ControlTcpPort.cpp @@ -141,13 +141,13 @@ bool ControlTcpPort::Write(std::string const& data) { return sent; } -bool ControlTcpPort::Read(std::string* data) { +bool ControlTcpPort::Read(std::string& data) { if (!IsOpen()) { return false; } Socket const connection{ToSocket(socket_)}; bool const open{ControlStream::ReceiveAvailable( - *data, + data, [connection](char* bytes, size_t length) { return recv(connection, bytes, ToLength(length), 0); }, diff --git a/control/ControlTcpPort.h b/control/ControlTcpPort.h index 50fc9d5..91821bf 100644 --- a/control/ControlTcpPort.h +++ b/control/ControlTcpPort.h @@ -54,7 +54,7 @@ class ControlTcpPort final : public ControlPort { MAXMATRIX_NODISCARD bool IsOpen() const override; bool Write(std::string const& data) override; - bool Read(std::string* data) override; + bool Read(std::string& data) override; void Close() override; }; diff --git a/control/ControlWindow.cpp b/control/ControlWindow.cpp index 10f1e1a..b9cbae2 100644 --- a/control/ControlWindow.cpp +++ b/control/ControlWindow.cpp @@ -35,7 +35,6 @@ #include #include #include -#include #include "ControlCommand.h" #include "ControlDotPanel.h" @@ -491,15 +490,14 @@ void ControlWindow::SendSettings(ControlLink& link, char const* name) { * settings. */ void ControlWindow::Follow(ControlLink& link, char const* name) { - std::vector lines; - if (!link.IsOpen()) { return; } bool const was_ready{link.IsReady()}; - bool const open{link.Task(&lines)}; + ControlLinkLines const read{link.Task()}; + bool const open{read.open}; - for (std::string const& line : lines) { + for (std::string const& line : read.lines) { Log(wxString(name) + ": " + ConvertToText(line) + "\n"); if (line == kControlLinkReady) { SendSettings(link, name); diff --git a/docu/DocuPictures.cpp b/docu/DocuPictures.cpp index 3ed2b8c..32a66da 100644 --- a/docu/DocuPictures.cpp +++ b/docu/DocuPictures.cpp @@ -126,6 +126,18 @@ struct DocuLed { uint8_t bit; }; +/*! \brief The LED a lookup found, if it found exactly one. */ +struct FoundLed { + bool found; /*!< Whether exactly one LED is lit. */ + DocuLed led; /*!< That LED. */ +}; + +/*! \brief The lit LEDs of one digit register: how many, and the last. */ +struct LitLeds { + uint8_t count; /*!< How many are lit. */ + DocuLed last; /*!< The last lit one, if any is. */ +}; + /*! \brief A dot of the panel, as the viewer sees it. */ struct Dot { uint8_t x; @@ -157,22 +169,28 @@ template using PerDot = std::array, kNumberOfColumns>; +/*! \brief The LED of every dot, if each lit exactly one. */ +struct FoundLeds { + bool found; /*!< Whether every dot lit exactly one LED. */ + PerDot leds; /*!< The LED of each dot. */ +}; + /*! - * \brief Counts the lit LEDs of one digit register, and keeps the last of them. + * \brief Counts the lit LEDs of one digit register, and finds the last of them. * * \param[in] chip The chip in the chain, 0 at DIN. * \param[in] digit The digit register. - * \param[in,out] led The chip, digit and bit of the last lit LED found. - * \return How many of its LEDs are lit. + * \return How many of its LEDs are lit, and the chip, digit and bit of the + * last. */ -uint8_t CountLit(uint8_t chip, uint8_t digit, DocuLed* led) { +LitLeds CountLit(uint8_t chip, uint8_t digit) { uint8_t const segments{mock::chain.chips[chip].digit[digit]}; - uint8_t lit{0}; + LitLeds lit{0, DocuLed{0, 0, 0}}; for (uint8_t bit{0}; bit < kBitsPerDigit; bit++) { if (max_matrix::Bit::ReadBit(segments, bit)) { - *led = DocuLed{chip, digit, bit}; - lit++; + lit.last = DocuLed{chip, digit, bit}; + lit.count++; } } return lit; @@ -182,19 +200,24 @@ uint8_t CountLit(uint8_t chip, uint8_t digit, DocuLed* led) { * \brief Finds the one LED the model has lit, in the digit registers of every * chip. * - * \param[out] led The chip, digit and bit of the lit LED. - * \return True if exactly one LED is lit, or false if none or more than one is. + * \return The chip, digit and bit of the lit LED; not found if none or more + * than one is lit. */ -bool FindLed(DocuLed* led) { +FoundLed FindLed() { + FoundLed found{false, DocuLed{0, 0, 0}}; uint8_t lit{0}; for (size_t chip{0}; chip < mock::chain.chips.size(); chip++) { for (uint8_t digit{0}; digit < Max7219::kNumberOfDigits; digit++) { - lit = static_cast( - lit + CountLit(static_cast(chip), digit, led)); + LitLeds const of_digit{CountLit(static_cast(chip), digit)}; + if (of_digit.count > 0) { + found.led = of_digit.last; + } + lit = static_cast(lit + of_digit.count); } } - return lit == 1; + found.found = (lit == 1); + return found; } /*! @@ -205,13 +228,13 @@ bool FindLed(DocuLed* led) { * * \param[in] x The column, as the viewer sees it. * \param[in] y The row, as the viewer sees it. - * \param[out] led The chip, digit and bit. - * \return True if the dot lit exactly one LED, or false if it did not. + * \return The chip, digit and bit; not found if the dot lit not exactly one + * LED. */ -bool FindLedOfDot(uint8_t x, uint8_t y, DocuLed* led) { +FoundLed FindLedOfDot(uint8_t x, uint8_t y) { matrix.Clear(); matrix.SetDot(max_matrix::Point{max_matrix::X{x}, max_matrix::Y{y}}, true); - return FindLed(led); + return FindLed(); } /*! @@ -342,18 +365,18 @@ uint16_t GetPictureHeight() { * \param[in] colour The fill colour. * \param[in] label The text in the LED, or empty. */ -void DrawLed(DocuSvg* svg, Dot dot, char const* colour, +void DrawLed(DocuSvg& svg, Dot dot, char const* colour, std::string const& label) { int32_t const inset{(kCell - kLed) / 2}; int32_t const left{GetCellX(dot.x)}; int32_t const top{GetCellY(dot.y)}; - svg->AddRect({left + inset, top + inset}, - {static_cast(kLed), static_cast(kLed)}, - {colour, "none", kLedRadius}); + svg.AddRect({left + inset, top + inset}, + {static_cast(kLed), static_cast(kLed)}, + {colour, "none", kLedRadius}); if (!label.empty()) { - svg->AddText({left + (kCell / 2), top + (kCell / 2) + kBaselineShift}, - label, kLedText); + svg.AddText({left + (kCell / 2), top + (kCell / 2) + kBaselineShift}, label, + kLedText); } } @@ -364,28 +387,28 @@ void DrawLed(DocuSvg* svg, Dot dot, char const* colour, * \param[in,out] svg The picture. * \param[in] module The module, from the left. */ -void DrawModule(DocuSvg* svg, uint8_t module) { +void DrawModule(DocuSvg& svg, uint8_t module) { int32_t const module_width{max_matrix::kColumnNumberOfModule * kCell}; int32_t const left{GetCellX(module * max_matrix::kColumnNumberOfModule)}; int32_t const middle{kTop + (kPanelHeight / 2)}; - DocuLed led{}; - - svg->AddRect({left - kFramePadding, kTop - kFramePadding}, - {static_cast(module_width + (2 * kFramePadding)), - static_cast(kPanelHeight + (2 * kFramePadding))}, - {"none", kColourFrame, kFrameRadius}); - svg->AddText({left + (module_width / 2), kTop - kModuleNameAbove}, - "Module " + std::to_string(module), kNameText); - if (!FindLedOfDot(module * max_matrix::kColumnNumberOfModule, 0, &led) || - (led.chip != 0)) { + + svg.AddRect({left - kFramePadding, kTop - kFramePadding}, + {static_cast(module_width + (2 * kFramePadding)), + static_cast(kPanelHeight + (2 * kFramePadding))}, + {"none", kColourFrame, kFrameRadius}); + svg.AddText({left + (module_width / 2), kTop - kModuleNameAbove}, + "Module " + std::to_string(module), kNameText); + FoundLed const first{ + FindLedOfDot(module * max_matrix::kColumnNumberOfModule, 0)}; + if (!first.found || (first.led.chip != 0)) { return; } bool const right{module == (kNumberOfModules - 1)}; int32_t const edge{right ? (left + module_width + (2 * kFramePadding)) : (left - (2 * kFramePadding))}; int32_t const outside{right ? (edge + kArrowLength) : (edge - kArrowLength)}; - svg->AddArrow({outside, middle}, edge, kArrowThickness, kColourFrame); - svg->AddText({(outside + edge) / 2, middle - kDinAbove}, "DIN", kDinText); + svg.AddArrow({outside, middle}, edge, kArrowThickness, kColourFrame); + svg.AddText({(outside + edge) / 2, middle - kDinAbove}, "DIN", kDinText); } /*! @@ -393,22 +416,21 @@ void DrawModule(DocuSvg* svg, uint8_t module) { * * \param[in,out] svg The picture. */ -void DrawAxes(DocuSvg* svg) { +void DrawAxes(DocuSvg& svg) { int32_t const below{kTop + kPanelHeight + kAxisBelow}; for (uint8_t x{0}; x < kNumberOfColumns; x++) { - svg->AddText({GetCellX(x) + (kCell / 2), below}, std::to_string(x), - kColumnAxisText); + svg.AddText({GetCellX(x) + (kCell / 2), below}, std::to_string(x), + kColumnAxisText); } for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { - svg->AddText( - {kLeft - kAxisLeft, GetCellY(y) + (kCell / 2) + kBaselineShift}, - std::to_string(y), kRowAxisText); + svg.AddText({kLeft - kAxisLeft, GetCellY(y) + (kCell / 2) + kBaselineShift}, + std::to_string(y), kRowAxisText); } - svg->AddText( + svg.AddText( {kLeft - kAxisNameLeft, kTop + (kPanelHeight / 2) + kAxisNameShift}, "Y", kNameText); - svg->AddText({kLeft - kAxisLeft, below}, "X", kXText); + svg.AddText({kLeft - kAxisLeft, below}, "X", kXText); } /*! @@ -418,9 +440,9 @@ void DrawAxes(DocuSvg* svg) { * \param[in,out] svg The picture. * \param[in] title The line above the panel, or empty for none. */ -void DrawPanel(DocuSvg* svg, std::string const& title) { +void DrawPanel(DocuSvg& svg, std::string const& title) { if (!title.empty()) { - svg->AddText({kLeft, kTitleBaseline}, title, kTitleText); + svg.AddText({kLeft, kTitleBaseline}, title, kTitleText); } for (uint8_t module{0}; module < kNumberOfModules; module++) { DrawModule(svg, module); @@ -431,18 +453,23 @@ void DrawPanel(DocuSvg* svg, std::string const& title) { /*! * \brief Finds the LED of every dot with the module type that is set. * - * \param[out] leds The chip, digit and bit of each dot's LED. - * \return True if every dot lit exactly one LED. + * \return The chip, digit and bit of each dot's LED; not found unless every dot + * lit exactly one LED. */ -bool FindLeds(PerDot* leds) { +FoundLeds FindLeds() { + FoundLeds found{false, PerDot{}}; + for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { - if (!FindLedOfDot(x, y, &(*leds)[x][y])) { - return false; + FoundLed const of_dot{FindLedOfDot(x, y)}; + if (!of_dot.found) { + return found; } + found.leds[x][y] = of_dot.led; } } - return true; + found.found = true; + return found; } /*! @@ -452,7 +479,7 @@ bool FindLeds(PerDot* leds) { * \param[in,out] svg The picture. * \param[in] leds The chip, digit and bit of each dot's LED. */ -void DrawBands(DocuSvg* svg, PerDot const& leds) { +void DrawBands(DocuSvg& svg, PerDot const& leds) { int32_t const inset{((kCell - kLed) / 2) - 2}; auto const across{static_cast(kCell + kLed + 4)}; auto const along{static_cast(kLed + 4)}; @@ -464,10 +491,10 @@ void DrawBands(DocuSvg* svg, PerDot const& leds) { (max_matrix::kColumnNumberOfModule - 1)}; bool const below_on_panel{y < (max_matrix::kRowNumberOfModule - 1)}; if (right_in_module && (leds[x + 1][y].digit == leds[x][y].digit)) { - svg->AddRect(corner, {across, along}, {kColourBand, "none", 0}); + svg.AddRect(corner, {across, along}, {kColourBand, "none", 0}); } if (below_on_panel && (leds[x][y + 1].digit == leds[x][y].digit)) { - svg->AddRect(corner, {along, across}, {kColourBand, "none", 0}); + svg.AddRect(corner, {along, across}, {kColourBand, "none", 0}); } } } @@ -478,16 +505,16 @@ void DrawBands(DocuSvg* svg, PerDot const& leds) { * * \param[in,out] svg The picture. */ -void DrawWiringLegend(DocuSvg* svg) { +void DrawWiringLegend(DocuSvg& svg) { int32_t const legend{GetCellY(max_matrix::kRowNumberOfModule - 1) + kCell + kLegendBelow}; - svg->AddText({kLeft, legend}, - "Each LED is labelled byte.bit: byte n is digit register n of " - "the module's MAX7219 and " - "matrix_buffer_[8 * module + n], bit b is bit b of it.", - kLegendText); - svg->AddText( + svg.AddText({kLeft, legend}, + "Each LED is labelled byte.bit: byte n is digit register n of " + "the module's MAX7219 and " + "matrix_buffer_[8 * module + n], bit b is bit b of it.", + kLegendText); + svg.AddText( {kLeft, legend + kLegendLine}, "A blue band joins the LEDs of one byte, the darker one is its bit 0. " "Matrix orientation 0. " @@ -509,23 +536,24 @@ void DrawWiringLegend(DocuSvg* svg) { */ std::string DrawWiring(max_matrix::ModuleType module_type) { DocuSvg svg{GetPictureWidth(), GetPictureHeight()}; - PerDot leds; matrix.SetModuleType(module_type); - if (!FindLeds(&leds)) { + FoundLeds const found{FindLeds()}; + if (!found.found) { return ""; } - DrawPanel(&svg, "Module type " + GetModules()); - DrawBands(&svg, leds); + PerDot const& leds{found.leds}; + DrawPanel(svg, "Module type " + GetModules()); + DrawBands(svg, leds); for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { char const* colour{(leds[x][y].bit == 0) ? kColourLedBit0 : kColourLed}; - DrawLed(&svg, {x, y}, colour, + DrawLed(svg, {x, y}, colour, std::to_string(leds[x][y].digit) + "." + std::to_string(leds[x][y].bit)); } } - DrawWiringLegend(&svg); + DrawWiringLegend(svg); return svg.GetDocument(); } @@ -535,12 +563,12 @@ std::string DrawWiring(max_matrix::ModuleType module_type) { * \param[in] bit The bit of the value that lit them. * \param[in,out] labels The label of each dot. */ -void LabelLitDots(uint8_t bit, PerDot* labels) { +void LabelLitDots(uint8_t bit, PerDot& labels) { for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { if (matrix.GetDot(max_matrix::Point{max_matrix::X{x}, max_matrix::Y{y}}) .GetValue()) { - (*labels)[x][y] = std::to_string(bit); + labels[x][y] = std::to_string(bit); } } } @@ -551,15 +579,15 @@ void LabelLitDots(uint8_t bit, PerDot* labels) { * * \param[in,out] svg The picture. */ -void DrawFunctionNames(DocuSvg* svg) { +void DrawFunctionNames(DocuSvg& svg) { int32_t const names{kTop + kPanelHeight + kNamesBelow}; int32_t const row_module_left{ GetCellX(kExampleRowModule * max_matrix::kColumnNumberOfModule)}; - svg->AddText({GetCellX(kExampleColumn) + (kCell / 2), names}, - "SetColumn(X{" + std::to_string(kExampleColumn) + "}, value)", - kColumnFunctionText); - svg->AddText( + svg.AddText({GetCellX(kExampleColumn) + (kCell / 2), names}, + "SetColumn(X{" + std::to_string(kExampleColumn) + "}, value)", + kColumnFunctionText); + svg.AddText( {row_module_left + (max_matrix::kColumnNumberOfModule * kCell / 2), names}, "SetRow(Module{" + std::to_string(kExampleRowModule) + "}, " + @@ -590,26 +618,26 @@ std::string DrawCoordinates() { for (uint8_t bit{0}; bit < max_matrix::kRowNumberOfModule; bit++) { matrix.Clear(); matrix.SetColumn(max_matrix::X{kExampleColumn}, max_matrix::Byte{1} << bit); - LabelLitDots(bit, &column_labels); + LabelLitDots(bit, column_labels); matrix.Clear(); matrix.SetRow(max_matrix::Module{kExampleRowModule}, kExampleRow, max_matrix::Byte{1} << bit); - LabelLitDots(bit, &row_labels); + LabelLitDots(bit, row_labels); } - DrawPanel(&svg, ""); + DrawPanel(svg, ""); for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { if (!column_labels[x][y].empty()) { - DrawLed(&svg, {x, y}, kColourLed, column_labels[x][y]); + DrawLed(svg, {x, y}, kColourLed, column_labels[x][y]); } else if (!row_labels[x][y].empty()) { - DrawLed(&svg, {x, y}, kColourRow, row_labels[x][y]); + DrawLed(svg, {x, y}, kColourRow, row_labels[x][y]); } else { - DrawLed(&svg, {x, y}, kColourLedOff, ""); + DrawLed(svg, {x, y}, kColourLedOff, ""); } } } - DrawFunctionNames(&svg); + DrawFunctionNames(svg); return svg.GetDocument(); } diff --git a/simulator/Host/SimulatorSerialHost.cpp b/simulator/Host/SimulatorSerialHost.cpp index 0ac4ab1..6411e1e 100644 --- a/simulator/Host/SimulatorSerialHost.cpp +++ b/simulator/Host/SimulatorSerialHost.cpp @@ -44,11 +44,12 @@ bool SimulatorSerialHost::Begin(uint16_t port) { return listener_ != kSimulatorSocketNone; } -void SimulatorSerialHost::Task(std::string* received) { +std::string SimulatorSerialHost::Task() { std::array chunk{}; + std::string received; if (listener_ == kSimulatorSocketNone) { - return; + return received; } // The client first, so that one which has gone frees the port for the next in @@ -56,7 +57,7 @@ void SimulatorSerialHost::Task(std::string* received) { while (client_ != kSimulatorSocketNone) { ssize_t const length{recv(client_, chunk.data(), chunk.size(), 0)}; if (length > 0) { - received->append(chunk.data(), static_cast(length)); + received.append(chunk.data(), static_cast(length)); } else { if (SimulatorSocket::IsGone(length)) { DropClient(); @@ -65,6 +66,7 @@ void SimulatorSerialHost::Task(std::string* received) { } } AcceptClient(); + return received; } void SimulatorSerialHost::Send(std::string const& text) { diff --git a/simulator/Host/SimulatorSerialHost.h b/simulator/Host/SimulatorSerialHost.h index f81357a..76c8091 100644 --- a/simulator/Host/SimulatorSerialHost.h +++ b/simulator/Host/SimulatorSerialHost.h @@ -19,6 +19,8 @@ #include +#include "MaxMatrixAttributes.h" + /*! * \brief The sketch's `Serial` as a TCP port on loopback, for the control * program. @@ -61,11 +63,10 @@ class SimulatorSerialHost { * Until Begin() has opened the port, it does nothing. A client that has * closed its end is dropped, and the next one may connect. * - * \param[in,out] received Every byte the client has sent since the last call - * is appended, as a board's `Serial` would receive - * it. + * \return Every byte the client has sent since the last call, as a board's + * `Serial` would receive it. */ - void Task(std::string* received); + MAXMATRIX_NODISCARD std::string Task(); /*! * \brief Sends the client what the sketch has printed. diff --git a/simulator/Host/SimulatorWebHost.cpp b/simulator/Host/SimulatorWebHost.cpp index 58b7c81..b23d285 100644 --- a/simulator/Host/SimulatorWebHost.cpp +++ b/simulator/Host/SimulatorWebHost.cpp @@ -50,17 +50,21 @@ bool SimulatorWebHost::Begin(uint16_t port, char const* page_path) { return listener_ != kSimulatorSocketNone; } -void SimulatorWebHost::Task(std::vector* messages) { +std::vector SimulatorWebHost::Task() { + std::vector messages; + if (listener_ == kSimulatorSocketNone) { - return; + return messages; } AcceptClients(); for (uint8_t slot{0}; slot < kSimulatorWebHostMaxClients; slot++) { if (clients_[slot] != kSimulatorSocketNone) { - ReadClient(slot, messages); + std::vector const read = ReadClient(slot); + messages.insert(messages.end(), read.begin(), read.end()); } } + return messages; } void SimulatorWebHost::Broadcast(std::string const& text) { @@ -94,34 +98,36 @@ void SimulatorWebHost::AcceptClients() { } /* - * Reads what the WebSocket in `slot` has sent and appends every complete text - * message to `messages`. The bytes are collected until a frame is complete; a - * closed connection or a close frame drops the client. + * Reads what the WebSocket in `slot` has sent and returns every complete text + * message. The bytes are collected until a frame is complete; a closed + * connection or a close frame drops the client. */ -void SimulatorWebHost::ReadClient(uint8_t slot, - std::vector* messages) { +std::vector SimulatorWebHost::ReadClient(uint8_t slot) { std::array chunk{}; ssize_t const received{recv(clients_[slot], chunk.data(), chunk.size(), 0)}; - uint8_t opcode{0}; - std::string payload; + std::vector messages; if (SimulatorSocket::IsGone(received)) { DropClient(slot); - return; + return messages; } if (received > 0) { pending_[slot].append(chunk.data(), static_cast(received)); } - while (SimulatorWebSocket::DecodeFrame(&pending_[slot], &opcode, &payload)) { - if (opcode == kSimulatorWebSocketOpcodeClose) { + SimulatorWebSocketFrame frame{ + SimulatorWebSocket::DecodeFrame(pending_[slot])}; + while (frame.complete) { + if (frame.opcode == kSimulatorWebSocketOpcodeClose) { DropClient(slot); - return; + return messages; } - if (opcode == kSimulatorWebSocketOpcodeText) { - messages->push_back(payload); + if (frame.opcode == kSimulatorWebSocketOpcodeText) { + messages.push_back(frame.payload); } + frame = SimulatorWebSocket::DecodeFrame(pending_[slot]); } + return messages; } /* @@ -131,18 +137,18 @@ void SimulatorWebHost::ReadClient(uint8_t slot, * does, and false once the connection is done. */ bool SimulatorWebHost::AnswerRequest(int socket, std::string const& request) { - std::string path; - std::string answer; + SimulatorFoundText const path{GetPath(request)}; - if (!GetPath(request, &path)) { + if (!path.found) { return false; } - if (path == kWebSocketPath) { - return SimulatorWebSocket::GetHandshakeAnswer(request, &answer) && - SimulatorSocket::SendAll(socket, answer); + if (path.text == kWebSocketPath) { + SimulatorFoundText const answer{ + SimulatorWebSocket::GetHandshakeAnswer(request)}; + return answer.found && SimulatorSocket::SendAll(socket, answer.text); } - if ((path == "/") || (path == "/index.html")) { + if ((path.text == "/") || (path.text == "/index.html")) { SendPage(socket); } else { SendResponse(socket, "404 Not Found", "text/plain", @@ -214,18 +220,16 @@ std::string SimulatorWebHost::ReadRequest(int socket) { } // Finds the path in `request`, what stands between the first two spaces of the -// request line, and gives it in `path`. Returns false if the request line has -// no path. -bool SimulatorWebHost::GetPath(std::string const& request, std::string* path) { +// request line, or none if the request line has no path. +SimulatorFoundText SimulatorWebHost::GetPath(std::string const& request) { size_t const start{request.find(' ')}; size_t const end{(start == std::string::npos) ? std::string::npos : request.find(' ', start + 1)}; if (end == std::string::npos) { - return false; + return SimulatorFoundText{false, std::string{}}; } - *path = request.substr(start + 1, end - start - 1); - return true; + return SimulatorFoundText{true, request.substr(start + 1, end - start - 1)}; } /* diff --git a/simulator/Host/SimulatorWebHost.h b/simulator/Host/SimulatorWebHost.h index a0bbc42..a2acde6 100644 --- a/simulator/Host/SimulatorWebHost.h +++ b/simulator/Host/SimulatorWebHost.h @@ -20,6 +20,7 @@ #include #include "MaxMatrixAttributes.h" +#include "SimulatorWebSocket.h" /* SimulatorWebHost Parameter */ constexpr uint8_t kSimulatorWebHostMaxClients{4u}; @@ -39,13 +40,14 @@ class SimulatorWebHost { char const* page_path_{nullptr}; void AcceptClients(); - void ReadClient(uint8_t slot, std::vector* messages); + std::vector ReadClient(uint8_t slot); bool AnswerRequest(int socket, std::string const& request); void SendPage(int socket); MAXMATRIX_NODISCARD uint8_t FindFreeSlot() const; void DropClient(uint8_t slot); static std::string ReadRequest(int socket); - static bool GetPath(std::string const& request, std::string* path); + MAXMATRIX_NODISCARD static SimulatorFoundText GetPath( + std::string const& request); static void SendResponse(int socket, char const* status, char const* content_type, std::string const& body); @@ -73,10 +75,9 @@ class SimulatorWebHost { * It accepts and answers new connections and reads the frames of the open * WebSockets. Until Begin() has opened the port, it does nothing. * - * \param[in,out] messages Every text message a page has sent since the last - * call is appended. + * \return Every text message a page has sent since the last call. */ - void Task(std::vector* messages); + MAXMATRIX_NODISCARD std::vector Task(); /*! * \brief Sends a text to every open WebSocket. diff --git a/simulator/Host/SimulatorWebSocket.cpp b/simulator/Host/SimulatorWebSocket.cpp index c148cfb..fe762ee 100644 --- a/simulator/Host/SimulatorWebSocket.cpp +++ b/simulator/Host/SimulatorWebSocket.cpp @@ -69,14 +69,25 @@ constexpr uint8_t kSha1TurnB{30u}; constexpr uint8_t kBase64Bits{6u}; constexpr uint32_t kBase64Mask{0x3Fu}; -// Turns the bytes of `payload` back with the four of the client's mask, which -// lie at `mask_at` of `frame`, RFC 6455 section 5.3. -void Unmask(std::string const& frame, size_t mask_at, std::string* payload) { - for (size_t i{0}; i < payload->size(); i++) { - (*payload)[i] = static_cast(ByteBits::ToggleBits( - static_cast((*payload)[i]), +// Returns the bytes of `payload` turned back with the four of the client's +// mask, which lie at `mask_at` of `frame`, RFC 6455 section 5.3. +std::string Unmask(std::string const& frame, size_t mask_at, + std::string payload) { + for (size_t i{0}; i < payload.size(); i++) { + payload[i] = static_cast(ByteBits::ToggleBits( + static_cast(payload[i]), static_cast(frame[mask_at + (i % kMaskLength)]))); } + return payload; +} + +// What DecodeFrame() and GetKey() return when there is nothing to take. +SimulatorWebSocketFrame NoFrame() { + return SimulatorWebSocketFrame{false, 0, std::string{}}; +} + +SimulatorFoundText NotFound() { + return SimulatorFoundText{false, std::string{}}; } // Returns the byte at `index` of `bytes` as a number, as a char may be @@ -87,19 +98,19 @@ uint32_t GetByte(std::string const& bytes, size_t index) { } // namespace -bool SimulatorWebSocket::GetHandshakeAnswer(std::string const& request, - std::string* answer) { - std::string key; - - if (GetKey(request, &key)) { - *answer = - "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: " - "Upgrade\r\n" - "Sec-WebSocket-Accept: " + - ConvertKeyToAcceptKey(key) + "\r\n\r\n"; - return true; +SimulatorFoundText SimulatorWebSocket::GetHandshakeAnswer( + std::string const& request) { + SimulatorFoundText const key{GetKey(request)}; + + if (!key.found) { + return NotFound(); } - return false; + return SimulatorFoundText{ + true, + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: " + "Upgrade\r\n" + "Sec-WebSocket-Accept: " + + ConvertKeyToAcceptKey(key.text) + "\r\n\r\n"}; } std::string SimulatorWebSocket::EncodeFrame(std::string const& payload) { @@ -118,12 +129,11 @@ std::string SimulatorWebSocket::EncodeFrame(std::string const& payload) { return frame + payload; } -bool SimulatorWebSocket::DecodeFrame(std::string* buffer, uint8_t* opcode, - std::string* payload) { - std::string const& frame{*buffer}; +SimulatorWebSocketFrame SimulatorWebSocket::DecodeFrame(std::string& buffer) { + std::string const& frame{buffer}; if (frame.size() < kHeaderLength) { - return false; + return NoFrame(); } uint8_t const second_byte{static_cast(frame[1])}; @@ -135,12 +145,12 @@ bool SimulatorWebSocket::DecodeFrame(std::string* buffer, uint8_t* opcode, if (length == kLength64Bit) { /* no command is this long; dropping what arrived is better than trying to * read it */ - buffer->clear(); - return false; + buffer.clear(); + return NoFrame(); } if (length == kLength16Bit) { if (frame.size() < kHeaderLength16Bit) { - return false; + return NoFrame(); } length = SizeBits::Combine( SizeBits::ShiftUp(static_cast(frame[2]), kBitsPerByte), @@ -148,16 +158,15 @@ bool SimulatorWebSocket::DecodeFrame(std::string* buffer, uint8_t* opcode, offset = kHeaderLength16Bit; } if (frame.size() < (offset + mask_length + length)) { - return false; + return NoFrame(); } - payload->assign(frame, offset + mask_length, length); - if (mask_length > 0) { - Unmask(frame, offset, payload); - } - *opcode = ByteBits::ReadBitGroup(static_cast(frame[0]), kOpcodeMask); - buffer->erase(0, offset + mask_length + length); - return true; + std::string const sent = frame.substr(offset + mask_length, 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); + return decoded; } // The accept key is the base64 of the SHA-1 of the key and the fixed GUID of @@ -226,12 +235,12 @@ std::string SimulatorWebSocket::ConvertToBase64(std::string const& bytes) { /* * Finds the browser's key in `request`, the whole HTTP request with its - * headers, and gives the value of Sec-WebSocket-Key in `key`. Returns false if - * the request has no such header. It searches a lowered copy of the request, as + * headers: the value of Sec-WebSocket-Key, or none if the request has no such + * header. It searches a lowered copy of the request, as * header names are case-insensitive, and takes the value from the request * itself. */ -bool SimulatorWebSocket::GetKey(std::string const& request, std::string* key) { +SimulatorFoundText SimulatorWebSocket::GetKey(std::string const& request) { std::string lowered(request); for (char& c : lowered) { @@ -239,7 +248,7 @@ bool SimulatorWebSocket::GetKey(std::string const& request, std::string* key) { } size_t const found{lowered.find(kKeyHeader)}; if (found == std::string::npos) { - return false; + return NotFound(); } size_t start{found + sizeof(kKeyHeader) - 1}; @@ -248,11 +257,9 @@ bool SimulatorWebSocket::GetKey(std::string const& request, std::string* key) { } size_t const end{request.find("\r\n", start)}; if (end == std::string::npos) { - return false; + return NotFound(); } - - *key = request.substr(start, end - start); - return true; + return SimulatorFoundText{true, request.substr(start, end - start)}; } /* diff --git a/simulator/Host/SimulatorWebSocket.h b/simulator/Host/SimulatorWebSocket.h index 52e79f3..3a776df 100644 --- a/simulator/Host/SimulatorWebSocket.h +++ b/simulator/Host/SimulatorWebSocket.h @@ -19,6 +19,8 @@ #include #include +#include "MaxMatrixAttributes.h" + /* SimulatorWebSocket opcodes, RFC 6455 section 5.2 */ constexpr uint8_t kSimulatorWebSocketOpcodeText{0x1u}; constexpr uint8_t kSimulatorWebSocketOpcodeClose{0x8u}; @@ -28,6 +30,21 @@ constexpr size_t kSimulatorWebSocketSha1Length{20u}; /* the hash of SHA-1 */ using SimulatorSha1Digest = std::array; +/*! \brief A text looked for in a request: a header's value, a path or an + * answer. */ +struct SimulatorFoundText { + bool found; /*!< Whether there is one. */ + std::string text; /*!< The text; empty if there is none. */ +}; + +/*! \brief The first frame out of what has arrived, as + * SimulatorWebSocket::DecodeFrame() takes it. */ +struct SimulatorWebSocketFrame { + bool complete; /*!< Whether a whole frame had arrived. */ + uint8_t opcode; /*!< Its opcode. */ + std::string payload; /*!< Its payload, unmasked. */ +}; + /*! * \brief The WebSocket protocol of the simulator's web page. * @@ -40,7 +57,8 @@ class SimulatorWebSocket { static constexpr uint8_t kSha1StateWords{5}; using Sha1State = std::array; - static bool GetKey(std::string const& request, std::string* key); + MAXMATRIX_NODISCARD static SimulatorFoundText GetKey( + std::string const& request); static std::string PadSha1Message(std::string const& message); static Sha1State ProcessSha1Block(std::string const& padded, size_t offset, Sha1State state); @@ -53,11 +71,11 @@ class SimulatorWebSocket { * The answer is the 101 response with the accept key the browser checks. * * \param[in] request The whole HTTP request, headers included. - * \param[out] answer The response to send back; left as it was on false. - * \return True, or false if the request has no `Sec-WebSocket-Key`. + * \return The response to send back, or none if the request has no + * `Sec-WebSocket-Key`. */ - static bool GetHandshakeAnswer(std::string const& request, - std::string* answer); + MAXMATRIX_NODISCARD static SimulatorFoundText GetHandshakeAnswer( + std::string const& request); /*! * \brief Wraps a text into a frame. @@ -77,16 +95,14 @@ class SimulatorWebSocket { * The payload is unmasked, as a browser always masks it, and the frame is * removed from `buffer`. A frame that has not fully arrived stays in `buffer` * for the next call. A frame with a 64 bit length is not read: `buffer` is - * cleared, and false comes back. + * cleared, and no frame comes back. * * \param[in,out] buffer What has arrived on the connection and is not yet * decoded. - * \param[out] opcode The opcode of the frame. - * \param[out] payload The payload of the frame, unmasked. - * \return True, or false if `buffer` holds no complete frame. + * \return The frame, or none if `buffer` holds no complete frame. */ - static bool DecodeFrame(std::string* buffer, uint8_t* opcode, - std::string* payload); + MAXMATRIX_NODISCARD static SimulatorWebSocketFrame DecodeFrame( + std::string& buffer); /*! * \brief Converts the browser's key into the key it expects back. diff --git a/simulator/SimulatorFrontEnd.cpp b/simulator/SimulatorFrontEnd.cpp index 46b58ff..5cda538 100644 --- a/simulator/SimulatorFrontEnd.cpp +++ b/simulator/SimulatorFrontEnd.cpp @@ -66,7 +66,7 @@ void SimulatorFrontEnd::Follow(SimulatorPanel& panel, uint32_t now) { web_.Task(panel, printed); } serial_host_.Send(printed); - serial_host_.Task(&mock::serial_input); + mock::serial_input += serial_host_.Task(); if (panel.IsDrawDue(now)) { if (web_on_) { diff --git a/simulator/SimulatorOptions.cpp b/simulator/SimulatorOptions.cpp index 807d5e6..8cbc285 100644 --- a/simulator/SimulatorOptions.cpp +++ b/simulator/SimulatorOptions.cpp @@ -29,7 +29,7 @@ bool SimulatorOptions::Parse(int argc, char** argv) { std::vector const arguments(argv, argv + argc); for (size_t i{1}; i < arguments.size(); i++) { - if (!ParseOption(arguments, &i)) { + if (!ParseOption(arguments, i)) { return false; } } @@ -48,13 +48,13 @@ void SimulatorOptions::PrintUsage(char const* program) { } /* - * Reads the option at `*index`, and its value if it has one: `*index` is then + * Reads the option at `index`, and its value if it has one: `index` is then * moved on to the value. Returns false if the option is unknown, lacks its * value or has a value it cannot take. */ bool SimulatorOptions::ParseOption(std::vector const& arguments, - size_t* index) { - std::string const option = arguments[*index]; + size_t& index) { + std::string const option = arguments[index]; if (option == "--upside-down") { upside_down_ = true; @@ -64,11 +64,11 @@ bool SimulatorOptions::ParseOption(std::vector const& arguments, web_ = true; return true; } - if ((*index + 1) >= arguments.size()) { + if ((index + 1) >= arguments.size()) { return false; } - ++*index; - return ParseValue(option, arguments[*index]); + ++index; + return ParseValue(option, arguments[index]); } /* @@ -78,13 +78,13 @@ bool SimulatorOptions::ParseOption(std::vector const& arguments, bool SimulatorOptions::ParseValue(std::string const& option, char const* value) { if (option == "--port") { - return ConvertToPort(value, &port_); + return Keep(ConvertToPort(value), port_); } if (option == "--tcp") { - return ConvertToPort(value, &tcp_port_); + return Keep(ConvertToPort(value), tcp_port_); } if (option == "--for") { - return ConvertToRunFor(value, &run_for_); + return Keep(ConvertToRunFor(value), run_for_); } if (option == "--wiring") { wiring_name_ = value; @@ -101,14 +101,15 @@ bool SimulatorOptions::ParseValue(std::string const& option, } /* - * Converts the value of --port or --tcp into `*port`: a decimal number from 1 - * to 65535 and nothing else. Returns false if the value is no number, or out of - * range; `*port` is then left as it was. + * Converts the value of --port or --tcp into a port: a decimal number from 1 to + * 65535 and nothing else. It is not valid if the value is no number, or out of + * range. * * atoi() and a cast, as before, turned 70000 into port 4464 and "80x" into port * 80, so the simulator listened somewhere else than asked without a word. */ -bool SimulatorOptions::ConvertToPort(char const* text, uint16_t* port) { +SimulatorOptions::Converted SimulatorOptions::ConvertToPort( + char const* text) { char* end{nullptr}; // uint64_t holds what strtoul() returns on every host, until the range check // below. @@ -116,24 +117,22 @@ bool SimulatorOptions::ConvertToPort(char const* text, uint16_t* port) { /* strtoul() takes a sign and wraps "-1" round to ULONG_MAX, which the range * check then refuses */ - if ((end == text) || (*end != '\0') || (value == 0) || - (value > kSimulatorOptionsMaxPort)) { - return false; - } - *port = static_cast(value); - return true; + bool const valid{(end != text) && (*end == '\0') && (value != 0) && + (value <= kSimulatorOptionsMaxPort)}; + return Converted{valid, static_cast(value)}; } /* * Converts the value of --for, the seconds as a decimal number, fractions - * included, and nothing else, into the milliseconds `*run_for`. Returns false - * if the value is no number, or not a single millisecond, or more than the - * milliseconds fit; `*run_for` is then left as it was. + * included, and nothing else, into milliseconds. They are not valid if the + * value is no number, or not a single millisecond, or more than the + * milliseconds fit. * * atof(), as before, took "2x" as two seconds, and a negative or a huge number * reached a cast to uint32_t that is undefined for it. */ -bool SimulatorOptions::ConvertToRunFor(char const* text, uint32_t* run_for) { +SimulatorOptions::Converted SimulatorOptions::ConvertToRunFor( + char const* text) { char* end{nullptr}; double const milliseconds{strtod(text, &end) * 1000}; @@ -142,8 +141,7 @@ bool SimulatorOptions::ConvertToRunFor(char const* text, uint32_t* run_for) { bool const in_range{(milliseconds >= 1) && (milliseconds <= kSimulatorOptionsMaxRunFor)}; if ((end == text) || (*end != '\0') || !in_range) { - return false; + return Converted{false, 0}; } - *run_for = static_cast(milliseconds); - return true; + return Converted{true, static_cast(milliseconds)}; } diff --git a/simulator/SimulatorOptions.h b/simulator/SimulatorOptions.h index 4b206f9..0370731 100644 --- a/simulator/SimulatorOptions.h +++ b/simulator/SimulatorOptions.h @@ -44,10 +44,28 @@ class SimulatorOptions { char const* elf_file_{nullptr}; std::string serial_input_; - bool ParseOption(std::vector const& arguments, size_t* index); + /* a number read from the command line, and whether it is one the option + * takes */ + template + struct Converted { + bool valid; + Number value; + }; + + bool ParseOption(std::vector const& arguments, size_t& index); bool ParseValue(std::string const& option, char const* value); - static bool ConvertToPort(char const* text, uint16_t* port); - static bool ConvertToRunFor(char const* text, uint32_t* run_for); + MAXMATRIX_NODISCARD static Converted ConvertToPort( + char const* text); + MAXMATRIX_NODISCARD static Converted ConvertToRunFor( + char const* text); + // Keeps `converted` in `option` if it is valid, and says whether it is. + template + static bool Keep(Converted converted, Number& option) { + if (converted.valid) { + option = converted.value; + } + return converted.valid; + } public: /*! diff --git a/simulator/SimulatorRun.h b/simulator/SimulatorRun.h index 57a061a..5d4e14d 100644 --- a/simulator/SimulatorRun.h +++ b/simulator/SimulatorRun.h @@ -41,7 +41,9 @@ class SimulatorRun { * \brief Sets a run up from its command line. * * It reads the options, draws the panel for their wiring and mounting, and - * gives the mock the chain every example has and the serial input. + * gives the mock the chain every example has and the serial input. It sets + * up the caller's objects rather than returning new ones, as the tick reaches + * those through a plain function pointer (FN-8). * * \param[in] argc The number of arguments, the program's name included. * \param[in] argv The arguments. diff --git a/simulator/Web/SimulatorWeb.cpp b/simulator/Web/SimulatorWeb.cpp index 3ae4b35..8353b5e 100644 --- a/simulator/Web/SimulatorWeb.cpp +++ b/simulator/Web/SimulatorWeb.cpp @@ -56,13 +56,10 @@ bool SimulatorWeb::Begin(uint16_t port, char const* page_path) { } void SimulatorWeb::Task(SimulatorPanel& panel, std::string const& printed) { - std::vector messages; - if (mock::frames != logged_frames_) { LogFrame(); } - host_.Task(&messages); - for (std::string const& message : messages) { + for (std::string const& message : host_.Task()) { Command(panel, message); } serial_output_ += printed; diff --git a/test/ControlCommandTest.cpp b/test/ControlCommandTest.cpp index f5218f7..ad698a8 100644 --- a/test/ControlCommandTest.cpp +++ b/test/ControlCommandTest.cpp @@ -66,35 +66,32 @@ TEST(ControlCommandTest, FitsRefusesALineBreak) { // the answer to picture, as max_matrix::Command prints it: "Hi" from the left // edge and the empty columns after it TEST(ControlCommandTest, DecodesThePicture) { - std::vector columns; std::vector expected{0x7F, 0x08, 0x08, 0x7F, 0x00, 0x44, 0x7D, 0x40}; expected.resize(static_cast(kControlNumberOfColumns), 0x00); - ASSERT_TRUE(ControlCommand::DecodePicture( + ControlPicture const hi{ControlCommand::DecodePicture( "picture=7F08087F00447D40" + - std::string((2 * kControlNumberOfColumns) - 16, '0'), - &columns)); - EXPECT_EQ(columns, expected); - ASSERT_TRUE(ControlCommand::DecodePicture( - "picture=ff" + std::string((2 * kControlNumberOfColumns) - 2, '0'), - &columns)); - EXPECT_EQ(columns[0], 0xFF); + std::string((2 * kControlNumberOfColumns) - 16, '0'))}; + ASSERT_TRUE(hi.answers_picture); + EXPECT_EQ(hi.columns, expected); + ControlPicture const lower_case{ControlCommand::DecodePicture( + "picture=ff" + std::string((2 * kControlNumberOfColumns) - 2, '0'))}; + ASSERT_TRUE(lower_case.answers_picture); + EXPECT_EQ(lower_case.columns[0], 0xFF); } // a picture of another chain, or one cut short, is still an answer to picture, // but has no columns to draw; any other line is no answer to it TEST(ControlCommandTest, DecodesAPictureItCannotDrawAsEmpty) { - std::vector columns{1, 2, 3}; - - EXPECT_TRUE(ControlCommand::DecodePicture( - "picture=" + std::string((2 * kControlNumberOfColumns) + 2, '0'), - &columns)); - EXPECT_TRUE(columns.empty()); - EXPECT_TRUE(ControlCommand::DecodePicture( - "picture=" + std::string((2 * kControlNumberOfColumns) - 1, '0') + "x", - &columns)); - EXPECT_TRUE(columns.empty()); - EXPECT_FALSE(ControlCommand::DecodePicture("ok", &columns)); + ControlPicture const too_long{ControlCommand::DecodePicture( + "picture=" + std::string((2 * kControlNumberOfColumns) + 2, '0'))}; + EXPECT_TRUE(too_long.answers_picture); + EXPECT_TRUE(too_long.columns.empty()); + ControlPicture const no_hex{ControlCommand::DecodePicture( + "picture=" + std::string((2 * kControlNumberOfColumns) - 1, '0') + "x")}; + EXPECT_TRUE(no_hex.answers_picture); + EXPECT_TRUE(no_hex.columns.empty()); + EXPECT_FALSE(ControlCommand::DecodePicture("ok").answers_picture); EXPECT_FALSE( - ControlCommand::DecodePicture("error: unknown command", &columns)); + ControlCommand::DecodePicture("error: unknown command").answers_picture); } diff --git a/test/ControlLinkTest.cpp b/test/ControlLinkTest.cpp index 70a10e9..c22025a 100644 --- a/test/ControlLinkTest.cpp +++ b/test/ControlLinkTest.cpp @@ -35,11 +35,11 @@ class FakePort : public ControlPort { written += data; return true; } - bool Read(std::string* data) override { + bool Read(std::string& data) override { if (!open) { return false; } - *data += incoming; + data += incoming; incoming.clear(); if (gone) { open = false; @@ -49,6 +49,15 @@ class FakePort : public ControlPort { void Close() override { open = false; } }; +// Calls Task() and appends the lines it read to `lines`, as the window logs +// them one after another; returns whether the port is still open. +bool TaskInto(ControlLink& link, std::vector& lines) { + ControlLinkLines const read{link.Task()}; + + lines.insert(lines.end(), read.lines.begin(), read.lines.end()); + return read.open; +} + // opening the port resets an Uno, and a line sent before SerialControl has // started is lost; the link holds back until the sketch says ready TEST(ControlLinkTest, WaitsForReadyOnABoard) { @@ -62,7 +71,7 @@ TEST(ControlLinkTest, WaitsForReadyOnABoard) { EXPECT_EQ(port.written, ""); port.incoming = "ready\r\n"; - EXPECT_TRUE(link.Task(&lines)); + EXPECT_TRUE(TaskInto(link, lines)); EXPECT_TRUE(link.IsReady()); EXPECT_TRUE(link.Send("text=Hi")); EXPECT_EQ(port.written, "text=Hi\n"); @@ -89,10 +98,10 @@ TEST(ControlLinkTest, CutsWhatArrivesIntoLines) { link.Begin(false); port.incoming = "o"; - link.Task(&lines); + TaskInto(link, lines); EXPECT_TRUE(lines.empty()); port.incoming = "k\r\nerror: out of range\r\nre"; - link.Task(&lines); + TaskInto(link, lines); EXPECT_EQ(lines, (std::vector{"ok", "error: out of range"})); } @@ -105,7 +114,7 @@ TEST(ControlLinkTest, CutsALineThatNeverEnds) { link.Begin(false); port.incoming = std::string(kControlLinkMaxLineLength + 10, 'x'); - link.Task(&lines); + TaskInto(link, lines); ASSERT_EQ(lines.size(), 1u); EXPECT_EQ(lines[0].size(), kControlLinkMaxLineLength); } @@ -120,7 +129,7 @@ TEST(ControlLinkTest, SaysWhenThePortIsGone) { link.Begin(false); port.incoming = "ok\r\n"; port.gone = true; - EXPECT_FALSE(link.Task(&lines)); + EXPECT_FALSE(TaskInto(link, lines)); EXPECT_EQ(lines, (std::vector{"ok"})); EXPECT_FALSE(link.IsReady()); EXPECT_FALSE(link.Send("clear")); @@ -135,10 +144,10 @@ TEST(ControlLinkTest, BeginForgetsHalfALine) { link.Begin(true); port.incoming = "rea"; - link.Task(&lines); + TaskInto(link, lines); link.Begin(true); port.incoming = "dy\r\n"; - link.Task(&lines); + TaskInto(link, lines); EXPECT_EQ(lines, (std::vector{"dy"})); EXPECT_FALSE(link.IsReady()); } @@ -163,7 +172,7 @@ TEST(ControlLinkTest, AsksForThePictureOncePerInterval) { link.AskForPicture(1010); EXPECT_EQ(port.written, "picture\n"); port.incoming = Picture("81"); - link.Task(&lines); + TaskInto(link, lines); EXPECT_TRUE(lines.empty()); ASSERT_EQ(link.GetPicture().size(), static_cast(kControlNumberOfColumns)); @@ -200,12 +209,12 @@ TEST(ControlLinkTest, DropsAPictureAskedForBeforeACommand) { link.AskForPicture(0); link.Send("setDot=0,0,1"); port.incoming = Picture("00") + "ok\r\n"; - link.Task(&lines); + TaskInto(link, lines); EXPECT_TRUE(link.GetPicture().empty()); EXPECT_EQ(lines, (std::vector{"ok"})); link.AskForPicture(kControlLinkPictureIntervalMs); port.incoming = Picture("01"); - link.Task(&lines); + TaskInto(link, lines); ASSERT_FALSE(link.GetPicture().empty()); EXPECT_EQ(link.GetPicture()[0], 0x01); } @@ -221,7 +230,7 @@ TEST(ControlLinkTest, AsksAgainWhenTheBoardHasStartedAgain) { link.Begin(false); link.AskForPicture(0); port.incoming = "ready\r\n"; - link.Task(&lines); + TaskInto(link, lines); EXPECT_EQ(lines, (std::vector{"ready"})); link.AskForPicture(kControlLinkPictureIntervalMs); EXPECT_EQ(port.written, "picture\npicture\n"); diff --git a/test/ControlPortTest.cpp b/test/ControlPortTest.cpp index 92a2bb6..024527d 100644 --- a/test/ControlPortTest.cpp +++ b/test/ControlPortTest.cpp @@ -43,8 +43,7 @@ std::string Receive(int descriptor) { std::string ReadUntilReceived(ControlPort& port) { std::string received; - for (int16_t i{0}; (i < 50) && received.empty() && port.Read(&received); - i++) { + for (int16_t i{0}; (i < 50) && received.empty() && port.Read(received); i++) { usleep(10000); } return received; @@ -93,7 +92,7 @@ TEST_F(ControlSerialPortTest, ReadDoesNotWait) { std::string received; ASSERT_TRUE(port.Open(name_, 115200)); - EXPECT_TRUE(port.Read(&received)); + EXPECT_TRUE(port.Read(received)); EXPECT_EQ(received, ""); } @@ -107,7 +106,7 @@ TEST_F(ControlSerialPortTest, ReadSaysWhenTheBoardIsGone) { ASSERT_TRUE(port.Open(name_, 115200)); close(board_); board_ = -1; - EXPECT_FALSE(port.Read(&received)); + EXPECT_FALSE(port.Read(received)); EXPECT_FALSE(port.IsOpen()); } @@ -141,7 +140,7 @@ TEST(ControlTcpPortTest, CarriesBothWaysToTheSimulator) { ASSERT_TRUE(port.Open(kPort)); EXPECT_TRUE(port.Write("clear\n")); for (int16_t i{0}; (i < 50) && received.empty(); i++) { - host.Task(&received); + received += host.Task(); usleep(10000); } EXPECT_EQ(received, "clear\n"); @@ -159,9 +158,9 @@ TEST(ControlTcpPortTest, ReadSaysWhenTheSimulatorIsGone) { SimulatorSerialHost host; ASSERT_TRUE(host.Begin(kPort)); ASSERT_TRUE(port.Open(kPort)); - host.Task(&received); + received += host.Task(); } - for (int16_t i{0}; (i < 50) && port.Read(&received); i++) { + for (int16_t i{0}; (i < 50) && port.Read(received); i++) { usleep(10000); } EXPECT_FALSE(port.IsOpen()); diff --git a/test/SimulatorSerialHostTest.cpp b/test/SimulatorSerialHostTest.cpp index 027274e..64aab1c 100644 --- a/test/SimulatorSerialHostTest.cpp +++ b/test/SimulatorSerialHostTest.cpp @@ -73,7 +73,7 @@ std::string TaskUntilReceived(SimulatorSerialHost& host) { std::string received; for (int16_t i{0}; (i < 100) && received.empty(); i++) { - host.Task(&received); + received += host.Task(); usleep(10000); } return received; @@ -105,10 +105,10 @@ TEST(SimulatorSerialHostTest, ClosesASecondClient) { ASSERT_TRUE(host.Begin(kPort)); int const first{Connect()}; ASSERT_GE(first, 0); - host.Task(&received); + received += host.Task(); int const second{Connect()}; ASSERT_GE(second, 0); - host.Task(&received); + received += host.Task(); EXPECT_TRUE(IsClosedByHost(second)); host.Send("ok\r\n"); @@ -126,9 +126,9 @@ TEST(SimulatorSerialHostTest, TakesTheNextClientOnceTheFirstHasGone) { ASSERT_TRUE(host.Begin(kPort)); int const first{Connect()}; ASSERT_GE(first, 0); - host.Task(&received); + received += host.Task(); close(first); - host.Task(&received); + received += host.Task(); int const next{Connect()}; ASSERT_GE(next, 0); diff --git a/test/SimulatorWebHostTest.cpp b/test/SimulatorWebHostTest.cpp index e7a4714..441b697 100644 --- a/test/SimulatorWebHostTest.cpp +++ b/test/SimulatorWebHostTest.cpp @@ -51,7 +51,7 @@ TEST(SimulatorWebHostTest, TaskDoesNotWaitForAConnectionThatSaysNothing) { }}; auto const start{std::chrono::steady_clock::now()}; - host.Task(&messages); + messages = host.Task(); auto const elapsed{std::chrono::duration_cast( std::chrono::steady_clock::now() - start)}; diff --git a/test/SimulatorWebSocketTest.cpp b/test/SimulatorWebSocketTest.cpp index 0051474..dd1ab6f 100644 --- a/test/SimulatorWebSocketTest.cpp +++ b/test/SimulatorWebSocketTest.cpp @@ -98,12 +98,12 @@ TEST(SimulatorWebSocketTest, AcceptKeyMatchesTheRfcExample) { /* header names are case-insensitive, and a browser may put more than one space * after the colon */ TEST(SimulatorWebSocketTest, HandshakeFindsTheKeyInAnyCase) { - std::string answer; - - ASSERT_TRUE(SimulatorWebSocket::GetHandshakeAnswer( + SimulatorFoundText const found{SimulatorWebSocket::GetHandshakeAnswer( "GET /ws HTTP/1.1\r\nSEC-WEBSOCKET-KEY: " - "dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n", - &answer)); + "dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n")}; + std::string const& answer{found.text}; + + ASSERT_TRUE(found.found); EXPECT_EQ(answer.compare(0, 13, "HTTP/1.1 101 "), 0); EXPECT_NE( answer.find("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n"), @@ -112,10 +112,9 @@ TEST(SimulatorWebSocketTest, HandshakeFindsTheKeyInAnyCase) { } TEST(SimulatorWebSocketTest, HandshakeWithoutKeyFails) { - std::string answer; - EXPECT_FALSE(SimulatorWebSocket::GetHandshakeAnswer( - "GET /ws HTTP/1.1\r\nHost: localhost\r\n\r\n", &answer)); + "GET /ws HTTP/1.1\r\nHost: localhost\r\n\r\n") + .found); } /* 125 bytes is the longest payload whose length fits in the second byte; a @@ -143,75 +142,69 @@ TEST(SimulatorWebSocketTest, EncodeUsesThe16BitLengthFrom126Bytes) { TEST(SimulatorWebSocketTest, DecodeUnmasksWhatABrowserSends) { std::string buffer = ClientFrame("wiring GENERIC"); - std::string payload; - uint8_t opcode{0}; - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(opcode, kSimulatorWebSocketOpcodeText); - EXPECT_EQ(payload, "wiring GENERIC"); + SimulatorWebSocketFrame const frame{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(frame.complete); + EXPECT_EQ(frame.opcode, kSimulatorWebSocketOpcodeText); + EXPECT_EQ(frame.payload, "wiring GENERIC"); EXPECT_TRUE(buffer.empty()); } TEST(SimulatorWebSocketTest, DecodeReadsThe16BitLength) { std::string const long_text(200, 'x'); std::string buffer = ClientFrame(long_text); - std::string payload; - uint8_t opcode{0}; - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(payload, long_text); + SimulatorWebSocketFrame const frame{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(frame.complete); + EXPECT_EQ(frame.payload, long_text); } /* a frame may arrive over several reads; until it is whole, nothing is taken * from the buffer */ TEST(SimulatorWebSocketTest, DecodeWaitsForTheWholeFrame) { - std::string const frame = ClientFrame("hello"); + std::string const sent = ClientFrame("hello"); std::string buffer; - std::string payload; - uint8_t opcode{0}; - for (size_t i{0}; (i + 1) < frame.size(); i++) { - buffer += frame[i]; - ASSERT_FALSE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)) + for (size_t i{0}; (i + 1) < sent.size(); i++) { + buffer += sent[i]; + ASSERT_FALSE(SimulatorWebSocket::DecodeFrame(buffer).complete) << "after " << (i + 1) << " bytes"; ASSERT_EQ(buffer.size(), i + 1); } - buffer += frame.back(); - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(payload, "hello"); + buffer += sent.back(); + SimulatorWebSocketFrame const frame{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(frame.complete); + EXPECT_EQ(frame.payload, "hello"); } /* the page sends "hello" and a command at once when it opens; both have to come * out, in order */ TEST(SimulatorWebSocketTest, DecodeTakesOneFrameAtATime) { std::string buffer = ClientFrame("hello") + ClientFrame("upside-down 1"); - std::string payload; - uint8_t opcode{0}; - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(payload, "hello"); - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(payload, "upside-down 1"); - EXPECT_FALSE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); + SimulatorWebSocketFrame const first{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(first.complete); + EXPECT_EQ(first.payload, "hello"); + SimulatorWebSocketFrame const second{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(second.complete); + EXPECT_EQ(second.payload, "upside-down 1"); + EXPECT_FALSE(SimulatorWebSocket::DecodeFrame(buffer).complete); } TEST(SimulatorWebSocketTest, DecodeDropsA64BitLength) { std::string buffer = std::string("\x81\xFF", 2) + std::string(12, '\0'); - std::string payload; - uint8_t opcode{0}; - EXPECT_FALSE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); + EXPECT_FALSE(SimulatorWebSocket::DecodeFrame(buffer).complete); EXPECT_TRUE(buffer.empty()); } TEST(SimulatorWebSocketTest, DecodeReadsWhatEncodeWrites) { std::string buffer = SimulatorWebSocket::EncodeFrame(std::string(300, 'y')); - std::string payload; - uint8_t opcode{0}; - ASSERT_TRUE(SimulatorWebSocket::DecodeFrame(&buffer, &opcode, &payload)); - EXPECT_EQ(opcode, kSimulatorWebSocketOpcodeText); - EXPECT_EQ(payload, std::string(300, 'y')); + SimulatorWebSocketFrame const frame{SimulatorWebSocket::DecodeFrame(buffer)}; + ASSERT_TRUE(frame.complete); + EXPECT_EQ(frame.opcode, kSimulatorWebSocketOpcodeText); + EXPECT_EQ(frame.payload, std::string(300, 'y')); } } // namespace From 3f18374d31f1274df0ea9153f877f479acdafbab Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 15:58:14 +0100 Subject: [PATCH 2/2] OIL.md: 41 is #126 as well --- OIL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OIL.md b/OIL.md index ce8a903..6b2a71f 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 | +| 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 | | 42 | A newer avr-gcc as a cross-check | 41 | done | | | 43 | Bit operations in one class, from the template | 41 | done | #109 |