BsPath.h 22 KB

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