• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Unittests for setbuf ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/stdio/fclose.h"
10 #include "src/stdio/fopen.h"
11 #include "src/stdio/fread.h"
12 #include "src/stdio/fwrite.h"
13 #include "src/stdio/setbuf.h"
14 #include "src/stdio/ungetc.h"
15 #include "test/UnitTest/Test.h"
16 
17 #include <stdio.h>
18 
TEST(LlvmLibcSetbufTest,DefaultBufsize)19 TEST(LlvmLibcSetbufTest, DefaultBufsize) {
20   // The idea in this test is to change the buffer after opening a file and
21   // ensure that read and write work as expected.
22   constexpr char FILENAME[] = "testdata/setbuf_test_default_bufsize.test";
23   ::FILE *file = LIBC_NAMESPACE::fopen(FILENAME, "w");
24   ASSERT_FALSE(file == nullptr);
25   char buffer[BUFSIZ];
26   LIBC_NAMESPACE::setbuf(file, buffer);
27   constexpr char CONTENT[] = "abcdef";
28   constexpr size_t CONTENT_SIZE = sizeof(CONTENT);
29   ASSERT_EQ(CONTENT_SIZE,
30             LIBC_NAMESPACE::fwrite(CONTENT, 1, CONTENT_SIZE, file));
31   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
32 
33   file = LIBC_NAMESPACE::fopen(FILENAME, "r");
34   LIBC_NAMESPACE::setbuf(file, buffer);
35   ASSERT_FALSE(file == nullptr);
36   char data[CONTENT_SIZE];
37   ASSERT_EQ(LIBC_NAMESPACE::fread(&data, 1, CONTENT_SIZE, file), CONTENT_SIZE);
38   ASSERT_STREQ(CONTENT, data);
39   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
40 }
41 
TEST(LlvmLibcSetbufTest,NullBuffer)42 TEST(LlvmLibcSetbufTest, NullBuffer) {
43   // The idea in this test is that we set a null buffer and ensure that
44   // everything works correctly.
45   constexpr char FILENAME[] = "testdata/setbuf_test_null_buffer.test";
46   ::FILE *file = LIBC_NAMESPACE::fopen(FILENAME, "w");
47   ASSERT_FALSE(file == nullptr);
48   LIBC_NAMESPACE::setbuf(file, nullptr);
49   constexpr char CONTENT[] = "abcdef";
50   constexpr size_t CONTENT_SIZE = sizeof(CONTENT);
51   ASSERT_EQ(CONTENT_SIZE,
52             LIBC_NAMESPACE::fwrite(CONTENT, 1, CONTENT_SIZE, file));
53   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
54 
55   file = LIBC_NAMESPACE::fopen(FILENAME, "r");
56   LIBC_NAMESPACE::setbuf(file, nullptr);
57   ASSERT_FALSE(file == nullptr);
58   char data[CONTENT_SIZE];
59   ASSERT_EQ(LIBC_NAMESPACE::fread(&data, 1, CONTENT_SIZE, file), CONTENT_SIZE);
60   ASSERT_STREQ(CONTENT, data);
61 
62   // Ensure that ungetc also works.
63   char unget_char = 'z';
64   ASSERT_EQ(int(unget_char), LIBC_NAMESPACE::ungetc(unget_char, file));
65   char c;
66   ASSERT_EQ(LIBC_NAMESPACE::fread(&c, 1, 1, file), size_t(1));
67   ASSERT_EQ(c, unget_char);
68 
69   ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
70 }
71