Path: blob/main/contrib/llvm-project/libc/src/__support/File/dir.h
213799 views
//===--- A platform independent Dir class ---------------------------------===//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#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_DIR_H9#define LLVM_LIBC_SRC___SUPPORT_FILE_DIR_H1011#include "src/__support/CPP/span.h"12#include "src/__support/error_or.h"13#include "src/__support/macros/config.h"14#include "src/__support/threads/mutex.h"1516#include <dirent.h>1718namespace LIBC_NAMESPACE_DECL {1920// Platform specific function which will open the directory |name|21// and return its file descriptor. Upon failure, the error value is returned.22ErrorOr<int> platform_opendir(const char *name);2324// Platform specific function which will close the directory with25// file descriptor |fd|. Returns 0 on success, or the error number on failure.26int platform_closedir(int fd);2728// Platform specific function which will fetch dirents in to buffer.29// Returns the number of bytes written into buffer or the error number on30// failure.31ErrorOr<size_t> platform_fetch_dirents(int fd, cpp::span<uint8_t> buffer);3233// This class is designed to allow implementation of the POSIX dirent.h API.34// By itself, it is platform independent but calls platform specific35// functions to perform OS operations.36class Dir {37static constexpr size_t BUFSIZE = 1024;38int fd;39size_t readptr = 0; // The current read pointer.40size_t fillsize = 0; // The number of valid bytes availabe in the buffer.4142// This is a buffer of struct dirent values which will be fetched43// from the OS. Since the d_name of struct dirent can be of a variable44// size, we store the data in a byte array.45uint8_t buffer[BUFSIZE];4647Mutex mutex;4849// A directory is to be opened by the static method open and closed50// by the close method. So, all constructors and destructor are declared51// as private. Inappropriate constructors are declared as deleted.52LIBC_INLINE Dir() = delete;53LIBC_INLINE Dir(const Dir &) = delete;5455LIBC_INLINE explicit Dir(int fdesc)56: fd(fdesc), readptr(0), fillsize(0),57mutex(/*timed=*/false, /*recursive=*/false, /*robust=*/false,58/*pshared=*/false) {}59LIBC_INLINE ~Dir() = default;6061LIBC_INLINE Dir &operator=(const Dir &) = delete;6263public:64static ErrorOr<Dir *> open(const char *path);6566ErrorOr<struct ::dirent *> read();6768// Returns 0 on success or the error number on failure. If an error number69// was returned, then the resources associated with the directory are not70// cleaned up.71int close();7273LIBC_INLINE int getfd() { return fd; }74};7576} // namespace LIBC_NAMESPACE_DECL7778#endif // LLVM_LIBC_SRC___SUPPORT_FILE_DIR_H798081