Last active
November 22, 2021 17:04
Gist to explain DecreaseMember
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copy <cs_Math> from bluenet repository and if not present add to it the following function. | |
template<class T, class M, class U=int> | |
constexpr inline decltype(auto) DecreaseMember(T& obj, M member, U diff=1) { | |
obj.*member = SafeAdd(obj.*member, -diff); | |
return obj.*member; | |
} | |
* Compile with g++ -I. main.cpp -o main | |
*/ | |
#include <cs_Math.h> | |
#include <iostream> | |
#define TRACKED_DEVICE_TOKEN_SIZE 3 | |
#define NOT_SET 0 | |
// Set to 1 for correct solution, set to 2 for incorrect solution | |
#define TEST_PACKED 1 | |
struct | |
#if TEST_PACKED != 0 | |
__attribute__((packed)) | |
#endif | |
register_tracked_device_packet_t { | |
uint16_t deviceId; | |
uint8_t locationId = 0; | |
uint8_t profileId; | |
int8_t rssiOffset = 0; | |
union __attribute__((packed)) { | |
struct __attribute__((packed)) { | |
bool reserved : 1; | |
bool ignoreForBehaviour : 1; | |
bool tapToToggle : 1; | |
} flags; | |
uint8_t asInt; | |
} flags; | |
uint8_t deviceToken[TRACKED_DEVICE_TOKEN_SIZE]; | |
uint16_t timeToLiveMinutes = 0; | |
}; | |
struct | |
#if TEST_PACKED != 0 | |
__attribute__((packed)) | |
#endif | |
internal_register_tracked_device_packet_t { | |
register_tracked_device_packet_t data; | |
uint8_t accessLevel = NOT_SET; | |
}; | |
struct | |
#if TEST_PACKED != 0 | |
__attribute__((packed)) | |
#endif | |
TrackedDevice { | |
uint8_t fieldsSet = 0; | |
uint8_t locationIdTTLMinutes; | |
uint8_t heartbeatTTLMinutes; | |
internal_register_tracked_device_packet_t data; | |
}; | |
int main() { | |
int t = 0; | |
TrackedDevice device; | |
device.data.data.timeToLiveMinutes = 5; | |
while(t < 10) { | |
#if TEST_PACKED == 0 | |
if (CsMath::Decrease(device.data.data.timeToLiveMinutes) == 0) { | |
std::cout << "Timeout " << std::endl; | |
} | |
#elif TEST_PACKED == 1 | |
if (CsMath::DecreaseMember(device.data.data, ®ister_tracked_device_packet_t::timeToLiveMinutes) == 0) { | |
std::cout << "Timeout " << std::endl; | |
} | |
#elif TEST_PACKED == 2 | |
if (*CsMath::DecreaseByPointer(&device.data.data.timeToLiveMinutes) == 0) { | |
std::cout << "Timeout " << std::endl; | |
} | |
#else | |
#warning "Not implemented" | |
#endif | |
std::cout << "Time to live: " << device.data.data.timeToLiveMinutes << std::endl; | |
t++; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment