Minor bug fix to UsefulBuf_Tail; add tests to check UsefulBuf_Tail and test for BStr wrap with NULL output buf
diff --git a/inc/UsefulBuf.h b/inc/UsefulBuf.h
index d3d828d..0d51644 100644
--- a/inc/UsefulBuf.h
+++ b/inc/UsefulBuf.h
@@ -448,18 +448,29 @@
/**
@brief Returns bytes from the end of a UsefulBufC
- @param[in] UB The buffer to get the tail of
- @param[in] uAmount The offset from the start where the tail is to begin
+ @param[in] UB The buffer to get the tail of
+ @param[in] uAmount The offset from the start where the tail is to begin
- @return A UsefulBufC that is the tail of UB
-
+ @return A UsefulBufC that is the tail of UB or NULLUsefulBufC if
+ uAmount is greater than the length of the UsefulBufC
+
+ If the input UsefulBufC is NULL, but the len is not, then the
+ length of the tail will be calculated and returned along
+ with a NULL ptr.
*/
static inline UsefulBufC UsefulBuf_Tail(UsefulBufC UB, size_t uAmount)
{
+ UsefulBufC ReturnValue;
+
if(uAmount > UB.len) {
- return NULLUsefulBufC;
+ ReturnValue = NULLUsefulBufC;
+ } else if(UB.ptr == NULL) {
+ ReturnValue = (UsefulBufC){NULL, UB.len - uAmount};
+ } else {
+ ReturnValue = (UsefulBufC){(uint8_t *)UB.ptr + uAmount, UB.len - uAmount};
}
- return (UsefulBufC){(uint8_t *)UB.ptr + uAmount, UB.len - uAmount};
+
+ return ReturnValue;
}
diff --git a/test/UsefulBuf_Tests.c b/test/UsefulBuf_Tests.c
index 3ec2529..6b73da2 100644
--- a/test/UsefulBuf_Tests.c
+++ b/test/UsefulBuf_Tests.c
@@ -403,6 +403,15 @@
if(!UsefulBuf_IsNULLC(UsefulBuf_Tail(xxyy, 5))) {
return "tail should have failed";
}
+
+ if(!UsefulBuf_IsNULLC(UsefulBuf_Tail(NULLUsefulBufC, 0))) {
+ return "tail of NULLUsefulBufC is not NULLUsefulBufC";
+ }
+
+ const UsefulBufC TailResult = UsefulBuf_Tail((UsefulBufC){NULL, 100}, 99);
+ if(TailResult.ptr != NULL || TailResult.len != 1) {
+ return "tail of NULL and length incorrect";
+ }
if(!UsefulBuf_IsNULLC(UsefulBuf_CopyOffset(Temp2, 100, UsefulBuf_FROM_SZ_LITERAL("yy")))) {
return "Copy Offset should have failed";
diff --git a/test/qcbor_encode_tests.c b/test/qcbor_encode_tests.c
index 9728a90..f1f0373 100644
--- a/test/qcbor_encode_tests.c
+++ b/test/qcbor_encode_tests.c
@@ -1405,6 +1405,20 @@
if(CheckResults(Encoded, spExpectedBstrWrap)) {
return -2;
}
+
+ /* Another test; see about handling length calculation */
+ QCBOREncode_Init(&EC, (UsefulBuf){NULL, INT32_MAX});
+ QCBOREncode_OpenArray(&EC);
+ QCBOREncode_BstrWrap(&EC);
+ QCBOREncode_OpenArray(&EC);
+ QCBOREncode_AddNULL(&EC);
+ QCBOREncode_CloseArray(&EC);
+ UsefulBufC BStr;
+ QCBOREncode_CloseBstrWrap(&EC, &BStr);
+ // 2 is one byte for an array of length 1 and 1 byte for a NULL
+ if(BStr.ptr != NULL || BStr.len != 2) {
+ return -5;
+ }
return 0;
}
@@ -1742,7 +1756,7 @@
if(QCBORDecode_Finish(&DC)) {
return -16;
}
-
+
return 0;
}