Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
src: add helpers for unsigned saturating addition
  • Loading branch information
bnoordhuis committed Aug 9, 2017
commit 1f8c353688652694fee116a8d24d2ff66dfa0f67
8 changes: 8 additions & 0 deletions src/util-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,14 @@ bool StringEqualNoCaseN(const char* a, const char* b, size_t length) {
return true;
}

inline uint32_t Add32Clamp(uint32_t x, uint32_t y) {
return x + y >= x ? x + y : static_cast<uint32_t>(-1);
}

inline uint64_t Add64Clamp(uint64_t x, uint64_t y) {
return x + y >= x ? x + y : static_cast<uint64_t>(-1);
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function seems unused.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added it for parity (I had plans to use it for something else) but I can remove it.

Copy link
Copy Markdown
Member

@BridgeAR BridgeAR Sep 26, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer not to add functions that have no functionality are unused.


inline size_t MultiplyWithOverflowCheck(size_t a, size_t b) {
size_t ret = a * b;
if (a != 0)
Expand Down
4 changes: 4 additions & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ inline bool StringEqualNoCase(const char* a, const char* b);
// strncasecmp() is locale-sensitive. Use StringEqualNoCaseN() instead.
inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length);

// Saturating addition.
inline uint32_t Add32Clamp(uint32_t x, uint32_t y);
inline uint64_t Add64Clamp(uint64_t x, uint64_t y);

// Allocates an array of member type T. For up to kStackStorageSize items,
// the stack is used, otherwise malloc().
template <typename T, size_t kStackStorageSize = 1024>
Expand Down