Strings.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /* Strings.cpp
  2. *
  3. * Copyright (C) 1992-2008,2011-2018 Paul Boersma
  4. *
  5. * This code is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This code is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. * See the GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this work. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. //#define USE_STAT 1
  19. #ifndef USE_STAT
  20. #if defined (_WIN32)
  21. #define USE_STAT 0
  22. #else
  23. #define USE_STAT 1
  24. #endif
  25. #endif
  26. #if USE_STAT
  27. #include <sys/types.h>
  28. //#define __USE_BSD
  29. #include <sys/stat.h>
  30. #include <dirent.h>
  31. #endif
  32. #if defined (_WIN32)
  33. #include "winport_on.h"
  34. #include <windows.h>
  35. #include "winport_off.h"
  36. #endif
  37. #include "Strings_.h"
  38. #include "../kar/longchar.h"
  39. #include "oo_DESTROY.h"
  40. #include "Strings_def.h"
  41. #include "oo_COPY.h"
  42. #include "Strings_def.h"
  43. #include "oo_EQUAL.h"
  44. #include "Strings_def.h"
  45. #include "oo_CAN_WRITE_AS_ENCODING.h"
  46. #include "Strings_def.h"
  47. #include "oo_WRITE_TEXT.h"
  48. #include "Strings_def.h"
  49. #include "oo_READ_TEXT.h"
  50. #include "Strings_def.h"
  51. #include "oo_WRITE_BINARY.h"
  52. #include "Strings_def.h"
  53. #include "oo_READ_BINARY.h"
  54. #include "Strings_def.h"
  55. #include "oo_DESCRIPTION.h"
  56. #include "Strings_def.h"
  57. Thing_implement (Strings, Daata, 0);
  58. static integer Strings_totalLength (Strings me) {
  59. integer totalLength = 0;
  60. for (integer i = 1; i <= my numberOfStrings; i ++) {
  61. totalLength += str32len (my strings [i].get());
  62. }
  63. return totalLength;
  64. }
  65. static integer Strings_maximumLength (Strings me) {
  66. integer maximumLength = 0;
  67. for (integer i = 1; i <= my numberOfStrings; i ++) {
  68. integer length = str32len (my strings [i].get());
  69. if (length > maximumLength) {
  70. maximumLength = length;
  71. }
  72. }
  73. return maximumLength;
  74. }
  75. void structStrings :: v_info () {
  76. structDaata :: v_info ();
  77. MelderInfo_writeLine (U"Number of strings: ", numberOfStrings);
  78. MelderInfo_writeLine (U"Total length: ", Strings_totalLength (this), U" characters");
  79. MelderInfo_writeLine (U"Longest string: ", Strings_maximumLength (this), U" characters");
  80. }
  81. conststring32 structStrings :: v_getVectorStr (integer icol) {
  82. if (icol < 1 || icol > our numberOfStrings) return U"";
  83. char32 *stringValue = strings [icol].get();
  84. return stringValue ? stringValue : U"";
  85. }
  86. #define Strings_createAsFileOrDirectoryList_TYPE_FILE 0
  87. #define Strings_createAsFileOrDirectoryList_TYPE_DIRECTORY 1
  88. static autoStrings Strings_createAsFileOrDirectoryList (conststring32 path /* cattable */, int type) {
  89. #if USE_STAT
  90. DIR *d = nullptr;
  91. try {
  92. /*
  93. Parse the path.
  94. This can be either a directory name such as "/Users/paul/sounds"
  95. or a wildcarded path such as "/Users/paul/sounds/h*.wav".
  96. Example: in "/Users/paul/sounds/h*llo.*av",
  97. the search directory is "/Users/paul/sounds",
  98. the left environment is "h", the middle environment is "llo.", and the right environment is "av".
  99. */
  100. autoMelderString searchDirectory, left, middle, right, filePath;
  101. MelderString_copy (& searchDirectory, path);
  102. char32 *asterisk1 = str32chr (searchDirectory. string, U'*');
  103. char32 *asterisk2 = str32rchr (searchDirectory. string, U'*');
  104. if (asterisk1) {
  105. /*
  106. The path is a wildcarded path.
  107. */
  108. *asterisk1 = U'\0';
  109. *asterisk2 = U'\0';
  110. searchDirectory. length = asterisk1 - searchDirectory. string; // probably superfluous, but correct
  111. char32 *lastSlash = str32rchr (searchDirectory. string, Melder_DIRECTORY_SEPARATOR);
  112. if (lastSlash) {
  113. *lastSlash = U'\0'; // this fixes searchDirectory
  114. searchDirectory. length = lastSlash - searchDirectory. string; // probably superfluous, but correct
  115. MelderString_copy (& left, lastSlash + 1);
  116. } else {
  117. MelderString_copy (& left, searchDirectory. string); // quickly save...
  118. MelderString_empty (& searchDirectory); // ...before destruction
  119. }
  120. if (asterisk1 != asterisk2) {
  121. MelderString_copy (& middle, asterisk1 + 1);
  122. }
  123. MelderString_copy (& right, asterisk2 + 1);
  124. } else {
  125. /*
  126. We're finished. No asterisk, hence the path is a directory name.
  127. */
  128. }
  129. char buffer8 [kMelder_MAXPATH+1];
  130. Melder_str32To8bitFileRepresentation_inplace (searchDirectory. string, buffer8);
  131. d = opendir (buffer8 [0] ? buffer8 : ".");
  132. if (! d)
  133. Melder_throw (U"Cannot open directory ", searchDirectory. string, U".");
  134. //Melder_casual (U"opened");
  135. autoStrings me = Thing_new (Strings);
  136. struct dirent *entry;
  137. while (!! (entry = readdir (d))) {
  138. MelderString_copy (& filePath, searchDirectory. string [0] ? searchDirectory. string : U".");
  139. MelderString_appendCharacter (& filePath, Melder_DIRECTORY_SEPARATOR);
  140. char32 buffer32 [kMelder_MAXPATH+1];
  141. Melder_8bitFileRepresentationToStr32_inplace (entry -> d_name, buffer32);
  142. MelderString_append (& filePath, buffer32);
  143. //Melder_casual (U"read ", filePath. string);
  144. Melder_str32To8bitFileRepresentation_inplace (filePath. string, buffer8);
  145. struct stat stats;
  146. if (stat (buffer8, & stats) != 0) {
  147. //Melder_throw (U"Cannot look at file ", filePath. string, U".");
  148. //stats. st_mode = -1L;
  149. }
  150. //Melder_casual (U"statted ", filePath. string);
  151. //Melder_casual (U"file ", filePath. string, U" mode ", stats. st_mode / 4096);
  152. if ((type == Strings_createAsFileOrDirectoryList_TYPE_FILE && S_ISREG (stats. st_mode)) ||
  153. (type == Strings_createAsFileOrDirectoryList_TYPE_DIRECTORY && S_ISDIR (stats. st_mode)))
  154. {
  155. Melder_8bitFileRepresentationToStr32_inplace (entry -> d_name, buffer32);
  156. int64 length = str32len (buffer32);
  157. integer numberOfMatchedCharacters = 0;
  158. bool doesTheLeftMatch = true;
  159. if (left. length != 0) {
  160. doesTheLeftMatch = str32nequ (buffer32, left. string, left. length);
  161. if (doesTheLeftMatch)
  162. numberOfMatchedCharacters = left.length;
  163. }
  164. bool doesTheMiddleMatch = true;
  165. if (middle. length != 0) {
  166. char32 *position = str32str (buffer32 + numberOfMatchedCharacters, middle. string);
  167. doesTheMiddleMatch = !! position;
  168. if (doesTheMiddleMatch)
  169. numberOfMatchedCharacters = position - buffer32 + middle.length;
  170. }
  171. bool doesTheRightMatch = true;
  172. if (right. length != 0) {
  173. int64 startOfRight = length - right. length;
  174. doesTheRightMatch = startOfRight >= numberOfMatchedCharacters &&
  175. str32equ (buffer32 + startOfRight, right. string);
  176. }
  177. if (buffer32 [0] != U'.' && doesTheLeftMatch && doesTheMiddleMatch && doesTheRightMatch) {
  178. Strings_insert (me.get(), 0, buffer32);
  179. }
  180. }
  181. }
  182. closedir (d);
  183. Strings_sort (me.get());
  184. return me;
  185. } catch (MelderError) {
  186. if (d) closedir (d); // "finally"
  187. throw;
  188. }
  189. #elif defined (_WIN32)
  190. try {
  191. char32 searchPath [kMelder_MAXPATH+1];
  192. int len = str32len (path);
  193. bool hasAsterisk = !! str32chr (path, U'*');
  194. bool endsInSeparator = ( len != 0 && path [len - 1] == U'\\' );
  195. autoStrings me = Thing_new (Strings);
  196. Melder_sprint (searchPath, kMelder_MAXPATH+1, path, hasAsterisk || endsInSeparator ? U"" : U"\\", hasAsterisk ? U"" : U"*");
  197. WIN32_FIND_DATAW findData;
  198. HANDLE searchHandle = FindFirstFileW (Melder_peek32toW (searchPath), & findData);
  199. if (searchHandle != INVALID_HANDLE_VALUE) {
  200. do {
  201. if ((type == Strings_createAsFileOrDirectoryList_TYPE_FILE &&
  202. (findData. dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
  203. || (type == Strings_createAsFileOrDirectoryList_TYPE_DIRECTORY &&
  204. (findData. dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
  205. {
  206. if (findData. cFileName [0] != L'.') {
  207. Strings_insert (me.get(), 0, Melder_peekWto32 (findData. cFileName));
  208. }
  209. }
  210. } while (FindNextFileW (searchHandle, & findData));
  211. FindClose (searchHandle);
  212. }
  213. Strings_sort (me.get());
  214. return me;
  215. } catch (MelderError) {
  216. throw;
  217. }
  218. #endif
  219. }
  220. autoStrings Strings_createAsFileList (conststring32 path /* cattable */) {
  221. try {
  222. return Strings_createAsFileOrDirectoryList (path, Strings_createAsFileOrDirectoryList_TYPE_FILE);
  223. } catch (MelderError) {
  224. Melder_throw (U"Strings object not created as file list.");
  225. }
  226. }
  227. autoStrings Strings_createAsDirectoryList (conststring32 path /* cattable */) {
  228. try {
  229. return Strings_createAsFileOrDirectoryList (path, Strings_createAsFileOrDirectoryList_TYPE_DIRECTORY);
  230. } catch (MelderError) {
  231. Melder_throw (U"Strings object not created as directory list.");
  232. }
  233. }
  234. autoStrings Strings_readFromRawTextFile (MelderFile file) {
  235. try {
  236. autoMelderReadText text = MelderReadText_createFromFile (file);
  237. /*
  238. * Count number of strings.
  239. */
  240. int64 n = MelderReadText_getNumberOfLines (text.get());
  241. /*
  242. * Create.
  243. */
  244. autoStrings me = Thing_new (Strings);
  245. if (n > 0) my strings = autostring32vector (n);
  246. my numberOfStrings = n;
  247. /*
  248. * Read strings.
  249. */
  250. for (integer i = 1; i <= n; i ++) {
  251. const mutablestring32 line = MelderReadText_readLine (text.get());
  252. my strings [i] = Melder_dup (line);
  253. }
  254. return me;
  255. } catch (MelderError) {
  256. Melder_throw (U"Strings not read from raw text file ", file, U".");
  257. }
  258. }
  259. void Strings_writeToRawTextFile (Strings me, MelderFile file) {
  260. autoMelderString buffer;
  261. for (integer i = 1; i <= my numberOfStrings; i ++) {
  262. MelderString_append (& buffer, my strings [i].get(), U"\n");
  263. }
  264. MelderFile_writeText (file, buffer.string, Melder_getOutputEncoding ());
  265. }
  266. void Strings_randomize (Strings me) {
  267. for (integer i = 1; i < my numberOfStrings; i ++) {
  268. integer other = NUMrandomInteger (i, my numberOfStrings);
  269. std::swap (my strings [other], my strings [i]);
  270. }
  271. }
  272. void Strings_genericize (Strings me) {
  273. autostring32 buffer (Strings_maximumLength (me) * 3);
  274. for (integer i = 1; i <= my numberOfStrings; i ++) {
  275. const conststring32 string = my strings [i].get();
  276. const char32 *p = & string [0];
  277. while (*p) {
  278. if (*p > 126) { // backslashes are not converted, i.e. genericize^2 == genericize
  279. Longchar_genericize32 (string, buffer.get());
  280. my strings [i] = Melder_dup (buffer.get());
  281. break;
  282. }
  283. p ++;
  284. }
  285. }
  286. }
  287. void Strings_nativize (Strings me) {
  288. autostring32 buffer = (Strings_maximumLength (me));
  289. for (integer i = 1; i <= my numberOfStrings; i ++) {
  290. Longchar_nativize32 (my strings [i].get(), buffer.get(), false);
  291. my strings [i] = Melder_dup (buffer.get());
  292. }
  293. }
  294. void Strings_sort (Strings me) {
  295. NUMsort_str (my strings.get());
  296. }
  297. void Strings_remove (Strings me, integer position) {
  298. if (position < 1 || position > my numberOfStrings)
  299. Melder_throw (U"You supplied a position of ", position, U", but for this string it should be in the range [1, ", my numberOfStrings, U"].");
  300. for (integer i = position; i < my numberOfStrings; i ++)
  301. my strings [i] = my strings [i + 1]. move();
  302. my strings [my numberOfStrings]. reset();
  303. my numberOfStrings --;
  304. }
  305. void Strings_replace (Strings me, integer position, conststring32 text) {
  306. if (position < 1 || position > my numberOfStrings)
  307. Melder_throw (U"You supplied a position of ", position, U", but for this string it should be in the range [1, ", my numberOfStrings, U"].");
  308. if (Melder_equ (my strings [position].get(), text))
  309. return; // nothing to change
  310. /*
  311. Create without change.
  312. */
  313. autostring32 newString = Melder_dup (text);
  314. /*
  315. Change without error.
  316. */
  317. my strings [position] = newString. move();
  318. }
  319. void Strings_insert (Strings me, integer position, conststring32 text) {
  320. if (position == 0) {
  321. position = my numberOfStrings + 1;
  322. } else if (position < 1 || position > my numberOfStrings + 1) {
  323. Melder_throw (U"You supplied a position of ", position, U", but for this string it should be in the range [1, ", my numberOfStrings, U"].");
  324. }
  325. /*
  326. Create without change.
  327. */
  328. autostring32 newString = Melder_dup (text);
  329. autostring32vector newStrings (my numberOfStrings + 1);
  330. /*
  331. Change without error.
  332. */
  333. for (integer i = 1; i < position; i ++)
  334. newStrings [i] = my strings [i]. move();
  335. newStrings [position] = newString. move();
  336. my numberOfStrings ++;
  337. for (integer i = position + 1; i <= my numberOfStrings; i ++)
  338. newStrings [i] = my strings [i - 1]. move();
  339. my strings = std::move (newStrings);
  340. }
  341. /* End of file Strings.cpp */