1 //===-- Unittests for setbuf ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
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
= __llvm_libc::fopen(FILENAME
, "w");
24 ASSERT_FALSE(file
== nullptr);
26 __llvm_libc::setbuf(file
, buffer
);
27 constexpr char CONTENT
[] = "abcdef";
28 constexpr size_t CONTENT_SIZE
= sizeof(CONTENT
);
29 ASSERT_EQ(CONTENT_SIZE
, __llvm_libc::fwrite(CONTENT
, 1, CONTENT_SIZE
, file
));
30 ASSERT_EQ(0, __llvm_libc::fclose(file
));
32 file
= __llvm_libc::fopen(FILENAME
, "r");
33 __llvm_libc::setbuf(file
, buffer
);
34 ASSERT_FALSE(file
== nullptr);
35 char data
[CONTENT_SIZE
];
36 ASSERT_EQ(__llvm_libc::fread(&data
, 1, CONTENT_SIZE
, file
), CONTENT_SIZE
);
37 ASSERT_STREQ(CONTENT
, data
);
38 ASSERT_EQ(0, __llvm_libc::fclose(file
));
41 TEST(LlvmLibcSetbufTest
, NullBuffer
) {
42 // The idea in this test is that we set a null buffer and ensure that
43 // everything works correctly.
44 constexpr char FILENAME
[] = "testdata/setbuf_test_null_buffer.test";
45 ::FILE *file
= __llvm_libc::fopen(FILENAME
, "w");
46 ASSERT_FALSE(file
== nullptr);
47 __llvm_libc::setbuf(file
, nullptr);
48 constexpr char CONTENT
[] = "abcdef";
49 constexpr size_t CONTENT_SIZE
= sizeof(CONTENT
);
50 ASSERT_EQ(CONTENT_SIZE
, __llvm_libc::fwrite(CONTENT
, 1, CONTENT_SIZE
, file
));
51 ASSERT_EQ(0, __llvm_libc::fclose(file
));
53 file
= __llvm_libc::fopen(FILENAME
, "r");
54 __llvm_libc::setbuf(file
, nullptr);
55 ASSERT_FALSE(file
== nullptr);
56 char data
[CONTENT_SIZE
];
57 ASSERT_EQ(__llvm_libc::fread(&data
, 1, CONTENT_SIZE
, file
), CONTENT_SIZE
);
58 ASSERT_STREQ(CONTENT
, data
);
60 // Ensure that ungetc also works.
61 char unget_char
= 'z';
62 ASSERT_EQ(int(unget_char
), __llvm_libc::ungetc(unget_char
, file
));
64 ASSERT_EQ(__llvm_libc::fread(&c
, 1, 1, file
), size_t(1));
65 ASSERT_EQ(c
, unget_char
);
67 ASSERT_EQ(0, __llvm_libc::fclose(file
));