gemini-code-assist[bot] commented on code in PR #387:
URL: https://github.com/apache/tvm-ffi/pull/387#discussion_r2673536256
##########
src/ffi/dtype.cc:
##########
@@ -206,17 +206,61 @@ inline DLDataType
StringViewToDLDataType_(std::string_view str) {
dtype.bits = 32;
dtype.lanes = 1;
const char* scan;
+ const char* str_end = str.data() + str.length();
+
+ // Helper lambda to parse decimal digits from a bounded string_view
+ // Returns the parsed value and updates *ptr to point past the last digit
+ auto parse_digits = [](const char** ptr, const char* end) -> uint32_t {
+ uint64_t value = 0;
+ const char* start_ptr = *ptr;
+ while (*ptr < end && **ptr >= '0' && **ptr <= '9') {
+ value = value * 10 + (**ptr - '0');
+ (*ptr)++;
+ }
Review Comment:

The current implementation of `parse_digits` has a subtle bug where `value`
can overflow `uint64_t` if the input string contains a very large number (more
than 19 digits). If `value` overflows, it will wrap around (which is defined
behavior for unsigned integers), and the subsequent check `value > UINT32_MAX`
might fail to detect the overflow, leading to incorrect parsing.
To make this function more robust, you should check for potential overflow
before performing the multiplication and addition. Since the final value should
fit in a `uint32_t`, you can check against `UINT32_MAX` within the loop.
```c
while (*ptr < end && **ptr >= '0' && **ptr <= '9') {
uint8_t digit = **ptr - '0';
if (value > UINT32_MAX / 10 || (value == UINT32_MAX / 10 && digit >
UINT32_MAX % 10)) {
// Number is too large for uint32_t, set to overflow and consume
rest of digits.
value = (uint64_t)UINT32_MAX + 1;
while (*ptr < end && **ptr >= '0' && **ptr <= '9') {
(*ptr)++;
}
break;
}
value = value * 10 + digit;
(*ptr)++;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]