Skip to content

Instantly share code, notes, and snippets.

@mrquincle
Last active November 22, 2021 17:04
Show Gist options
  • Save mrquincle/ab9810bfbfe503070c2134c3f75b781c to your computer and use it in GitHub Desktop.
Save mrquincle/ab9810bfbfe503070c2134c3f75b781c to your computer and use it in GitHub Desktop.
Gist to explain DecreaseMember
/**
* 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, &register_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