Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / src / inference_engine / w_dirent.h
1 // Copyright (C) 2018-2019 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4
5 #pragma once
6 #include <string>
7 #if defined(WIN32)
8 #include "w_unistd.h"
9 #include "debug.h"
10 #include <sys/stat.h>
11
12 // Copied from linux libc sys/stat.h:
13 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
14 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
15
16 struct dirent {
17     char *d_name;
18
19     explicit dirent(const wchar_t *wsFilePath) {
20         size_t i;
21         auto slen = wcslen(wsFilePath);
22         d_name = static_cast<char *>(malloc(slen + 1));
23         wcstombs_s(&i, d_name, slen + 1, wsFilePath, slen);
24     }
25     ~dirent() {
26         free(d_name);
27     }
28 };
29
30 class DIR {
31     WIN32_FIND_DATA FindFileData;
32     HANDLE hFind;
33     dirent *next;
34
35 public:
36     DIR(const DIR &other) = delete;
37     DIR(DIR &&other) = delete;
38     DIR& operator=(const DIR &other) = delete;
39     DIR& operator=(DIR &&other) = delete;
40
41     explicit DIR(const char *dirPath) : next(nullptr) {
42         // wchar_t  ws[1024];
43         // swprintf(ws, 1024, L"%hs\\*", dirPath);
44         std::string ws = dirPath;
45         if (InferenceEngine::details::endsWith(ws, "\\"))
46             ws += "*";
47         else
48             ws += "\\*";
49         hFind = FindFirstFile(ws.c_str(), &FindFileData);
50         FindFileData.dwReserved0 = hFind != INVALID_HANDLE_VALUE;
51     }
52
53     ~DIR() {
54         if (!next) delete next;
55         next = nullptr;
56         FindClose(hFind);
57     }
58
59     bool isValid() const {
60         return (hFind != INVALID_HANDLE_VALUE && FindFileData.dwReserved0);
61     }
62
63     dirent* nextEnt() {
64         if (next != nullptr) delete next;
65         next = nullptr;
66
67         if (!FindFileData.dwReserved0) return nullptr;
68
69         wchar_t wbuf[4096];
70
71         size_t outSize;
72         mbstowcs_s(&outSize, wbuf, 4094, FindFileData.cFileName, 4094);
73         next = new dirent(wbuf);
74         FindFileData.dwReserved0 = FindNextFile(hFind, &FindFileData);
75         return next;
76     }
77 };
78
79
80 static DIR* opendir(const char *dirPath) {
81     auto dp = new DIR(dirPath);
82     if (!dp->isValid()) {
83         delete dp;
84         return nullptr;
85     }
86     return dp;
87 }
88
89 static struct dirent* readdir(DIR *dp) {
90     return dp->nextEnt();
91 }
92
93 static void closedir(DIR *dp) {
94     delete dp;
95 }
96 #else
97
98 #include <sys/types.h>
99 #include <dirent.h>
100
101 #endif
102