sort.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  1. /*++
  2. Copyright (c) 2013 Minoca Corp. All Rights Reserved
  3. Module Name:
  4. sort.c
  5. Abstract:
  6. This module implements the sort utility.
  7. Author:
  8. Evan Green 15-Aug-2013
  9. Environment:
  10. POSIX
  11. --*/
  12. //
  13. // ------------------------------------------------------------------- Includes
  14. //
  15. #include <minoca/lib/types.h>
  16. #include <assert.h>
  17. #include <ctype.h>
  18. #include <errno.h>
  19. #include <getopt.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <unistd.h>
  23. #include "swlib.h"
  24. //
  25. // ---------------------------------------------------------------- Definitions
  26. //
  27. #define SORT_VERSION_MAJOR 1
  28. #define SORT_VERSION_MINOR 0
  29. #define SORT_USAGE \
  30. "usage: sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]\n" \
  31. " sort -c [-bdfinru][-t char][-k keydef][file]\n\n" \
  32. "The sort utility either sorts all lines in a file, merges line of all \n" \
  33. "the named (presorted) files together, or checks to see if a single \n" \
  34. "input file is sorted.\n" \
  35. "Options are:\n" \
  36. " -c, --check -- Check that a single input file is sorted. No output \n" \
  37. " shall be produced, only the exit code is affected.\n" \
  38. " -m, --merge -- Merge only. The input files are assumed to be sorted.\n" \
  39. " -o, --output <file> -- Specify an output file to be used instead of \n" \
  40. " standard out. This file can be the same as one of the input " \
  41. "files.\n" \
  42. " -u, --unique -- Unique: suppress all but one in each set of lines \n" \
  43. " having equal keys. If used with the -c option, check that \n" \
  44. " there are no lines with duplicate keys, in addition to \n" \
  45. " checking that the input file is sorted.\n" \
  46. " -d, --dictionary-order -- Only blanks and alphanumeric characters \n" \
  47. " shall be significant in comparisons.\n" \
  48. " -f, --ignore-case -- Convert any lower case characters to uppercase \n" \
  49. " when comparing.\n" \
  50. " -i, --ignore-nonprinting -- Ignore non-printable characters.\n" \
  51. " -n, --numeric-sort -- Sort numerically.\n" \
  52. " -r, --reverse -- Reverse the sort order.\n" \
  53. " -b, --ignore-leading-blanks -- Ignore leading blanks.\n" \
  54. " -k, --key <keydef> -- Restrict the sorting key to a certain region \n" \
  55. " of the line. The keydef parameter is defined by:\n" \
  56. " field_start[type][,field_end[type]]\n" \
  57. " where field_start takes the form \n" \
  58. " field_number[.first_character] and field_end takes the form \n" \
  59. " field_number[.last_character]. \n" \
  60. " Fields and characters are indexed from 1. The type parameter \n" \
  61. " is one or more of [bdfinr], which attach the corresponding \n" \
  62. " flag meaning to that specific field.\n" \
  63. " -t, --field-separator <character> -- Use the given character as a \n" \
  64. " field separator.\n" \
  65. " file -- Supplies the input file to sort. If no file is supplied or \n" \
  66. " the file is -, then use stdin.\n\n"
  67. #define SORT_OPTIONS_STRING "cmo:udfinrbk:t:"
  68. //
  69. // Set this option to ignore leading blanks in comparisons.
  70. //
  71. #define SORT_OPTION_IGNORE_LEADING_BLANKS 0x00000001
  72. //
  73. // Set this option to consider only blanks and alphanumeric characters in
  74. // comparisons.
  75. //
  76. #define SORT_OPTION_ONLY_ALPHANUMERICS 0x00000002
  77. //
  78. // Set this option to uppercase everything for comparisons.
  79. //
  80. #define SORT_OPTION_UPPERCASE_EVERYTHING 0x00000004
  81. //
  82. // Set this option to ignore non-printable characters during the comparison.
  83. //
  84. #define SORT_OPTION_IGNORE_NONPRINTABLE 0x00000008
  85. //
  86. // Set this option to convert strings to integers and compare those.
  87. //
  88. #define SORT_OPTION_COMPARE_NUMERICALLY 0x00000010
  89. //
  90. // Set this option to reverse the sort order.
  91. //
  92. #define SORT_OPTION_REVERSE 0x00000020
  93. //
  94. // Set this option to check if a file is sorted.
  95. //
  96. #define SORT_OPTION_CHECK_ONLY 0x00000040
  97. //
  98. // Set this option to merge only.
  99. //
  100. #define SORT_OPTION_MERGE_ONLY 0x00000080
  101. //
  102. // Set this option to only print unique lines, and check for uniqueness on
  103. // checks.
  104. //
  105. #define SORT_OPTION_UNIQUE 0x00000100
  106. #define SORT_INITIAL_ELEMENT_COUNT 32
  107. #define SORT_INITIAL_STRING_SIZE 32
  108. //
  109. // ------------------------------------------------------ Data Type Definitions
  110. //
  111. typedef
  112. VOID
  113. (*PSORT_DESTROY_ARRAY_ELEMENT_ROUTINE) (
  114. PVOID Element
  115. );
  116. /*++
  117. Routine Description:
  118. This routine is called to destroy an element in a sort array.
  119. Arguments:
  120. Element - Supplies the element being destroyed.
  121. Return Value:
  122. None.
  123. --*/
  124. /*++
  125. Structure Description:
  126. This structure defines a mutable array of pointers in the sort utility.
  127. Members:
  128. Data - Supplies a pointer to the malloced string array buffer itself.
  129. Size - Supplies the number of valid elements in the buffer.
  130. Capacity - Supplies the maximum number of elements before the array needs
  131. to be reallocated.
  132. --*/
  133. typedef struct _SORT_ARRAY {
  134. PVOID *Data;
  135. UINTN Size;
  136. UINTN Capacity;
  137. } SORT_ARRAY, *PSORT_ARRAY;
  138. /*++
  139. Structure Description:
  140. This structure defines a mutable string in the sort utility.
  141. Members:
  142. Data - Supplies a pointer to the malloced string buffer itself.
  143. Size - Supplies the number of valid bytes in the buffer including the
  144. null terminator if there is one.
  145. Capacity - Supplies the size of the buffer allocation.
  146. --*/
  147. typedef struct _SORT_STRING {
  148. PSTR Data;
  149. UINTN Size;
  150. UINTN Capacity;
  151. } SORT_STRING, *PSORT_STRING;
  152. /*++
  153. Structure Description:
  154. This structure defines an input file to the sort utility.
  155. Members:
  156. File - Stores the open file pointer, or NULL if the file could not be
  157. opened.
  158. Line - Stores a pointer to the string containing the most recent line.
  159. --*/
  160. typedef struct _SORT_INPUT {
  161. FILE *File;
  162. PSORT_STRING Line;
  163. } SORT_INPUT, *PSORT_INPUT;
  164. /*++
  165. Structure Description:
  166. This structure defines a sort key used by the sort utility.
  167. Members:
  168. StartField - Stores the starting field number to use in comparisons.
  169. StartCharacter - Stores the starting character within the starting field
  170. to use in comparisons.
  171. StartOptions - Stores any specific options attached to the start field.
  172. EndField - Stores the ending field, or -1 for the end of the line.
  173. EndCharacter - Stores the ending character within the ending field, or -1
  174. for the end of the field.
  175. EndOptions - Stores options associated with the ending field.
  176. --*/
  177. typedef struct _SORT_KEY {
  178. LONG StartField;
  179. LONG StartCharacter;
  180. ULONG StartOptions;
  181. LONG EndField;
  182. LONG EndCharacter;
  183. ULONG EndOptions;
  184. } SORT_KEY, *PSORT_KEY;
  185. /*++
  186. Structure Description:
  187. This structure defines the context for an instantiation of the sort utility.
  188. Members:
  189. Input - Stores the array of pointers to sort inputs.
  190. Key - Stores the array of pointers to sort keys.
  191. KeyCount - Stores the number of elements in the key array.
  192. Options - Stores the global options.
  193. Output - Stores the name of the output file.
  194. Separator - Stores the field separator character, or -1 if none was
  195. supplied.
  196. --*/
  197. typedef struct _SORT_CONTEXT {
  198. SORT_ARRAY Input;
  199. SORT_ARRAY Key;
  200. ULONG Options;
  201. PSTR Output;
  202. INT Separator;
  203. } SORT_CONTEXT, *PSORT_CONTEXT;
  204. //
  205. // ----------------------------------------------- Internal Function Prototypes
  206. //
  207. INT
  208. SortCheckFile (
  209. PSORT_CONTEXT Context,
  210. PSORT_INPUT Input
  211. );
  212. INT
  213. SortMergeSortedFiles (
  214. PSORT_CONTEXT Context,
  215. FILE *Output
  216. );
  217. INT
  218. SortCompareLines (
  219. const VOID *LeftPointer,
  220. const VOID *RightPointer
  221. );
  222. INT
  223. SortReadLine (
  224. PSORT_CONTEXT Context,
  225. PSORT_INPUT Input,
  226. PSORT_STRING Holding,
  227. PSORT_STRING *String
  228. );
  229. INT
  230. SortAddInputFile (
  231. PSORT_CONTEXT Context,
  232. PSTR FileName
  233. );
  234. INT
  235. SortAddKey (
  236. PSORT_CONTEXT Context,
  237. PSTR Argument
  238. );
  239. VOID
  240. SortScanKeyFlags (
  241. PSTR *Argument,
  242. PULONG Flags
  243. );
  244. INT
  245. SortArrayAddElement (
  246. PSORT_ARRAY Array,
  247. PVOID Element
  248. );
  249. INT
  250. SortStringAddCharacter (
  251. PSORT_STRING String,
  252. CHAR Character
  253. );
  254. PSORT_STRING
  255. SortCreateString (
  256. PSTR InitialData,
  257. UINTN InitialDataSize
  258. );
  259. VOID
  260. SortDestroyString (
  261. PSORT_STRING String
  262. );
  263. VOID
  264. SortDestroyArray (
  265. PSORT_ARRAY Array,
  266. PSORT_DESTROY_ARRAY_ELEMENT_ROUTINE DestroyElementRoutine
  267. );
  268. VOID
  269. SortDestroyInput (
  270. PSORT_INPUT Input
  271. );
  272. VOID
  273. SortGetFieldOffset (
  274. PSORT_STRING String,
  275. INT Separator,
  276. LONG Field,
  277. LONG Character,
  278. PULONG Offset
  279. );
  280. LONG
  281. SortStringToLong (
  282. PSORT_STRING String,
  283. ULONG Options,
  284. ULONG Offset
  285. );
  286. //
  287. // -------------------------------------------------------------------- Globals
  288. //
  289. //
  290. // Store a global pointer to the sort context since a context pointer can't be
  291. // passed through the qsort routine to the compare function.
  292. //
  293. PSORT_CONTEXT SortContext;
  294. struct option SortLongOptions[] = {
  295. {"check", no_argument, 0, 'c'},
  296. {"merge", no_argument, 0, 'm'},
  297. {"output", required_argument, 0, 'o'},
  298. {"unique", no_argument, 0, 'u'},
  299. {"dictionary-order", no_argument, 0, 'd'},
  300. {"ignore-case", no_argument, 0, 'f'},
  301. {"ignore-nonprinting", no_argument, 0, 'i'},
  302. {"numeric-sort", no_argument, 0, 'n'},
  303. {"reverse", no_argument, 0, 'r'},
  304. {"ignore-leading-blanks", no_argument, 0, 'b'},
  305. {"key", required_argument, 0, 'k'},
  306. {"field-separator", required_argument, 0, 't'},
  307. {"help", no_argument, 0, 'h'},
  308. {"version", no_argument, 0, 'V'},
  309. {NULL, 0, 0, 0}
  310. };
  311. //
  312. // ------------------------------------------------------------------ Functions
  313. //
  314. INT
  315. SortMain (
  316. INT ArgumentCount,
  317. CHAR **Arguments
  318. )
  319. /*++
  320. Routine Description:
  321. This routine is the main entry point for the sort utility.
  322. Arguments:
  323. ArgumentCount - Supplies the number of command line arguments the program
  324. was invoked with.
  325. Arguments - Supplies a tokenized array of command line arguments.
  326. Return Value:
  327. Returns an integer exit code. 0 for success, nonzero otherwise.
  328. --*/
  329. {
  330. PSTR Argument;
  331. ULONG ArgumentIndex;
  332. SORT_CONTEXT Context;
  333. PSORT_INPUT Input;
  334. ULONG InputIndex;
  335. PSORT_STRING InputLine;
  336. SORT_ARRAY InputLines;
  337. SORT_STRING InputString;
  338. PSORT_KEY Key;
  339. UINTN KeyIndex;
  340. UINTN LineIndex;
  341. INT Option;
  342. FILE *Output;
  343. PSORT_STRING PreviousLine;
  344. INT Status;
  345. Input = NULL;
  346. InputLine = NULL;
  347. memset(&Context, 0, sizeof(SORT_CONTEXT));
  348. memset(&InputString, 0, sizeof(SORT_STRING));
  349. memset(&InputLines, 0, sizeof(SORT_ARRAY));
  350. Context.Separator = -1;
  351. Output = NULL;
  352. //
  353. // Process the control arguments.
  354. //
  355. while (TRUE) {
  356. Option = getopt_long(ArgumentCount,
  357. Arguments,
  358. SORT_OPTIONS_STRING,
  359. SortLongOptions,
  360. NULL);
  361. if (Option == -1) {
  362. break;
  363. }
  364. if ((Option == '?') || (Option == ':')) {
  365. Status = 1;
  366. return Status;
  367. }
  368. switch (Option) {
  369. case 'c':
  370. Context.Options |= SORT_OPTION_CHECK_ONLY;
  371. break;
  372. case 'm':
  373. Context.Options |= SORT_OPTION_MERGE_ONLY;
  374. break;
  375. case 'o':
  376. Context.Output = optarg;
  377. assert(Context.Output != NULL);
  378. break;
  379. case 'u':
  380. Context.Options |= SORT_OPTION_UNIQUE;
  381. break;
  382. case 'd':
  383. Context.Options |= SORT_OPTION_ONLY_ALPHANUMERICS;
  384. break;
  385. case 'f':
  386. Context.Options |= SORT_OPTION_UPPERCASE_EVERYTHING;
  387. break;
  388. case 'i':
  389. Context.Options |= SORT_OPTION_IGNORE_NONPRINTABLE;
  390. break;
  391. case 'n':
  392. Context.Options |= SORT_OPTION_COMPARE_NUMERICALLY;
  393. break;
  394. case 'r':
  395. Context.Options |= SORT_OPTION_REVERSE;
  396. break;
  397. case 'b':
  398. Context.Options |= SORT_OPTION_IGNORE_LEADING_BLANKS;
  399. break;
  400. case 'k':
  401. Argument = optarg;
  402. assert(Argument != NULL);
  403. Status = SortAddKey(&Context, Argument);
  404. if (Status != 0) {
  405. SwPrintError(0, Argument, "Invalid key argument");
  406. return Status;
  407. }
  408. break;
  409. case 't':
  410. Argument = optarg;
  411. assert(Argument != NULL);
  412. if (strlen(Argument) == 1) {
  413. Context.Separator = *Argument;
  414. } else if ((*Argument == '\\') && (strlen(Argument) == 2)) {
  415. switch (*(Argument + 1)) {
  416. case 'a':
  417. Context.Separator = '\a';
  418. break;
  419. case 'b':
  420. Context.Separator = '\b';
  421. break;
  422. case 'f':
  423. Context.Separator = '\f';
  424. break;
  425. case 'n':
  426. Context.Separator = '\n';
  427. break;
  428. case 'r':
  429. Context.Separator = '\r';
  430. break;
  431. case 't':
  432. Context.Separator = '\t';
  433. break;
  434. case 'v':
  435. Context.Separator = '\v';
  436. break;
  437. case '0':
  438. Context.Separator = '\0';
  439. break;
  440. case '\\':
  441. Context.Separator = '\\';
  442. break;
  443. default:
  444. SwPrintError(0,
  445. Argument,
  446. "Field separator should be a single "
  447. "character");
  448. return 2;
  449. }
  450. } else {
  451. SwPrintError(0,
  452. Argument,
  453. "Field separator should be a single "
  454. "character");
  455. return 2;
  456. }
  457. break;
  458. case 'V':
  459. SwPrintVersion(SORT_VERSION_MAJOR, SORT_VERSION_MINOR);
  460. return 1;
  461. case 'h':
  462. printf(SORT_USAGE);
  463. return 1;
  464. default:
  465. assert(FALSE);
  466. Status = 1;
  467. return Status;
  468. }
  469. }
  470. ArgumentIndex = optind;
  471. if (ArgumentIndex > ArgumentCount) {
  472. ArgumentIndex = ArgumentCount;
  473. }
  474. //
  475. // Add the remainder of the arguments as inputs.
  476. //
  477. while (ArgumentIndex < ArgumentCount) {
  478. Status = SortAddInputFile(&Context, Arguments[ArgumentIndex]);
  479. if (Status != 0) {
  480. goto MainEnd;
  481. }
  482. ArgumentIndex += 1;
  483. }
  484. //
  485. // Use standard out if nothing else was supplied.
  486. //
  487. if (Context.Input.Size == 0) {
  488. Status = SortAddInputFile(&Context, "-");
  489. if (Status != 0) {
  490. goto MainEnd;
  491. }
  492. }
  493. //
  494. // If there are no keys, create a default one of the whole line.
  495. //
  496. if (Context.Key.Size == 0) {
  497. Status = SortAddKey(&Context, "1");
  498. if (Status != 0) {
  499. goto MainEnd;
  500. }
  501. }
  502. //
  503. // Copy in the global flags to the key flags to avoid extra work during
  504. // compares.
  505. //
  506. for (KeyIndex = 0; KeyIndex < Context.Key.Size; KeyIndex += 1) {
  507. Key = Context.Key.Data[KeyIndex];
  508. Key->StartOptions |= Context.Options;
  509. Key->EndOptions |= Context.Options;
  510. }
  511. //
  512. // Open up the output if needed.
  513. //
  514. if (Context.Output != NULL) {
  515. Output = fopen(Context.Output, "w");
  516. if (Output == NULL) {
  517. Status = errno;
  518. SwPrintError(Status, Context.Output, "Failed to open output");
  519. goto MainEnd;
  520. }
  521. } else {
  522. Output = stdout;
  523. }
  524. //
  525. // All the arguments are parsed, start the work.
  526. //
  527. SortContext = &Context;
  528. if ((Context.Options & SORT_OPTION_CHECK_ONLY) != 0) {
  529. if (Context.Input.Size != 1) {
  530. SwPrintError(0, NULL, "Only one file can be specified with -c");
  531. Status = 2;
  532. goto MainEnd;
  533. }
  534. Status = SortCheckFile(&Context, Context.Input.Data[0]);
  535. goto MainEnd;
  536. } else if ((Context.Options & SORT_OPTION_MERGE_ONLY) != 0) {
  537. Status = SortMergeSortedFiles(&Context, Output);
  538. goto MainEnd;
  539. }
  540. //
  541. // This is the real sort, not merge or check. Read in all inputs.
  542. //
  543. for (InputIndex = 0; InputIndex < Context.Input.Size; InputIndex += 1) {
  544. Input = Context.Input.Data[InputIndex];
  545. while (TRUE) {
  546. Status = SortReadLine(&Context,
  547. Input,
  548. &InputString,
  549. &InputLine);
  550. if (Status != 0) {
  551. SwPrintError(Status, NULL, "Failed to read line");
  552. goto MainEnd;
  553. }
  554. if (InputLine == NULL) {
  555. break;
  556. }
  557. Status = SortArrayAddElement(&InputLines, InputLine);
  558. if (Status != 0) {
  559. SortDestroyString(InputLine);
  560. goto MainEnd;
  561. }
  562. InputLine = NULL;
  563. }
  564. }
  565. if (InputLines.Size == 0) {
  566. Status = 0;
  567. goto MainEnd;
  568. }
  569. //
  570. // Do it, sort the arrays.
  571. //
  572. qsort(InputLines.Data, InputLines.Size, sizeof(PVOID), SortCompareLines);
  573. //
  574. // Write all the lines to the output.
  575. //
  576. PreviousLine = NULL;
  577. for (LineIndex = 0; LineIndex < InputLines.Size; LineIndex += 1) {
  578. InputLine = InputLines.Data[LineIndex];
  579. //
  580. // If the unique flag is off, this is the first line, or the lines
  581. // aren't equal then print the line.
  582. //
  583. if (((Context.Options & SORT_OPTION_UNIQUE) == 0) ||
  584. (PreviousLine == NULL) ||
  585. (SortCompareLines(&PreviousLine, &InputLine) != 0)) {
  586. fprintf(Output, "%s\n", InputLine->Data);
  587. }
  588. PreviousLine = InputLine;
  589. }
  590. Status = 0;
  591. MainEnd:
  592. SortContext = NULL;
  593. if ((Output != NULL) && (Output != stdout)) {
  594. fclose(Output);
  595. }
  596. SortDestroyArray(&(Context.Input),
  597. (PSORT_DESTROY_ARRAY_ELEMENT_ROUTINE)SortDestroyInput);
  598. SortDestroyArray(&(Context.Key), free);
  599. if (InputString.Data != NULL) {
  600. free(InputString.Data);
  601. }
  602. SortDestroyArray(&InputLines,
  603. (PSORT_DESTROY_ARRAY_ELEMENT_ROUTINE)SortDestroyString);
  604. if ((Status != 0) && (Status != 1)) {
  605. SwPrintError(Status, NULL, "Sort exiting abnormally");
  606. }
  607. return Status;
  608. }
  609. //
  610. // --------------------------------------------------------- Internal Functions
  611. //
  612. INT
  613. SortCheckFile (
  614. PSORT_CONTEXT Context,
  615. PSORT_INPUT Input
  616. )
  617. /*++
  618. Routine Description:
  619. This routine checks a file to see if it is sorted (and optionally unique).
  620. Arguments:
  621. Context - Supplies a pointer to the application context.
  622. Input - Supplies a pointer to the input to check.
  623. Return Value:
  624. 0 if the file is sorted.
  625. 1 if the file is not sorted.
  626. >1 error number if an error occurred.
  627. --*/
  628. {
  629. INT Comparison;
  630. PSORT_STRING Line;
  631. PSORT_STRING PreviousLine;
  632. INT Status;
  633. SORT_STRING WorkingBuffer;
  634. memset(&WorkingBuffer, 0, sizeof(SORT_STRING));
  635. Line = NULL;
  636. PreviousLine = NULL;
  637. while (TRUE) {
  638. Status = SortReadLine(Context,
  639. Input,
  640. &WorkingBuffer,
  641. &Line);
  642. if (Status != 0) {
  643. SwPrintError(Status, NULL, "Failed to read file");
  644. goto CheckFileEnd;
  645. }
  646. if (Line == NULL) {
  647. break;
  648. }
  649. if (PreviousLine != NULL) {
  650. Comparison = SortCompareLines(&PreviousLine, &Line);
  651. if (Comparison > 1) {
  652. Status = 1;
  653. goto CheckFileEnd;
  654. }
  655. if (((Context->Options & SORT_OPTION_UNIQUE) != 0) &&
  656. (Comparison == 0)) {
  657. Status = 1;
  658. goto CheckFileEnd;
  659. }
  660. SortDestroyString(PreviousLine);
  661. }
  662. PreviousLine = Line;
  663. Line = NULL;
  664. }
  665. Status = 0;
  666. CheckFileEnd:
  667. if (WorkingBuffer.Data != NULL) {
  668. free(WorkingBuffer.Data);
  669. }
  670. if (Line != NULL) {
  671. SortDestroyString(Line);
  672. }
  673. if (PreviousLine != NULL) {
  674. SortDestroyString(PreviousLine);
  675. }
  676. return Status;
  677. }
  678. INT
  679. SortMergeSortedFiles (
  680. PSORT_CONTEXT Context,
  681. FILE *Output
  682. )
  683. /*++
  684. Routine Description:
  685. This routine merges several files that are already in order.
  686. Arguments:
  687. Context - Supplies a pointer to the application context.
  688. Output - Supplies a pointer to the output file to write to.
  689. Return Value:
  690. 0 on success.
  691. Non-zero on failure.
  692. --*/
  693. {
  694. INT Comparison;
  695. PSORT_INPUT Input;
  696. UINTN InputIndex;
  697. PSORT_STRING PreviousWinner;
  698. INT Status;
  699. PSORT_INPUT Winner;
  700. SORT_STRING WorkingBuffer;
  701. PreviousWinner = NULL;
  702. memset(&WorkingBuffer, 0, sizeof(SORT_STRING));
  703. //
  704. // Prime all the inputs by reading their first lines.
  705. //
  706. for (InputIndex = 0; InputIndex < Context->Input.Size; InputIndex += 1) {
  707. Input = Context->Input.Data[InputIndex];
  708. Status = SortReadLine(Context,
  709. Input,
  710. &WorkingBuffer,
  711. &(Input->Line));
  712. if (Status != 0) {
  713. SwPrintError(Status, NULL, "Failed to read file");
  714. goto MergeSortedFilesEnd;
  715. }
  716. }
  717. //
  718. // Loop getting the winning line until all files are drained.
  719. //
  720. while (TRUE) {
  721. Winner = NULL;
  722. for (InputIndex = 0;
  723. InputIndex < Context->Input.Size;
  724. InputIndex += 1) {
  725. Input = Context->Input.Data[InputIndex];
  726. if (Input->Line == NULL) {
  727. continue;
  728. }
  729. if (Winner == NULL) {
  730. Winner = Input;
  731. } else {
  732. //
  733. // If this input's line is less than the current winner, set it
  734. // to the new winner.
  735. //
  736. Comparison = SortCompareLines(&(Input->Line), &(Winner->Line));
  737. if (Comparison < 0) {
  738. Winner = Input;
  739. }
  740. }
  741. }
  742. //
  743. // If there is no winner, then all files must be drained. Stop.
  744. //
  745. if (Winner == NULL) {
  746. break;
  747. }
  748. //
  749. // Print the line.
  750. //
  751. if (((Context->Options & SORT_OPTION_UNIQUE) == 0) ||
  752. (PreviousWinner == NULL) ||
  753. (SortCompareLines(&(Winner->Line), &PreviousWinner) != 0)) {
  754. fprintf(Output, "%s\n", Winner->Line->Data);
  755. }
  756. //
  757. // Set the new previous winner, and read a new line from that winning
  758. // file.
  759. //
  760. if (PreviousWinner != NULL) {
  761. SortDestroyString(PreviousWinner);
  762. }
  763. PreviousWinner = Winner->Line;
  764. if (Winner->Line != NULL) {
  765. Status = SortReadLine(Context,
  766. Winner,
  767. &WorkingBuffer,
  768. &(Winner->Line));
  769. if (Status != 0) {
  770. SwPrintError(Status, NULL, "Failed to read file");
  771. goto MergeSortedFilesEnd;
  772. }
  773. }
  774. }
  775. Status = 0;
  776. MergeSortedFilesEnd:
  777. if (PreviousWinner != NULL) {
  778. SortDestroyString(PreviousWinner);
  779. }
  780. if (WorkingBuffer.Data != NULL) {
  781. free(WorkingBuffer.Data);
  782. }
  783. return Status;
  784. }
  785. INT
  786. SortCompareLines (
  787. const VOID *LeftPointer,
  788. const VOID *RightPointer
  789. )
  790. /*++
  791. Routine Description:
  792. This routine compares two sort string elements.
  793. Arguments:
  794. LeftPointer - Supplies a pointer containing a pointer to the left string
  795. of the comparison.
  796. RightPointer - Supplies a pointer containing a pointer to the right string
  797. of the comparison.
  798. Return Value:
  799. 1 if Left > Right.
  800. 0 if Left == Right.
  801. -1 if Left < Right.
  802. --*/
  803. {
  804. PSORT_CONTEXT Context;
  805. PSORT_KEY Key;
  806. UINTN KeyIndex;
  807. PSORT_STRING Left;
  808. CHAR LeftCharacter;
  809. ULONG LeftEndIndex;
  810. ULONG LeftStartIndex;
  811. LONG LeftValue;
  812. ULONG Options;
  813. INT Result;
  814. PSORT_STRING Right;
  815. CHAR RightCharacter;
  816. ULONG RightEndIndex;
  817. ULONG RightStartIndex;
  818. LONG RightValue;
  819. Context = SortContext;
  820. Left = *(PSORT_STRING *)LeftPointer;
  821. Right = *(PSORT_STRING *)RightPointer;
  822. for (KeyIndex = 0; KeyIndex < Context->Key.Size; KeyIndex += 1) {
  823. Key = Context->Key.Data[KeyIndex];
  824. Options = Key->StartOptions | Key->EndOptions;
  825. SortGetFieldOffset(Left,
  826. Context->Separator,
  827. Key->StartField,
  828. Key->StartCharacter,
  829. &LeftStartIndex);
  830. SortGetFieldOffset(Left,
  831. Context->Separator,
  832. Key->EndField,
  833. Key->EndCharacter,
  834. &LeftEndIndex);
  835. SortGetFieldOffset(Right,
  836. Context->Separator,
  837. Key->StartField,
  838. Key->StartCharacter,
  839. &RightStartIndex);
  840. SortGetFieldOffset(Right,
  841. Context->Separator,
  842. Key->EndField,
  843. Key->EndCharacter,
  844. &RightEndIndex);
  845. //
  846. // Strip leading blanks if requested.
  847. //
  848. if ((Options & SORT_OPTION_IGNORE_LEADING_BLANKS) != 0) {
  849. while ((LeftStartIndex < LeftEndIndex) &&
  850. (isblank(Left->Data[LeftStartIndex]))) {
  851. LeftStartIndex += 1;
  852. }
  853. while ((RightStartIndex < RightEndIndex) &&
  854. (isblank(Right->Data[RightStartIndex]))) {
  855. RightStartIndex += 1;
  856. }
  857. }
  858. //
  859. // Scan and compare the numbers if sorting numerically.
  860. //
  861. if ((Options & SORT_OPTION_COMPARE_NUMERICALLY) != 0) {
  862. LeftValue = SortStringToLong(Left, Options, LeftStartIndex);
  863. RightValue = SortStringToLong(Right, Options, RightStartIndex);
  864. if (LeftValue < RightValue) {
  865. Result = -1;
  866. if ((Options & SORT_OPTION_REVERSE) != 0) {
  867. Result = -Result;
  868. }
  869. goto CompareLinesEnd;
  870. } else if (LeftValue > RightValue) {
  871. Result = 1;
  872. if ((Options & SORT_OPTION_REVERSE) != 0) {
  873. Result = -Result;
  874. }
  875. goto CompareLinesEnd;
  876. }
  877. //
  878. // Compare alphabetically.
  879. //
  880. } else {
  881. while ((LeftStartIndex < LeftEndIndex) ||
  882. (RightStartIndex < RightEndIndex)) {
  883. //
  884. // Get the left and right characters. Skip non-printables or
  885. // non-alphanumeric and non-blank if requested.
  886. //
  887. LeftCharacter = 0;
  888. RightCharacter = 0;
  889. if (LeftStartIndex < LeftEndIndex) {
  890. LeftCharacter = Left->Data[LeftStartIndex];
  891. if (((Options & SORT_OPTION_IGNORE_NONPRINTABLE) != 0) &&
  892. (!isprint(LeftCharacter))) {
  893. LeftStartIndex += 1;
  894. continue;
  895. }
  896. if (((Options & SORT_OPTION_ONLY_ALPHANUMERICS) != 0) &&
  897. (!isalnum(LeftCharacter)) &&
  898. (!isspace(LeftCharacter))) {
  899. LeftStartIndex += 1;
  900. continue;
  901. }
  902. }
  903. if (RightStartIndex < RightEndIndex) {
  904. RightCharacter = Right->Data[RightStartIndex];
  905. if (((Options & SORT_OPTION_IGNORE_NONPRINTABLE) != 0) &&
  906. (!isprint(RightCharacter))) {
  907. RightStartIndex += 1;
  908. continue;
  909. }
  910. if (((Options & SORT_OPTION_ONLY_ALPHANUMERICS) != 0) &&
  911. (!isalnum(RightCharacter)) &&
  912. (!isspace(RightCharacter))) {
  913. RightStartIndex += 1;
  914. continue;
  915. }
  916. }
  917. //
  918. // Upper-case the characters if requested.
  919. //
  920. if ((Options & SORT_OPTION_UPPERCASE_EVERYTHING) != 0) {
  921. LeftCharacter = toupper(LeftCharacter);
  922. RightCharacter = toupper(RightCharacter);
  923. }
  924. //
  925. // Finally finally finally compare the values.
  926. //
  927. if (LeftCharacter < RightCharacter) {
  928. Result = -1;
  929. if ((Options & SORT_OPTION_REVERSE) != 0) {
  930. Result = -Result;
  931. }
  932. goto CompareLinesEnd;
  933. } else if (LeftCharacter > RightCharacter) {
  934. Result = 1;
  935. if ((Options & SORT_OPTION_REVERSE) != 0) {
  936. Result = -Result;
  937. }
  938. goto CompareLinesEnd;
  939. }
  940. LeftStartIndex += 1;
  941. RightStartIndex += 1;
  942. }
  943. }
  944. }
  945. //
  946. // After all that, they come out the same.
  947. //
  948. Result = 0;
  949. CompareLinesEnd:
  950. return Result;
  951. }
  952. INT
  953. SortReadLine (
  954. PSORT_CONTEXT Context,
  955. PSORT_INPUT Input,
  956. PSORT_STRING Holding,
  957. PSORT_STRING *String
  958. )
  959. /*++
  960. Routine Description:
  961. This routine creates a string containing the next input line.
  962. Arguments:
  963. Context - Supplies a pointer to the application context.
  964. Input - Supplies a pointer to the input.
  965. Holding - Supplies a pointer to a transitory buffer to use to hold the
  966. string while it's being read.
  967. String - Supplies a pointer where the string will be returned on success.
  968. Return Value:
  969. Returns an integer exit code. 0 for success, nonzero otherwise.
  970. --*/
  971. {
  972. INT Character;
  973. PSORT_STRING NewString;
  974. INT Result;
  975. Holding->Size = 0;
  976. NewString = NULL;
  977. Character = fgetc(Input->File);
  978. if (Character == EOF) {
  979. Result = 0;
  980. goto ReadLineEnd;
  981. }
  982. //
  983. // Loop reading characters and shoving them into the holding buffer.
  984. //
  985. while (TRUE) {
  986. if (Character == EOF) {
  987. break;
  988. } else if (Character == '\n') {
  989. //
  990. // Peel off a carraige return too if it's there.
  991. //
  992. if ((Character == '\n') &&
  993. (Holding->Size != 0) &&
  994. (Holding->Data[Holding->Size - 1] == '\r')) {
  995. Holding->Size -= 1;
  996. }
  997. break;
  998. }
  999. Result = SortStringAddCharacter(Holding, (CHAR)Character);
  1000. if (Result != 0) {
  1001. goto ReadLineEnd;
  1002. }
  1003. Character = fgetc(Input->File);
  1004. }
  1005. //
  1006. // Terminate the string.
  1007. //
  1008. Result = SortStringAddCharacter(Holding, '\0');
  1009. if (Result != 0) {
  1010. goto ReadLineEnd;
  1011. }
  1012. //
  1013. // Create a new string that's well sized.
  1014. //
  1015. NewString = SortCreateString(Holding->Data, Holding->Size);
  1016. if (NewString == NULL) {
  1017. Result = ENOMEM;
  1018. goto ReadLineEnd;
  1019. }
  1020. Result = 0;
  1021. ReadLineEnd:
  1022. *String = NewString;
  1023. return Result;
  1024. }
  1025. INT
  1026. SortAddInputFile (
  1027. PSORT_CONTEXT Context,
  1028. PSTR FileName
  1029. )
  1030. /*++
  1031. Routine Description:
  1032. This routine adds an input file to the sort input array.
  1033. Arguments:
  1034. Context - Supplies a pointer to the application context.
  1035. FileName - Supplies a pointer to the file to add.
  1036. Return Value:
  1037. Returns an integer exit code. 0 for success, nonzero otherwise.
  1038. --*/
  1039. {
  1040. PSORT_INPUT Input;
  1041. INT Status;
  1042. Input = malloc(sizeof(SORT_INPUT));
  1043. if (Input == NULL) {
  1044. Status = ENOMEM;
  1045. goto AddInputFileEnd;
  1046. }
  1047. memset(Input, 0, sizeof(SORT_INPUT));
  1048. if (strcmp(FileName, "-") == 0) {
  1049. Input->File = stdin;
  1050. } else {
  1051. Input->File = fopen(FileName, "rb");
  1052. if (Input->File == NULL) {
  1053. Status = errno;
  1054. goto AddInputFileEnd;
  1055. }
  1056. }
  1057. Status = SortArrayAddElement(&(Context->Input), Input);
  1058. if (Status != 0) {
  1059. goto AddInputFileEnd;
  1060. }
  1061. Status = 0;
  1062. Input = NULL;
  1063. AddInputFileEnd:
  1064. if (Input != NULL) {
  1065. if (Input->File != NULL) {
  1066. fclose(Input->File);
  1067. }
  1068. free(Input);
  1069. }
  1070. return Status;
  1071. }
  1072. INT
  1073. SortAddKey (
  1074. PSORT_CONTEXT Context,
  1075. PSTR Argument
  1076. )
  1077. /*++
  1078. Routine Description:
  1079. This routine adds a sort key to the application context.
  1080. Arguments:
  1081. Context - Supplies a pointer to the application context.
  1082. Argument - Supplies a pointer to the key argument to parse and add.
  1083. Return Value:
  1084. Returns an integer exit code. 0 for success, nonzero otherwise.
  1085. --*/
  1086. {
  1087. PSTR AfterScan;
  1088. PSORT_KEY Key;
  1089. INT Status;
  1090. LONG Value;
  1091. Key = malloc(sizeof(SORT_KEY));
  1092. if (Key == NULL) {
  1093. Status = ENOMEM;
  1094. SwPrintError(0, NULL, "Allocation failure");
  1095. goto AddKeyEnd;
  1096. }
  1097. memset(Key, 0, sizeof(SORT_KEY));
  1098. Key->StartField = 1;
  1099. Key->StartCharacter = 1;
  1100. Key->EndField = -1;
  1101. Key->EndCharacter = -1;
  1102. //
  1103. // The total format looks like field_start[type][,field_end[type]], where
  1104. // type is [bdfinr] repeated, and field start and end are int[.int]. Start
  1105. // with the field_start field number.
  1106. //
  1107. Status = EINVAL;
  1108. Value = strtol(Argument, &AfterScan, 10);
  1109. if (Value <= 0) {
  1110. SwPrintError(0, Argument, "Invalid key start field");
  1111. goto AddKeyEnd;
  1112. }
  1113. Key->StartField = Value;
  1114. //
  1115. // If there's a dot next, scan the starting character.
  1116. //
  1117. Argument = AfterScan;
  1118. if (*Argument == '.') {
  1119. Argument += 1;
  1120. Value = strtol(Argument, &AfterScan, 10);
  1121. if (Value <= 0) {
  1122. SwPrintError(0, Argument, "Invalid key start character");
  1123. goto AddKeyEnd;
  1124. }
  1125. Key->StartCharacter = Value;
  1126. Argument = AfterScan;
  1127. }
  1128. //
  1129. // Scan any flags.
  1130. //
  1131. SortScanKeyFlags(&Argument, &(Key->StartOptions));
  1132. //
  1133. // If there's a comma, scan the end field number.
  1134. //
  1135. if (*Argument == ',') {
  1136. Argument += 1;
  1137. Value = strtol(Argument, &AfterScan, 10);
  1138. if (Value <= 0) {
  1139. SwPrintError(0, Argument, "Invalid key end field");
  1140. goto AddKeyEnd;
  1141. }
  1142. Key->EndField = Value;
  1143. //
  1144. // If there's a dot next, scan the ending character.
  1145. //
  1146. Argument = AfterScan;
  1147. if (*Argument == '.') {
  1148. Argument += 1;
  1149. Value = strtol(Argument, &AfterScan, 10);
  1150. if (Value <= 0) {
  1151. SwPrintError(0, Argument, "Invalid key end character");
  1152. goto AddKeyEnd;
  1153. }
  1154. Key->EndCharacter = Value;
  1155. Argument = AfterScan;
  1156. }
  1157. //
  1158. // Scan any flags.
  1159. //
  1160. SortScanKeyFlags(&Argument, &(Key->StartOptions));
  1161. }
  1162. //
  1163. // Add this new key to the array.
  1164. //
  1165. Status = SortArrayAddElement(&(Context->Key), Key);
  1166. if (Status != 0) {
  1167. goto AddKeyEnd;
  1168. }
  1169. Status = 0;
  1170. Key = NULL;
  1171. AddKeyEnd:
  1172. if (Key != NULL) {
  1173. free(Key);
  1174. }
  1175. return Status;
  1176. }
  1177. VOID
  1178. SortScanKeyFlags (
  1179. PSTR *Argument,
  1180. PULONG Flags
  1181. )
  1182. /*++
  1183. Routine Description:
  1184. This routine scans sort key type flags.
  1185. Arguments:
  1186. Argument - Supplies a pointer that on input contains a pointer where the
  1187. flags might be. On output, this pointer is advanced past any flags.
  1188. Flags - Supplies a pointer where the flags will be ORed in.
  1189. Return Value:
  1190. None.
  1191. --*/
  1192. {
  1193. PSTR String;
  1194. String = *Argument;
  1195. while (*String != '\0') {
  1196. switch (*String) {
  1197. case 'b':
  1198. *Flags |= SORT_OPTION_IGNORE_LEADING_BLANKS;
  1199. break;
  1200. case 'd':
  1201. *Flags |= SORT_OPTION_ONLY_ALPHANUMERICS;
  1202. break;
  1203. case 'f':
  1204. *Flags |= SORT_OPTION_UPPERCASE_EVERYTHING;
  1205. break;
  1206. case 'i':
  1207. *Flags |= SORT_OPTION_IGNORE_NONPRINTABLE;
  1208. break;
  1209. case 'n':
  1210. *Flags |= SORT_OPTION_COMPARE_NUMERICALLY;
  1211. break;
  1212. case 'r':
  1213. *Flags |= SORT_OPTION_REVERSE;
  1214. break;
  1215. default:
  1216. goto ScanKeyFlagsEnd;
  1217. }
  1218. String += 1;
  1219. }
  1220. ScanKeyFlagsEnd:
  1221. *Argument = String;
  1222. return;
  1223. }
  1224. INT
  1225. SortArrayAddElement (
  1226. PSORT_ARRAY Array,
  1227. PVOID Element
  1228. )
  1229. /*++
  1230. Routine Description:
  1231. This routine adds an element to the given array.
  1232. Arguments:
  1233. Array - Supplies a pointer to the array to add an element to.
  1234. Element - Supplies the element to add.
  1235. Return Value:
  1236. 0 on success.
  1237. ENOMEM on allocation failure.
  1238. --*/
  1239. {
  1240. PVOID NewBuffer;
  1241. UINTN NewCapacity;
  1242. if (Array->Size == Array->Capacity) {
  1243. if (Array->Capacity == 0) {
  1244. NewCapacity = SORT_INITIAL_ELEMENT_COUNT;
  1245. } else {
  1246. NewCapacity = Array->Capacity * 2;
  1247. }
  1248. NewBuffer = realloc(Array->Data, NewCapacity * sizeof(PVOID));
  1249. if (NewBuffer == NULL) {
  1250. return ENOMEM;
  1251. }
  1252. Array->Data = NewBuffer;
  1253. Array->Capacity = NewCapacity;
  1254. }
  1255. Array->Data[Array->Size] = Element;
  1256. Array->Size += 1;
  1257. return 0;
  1258. }
  1259. INT
  1260. SortStringAddCharacter (
  1261. PSORT_STRING String,
  1262. CHAR Character
  1263. )
  1264. /*++
  1265. Routine Description:
  1266. This routine adds a character to the given string.
  1267. Arguments:
  1268. String - Supplies a pointer to the string to add a character to.
  1269. Character - Supplies the character to add.
  1270. Return Value:
  1271. 0 on success.
  1272. ENOMEM on allocation failure.
  1273. --*/
  1274. {
  1275. PVOID NewBuffer;
  1276. UINTN NewCapacity;
  1277. if (String->Size == String->Capacity) {
  1278. if (String->Capacity == 0) {
  1279. NewCapacity = SORT_INITIAL_STRING_SIZE;
  1280. } else {
  1281. NewCapacity = String->Capacity * 2;
  1282. }
  1283. NewBuffer = realloc(String->Data, NewCapacity * sizeof(PVOID));
  1284. if (NewBuffer == NULL) {
  1285. return ENOMEM;
  1286. }
  1287. String->Data = NewBuffer;
  1288. String->Capacity = NewCapacity;
  1289. }
  1290. String->Data[String->Size] = Character;
  1291. String->Size += 1;
  1292. return 0;
  1293. }
  1294. PSORT_STRING
  1295. SortCreateString (
  1296. PSTR InitialData,
  1297. UINTN InitialDataSize
  1298. )
  1299. /*++
  1300. Routine Description:
  1301. This routine creates a new string.
  1302. Arguments:
  1303. InitialData - Supplies an optional pointer to an initial buffer to fill it
  1304. with.
  1305. InitialDataSize - Supplies the size of the initial data in bytes.
  1306. Return Value:
  1307. Returns a pointer to the new string on success. The caller is responsible
  1308. for destroying this string.
  1309. NULL on allocation failure.
  1310. --*/
  1311. {
  1312. INT Status;
  1313. PSORT_STRING String;
  1314. Status = ENOMEM;
  1315. String = malloc(sizeof(SORT_STRING));
  1316. if (String == NULL) {
  1317. goto CreateStringEnd;
  1318. }
  1319. memset(String, 0, sizeof(SORT_STRING));
  1320. if (InitialDataSize == 0) {
  1321. Status = 0;
  1322. goto CreateStringEnd;
  1323. }
  1324. String->Data = malloc(InitialDataSize);
  1325. if (String->Data == NULL) {
  1326. goto CreateStringEnd;
  1327. }
  1328. if (InitialData != NULL) {
  1329. memcpy(String->Data, InitialData, InitialDataSize);
  1330. }
  1331. String->Size = InitialDataSize;
  1332. String->Capacity = InitialDataSize;
  1333. Status = 0;
  1334. CreateStringEnd:
  1335. if (Status != 0) {
  1336. if (String != NULL) {
  1337. if (String->Data != NULL) {
  1338. free(String->Data);
  1339. }
  1340. free(String);
  1341. String = NULL;
  1342. }
  1343. }
  1344. return String;
  1345. }
  1346. VOID
  1347. SortDestroyString (
  1348. PSORT_STRING String
  1349. )
  1350. /*++
  1351. Routine Description:
  1352. This routine destroys a string.
  1353. Arguments:
  1354. String - Supplies a pointer to the string to destroy.
  1355. Return Value:
  1356. None.
  1357. --*/
  1358. {
  1359. if (String->Data != NULL) {
  1360. free(String->Data);
  1361. }
  1362. free(String);
  1363. return;
  1364. }
  1365. VOID
  1366. SortDestroyArray (
  1367. PSORT_ARRAY Array,
  1368. PSORT_DESTROY_ARRAY_ELEMENT_ROUTINE DestroyElementRoutine
  1369. )
  1370. /*++
  1371. Routine Description:
  1372. This routine destroys an array, calling the given destroy routine on each
  1373. element in the array.
  1374. Arguments:
  1375. Array - Supplies a pointer to the array to destroy.
  1376. DestroyElementRoutine - Supplies a pointer to the routine that gets called
  1377. on each element to perform any necessary cleanup on the elements in the
  1378. array.
  1379. Return Value:
  1380. None.
  1381. --*/
  1382. {
  1383. UINTN ElementIndex;
  1384. for (ElementIndex = 0; ElementIndex < Array->Size; ElementIndex += 1) {
  1385. DestroyElementRoutine(Array->Data[ElementIndex]);
  1386. }
  1387. if (Array->Data != NULL) {
  1388. free(Array->Data);
  1389. }
  1390. Array->Data = NULL;
  1391. Array->Size = 0;
  1392. Array->Capacity = 0;
  1393. return;
  1394. }
  1395. VOID
  1396. SortDestroyInput (
  1397. PSORT_INPUT Input
  1398. )
  1399. /*++
  1400. Routine Description:
  1401. This routine destroys an input.
  1402. Arguments:
  1403. Input - Supplies a pointer to the input to destroy.
  1404. Return Value:
  1405. None.
  1406. --*/
  1407. {
  1408. if ((Input->File != NULL) && (Input->File != stdout)) {
  1409. fclose(Input->File);
  1410. }
  1411. if (Input->Line != NULL) {
  1412. SortDestroyString(Input->Line);
  1413. }
  1414. free(Input);
  1415. return;
  1416. }
  1417. VOID
  1418. SortGetFieldOffset (
  1419. PSORT_STRING String,
  1420. INT Separator,
  1421. LONG Field,
  1422. LONG Character,
  1423. PULONG Offset
  1424. )
  1425. /*++
  1426. Routine Description:
  1427. This routine gets the offset within the string corresponding to the given
  1428. field, character combination.
  1429. Arguments:
  1430. String - Supplies a pointer to the string.
  1431. Separator - Supplies the separator character, or -1 if no separator was
  1432. set.
  1433. Field - Supplies the one-based field number.
  1434. Character - Supplies the one-based character within the field.
  1435. Offset - Supplies a pointer where the offset within the string
  1436. corresponding to the given field and character will be returned.
  1437. Return Value:
  1438. None.
  1439. --*/
  1440. {
  1441. LONG CharacterIndex;
  1442. PSTR CurrentString;
  1443. LONG FieldIndex;
  1444. //
  1445. // Check for a quick exit.
  1446. //
  1447. if ((Field == 1) && (Character == 1)) {
  1448. *Offset = 0;
  1449. return;
  1450. }
  1451. if (Field == -1) {
  1452. *Offset = String->Size;
  1453. return;
  1454. }
  1455. //
  1456. // Advance through the fields.
  1457. //
  1458. CurrentString = String->Data;
  1459. for (FieldIndex = 1; FieldIndex < Field; FieldIndex += 1) {
  1460. if (Separator == -1) {
  1461. while ((UINTN)CurrentString - (UINTN)String->Data < String->Size) {
  1462. //
  1463. // By default, a field is delimited by the space between a
  1464. // non-blank and a blank.
  1465. //
  1466. if ((isspace(*CurrentString)) &&
  1467. (CurrentString != String->Data) &&
  1468. (!isspace(*(CurrentString - 1)))) {
  1469. break;
  1470. }
  1471. CurrentString += 1;
  1472. }
  1473. if ((UINTN)CurrentString - (UINTN)String->Data == String->Size) {
  1474. *Offset = String->Size;
  1475. return;
  1476. }
  1477. } else {
  1478. CurrentString = strchr(CurrentString, Separator);
  1479. if (CurrentString == NULL) {
  1480. *Offset = String->Size;
  1481. return;
  1482. }
  1483. }
  1484. CurrentString += 1;
  1485. }
  1486. //
  1487. // Advance through the characters.
  1488. //
  1489. for (CharacterIndex = 1;
  1490. (CharacterIndex < Character) || (Character == -1);
  1491. CharacterIndex += 1) {
  1492. if (Separator == -1) {
  1493. if ((isspace(*CurrentString)) &&
  1494. (CurrentString != String->Data) &&
  1495. (!isspace(*(CurrentString - 1)))) {
  1496. break;
  1497. }
  1498. } else {
  1499. if (*CurrentString == Separator) {
  1500. break;
  1501. }
  1502. }
  1503. if ((UINTN)CurrentString - (UINTN)String->Data == String->Size) {
  1504. break;
  1505. }
  1506. CurrentString += 1;
  1507. }
  1508. *Offset = (UINTN)CurrentString - (UINTN)String->Data;
  1509. return;
  1510. }
  1511. LONG
  1512. SortStringToLong (
  1513. PSORT_STRING String,
  1514. ULONG Options,
  1515. ULONG Offset
  1516. )
  1517. /*++
  1518. Routine Description:
  1519. This routine converts the given string to a decimal number, ignoring
  1520. thousands groupings and potentially non-printable characters.
  1521. Arguments:
  1522. String - Supplies a pointer to the string.
  1523. Options - Supplies the options governing the scan.
  1524. Offset - Supplies the offset from the beginning of the string to start
  1525. scanning from.
  1526. Return Value:
  1527. Returns the integer representation of the string.
  1528. --*/
  1529. {
  1530. CHAR Character;
  1531. LONG Index;
  1532. BOOL Negative;
  1533. BOOL SeenSomething;
  1534. LONG Value;
  1535. Negative = FALSE;
  1536. SeenSomething = FALSE;
  1537. Value = 0;
  1538. for (Index = Offset; Index < String->Size; Index += 1) {
  1539. Character = String->Data[Index];
  1540. if (((Options & SORT_OPTION_IGNORE_NONPRINTABLE) != 0) &&
  1541. (!isprint(Character))) {
  1542. continue;
  1543. }
  1544. if ((SeenSomething == FALSE) && (Character == '-')) {
  1545. SeenSomething = TRUE;
  1546. Negative = TRUE;
  1547. continue;
  1548. }
  1549. SeenSomething = TRUE;
  1550. if (Character == ',') {
  1551. continue;
  1552. }
  1553. if (!isdigit(Character)) {
  1554. break;
  1555. }
  1556. Value = (Value * 10) + (Character - '0');
  1557. }
  1558. if (Negative != FALSE) {
  1559. Value = -Value;
  1560. }
  1561. return Value;
  1562. }