|
| 1 | +//===----------------------------------------------------------------------===// |
| 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 | +// FILE_DEPENDENCIES: xsgetn.test.dat |
| 10 | + |
| 11 | +// <fstream> |
| 12 | + |
| 13 | +// template <class charT, class traits = char_traits<charT> > |
| 14 | +// class basic_ifstream |
| 15 | + |
| 16 | +// streamsize xsgetn(char_type*, streamsize) override; |
| 17 | + |
| 18 | +// This isn't a required override by the standard, but most implementations override it, since it allows for |
| 19 | +// significantly improved performance in some cases. All of this code is required to work, so this isn't a libc++ |
| 20 | +// extension |
| 21 | + |
| 22 | +#include <cassert> |
| 23 | +#include <fstream> |
| 24 | + |
| 25 | +#include "test_macros.h" |
| 26 | + |
| 27 | +int main(int, char**) { |
| 28 | + { |
| 29 | + char buffer[10]; |
| 30 | + std::ifstream fs("xsgetn.test.dat"); |
| 31 | + std::filebuf* fb = fs.rdbuf(); |
| 32 | + fb->pubsetbuf(buffer, 10); |
| 33 | + |
| 34 | + // Ensure that the buffer is set up |
| 35 | + assert(fb->sgetc() == 't'); |
| 36 | + |
| 37 | + std::string str(5, '\0'); |
| 38 | + |
| 39 | + { // Check that a read smaller than the buffer works fine |
| 40 | + assert(fb->sgetn(str.data(), 5) == 5); |
| 41 | + assert(str == "this "); |
| 42 | + } |
| 43 | + { // Check that reading up to the buffer end works fine |
| 44 | + assert(fb->sgetn(str.data(), 5) == 5); |
| 45 | + assert(str == "is so"); |
| 46 | + } |
| 47 | + { // Check that reading from an empty buffer, but more than the buffer can hold works fine |
| 48 | + str.resize(12); |
| 49 | + assert(fb->sgetn(str.data(), 12) == 12); |
| 50 | + assert(str == "me random da"); |
| 51 | + } |
| 52 | + { // Check that reading from a non-empty buffer, and more than the buffer can hold works fine |
| 53 | + // Fill the buffer up |
| 54 | + str.resize(2); |
| 55 | + assert(fb->sgetn(str.data(), 2) == 2); |
| 56 | + assert(str == "ta"); |
| 57 | + |
| 58 | + // Do the actual check |
| 59 | + str.resize(12); |
| 60 | + assert(fb->sgetn(str.data(), 12) == 12); |
| 61 | + assert(str == " to be able "); |
| 62 | + } |
| 63 | + { // Check that trying to read more than the file size works fine |
| 64 | + str.resize(30); |
| 65 | + assert(fb->sgetn(str.data(), 30) == 24); |
| 66 | + str.resize(24); |
| 67 | + assert(str == "to test buffer behaviour"); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return 0; |
| 72 | +} |
0 commit comments