BsPath.h 21 KB

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