BsPath.h 22 KB

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