brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.6 KiB · f1f98f7 Raw
72 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "hdr/stdio_macros.h"10#include "src/stdio/fclose.h"11#include "src/stdio/fopen.h"12#include "src/stdio/fread.h"13#include "src/stdio/fwrite.h"14#include "src/stdio/setbuf.h"15#include "src/stdio/ungetc.h"16#include "test/UnitTest/Test.h"17 18TEST(LlvmLibcSetbufTest, DefaultBufsize) {19  // The idea in this test is to change the buffer after opening a file and20  // ensure that read and write work as expected.21  constexpr char FILENAME[] =22      APPEND_LIBC_TEST("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 42TEST(LlvmLibcSetbufTest, NullBuffer) {43  // The idea in this test is that we set a null buffer and ensure that44  // everything works correctly.45  constexpr char FILENAME[] =46      APPEND_LIBC_TEST("testdata/setbuf_test_null_buffer.test");47  ::FILE *file = LIBC_NAMESPACE::fopen(FILENAME, "w");48  ASSERT_FALSE(file == nullptr);49  LIBC_NAMESPACE::setbuf(file, nullptr);50  constexpr char CONTENT[] = "abcdef";51  constexpr size_t CONTENT_SIZE = sizeof(CONTENT);52  ASSERT_EQ(CONTENT_SIZE,53            LIBC_NAMESPACE::fwrite(CONTENT, 1, CONTENT_SIZE, file));54  ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));55 56  file = LIBC_NAMESPACE::fopen(FILENAME, "r");57  LIBC_NAMESPACE::setbuf(file, nullptr);58  ASSERT_FALSE(file == nullptr);59  char data[CONTENT_SIZE];60  ASSERT_EQ(LIBC_NAMESPACE::fread(&data, 1, CONTENT_SIZE, file), CONTENT_SIZE);61  ASSERT_STREQ(CONTENT, data);62 63  // Ensure that ungetc also works.64  char unget_char = 'z';65  ASSERT_EQ(int(unget_char), LIBC_NAMESPACE::ungetc(unget_char, file));66  char c;67  ASSERT_EQ(LIBC_NAMESPACE::fread(&c, 1, 1, file), size_t(1));68  ASSERT_EQ(c, unget_char);69 70  ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));71}72