10#include "gtest/gtest.h"
23TEST(TypedPortsTest, UnwrapTypeAlias) {
28 TypeAliasType channelAlias(
"channelAlias",
"ChannelAlias", &channel);
36TEST(TypedPortsTest, GetUnwrappedAs) {
38 StructType payload(
"payload", {{
"data", &bits}});
40 TypeAliasType nestedAlias(
"nestedAlias",
"NestedAlias", &alias);
42 TypeAliasType channelAlias(
"channelAlias",
"ChannelAlias", &channel);
43 ChannelType outerChannel(
"outerChannel", &channelAlias);
61TEST(TypedPortsTest, VoidTypeCompatibility) {
74TEST(TypedPortsTest, BoolTypeCompatibility) {
87TEST(TypedPortsTest, SignedIntTypeCompatibility) {
137TEST(TypedPortsTest, UnsignedIntTypeCompatibility) {
203 static constexpr std::string_view _ESI_ID =
"MyModule.TestStruct";
208struct DeserializerWithESIID {
209 static constexpr std::string_view _ESI_ID =
"MyModule.DeserializedStruct";
211 class TypeDeserializer
212 :
public QueuedDecodeTypeDeserializer<DeserializerWithESIID> {
214 using Base = QueuedDecodeTypeDeserializer<DeserializerWithESIID>;
218 explicit TypeDeserializer(OutputCallback output)
219 : Base(std::move(output)) {}
222 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg)
override {
229TEST(TypedPortsTest, ESIIDTypeCompatibility) {
231 StructType matchType(
"MyModule.TestStruct", {});
235 StructType mismatchType(
"OtherModule.OtherStruct", {});
240 UIntType uintWithMatchingID(
"MyModule.TestStruct", 32);
244TEST(TypedPortsTest, NullPortTypeThrows) {
254struct UnknownCppType {
258TEST(TypedPortsTest, FallbackThrows) {
272 MockWritePort(
const Type *type) : WriteChannelPort(type) {}
274 void connect(
const ConnectOptions &opts = {})
override {
278 void disconnect()
override { connected =
false; }
279 bool isConnected()
const override {
return connected; }
281 MessageData lastWritten;
283 bool acceptTryWrites =
true;
286 void writeImpl(
const MessageData &data)
override { lastWritten =
data; }
287 bool tryWriteImpl(
const MessageData &data)
override {
288 if (!acceptTryWrites)
295 bool connected =
false;
302 using WriteChannelPort::WriteChannelPort;
305 std::vector<MessageData> written;
308 void writeImpl(
const MessageData &data)
override { written.push_back(data); }
309 bool tryWriteImpl(
const MessageData &data)
override {
313 written.push_back(data);
318TEST(TypedPortsTest, TranslatedTryWriteKeepsNothingWhenRefused) {
320 StructType into(
"into", {{
"a", &u8}, {
"b", &u8}});
323 {{
"f0", {{
"a"}}}, {
"f1", {{
"b"}}}});
324 CreditedWritePort port(&window);
329 EXPECT_FALSE(port.tryWrite(data));
330 EXPECT_TRUE(port.flush());
331 EXPECT_TRUE(port.written.empty());
335 EXPECT_TRUE(port.tryWrite(data));
336 EXPECT_EQ(port.written.size(), 1u);
337 EXPECT_FALSE(port.flush());
339 EXPECT_TRUE(port.flush());
340 EXPECT_EQ(port.written.size(), 2u);
343TEST(TypedPortsTest, TypedWritePortConnectThrowsOnMismatch) {
345 MockWritePort mock(&uint32);
350TEST(TypedPortsTest, TypedWritePortConnectSucceeds) {
352 MockWritePort mock(&sint31);
354 EXPECT_NO_THROW(typed.connect());
355 EXPECT_TRUE(typed.isConnected());
358TEST(TypedPortsTest, TypedWritePortRoundTrip) {
360 MockWritePort mock(&sint15);
368 ASSERT_EQ(mock.lastWritten.getSize(), 2u);
371TEST(TypedPortsTest, SignExtensionNonByteAligned) {
377 EXPECT_EQ(wi.
bytes, 1u);
398 EXPECT_EQ(wi.
bytes, 3u);
399 uint8_t wire[3] = {0xFF, 0xFF, 0x3F};
408 uint8_t wire[3] = {0xFF, 0xFF, 0x1F};
411 EXPECT_EQ(val, 0x1FFFFF);
415TEST(TypedPortsTest, TypedWritePortVoid) {
417 MockWritePort mock(&voidType);
419 EXPECT_NO_THROW(typed.connect());
422 ASSERT_EQ(mock.lastWritten.getSize(), 1u);
423 EXPECT_EQ(mock.lastWritten.getData()[0], 0);
433 MockReadPort(
const Type *type) : ReadChannelPort(type) {}
435 void connect(std::function<
bool(MessageData)>,
436 const ConnectOptions & = {})
override {
437 mode = Mode::Callback;
439 void connect(
const ConnectOptions & = {})
override { mode = Mode::Polling; }
441 void read(MessageData &outData)
override { outData = nextResponse; }
442 std::future<MessageData> readAsync()
override {
443 std::promise<MessageData> p;
444 p.set_value(nextResponse);
445 return p.get_future();
448 MessageData nextResponse;
451TEST(TypedPortsTest, TypedReadPortCustomDeserializerVerifiesESIID) {
452 StructType matchType(
"MyModule.DeserializedStruct", {});
453 MockReadPort matching(&matchType);
455 EXPECT_NO_THROW(ok.connect());
457 StructType mismatchType(
"OtherModule.OtherStruct", {});
458 MockReadPort mismatch(&mismatchType);
465 CallbackDrivenMockReadPort(
const Type *type) : ReadChannelPort(type) {}
467 bool deliver(std::unique_ptr<SegmentedMessageData> msg) {
469 pending = std::move(msg);
470 return retryPending();
473 bool retryPending() {
475 throw std::runtime_error(
476 "CallbackDrivenMockReadPort::retryPending with no message");
477 if (!invokeCallback(pending))
483 bool hasPending()
const {
return static_cast<bool>(pending); }
484 size_t numActiveCallbacks()
const {
return activeCallbacks; }
486 size_t deliveryCount = 0;
489 std::unique_ptr<SegmentedMessageData> pending;
492class ThrowOnCopyReadCallback {
494 explicit ThrowOnCopyReadCallback(std::shared_ptr<bool> shouldThrow)
495 : shouldThrow(std::move(shouldThrow)) {}
497 ThrowOnCopyReadCallback(
const ThrowOnCopyReadCallback &other)
498 : shouldThrow(other.shouldThrow) {
500 throw std::runtime_error(
"ThrowOnCopyReadCallback copy failure");
503 ThrowOnCopyReadCallback(ThrowOnCopyReadCallback &&) =
default;
504 ThrowOnCopyReadCallback &operator=(
const ThrowOnCopyReadCallback &) =
default;
505 ThrowOnCopyReadCallback &operator=(ThrowOnCopyReadCallback &&) =
default;
507 bool operator()(std::unique_ptr<SegmentedMessageData> &)
const {
512 std::shared_ptr<bool> shouldThrow;
515static MessageData packUint32Words(std::initializer_list<uint32_t> values) {
516 std::vector<uint8_t> bytes(values.size() *
sizeof(uint32_t));
518 for (uint32_t value : values) {
519 std::memcpy(bytes.data() + offset, &value,
sizeof(value));
520 offset +=
sizeof(value);
525struct BufferedSequence {
526 std::vector<uint32_t> values;
528 class TypeDeserializer
529 :
public QueuedDecodeTypeDeserializer<BufferedSequence> {
531 using Base = QueuedDecodeTypeDeserializer<BufferedSequence>;
535 explicit TypeDeserializer(OutputCallback output)
536 : Base(std::move(output)) {}
539 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg)
override {
541 const MessageData &flat = msg->asMessageData(scratch);
542 if (flat.
getSize() %
sizeof(uint32_t) != 0)
543 throw std::runtime_error(
544 "BufferedSequence::TypeDeserializer: truncated word payload");
546 DecodedOutputs decoded;
547 for (
size_t offset = 0; offset < flat.
getSize();
548 offset +=
sizeof(uint32_t)) {
550 std::memcpy(&value, flat.
getBytes() + offset,
sizeof(value));
551 auto sequence = std::make_unique<BufferedSequence>();
552 sequence->values.push_back(value);
553 decoded.push_back(std::move(sequence));
561TEST(TypedPortsTest, TypedReadPortPODBackpressuresAfterOneBufferedOutput) {
563 CallbackDrivenMockReadPort mock(&uint32);
567 typed.setMaxDataQueueMsgs(1);
570 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
575 mock.deliver(std::make_unique<MessageData>(packUint32Words({22}))));
576 EXPECT_FALSE(mock.hasPending());
578 mock.deliver(std::make_unique<MessageData>(packUint32Words({33}))));
579 EXPECT_TRUE(mock.hasPending());
581 std::unique_ptr<uint32_t> first = typed.read();
583 EXPECT_EQ(*first, 11u);
584 EXPECT_TRUE(mock.retryPending());
585 EXPECT_FALSE(mock.hasPending());
586 std::unique_ptr<uint32_t> second = typed.read();
588 EXPECT_EQ(*second, 22u);
589 std::unique_ptr<uint32_t> third = typed.read();
591 EXPECT_EQ(*third, 33u);
594TEST(TypedPortsTest, TypedReadPortPODRetriesSameOwnedObjectOnLaterPush) {
596 CallbackDrivenMockReadPort mock(&uint32);
599 const uint32_t *firstObject =
nullptr;
600 size_t callbackAttempts = 0;
602 typed.connect([&](std::unique_ptr<uint32_t> &value) {
605 if (callbackAttempts == 1) {
606 EXPECT_EQ(*value, 11u);
607 firstObject = value.get();
610 if (callbackAttempts == 2) {
611 EXPECT_EQ(*value, 11u);
612 EXPECT_EQ(value.get(), firstObject);
615 EXPECT_EQ(*value, 22u);
620 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
621 EXPECT_FALSE(mock.hasPending());
625 mock.deliver(std::make_unique<MessageData>(packUint32Words({22}))));
626 EXPECT_FALSE(mock.hasPending());
627 EXPECT_EQ(callbackAttempts, 3u);
630TEST(TypedPortsTest, ZeroWidthMessagePlaceholderAndEmpty) {
632 CallbackDrivenMockReadPort mock(&voidType);
635 mock.connect([&](std::unique_ptr<SegmentedMessageData> &msg) {
637 EXPECT_EQ(msg->totalSize(), 0u);
642 mock.deliver(std::make_unique<MessageData>(std::vector<uint8_t>{0})));
643 EXPECT_TRUE(mock.hasPending());
646 EXPECT_TRUE(mock.retryPending());
647 EXPECT_FALSE(mock.hasPending());
648 EXPECT_EQ(attempts, 2u);
651 EXPECT_TRUE(mock.deliver(std::make_unique<MessageData>()));
652 EXPECT_EQ(attempts, 3u);
655 mock.deliver(std::make_unique<MessageData>(std::vector<uint8_t>{0, 0})),
657 EXPECT_EQ(mock.numActiveCallbacks(), 0u);
661TEST(TypedPortsTest, TypedReadPortCustomDeserializerPokesBlockedOutput) {
663 CallbackDrivenMockReadPort mock(&uint32);
667 typed.setMaxDataQueueMsgs(1);
670 mock.deliver(std::make_unique<MessageData>(packUint32Words({10, 20}))));
671 EXPECT_EQ(mock.deliveryCount, 1u);
673 std::unique_ptr<BufferedSequence> first = typed.read();
675 ASSERT_EQ(first->values.size(), 1u);
676 EXPECT_EQ(first->values[0], 10u);
678 std::unique_ptr<BufferedSequence> second = typed.read();
680 ASSERT_EQ(second->values.size(), 1u);
681 EXPECT_EQ(second->values[0], 20u);
682 EXPECT_EQ(mock.deliveryCount, 1u);
686 TypedReadPortCustomDeserializerConsumesMultipleFramesPerRawMessage) {
688 CallbackDrivenMockReadPort mock(&uint32);
693 std::future<std::unique_ptr<BufferedSequence>> first = typed.readAsync();
694 std::future<std::unique_ptr<BufferedSequence>> second = typed.readAsync();
695 std::future<std::unique_ptr<BufferedSequence>> third = typed.readAsync();
698 mock.deliver(std::make_unique<MessageData>(packUint32Words({1, 2, 3}))));
700 std::unique_ptr<BufferedSequence> firstValue = first.get();
701 ASSERT_TRUE(firstValue);
702 EXPECT_EQ(firstValue->values[0], 1u);
704 std::unique_ptr<BufferedSequence> secondValue = second.get();
705 ASSERT_TRUE(secondValue);
706 EXPECT_EQ(secondValue->values[0], 2u);
708 std::unique_ptr<BufferedSequence> thirdValue = third.get();
709 ASSERT_TRUE(thirdValue);
710 EXPECT_EQ(thirdValue->values[0], 3u);
714 TypedReadPortCustomDeserializerQueuesMultiplePendingOutputs) {
716 CallbackDrivenMockReadPort mock(&uint32);
720 typed.setMaxDataQueueMsgs(1);
723 mock.deliver(std::make_unique<MessageData>(packUint32Words({7, 8, 9}))));
724 EXPECT_EQ(mock.deliveryCount, 1u);
726 std::unique_ptr<BufferedSequence> first = typed.read();
728 EXPECT_EQ(first->values[0], 7u);
730 std::unique_ptr<BufferedSequence> second = typed.read();
732 EXPECT_EQ(second->values[0], 8u);
734 std::unique_ptr<BufferedSequence> third = typed.read();
736 EXPECT_EQ(third->values[0], 9u);
737 EXPECT_EQ(mock.deliveryCount, 1u);
740struct FragmentedCoord {
744static_assert(
sizeof(FragmentedCoord) == 8,
"Size mismatch");
746static std::array<uint8_t,
sizeof(FragmentedCoord)> packCoordBytes(uint32_t y,
748 FragmentedCoord coord{y, x};
749 std::array<uint8_t,
sizeof(FragmentedCoord)> bytes{};
750 std::memcpy(bytes.data(), &coord,
sizeof(coord));
754struct FragmentedCoordBatch {
755 std::vector<FragmentedCoord> coords;
757 class TypeDeserializer
758 :
public QueuedDecodeTypeDeserializer<FragmentedCoordBatch> {
760 using Base = QueuedDecodeTypeDeserializer<FragmentedCoordBatch>;
764 explicit TypeDeserializer(OutputCallback output)
765 : Base(std::move(output)) {}
768 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg)
override {
772 DecodedOutputs decoded;
773 const uint8_t *bytes = flat.
getBytes();
775 while (offset < flat.
getSize()) {
776 size_t needed =
sizeof(FragmentedCoord) - partialFrameBytes.size();
777 size_t chunkSize = std::min(needed, flat.
getSize() - offset);
778 partialFrameBytes.insert(partialFrameBytes.end(), bytes + offset,
779 bytes + offset + chunkSize);
782 if (partialFrameBytes.size() !=
sizeof(FragmentedCoord))
785 FragmentedCoord coord;
786 std::memcpy(&coord, partialFrameBytes.data(),
sizeof(coord));
787 partialFrameBytes.clear();
789 auto batch = std::make_unique<FragmentedCoordBatch>();
790 batch->coords.push_back(coord);
791 decoded.push_back(std::move(batch));
798 std::vector<uint8_t> partialFrameBytes;
803 TypedReadPortCustomDeserializerConsumesSplitFramesAcrossRawMessages) {
805 CallbackDrivenMockReadPort mock(&uint32);
810 std::future<std::unique_ptr<FragmentedCoordBatch>> first = typed.readAsync();
811 std::future<std::unique_ptr<FragmentedCoordBatch>> second = typed.readAsync();
813 std::array<uint8_t,
sizeof(FragmentedCoord)> coordA = packCoordBytes(10, 20);
814 std::array<uint8_t,
sizeof(FragmentedCoord)> coordB = packCoordBytes(30, 40);
816 std::vector<uint8_t> firstChunk(coordA.begin(), coordA.begin() + 6);
817 EXPECT_TRUE(mock.deliver(
818 std::make_unique<MessageData>(
MessageData(std::move(firstChunk)))));
820 std::vector<uint8_t> secondChunk;
821 secondChunk.insert(secondChunk.end(), coordA.begin() + 6, coordA.end());
822 secondChunk.insert(secondChunk.end(), coordB.begin(), coordB.end());
823 EXPECT_TRUE(mock.deliver(
824 std::make_unique<MessageData>(
MessageData(std::move(secondChunk)))));
826 std::unique_ptr<FragmentedCoordBatch> firstBatch = first.get();
827 ASSERT_TRUE(firstBatch);
828 ASSERT_EQ(firstBatch->coords.size(), 1u);
829 EXPECT_EQ(firstBatch->coords[0].y, 10u);
830 EXPECT_EQ(firstBatch->coords[0].x, 20u);
832 std::unique_ptr<FragmentedCoordBatch> secondBatch = second.get();
833 ASSERT_TRUE(secondBatch);
834 ASSERT_EQ(secondBatch->coords.size(), 1u);
835 EXPECT_EQ(secondBatch->coords[0].y, 30u);
836 EXPECT_EQ(secondBatch->coords[0].x, 40u);
842TEST(TypedPortsTest, TypedFunctionNullThrowsAtConnect) {
848TEST(TypedPortsTest, TypedFunctionCallBeforeConnectThrows) {
851 EXPECT_THROW(typed.call(0u).get(), std::runtime_error);
854TEST(TypedPortsTest, TypedFunctionDoubleConnectThrows) {
858 ChannelType argChanType(
"channel<si24>", &argInner);
860 ChannelType resultChanType(
"channel<ui15>", &resultInner);
866 BundleType bundleType(
"func_bundle", channels);
868 MockWritePort mockWrite(&argInner);
869 CallbackDrivenMockReadPort mockRead(&resultInner);
872 mockWrite, mockRead);
876 EXPECT_THROW(typed.connect(), std::runtime_error);
880TEST(TypedPortsTest, TypedFunctionConnectVerifiesTypes) {
883 ChannelType argChanType(
"channel<si24>", &argInner);
885 ChannelType resultChanType(
"channel<ui15>", &resultInner);
891 BundleType bundleType(
"func_bundle", channels);
893 MockWritePort mockWrite(&argInner);
894 MockReadPort mockRead(&resultInner);
897 mockWrite, mockRead);
902 EXPECT_NO_THROW(typed.connect());
906TEST(TypedPortsTest, TypedFunctionConnectRejectsArgMismatch) {
908 ChannelType argChanType(
"channel<ui24>", &argInner);
910 ChannelType resultChanType(
"channel<ui15>", &resultInner);
916 BundleType bundleType(
"func_bundle", channels);
918 MockWritePort mockWrite(&argInner);
919 MockReadPort mockRead(&resultInner);
922 mockWrite, mockRead);
930TEST(TypedPortsTest, TypedFunctionCallRoundTrip) {
932 ChannelType argChanType(
"channel<si24>", &argInner);
934 ChannelType resultChanType(
"channel<ui15>", &resultInner);
940 BundleType bundleType(
"func_bundle", channels);
942 MockWritePort mockWrite(&argInner);
943 CallbackDrivenMockReadPort mockRead(&resultInner);
946 mockWrite, mockRead);
952 std::future<uint16_t> f = typed.call(arg);
955 uint16_t expected = 42;
956 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(
MessageData(
957 reinterpret_cast<const uint8_t *
>(&expected),
sizeof(expected)))));
958 uint16_t result = f.get();
959 EXPECT_EQ(result, 42);
962 ASSERT_EQ(mockWrite.lastWritten.getSize(), 3u);
980 std::vector<uint32_t> items;
982 size_t numSegments()
const override {
return 2; }
983 Segment segment(
size_t idx)
const override {
985 return {
reinterpret_cast<const uint8_t *
>(&header),
sizeof(Header)};
986 return {
reinterpret_cast<const uint8_t *
>(items.data()),
987 items.size() *
sizeof(uint32_t)};
991TEST(TypedPortsTest, ReadChannelPortSegmentedCallbackRetriesSameMessageObject) {
993 CallbackDrivenMockReadPort mock(&uint32);
995 uint32_t expected = 0x12345678;
996 const uint8_t *firstBytes =
nullptr;
997 size_t callbackCalls = 0;
999 mock.connect([&](std::unique_ptr<SegmentedMessageData> &msg) ->
bool {
1001 EXPECT_EQ(msg->numSegments(), 1u);
1003 auto *flat =
dynamic_cast<MessageData *
>(msg.get());
1004 EXPECT_NE(flat,
nullptr);
1007 EXPECT_EQ(*flat->
as<uint32_t>(), expected);
1009 if (callbackCalls == 1)
1012 EXPECT_EQ(flat->
getBytes(), firstBytes);
1014 return callbackCalls == 2;
1019 EXPECT_TRUE(mock.hasPending());
1020 EXPECT_TRUE(mock.retryPending());
1021 EXPECT_FALSE(mock.hasPending());
1022 EXPECT_EQ(callbackCalls, 2u);
1025TEST(TypedPortsTest, ReadChannelPortFlatCallbackFlattensSegmentedMessageRetry) {
1027 CallbackDrivenMockReadPort mock(&uint32);
1029 TestSegmented input;
1030 input.header.a = 0x12345678;
1031 input.header.b = 0xABCD;
1032 input.items = {1, 2, 3};
1035 size_t callbackCalls = 0;
1039 return callbackCalls == 2;
1042 EXPECT_FALSE(mock.deliver(std::make_unique<TestSegmented>(input)));
1043 EXPECT_TRUE(mock.hasPending());
1044 EXPECT_TRUE(mock.retryPending());
1045 EXPECT_FALSE(mock.hasPending());
1046 EXPECT_EQ(callbackCalls, 2u);
1049TEST(TypedPortsTest, ReadChannelPortPollingRetriesFlattenedSegmentedMessage) {
1051 CallbackDrivenMockReadPort mock(&uint32);
1053 mock.setMaxDataQueueMsgs(1);
1055 TestSegmented firstInput;
1056 firstInput.header.a = 0xAAAA5555;
1057 firstInput.header.b = 0x1357;
1058 firstInput.items = {10};
1059 MessageData firstExpected = firstInput.toMessageData();
1061 TestSegmented secondInput;
1062 secondInput.header.a = 0xDEADBEEF;
1063 secondInput.header.b = 0x2468;
1064 secondInput.items = {20, 30};
1065 MessageData secondExpected = secondInput.toMessageData();
1067 EXPECT_TRUE(mock.deliver(std::make_unique<TestSegmented>(firstInput)));
1068 EXPECT_FALSE(mock.deliver(std::make_unique<TestSegmented>(secondInput)));
1069 EXPECT_TRUE(mock.hasPending());
1072 mock.read(firstOut);
1075 EXPECT_TRUE(mock.retryPending());
1076 EXPECT_FALSE(mock.hasPending());
1079 mock.read(secondOut);
1083TEST(TypedPortsTest, ReadChannelPortPollingReadAsyncThrowsWhenDisconnected) {
1085 CallbackDrivenMockReadPort mock(&uint32);
1087 EXPECT_THROW(mock.readAsync(), std::runtime_error);
1090 std::future<MessageData> pending = mock.readAsync();
1093 EXPECT_EQ(pending.wait_for(std::chrono::milliseconds(0)),
1094 std::future_status::ready);
1095 EXPECT_THROW(pending.get(), std::future_error);
1096 EXPECT_THROW(mock.readAsync(), std::runtime_error);
1100 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1103 EXPECT_EQ(*out.as<uint32_t>(), 11u);
1106TEST(TypedPortsTest, ReadChannelPortPollingConnectRejectsReconnect) {
1108 CallbackDrivenMockReadPort mock(&uint32);
1111 EXPECT_THROW(mock.connect(), std::runtime_error);
1114TEST(TypedPortsTest, ReadChannelPortDisconnectRevokesCallback) {
1116 CallbackDrivenMockReadPort mock(&uint32);
1122 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1123 EXPECT_TRUE(mock.hasPending());
1126 EXPECT_TRUE(mock.retryPending());
1127 EXPECT_FALSE(mock.hasPending());
1131 EXPECT_EQ(*out.
as<uint32_t>(), 11u);
1134TEST(TypedPortsTest, TypedReadPortDestructorDisconnectsRawPort) {
1136 CallbackDrivenMockReadPort mock(&uint32);
1141 EXPECT_TRUE(mock.isConnected());
1144 EXPECT_FALSE(mock.isConnected());
1146 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1147 EXPECT_TRUE(mock.hasPending());
1150 reconnected.connect();
1151 EXPECT_TRUE(mock.retryPending());
1152 EXPECT_FALSE(mock.hasPending());
1154 std::unique_ptr<uint32_t> out = reconnected.read();
1156 EXPECT_EQ(*out, 11u);
1160 ReadChannelPortInvokeCallbackMaintainsCountOnCallbackCopyFailure) {
1162 CallbackDrivenMockReadPort mock(&uint32);
1163 auto shouldThrow = std::make_shared<bool>(
false);
1165 mock.connect(ThrowOnCopyReadCallback(shouldThrow));
1166 *shouldThrow =
true;
1169 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))),
1170 std::runtime_error);
1171 EXPECT_EQ(mock.numActiveCallbacks(), 0u);
1174TEST(TypedPortsTest, TypedWritePortSegmentedMessageData) {
1177 MockWritePort mock(&uint32);
1183 msg.header.a = 0x12345678;
1184 msg.header.b = 0xABCD;
1185 msg.items = {1, 2, 3};
1191 EXPECT_EQ(mock.lastWritten.getSize(), 18u);
1194 const uint8_t *bytes = mock.lastWritten.getBytes();
1197 std::memcpy(&gotA, bytes, 4);
1198 std::memcpy(&gotB, bytes + 4, 2);
1199 EXPECT_EQ(gotA, 0x12345678u);
1200 EXPECT_EQ(gotB, 0xABCDu);
1203 uint32_t gotItems[3];
1204 std::memcpy(gotItems, bytes + 6, 12);
1205 EXPECT_EQ(gotItems[0], 1u);
1206 EXPECT_EQ(gotItems[1], 2u);
1207 EXPECT_EQ(gotItems[2], 3u);
1210TEST(TypedPortsTest, WriteChannelPortTryWriteSegmented) {
1212 MockWritePort mock(&uint32);
1215 auto input = std::make_unique<TestSegmented>();
1216 input->header.a = 0x12345678;
1217 input->header.b = 0xABCD;
1218 input->items = {1, 2, 3};
1221 std::unique_ptr<SegmentedMessageData> msg = std::move(input);
1224 mock.acceptTryWrites =
false;
1225 EXPECT_FALSE(mock.tryWrite(msg));
1226 ASSERT_NE(msg,
nullptr);
1227 EXPECT_EQ(msg.get(), raw);
1228 EXPECT_EQ(mock.lastWritten.getSize(), 0u);
1231 mock.acceptTryWrites =
true;
1232 EXPECT_TRUE(mock.tryWrite(msg));
1233 EXPECT_EQ(msg,
nullptr);
1234 EXPECT_EQ(mock.lastWritten.getData(), expected.
getData());
1236 std::unique_ptr<SegmentedMessageData> null;
1237 EXPECT_THROW(mock.tryWrite(null), std::runtime_error);
1240TEST(TypedPortsTest, TypedWritePortTryWriteSegmentedUniquePtr) {
1242 MockWritePort mock(&uint32);
1247 auto msg = std::make_unique<TestSegmented>();
1250 msg->items = {100, 200};
1252 TestSegmented *raw = msg.get();
1254 mock.acceptTryWrites =
false;
1255 EXPECT_FALSE(typed.tryWrite(msg));
1256 ASSERT_NE(msg,
nullptr);
1257 EXPECT_EQ(msg.get(), raw);
1258 EXPECT_EQ(msg->items.size(), 2u);
1260 mock.acceptTryWrites =
true;
1261 EXPECT_TRUE(typed.tryWrite(msg));
1262 EXPECT_EQ(msg,
nullptr);
1263 EXPECT_EQ(mock.lastWritten.getData(), expected.
getData());
1265 std::unique_ptr<TestSegmented> null;
1266 EXPECT_THROW(typed.tryWrite(null), std::runtime_error);
1269TEST(TypedPortsTest, TypedWritePortTryWriteNonSegmentedUniquePtr) {
1271 MockWritePort mock(&uint32);
1276 auto value = std::make_unique<uint32_t>(0xDEADBEEF);
1278 mock.acceptTryWrites =
false;
1279 EXPECT_FALSE(typed.tryWrite(value));
1280 ASSERT_NE(value,
nullptr);
1281 EXPECT_EQ(*value, 0xDEADBEEFu);
1283 mock.acceptTryWrites =
true;
1284 EXPECT_TRUE(typed.tryWrite(value));
1285 EXPECT_EQ(value,
nullptr);
1286 ASSERT_EQ(mock.lastWritten.getSize(), 4u);
1287 EXPECT_EQ(*mock.lastWritten.as<uint32_t>(), 0xDEADBEEFu);
1290TEST(TypedPortsTest, TypedWritePortSegmentedNoTypeCheck) {
1294 MockWritePort mock(&sint8);
1297 EXPECT_NO_THROW(typed.connect());
1306 EXPECT_EQ(mock.lastWritten.getSize(), 10u);
1309TEST(TypedPortsTest, TypedFunctionSegmentedArg) {
1313 ChannelType argChanType(
"channel<ui32>", &argInner);
1315 ChannelType resultChanType(
"channel<ui16>", &resultInner);
1321 BundleType bundleType(
"func_bundle", channels);
1323 MockWritePort mockWrite(&argInner);
1324 CallbackDrivenMockReadPort mockRead(&resultInner);
1327 mockWrite, mockRead);
1333 arg.header.a = 0xDEAD;
1334 arg.header.b = 0xBE;
1335 arg.items = {10, 20};
1337 std::future<uint16_t> f = typed.call(arg);
1339 uint16_t expected = 99;
1340 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(
MessageData(
1341 reinterpret_cast<const uint8_t *
>(&expected),
sizeof(expected)))));
1342 uint16_t result = f.get();
1343 EXPECT_EQ(result, 99u);
1346 EXPECT_EQ(mockWrite.lastWritten.getSize(), 14u);
1348 const uint8_t *bytes = mockWrite.lastWritten.getBytes();
1350 std::memcpy(&gotA, bytes, 4);
1351 EXPECT_EQ(gotA, 0xDEADu);
1353 uint32_t gotItem0, gotItem1;
1354 std::memcpy(&gotItem0, bytes + 6, 4);
1355 std::memcpy(&gotItem1, bytes + 10, 4);
1356 EXPECT_EQ(gotItem0, 10u);
1357 EXPECT_EQ(gotItem1, 20u);
1363struct UnrecognizedCppType {
1368TEST(TypedPortsTest, VerifyTypeCompatibilityThrowsForUnsupportedType) {
1394 class TypeDeserializer {
1396 using OutputCallback = detail::TypedReadOwnedCallback<OneWord>;
1398 explicit TypeDeserializer(OutputCallback output)
1399 : output(std::move(output)) {}
1401 bool push(std::unique_ptr<SegmentedMessageData> &msg) {
1404 if (!output(pending))
1409 MessageData scratch;
1411 if (flat.
getSize() !=
sizeof(uint32_t))
1412 throw std::runtime_error(
"OneWord: bad size");
1413 pending = std::make_unique<OneWord>();
1414 std::memcpy(&pending->value, flat.
getBytes(),
sizeof(uint32_t));
1418 if (output(pending))
1424 if (pending && output(pending)) {
1432 OutputCallback output;
1433 std::unique_ptr<OneWord> pending;
1437TEST(TypedPortsTest, TypedFunctionCustomDeserializerSingleFrame) {
1439 ChannelType argChanType(
"channel<ui32>", &argInner);
1441 ChannelType resultChanType(
"channel<ui32>", &resultInner);
1447 BundleType bundleType(
"func_bundle", channels);
1449 MockWritePort mockWrite(&argInner);
1450 CallbackDrivenMockReadPort mockRead(&resultInner);
1453 mockWrite, mockRead);
1458 std::future<OneWord> f = typed.call(0u);
1461 uint32_t expected = 0xCAFE;
1462 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(
MessageData(
1463 reinterpret_cast<const uint8_t *
>(&expected),
sizeof(expected)))));
1465 OneWord result = f.get();
1466 EXPECT_EQ(result.value, expected);
1471TEST(TypedPortsTest, TypedFunctionCustomDeserializerReadsMultipleFrames) {
1477 ChannelType argChanType(
"channel<ui32>", &argInner);
1479 ChannelType resultChanType(
"channel<ui32>", &resultInner);
1485 BundleType bundleType(
"func_bundle", channels);
1487 MockWritePort mockWrite(&argInner);
1488 CallbackDrivenMockReadPort mockRead(&resultInner);
1491 mockWrite, mockRead);
1496 std::future<FragmentedCoordBatch> f = typed.call(0u);
1499 std::array<uint8_t,
sizeof(FragmentedCoord)> coordBytes =
1500 packCoordBytes(55, 77);
1501 std::vector<uint8_t> firstChunk(coordBytes.begin(), coordBytes.begin() + 6);
1502 std::vector<uint8_t> secondChunk(coordBytes.begin() + 6, coordBytes.end());
1504 mockRead.deliver(std::make_unique<MessageData>(std::move(firstChunk))));
1506 mockRead.deliver(std::make_unique<MessageData>(std::move(secondChunk))));
1508 FragmentedCoordBatch batch = f.get();
1509 ASSERT_EQ(batch.coords.size(), 1u);
1510 EXPECT_EQ(batch.coords[0].y, 55u);
1511 EXPECT_EQ(batch.coords[0].x, 77u);
1516TEST(TypedPortsTest, TypedFunctionCustomDeserializerSkipsResultTypeCheck) {
1521 ChannelType argChanType(
"channel<ui32>", &argInner);
1524 ChannelType resultChanType(
"channel<Anything>", &resultInner);
1530 BundleType bundleType(
"func_bundle", channels);
1532 MockWritePort mockWrite(&argInner);
1533 CallbackDrivenMockReadPort mockRead(&resultInner);
1536 mockWrite, mockRead);
1539 EXPECT_NO_THROW(typed.connect());
1544TEST(TypedPortsTest, TypedFunctionPipelinedCallsGetOutOfOrder) {
1551 ChannelType argChanType(
"channel<ui32>", &argInner);
1553 ChannelType resultChanType(
"channel<ui32>", &resultInner);
1559 BundleType bundleType(
"func_bundle", channels);
1561 MockWritePort mockWrite(&argInner);
1562 CallbackDrivenMockReadPort mockRead(&resultInner);
1565 mockWrite, mockRead);
1572 std::future<FragmentedCoordBatch> f1 = typed.call(0u);
1573 std::future<FragmentedCoordBatch> f2 = typed.call(0u);
1575 auto deliverCoord = [&](uint32_t y, uint32_t x) {
1576 auto bytes = packCoordBytes(y, x);
1577 std::vector<uint8_t> first(bytes.begin(), bytes.begin() + 6);
1578 std::vector<uint8_t> second(bytes.begin() + 6, bytes.end());
1580 mockRead.deliver(std::make_unique<MessageData>(std::move(first))));
1582 mockRead.deliver(std::make_unique<MessageData>(std::move(second))));
1584 deliverCoord(11, 22);
1585 deliverCoord(33, 44);
1588 FragmentedCoordBatch r2 = f2.get();
1589 ASSERT_EQ(r2.coords.size(), 1u);
1590 EXPECT_EQ(r2.coords[0].y, 33u);
1591 EXPECT_EQ(r2.coords[0].x, 44u);
1593 FragmentedCoordBatch r1 = f1.get();
1594 ASSERT_EQ(r1.coords.size(), 1u);
1595 EXPECT_EQ(r1.coords[0].y, 11u);
1596 EXPECT_EQ(r1.coords[0].x, 22u);
Arrays have a compile time specified (static) size and an element type.
Bits are just an array of bits.
Bundles represent a collection of channels.
std::vector< std::tuple< std::string, Direction, const Type * > > ChannelVector
Channels are the basic communication primitives.
A concrete flat message backed by a single vector of bytes.
const std::vector< uint8_t > & getData() const
Get the data as a vector of bytes.
const uint8_t * getBytes() const
const T * as() const
Cast to a type.
size_t getSize() const
Get the size of the data in bytes.
static MessageData from(T &t)
Cast from a type to its raw bytes.
detail::TypedReadOwnedCallback< DeserializerWithESIID > OutputCallback
std::vector< std::unique_ptr< DeserializerWithESIID > > DecodedOutputs
A ChannelPort which reads data from the accelerator.
Abstract multi-segment message.
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Structs are an ordered collection of fields, each with a name and a type.
Type aliases provide a named type which forwards to an inner type.
Root class of the ESI type system.
Strongly typed wrapper around a raw read channel.
The "void" type is a special type which can be used to represent no type.
Windows represent a fixed-size sliding window over a stream of data.
A ChannelPort which sends data to the accelerator.
static Function * get(AppID id, BundleType *type, WriteChannelPort &arg, ReadChannelPort &result)
connect(destination, source)
void verifyTypeCompatibility(const Type *portType)
WireInfo getWireInfo(const Type *portType)
const T * getUnwrappedAs(const Type *type)
Unwrap aliases and channels, then cast the payload to T.
T fromMessageData(const MessageData &msg, WireInfo wi)
Unpack a MessageData into a C++ integral value with the given wire info.
const Type * unwrapTypeAlias(const Type *type)
Unwrap TypeAliasType (possibly recursively) to get the underlying type.
Compute the wire byte count for a port type.