Skip to content

Conversation

@srgg
Copy link

@srgg srgg commented Oct 24, 2025

Correct byte size handling for container types in NimBLEAttValue::setValue

Summary

Improves NimBLEAttValue::setValue so that all container types correctly calculate byte size before updating an ATT value. The fix fully addresses incorrect buffer sizing when the container element type is larger than one byte.

Problem

The previous implementation used v.size() as the byte length. This works only when elements are 1 byte. For multi-byte element types (for example uint16_t), this caused:

  • Incorrect memory allocation
  • Data truncation or potential buffer overflow
  • Wrong BLE payload size reported to the stack

Example:
std::vector<uint16_t> with 10 elements

  • Before: 10 bytes (incorrect)
  • Now: 20 bytes (correct: 10 × 2 bytes)

Changes Made

  1. Added Has_value_type trait (lines 76–82)

    • C++11-compatible SFINAE trait that detects presence of value_type
    • Works with all standard containers (std::vector, std::array, std::string, etc.)
  2. Updated pre-C++17 templates (lines 282–314)

    • Split into two overloads:
      • With value_type: size in bytes = size() × sizeof(value_type)
      • Without value_type: use size() directly (assumed to already represent bytes)
  3. Updated C++17+ template (lines 324–329)

    • Uses nested if constexpr to branch at compile time
    • Same logic as pre-C++17 implementation but cleaner and safer

Behavior Examples

Type size() Byte calculation Result
std::vector<uint8_t> 10 10×1 10 ✓
std::vector<uint16_t> 10 10×2 20 ✓
std::vector<uint32_t> 10 10×4 40 ✓
std::string chars Has_c_str_length override
Custom container without value_type N elements Uses size() directly

Impact

  • Correct, safe sizing for all container types
  • Avoids data corruption and memory errors
  • No API changes required
  • Backwards compatible behavior for byte-sized types

@srgg srgg force-pushed the bugfix/attvalue-container-size branch from 5d56313 to 3c1aa03 Compare October 24, 2025 14:11
@h2zero
Copy link
Owner

h2zero commented Oct 24, 2025

Thanks! I hadn't thought of this use case before. Could you also apply this to the NimBLERemoteAttribute::writeValue and NimBLECharacteristic::notify/NimBLECharateristic::indicate templates as well?

@srgg
Copy link
Author

srgg commented Oct 24, 2025

e80a7fc extends the previous fix for NimBLEAttValue::setValue to additional template methods across the NimBLE library. These changes ensure that containers with multi-byte element types are properly sized when written, notified, or indicated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants