BsPath.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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(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. /** Checks is the path a directory (contains no file-name). */
  152. bool isDirectory() const { return mFilename.empty(); }
  153. /** Checks does the path point to a file. */
  154. bool isFile() const { return !mFilename.empty(); }
  155. /** Checks is the contained path absolute. */
  156. bool isAbsolute() const { return mIsAbsolute; }
  157. /**
  158. * Returns parent path. If current path points to a file the parent path will be the folder where the file is located.
  159. * Or if it contains a directory the parent will be the parent directory. If no parent exists, same path will be
  160. * returned.
  161. */
  162. Path getParent() const;
  163. /**
  164. * Returns an absolute path by appending the current path to the provided base. If path was already absolute no
  165. * changes are made and copy of current path is returned. If base is not absolute, then the returned path will be
  166. * made relative to base, but will not be absolute.
  167. */
  168. Path getAbsolute(const Path& base) const;
  169. /**
  170. * Returns a relative path by making the current path relative to the provided base. Base must be a part of the
  171. * current path. If base is not a part of the path no changes are made and a copy of the current path is returned.
  172. */
  173. Path getRelative(const Path& base) const;
  174. /**
  175. * Returns the path as a path to directory. If path was pointing to a file, the filename is removed, otherwise no
  176. * changes are made and exact copy is returned.
  177. */
  178. Path getDirectory() const;
  179. /**
  180. * Makes the path the parent of the current path. If current path points to a file the parent path will be the
  181. * folder where the file is located. Or if it contains a directory the parent will be the parent directory. If no
  182. * parent exists, same path will be returned.
  183. */
  184. Path& makeParent();
  185. /**
  186. * Makes the current path absolute by appending it to base. If path was already absolute no changes are made and
  187. * copy of current path is returned. If base is not absolute, then the returned path will be made relative to base,
  188. * but will not be absolute.
  189. */
  190. Path& makeAbsolute(const Path& base);
  191. /**
  192. * Makes the current path relative to the provided base. Base must be a part of the current path. If base is not
  193. * a part of the path no changes are made and a copy of the current path is returned.
  194. */
  195. Path& makeRelative(const Path& base);
  196. /** Appends another path to the end of this path. */
  197. Path& append(const Path& path);
  198. /**
  199. * Checks if the current path contains the provided path. Comparison is case insensitive and paths will be compared
  200. * as-is, without canonization.
  201. */
  202. bool includes(const Path& child) const;
  203. /**
  204. * Compares two paths and returns true if they match. Comparison is case insensitive and paths will be compared
  205. * as-is, without canonization.
  206. */
  207. bool equals(const Path& other) const;
  208. /** Change or set the filename in the path. */
  209. void setFilename(const WString& filename) { mFilename = filename; }
  210. /** Change or set the filename in the path. */
  211. void setFilename(const String& filename) { mFilename = BansheeEngine::toWString(filename); }
  212. /**
  213. * Change or set the base name in the path. Base name changes the filename by changing its base to the provided
  214. * value but keeping extension intact.
  215. */
  216. void setBasename(const WString& basename);
  217. /**
  218. * Change or set the base name in the path. Base name changes the filename by changing its base to the provided
  219. * value but keeping extension intact.
  220. */
  221. void setBasename(const String& basename);
  222. /**
  223. * Change or set the extension of the filename in the path.
  224. *
  225. * @param[in] extension Extension with a leading ".".
  226. */
  227. void setExtension(const WString& extension);
  228. /**
  229. * Change or set the extension of the filename in the path.
  230. *
  231. * @param[in] extension Extension with a leading ".".
  232. */
  233. void setExtension(const String& extension);
  234. /**
  235. * Returns a filename in the path.
  236. *
  237. * @param[in] extension If true, returned filename will contain an extension.
  238. */
  239. WString getWFilename(bool extension = true) const;
  240. /**
  241. * Returns a filename in the path.
  242. *
  243. * @param[in] extension If true, returned filename will contain an extension.
  244. */
  245. String getFilename(bool extension = true) const;
  246. /** Returns file extension with the leading ".". */
  247. WString getWExtension() const;
  248. /** Returns file extension with the leading ".". */
  249. String getExtension() const;
  250. /** Gets the number of directories in the path. */
  251. UINT32 getNumDirectories() const { return (UINT32)mDirectories.size(); }
  252. /** Gets a directory name with the specified index from the path. */
  253. const WString& getWDirectory(UINT32 idx) const;
  254. /** Gets a directory name with the specified index from the path. */
  255. String getDirectory(UINT32 idx) const;
  256. /** Returns path device (for example drive, volume, etc.) if one exists in the path. */
  257. const WString& getWDevice() const { return mDevice; }
  258. /** Returns path device (for example drive, volume, etc.) if one exists in the path. */
  259. String getDevice() const { return BansheeEngine::toString(mDevice); }
  260. /** Returns path node (for example network name) if one exists in the path. */
  261. const WString& getWNode() const { return mNode; }
  262. /** Returns path node (for example network name) if one exists in the path. */
  263. String getNode() const { return BansheeEngine::toString(mNode); }
  264. /**
  265. * Gets last element in the path, filename if it exists, otherwise the last directory. If no directories exist
  266. * returns device or node.
  267. *
  268. * @param[in] type Determines format of node or device, in case they are returned. When default, format for
  269. * the active platform will be used, otherwise the format defined by the parameter will be used.
  270. */
  271. WString getWTail(PathType type = PathType::Default) const;
  272. /**
  273. * Gets last element in the path, filename if it exists, otherwise the last directory. If no directories exist
  274. * returns device or node.
  275. *
  276. * @param[in] type Determines format of node or device, in case they are returned. When default, format for the
  277. * active platform will be used, otherwise the format defined by the parameter will be used.
  278. */
  279. String getTail(PathType type = PathType::Default) const;
  280. /** Clears the path to nothing. */
  281. void clear();
  282. /** Returns true if no path has been set. */
  283. bool isEmpty() const { return mDirectories.empty() && mFilename.empty() && mDevice.empty() && mNode.empty(); }
  284. /** Concatenates two paths. */
  285. Path operator+ (const Path& rhs) const;
  286. /** Concatenates two paths. */
  287. Path& operator+= (const Path& rhs);
  288. /** Compares two path elements (filenames, directory names, etc.). */
  289. static bool comparePathElem(const WString& left, const WString& right);
  290. /** Combines two paths and returns the result. Right path should be relative. */
  291. static Path combine(const Path& left, const Path& right);
  292. static const Path BLANK;
  293. private:
  294. /**
  295. * Constructs a path by parsing the provided raw string data. Throws exception if provided path is not valid.
  296. *
  297. * @param[in] pathStr String containing the path.
  298. * @param[in] numChars Number of character in the provided path string.
  299. * @param[in] type If set to default path will be parsed according to the rules of the platform the
  300. * application is being compiled to. Otherwise it will be parsed according to provided
  301. * type.
  302. */
  303. void assign(const wchar_t* pathStr, UINT32 numChars, PathType type = PathType::Default);
  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 char* pathStr, UINT32 numChars, PathType type = PathType::Default);
  314. /** Parses a Windows path and stores the parsed data internally. Throws an exception if parsing fails. */
  315. template<class T>
  316. void parseWindows(const T* pathStr, UINT32 numChars)
  317. {
  318. clear();
  319. UINT32 idx = 0;
  320. BasicStringStream<T> tempStream;
  321. if (idx < numChars)
  322. {
  323. if (pathStr[idx] == '\\' || pathStr[idx] == '/')
  324. {
  325. mIsAbsolute = true;
  326. idx++;
  327. }
  328. }
  329. if (idx < numChars)
  330. {
  331. // Path starts with a node, a drive letter or is relative
  332. if (mIsAbsolute && (pathStr[idx] == '\\' || pathStr[idx] == '/')) // Node
  333. {
  334. idx++;
  335. tempStream.str(BasicString<T>());
  336. tempStream.clear();
  337. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  338. tempStream << pathStr[idx++];
  339. setNode(tempStream.str());
  340. if (idx < numChars)
  341. idx++;
  342. }
  343. else // A drive letter or not absolute
  344. {
  345. T drive = pathStr[idx];
  346. idx++;
  347. if (idx < numChars && pathStr[idx] == ':')
  348. {
  349. if (mIsAbsolute || !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')))
  350. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  351. mIsAbsolute = true;
  352. setDevice(BansheeEngine::toWString(drive));
  353. idx++;
  354. if (idx >= numChars || (pathStr[idx] != '\\' && pathStr[idx] != '/'))
  355. throwInvalidPathException(BasicString<T>(pathStr, numChars));
  356. idx++;
  357. }
  358. else
  359. idx--;
  360. }
  361. while (idx < numChars)
  362. {
  363. tempStream.str(BasicString<T>());
  364. tempStream.clear();
  365. while (idx < numChars && pathStr[idx] != '\\' && pathStr[idx] != '/')
  366. {
  367. tempStream << pathStr[idx];
  368. idx++;
  369. }
  370. if (idx < numChars)
  371. pushDirectory(tempStream.str());
  372. else
  373. setFilename(tempStream.str());
  374. idx++;
  375. }
  376. }
  377. }
  378. /** Parses a Unix path and stores the parsed data internally. Throws an exception if parsing fails. */
  379. template<class T>
  380. void parseUnix(const T* pathStr, UINT32 numChars)
  381. {
  382. clear();
  383. UINT32 idx = 0;
  384. BasicStringStream<T> tempStream;
  385. if (idx < numChars)
  386. {
  387. if (pathStr[idx] == '/')
  388. {
  389. mIsAbsolute = true;
  390. idx++;
  391. }
  392. else if (pathStr[idx] == '~')
  393. {
  394. idx++;
  395. if (idx >= numChars || pathStr[idx] == '/')
  396. {
  397. pushDirectory(BansheeEngine::toWString('~'));
  398. mIsAbsolute = true;
  399. }
  400. else
  401. idx--;
  402. }
  403. while (idx < numChars)
  404. {
  405. tempStream.str(BasicString<T>());
  406. tempStream.clear();
  407. while (idx < numChars && pathStr[idx] != '/')
  408. {
  409. tempStream << pathStr[idx];
  410. idx++;
  411. }
  412. if (idx < numChars)
  413. {
  414. if (mDirectories.empty())
  415. {
  416. BasicString<T> deviceStr = tempStream.str();
  417. if (!deviceStr.empty() && *(deviceStr.rbegin()) == ':')
  418. {
  419. setDevice(deviceStr.substr(0, deviceStr.length() - 1));
  420. mIsAbsolute = true;
  421. }
  422. else
  423. {
  424. pushDirectory(deviceStr);
  425. }
  426. }
  427. else
  428. {
  429. pushDirectory(tempStream.str());
  430. }
  431. }
  432. else
  433. {
  434. setFilename(tempStream.str());
  435. }
  436. idx++;
  437. }
  438. }
  439. }
  440. void setNode(const WString& node) { mNode = node; }
  441. void setNode(const String& node) { mNode = BansheeEngine::toWString(node); }
  442. void setDevice(const WString& device) { mDevice = device; }
  443. void setDevice(const String& device) { mDevice = BansheeEngine::toWString(device); }
  444. /** Build a Windows path string from internal path data. */
  445. WString buildWindows() const;
  446. /** Build a Unix path string from internal path data. */
  447. WString buildUnix() const;
  448. /** Add new directory to the end of the path. */
  449. void pushDirectory(const WString& dir);
  450. /** Add new directory to the end of the path. */
  451. void pushDirectory(const String& dir);
  452. /** Helper method that throws invalid path exception. */
  453. void throwInvalidPathException(const WString& path) const;
  454. /** Helper method that throws invalid path exception. */
  455. void throwInvalidPathException(const String& path) const;
  456. private:
  457. friend struct RTTIPlainType<Path>; // For serialization
  458. friend struct ::std::hash<BansheeEngine::Path>;
  459. Vector<WString> mDirectories;
  460. WString mDevice;
  461. WString mFilename;
  462. WString mNode;
  463. bool mIsAbsolute;
  464. };
  465. /** @cond SPECIALIZATIONS */
  466. /**
  467. * RTTIPlainType specialization for Path that allows paths be serialized as value types.
  468. *
  469. * @see RTTIPlainType
  470. */
  471. template<> struct RTTIPlainType<Path>
  472. {
  473. enum { id = TID_Path }; enum { hasDynamicSize = 1 };
  474. static void toMemory(const Path& data, char* memory)
  475. {
  476. UINT32 size = getDynamicSize(data);
  477. memcpy(memory, &size, sizeof(UINT32));
  478. memory += sizeof(UINT32);
  479. memory = rttiWriteElem(data.mDevice, memory);
  480. memory = rttiWriteElem(data.mNode, memory);
  481. memory = rttiWriteElem(data.mFilename, memory);
  482. memory = rttiWriteElem(data.mIsAbsolute, memory);
  483. memory = rttiWriteElem(data.mDirectories, memory);
  484. }
  485. static UINT32 fromMemory(Path& data, char* memory)
  486. {
  487. UINT32 size;
  488. memcpy(&size, memory, sizeof(UINT32));
  489. memory += sizeof(UINT32);
  490. memory = rttiReadElem(data.mDevice, memory);
  491. memory = rttiReadElem(data.mNode, memory);
  492. memory = rttiReadElem(data.mFilename, memory);
  493. memory = rttiReadElem(data.mIsAbsolute, memory);
  494. memory = rttiReadElem(data.mDirectories, memory);
  495. return size;
  496. }
  497. static UINT32 getDynamicSize(const Path& data)
  498. {
  499. UINT64 dataSize = rttiGetElemSize(data.mDevice) + rttiGetElemSize(data.mNode) + rttiGetElemSize(data.mFilename) +
  500. rttiGetElemSize(data.mIsAbsolute) + rttiGetElemSize(data.mDirectories) + sizeof(UINT32);
  501. #if BS_DEBUG_MODE
  502. if (dataSize > std::numeric_limits<UINT32>::max())
  503. {
  504. __string_throwDataOverflowException();
  505. }
  506. #endif
  507. return (UINT32)dataSize;
  508. }
  509. };
  510. /** @endcond */
  511. /** @} */
  512. }
  513. /** @cond STDLIB */
  514. /** Hash value generator for Path. */
  515. template<>
  516. struct std::hash<BansheeEngine::Path>
  517. {
  518. size_t operator()(const BansheeEngine::Path& path) const
  519. {
  520. size_t hash = 0;
  521. BansheeEngine::hash_combine(hash, path.mFilename);
  522. BansheeEngine::hash_combine(hash, path.mDevice);
  523. BansheeEngine::hash_combine(hash, path.mNode);
  524. for (auto& dir : path.mDirectories)
  525. BansheeEngine::hash_combine(hash, dir);
  526. return hash;
  527. }
  528. };
  529. /** @endcond */