[NFC][Py Reformat] Added more commits to .git-blame-ignore-revs
[llvm-project.git] / libc / src / __support / File / dir.cpp
blobe632c9293d617a754ab2b1cfb23d9132fd0869b2
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 __llvm_libc {
17 ErrorOr<Dir *> Dir::open(const char *path) {
18 auto fd = platform_opendir(path);
19 if (!fd)
20 return __llvm_libc::Error(fd.error());
22 __llvm_libc::AllocChecker ac;
23 Dir *dir = new (ac) Dir(fd);
24 if (!ac)
25 return __llvm_libc::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 __llvm_libc::Error(readsize.error());
35 fillsize = readsize;
36 readptr = 0;
38 if (fillsize == 0)
39 return nullptr;
41 struct ::dirent *d = reinterpret_cast<struct ::dirent *>(buffer + readptr);
42 #ifdef __unix__
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 __llvm_libc