Path: blob/main/contrib/llvm-project/libc/src/__support/File/dir.cpp
213799 views
//===--- Implementation of a platform independent Dir data structure ------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "dir.h"910#include "src/__support/CPP/mutex.h" // lock_guard11#include "src/__support/CPP/new.h"12#include "src/__support/error_or.h"13#include "src/__support/libc_errno.h" // For error macros14#include "src/__support/macros/config.h"1516namespace LIBC_NAMESPACE_DECL {1718ErrorOr<Dir *> Dir::open(const char *path) {19auto fd = platform_opendir(path);20if (!fd)21return LIBC_NAMESPACE::Error(fd.error());2223LIBC_NAMESPACE::AllocChecker ac;24Dir *dir = new (ac) Dir(fd.value());25if (!ac)26return LIBC_NAMESPACE::Error(ENOMEM);27return dir;28}2930ErrorOr<struct ::dirent *> Dir::read() {31cpp::lock_guard lock(mutex);32if (readptr >= fillsize) {33auto readsize = platform_fetch_dirents(fd, buffer);34if (!readsize)35return LIBC_NAMESPACE::Error(readsize.error());36fillsize = readsize.value();37readptr = 0;38}39if (fillsize == 0)40return nullptr;4142struct ::dirent *d = reinterpret_cast<struct ::dirent *>(buffer + readptr);43#ifdef __linux__44// The d_reclen field is available on Linux but not required by POSIX.45readptr += d->d_reclen;46#else47// Other platforms have to implement how the read pointer is to be updated.48#error "DIR read pointer update is missing."49#endif50return d;51}5253int Dir::close() {54{55cpp::lock_guard lock(mutex);56int retval = platform_closedir(fd);57if (retval != 0)58return retval;59}60delete this;61return 0;62}6364} // namespace LIBC_NAMESPACE_DECL656667