[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:23:00 PST 2024


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

>From 7fe805ee4651b5be7492d1f71c4ee68ee360182f 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 | 7 +++++++
 2 files changed, 11 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..1c8f1ce87415bf 100644
--- a/libc/test/src/__support/memory_size_test.cpp
+++ b/libc/test/src/__support/memory_size_test.cpp
@@ -49,6 +49,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