[libc-commits] [libc] [libc] Add tmpnam implementation (PR #204901)
via libc-commits
libc-commits at lists.llvm.org
Sun Sep 6 00:26:59 PDT 2026
================
@@ -0,0 +1,142 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Tests for tmpnam
+/// See: https://pubs.opengroup.org/onlinepubs/9799919799/functions/tmpnam.html
+///
+//===----------------------------------------------------------------------===//
+#include "src/stdio/tmpnam.h"
+
+#include "hdr/stdio_macros.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/macros/config.h"
+#include "test/UnitTest/Test.h"
+
+#include "hdr/types/size_t.h"
+namespace {
+
+using LIBC_NAMESPACE::cpp::string_view;
+
+// The portable filename character set the implementation draws from, plus the
+// '/' that appears in the P_tmpdir prefix. Any byte in a returned name must be
+// one of these.
+constexpr char Allowed[] = "0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "_./";
+
+bool only_allowed_chars(string_view sv) {
+ for (char c : sv) {
+ if (!string_view(Allowed).contains(c))
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+// Caller-supplied buffer: the spec requires the return value to be exactly the
+// argument pointer, the string to be null-terminated within L_tmpnam bytes,
+// and the result to begin with the temp-dir prefix.
+TEST(LlvmLibcTmpnamTest, NonNullBufferReturnsSamePointer) {
+ char buf[L_tmpnam];
+ char *result = LIBC_NAMESPACE::tmpnam(buf);
+ ASSERT_EQ(result, buf);
+}
+
+TEST(LlvmLibcTmpnamTest, NonNullBufferIsNullTerminated) {
+ char buf[L_tmpnam];
+ char *result = LIBC_NAMESPACE::tmpnam(buf);
+ ASSERT_NE(result, static_cast<char *>(nullptr));
+ // A NULL must appear within the buffer bounds.
+ bool terminated = false;
+ for (size_t i = 0; i < L_tmpnam; ++i) {
+ if (result[i] == '\0') {
+ terminated = true;
+ break;
+ }
+ }
+ ASSERT_TRUE(terminated);
----------------
shubhe25p wrote:
I think it would be better to check the last character directly, then add another dependency, let me know if you disagree.
https://github.com/llvm/llvm-project/pull/204901
More information about the libc-commits
mailing list