1*5793c849SAlex Brachet //===-- FDReader.cpp ------------------------------------------------------===//
2*5793c849SAlex Brachet //
3*5793c849SAlex Brachet // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*5793c849SAlex Brachet // See https://llvm.org/LICENSE.txt for license information.
5*5793c849SAlex Brachet // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*5793c849SAlex Brachet //
7*5793c849SAlex Brachet //===----------------------------------------------------------------------===//
8*5793c849SAlex Brachet 
9*5793c849SAlex Brachet #include "FDReader.h"
10*5793c849SAlex Brachet #include "llvm/Support/MemoryBuffer.h"
11*5793c849SAlex Brachet #include <cassert>
12*5793c849SAlex Brachet #include <cstring>
13*5793c849SAlex Brachet #include <unistd.h>
14*5793c849SAlex Brachet 
15*5793c849SAlex Brachet namespace __llvm_libc {
16*5793c849SAlex Brachet namespace testutils {
17*5793c849SAlex Brachet 
18*5793c849SAlex Brachet FDReader::FDReader() {
19*5793c849SAlex Brachet   int err = ::pipe(pipefd);
20*5793c849SAlex Brachet   assert(!err && "pipe(2) failed");
21*5793c849SAlex Brachet }
22*5793c849SAlex Brachet 
23*5793c849SAlex Brachet FDReader::~FDReader() {
24*5793c849SAlex Brachet   ::close(pipefd[0]);
25*5793c849SAlex Brachet   ::close(pipefd[1]);
26*5793c849SAlex Brachet }
27*5793c849SAlex Brachet 
28*5793c849SAlex Brachet bool FDReader::matchWritten(const char *str) {
29*5793c849SAlex Brachet   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> bufOrErr =
30*5793c849SAlex Brachet       llvm::MemoryBuffer::getOpenFile(pipefd[0], "<pipe>",
31*5793c849SAlex Brachet                                       /* FileSize (irrelevant) */ 0);
32*5793c849SAlex Brachet   if (!bufOrErr) {
33*5793c849SAlex Brachet     assert(0 && "Error reading from pipe");
34*5793c849SAlex Brachet     return false;
35*5793c849SAlex Brachet   }
36*5793c849SAlex Brachet   const llvm::MemoryBuffer &buf = **bufOrErr;
37*5793c849SAlex Brachet   return !std::strncmp(buf.getBufferStart(), str, buf.getBufferSize());
38*5793c849SAlex Brachet }
39*5793c849SAlex Brachet 
40*5793c849SAlex Brachet } // namespace testutils
41*5793c849SAlex Brachet } // namespace __llvm_libc
42