2
0

BsPath.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. #pragma once
  2. /** @addtogroup Filesystem
  3. * @{
  4. */
  5. namespace BansheeEngine
  6. {
  7. /**
  8. * Class for storing and manipulating file paths. Paths may be parsed from and to raw strings according to various
  9. * platform specific path types.
  10. *
  11. * @note
  12. * In order to allow the system to easily distinguish between file and directory paths, try to ensure that all directory
  13. * paths end with a separator (\ or / depending on platform). System won't fail if you don't but it will be easier to
  14. * misuse.
  15. */
  16. class BS_UTILITY_EXPORT Path
  17. {
  18. public:
  19. enum class PathType
  20. {
  21. Windows,
  22. Unix,
  23. Default
  24. };
  25. public:
  26. Path();
  27. /**
  28. * Constructs a path by parsing the provided path string. Throws exception if provided path is not valid.
  29. *
  30. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  31. * is being compiled to. Otherwise it will be parsed according to provided type.
  32. */
  33. Path(const WString& pathStr, PathType type = PathType::Default);
  34. /**
  35. * Constructs a path by parsing the provided path string. Throws exception if provided path is not valid.
  36. *
  37. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  38. * is being compiled to. Otherwise it will be parsed according to provided type.
  39. */
  40. Path(const String& pathStr, PathType type = PathType::Default);
  41. /**
  42. * Constructs a path by parsing the provided path null terminated string. Throws exception if provided path is not
  43. * valid.
  44. *
  45. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  46. * is being compiled to. Otherwise it will be parsed according to provided type.
  47. */
  48. Path(wchar_t* pathStr, PathType type = PathType::Default);
  49. /**
  50. * Constructs a path by parsing the provided path null terminated string. Throws exception if provided path is
  51. * not valid.
  52. *
  53. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  54. * is being compiled to. Otherwise it will be parsed according to provided type.
  55. */
  56. Path(const char* pathStr, PathType type = PathType::Default);
  57. Path(const Path& other);
  58. /**
  59. * Assigns a path by parsing the provided path string. Path will be parsed according to the rules of the platform
  60. * the application is being compiled to.
  61. */
  62. Path& operator= (const WString& pathStr);
  63. /**
  64. * Assigns a path by parsing the provided path string. Path will be parsed according to the rules of the platform
  65. * the application is being compiled to.
  66. */
  67. Path& operator= (const String& pathStr);
  68. /**
  69. * Assigns a path by parsing the provided path null terminated string. Path will be parsed according to the rules
  70. * of the platform the application is being compiled to.
  71. */
  72. Path& operator= (const wchar_t* pathStr);
  73. /**
  74. * Assigns a path by parsing the provided path null terminated string. Path will be parsed according to the rules
  75. * of the platform the application is being compiled to.
  76. */
  77. Path& operator= (const char* pathStr);
  78. Path& operator= (const Path& path);
  79. /**
  80. * Compares two paths and returns true if they match. Comparison is case insensitive and paths will be compared
  81. * as-is, without canonization.
  82. */
  83. bool operator== (const Path& path) const { return equals(path); }
  84. /**
  85. * Compares two paths and returns true if they don't match. Comparison is case insensitive and paths will be
  86. * compared as-is, without canonization.
  87. */
  88. bool operator!= (const Path& path) const { return !equals(path); }
  89. /** Gets a directory name with the specified index from the path. */
  90. const WString& operator[] (UINT32 idx) const { return getWDirectory(idx); }
  91. /** Swap internal data with another Path object. */
  92. void swap(Path& path);
  93. /**
  94. * @brief Create a path from another Path object.
  95. */
  96. void assign(const Path& path);
  97. /**
  98. * Constructs a path by parsing the provided path string. Throws exception if provided path is not valid.
  99. *
  100. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  101. * is being compiled to. Otherwise it will be parsed according to provided type.
  102. */
  103. void assign(const WString& pathStr, PathType type = PathType::Default);
  104. /**
  105. * Constructs a path by parsing the provided path string. Throws exception if provided path is not valid.
  106. *
  107. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  108. * is being compiled to. Otherwise it will be parsed according to provided type.
  109. */
  110. void assign(const String& pathStr, PathType type = PathType::Default);
  111. /**
  112. * Constructs a path by parsing the provided path null terminated string. Throws exception if provided path is not
  113. * valid.
  114. *
  115. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  116. * is being compiled to. Otherwise it will be parsed according to provided type.
  117. */
  118. void assign(const wchar_t* pathStr, PathType type = PathType::Default);
  119. /**
  120. * Constructs a path by parsing the provided path null terminated string. Throws exception if provided path is not
  121. * valid.
  122. *
  123. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  124. * is being compiled to. Otherwise it will be parsed according to provided type.
  125. */
  126. void assign(const char* pathStr, PathType type = PathType::Default);
  127. /**
  128. * Converts the path in a string according to platform path rules.
  129. *
  130. * @param[in] type If set to default path will be parsed according to the rules of the platform the application is
  131. * being compiled to. Otherwise it will be parsed according to provided type.
  132. */
  133. WString toWString(PathType type = PathType::Default) const;
  134. /**
  135. * Converts the path in a string according to platform path rules.
  136. *
  137. * @param[in] type If set to default path will be parsed according to the rules of the platform the application is
  138. * being compiled to. Otherwise it will be parsed according to provided type.
  139. */
  140. String toString(PathType type = PathType::Default) const;
  141. /** Checks is the path a directory (contains no file-name). */
  142. bool isDirectory() const { return mFilename.empty(); }
  143. /** Checks does the path point to a file. */
  144. bool isFile() const { return !mFilename.empty(); }
  145. /** Checks is the contained path absolute. */
  146. bool isAbsolute() const { return mIsAbsolute; }
  147. /**
  148. * Returns parent path. If current path points to a file the parent path will be the folder where the file is located.
  149. * Or if it contains a directory the parent will be the parent directory. If no parent exists, same path will be
  150. * returned.
  151. */
  152. Path getParent() const;
  153. /**
  154. * Returns an absolute path by appending the current path to the provided base. If path was already absolute no
  155. * changes are made and copy of current path is returned. If base is not absolute, then the returned path will be
  156. * made relative to base, but will not be absolute.
  157. */
  158. Path getAbsolute(const Path& base) const;
  159. /**
  160. * Returns a relative path by making the current path relative to the provided base. Base must be a part of the
  161. * current path. If base is not a part of the path no changes are made and a copy of the current path is returned.
  162. */
  163. Path getRelative(const Path& base) const;
  164. /**
  165. * Returns the path as a path to directory. If path was pointing to a file, the filename is removed, otherwise no
  166. * changes are made and exact copy is returned.
  167. */
  168. Path getDirectory() const;
  169. /**
  170. * Makes the path the parent of the current path. If current path points to a file the parent path will be the
  171. * folder where the file is located. Or if it contains a directory the parent will be the parent directory. If no
  172. * parent exists, same path will be returned.
  173. */
  174. Path& makeParent();
  175. /**
  176. * Makes the current path absolute by appending it to base. If path was already absolute no changes are made and
  177. * copy of current path is returned. If base is not absolute, then the returned path will be made relative to base,
  178. * but will not be absolute.
  179. */
  180. Path& makeAbsolute(const Path& base);
  181. /**
  182. * Makes the current path relative to the provided base. Base must be a part of the current path. If base is not
  183. * a part of the path no changes are made and a copy of the current path is returned.
  184. */
  185. Path& makeRelative(const Path& base);
  186. /** Appends another path to the end of this path. */
  187. Path& append(const Path& path);
  188. /**
  189. * Checks if the current path contains the provided path. Comparison is case insensitive and paths will be compared
  190. * as-is, without canonization.
  191. */
  192. bool includes(const Path& child) const;
  193. /**
  194. * Compares two paths and returns true if they match. Comparison is case insensitive and paths will be compared
  195. * as-is, without canonization.
  196. */
  197. bool equals(const Path& other) const;
  198. /** Change or set the filename in the path. */
  199. void setFilename(const WString& filename) { mFilename = filename; }
  200. /** Change or set the filename in the path. */
  201. void setFilename(const String& filename) { mFilename = BansheeEngine::toWString(filename); }
  202. /**
  203. * Change or set the base name in the path. Base name changes the filename by changing its base to the provided
  204. * value but keeping extension intact.
  205. */
  206. void setBasename(const WString& basename);
  207. /**
  208. * Change or set the base name in the path. Base name changes the filename by changing its base to the provided
  209. * value but keeping extension intact.
  210. */
  211. void setBasename(const String& basename);
  212. /**
  213. * Change or set the extension of the filename in the path.
  214. *
  215. * @param[in] extension Extension with a leading ".".
  216. */
  217. void setExtension(const WString& extension);
  218. /**
  219. * Change or set the extension of the filename in the path.
  220. *
  221. * @param[in] extension Extension with a leading ".".
  222. */
  223. void setExtension(const String& extension);
  224. /**
  225. * Returns a filename in the path.
  226. *
  227. * @param[in] extension If true, returned filename will contain an extension.
  228. */
  229. WString getWFilename(bool extension = true) const;
  230. /**
  231. * Returns a filename in the path.
  232. *
  233. * @param[in] extension If true, returned filename will contain an extension.
  234. */
  235. String getFilename(bool extension = true) const;
  236. /** Returns file extension with the leading ".". */
  237. WString getWExtension() const;
  238. /** Returns file extension with the leading ".". */
  239. String getExtension() const;
  240. /** Gets the number of directories in the path. */
  241. UINT32 getNumDirectories() const { return (UINT32)mDirectories.size(); }
  242. /** Gets a directory name with the specified index from the path. */
  243. const WString& getWDirectory(UINT32 idx) const;
  244. /** Gets a directory name with the specified index from the path. */
  245. String getDirectory(UINT32 idx) const;
  246. /** Returns path device (e.g. drive, volume, etc.) if one exists in the path. */
  247. const WString& getWDevice() const { return mDevice; }
  248. /** Returns path device (e.g. drive, volume, etc.) if one exists in the path. */
  249. String getDevice() const { return BansheeEngine::toString(mDevice); }
  250. /** Returns path node (e.g. network name) if one exists in the path. */
  251. const WString& getWNode() const { return mNode; }
  252. /** Returns path node (e.g. network name) if one exists in the path. */
  253. String getNode() const { return BansheeEngine::toString(mNode); }
  254. /**
  255. * Gets last element in the path, filename if it exists, otherwise the last directory. If no directories exist
  256. * returns device or node.
  257. *
  258. * @param[in] type Determines format of node or device, in case they are returned. When default, format for
  259. * the active platform will be used, otherwise the format defined by the parameter will be used.
  260. */
  261. WString getWTail(PathType type = PathType::Default) const;
  262. /**
  263. * Gets last element in the path, filename if it exists, otherwise the last directory. If no directories exist
  264. * returns device or node.
  265. *
  266. * @param[in] type Determines format of node or device, in case they are returned. When default, format for the
  267. * active platform will be used, otherwise the format defined by the parameter will be used.
  268. */
  269. String getTail(PathType type = PathType::Default) const;
  270. /** Clears the path to nothing. */
  271. void clear();
  272. /** Returns true if no path has been set. */
  273. bool isEmpty() const { return mDirectories.empty() && mFilename.empty() && mDevice.empty() && mNode.empty(); }
  274. /** Concatenates two paths. */
  275. Path operator+ (const Path& rhs) const;
  276. /** Concatenates two paths. */
  277. Path& operator+= (const Path& rhs);
  278. /** Compares two path elements (i.e. filenames, directory names, etc.). */
  279. static bool comparePathElem(const WString& left, const WString& right);
  280. /** Combines two paths and returns the result. Right path should be relative. */
  281. static Path combine(const Path& left, const Path& right);
  282. static const Path BLANK;
  283. private:
  284. /**
  285. * Constructs a path by parsing the provided raw string data. Throws exception if provided path is not valid.
  286. *
  287. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  288. * is being compiled to. Otherwise it will be parsed according to provided type.
  289. */
  290. void assign(const wchar_t* pathStr, UINT32 numChars, PathType type = PathType::Default);
  291. /**
  292. * Constructs a path by parsing the provided raw string data. Throws exception if provided path is not valid.
  293. *
  294. * @param[in] type If set to default path will be parsed according to the rules of the platform the application
  295. * is being compiled to. Otherwise it will be parsed according to provided type.
  296. */
  297. void assign(const char* pathStr, UINT32 numChars, PathType type = PathType::Default);
  298. /** Parses a Windows path and stores the parsed data internally. Throws an exception if parsing fails. */
  299. template<class T>
  300. void parseWindows(const T* pathStr, UINT32 numChars)
  301. {
  302. clear();
  303. UINT32 idx = 0;
  304. BasicStringStream<T> tempStream;
  305. if (idx < numChars)
  306. {
  307. if (pathStr[idx] == '\\' || pathStr[idx] == '/')
  308. {
  309. mIsAbsolute = true;
  310. idx++;
  311. }
  312. }
  313. if (idx < numChars)
  314. {
  315. // Path starts with a node, a drive letter or is relative
  316. if (mIsAbsolute && pathStr[idx] == '\\' || pathStr[idx] == '/') // Node
  317. {
  318. idx++;
  319. tempStream.str(BasicString<T>());
  320. tempStream.clear();
  321. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  322. tempStream << pathStr[idx++];
  323. setNode(tempStream.str());
  324. if (idx < numChars)
  325. idx++;
  326. }
  327. else // A drive letter or not absolute
  328. {
  329. T drive = pathStr[idx];
  330. idx++;
  331. if (idx < numChars && pathStr[idx] == ':')
  332. {
  333. if (mIsAbsolute || !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')))
  334. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  335. mIsAbsolute = true;
  336. setDevice(BansheeEngine::toWString(drive));
  337. idx++;
  338. if (idx >= numChars || (pathStr[idx] != '\\' && pathStr[idx] != '/'))
  339. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  340. idx++;
  341. }
  342. else
  343. idx--;
  344. }
  345. while (idx < numChars)
  346. {
  347. tempStream.str(BasicString<T>());
  348. tempStream.clear();
  349. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  350. {
  351. tempStream << pathStr[idx];
  352. idx++;
  353. }
  354. if (idx < numChars)
  355. pushDirectory(tempStream.str());
  356. else
  357. setFilename(tempStream.str());
  358. idx++;
  359. }
  360. }
  361. }
  362. /** Parses a Unix path and stores the parsed data internally. Throws an exception if parsing fails. */
  363. template<class T>
  364. void parseUnix(const T* pathStr, UINT32 numChars)
  365. {
  366. clear();
  367. UINT32 idx = 0;
  368. BasicStringStream<T> tempStream;
  369. if (idx < numChars)
  370. {
  371. if (pathStr[idx] == '/')
  372. {
  373. mIsAbsolute = true;
  374. idx++;
  375. }
  376. else if (pathStr[idx] == '~')
  377. {
  378. idx++;
  379. if (idx >= numChars || pathStr[idx] == '/')
  380. {
  381. pushDirectory(BansheeEngine::toWString('~'));
  382. mIsAbsolute = true;
  383. }
  384. else
  385. idx--;
  386. }
  387. while (idx < numChars)
  388. {
  389. tempStream.str(BasicString<T>());
  390. tempStream.clear();
  391. while (idx < numChars && pathStr[idx] != '/')
  392. {
  393. tempStream << pathStr[idx];
  394. idx++;
  395. }
  396. if (idx < numChars)
  397. {
  398. if (mDirectories.empty())
  399. {
  400. BasicString<T> deviceStr = tempStream.str();
  401. if (!deviceStr.empty() && *(deviceStr.rbegin()) == ':')
  402. {
  403. setDevice(deviceStr.substr(0, deviceStr.length() - 1));
  404. mIsAbsolute = true;
  405. }
  406. else
  407. {
  408. pushDirectory(deviceStr);
  409. }
  410. }
  411. else
  412. {
  413. pushDirectory(tempStream.str());
  414. }
  415. }
  416. else
  417. {
  418. setFilename(tempStream.str());
  419. }
  420. idx++;
  421. }
  422. }
  423. }
  424. void setNode(const WString& node) { mNode = node; }
  425. void setNode(const String& node) { mNode = BansheeEngine::toWString(node); }
  426. void setDevice(const WString& device) { mDevice = device; }
  427. void setDevice(const String& device) { mDevice = BansheeEngine::toWString(device); }
  428. /** Build a Windows path string from internal path data. */
  429. WString buildWindows() const;
  430. /** Build a Unix path string from internal path data. */
  431. WString buildUnix() const;
  432. /** Add new directory to the end of the path. */
  433. void pushDirectory(const WString& dir);
  434. /** Add new directory to the end of the path. */
  435. void pushDirectory(const String& dir);
  436. /** Helper method that throws invalid path exception. */
  437. void throwInvalidPathException(const WString& path) const;
  438. /** Helper method that throws invalid path exception. */
  439. void throwInvalidPathException(const String& path) const;
  440. private:
  441. friend struct RTTIPlainType<Path>; // For serialization
  442. friend struct ::std::hash<BansheeEngine::Path>;
  443. Vector<WString> mDirectories;
  444. WString mDevice;
  445. WString mFilename;
  446. WString mNode;
  447. bool mIsAbsolute;
  448. };
  449. /** @cond SPECIALIZATIONS */
  450. /**
  451. * RTTIPlainType specialization for Path that allows paths be serialized as value types.
  452. *
  453. * @see RTTIPlainType
  454. */
  455. template<> struct RTTIPlainType<Path>
  456. {
  457. enum { id = TID_Path }; enum { hasDynamicSize = 1 };
  458. static void toMemory(const Path& data, char* memory)
  459. {
  460. UINT32 size = getDynamicSize(data);
  461. memcpy(memory, &size, sizeof(UINT32));
  462. memory += sizeof(UINT32);
  463. memory = rttiWriteElem(data.mDevice, memory);
  464. memory = rttiWriteElem(data.mNode, memory);
  465. memory = rttiWriteElem(data.mFilename, memory);
  466. memory = rttiWriteElem(data.mIsAbsolute, memory);
  467. memory = rttiWriteElem(data.mDirectories, memory);
  468. }
  469. static UINT32 fromMemory(Path& data, char* memory)
  470. {
  471. UINT32 size;
  472. memcpy(&size, memory, sizeof(UINT32));
  473. memory += sizeof(UINT32);
  474. memory = rttiReadElem(data.mDevice, memory);
  475. memory = rttiReadElem(data.mNode, memory);
  476. memory = rttiReadElem(data.mFilename, memory);
  477. memory = rttiReadElem(data.mIsAbsolute, memory);
  478. memory = rttiReadElem(data.mDirectories, memory);
  479. return size;
  480. }
  481. static UINT32 getDynamicSize(const Path& data)
  482. {
  483. UINT64 dataSize = rttiGetElemSize(data.mDevice) + rttiGetElemSize(data.mNode) + rttiGetElemSize(data.mFilename) +
  484. rttiGetElemSize(data.mIsAbsolute) + rttiGetElemSize(data.mDirectories) + sizeof(UINT32);
  485. #if BS_DEBUG_MODE
  486. if (dataSize > std::numeric_limits<UINT32>::max())
  487. {
  488. __string_throwDataOverflowException();
  489. }
  490. #endif
  491. return (UINT32)dataSize;
  492. }
  493. };
  494. /** @endcond */
  495. }
  496. /** @cond STDLIB */
  497. /** Hash value generator for Path. */
  498. template<>
  499. struct std::hash<BansheeEngine::Path>
  500. {
  501. size_t operator()(const BansheeEngine::Path& path) const
  502. {
  503. size_t hash = 0;
  504. BansheeEngine::hash_combine(hash, path.mFilename);
  505. BansheeEngine::hash_combine(hash, path.mDevice);
  506. BansheeEngine::hash_combine(hash, path.mNode);
  507. for (auto& dir : path.mDirectories)
  508. BansheeEngine::hash_combine(hash, dir);
  509. return hash;
  510. }
  511. };
  512. /** @endcond */
  513. /** @} */