Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / src / __support / File / dir.cpp
blob9ff639a777e2347dea6a16d6a66aa7829f7e33b6
1 //===--- Implementation of a platform independent Dir data structure ------===//
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 //===----------------------------------------------------------------------===//
9 #include "dir.h"
11 #include "src/__support/CPP/new.h"
12 #include "src/__support/error_or.h"
13 #include "src/errno/libc_errno.h" // For error macros
15 namespace LIBC_NAMESPACE {
17 ErrorOr<Dir *> Dir::open(const char *path) {
18 auto fd = platform_opendir(path);
19 if (!fd)
20 return LIBC_NAMESPACE::Error(fd.error());
22 LIBC_NAMESPACE::AllocChecker ac;
23 Dir *dir = new (ac) Dir(fd.value());
24 if (!ac)
25 return LIBC_NAMESPACE::Error(ENOMEM);
26 return dir;
29 ErrorOr<struct ::dirent *> Dir::read() {
30 MutexLock lock(&mutex);
31 if (readptr >= fillsize) {
32 auto readsize = platform_fetch_dirents(fd, buffer);
33 if (!readsize)
34 return LIBC_NAMESPACE::Error(readsize.error());
35 fillsize = readsize.value();
36 readptr = 0;
38 if (fillsize == 0)
39 return nullptr;
41 struct ::dirent *d = reinterpret_cast<struct ::dirent *>(buffer + readptr);
42 #ifdef __linux__
43 // The d_reclen field is available on Linux but not required by POSIX.
44 readptr += d->d_reclen;
45 #else
46 // Other platforms have to implement how the read pointer is to be updated.
47 #error "DIR read pointer update is missing."
48 #endif
49 return d;
52 int Dir::close() {
54 MutexLock lock(&mutex);
55 int retval = platform_closedir(fd);
56 if (retval != 0)
57 return retval;
59 delete this;
60 return 0;
63 } // namespace LIBC_NAMESPACE