[libc-commits] [libc] [libc][__support/memory_size] fix missing branch and add related tests (PR #83016)

Schrodinger ZHU Yifan via libc-commits libc-commits at lists.llvm.org
Mon Feb 26 07:22:13 PST 2024


https://github.com/SchrodingerZhu updated https://github.com/llvm/llvm-project/pull/83016

>From e591435658d9a0b48e06f4546a944dd45d7f568b Mon Sep 17 00:00:00 2001
From: Schrodinger ZHU Yifan <yifanzhu at rochester.edu>
Date: Mon, 26 Feb 2024 10:19:17 -0500
Subject: [PATCH] [libc][__support/memory_size] fix missing branch and add
 related tests

---
 libc/src/__support/memory_size.h             | 6 ++++--
 libc/test/src/__support/memory_size_test.cpp | 8 ++++++++
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/libc/src/__support/memory_size.h b/libc/src/__support/memory_size.h
index 4c7d2079553e88..94aee2520afaa1 100644
--- a/libc/src/__support/memory_size.h
+++ b/libc/src/__support/memory_size.h
@@ -52,9 +52,11 @@ class SafeMemSize {
 
   LIBC_INLINE SafeMemSize operator+(const SafeMemSize &other) {
     type result;
-    if (LIBC_UNLIKELY((value | other.value) < 0))
+    if (LIBC_UNLIKELY((value | other.value) < 0)) {
       result = -1;
-    result = value + other.value;
+    } else {
+      result = value + other.value;
+    }
     return SafeMemSize{result};
   }
 
diff --git a/libc/test/src/__support/memory_size_test.cpp b/libc/test/src/__support/memory_size_test.cpp
index 93ef3711d40e00..cb7e4f43cc5e2f 100644
--- a/libc/test/src/__support/memory_size_test.cpp
+++ b/libc/test/src/__support/memory_size_test.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/__support/memory_size.h"
+#include "test/UnitTest/LibcTest.h"
 #include "test/UnitTest/Test.h"
 
 namespace LIBC_NAMESPACE {
@@ -49,6 +50,13 @@ TEST(LlvmLibcMemSizeTest, Addition) {
   ASSERT_FALSE((max + SafeMemSize{static_cast<size_t>(1)}).valid());
   ASSERT_FALSE((third + third + third + third).valid());
   ASSERT_FALSE((half + half + half).valid());
+
+  ASSERT_FALSE((SafeMemSize{static_cast<size_t>(-1)} +
+                SafeMemSize{static_cast<size_t>(2)})
+                   .valid());
+  ASSERT_FALSE((SafeMemSize{static_cast<size_t>(2)} +
+                SafeMemSize{static_cast<size_t>(-1)})
+                   .valid());
 }
 
 TEST(LlvmLibcMemSizeTest, Multiplication) {



More information about the libc-commits mailing list