15793c849SAlex Brachet //===-- FDReader.cpp ------------------------------------------------------===//
25793c849SAlex Brachet //
35793c849SAlex Brachet // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45793c849SAlex Brachet // See https://llvm.org/LICENSE.txt for license information.
55793c849SAlex Brachet // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65793c849SAlex Brachet //
75793c849SAlex Brachet //===----------------------------------------------------------------------===//
85793c849SAlex Brachet 
95793c849SAlex Brachet #include "FDReader.h"
105793c849SAlex Brachet #include <cassert>
115793c849SAlex Brachet #include <cstring>
128a4ee355SMichael Jones #include <iostream>
135793c849SAlex Brachet #include <unistd.h>
145793c849SAlex Brachet 
155793c849SAlex Brachet namespace __llvm_libc {
165793c849SAlex Brachet namespace testutils {
175793c849SAlex Brachet 
FDReader()185793c849SAlex Brachet FDReader::FDReader() {
198a4ee355SMichael Jones   if (::pipe(pipefd)) {
208a4ee355SMichael Jones     std::cerr << "pipe(2) failed";
218a4ee355SMichael Jones     abort();
228a4ee355SMichael Jones   }
235793c849SAlex Brachet }
245793c849SAlex Brachet 
~FDReader()255793c849SAlex Brachet FDReader::~FDReader() {
265793c849SAlex Brachet   ::close(pipefd[0]);
275793c849SAlex Brachet   ::close(pipefd[1]);
285793c849SAlex Brachet }
295793c849SAlex Brachet 
match_written(const char * str)30*25226f3eSMichael Jones bool FDReader::match_written(const char *str) {
318a4ee355SMichael Jones 
328a4ee355SMichael Jones   ::close(pipefd[1]);
338a4ee355SMichael Jones 
348a4ee355SMichael Jones   constexpr ssize_t ChunkSize = 4096 * 4;
358a4ee355SMichael Jones 
368a4ee355SMichael Jones   char Buffer[ChunkSize];
378a4ee355SMichael Jones   std::string PipeStr;
388a4ee355SMichael Jones   std::string InputStr(str);
398a4ee355SMichael Jones 
408a4ee355SMichael Jones   for (int BytesRead; (BytesRead = ::read(pipefd[0], Buffer, ChunkSize));) {
418a4ee355SMichael Jones     if (BytesRead > 0) {
428a4ee355SMichael Jones       PipeStr.insert(PipeStr.size(), Buffer, BytesRead);
438a4ee355SMichael Jones     } else {
445793c849SAlex Brachet       assert(0 && "Error reading from pipe");
455793c849SAlex Brachet       return false;
465793c849SAlex Brachet     }
478a4ee355SMichael Jones   }
488a4ee355SMichael Jones 
498a4ee355SMichael Jones   return PipeStr == InputStr;
505793c849SAlex Brachet }
515793c849SAlex Brachet 
525793c849SAlex Brachet } // namespace testutils
535793c849SAlex Brachet } // namespace __llvm_libc
54