libfossil
util.h
Go to the documentation of this file.
1/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* vim: set ts=2 et sw=2 tw=80: */
3#if !defined(ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED)
4#define ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED
5/*
6 Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt
7
8 SPDX-License-Identifier: BSD-2-Clause-FreeBSD
9 SPDX-FileCopyrightText: 2021 The Libfossil Authors
10 SPDX-FileType: Code
11
12 Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
13
14*/
15
16/** @file util.h
17
18 This file declares a number of utility classes and routines used by
19 libfossil. All of them considered "public", suitable for direct use
20 by client code.
21*/
22
23#include "config.h" /* MUST come first b/c of config macros */
24#include <stdio.h> /* FILE type */
25#include <stdarg.h> /* va_list */
26#include <time.h> /* tm struct */
27#include <stdbool.h>
28#if defined(__cplusplus)
29extern "C" {
30#endif
32typedef struct fsl_buffer fsl_buffer;
33typedef struct fsl_error fsl_error;
35typedef struct fsl_fstat fsl_fstat;
36typedef struct fsl_list fsl_list;
38typedef struct fsl_state fsl_state;
39typedef struct fsl_id_bag fsl_id_bag;
40
41/**
42 fsl_uuid_str and fsl_uuid_cstr are "for documentation and
43 readability purposes" typedefs used to denote strings which the API
44 requires to be in the form of Fossil UUID strings. Such strings are
45 exactly FSL_STRLEN_SHA1 or FSL_STRLEN_K256 bytes long plus a
46 terminating NUL byte and contain only lower-case hexadecimal
47 bytes. Where this typedef is used, the library requires, enforces,
48 and/or assumes (at different times) that fsl_is_uuid() returns true
49 for such strings (if they are not NULL, though not all contexts
50 allow a NULL UUID). These typedef are _not_ used to denote
51 arguments which may refer to partial UUIDs or symbolic names, only
52 100% bonafide Fossil UUIDs (which are different from RFC4122
53 UUIDs).
54
55 The API guarantees that this typedef will always be (char *) and
56 that fsl_uuid_cstr will always ben (char const *), and thus it
57 is safe/portable to use those type instead of these. These
58 typedefs serve only to improve the readability of certain APIs
59 by implying (through the use of this typedef) the preconditions
60 defined for UUID strings.
61
62 Sidebar: fossil historically used the term UUID for blob IDs, and
63 still uses that term in the DB schema, but it has fallen out of
64 favor in documentation and discussions, with "hash" being the
65 preferred term. Much of the libfossil code was developed before
66 that happened, though, so "UUID" is still prevalent in its API and
67 documentation.
68
69 @see fsl_is_uuid()
70 @see fsl_uuid_cstr
71*/
72typedef char * fsl_uuid_str;
73
74/**
75 The const counterpart of fsl_uuid_str.
76
77 @see fsl_is_uuid()
78 @see fsl_uuid_str
79*/
80typedef char const * fsl_uuid_cstr;
81
82/**
83 A typedef for comparison function used by standard C routines such
84 as qsort(). It is provided here primarily to simplify documentation
85 of other APIs. Concrete implementations must compare lhs and rhs,
86 returning negative, 0, or positive depending on whether lhs is less
87 than, equal to, or greater than rhs.
88
89 Implementations might need to be able to deal with NULL
90 arguments. That depends on the routine which uses the comparison
91 function.
92*/
93typedef int (*fsl_generic_cmp_f)( void const * lhs, void const * rhs );
94
95/**
96 If the NUL-terminated input str is exactly FSL_STRLEN_SHA1 or
97 FSL_STRLEN_K256 bytes long and contains only lower-case
98 hexadecimal characters, returns the length of the string, else
99 returns 0.
100
101 Note that Fossil UUIDs are not RFC4122 UUIDs, but are SHA1 or
102 SHA3-256 hash strings. Don't let that disturb you. As Tim
103 Berners-Lee writes:
104
105 'The assertion that the space of URIs is a universal space
106 sometimes encounters opposition from those who feel there should
107 not be one universal space. These people need not oppose the
108 concept because it is not of a single universal space: Indeed,
109 the fact that URIs form universal space does not prevent anyone
110 else from forming their own universal space, which of course by
111 definition would be able to envelop within it as a subset the
112 universal URI space. Therefore the web meets the "independent
113 design" test, that if a similar system had been concurrently and
114 independently invented elsewhere, in such a way that the
115 arbitrary design decisions were made differently, when they met
116 later, the two systems could be made to interoperate.'
117
118 Source: https://www.w3.org/DesignIssues/Axioms.html
119
120 (Just mentally translate URI as UUID.)
121*/
122FSL_EXPORT int fsl_is_uuid(char const * str);
123
124/**
125 If x is a valid fossil UUID length, it is returned, else 0 is returned.
126*/
128
129/**
130 Expects str to be a string containing an unsigned decimal
131 value. Returns its decoded value, or -1 on error.
132*/
134
135/**
136 Expects str to be a string containing a decimal value,
137 optionally with a leading sign. Returns its decoded value, or
138 dflt if !str or on error.
139*/
141
142
143/**
144 Generic list container type. This is used heavily by the Fossil
145 API for storing arrays of dynamically-allocated objects. It is
146 not useful as a non-pointer-array replacement.
147
148 It is up to the APIs using this type to manage the entry count
149 member and use fsl_list_reserve() to manage the "capacity"
150 member.
151
152 @see fsl_list_reserve()
153 @see fsl_list_append()
154 @see fsl_list_visit()
155*/
156struct fsl_list {
157 /**
158 Array of entries. It contains this->capacity entries,
159 this->count of which are "valid" (in use).
160 */
161 void ** list;
162 /**
163 Number of "used" entries in the list.
164 */
166 /**
167 Number of slots allocated in this->list. Use fsl_list_reserve()
168 to modify this. Doing so might move the this->list pointer but
169 the values it points to will stay stable.
170 */
172};
173
174/**
175 Empty-initialized fsl_list structure, intended for const-copy
176 initialization.
177*/
178#define fsl_list_empty_m { .list=NULL, .used=0, .capacity=0 }
179
180/**
181 Empty-initialized fsl_list structure, intended for copy
182 initialization.
183*/
185
186/**
187 Generic interface for finalizing/freeing memory. Intended
188 primarily for use as a destructor/finalizer for high-level
189 structs. Implementations must semantically behave like free(mem),
190 regardless of whether or not they actually free the memory. At
191 the very least, they generally should clean up any memory owned by
192 mem (e.g. db resources or buffers), even if they do not free() mem.
193 some implementations assume that mem is stack-allocated
194 and they only clean up resources owned by mem.
195
196 The state parameter is any state needed by the finalizer
197 (e.g. a memory allocation context) and mem is the memory which is
198 being finalized.
199
200 The exact interpretaion of the state and mem are of course
201 implementation-specific.
202*/
203typedef void (*fsl_finalizer_f)( void * state, void * mem );
204
205/**
206 Generic interface for memory finalizers.
207*/
209 /**
210 State to be passed as the first argument to f().
211 */
212 void * state;
213 /**
214 Finalizer function. Should be called like this->f( this->state, ... ).
215 */
217};
218
219/** Empty-initialized fsl_finalizer struct. */
220#define fsl_finalizer_empty_m {NULL,NULL}
221
222/**
223 fsl_finalizer_f() impl which requires that mem be-a
224 (fsl_buffer*). This function frees all memory associated with
225 that buffer and zeroes out the structure, but does not free mem
226 (because it is rare that fsl_buffers are created on the
227 heap). The state parameter is ignored.
228*/
229FSL_EXPORT int fsl_finalizer_f_buffer( void * state, void * mem );
230
231
232/**
233 Generic state-with-finalizer holder. Used for binding
234 client-specified state to another object, such that a
235 client-specified finalizer is called with the other object is
236 cleaned up.
237*/
238struct fsl_state {
239 /**
240 Arbitrary context-dependent state.
241 */
242 void * state;
243 /**
244 Finalizer for this->state. If used, it should be called like:
245
246 ```
247 this->finalize.f( this->finalize.state, this->state );
248 ```
249
250 After which this->state must be treated as if it has been
251 free(3)'d. See fsl_state_finalize().
252 */
254};
255
256/** Empty-initialized fsl_state struct. */
257#define fsl_state_empty_m {NULL,fsl_finalizer_empty_m}
258
259/**
260 Empty-initialized fsl_state struct, intended for
261 copy-initializing.
262*/
264
265/**
266 If fst is not NULL then:
267
268 - If fst->finalize.f is not null, then it is called and
269 passed (fst->finalize.f, fst->state).
270
271 - *fst is cleared out. fst is not freed.
272
273 This is a no-op if fst is NULL.
274*/
276
277/**
278 Generic interface for streaming out data. Implementations must
279 write n bytes from src to their destination channel and return 0
280 on success, non-0 on error (assumed to be a value from the fsl_rc_e
281 enum). The state parameter is the implementation-specified output
282 channel.
283
284 Potential TODO: change the final argument to a pointer, with
285 semantics similar to fsl_input_f(): at call-time n is the number
286 of bytes to output, and on returning n is the number of bytes
287 actually written. This would allow, e.g. the fsl_zip_writer APIs
288 to be able to stream a ZIP file (they have to know the real size
289 of the output, and this interface doesn't support that
290 operation).
291*/
292typedef int (*fsl_output_f)( void * state, void const * src, fsl_size_t n );
293
294
295/**
296 Generic interface for flushing arbitrary output streams. Must
297 return 0 on success, non-0 on error, but the result code
298 "should" (to avoid downstream confusion) be one of the fsl_rc_e
299 values. When in doubt, return FSL_RC_IO on error. The
300 interpretation of the state parameter is
301 implementation-specific.
302*/
303typedef int (*fsl_flush_f)(void * state);
304
305/**
306 Generic interface for streaming in data. Implementations must
307 read (at most) *n bytes from their input, copy it to dest, assign
308 *n to the number of bytes actually read, return 0 on success, and
309 return non-0 on error (assumed to be a value from the fsl_rc_e
310 enum). When called, *n is the max length to read. On return, *n
311 is the actual amount read. The state parameter is the
312 implementation-specified input file/buffer/whatever channel.
313
314 Implementations may need to distinguish a short read due to EOF
315 from a short read due to an I/O error, e.g. using feof() and/or
316 ferror().
317*/
318typedef int (*fsl_input_f)( void * state, void * dest, fsl_size_t * n );
319
320/**
321 fsl_output_f() implementation which requires state to be a
322 (fsl_cx*) to which this routine simply redirects the output via
323 fsl_output(). Is a no-op (returning 0) if !n. Returns
324 FSL_RC_MISUSE if !state or !src.
325*/
326FSL_EXPORT int fsl_output_f_fsl_cx(void * state, void const * src, fsl_size_t n );
327
328/**
329 An interface which encapsulates data for managing an output
330 destination, primarily intended for use with fsl_output(). Why
331 abstract it to this level? So that we can do interesting things
332 like output to buffers, files, sockets, etc., using the core
333 output mechanism. e.g. so script bindings can send their output
334 to the same channel used by the library and other library
335 clients.
336*/
338 /**
339 Output channel.
340 */
342 /**
343 flush() implementation. This may be NULL for most uses of this
344 class. Cases which specifically require it must document that
345 requirement so.
346 */
348 /**
349 State to be used when calling this->out(), namely:
350 this->out( this->state, ... ) and this->flush(this->state).
351 */
352 void * state;
353};
354/** Empty-initialized fsl_outputer instance. */
355#define fsl_outputer_empty_m {NULL,NULL,NULL}
356/**
357 Empty-initialized fsl_outputer instance, intended for
358 copy-initializing.
359*/
361
362/**
363 A fsl_outputer instance which is initialized to output to a
364 (FILE*). To use it, this value then set the copy's state
365 member to an opened-for-write (FILE*) handle. By default it will
366 use stdout.
367*/
369
370/**
371 fsl_outputer initializer which uses fsl_flush_f_FILE() and
372 fsl_output_f_FILE(). After copying, the state member must be
373 pointed to an opened-for-writing (FILE*).
374*/
375#define fsl_outputer_FILE_m { \
376 .out = fsl_output_f_FILE, \
377 .flush = fsl_flush_f_FILE, \
378 .state = NULL \
379}
380
381/**
382 Generic stateful alloc/free/realloc() interface.
383
384 Implementations must behave as follows:
385
386 - If 0==n then semantically behave like free(3) and return
387 NULL.
388
389 - If 0!=n and !mem then semantically behave like malloc(3), returning
390 newly-allocated memory on success and NULL on error.
391
392 - If 0!=n and NULL!=mem then semantically behave like
393 realloc(3). Note that realloc specifies: "If n was equal to 0,
394 either NULL or a pointer suitable to be passed to free() is
395 returned." Which is kind of useless, and thus implementations
396 MUST return NULL when n==0.
397*/
398typedef void *(*fsl_realloc_f)(void * state, void * mem, fsl_size_t n);
399
400/**
401 Holds an allocator function and its related state.
402*/
404 /**
405 Base allocator function. It must be passed this->state as its
406 first argument.
407 */
409 /**
410 State intended to be passed as the first argument to this->f().
411 */
412 void * state;
413};
414
415/** Empty-initialized fsl_allocator instance. */
416#define fsl_allocator_empty_m {NULL,NULL}
417
418
419/**
420 A fsl_realloc_f() implementation which uses the standard
421 malloc()/free()/realloc(). The state parameter is ignored.
422*/
423FSL_EXPORT void * fsl_realloc_f_stdalloc(void * state, void * mem, fsl_size_t n);
424
425
426/**
427 Semantically behaves like malloc(3), but may introduce instrumentation,
428 error checking, or similar.
429*/
431#ifdef __GNUC__
432 __attribute__ ((malloc))
433#endif
434 ;
435
436/**
437 Semantically behaves like free(3), but may introduce instrumentation,
438 error checking, or similar.
439*/
440FSL_EXPORT void fsl_free( void * mem );
441
442/**
443 Behaves like realloc(3). Clarifications on the behaviour (because
444 the standard has one case of unfortunate wording involving what
445 it returns when n==0):
446
447 - If passed (NULL, n>0) then it semantically behaves like
448 fsl_malloc(f, n).
449
450 - If 0==n then it semantically behaves like free(2) and returns
451 NULL (clarifying the aforementioned wording problem).
452
453 - If passed (non-NULL, n) then it semantically behaves like
454 realloc(mem,n).
455
456*/
457FSL_EXPORT void * fsl_realloc( void * mem, fsl_size_t n );
458
459/**
460 A fsl_flush_f() impl which expects _FILE to be-a (FILE*) opened
461 for writing, which this function passes the call on to
462 fflush(). If fflush() returns 0, so does this function, else it
463 returns non-0.
464*/
465FSL_EXPORT int fsl_flush_f_FILE(void * _FILE);
466
467/**
468 A fsl_finalizer_f() impl which requires that mem be-a (FILE*).
469 This function passes that FILE to fsl_fclose(). The state
470 parameter is ignored.
471*/
472FSL_EXPORT void fsl_finalizer_f_FILE( void * state, void * mem );
473
474/**
475 A fsl_output_f() impl which requires state to be-a (FILE*), which
476 this function passes the call on to fwrite(). Returns 0 on
477 success, FSL_RC_IO on error.
478*/
479FSL_EXPORT int fsl_output_f_FILE( void * state, void const * src, fsl_size_t n );
480
481/**
482 A fsl_output_f() impl which requires state to be-a (fsl_buffer*),
483 which this function passes to fsl_buffer_append(). Returns 0 on
484 success, FSL_RC_OOM (probably) on error.
485*/
486FSL_EXPORT int fsl_output_f_buffer( void * state, void const * src, fsl_size_t n );
487
488
489/**
490 A fsl_output_f() impl which requires state to be-a (int*) referring
491 to a writable file descriptor, which this function passes to
492 write(2). Returns 0 on success.
493*/
494FSL_EXPORT int fsl_output_f_fd( void * state, void const * src, fsl_size_t n );
495
496/**
497 A fsl_input_f() implementation which requires that state be
498 a readable (FILE*) handle.
499*/
500FSL_EXPORT int fsl_input_f_FILE( void * state, void * dest, fsl_size_t * n );
501
502/**
503 A fsl_input_f() implementation which requires that state be a
504 readable file descriptor, in the form of an ([const] int*). This
505 function will not modify that value.
506*/
507FSL_EXPORT int fsl_input_f_fd( void * state, void * dest, fsl_size_t * n );
508
509/**
510 A fsl_input_f() implementation which requires that state be a
511 readable (fsl_buffer*) handle. The buffer's cursor member is
512 updated to track input postion, but that is the only modification
513 made by this routine. Thus the user may need to reset the cursor to
514 0 if he wishes to start consuming the buffer at its starting point
515 (e.g. call fsl_buffer_rewind()). Subsequent calls to this function
516 will increment the cursor by the number of bytes returned via *n.
517 The buffer's "used" member is used to determine the logical end of
518 input.
519
520 If fsl_buffer_err() is non-zero for the state argument, that code
521 is returned without other side effects.
522
523 Returns 0 on success and has no error conditions except for invalid
524 arguments, which result in undefined beavhiour, or fsl_buffer_err()
525 being true for the state argument. Results are undefined if any
526 argument is NULL.
527
528 Tip (and warning): sometimes a routine might have a const buffer
529 handle which it would like to use in conjunction with this
530 routine but cannot without violating constness. Here's a crude
531 workaround:
532
533 ```
534 fsl_buffer kludge = fsl_buffer_empty;
535 fsl_buffer_external(&kludge, theConstBuffer->mem, theConstBuffer->used);
536 rc = some_func( fsl_input_f_buffer, &kludge, ... );
537 assert( kludge.mem == theConstBuffer->mem );// not reallocated
538 assert( 0==kludge.capacity );// b/c it's an external buffer
539 ```
540
541 That is legal because this routine modifies only
542 fsl_buffer::cursor. It is not useful as a constness workaround if
543 there is ANY CHANCE WHATSOEVER that the buffer's memory will be
544 modified. If such tricks are used for APIs which may modify their
545 buffer, the "kludge" buffer (above), because it's an "external"
546 buffer, will create a new copy of theConstBuffer's memory before
547 making any changes, which will lead a leak if that object is not
548 cleaned up.
549
550 [Much later:] a cleaner approach is to use fsl_buffer_external().
551*/
552FSL_EXPORT int fsl_input_f_buffer( void * state, void * dest, fsl_size_t * n );
553
554
555/**
556 A generic streaming routine which copies data from an
557 fsl_input_f() to an fsl_outpuf_f().
558
559 Reads all data from inF() in chunks of an unspecified size and
560 passes them on to outF(). It reads until inF() returns fewer bytes
561 than requested. Returns the result of the last call to outF() or
562 (only if reading fails) inF(). Results are undefined if either of
563 the callback function arguments are NULL. (This function cannot
564 know whether a NULL state argument is legal.)
565
566 Here is an example which basically does the same thing as the
567 cat(1) command on Unix systems:
568
569 ```
570 fsl_stream( fsl_input_f_FILE, stdin, fsl_output_f_FILE, stdout );
571 ```
572
573 Or copy a FILE to a buffer:
574
575 ```
576 FILE * f = fopen(...);
577 fsl_buffer myBuf = fsl_buffer_empty;
578 rc = fsl_stream( fsl_input_f_FILE, f, fsl_output_f_buffer, &myBuf );
579 // Note that on error myBuf might be partially populated.
580 // Eventually clean up the buffer:
581 fsl_buffer_clear(&myBuf);
582 ```
583*/
584FSL_EXPORT int fsl_stream( fsl_input_f inF, void * inState,
585 fsl_output_f outF, void * outState );
586
587/**
588 Consumes two input streams looking for differences. It stops
589 reading as soon as either or both streams run out of input or a
590 byte-level difference is found. It consumes input in chunks of
591 an unspecified size, and after this returns the input cursor of
592 the streams is not well-defined. i.e. the cursor probably does
593 not point to the exact position of the difference because this
594 level of abstraction does not allow that unless we read byte by
595 byte.
596
597 Returns 0 if both streams emit the same amount of output and
598 that ouput is bitwise identical, otherwise it returns non-0.
599*/
600FSL_EXPORT int fsl_stream_compare( fsl_input_f in1, void * in1State,
601 fsl_input_f in2, void * in2State );
602
603
604/**
605 A general-purpose buffer class, analog to Fossil's Blob
606 class, but it is not called fsl_blob to avoid confusion with
607 DB-side blobs. Buffers are used extensively in fossil to do
608 everything from reading files to compressing artifacts to
609 creating dynamically-formatted strings. Because they are such a
610 pervasive low-level type, and have such a simple structure,
611 their members (unlike most other structs in this API) may be
612 considered public and used directly by client code (as long as
613 they do not mangle their state, e.g. by setting this->capacity
614 smaller than this->used!).
615
616 General conventions of this class:
617
618 - ALWAYS initialize them by copying fsl_buffer_empty or
619 (depending on the context) fsl_buffer_empty_m. Failing to
620 initialize them properly leads to undefined behaviour.
621
622 - ALWAYS fsl_buffer_clear() buffers when done with
623 them. Remember that failed routines which output to buffers
624 might partially populate the buffer, so be sure to clean up in
625 error cases.
626
627 - The `capacity` member specifies how much memory the buffer
628 currently holds in its `mem` member. If `capacity` is 0 and `mem`
629 is not then the memory is expected to refer to `used` bytes of
630 memory which are owned elsewhere. See fsl_buffer_external() and
631 fsl_buffer_materialize() for details.
632
633 - The `used` member specifies how much of the memory is actually
634 "in use" by the buffer. The exact meaning of "used" is
635 context-dependent but it's typically equivalent to the strlen() of
636 the buffer's contents.
637
638 - As a rule, the public APIs keep (`used`<`capacity`) and always
639 (unless documented otherwise) tries to keep the memory buffer
640 NUL-terminated (if it has any memory at all). The notable
641 potential exception to that is that "external" buffers
642 may not be NUL-terminated (see fsl_buffer_external()).
643
644 - Use fsl_buffer_reuse() to keep memory around and reset the `used`
645 amount to 0. Most library-wide routines which write to buffers will
646 re-use that memory if they can, rather than re-allocating.
647
648 This example demonstrates the difference between `used` and
649 `capacity` (error checking reduced to assert()ions for clarity):
650
651 ```
652 fsl_buffer b = fsl_buffer_empty;
653 // ALWAYS init via copying fsl_buffer_empty or (depending on
654 // the context) fsl_buffer_empty_m. The latter is used for
655 // in-struct initialization of struct members.
656 int rc = fsl_buffer_reserve(&b, 20);
657 assert(0==rc);
658 assert(b.capacity>=20); // it may reserve more!
659 assert(0==b.used);
660 rc = fsl_buffer_append(&b, "abc", 3);
661 assert(0==rc);
662 assert(3==b.used);
663 assert(0==b.mem[b.used]); // API always NUL-terminates
664 fsl_buffer_reuse(&b);
665 assert(0==b.used); // Resets the buffer but...
666 assert(b.capacity>=20); // ... keeps the memory.
667 fsl_buffer_clear(&b); // ALWAYS clean up
668 ```
669
670 @see fsl_buffer_reserve()
671 @see fsl_buffer_resize()
672 @see fsl_buffer_external()
673 @see fsl_buffer_materialize()
674 @see fsl_buffer_append()
675 @see fsl_buffer_appendf()
676 @see fsl_buffer_cstr()
677 @see fsl_buffer_size()
678 @see fsl_buffer_capacity()
679 @see fsl_buffer_clear()
680 @see fsl_buffer_reuse()
681 @see fsl_buffer_err()
682 @see fsl_buffer_err_clear()
683*/
685 /**
686 The raw memory pointed to by this buffer. There are two ways of
687 using this member:
688
689 - If `this->capacity` is non-0 then the first `this->capacity`
690 bytes of `this->mem` are owned by this buffer instance. The API
691 docs call this state "managed" buffers.
692
693 - `If this->capacity` is 0 and this->mem is not NULL then the
694 memory is owned by "somewhere else" and this API will treat it as
695 _immutable_ (so it may safely point to const data). Its lifetime
696 must exceed this object's and any attempt made via this API to
697 write to it will cause the memory to be copied (effectively a
698 copy-on-write op). The API calls this state "external" buffers
699 and refers to the copy-on-write of such buffers as
700 "materializing" them. See fsl_buffer_external() and
701 fsl_buffer_materialize() for details.
702
703 `this->used` bytes are treated as the "used" part of the buffer
704 (as opposed to its capacity). When `this->capacity>0` the
705 difference beween (`this->capacity - this->used`) represents
706 space the buffer has available for use before it will require
707 another expansion/reallocation.
708 */
709 unsigned char * mem;
710 /**
711 Number of bytes allocated for this buffer. If capacity is 0
712 and `this->mem` is not NULL then this buffer's memory is assumed
713 to be owned "elsewhere" and will be considered immutable by the
714 API. Any attempt to modify it will result in a copy-on-write
715 operation
716 */
718
719 /**
720 Number of "used" bytes in the buffer. This is generally
721 interpreted as the string length of this->mem, and the buffer
722 APIs which add data to a buffer always ensure that
723 this->capacity is large enough to account for a trailing NUL
724 byte in this->mem.
725
726 Library routines which manipulate buffers must ensure that
727 (this->used<this->capacity) is always true, expanding the buffer
728 if necessary. Much of the API assumes that precondition is always
729 met, and any violation of it opens the code to undefined
730 behaviour (which is okay, just don't ever break that
731 precondition). Most APIs ensure that (used<capacity) is always
732 true (as opposed to used<=capacity) because they add a trailing
733 NUL byte which is not counted in the "used" length.
734 */
736 /**
737 Used by some routines to keep a cursor into this->mem. Note that
738 a pointer-based cursor is not valid for some uses because mem can
739 be reallocated (and thus moved).
740 */
742
743 /**
744 When any buffer-related routines encounter an error, they set
745 this flag so that the error can be propagated. Many APIs also
746 become no-ops when this is set, the intention being to simplify
747 many common uses of this class, e.g.:
748
749 ```
750 fsl_buffer_append(b, ... );
751 fsl_buffer_append(b, ... );
752 fsl_buffer_append(b, ... );
753 if(fsl_buffer_err(b)) ...
754 ```
755
756 The alternative (without this member) being to check for an OOM
757 error after every append operation.
758 */
760};
761
762/** Empty-initialized fsl_buffer instance, intended for const-copy
763 initialization. */
764#define fsl_buffer_empty_m \
765 {.mem=NULL,.capacity=0U,.used=0U,.cursor=0U,.errCode=0}
766
767/** Empty-initialized fsl_buffer instance, intended for copy
768 initialization. */
770
771/**
772 A container for storing generic error state. It is used to
773 propagate error state between layers of the API back to the
774 client. i.e. they act as basic exception containers.
775
776 @see fsl_error_set()
777 @see fsl_error_get()
778 @see fsl_error_propagate()
779 @see fsl_error_clear()
780*/
781struct fsl_error {
782 /**
783 Error message text is stored in this->msg.mem. The usable text
784 part is this->msg.used bytes long.
785 */
787 /**
788 Error code, generally assumed to be a fsl_rc_e value. The
789 "non-error" code is 0.
790 */
791 int code;
792};
793
794/** Empty-initialized fsl_error instance, intended for const-copy
795 initialization. */
796#define fsl_error_empty_m {.msg = fsl_buffer_empty_m, .code = 0}
797
798/** Empty-initialized fsl_error instance, intended for copy
799 initialization. */
801
802/**
803 If err is not NULL, populates err with the given code and formatted
804 string, replacing any existing state. If fmt==NULL then
805 fsl_rc_cstr(rc) is used to get the error string.
806
807 If err is NULL this is a no-op and returns code.
808
809 Returns code on success, some other non-0 code on error.
810
811 As a special case, if 0==code then fmt is ignored and the error
812 state is cleared. This will not free any memory held by err but
813 will re-set its string to start with a NUL byte, ready for
814 re-use later on.
815
816 As a special case, if code==FSL_RC_OOM then fmt is ignored
817 to avoid a memory allocation (which would presumably fail).
818
819 @see fsl_error_get()
820 @see fsl_error_clear()
821 @see fsl_error_propagate()
822*/
823FSL_EXPORT int fsl_error_set( fsl_error * err, int code,
824 char const * fmt, ... );
825
826/**
827 va_list counterpart to fsl_error_set().
828*/
830 char const * fmt, va_list args );
831
832/**
833 Fetches the error state from err. Returns err's current error code.
834
835 If str is not NULL then *str will be assigned to the raw
836 (NUL-terminated) error string (which might be empty or even
837 NULL). The memory for the string is owned by err and may be
838 invalidated by any calls which take err as a non-const parameter OR
839 which might modify it indirectly through a container object, so the
840 client is required to copy it if it is needed for later
841 reference. As a special case, if the error object has no message
842 then the returned string is set to NULL, as opposed to an empty
843 string.
844
845 If len is not NULL then *len will be assigned to the length of
846 the (*str) string (in bytes).
847
848 @see fsl_error_set()
849 @see fsl_error_clear()
850 @see fsl_error_propagate()
851*/
853 char const ** str, fsl_size_t * len );
854
855/**
856 If err is not NULL, frees up any resources owned by err and sets
857 its error code to 0, but does not free err. This is harmless no-op
858 if err is NULL or holds no dynamically allocated no memory.
859
860 @see fsl_error_set()
861 @see fsl_error_get()
862 @see fsl_error_propagate()
863 @see fsl_error_reset()
864*/
866
867/**
868 Sets err->code to 0 and resets its buffer, but keeps any err->msg
869 memory around for later re-use. This is a no-op if err is NULL.
870
871 @see fsl_error_clear()
872*/
874
875/**
876 Copies the error state from src to dest. If dest contains state, it is
877 cleared/recycled by this operation.
878
879 Returns 0 on success, FSL_RC_MISUSE if either argument is NULL
880 or if (src==dest), and FSL_RC_OOM if allocation of the message
881 string fails.
882
883 As a special case, if src->code==FSL_RC_OOM, then the code is
884 copied but the message bytes (if any) are not (under the
885 assumption that we have no more memory).
886*/
888 fsl_error * dest );
889
890/**
891 Swaps the state between two fsl_error objects and then resets the
892 error state on the `from` object. Intended as an allocation
893 optimization when propagating error state up the API.
894
895 This is a no-op if from==to.
896
897 Because this modifies one argument differently from the other, it's
898 not exactly like a swap, but it has the effect of moving an error
899 from the `from` object to the `to` object, while keeping `to`'s
900 former memory intact for re-use (now inside the `from` object).
901
902 Results are undefined if either parameter is NULL or either is not
903 properly initialized. i.e. neither may refer to uninitialized
904 memory. Copying fsl_error_empty at declaration-time is a simple way
905 to ensure that instances are cleanly initialized.
906*/
908
909/** Old name for fsl_error_propagate() */
910#define fsl_error_move fsl_error_propagate
911///** Old, misleading name for fsl_error_propagate() */
912//#define fsl_error_swap fsl_error_propagate
913
914/**
915 Returns the given Unix Epoch timestamp value as its approximate
916 Julian Day value. Note that the calculation does not account for
917 leap seconds.
918*/
920
921/**
922 Returns the current Unix Epoch time converted to its approximate
923 Julian form. Equivalent to fsl_unix_to_julian(time(0)). See
924 fsl_unix_to_julian() for details. Note that the returned time
925 has seconds, not milliseconds, precision.
926*/
928
929#if 0
930/** UNTESTED, possibly broken vis-a-vis timezone conversion.
931
932 Returns the given Unix Epoch time value formatted as an ISO8601
933 string. Returns NULL on allocation error, else a string 19
934 bytes long plus a terminating NUL
935 (e.g. "2013-08-19T20:35:49"). The returned memory must
936 eventually be freed using fsl_free().
937*/
938FSL_EXPORT char * fsl_unix_to_iso8601( fsl_time_t j );
939#endif
940
941/**
942 Returns true if the first 10 digits of z _appear_ to form the start
943 of an ISO date string (YYYY-MM-DD). Whether or not the string is
944 really a valid date is left for downstream code to
945 determine. Returns false in all other cases, including if z is
946 NULL.
947*/
948FSL_EXPORT bool fsl_str_is_date(const char *z);
949
950
951/**
952 Checks if z is syntactically a time-format string in the format:
953
954 [Y]YYYY-MM-DD
955
956 (Yes, the year may be five-digits, left-padded with a zero for
957 years less than 9999.)
958
959 Returns a positive value if the YYYYY part has five digits, a
960 negative value if it has four. It returns 0 (false) if z does not
961 match that pattern.
962
963 If it returns a negative value, the MM part of z starts at byte offset
964 (z+5), and a positive value means the MM part starts at (z+6).
965
966 z need not be NUL terminated - this function does not read past
967 the first invalid byte. Thus is can be used on, e.g., full
968 ISO8601-format strings. If z is NULL, 0 is returned.
969*/
970FSL_EXPORT int fsl_str_is_date2(const char *z);
971
972
973/**
974 Returns the current error code of the given buffer. Many buffer
975 APIs become noops when this function returns non-0.
976*/
978
979/**
980 Resets the error code of the given buffer to 0.
981*/
983
984/**
985 Reserves at least n bytes of capacity in buf. Returns 0 on
986 success, FSL_RC_OOM if allocation fails. Results are undefined
987 if !buf.
988
989 If fsl_buffer_err() is true and n is not 0 then this function
990 returns its value without other side effects. If n is 0 then the
991 error state is cleared.
992
993 If b is an external buffer then:
994
995 - If n is 0, this disassociates b->mem from b, effectively clearing
996 the buffer's state. Else...
997
998 - The buffer is materialized, transformed into a managed buffer.
999 This happens even if n is less than b->used because this routine
1000 is always used in preparation for writing to the buffer.
1001
1002 - If n>0 then the greater of (n, b->used) bytes of memory are
1003 allocated, b->used bytes are copied from b->mem (its external
1004 memory) to the new block, and b->mem is replaced with the new
1005 block. Afterwards, b->capacity will be non-0.
1006
1007 This does not change b->used, nor will it shrink the buffer
1008 (reduce buf->capacity) unless n is 0, in which case it immediately:
1009
1010 - frees b->mem (if b is a managed buffer)
1011 - sets b->capacity, buf->used, and b->cursor to 0
1012 - sets b->errCode to 0
1013
1014 @see fsl_buffer_resize()
1015 @see fsl_buffer_materialize()
1016 @see fsl_buffer_clear()
1017*/
1019
1020/**
1021 If b is a "managed" buffer, this is a no-op and returns 0, else b
1022 is an "external" buffer and it...
1023
1024 - Allocates enough memory to store b->used bytes plus a NUL
1025 terminator.
1026
1027 - Copies b->mem to the new block.
1028
1029 - NUL-terminates the new block.
1030
1031 - Assigns b->mem to the new block.
1032
1033 b is thereby transformed to a managed buffer, i.e. b owns b->mem.
1034
1035 If fsl_buffer_err() is non-0 before this call, this call is a no-op
1036 and that value is returned.
1037
1038 Returns 0 on success, FSL_RC_OOM on allocation error.
1039
1040 Note that materialization happens automatically on demand by
1041 fsl_buffer APIs which write to the buffer but clients can use this
1042 to ensure that it is managed memory before they manipulate b->mem
1043 directly.
1044
1045 @see fsl_buffer_external()
1046*/
1048
1049/**
1050 Initializes b to be an "external" buffer pointing to n bytes of the
1051 given memory. If n is negative, the equivalent of fsl_strlen() is
1052 used to count its length. The buffer API treats external buffers as
1053 immutable. If asked to write to one, the API will first
1054 "materialize" the buffer, as documented for
1055 fsl_buffer_materialize().
1056
1057 Either mem must be guaranteed to outlive b or b must be
1058 materialized before mem goes out of scope.
1059
1060 ACHTUNG: it is NEVER legal to pass a pointer which may get
1061 reallocated, as doing so may change its address, invaliding the
1062 resulting `b->mem` pointer. Similarly, it is never legal to pass it
1063 scope-local memory unless b's lifetime is limited to that scope.
1064
1065 If b->mem is not NULL, this function first passes the buffer to
1066 fsl_buffer_clear() to ensure that this routine does not leak any
1067 dynamic memory it may already own.
1068
1069 Results are undefined if mem is NULL, but n may be 0.
1070
1071 Results are undefined if passed a completely uninitialized buffer
1072 object. _Always_ initialize new buffer objects by copying
1073 fsl_buffer_empty or (when appropriate) fsl_buffer_empty_m.
1074
1075 This function resets b->errCode.
1076
1077 @see fsl_buffer_materialize()
1078*/
1079FSL_EXPORT void fsl_buffer_external( fsl_buffer * b, void const * mem, fsl_int_t n );
1080
1081/**
1082 Convenience equivalent of fsl_buffer_reserve(b,0).
1083*/
1085
1086/**
1087 If b is a managed buffer, this resets b->used, b->cursor, and
1088 b->mem[0] (if b->mem is not NULL) to 0. If b is an external buffer,
1089 this clears all state from the buffer, behaving like
1090 fsl_buffer_clear() (making it available for reuse as a managed or
1091 external buffer).
1092
1093 This does not (de)allocate memory, only changes the logical "used"
1094 size of the buffer. Returns its argument.
1095
1096 This function resets b->errCode.
1097
1098 Returns b.
1099
1100 Achtung for fossil(1) porters: this function's semantics are much
1101 different from the fossil's blob_reset(). To get those semantics,
1102 use fsl_buffer_reserve(buf, 0) or its convenience form
1103 fsl_buffer_clear(). (This function _used_ to be called
1104 fsl_buffer_reset(), but it was renamed in the hope of avoiding
1105 related confusion.)
1106*/
1108
1109/**
1110 Similar to fsl_buffer_reserve() except that...
1111
1112 - If fsl_buffer_err() is true, that result is returned with no other
1113 side effects.
1114
1115 For managed buffers:
1116
1117 - It does not free all memory when n==0. Instead it essentially
1118 makes the memory a length-0, NUL-terminated string.
1119
1120 - It will try to shrink (realloc) buf's memory if (n<buf->capacity).
1121
1122 - It sets buf->capacity to (n+1) and buf->used to n. This routine
1123 allocates one extra byte to ensure that buf is always
1124 NUL-terminated.
1125
1126 - On success it always NUL-terminates the buffer at
1127 offset buf->used.
1128
1129 For external buffers it behaves slightly differently:
1130
1131 - If n==buf->used, this is a no-op and returns 0.
1132
1133 - If n==0 then it behaves like fsl_buffer_external(buf,"",0)
1134 and returns 0.
1135
1136 - Else it materializes the buffer, as per fsl_buffer_materialize(),
1137 copies the lesser of (n, buf->used) bytes from buf->mem to that
1138 memory, NUL-terminates the new block, replaces buf->mem with the
1139 new block, sets buf->used to n and buf->capacity to n+1.
1140
1141 Returns 0 on success or FSL_RC_OOM if a (re)allocation fails. On
1142 allocation error, the buffer's memory state is unchanged.
1143
1144 @see fsl_buffer_reserve()
1145 @see fsl_buffer_materialize()
1146 @see fsl_buffer_clear()
1147*/
1149
1150/**
1151 Swaps the entire state of the left and right arguments. Results are
1152 undefined if either argument is NULL or points to uninitialized
1153 memory.
1154*/
1156
1157/**
1158 Similar fsl_buffer_swap() but it also optionally frees one of
1159 the buffer's memories after swapping them. If clearWhich is
1160 negative then the left buffer (1st arg) is cleared _after_
1161 swapping (i.e., the NEW left hand side gets cleared). If
1162 clearWhich is greater than 0 then the right buffer (2nd arg) is
1163 cleared _after_ swapping (i.e. the NEW right hand side gets
1164 cleared). If clearWhich is 0, this function behaves identically
1165 to fsl_buffer_swap().
1166
1167 A couple examples should clear this up:
1168
1169 ```
1170 fsl_buffer_swap_free( &b1, &b2, -1 );
1171 ```
1172
1173 Swaps the contents of b1 and b2, then frees the contents
1174 of the left-side buffer (b1).
1175
1176 ```
1177 fsl_buffer_swap_free( &b1, &b2, 1 );
1178 ```
1179
1180 Swaps the contents of b1 and b2, then frees the contents
1181 of the right-side buffer (b2).
1182*/
1184 fsl_buffer * right,
1185 int clearWhich );
1186
1187/**
1188 Appends the first n bytes of src, plus a NUL byte, to b,
1189 expanding b as necessary and incrementing b->used by n. If n is
1190 less than 0 then the equivalent of fsl_strlen((char const*)src)
1191 is used to calculate the length.
1192
1193 If fsl_buffer_err() is true, its result is returned without further
1194 side effects.
1195
1196 If b is an external buffer, it is first transformed into a
1197 managed buffer.
1198
1199 Results are undefined if b or src are NULL.
1200
1201 If n is 0 (or negative and !*src), this function ensures that
1202 b->mem is not NULL and is NUL-terminated, so it may allocate
1203 to have space for that NUL byte.
1204
1205 Returns 0 on success, FSL_RC_OOM if allocation of memory fails.
1206
1207 If this function succeeds, it guarantees that it NUL-terminates the
1208 buffer (but that the NUL terminator is not counted in b->used).
1209
1210 This function does not modify b's cursor.
1211
1212 @see fsl_buffer_appendf()
1213 @see fsl_buffer_reserve()
1214*/
1216 void const * src, fsl_int_t n );
1217
1218/**
1219 Uses fsl_appendf() to append formatted output to the given buffer.
1220 Returns 0 on success and FSL_RC_OOM if an allocation fails while
1221 expanding dest. Results are undefined if either of the first two
1222 arguments are NULL.
1223
1224 If fsl_buffer_err() is true, its result is returned without further
1225 side effects.
1226
1227 @see fsl_buffer_append()
1228 @see fsl_buffer_reserve()
1229*/
1231 char const * fmt, ... );
1232
1233/** va_list counterpart to fsl_buffer_appendf(). */
1235 char const * fmt, va_list args );
1236
1237/**
1238 Appends the given byte to b. This is slightly more efficient than
1239 fsl_buffer_append() for the common case where b has slack memory to
1240 fill.
1241
1242 If b->errCode is non-0, this is a no-op and returns that code.
1243
1244 On success this routine always NUL-terminates b. On error,
1245 b->errCode is returned.
1246*/
1248
1249/**
1250 Add an EOL to b if it has content (i.e. b->used is not 0) but does
1251 not end on one, else do nothing. It does not modify empty buffers.
1252 b is materialized if needed.
1253
1254 Returns b->errCode and is a no-op if b->errCode is non-0 when this
1255 is called.
1256*/
1258
1259/**
1260 If b ends with a `\n` character or a pair of `\r\n`, the `\n` or
1261 `\r\n` pair are "chomped" (to use Perl's term for it), reducing
1262 b->used by 1 or 2, else this function has no side-effects.
1263
1264 For external buffers, the b->used is adjusted but the memory is
1265 otherwise not modified (as external buffers are never guaranteed to
1266 be NUL-terminated). For non-external buffers b is NUL-terminated at
1267 its new length. If you really need to chomp an external buffer,
1268 pass it to fsl_buffer_materialize() first.
1269
1270 This is a no-op if b->errCode is non-0. (We don't strictly need to
1271 do so, but we do for consistency - b's state should not change when
1272 errCode is non-0.)
1273*/
1275
1276/**
1277 Expects z to be a single argument intended for future call to
1278 system()-like function. It is quoted/escaped appropriately and
1279 appended to b, adding a space between any previous contents of
1280 b. It will fail, returning FSL_RC_SYNTAX, if the input contains
1281 what it believes to be malicious characters or if z contains any
1282 non-UTF-8 characters. It does not permit control characters of any
1283 kind, for example.
1284
1285 If isFilename is true and z starts with a '-' character then the
1286 result gets prefixed with `./` (or `.\` on Windows) to (A)
1287 differentiate it from a flag argument and (B) avoid passing an
1288 unintended, but valid, flag to a command. isFilename has no further
1289 effect.
1290
1291 The intent is that this function be called once per argument for a
1292 pending system()-style call, and b's contents eventually be used as
1293 the argument for that system()-style call.
1294
1295 If b->errCode is non-0 when this is called, this function is a no-op
1296 and that value is returned.
1297
1298 If err is not NULL then any validation-time error state are set in
1299 err and err->code is returned, It may fail for a number of reasons,
1300 as it performs checks on the input to avoid certain types of
1301 malicious uses. If initial validation of b->errCode and
1302 materialization of b (if needed) both pass, err is passed to
1303 fsl_error_reset() before this function starts its work.
1304
1305 If err is NULL then this function still returns non-0 on error but
1306 the caller will not know exactl which validation failed.
1307
1308 If this function returns FSL_RC_SYNTAX and err is not NULL, err
1309 will contain more info about the problem. If it returns any other
1310 error code, it's an allocation error and err will not have been
1311 updated.
1312
1313 On error it always updates b->errCode so that subsequent calls
1314 will not mask the error.
1315*/
1317 fsl_error * err,
1318 char const *z,
1319 bool isFilename);
1320/**
1321 Equivalent to fsl_buffer_esc_arg_v2() with NULL as its second
1322 argument.
1323*/
1324
1326 char const *z,
1327 bool isFilename);
1328
1329/**
1330 Hex-encodes n bytes of src into n*2 hex-digit bytes appended to
1331 b. On error, b->errCode will be set to non-0 and that value is
1332 returned. If the final argument is true, upper-case hex digits are
1333 used, else lower-case are used.
1334
1335 If fsl_buffer_err() is non-0 when this is called, this function has
1336 no side effects and that value is returned.
1337*/
1339 void const * src, fsl_uint_t n,
1340 bool upperCase);
1341
1342
1343/**
1344 Compresses the first pIn->used bytes of pIn to pOut. It is ok for
1345 pIn and pOut to be the same blob.
1346
1347 If fsl_buffer_err() is true for either buffer, its result is
1348 returned without further side effects. The buffers are checked in
1349 the order of their parameter declaration.
1350
1351 pOut must either be the same as pIn or else a properly
1352 initialized buffer. Any prior contents will be freed or their
1353 memory reused.
1354
1355 Results are undefined if any argument is NULL.
1356
1357 Returns 0 on success, FSL_RC_OOM on allocation error, and
1358 FSL_RC_ERROR if the lower-level compression routines fail. If this
1359 function returns non-0, it does not update pOut's error state
1360 because the error will have happened on a temporary buffer.
1361
1362 Use fsl_buffer_uncompress() to uncompress the data. The data is
1363 encoded with a big-endian, unsigned 32-bit length as the first four
1364 bytes (holding its uncomressed size), and then the data as
1365 compressed by zlib.
1366
1367 TODO: if pOut!=pIn1 then re-use pOut's memory, if it has any.
1368
1369 @see fsl_buffer_compress2()
1370 @see fsl_buffer_uncompress()
1371 @see fsl_buffer_is_compressed()
1372*/
1374
1375/**
1376 Compress the concatenation of a blobs pIn1 and pIn2 into pOut.
1377
1378 pOut must be either empty (cleanly initialized or newly
1379 recycled) or must be the same as either pIn1 or pIn2.
1380
1381 Results are undefined if any argument is NULL.
1382
1383 If fsl_buffer_err() is true for any buffer, its result is
1384 returned without further side effects. The buffers are checked in
1385 the order of their parameter declaration.
1386
1387 Returns 0 on success, FSL_RC_OOM on allocation error, and FSL_RC_ERROR
1388 if the lower-level compression routines fail.
1389
1390 TODO: if pOut!=(pIn1 or pIn2) then re-use its memory, if it has any.
1391
1392 @see fsl_buffer_compress()
1393 @see fsl_buffer_uncompress()
1394 @see fsl_buffer_is_compressed()
1395*/
1397 fsl_buffer const *pIn2,
1398 fsl_buffer * pOut);
1399
1400/**
1401 Uncompress buffer pIn and store the result in pOut. It is ok for
1402 pIn and pOut to be the same buffer. Returns 0 on success. If
1403 pIn!=pOut then on error, depending on the type of error, pOut may
1404 have been partially written so the state of its contents are
1405 unspecified (but its state as a buffer object is still valid).
1406
1407 If fsl_buffer_err() is true for either buffer, its result is
1408 returned without further side effects. The buffers are checked in
1409 the order of their parameter declaration.
1410
1411 pOut must be either cleanly initialized/empty or the same object as
1412 pIn. If it has any current memory, it will be reused if it's
1413 large enough and it is not the same pointer as pIn.
1414
1415 Results are undefined if any argument is NULL.
1416
1417 Returns 0 on success, FSL_RC_OOM on allocation error, and some
1418 other code if the lower-level decompression routines fail. On
1419 error, pOut->errCode is updated.
1420
1421 Note that the decompression process, though computationally costly,
1422 is a no-op if pIn is not actually compressed.
1423
1424 As a special case, if pIn==pOut and fsl_buffer_is_compressed() returns
1425 false for pIn then this is a no-op.
1426
1427 @see fsl_buffer_compress()
1428 @see fsl_buffer_compress2()
1429 @see fsl_buffer_is_compressed()
1430*/
1432 fsl_buffer * pOut);
1433
1434/**
1435 Returns true if this function believes that mem (which must be
1436 at least len bytes of valid memory long) appears to have been
1437 compressed by fsl_buffer_compress() or equivalent. This is not a
1438 100% reliable check - it could potentially have false positives
1439 on certain inputs, but that is thought to be unlikely (at least
1440 for text data).
1441
1442 Returns 0 if mem is NULL.
1443*/
1444FSL_EXPORT bool fsl_data_is_compressed(unsigned char const * mem, fsl_size_t len);
1445
1446/**
1447 Equivalent to fsl_data_is_compressed(buf->mem, buf->used).
1448*/
1450
1451/**
1452 If fsl_data_is_compressed(mem,len) returns true then this function
1453 returns the uncompressed size of the data, else it returns a negative
1454 value.
1455*/
1457
1458/**
1459 The fsl_buffer counterpart of fsl_data_uncompressed_size().
1460*/
1462
1463/**
1464 Equivalent to ((char const *)b->mem) except that if b->errCode is
1465 non-0, this returns NULL. The returned string is effectively
1466 b->used bytes long unless the user decides to apply his own
1467 conventions. Note that the buffer APIs generally assure that
1468 buffers are NUL-terminated, meaning that strings returned from this
1469 function can (for the vast majority of cases) assume that the
1470 returned string is NUL-terminated (with a string length of b->used
1471 _bytes_). It is, however, possible for client code to violate that
1472 convention via direct manipulation of the buffer or using
1473 non-NUL-terminated extranal buffers.
1474
1475 Results are undefined if b is NULL.
1476
1477 @see fsl_buffer_str()
1478 @see fsl_buffer_cstr2()
1479*/
1480FSL_EXPORT char const * fsl_buffer_cstr(fsl_buffer const * b);
1481
1482/**
1483 If b has any memory allocated to it and b->errCode is non-0, that
1484 memory is returned. If len is not NULL then *len is set to
1485 b->used. If b has no memory or b->errCode is non-0 then NULL is
1486 returned and *len (if len is not NULL) is set to 0.
1487
1488 Results are undefined if b is NULL.
1489
1490 @see fsl_buffer_str()
1491 @see fsl_buffer_cstr()
1492*/
1493FSL_EXPORT char const * fsl_buffer_cstr2(fsl_buffer const * b, fsl_size_t * len);
1494
1495/**
1496 Equivalent to ((char *)b->mem) except that if b->errCode is non-0
1497 then NULL is returned. The returned memory is effectively b->used
1498 bytes long unless the user decides to apply their own conventions.
1499
1500 Care must be taken to only write to the returned pointer for memory
1501 owned or write-proxied by this buffer. More specifically, results
1502 are undefined if b is an external buffer proxying const bytes. When
1503 in doubt about whether b is external, use fsl_buffer_materialize()
1504 to transform it to a managed buffer before using this routine,
1505 noting that any of the public fsl_buffer APIs which write to a
1506 buffer will materialize it on demand if needed.
1507
1508 @see fsl_buffer_take()
1509*/
1511
1512/**
1513 "Takes" the memory refered to by the given buffer, transfering
1514 ownership to the caller. After calling this, b's state will be
1515 empty. If b is an external buffer, this will materialize it
1516 first and return NULL if that fails.
1517
1518 @see fsl_buffer_materialize()
1519 @see fsl_buffer_str()
1520 @see fsl_buffer_cstr()
1521 @see fsl_buffer_cstr2()
1522*/
1524
1525/**
1526 Returns the "used" size of b, or 0 if !b.
1527*/
1528#define fsl_buffer_size(b) (b)->used
1529#if 0
1531#endif
1532
1533/**
1534 Returns the current capacity of b, or 0 if !b.
1535*/
1536#define fsl_buffer_capacity(b) (b)->capacity
1537#if 0
1539#endif
1540/**
1541 Compares the contents of buffers lhs and rhs using memcmp(3)
1542 semantics. Returns negative, zero, or positive if the first buffer
1543 is less then, equal to, or greater than the second. Results are
1544 undefined if either argument is NULL.
1545
1546 When buffers of different length match on the first N bytes,
1547 where N is the shorter of the two buffers' lengths, it treats the
1548 shorter buffer as being "less than" the longer one.
1549*/
1551 fsl_buffer const * rhs);
1552
1553/**
1554 Compares b and the first nStr bytes of the given string. If nStr is
1555 negative, fsl_strlen() is used to calculate it. Returns true if the
1556 buffer and the string match, as per the rules of
1557 fsl_buffer_compare(), else returns false.
1558*/
1559FSL_EXPORT bool fsl_buffer_eq(fsl_buffer const * b, char const * str,
1560 fsl_int_t nStr);
1561
1562/**
1563 Bitwise-compares the contents of b against the file named by
1564 zFile. Returns 0 if they have the same size and contents, else
1565 non-zero. This function has no way to report if zFile cannot be
1566 opened, and any error results in a non-0 return value. No
1567 interpretation/canonicalization of zFile is performed - it is
1568 used as-is.
1569
1570 This resolves symlinks and returns non-0 if zFile refers (after
1571 symlink resolution) to a non-file.
1572
1573 If zFile does not exist, is not readable, or has a different
1574 size than b->used, non-0 is returned without opening/reading the
1575 file contents. If a content comparison is performed, it is
1576 streamed in chunks of an unspecified (but relatively small)
1577 size, so it does not need to read the whole file into memory
1578 (unless it is smaller than the chunk size).
1579*/
1580FSL_EXPORT int fsl_buffer_compare_file( fsl_buffer const * b, char const * zFile );
1581
1582/**
1583 Compare two buffers in constant (a.k.a. O(1)) time and return
1584 zero if they are equal. Constant time comparison only applies
1585 for buffers of the same length. If lengths are different,
1586 immediately returns 1. This operation is provided for cases
1587 where the timing/duration of fsl_buffer_compare() (or an
1588 equivalent memcmp()) might inadvertently leak security-relevant
1589 information. Specifically, it address the concern that
1590 attackers can use timing differences to check for password
1591 misses, to narrow down an attack to passwords of a specific
1592 length or content properties.
1593*/
1595
1596/**
1597 Overwrites dest's contents with a copy of those from src
1598 (reusing dest's memory if it has any). Results are undefined if
1599 either pointer is NULL or invalid. Returns 0 on success,
1600 FSL_RC_OOM on allocation error.
1601*/
1603 fsl_buffer const * src );
1604
1605/**
1606 Apply the delta in pDelta to the original content pOriginal to
1607 generate the target content pTarget. All three pointers must point
1608 to properly initialized memory.
1609
1610 If pTarget==pOriginal then this is a destructive operation,
1611 replacing the original's content with its new form.
1612
1613 If fsl_buffer_err() is true for any buffer, its result is
1614 returned without further side effects. The buffers are checked in
1615 the order of their parameter declaration.
1616
1617 Return 0 on success.
1618
1619 @see fsl_buffer_delta_apply()
1620 @see fsl_delta_apply()
1621 @see fsl_delta_apply2()
1622*/
1624 fsl_buffer const * pDelta,
1625 fsl_buffer * pTarget);
1626
1627/**
1628 Identical to fsl_buffer_delta_apply() except that if delta
1629 application fails then any error messages/codes are written to
1630 pErr if it is not NULL. It is rare that delta application fails
1631 (only if the inputs are invalid, e.g. do not belong together or
1632 are corrupt), but when it does, having error information can be
1633 useful.
1634
1635 If fsl_buffer_err() is true for any buffer, its result is
1636 returned without further side effects. The buffers are checked in
1637 the order of their parameter declaration.
1638
1639 @see fsl_buffer_delta_apply()
1640 @see fsl_delta_apply()
1641 @see fsl_delta_apply2()
1642*/
1644 fsl_buffer const * pDelta,
1645 fsl_buffer * pTarget,
1646 fsl_error * pErr);
1647
1648
1649/**
1650 Uses a fsl_input_f() function to buffer input into a fsl_buffer.
1651
1652 dest must be a non-NULL, initialized (though possibly empty)
1653 fsl_buffer object. Its contents, if any, will be overwritten by
1654 this function, and any memory it holds might be re-used.
1655
1656 If fsl_buffer_err() is true then this function returns its value
1657 without other side effects.
1658
1659 The src function is called, and passed the state parameter, to
1660 fetch the input. If it returns non-0, this function returns that
1661 error code. src() is called, possibly repeatedly, until it
1662 reports that there is no more data.
1663
1664 Whether or not this function succeeds, dest still owns any memory
1665 pointed to by dest->mem, and the client must eventually free it
1666 by calling fsl_buffer_reserve(dest,0).
1667
1668 dest->mem might (and possibly will) be (re)allocated by this
1669 function, so any pointers to it held from before this call might
1670 be invalidated by this call.
1671
1672 On error non-0 is returned and dest may be partially populated.
1673
1674 Errors include:
1675
1676 - Allocation error (FSL_RC_OOM), in which case dest->errCode is
1677 updated.
1678
1679 - src() returns an error code, in which case dest->errCode is _not_
1680 modified.
1681
1682 Whether or not the state parameter may be NULL depends on the src
1683 implementation requirements.
1684
1685 On success dest will contain the contents read from the input
1686 source. dest->used will be the length of the read-in data, and
1687 dest->mem will point to the memory. dest->mem is automatically
1688 NUL-terminated if this function succeeds, but dest->used does not
1689 count that terminator. On error the state of dest->mem must be
1690 considered incomplete, and is not guaranteed to be NUL-terminated.
1691
1692 Example usage:
1693
1694 ```
1695 fsl_buffer buf = fsl_buffer_empty;
1696 int rc = fsl_buffer_fill_from( &buf,
1697 fsl_input_f_FILE,
1698 stdin );
1699 if( rc ){
1700 fprintf(stderr,"Error %d (%s) while filling buffer.\n",
1701 rc, fsl_rc_cstr(rc));
1702 fsl_buffer_reserve( &buf, 0 );
1703 return ...;
1704 }
1705 ... use the buf->mem ...
1706 ... clean up the buffer ...
1707 fsl_buffer_reserve( &buf, 0 );
1708 ```
1709
1710 To take over ownership of the buffer's memory, do:
1711
1712 ```
1713 void * mem = buf.mem;
1714 buf = fsl_buffer_empty;
1715 ```
1716
1717 In which case the memory must eventually be passed to fsl_free()
1718 to free it.
1719*/
1721 fsl_input_f src, void * state );
1722
1723/**
1724 A fsl_buffer_fill_from() proxy which overwrite's dest->mem with
1725 the contents of the given FILE handler (which must be opened for
1726 read access). Returns 0 on success, after which dest->mem
1727 contains dest->used bytes of content from the input source. On
1728 error dest may be partially filled.
1729*/
1731 FILE * src );
1732
1733/**
1734 A wrapper for fsl_buffer_fill_from_FILE() which gets its input
1735 from the given file name.
1736
1737 If fsl_buffer_err() is true then this function returns its value
1738 without other side effects.
1739
1740 It uses fsl_fopen() to open the file, so it supports the name '-'
1741 as an alias for stdin.
1742*/
1744 char const * filename );
1745
1746/**
1747 Writes the given buffer to the given filename. Returns 0 on success,
1748 FSL_RC_MISUSE if !b or !fname, FSL_RC_IO if opening or writing fails.
1749
1750 If fsl_buffer_err() is true, that result is returned with no other
1751 side effects.
1752
1753 Uses fsl_fopen() to open the file, so it supports the name '-'
1754 as an alias for stdout.
1755*/
1757 char const * fname );
1758
1759/**
1760 Copy N lines of text from pFrom into pTo. The copy begins at the
1761 current pFrom->cursor position. On success, pFrom->cursor is left
1762 pointing at the first character past the last `\n` copied.
1763 (Modification of the cursor is why pFrom is not const.) The copy is
1764 made in a single go, not line-by-line.
1765
1766 If fsl_buffer_err() is true for either buffer (checked in parameter
1767 order), that result is returned with no other side effects.
1768
1769 If pTo==NULL then this routine simply skips over N lines.
1770
1771 Returns 0 if it copies lines or does nothing (because N is 0 or
1772 pFrom's contents have been exhausted). Copying fewer lines than
1773 requested (because of EOF) is not an error. Returns non-0 only on
1774 allocation error. Results are undefined if pFrom is NULL or not
1775 properly initialized. Whether or not it copies anything can be
1776 checked by copying pTo->used before calling this and comparing
1777 pTo->used to that value afterwards. The difference is the number of
1778 bytes added.
1779
1780 @see fsl_buffer_stream_lines()
1781*/
1783 fsl_buffer * pFrom,
1784 fsl_size_t N);
1785
1786/**
1787 Works identically to fsl_buffer_copy_lines() except that it sends
1788 its output to the fTo output function. If fTo is NULL then it
1789 simply skips over N lines. The callback is called a single time,
1790 not once per line.
1791
1792 If fsl_buffer_err() is true, that result is returned with no other
1793 side effects.
1794
1795 @see fsl_buffer_copy_lines()
1796*/
1798 fsl_buffer * pFrom,
1799 fsl_size_t N);
1800
1801
1802/**
1803 Works like fsl_appendfv(), but appends all output to a
1804 dynamically-allocated string, expanding the string as necessary
1805 to collect all formatted data. The returned NUL-terminated string
1806 is owned by the caller and it must be cleaned up using
1807 fsl_free(...). If !fmt, NULL is returned. It is conceivable that
1808 it returns NULL on a zero-length formatted string, e.g. (%.*s)
1809 with (0,"...") as arguments, but it will only do that if the
1810 whole format string resolves to empty.
1811*/
1812FSL_EXPORT char * fsl_mprintf( char const * fmt, ... );
1813
1814/**
1815 va_list counterpart to fsl_mprintf().
1816*/
1817FSL_EXPORT char * fsl_mprintfv(char const * fmt, va_list vargs );
1818
1819/**
1820 An sprintf(3) clone which uses fsl_appendf() for the formatting.
1821 Outputs at most n bytes to dest. Returns 0 on success, non-0
1822 on error. Returns 0 without side-effects if !n or !*fmt.
1823
1824 If the destination buffer is long enough, this function
1825 NUL-terminates it.
1826*/
1827FSL_EXPORT int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... );
1828
1829/**
1830 va_list counterpart to fsl_snprintf()
1831*/
1832FSL_EXPORT int fsl_snprintfv( char * dest, fsl_size_t n, char const * fmt, va_list args );
1833
1834/**
1835 Equivalent to fsl_strndup(src,-1).
1836*/
1837FSL_EXPORT char * fsl_strdup( char const * src );
1838
1839/**
1840 Similar to strndup(3) but returns NULL if !src. The returned
1841 memory must eventually be passed to fsl_free(). Returns NULL on
1842 allocation error. If len is less than 0 and src is not NULL then
1843 fsl_strlen() is used to calculate its length.
1844
1845 If src is not NULL but len is 0 then it will return an empty
1846 (length-0) string, as opposed to NULL.
1847*/
1848FSL_EXPORT char * fsl_strndup( char const * src, fsl_int_t len );
1849
1850/**
1851 Equivalent to strlen(3) but returns 0 if src is NULL.
1852 Note that it counts bytes, not UTF characters.
1853*/
1855
1856/**
1857 Returns the number of UTF8 characters which begin within the first
1858 n bytes of str (noting that it's possible that a multi-byte
1859 character starts 1-3 bytes away from the end and overlaps past the
1860 end of (str+len)). If len is negative then fsl_strlen() is used to
1861 calculate it.
1862
1863 Results are undefined if str is not UTF8 input or if str contains a
1864 BOM marker.
1865*/
1867
1868/**
1869 Like strcmp(3) except that it accepts NULL pointers. NULL sorts
1870 before all non-NULL string pointers. Also, this routine
1871 performs a binary comparison that does not consider locale.
1872*/
1873FSL_EXPORT int fsl_strcmp( char const * lhs, char const * rhs );
1874
1875/**
1876 Equivalent to fsl_strcmp(), but with a signature suitable
1877 for use as a generic comparison function (e.g. for use with
1878 qsort() and search algorithms).
1879*/
1880FSL_EXPORT int fsl_strcmp_cmp( void const * lhs, void const * rhs );
1881
1882/**
1883 Case-insensitive form of fsl_strcmp().
1884
1885 @implements fsl_generic_cmp_f()
1886*/
1887FSL_EXPORT int fsl_stricmp(const char *zA, const char *zB);
1888
1889/**
1890 Equivalent to fsl_stricmp(), but with a signature suitable
1891 for use as a generic comparison function (e.g. for use with
1892 qsort() and search algorithms).
1893
1894 @implements fsl_generic_cmp_f()
1895*/
1896FSL_EXPORT int fsl_stricmp_cmp( void const * lhs, void const * rhs );
1897
1898/**
1899 fsl_strcmp() variant which compares at most nByte bytes of the
1900 given strings, case-insensitively. If nByte is less than 0 then
1901 fsl_strlen(zB) is used to obtain the length for comparision
1902 purposes.
1903*/
1904FSL_EXPORT int fsl_strnicmp(const char *zA, const char *zB, fsl_int_t nByte);
1905
1906/**
1907 fsl_strcmp() variant which compares at most nByte bytes of the
1908 given strings, case-sensitively. Returns 0 if nByte is 0.
1909*/
1910FSL_EXPORT int fsl_strncmp(const char *zA, const char *zB, fsl_size_t nByte);
1911
1912/**
1913 BSD strlcpy() variant which is less error prone than strncpy. Copy up to
1914 dstsz - 1 characters from src to dst and NUL-terminate the resulting string
1915 if dstsz is not 0.
1916
1917 Returns the length of the string it writes to dst. If it returns a value
1918 equal to or greater than its 3rd argument then the output was truncated.
1919*/
1920FSL_EXPORT fsl_size_t fsl_strlcpy(char *dst, const char *src, fsl_size_t dstsz);
1921
1922/**
1923 BSD strlcat() variant which is less error prone than strncat. Append src to
1924 the end of dst. Append at most dstsz - strlen(dst - 1) characters, and
1925 NUL-terminate unless dstsize is 0 or the passed in dst string was longer
1926 than dstsz to begin with.
1927
1928 Returns the initial string-length of dest plus the length src. If
1929 it returns a value equal to or greater than its 3rd argument then
1930 the output was truncated.
1931*/
1932FSL_EXPORT fsl_size_t fsl_strlcat(char *dst, const char *src, fsl_size_t dstsz);
1933
1934/**
1935 Equivalent to fsl_strncmp(lhs, rhs, X), where X is either
1936 FSL_STRLEN_SHA1 or FSL_STRLEN_K256: if both lhs and rhs are
1937 longer than FSL_STRLEN_SHA1 then they are assumed to be
1938 FSL_STRLEN_K256 bytes long and are compared as such, else they
1939 are assumed to be FSL_STRLEN_SHA1 bytes long and compared as
1940 such.
1941
1942 Potential FIXME/TODO: if their lengths differ, i.e. one is v1 and
1943 one is v2, compare them up to their common length then, if they
1944 still compare equivalent, treat the shorter one as less-than the
1945 longer.
1946*/
1948
1949/**
1950 Returns false if s is NULL or starts with any of (0 (NUL), '0'
1951 (ASCII character zero), 'f', 'n', "off"), case-insensitively,
1952 else it returns true.
1953*/
1954FSL_EXPORT bool fsl_str_bool( char const * s );
1955
1956/**
1957 _Almost_ equivalent to fopen(3) but:
1958
1959 - expects name to be UTF8-encoded.
1960
1961 - If name=="-", it returns one of stdin or stdout, depending on
1962 the mode string: stdout is returned if 'w' or '+' appear,
1963 otherwise stdin.
1964
1965 If it returns NULL, the global errno "should" contain a description
1966 of the problem unless the problem was argument validation. Pass it
1967 to fsl_errno_to_rc() to convert that into an API-conventional error
1968 code.
1969
1970 If at all possible, use fsl_fclose() (as opposed to fclose()) to
1971 close these handles, as it has logic to skip closing the
1972 standard streams.
1973
1974 Potential TODOs:
1975
1976 - extend mode string to support 'x', meaning "exclusive", analog
1977 to open(2)'s O_EXCL flag. Barring race conditions, we have
1978 enough infrastructure to implement that. (It turns out that
1979 glibc's fopen() supports an 'x' with exactly this meaning.)
1980
1981 - extend mode to support a 't', meaning "temporary". The idea
1982 would be that we delete the file from the FS right after
1983 opening, except that Windows can't do that.
1984*/
1985FSL_EXPORT FILE * fsl_fopen(char const * name, char const *mode);
1986
1987/**
1988 Passes f to fclose(3) unless f is NULL or one of the C-standard
1989 (stdin, stdout, stderr) handles, in which cases it does nothing
1990 at all.
1991*/
1992FSL_EXPORT void fsl_fclose(FILE * f);
1993
1994/**
1995 This function works similarly to classical printf
1996 implementations, but instead of outputing somewhere specific, it
1997 uses a callback function to push its output somewhere. This
1998 allows it to be used for arbitrary external representations. It
1999 can be used, for example, to output to an external string, a UI
2000 widget, or file handle (it can also emulate printf by outputing
2001 to stdout this way).
2002
2003 INPUTS:
2004
2005 pfAppend: The is a fsl_output_f function which is responsible
2006 for accumulating the output. If pfAppend returns a negative
2007 value then processing stops immediately.
2008
2009 pfAppendArg: is ignored by this function but passed as the first
2010 argument to pfAppend. pfAppend will presumably use it as a data
2011 store for accumulating its string.
2012
2013 fmt: This is the format string, as in the usual printf(3), except
2014 that it supports more options (detailed below).
2015
2016 ap: This is a pointer to a list of arguments. Same as in
2017 vprintf() and friends.
2018
2019
2020 OUTPUTS:
2021
2022 ACHTUNG: this interface changed significantly in 2021-09:
2023
2024 - The output function was changed from a type specific to this
2025 interface to fsl_output_f().
2026
2027 - The return semantics where changed from printf()-like to
2028 0 on success, non-0 on error.
2029
2030 Most printf-style specifiers work as they do in standard printf()
2031 implementations. There might be some very minor differences, but
2032 the more common format specifiers work as most developers expect
2033 them to. In addition...
2034
2035 Current (documented) printf extensions:
2036
2037 `%s` works like conventional printf `%s` except that any precision
2038 value can be modified via the '#' flag to count in UTF8 characters
2039 instead of bytes. That is, if an `%#.10s` argument has a byte
2040 length of 20, a precision of 10, and contains only 8 UTF8, its
2041 precision will allow it to output all 8 characters, even though
2042 they total 20 bytes. The '#' flag works this way for both width and
2043 precision.
2044
2045 `%z` works exactly like `%s`, but takes a non-const (char *) and
2046 deletes the string (using fsl_free()) after appending it to the
2047 output.
2048
2049 `%h` (HTML) works like `%s` but (A) does not support the '#' flag and
2050 (B) converts certain characters (namely '<' and '&') to their HTML
2051 escaped equivalents.
2052
2053 `%t` (URL encode) works like `%h` but converts certain characters
2054 into a representation suitable for use in an HTTP URL. (e.g. ' '
2055 gets converted to `%20`)
2056
2057 `%T` (URL decode) does the opposite of `%t` - it decodes
2058 URL-encoded strings and outputs their decoded form. ACHTUNG:
2059 fossil(1) interprets this the same as `%t` except that it leaves
2060 '/' characters unescaped (did that change at some point? This code
2061 originally derived from that one some years ago!). It is still to
2062 be determined whether we "really need" that behaviour (we don't
2063 really need either one, seeing as the library is not CGI-centric
2064 like fossil(1) is).
2065
2066 `%r` requires an int and renders it in "ordinal form". That is,
2067 the number 1 converts to "1st" and 398 converts to "398th".
2068
2069 `%q` quotes a string as required for SQL. That is, '\''
2070 characters get doubled. It does NOT included the outer quotes
2071 and NULL values get replaced by the string "(NULL)" (without
2072 quotes). See `%Q`...
2073
2074 `%Q` works like `%q`, but includes the outer '\'' characters and
2075 NULL pointers get output as the string literal "NULL" (without
2076 quotes), i.e. an SQL NULL. If modified with `%!Q` then it instead
2077 uses double quotes, the intent being for use with identifiers.
2078 In that form it still emits `NULL` without quotes, but it is not
2079 intended to be used with `NULL` values.
2080
2081 `%S` works like `%.16s`. It is intended for fossil hashes. The '!'
2082 modifier removes the length limit, resulting in the whole hash
2083 (making this formatting option equivalent to `%s`). (Sidebar: in
2084 fossil(1) this length is runtime configurable but that requires
2085 storing that option in global state, which is not an option for
2086 this implementation.)
2087
2088 `%/`: works mostly like `%s` but normalizes path-like strings by
2089 replacing backslashes with the One True Slash.
2090
2091 `%b`: works like `%s` but takes its input from a (fsl_buffer
2092 const*) argument. It does not support the '#' flag.
2093
2094 `%B`: works like `%Q` but takes its input from a (fsl_buffer
2095 const*) argument.
2096
2097 `%F`: works like `%s` but runs the output through
2098 fsl_bytes_fossilize(). This requires dynamic memory allocation, so
2099 is less efficient than re-using a client-provided buffer with
2100 fsl_bytes_fossilize() if the client needs to fossilize more than
2101 one element. Does not support the '#' flag.
2102
2103 `%j`: works like `%s` but JSON-encodes the string. It does not
2104 include the outer quotation marks by default, but using the '!'
2105 flag, i.e. `%!j`, causes those to be added. The length and precision
2106 flags are NOT supported for this format. Results are undefined if
2107 given input which is not legal UTF8. By default non-ASCII
2108 characters with values less than 0xffff are emitted as as literal
2109 characters (no escaping), but the '#' modifier flag will cause it
2110 to emit such characters in the `\u####` form. It always encodes
2111 characters above 0xFFFF as UTF16 surrogate pairs (as JSON
2112 requires). Invalid UTF8 characters may get converted to '?' or may
2113 produce invalid JSON output. As a special case, if the value is NULL
2114 pointer, it resolves to "null" without quotes (regardless of the '!'
2115 modifier).
2116
2117 `%R`: requires an integer argument and renders it like fsl_rc_cstr()
2118 would. If that function result is NULL then "#n" is used, where n
2119 is the integer argument.
2120
2121 Some of these extensions may be disabled by setting certain macros
2122 when compiling appendf.c (see that file for details).
2123
2124 Potential TODO: add fsl_bytes_fossilize_out() which works like
2125 fsl_bytes_fossilize() but sends its output to an fsl_output_f(), so
2126 that this routine doesn't need to alloc for that case.
2127*/
2128FSL_EXPORT int fsl_appendfv(fsl_output_f pfAppend, void * pfAppendArg,
2129 const char *fmt, va_list ap );
2130
2131/**
2132 Identical to fsl_appendfv() but takes an ellipses list (...)
2133 instead of a va_list.
2134*/
2136 void * pfAppendArg,
2137 const char *fmt,
2138 ... )
2139#if 0
2140/* Would be nice, but complains about our custom format options: */
2141 __attribute__ ((__format__ (__printf__, 3, 4)))
2142#endif
2143 ;
2144
2145/**
2146 Works like fsl_appendf() except that it sends the first n bytes of
2147 str as-is to pfAppend(). If n is negative, fsl_strlen() is used to
2148 calculate its lenght.
2149*/
2150FSL_EXPORT int fsl_appendn(fsl_output_f pfAppend, void * pfAppendArg,
2151 const char *str, fsl_int_t n);
2152
2153
2154/**
2155 A fsl_output_f() impl which requires that state be an opened,
2156 writable (FILE*) handle.
2157*/
2158FSL_EXPORT int fsl_output_f_FILE( void * state, void const * s,
2159 fsl_size_t n );
2160
2161
2162/**
2163 Emulates fprintf() using fsl_appendf(). Returns the result of
2164 passing the data through fsl_appendf() to the given file handle.
2165*/
2166FSL_EXPORT int fsl_fprintf( FILE * fp, char const * fmt, ... );
2167
2168/**
2169 The va_list counterpart of fsl_fprintf().
2170*/
2171FSL_EXPORT int fsl_fprintfv( FILE * fp, char const * fmt, va_list args );
2172
2173
2174/**
2175 Possibly reallocates self->list, changing its size. This function
2176 ensures that self->list has at least n entries. If n is 0 then
2177 the list is deallocated (but the self object is not), BUT THIS
2178 DOES NOT DO ANY TYPE-SPECIFIC CLEANUP of the items. If n is less
2179 than or equal to self->capacity then there are no side effects. If
2180 n is greater than self->capacity, self->list is reallocated and
2181 self->capacity is adjusted to be at least n (it might be bigger -
2182 this function may pre-allocate a larger value).
2183
2184 Passing an n of 0 when self->capacity is 0 is a no-op.
2185
2186 Newly-allocated slots will be initialized with NULL pointers.
2187
2188 Returns 0 on success, FSL_RC_MISUSE if !self, FSL_RC_OOM if
2189 reservation of new elements fails.
2190
2191 The return value should be used like this:
2192
2193 ```
2194 fsl_size_t const n = number of bytes to allocate;
2195 int const rc = fsl_list_reserve( myList, n );
2196 if( rc ) { ... error ... }
2197 ```
2198
2199 @see fsl_list_clear()
2200 @see fsl_list_visit_free()
2201*/
2203
2204/**
2205 Appends a bitwise copy of cp to self->list, expanding the list as
2206 necessary and adjusting self->used.
2207
2208 Returns 0 on success, FSL_RC_OOM on allocation error.
2209
2210 Ownership of cp is unchanged by this call. cp may not be NULL.
2211*/
2212FSL_EXPORT int fsl_list_append( fsl_list * self, void * cp );
2213
2214/**
2215 Swaps all contents of both lhs and rhs. Results are undefined if
2216 lhs or rhs are NULL or not properly initialized (via initial copy
2217 initialization from fsl_list_empty resp. fsl_list_empty_m).
2218*/
2220
2221/** @typedef typedef int (*fsl_list_visitor_f)(void * p, void * visitorState )
2222
2223 Generic visitor interface for fsl_list lists. Used by
2224 fsl_list_visit(). p is the pointer held by that list entry and
2225 visitorState is the 4th argument passed to fsl_list_visit().
2226
2227 Implementations must return 0 on success. Any other value causes
2228 looping to stop and that value to be returned, but interpretation
2229 of the value is up to the caller (it might or might not be an
2230 error, depending on the context). Note that client code may use
2231 custom values, and is not strictly required to use FSL_RC_xxx
2232 values. HOWEVER... all of the libfossil APIs which take these
2233 as arguments may respond differently to some codes (most notable
2234 FSL_RC_BREAK, which they tend to treat as a
2235 stop-iteration-without-error result), so clients are strongly
2236 encourage to return an FSL_RC_xxx value on error.
2237*/
2238typedef int (*fsl_list_visitor_f)(void * obj, void * visitorState );
2239
2240/**
2241 A fsl_list_visitor_f() implementation which requires that obj be
2242 arbitrary memory which can legally be passed to fsl_free()
2243 (which this function does). The visitorState parameter is
2244 ignored.
2245*/
2246FSL_EXPORT int fsl_list_v_fsl_free(void * obj, void * visitorState );
2247
2248
2249/**
2250 For each item in self->list, visitor(item,visitorState) is
2251 called. The item is owned by self. The visitor function MUST
2252 NOT free the item (unless the visitor is a finalizer!), but may
2253 manipulate its contents if application rules do not specify
2254 otherwise.
2255
2256 If order is 0 or greater then the list is traversed from start
2257 to finish, else it is traverse from end to begin.
2258
2259 Returns 0 on success, non-0 on error.
2260
2261 If visitor() returns non-0 then looping stops and that code is
2262 returned.
2263*/
2264FSL_EXPORT int fsl_list_visit( fsl_list const * self, int order,
2265 fsl_list_visitor_f visitor, void * visitorState );
2266
2267/**
2268 A list clean-up routine which takes a callback to clean up its
2269 contents.
2270
2271 Passes each element in the given list to
2272 childFinalizer(item,finalizerState). If that returns non-0,
2273 processing stops and that value is returned, otherwise
2274 fsl_list_reserve(list,0) is called and 0 is returned.
2275
2276 WARNING: if cleanup fails because childFinalizer() returns non-0,
2277 the returned object is effectively left in an undefined state and
2278 the client has no way (unless the finalizer somehow accounts for it)
2279 to know which entries in the list were cleaned up. Thus it is highly
2280 recommended that finalizer functions follow the conventional wisdom
2281 of "destructors do not throw."
2282
2283 @see fsl_list_visit_free()
2284*/
2286 fsl_list_visitor_f childFinalizer,
2287 void * finalizerState );
2288/**
2289 Similar to fsl_list_clear(list, fsl_list_v_fsl_free, NULL), but
2290 only frees list->list if the second argument is true, otherwise
2291 it sets the list's length to 0 but keep the list->list memory
2292 intact for later use.
2293
2294 Be sure only to use this on lists of types for which fsl_free()
2295 is legal. i.e. don't use it on a list of fsl_deck objects or
2296 other types which have their own finalizers.
2297
2298 Results are undefined if list is NULL.
2299
2300 @see fsl_list_clear()
2301*/
2302FSL_EXPORT void fsl_list_visit_free( fsl_list * list, bool freeListMem );
2303
2304/**
2305 Works similarly to the visit operation without the _p suffix
2306 except that the pointer the visitor function gets is a (**)
2307 pointing back to the entry within this list. That means that
2308 callers can assign the entry in the list to another value during
2309 the traversal process (e.g. set it to 0). If shiftIfNulled is
2310 true then if the callback sets the list's value to 0 then it is
2311 removed from the list and self->used is adjusted (self->capacity
2312 is not changed).
2313*/
2314FSL_EXPORT int fsl_list_visit_p( fsl_list * self, int order,
2315 bool shiftIfNulled,
2316 fsl_list_visitor_f visitor, void * visitorState );
2317
2318
2319/**
2320 Sorts the given list using the given comparison function. Neither
2321 argument may be NULL. The arugments passed to the comparison function
2322 will be pointers to pointers to the original entries, and may (depending
2323 on how the list is used) point to NULL.
2324*/
2326
2327/**
2328 Searches for a value in the given list, using the given
2329 comparison function to determine equivalence. The comparison
2330 function will never be passed a NULL value by this function - if
2331 value is NULL then only a NULL entry will compare equal to it.
2332 Results are undefined if li or cmpf are NULL.
2333
2334 Returns the index in li of the entry, or a negative value if no
2335 match is found.
2336*/
2338 void const * value,
2339 fsl_generic_cmp_f cmpf);
2340
2341/**
2342 Equivalent to fsl_list_index_of(li, key, fsl_strcmp_cmp).
2343*/
2345 char const * key );
2346
2347
2348/**
2349 Returns 0 if the given file is readable. Flags may be any values
2350 accepted by the access(2) resp. _waccess() system calls.
2351*/
2352FSL_EXPORT int fsl_file_access(const char *zFilename, int flags);
2353
2354/**
2355 Computes a canonical pathname for a file or directory. Makes the
2356 name absolute if it is relative. Removes redundant / characters.
2357 Removes all /./ path elements. Converts /A/../ to just /. If the
2358 slash parameter is non-zero, the trailing slash, if any, is
2359 retained.
2360
2361 If zRoot is not NULL then it is used for transforming a relative
2362 zOrigName into an absolute path. If zRoot is NULL fsl_getcwd()
2363 is used to determine the virtual root directory. If zRoot is
2364 empty (starts with a NUL byte) then this function effectively
2365 just sends zOrigName through fsl_file_simplify_name().
2366
2367 Returns 0 on success, FSL_RC_MISUSE if !zOrigName or !pOut,
2368 FSL_RC_OOM if an allocation fails.
2369
2370 pOut, if not NULL, is _appended_ to, so be sure to set pOut->used=0
2371 (or pass it to fsl_buffer_reuse()) before calling this to start
2372 writing at the beginning of a re-used buffer. On error pOut might
2373 conceivably be partially populated, but that is highly
2374 unlikely. Nonetheless, be sure to fsl_buffer_clear() it at some
2375 point regardless of success or failure.
2376
2377 This function does no actual filesystem-level processing unless
2378 zRoot is NULL or empty (and then only to get the current
2379 directory). This does not confirm whether the resulting file
2380 exists, nor that it is strictly a valid filename for the current
2381 filesystem. It simply transforms a potentially relative path
2382 into an absolute one.
2383
2384 Example:
2385
2386 ```
2387 int rc;
2388 char const * zRoot = "/a/b/c";
2389 char const * zName = "../foo.bar";
2390 fsl_buffer buf = fsl_buffer_empty;
2391 rc = fsl_file_canonical_name2(zRoot, zName, &buf, 0);
2392 if(rc){
2393 fsl_buffer_clear(&buf);
2394 return rc;
2395 }
2396 assert(0 == fsl_strcmp( "/a/b/foo.bar, fsl_buffer_cstr(&buf)));
2397 fsl_buffer_clear(&buf);
2398 ```
2399*/
2401 const char *zOrigName,
2402 fsl_buffer * pOut,
2403 bool slash);
2404
2405/**
2406 Equivalent to fsl_file_canonical_name2(NULL, zOrigName, pOut, slash).
2407
2408 @see fsl_file_canonical_name2()
2409*/
2410
2411FSL_EXPORT int fsl_file_canonical_name(const char *zOrigName,
2412 fsl_buffer * pOut, bool slash);
2413
2414/**
2415 Calculates the "directory part" of zFilename and _appends_ it to
2416 pOut. The directory part is all parts up to the final path
2417 separator ('\\' or '/'). If leaveSlash is true then the separator
2418 part is appended to pOut, otherwise it is not. This function only
2419 examines the first nLen bytes of zFilename. If nLen is negative
2420 then fsl_strlen() is used to determine the number of bytes to
2421 examine.
2422
2423 If zFilename ends with a slash then it is considered to be its
2424 own directory part. i.e. the dirpart of "foo/" evaluates to
2425 "foo" (or "foo/" if leaveSlash is true), whereas the dirpart of
2426 "foo" resolves to nothing (empty - no output except a NUL
2427 terminator sent to pOut).
2428
2429 Returns 0 on success, FSL_RC_MISUSE if !zFilename or !pOut,
2430 FSL_RC_RANGE if 0==nLen or !*zFilename, and FSL_RC_OOM if
2431 appending to pOut fails. If zFilename contains only a path
2432 separator and leaveSlash is false then only a NUL terminator is
2433 appended to pOut if it is not already NUL-terminated.
2434
2435 This function does no filesystem-level validation of the the
2436 given path - only string evaluation.
2437*/
2438FSL_EXPORT int fsl_file_dirpart(char const * zFilename, fsl_int_t nLen,
2439 fsl_buffer * pOut, bool leaveSlash);
2440
2441/**
2442 Return the tail of a NUL-terminated file pathname. The tail is the
2443 last component of the path. For example, the tail of "/a/b/c.d" is
2444 "c.d". If the name ends in a slash, a pointer to its NUL terminator
2445 is returned.
2446*/
2447FSL_EXPORT const char *fsl_file_tail(const char *z);
2448
2449/**
2450 Writes the absolute path name of the current directory to zBuf,
2451 which must be at least nBuf bytes long (nBuf includes the space
2452 for a trailing NUL terminator).
2453
2454 Returns FSL_RC_RANGE if the name would be too long for nBuf,
2455 FSL_RC_IO if it cannot determine the current directory (e.g. a
2456 side effect of having removed the directory at runtime or similar
2457 things), and 0 on success.
2458
2459 On success, if outLen is not NULL then the length of the string
2460 written to zBuf is assigned to *outLen. The output string is
2461 always NUL-terminated.
2462
2463 On Windows, the name is converted from unicode to UTF8 and all '\\'
2464 characters are converted to '/'. No conversions are needed on
2465 Unix.
2466*/
2467FSL_EXPORT int fsl_getcwd(char *zBuf, fsl_size_t nBuf, fsl_size_t * outLen);
2468
2469
2470/**
2471 Return true if the filename given is a valid filename
2472 for a file in a repository. Valid filenames follow all of the
2473 following rules:
2474
2475 - Does not begin with "/"
2476 - Does not contain any path element named "." or ".."
2477 - Does not contain "/..." (special case)
2478 - Does not contain any of these characters in the path: "\"
2479 - Does not end with "/".
2480 - Does not contain two or more "/" characters in a row.
2481 - Contains at least one character
2482
2483 Invalid UTF8 characters result in a false return if bStrictUtf8 is
2484 true. If bStrictUtf8 is false, invalid UTF8 characters are
2485 silently ignored. See
2486 https://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences and
2487 https://en.wikipedia.org/wiki/Unicode (for the non-characters).
2488
2489 Fossil compatibility note: the bStrictUtf8 flag must be true
2490 when parsing new manifests but is false when parsing legacy
2491 manifests, for backwards compatibility.
2492
2493 z must be NUL terminated. Results are undefined if !z.
2494
2495 Note that periods in and of themselves are valid filename
2496 components, with the special exceptions of "." and "..", one
2497 implication being that "...." is, for purposes of this function,
2498 a valid simple filename.
2499*/
2500FSL_EXPORT bool fsl_is_simple_pathname(const char *z, bool bStrictUtf8);
2501
2502/**
2503 Return the size of a file in bytes. Returns -1 if the file does
2504 not exist or is not stat(2)able.
2505*/
2506FSL_EXPORT fsl_int_t fsl_file_size(const char *zFilename);
2507
2508/**
2509 Return the modification time for a file. Return -1 if the file
2510 does not exist or is not stat(2)able.
2511*/
2512FSL_EXPORT fsl_time_t fsl_file_mtime(const char *zFilename);
2513
2514#if 0
2515/**
2516 Don't use this. The wd (working directory) family of functions
2517 might or might-not be necessary and in any case they require
2518 a fsl_cx context argument because they require repo-specific
2519 "allow-symlinks" setting.
2520
2521 Return TRUE if the named file is an ordinary file or symlink
2522 and symlinks are allowed.
2523
2524 Return false for directories, devices, fifos, etc.
2525*/
2526FSL_EXPORT bool fsl_wd_isfile_or_link(const char *zFilename);
2527#endif
2528
2529/**
2530 Returns true if the named file is an ordinary file. Returns false
2531 for directories, devices, fifos, symlinks, etc. The name
2532 may be absolute or relative to the current working dir.
2533*/
2534FSL_EXPORT bool fsl_is_file(const char *zFilename);
2535
2536/**
2537 Returns true if the given file is a symlink, else false. The name
2538 may be absolute or relative to the current working dir. On Windows
2539 platforms this always returns false.
2540*/
2541FSL_EXPORT bool fsl_is_symlink(const char *zFilename);
2542
2543/**
2544 Returns true if the given filename refers to a plain file or
2545 symlink, else returns false. The name may be absolute or relative
2546 to the current working dir.
2547*/
2548FSL_EXPORT bool fsl_is_file_or_link(const char *zFilename);
2549
2550/**
2551 Returns true if the given path appears to be absolute, else
2552 false. On Unix a path is absolute if it starts with a '/'. On
2553 Windows a path is also absolute if it starts with a letter, a
2554 colon, and either a backslash or forward slash.
2555*/
2556FSL_EXPORT bool fsl_is_absolute_path(const char *zPath);
2557
2558/**
2559 Simplify a filename by:
2560
2561 * converting all \ into / on windows and cygwin
2562 * removing any trailing and duplicate /
2563 * removing /./
2564 * removing /A/../
2565
2566 Changes are made in-place. Return the new name length.
2567
2568 If n is <0 then fsl_strlen() is used to calculate the length.
2569
2570 If the slash parameter is true, the trailing slash, if any, is
2571 retained, else any trailing slash is removed.
2572
2573 As a special case, if the input string (simplified) is "/" then the
2574 output string will be "/", regardless of the value of the final
2575 argument. That behavior is debatable but this API is really
2576 intended to be used for paths deeper than the root directory.
2577*/
2579
2580/**
2581 Return true if string z matches glob pattern zGlob and false if the
2582 pattern does not match. Always returns false if either argument is
2583 NULL. Supports all globbing rules supported by sqlite3_strglob().
2584*/
2585FSL_EXPORT bool fsl_str_glob(const char *zGlob, const char *z);
2586
2587/**
2588 Parses zPatternList as a comma-and/or-fsl_isspace()-delimited
2589 list of glob patterns (as supported by fsl_str_glob()). Each
2590 pattern in that list is copied and appended to tgt in the form
2591 of a new (char *) owned by that list.
2592
2593 Returns 0 on success, FSL_RC_OOM if copying a pattern to tgt
2594 fails, FSL_RC_MISUSE if !tgt or !zPatternList. An empty
2595 zPatternList is not considered an error (to simplify usage) and
2596 has no side-effects. On allocation error, tgt might be partially
2597 populated.
2598
2599 Elements of the glob list may be optionally enclosed in single
2600 or double-quotes. This allows a comma to be part of a glob
2601 pattern.
2602
2603 Leading and trailing spaces on unquoted glob patterns are
2604 ignored.
2605
2606 Note that there is no separate "glob list" class. A "glob list"
2607 is simply a fsl_list whose list entries are glob-pattern strings
2608 owned by that list.
2609
2610 Calling this does not reset tgt's list, so it may be called
2611 multiple times to prepare a given list.
2612
2613 Examples of a legal value for zPatternList:
2614
2615 ```
2616 "*.c *.h, *.sh, '*.in'"
2617 ```
2618
2619 @see fsl_glob_list_append()
2620 @see fsl_glob_list_matches()
2621 @see fsl_glob_list_clear()
2622*/
2623FSL_EXPORT int fsl_glob_list_parse( fsl_list * tgt, char const * zPatternList );
2624
2625/**
2626 Appends a single blob pattern to tgt, in the form of a new (char *)
2627 owned by tgt. This function copies zGlob and appends that copy
2628 to tgt.
2629
2630 Returns 0 on success, FSL_RC_MISUSE if !tgt or !zGlob or
2631 !*zGlob, FSL_RC_OOM if appending to the list fails.
2632
2633 @see fsl_glob_list_parse()
2634 @see fsl_glob_list_matches()
2635 @see fsl_glob_list_clear()
2636*/
2637FSL_EXPORT int fsl_glob_list_append( fsl_list * tgt, char const * zGlob );
2638
2639/**
2640 Assumes globList is a list of (char [const] *) glob values and
2641 tries to match each one against zNeedle using
2642 fsl_str_glob(). If any glob matches, it returns a pointer to the
2643 matched globList->list entry. If no matches are found, or if any
2644 argument is invalid, NULL is returned.
2645
2646 The returned bytes are owned by globList and may be invalidated at
2647 its leisure. It is primarily intended to be used as a boolean,
2648 for example:
2649
2650 ```
2651 if( fsl_glob_list_matches(myGlobs, someFilename) ) { ... }
2652 ```
2653
2654 @see fsl_glob_list_parse()
2655 @see fsl_glob_list_append()
2656 @see fsl_glob_list_clear()
2657*/
2658FSL_EXPORT char const * fsl_glob_list_matches( fsl_list const * globList,
2659 char const * zNeedle );
2660
2661/**
2662 If globList is not NULL this is equivalent to
2663 fsl_list_visit_free(globList, 1), otherwise it is a no-op.
2664
2665 Note that this does not free the globList object itself, just
2666 its underlying list entries and list memory. (In practice, lists
2667 are either allocated on the stack or as part of a higher-level
2668 structure, and not on the heap.)
2669
2670 @see fsl_glob_list_parse()
2671 @see fsl_glob_list_append()
2672 @see fsl_glob_list_matches()
2673*/
2675
2676
2677/**
2678 Returns true if the given letter is an ASCII alphabet character.
2679*/
2681
2682/**
2683 Returns true if c is a lower-case ASCII alphabet character.
2684*/
2686
2687/**
2688 Returns true if c is an upper-case ASCII alphabet character.
2689*/
2691
2692/**
2693 Returns true if c is ' ', '\\r' (ASCII 13dec), or '\\t' (ASCII 9
2694 dec).
2695*/
2697
2698/**
2699 Returns true if c is an ASCII digit in the range '0' to '9'.
2700*/
2702
2703/**
2704 Equivalent to fsl_isdigit(c) || fsl_isalpha().
2705*/
2707
2708/**
2709 Returns the upper-case form of c if c is an ASCII alphabet
2710 letter, else returns c.
2711*/
2713
2714/**
2715 Returns the lower-case form of c if c is an ASCII alphabet
2716 letter, else returns c.
2717*/
2719
2720#ifdef _WIN32
2721/**
2722 Translate MBCS to UTF-8. Return a pointer to the translated
2723 text. ACHTUNG: Call fsl_mbcs_free() (not fsl_free()) to
2724 deallocate any memory used to store the returned pointer when
2725 done.
2726*/
2727FSL_EXPORT char * fsl_mbcs_to_utf8(char const * mbcs);
2728
2729/**
2730 Frees a string allocated from fsl_mbcs_to_utf8(). Results are undefined
2731 if mbcs was allocated using any other mechanism.
2732*/
2733FSL_EXPORT void fsl_mbcs_free(char * mbcs);
2734#endif
2735/* _WIN32 */
2736
2737/**
2738 Deallocates the given memory, which must have been allocated
2739 from fsl_unicode_to_utf8(), fsl_utf8_to_unicode(), or any
2740 function which explicitly documents this function as being the
2741 proper finalizer for its returned memory.
2742*/
2744
2745/**
2746 Translate UTF-8 to Unicode for use in system calls. Returns a
2747 pointer to the translated text. The returned value must
2748 eventually be passed to fsl_unicode_free() to deallocate any
2749 memory used to store the returned pointer when done.
2750
2751 This function exists only for Windows. On other platforms
2752 it behaves like fsl_strdup().
2753
2754 The returned type is (wchar_t*) on Windows and (char*)
2755 everywhere else.
2756*/
2757FSL_EXPORT void *fsl_utf8_to_unicode(const char *zUtf8);
2758
2759/**
2760 Translates Unicode text into UTF-8. Return a pointer to the
2761 translated text. Call fsl_unicode_free() to deallocate any
2762 memory used to store the returned pointer when done.
2763
2764 This function exists only for Windows. On other platforms it
2765 behaves like fsl_strdup().
2766*/
2767FSL_EXPORT char *fsl_unicode_to_utf8(const void *zUnicode);
2768
2769/**
2770 Translate text from the OS's character set into UTF-8. Return a
2771 pointer to the translated text. Call fsl_os_str_free() to
2772 deallocate any memory used to store the returned pointer when
2773 done.
2774
2775 This function must not convert '\' to '/' on Windows/Cygwin, as
2776 it is used in places where we are not sure it's really filenames
2777 we are handling, e.g. fsl_getenv() or handling the argv
2778 arguments from main().
2779
2780 On Windows, translate some characters in the in the range
2781 U+F001 - U+F07F (private use area) to ASCII. Cygwin sometimes
2782 generates such filenames. See:
2783 <https://cygwin.com/cygwin-ug-net/using-specialnames.html>
2784*/
2785FSL_EXPORT char *fsl_filename_to_utf8(const void *zFilename);
2786
2787/**
2788 Attempts to ensure that the name of a file in the filesystem matches
2789 the same case as one provided by the user. This distinction can be
2790 significant for users on case-insensitive filesystems.
2791
2792 `zDir` must be the name of the target directory and `zPath` must be
2793 a relative path rooted at `zDir`. If `zPath` does not exist, it is
2794 assumed to be a _potential_ name and `*zOut` will be set to an
2795 as-is copy of `zPath`.
2796
2797 If `isCaseSensitive` is true then this function is essentially a
2798 dummy stub which returns a copy of `zPath`, made using
2799 fsl_strdup(), via `*zOut`.
2800
2801 If isCaseSensitive is false, then it behaves rather differently:
2802
2803 Uses opendir() on the given directory and scans it for a name
2804 matching `zPath`, case-insensitvely and recursively. On success,
2805 the result is a case-correct copy of `zPath`.
2806
2807 On error, non-zero is returned and `*zOut` is not modified. On
2808 success, `*zOut` is modified as described above and ownership of it
2809 is transfered to the caller, who must eventually pass it to
2810 fsl_free().
2811
2812 Non-0 error codes include:
2813
2814 - FSL_RC_OOM on allocation error.
2815 - FSL_RC_IO if opendir() fails.
2816
2817 Design note: `isCaseSensitive` is provided as a bool, rather than a
2818 fsl_cx instance (which has a setting for that flag), so that this
2819 routine can be used in cases where a fsl_cx is not readily
2820 available and in cases where this validation is desired on
2821 case-sensitive filesystems. When a fsl_cx is available,
2822 fsl_cx_is_case_sensitive() may optionally be used to as the value
2823 for the first argument. Depending on _how_ filenames are collected,
2824 however, this case-check may or may not be entirely superfluous.
2825*/
2826FSL_EXPORT int fsl_filename_preferred_case(bool isCaseSensitive, const char *zDir,
2827 const char *zPath, char **zOut);
2828
2829/**
2830 Translate text from UTF-8 to the OS's filename character set.
2831 Return a pointer to the translated text. Call
2832 fsl_os_str_free() to deallocate any memory used to store the
2833 returned pointer when done.
2834
2835 On Windows, characters in the range U+0001 to U+0031 and the
2836 characters '"', '*', ':', '<', '>', '?' and '|' are invalid in
2837 filenames. Therefore, translate those to characters in the in the
2838 range U+F001 - U+F07F (private use area), so those characters
2839 never arrive in any Windows API. The filenames might look
2840 strange in Windows explorer, but in the cygwin shell everything
2841 looks as expected.
2842
2843 See: <https://cygwin.com/cygwin-ug-net/using-specialnames.html>
2844
2845 The returned type is (wchar_t*) on Windows and (char*)
2846 everywhere else.
2847*/
2848FSL_EXPORT void *fsl_utf8_to_filename(const char *zUtf8);
2849
2850
2851/**
2852 Deallocate pOld, which must be NULL or must have been allocated by
2853 fsl_filename_to_utf8(), fsl_utf8_to_filename(), fsl_getenv(), or
2854 another routine which explicitly documents this function as being
2855 the proper finalizer for its returned memory.
2856*/
2858
2859/**
2860 Returns a (possible) copy of the environment variable with the
2861 given key, or NULL if no entry is found. The returned value must
2862 be passed to fsl_os_str_free() to free it. ACHTUNG: DO NOT
2863 MODIFY the returned value - on Unix systems it is _not_ a
2864 copy. That interal API inconsistency "should" be resolved
2865 (==return a copy from here, but that means doing it everywhere)
2866 to avoid memory ownership problems later on.
2867
2868 Why return a copy? Because native strings from at least one of
2869 the more widespread OSes often have to be converted to something
2870 portable and this requires allocation on such platforms, but
2871 not on Unix. For API transparency, that means all platforms get
2872 the copy(-like) behaviour.
2873*/
2874FSL_EXPORT char *fsl_getenv(const char *zName);
2875
2876/**
2877 Collects a list of directories intended to use as temp dirs in the
2878 current environment. The returned array ends with a NULL element to
2879 mark its end. The memory's ownership is a bit awkward and
2880 therefore it must be eventually freed by passing it to
2881 fsl_temp_dirs_free().
2882
2883 No entries in the returned list contain a trailing slash unless the
2884 entry is itself a reference to a Unix-style root directory (which
2885 would be highly unusual).
2886
2887 The list of directories varies by platform:
2888
2889 Windows:
2890
2891 - `GetTempPath()`, `$TEMP`, `$TMP`, "."
2892
2893 Non-Windows:
2894
2895 - `$TMPDIR`, "/var/tmp", "/usr/tmp", "/tmp", "/temp",
2896 "."
2897
2898 (`$X` refers to the value of environment variable `X`.)
2899
2900 Noting that only directories in those lists which actually exist
2901 (at the time this is called) are added to the list (also noting
2902 that "." always exists unless CWD is deleted while the app is
2903 active). If no suitable directories are found, an empty array (with
2904 a leading `NULL` element) is returned, but this would indicate
2905 that, e.g., even CWD does not exist (so the app has bigger
2906 problems).
2907
2908 `NULL` is only returned if allocation of the containing array
2909 fails. Failure to allocate memory for a given directory name (as
2910 those require conversion on some platforms) is ignored and such
2911 entries are simply skipped over.
2912
2913 @see fsl_temp_dirs_free()
2914 @see fsl_file_tempname()
2915*/
2917
2918/**
2919 If aDirs is not NULL then it is expected to be an array created by
2920 fsl_temp_dirs_get() and it frees the list's entries and the list
2921 itself. After calling this, the argument's memory is invalidated
2922 and any use of it leads to undefined results.
2923
2924 This is a harmless no-op if the argument is NULL.
2925
2926 @see fsl_temp_dirs_get()
2927 @see fsl_file_tempname()
2928*/
2930
2931/**
2932 Creates a semi-random temp filename and appends it to the given
2933 buffer. The second argument is an optional string to prefix
2934 each filename with. If it is NULL then a library-wide default is
2935 used. If it is empty then no prefix is used. The final argument is
2936 expected to be NULL or a list of directories in the format
2937 constructed by fsl_temp_dirs_get(). If it is not NULL, this
2938 function uses the first entry in dirs which refers to an existing
2939 directory. If it is NULL then the buffer is filled with the new
2940 name with no directory prefix.
2941
2942 Returns...
2943
2944 - 0 on success, in which case tgt is populated with the new name.
2945
2946 - If tgt->errCode is not 0 when this is called, that is returned
2947 and this function has no further side effects.
2948
2949 - FSL_RC_NOT_FOUND if dirs is empty or refers only to non-existent
2950 directories.
2951
2952 - FSL_RC_OOM if allocating memory for the target buffer fails.
2953
2954 - FSL_RC_RANGE if, after some hard-coded number of attempts, it is
2955 unable to construct a unique filename due to name collisions in
2956 the target directory. That "shouldn't ever happen."
2957
2958 Sidebars:
2959
2960 - This function does no translation or validation of the 2nd
2961 argument other than to check if it is NULL. It "should" be either
2962 a file base name, with no path component, or a relative path
2963 component for which the caller has already created the directory.
2964 e.g. use the base name of the application, e.g. "my-app".
2965
2966 - This function does not actually write to the filesystem, it just
2967 constructs a name. There is hypothetically a window of
2968 opportunity for another file with the same name to be created
2969 before the caller has a chance to create the file, but the
2970 chances of that actually happening are close enough to zero to
2971 rule them out for all practical purposes.
2972
2973 - The RNG is officially unspecified. (That said:
2974 sqlite3_randomness().)
2975
2976 @see fsl_temp_dirs_get()
2977 @see fsl_temp_dirs_free()
2978*/
2979FSL_EXPORT int fsl_file_tempname(fsl_buffer * tgt, char const *zPrefix,
2980 char * const * dirs);
2981
2982/**
2983 Returns a positive value if zFilename is a directory, 0 if
2984 zFilename does not exist, or a negative value if zFilename
2985 exists but is something other than a directory. Results are
2986 undefined if zFilename is NULL.
2987
2988 This function expects zFilename to be a well-formed path -
2989 it performs no normalization on it.
2990*/
2991FSL_EXPORT int fsl_dir_check(const char *zFilename);
2992
2993/**
2994 Check the given path to determine whether it is an empty directory.
2995 Returns 0 on success (i.e., directory exists and is empty), <0 if
2996 the provided path is not a directory or cannot be opened, and >0 if
2997 the directory is not empty.
2998*/
2999FSL_EXPORT int fsl_dir_is_empty(const char *path);
3000
3001/**
3002 Deletes the given file from the filesystem. Returns 0 on
3003 success. If the component is a directory, this operation will
3004 fail. If zFilename refers to a symlink, the link (not its target)
3005 is removed.
3006
3007 Results are undefined if zFilename is NULL.
3008
3009 Potential TODO: if it refers to a dir, forward the call to
3010 fsl_rmdir().
3011*/
3012FSL_EXPORT int fsl_file_unlink(const char *zFilename);
3013
3014/**
3015 Renames file zFrom to zTo using the OS's equivalent of
3016 `rename(2)`. Both files must be in the same filesystem and any
3017 directory parts of zTo must already exist. Returns 0 on success,
3018 FSL_RC_OOM if a filename conversion allocation fails (on platforms
3019 which do that), or a FSL_RC_xxx counterpart of an `errno` value if
3020 the `rename(2)` call fails (as per fsl_errno_to_rc()).
3021*/
3022FSL_EXPORT int fsl_file_rename(const char *zFrom, const char *zTo);
3023
3024/**
3025 Deletes an empty directory from the filesystem. Returns 0
3026 on success. There are any number of reasons why deletion
3027 of a directory can fail, some of which include:
3028
3029 - It is not empty or permission denied (FSL_RC_ACCESS).
3030
3031 - Not found (FSL_RC_NOT_FOUND).
3032
3033 - Is not a directory or (on Windows) is a weird pseudo-dir type for
3034 which rmdir() does not work (FSL_RC_TYPE).
3035
3036 - I/O error (FSL_RC_IO).
3037
3038 @see fsl_dir_is_empty()
3039*/
3040FSL_EXPORT int fsl_rmdir(const char *zFilename);
3041
3042/**
3043 Sets the mtime (Unix epoch) for a file. Returns 0 on success,
3044 non-0 on error. If newMTime is less than 0 then the current
3045 time(2) is used. This routine does not create non-existent files
3046 (e.g. like a Unix "touch" command).
3047*/
3048FSL_EXPORT int fsl_file_mtime_set(const char *zFilename, fsl_time_t newMTime);
3049
3050/**
3051 On non-Windows platforms, this function sets or unsets the
3052 executable bits on the given filename. All other permissions are
3053 retained as-is. Returns 0 on success. On Windows this is a no-op,
3054 returning 0.
3055
3056 If the target is a directory or a symlink, this is a no-op and
3057 returns 0.
3058*/
3059FSL_EXPORT int fsl_file_exec_set(const char *zFilename, bool isExec);
3060
3061/**
3062 Returns true if the argument is fsl_stat()'able and has the
3063 executable bit set, else false.
3064*/
3065FSL_EXPORT bool fsl_file_isexec(const char *zFilename);
3066
3067/**
3068 Makes a bitwise copy of the file zFrom to file zTo, creating any
3069 directories needed for the target file's if they do not already
3070 exist. If the source file is executable then the target file will
3071 also be made so, but any failure to do so (e.g. because the target
3072 filesystem does not support it) is silently ignored.
3073
3074 Returns 0 on success. On error it may return any number of result
3075 codes if opening a file fails, if a mkdir fails (see
3076 fsl_mkdir_for_file()), or if any I/O fails.
3077
3078 Results are undefined if the source and target refer to the
3079 same file.
3080*/
3081FSL_EXPORT int fsl_file_copy(char const *zFrom, char const *zTo);
3082
3083/**
3084 Create the directory with the given name if it does not already
3085 exist. If forceFlag is true, delete any prior non-directory
3086 object with the same name.
3087
3088 Return 0 on success, non-0 on error.
3089
3090 If the directory already exists then 0 is returned, not an error
3091 (FSL_RC_ALREADY_EXISTS), because that simplifies usage. If
3092 another filesystem entry with this name exists and forceFlag is
3093 true then that entry is deleted before creating the directory,
3094 and this operation fails if deletion fails. If forceFlag is
3095 false and a non-directory entry already exists, FSL_RC_TYPE is
3096 returned.
3097
3098 For recursively creating directories, use fsl_mkdir_for_file().
3099
3100 Bug/corner case: if zFilename refers to a symlink to a
3101 non-existent directory, this function gets slightly confused,
3102 tries to make a dir with the symlink's name, and returns
3103 FSL_RC_ALREADY_EXISTS. How best to resolve that is not yet
3104 clear. The problem is that stat(2)ing the symlink says "nothing
3105 is there" (because the link points to a non-existing thing), so
3106 we move on to the underlying mkdir(), which then fails because
3107 the link exists with that name.
3108*/
3109FSL_EXPORT int fsl_mkdir(const char *zName, bool forceFlag);
3110
3111/**
3112 A convenience form of fsl_mkdir() which can recursively create
3113 directories. If zName has a trailing slash then the last
3114 component is assumed to be a directory part, otherwise it is
3115 assumed to be a file part (and no directory is created for that
3116 part). zName may be either an absolute or relative path.
3117
3118 Returns 0 on success (including if all directories already exist).
3119 Returns FSL_RC_OOM if there is an allocation error. Returns
3120 FSL_RC_TYPE if one of the path components already exists and is not
3121 a directory. Returns FSL_RC_RANGE if zName is NULL or empty. If
3122 zName is only 1 byte long, this is a no-op.
3123
3124 On systems which support symlinks, a link to a directory is
3125 considered to be a directory for purposes of this function.
3126
3127 If forceFlag is true and a non-directory component is found in
3128 the filesystem where zName calls for a directory, that component
3129 is removed (and this function fails if removal fails).
3130
3131 Examples:
3132
3133 "/foo/bar" creates (if needed) /foo, but assumes "bar" is a file
3134 component. "/foo/bar/" creates /foo/bar. However "foo" will not
3135 create a directory - because the string has no path component,
3136 it is assumed to be a filename.
3137
3138 Both "/foo/bar/my.doc" and "/foo/bar/" result in the directories
3139 "/foo/bar".
3140*/
3141FSL_EXPORT int fsl_mkdir_for_file(char const *zName, bool forceFlag);
3142
3143/**
3144 This function expects its second argument to refer to a symlink
3145 (and that the caller has already validated that it is one). The
3146 `readlink(2)` system call is used to fetch the contents of that
3147 link and the target buffer is populated with those contents
3148 (reusing any memory the buffer may already own).
3149
3150 Returns 0 on success, FSL_RC_OOM if copying to the target buffer
3151 fails due to an allocation error, or an error propagated from
3152 `readlink()` in the form of a fsl_errno_to_rc() result.
3153
3154 Caveat: on Windows platforms this function simply passes the buffer
3155 to fsl_buffer_reuse() and returns 0. It should arguably read the
3156 contents of zFilename into the buffer in that case, on the
3157 assumption that the file is a pseudo-symlink. That decision may be
3158 re-evaluated if/when the library claims to have fossil-compatible
3159 symlink support.
3160
3161 Bugs:
3162
3163 - This function has a limited internal buffer as a target for
3164 `readlink()`. It "should be" long enough for any "reasonable"
3165 uses in the scope of this library, but there's bound to be some
3166 user out there who wants to use it for other contexts.
3167*/
3168FSL_EXPORT int fsl_symlink_read(fsl_buffer * tgt, char const * zFilename);
3169
3170/**
3171 Creates a symlink or pseudo-symlink named zLinkFile linking to
3172 zTargetFile. If realLink is true and this is a non-Windows platform
3173 then:
3174
3175 - fsl_file_simplify_name() is used to normalize zLinkFile.
3176
3177 - `symlink(2)` is used to link zTargetFile to a new link named the
3178 simplified form of zLinkFile. If zLinkFile already exists, this
3179 will fail.
3180
3181 If realLink is false or this is a Windows platform, a file is
3182 created named zLinkFile containing the string zTargetFile as its
3183 contents. If a file or symlink named zLinkFile already exists, it
3184 is removed before writing the new contents.
3185
3186 In both cases the parent directories for zLinkFile are created, if
3187 needed, but that process will fail with FSL_RC_TYPE if any
3188 non-directory components with conflicting names are found in the
3189 to-be-mkdir'd path.
3190
3191 Returns 0 on success or some lower-level result code if
3192 creation/writing of a directory, a symlink, or pseudo-symlink
3193 fails.
3194*/
3195FSL_EXPORT int fsl_symlink_create(char const *zTargetFile, char const * zLinkFile,
3196 bool realLink);
3197
3198/**
3199 Reads symlink zFrom, as per fsl_symlink_read(), then creates a copy
3200 named zTo, as per fsl_symlink_create(). The first argument for the
3201 latter call is the contents of the result of fsl_symlink_read().
3202 The 2nd and 3rd arguments to fsl_symlink_create() are the 2nd and
3203 3rd arguments to this function.
3204
3205 Returns 0 on success, FSL_RC_OOM on OOM, or any of various
3206 filesystem-related non-0 codes if reading or saving the link fails.
3207*/
3208FSL_EXPORT int fsl_symlink_copy(char const *zFrom, char const *zTo, bool realLink);
3209
3210/**
3211 Uses fsl_getenv() to look for the environment variables
3212 (FOSSIL_USER, (Windows: USERNAME), (Unix: USER, LOGNAME)). If
3213 it finds one it returns a copy of that value, which must
3214 eventually be passed to fsl_free() to free it (NOT
3215 fsl_os_str_free(), though fsl_getenv() requires that one). If
3216 it finds no match, or if copying the entry fails, it returns
3217 NULL.
3218
3219 @see fsl_cx_user_set()
3220 @see fsl_cx_user_get()
3221*/
3223
3224/**
3225 Tries to find the user's home directory. If found, 0 is
3226 returned, tgt's memory is _overwritten_ (not appended) with the
3227 path, and tgt->used is set to the path's string length. (Design
3228 note: the overwrite behaviour is inconsistent with most of the
3229 API, but the implementation currently requires this.)
3230
3231 If requireWriteAccess is true then the directory is checked for
3232 write access, and FSL_RC_ACCESS is returned if that check
3233 fails. For historical (possibly techinical?) reasons, this check
3234 is only performed on Unix platforms. On others this argument is
3235 ignored. When writing code on Windows, it may be necessary to
3236 assume that write access is necessary on non-Windows platform,
3237 and to pass 1 for the second argument even though it is ignored
3238 on Windows.
3239
3240 On error non-0 is returned and tgt is updated with an error
3241 string OR (if the error was an allocation error while appending
3242 to the path or allocating MBCS strings for Windows), it returns
3243 FSL_RC_OOM and tgt "might" be updated with a partial path (up to
3244 the allocation error), and "might" be empty (if the allocation
3245 error happens early on).
3246
3247 This routine does not canonicalize/transform the home directory
3248 path provided by the environment, other than to convert the
3249 string byte encoding on some platforms. i.e. if the environment
3250 says that the home directory is "../" then this function will
3251 return that value, possibly to the eventual disappointment of
3252 the caller.
3253
3254 Result codes include:
3255
3256 - FSL_RC_OK (0) means a home directory was found and tgt is
3257 populated with its path.
3258
3259 - FSL_RC_NOT_FOUND means the home directory (platform-specific)
3260 could not be found.
3261
3262 - FSL_RC_ACCESS if the home directory is not writable and
3263 requireWriteAccess is true. Unix platforms only -
3264 requireWriteAccess is ignored on others.
3265
3266 - FSL_RC_TYPE if the home (as determined via inspection of the
3267 environment) is not a directory.
3268
3269 - FSL_RC_OOM if a memory (re)allocation fails.
3270*/
3271FSL_EXPORT int fsl_find_home_dir( fsl_buffer * tgt, bool requireWriteAccess );
3272
3273/**
3274 Values for use with the fsl_fstat::type field.
3275*/
3277/** Sentinel value for unknown/invalid filesystem entry types. */
3279/** Indicates a directory filesystem entry. */
3281/** Indicates a non-directory, non-symlink filesystem entry.
3282 Because fossil's scope is limited to SCM work, it assumes that
3283 "special files" (sockets, etc.) are just files, and makes no
3284 special effort to handle them.
3285*/
3287/** Indicates a symlink filesystem entry. */
3289};
3291
3292/**
3293 Bitmask values for use with the fsl_fstat::perms field.
3294
3295 Only permissions which are relevant for fossil are listed here.
3296 e.g. read-vs-write modes are irrelevant for fossil as it does not
3297 track them. It manages only the is-executable bit. In in the
3298 contexts of fossil manifests, it also treats "is a symlink" as a
3299 permission flag.
3300*/
3302/**
3303 Sentinel value.
3304*/
3306/**
3307 The executable bit, as understood by Fossil. Fossil does not
3308 differentiate between different +x values for user/group/other.
3309*/
3311};
3313
3314/**
3315 A simple wrapper around the stat(2) structure resp. _stat/_wstat
3316 (on Windows). It exposes only the aspects of stat(2) info which
3317 Fossil works with, and not any platform-/filesystem-specific
3318 details except the executable bit for the permissions mode and some
3319 handling of symlinks.
3320*/
3322 /**
3323 Indicates the type of filesystem object.
3324 */
3326 /**
3327 The time of the last file metadata change (owner, permissions,
3328 etc.). The man pages (neither for Linux nor Windows) do not
3329 specify exactly what unit this is. Let's assume seconds since the
3330 start of the Unix Epoch.
3331 */
3333 /**
3334 Last modification time.
3335 */
3337 /**
3338 The size of the stat'd file, in bytes.
3339 */
3341 /**
3342 Contains the filesystem entry's permissions as a bitmask of
3343 fsl_fstat_perm_e values. Note that only the executable bit for
3344 _files_ (not directories) is exposed here.
3345 */
3346 int perm;
3347};
3348
3349/** Empty-initialized fsl_fstat structure, intended for const-copy
3350 construction. */
3351#define fsl_fstat_empty_m {FSL_FSTAT_TYPE_UNKNOWN,0,0,-1,0}
3352
3353/** Empty-initialized fsl_fstat instance, intended for non-const copy
3354 construction. */
3356
3357/**
3358 Runs the OS's stat(2) equivalent to populate fst (if not NULL) with
3359 information about the given file.
3360
3361 The second argument may be NULL.
3362
3363 Returns 0 on success. Results are undefined if zFilename is NULL or
3364 invalid. Returns FSL_RC_NOT_FOUND if no filesystem entry is found
3365 for the given name. Returns FSL_RC_IO if the underlying stat() (or
3366 equivalent) fails for undetermined reasons inside the underlying
3367 stat()/_wstati64() call. Note that the fst parameter may be NULL,
3368 in which case the return value will be 0 if the name is stat-able,
3369 but will return no other information about it.
3370
3371 The derefSymlinks argument is ignored on non-Unix platforms. On
3372 Unix platforms, if derefSymlinks is true then stat(2) is used, else
3373 lstat(2) (if available on the platform) is used. For most cases
3374 clients should pass true. They should only pass false if they need
3375 to differentiate between symlinks and files.
3376
3377 The fsl_fstat_type_e family of flags can be used to determine the
3378 type of the filesystem object being stat()'d (file, directory, or
3379 symlink). It does not apply any special logic for platform-specific
3380 oddities other than symlinks (e.g. character devices and such).
3381*/
3382FSL_EXPORT int fsl_stat(const char *zFilename, fsl_fstat * fst,
3383 bool derefSymlinks);
3384
3385/**
3386 Create a new fossil-format delta between the memory zIn and zOut.
3387
3388 The delta is written into a preallocated buffer, zDelta, which
3389 must be at least 60 bytes longer than the target memory, zOut.
3390 The delta string will be NUL-terminated, but it might also
3391 contain embedded NUL characters if either the zSrc or zOut files
3392 are binary.
3393
3394 On success this function returns 0 and the length of the delta
3395 string, in bytes, excluding the final NUL terminator character,
3396 is written to *deltaSize.
3397
3398 Returns FSL_RC_OOM if memory allocation fails during generation of
3399 the delta. Returns FSL_RC_RANGE if lenSrc or lenOut are "too
3400 big" (if they cause an overflow in the math).
3401
3402 Results are undefined if any pointer is NULL.
3403
3404 Output Format:
3405
3406 The delta begins with a base64 number followed by a newline.
3407 This number is the number of bytes in the TARGET file. Thus,
3408 given a delta file z, a program can compute the size of the
3409 output file simply by reading the first line and decoding the
3410 base-64 number found there. The fsl_delta_applied_size()
3411 routine does exactly this.
3412
3413 After the initial size number, the delta consists of a series of
3414 literal text segments and commands to copy from the SOURCE file.
3415 A copy command looks like this:
3416
3417 (Achtung: extra backslashes are for Doxygen's benefit - not
3418 visible in the processsed docs.)
3419
3420 NNN\@MMM,
3421
3422 where NNN is the number of bytes to be copied and MMM is the
3423 offset into the source file of the first byte (both base-64).
3424 If NNN is 0 it means copy the rest of the input file. Literal
3425 text is like this:
3426
3427 NNN:TTTTT
3428
3429 where NNN is the number of bytes of text (base-64) and TTTTT is
3430 the text.
3431
3432 The last term is of the form
3433
3434 NNN;
3435
3436 In this case, NNN is a 32-bit bigendian checksum of the output
3437 file that can be used to verify that the delta applied
3438 correctly. All numbers are in base-64.
3439
3440 Pure text files generate a pure text delta. Binary files
3441 generate a delta that may contain some binary data.
3442
3443 Algorithm:
3444
3445 The encoder first builds a hash table to help it find matching
3446 patterns in the source file. 16-byte chunks of the source file
3447 sampled at evenly spaced intervals are used to populate the hash
3448 table.
3449
3450 Next we begin scanning the target file using a sliding 16-byte
3451 window. The hash of the 16-byte window in the target is used to
3452 search for a matching section in the source file. When a match
3453 is found, a copy command is added to the delta. An effort is
3454 made to extend the matching section to regions that come before
3455 and after the 16-byte hash window. A copy command is only
3456 issued if the result would use less space that just quoting the
3457 text literally. Literal text is added to the delta for sections
3458 that do not match or which can not be encoded efficiently using
3459 copy commands.
3460
3461 @see fsl_delta_applied_size()
3462 @see fsl_delta_apply()
3463*/
3464FSL_EXPORT int fsl_delta_create( unsigned char const *zSrc, fsl_size_t lenSrc,
3465 unsigned char const *zOut, fsl_size_t lenOut,
3466 unsigned char *zDelta, fsl_size_t * deltaSize);
3467
3468/**
3469 Works identically to fsl_delta_create() but sends its output to
3470 the given output function. out(outState,...) may be called any
3471 number of times to emit delta output. Each time it is called it
3472 should append the new bytes to its output channel.
3473
3474 The semantics of the return value and the first four arguments
3475 are identical to fsl_delta_create(), with these ammendments
3476 regarding the return value:
3477
3478 - Returns FSL_RC_MISUSE if any of (zV1, zV2, out) are NULL.
3479
3480 - If out() returns non-0 at any time, delta generation is
3481 aborted and that code is returned.
3482
3483 Example usage:
3484
3485 ```
3486 int rc = fsl_delta_create( v1, v1len, v2, v2len,
3487 fsl_output_f_FILE, stdout);
3488 ```
3489*/
3490FSL_EXPORT int fsl_delta_create2( unsigned char const *zV1, fsl_size_t lenV1,
3491 unsigned char const *zV2, fsl_size_t lenV2,
3492 fsl_output_f out, void * outState);
3493
3494/**
3495 A fsl_delta_create() wrapper which uses the first two arguments
3496 as the original and "new" content versions to delta, and outputs
3497 the delta to the 3rd argument (overwriting any existing contents
3498 and re-using any memory it had allocated).
3499
3500 If any of the buffers have the same address, FSL_RC_MISUSE is
3501 returned. If fsl_buffer_err() is true for the 3rd argument, that
3502 value is returned without side effects. If allocation of memory for
3503 the delta fails, FSL_RC_OOM is returned and delta's errCode is
3504 updated with that value.
3505
3506 Results are undefined if any argument is NULL.
3507
3508 Returns 0 on success.
3509*/
3511 fsl_buffer const * newVers,
3512 fsl_buffer * delta);
3513
3514/**
3515 Apply a delta created using fsl_delta_create().
3516
3517 The output buffer must be big enough to hold the whole output
3518 file and a NUL terminator at the end. The
3519 fsl_delta_applied_size() routine can be used to determine that
3520 size.
3521
3522 zSrc represents the original sources to apply the delta to.
3523 It must be at least lenSrc bytes of valid memory.
3524
3525 zDelta holds the delta (created using fsl_delta_create()),
3526 and it must be lenDelta bytes long.
3527
3528 On success this function returns 0 and writes the applied delta
3529 to zOut.
3530
3531 Returns FSL_RC_MISUSE if any pointer argument is NULL. Returns
3532 FSL_RC_RANGE if lenSrc or lenDelta are "too big" (if they cause
3533 an overflow in the math). Invalid delta input can cause any of
3534 FSL_RC_RANGE, FSL_RC_DELTA_INVALID_TERMINATOR,
3535 FSL_RC_CHECKSUM_MISMATCH, FSL_RC_SIZE_MISMATCH, or
3536 FSL_RC_DELTA_INVALID_OPERATOR to be returned.
3537
3538 Refer to the fsl_delta_create() documentation above for a
3539 description of the delta file format.
3540
3541 @see fsl_delta_applied_size()
3542 @see fsl_delta_create()
3543 @see fsl_delta_apply2()
3544*/
3545FSL_EXPORT int fsl_delta_apply( unsigned char const *zSrc, fsl_size_t lenSrc,
3546 unsigned char const *zDelta, fsl_size_t lenDelta,
3547 unsigned char *zOut );
3548
3549/**
3550 Functionally identical to fsl_delta_apply() but any errors generated
3551 during application of the delta are described in more detail
3552 in pErr. If pErr is NULL this behaves exactly as documented for
3553 fsl_delta_apply().
3554*/
3555FSL_EXPORT int fsl_delta_apply2( unsigned char const *zSrc,
3556 fsl_size_t lenSrc,
3557 unsigned char const *zDelta,
3558 fsl_size_t lenDelta,
3559 unsigned char *zOut,
3560 fsl_error * pErr);
3561/**
3562 Calculates the size (in bytes) of the output from applying a the
3563 given delta. On success 0 is returned and *appliedSize will be
3564 updated with the amount of memory required for applying the
3565 delta. zDelta must point to lenDelta bytes of memory in the
3566 format emitted by fsl_delta_create(). It is legal for appliedSize
3567 to point to the same memory as the 2nd argument.
3568
3569 Returns FSL_RC_RANGE if lenDelta is too short to be a delta. Returns
3570 FSL_RC_DELTA_INVALID_TERMINATOR if the delta's encoded length is not
3571 properly terminated.
3572
3573 Results are undefined if any pointer argument is NULL.
3574
3575 This routine is provided so that an procedure that is able to call
3576 fsl_delta_apply() can learn how much space is required for the
3577 output and hence allocate no more space that is really needed.
3578
3579 TODO?: consolidate 2nd and 3rd parameters into one i/o parameter?
3580
3581 @see fsl_delta_apply()
3582 @see fsl_delta_create()
3583*/
3584FSL_EXPORT int fsl_delta_applied_size(unsigned char const *zDelta,
3585 fsl_size_t lenDelta,
3586 fsl_size_t * appliedSize);
3587
3588/**
3589 "Fossilizes" the first len bytes of the given input string. If
3590 (len<0) then fsl_strlen(inp) is used to calculate its length.
3591 The output is appended to out, which is expanded as needed and
3592 out->used is updated accordingly. Returns 0 on success,
3593 FSL_RC_MISUSE if !inp or !out. Returns 0 without side-effects if
3594 0==len or (!*inp && len<0). Returns FSL_RC_OOM if reservation of
3595 the output buffer fails (it is expanded, at most, one time by
3596 this function).
3597
3598 Fossilization replaces the following bytes/sequences with the
3599 listed replacements:
3600
3601 (Achtung: usage of doubled backslashes here it just to please
3602 doxygen - they will show up as single slashes in the processed
3603 output.)
3604
3605 - Backslashes are doubled.
3606
3607 - (\\n, \\r, \\v, \\t, \\f) are replaced with \\\\X, where X is the
3608 conventional encoding letter for that escape sequence.
3609
3610 - Spaces are replaced with \\s.
3611
3612 - Embedded NULs are replaced by \\0 (numeric 0, not character
3613 '0').
3614*/
3615FSL_EXPORT int fsl_bytes_fossilize( unsigned char const * inp, fsl_int_t len,
3616 fsl_buffer * out );
3617/**
3618 "Defossilizes" bytes encoded by fsl_bytes_fossilize() in-place.
3619 inp must be a string encoded by fsl_bytes_fossilize(), and the
3620 decoding processes stops at the first unescaped NUL terminator.
3621 It has no error conditions except for !inp or if inp is not
3622 NUL-terminated, both of which invoke in undefined behaviour.
3623
3624 If resultLen is not NULL then *resultLen is set to the resulting string
3625 length.
3626
3627*/
3628FSL_EXPORT void fsl_bytes_defossilize( unsigned char * inp, fsl_size_t * resultLen );
3629
3630/**
3631 Defossilizes the contents of b. Equivalent to:
3632 fsl_bytes_defossilize( b->mem, &b->used );
3633*/
3635
3636/**
3637 Returns true if the input string contains only valid lower-case
3638 base-16 digits. If any invalid characters appear in the string,
3639 false is returned.
3640*/
3641FSL_EXPORT bool fsl_validate16(const char *zIn, fsl_size_t nIn);
3642
3643/**
3644 The input string is a base16 value. Convert it into its canonical
3645 form. This means that digits are all lower case and that conversions
3646 like "l"->"1" and "O"->"0" occur.
3647*/
3649
3650/**
3651 Decode a N-character base-16 number into base-256. N must be a
3652 multiple of 2. The output buffer must be at least N/2 characters
3653 in length. Returns 0 on success.
3654*/
3655FSL_EXPORT int fsl_decode16(const unsigned char *zIn, unsigned char *pOut, fsl_size_t N);
3656
3657/**
3658 Encode a N-digit base-256 in base-16. N is the byte length of pIn
3659 and zOut must be at least (N*2+1) bytes long (the extra is for a
3660 terminating NUL). Returns zero on success, FSL_RC_MISUSE if !pIn
3661 or !zOut.
3662*/
3663FSL_EXPORT int fsl_encode16(const unsigned char *pIn, unsigned char *zOut, fsl_size_t N);
3664
3665
3666/**
3667 Tries to convert the value of errNo, which is assumed to come
3668 from the global errno, to a fsl_rc_e code. If it can, it returns
3669 something approximating the errno value, else it returns dflt.
3670
3671 Example usage:
3672
3673 ```
3674 FILE * f = fsl_fopen("...", "...");
3675 int rc = f ? 0 : fsl_errno_to_rc(errno, FSL_RC_IO);
3676 ...
3677 ```
3678
3679 Why require the caller to pass in errno, instead of accessing it
3680 directly from this function? To avoid the the off-chance that
3681 something changes errno between the call and the conversion
3682 (whether or not that's possible is as yet undetermined). It can
3683 also be used by clients to map to explicit errno values to
3684 fsl_rc_e values, e.g. fsl_errno_to_rc(EROFS,-1) returns
3685 FSL_RC_ACCESS.
3686
3687 A list of the errno-to-fossil conversions:
3688
3689 - 0: FSL_RC_OK (0)
3690
3691 - EINVAL: FSL_RC_MISUSE (could arguably be FSL_RC_RANGE, though)
3692
3693 - ENOMEM: FSL_RC_OOM
3694
3695 - EACCES, EBUSY, EPERM, EROFS, EDQUOT, EAGAIN: FSL_RC_ACCESS
3696
3697 - EISDIR, ENOTDIR: FSL_RC_TYPE
3698
3699 - ENAMETOOLONG, ELOOP, ERANGE: FSL_RC_RANGE
3700
3701 - ENOENT: FSL_RC_NOT_FOUND
3702
3703 - EEXIST: FSL_RC_ALREADY_EXISTS
3704
3705 - EIO: FSL_RC_IO
3706
3707 Any other value for errNo causes dflt to be returned.
3708*/
3709FSL_EXPORT int fsl_errno_to_rc(int errNo, int dflt);
3710
3711/**
3712 Make the given string safe for HTML by converting every "<" into
3713 "&lt;", every ">" into "&gt;", every "&" into "&amp;", and
3714 encode '"' as &quot; so that it can appear as an argument to
3715 markup.
3716
3717 The escaped output is send to out(oState,...).
3718
3719 Returns 0 on success or if there is nothing to do (input has a
3720 length of 0, in which case out() is not called). Returns
3721 FSL_RC_MISUSE if !out or !zIn. If out() returns a non-0 code
3722 then that value is returned to the caller.
3723
3724 If n is negative, fsl_strlen() is used to calculate zIn's length.
3725*/
3726FSL_EXPORT int fsl_htmlize(fsl_output_f out, void * oState,
3727 const char *zIn, fsl_int_t n);
3728
3729/**
3730 Functionally equivalent to fsl_htmlize() but optimized to perform
3731 only a single allocation.
3732
3733 Returns 0 on success or if there is nothing to do (input has a
3734 length of 0). Returns FSL_RC_MISUSE if !p or !zIn, and
3735 FSL_RC_OOM on allocation error.
3736
3737 If n is negative, fsl_strlen() is used to calculate zIn's length.
3738*/
3740
3741/**
3742 Equivalent to fsl_htmlize_to_buffer() but returns the result as a
3743 new string which must eventually be fsl_free()d by the caller.
3744
3745 Returns NULL for invalid arguments or allocation error.
3746*/
3747FSL_EXPORT char *fsl_htmlize_str(const char *zIn, fsl_int_t n);
3748
3749/**
3750 If c is a character Fossil likes to HTML-escape, assigns *xlate
3751 to its transformed form, else set it to NULL. Returns 1 for
3752 untransformed characters and the strlen of *xlate for others.
3753 Bytes returned via xlate are static and immutable.
3754
3755 Results are undefined if xlate is NULL.
3756*/
3757FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate);
3758
3759
3760/** @enum fsl_diff2_flag_e
3761
3762 Flags for use with the 2021-era text-diff generation APIs
3763 (fsl_dibu and friends). This set of flags may still change
3764 considerably.
3765
3766 Maintenance reminders:
3767
3768 - Some of these values are holy and must not be changed without
3769 also changing the corresponding code in diff2.c.
3770
3771 - Where these entries semantically overlap with their
3772 older/deprecated fsl_diff_flag_e counterparts, they MUST (for the
3773 sake of avoiding client-side Grief) have the same values because
3774 some internal APIs are used by both of the diff APIs.
3775
3776 @see fsl_dibu_impl_flags_e
3777
3778 TODO?:
3779
3780 - Move the diff-builder-specific flags from here to, possibly, the
3781 fsl_dibu::implFlags member or a new flag member dedicated to this
3782 type of flag.
3783*/
3785/** Ignore end-of-line whitespace. Applies to all diff builders. */
3787/** Ignore all whitespace. Applies to all diff builders. */
3789/** Suppress optimizations (debug). Applies to
3790 all diff builders. */
3792/** Invert the diff. Applies to all diff builders. */
3794/** Use context line count even if it's zero. Applies to all diff
3795 builders. Normally a value of 0 is treated as the built-in
3796 default. */
3798/**
3799 Only calculate diff if it's not "too big." Applies to all diff
3800 builders and will cause the public APIs which hit this to return
3801 FSL_RC_RANGE.
3802*/
3804/**
3805 Strip trailing CR before diffing. Applies to all diff builders.
3806*/
3808/*
3809 ACHTUNG: do not use 0x2000 because it would semantically collide
3810 with FSL_DIFF_ANSI_COLOR.
3811*/
3812/**
3813 More precise but slower side-by-side diff algorithm, for diffs
3814 which use that.
3815*/
3817/**
3818 Tells diff builders which support it to include line numbers in
3819 their output.
3820*/
3822/**
3823 Tells diff builders which optionally support an "index" line
3824 to NOT include it in their output.
3825*/
3827
3828/**
3829 Reserved for client-defined diff builder use.
3830*/
3832/**
3833 Reserved for client-defined diff builder use.
3834*/
3836/**
3837 Reserved for client-defined diff builder use.
3838*/
3840/**
3841 Reserved for client-defined diff builder use.
3842*/
3844};
3845
3846/**
3847 Flags for use with various concrete fsl_dibu implementations.
3848 Specifically, these are flags for fsl_dibu::implFlags (as opposed
3849 to fsl_dibu::pimplFlags, which must not be modified by clients).
3850
3851 Note that it is perfectly legitimate for different entries to have
3852 the same values, but different semantics, so long as the different
3853 entries are specific to different fsl_dibu types.
3854*/
3856/**
3857 Tells the TCL diff builder that the complete output and each line
3858 should be wrapped in {...}.
3859*/
3861/**
3862 Tells the TCL diff builder that the squiggly braces embedded in any
3863 output (as opposed to the braces added by FSL_DIBU_TCL_BRACES)
3864 need to be backslash-escaped. Whether this is required depends on
3865 how the output will be used.
3866*/
3868/**
3869 Tells the TCL diff builder to generate a complete TCL/TK app as output.
3870 The resulting script can (if tcl and tk are installed) be run with
3871 tclsh to get a graphical diff.
3872
3873 Note that this flag includes both FSL_DIBU_TCL_BRACES and
3874 FSL_DIBU_TCL_BRACES_ESC.
3875*/
3877
3878};
3879
3880/**
3881 An instance of this class is used to convey certain state to
3882 fsl_dibu objects. Some of this state is configuration
3883 provided by the client and some is volatile, used for communicating
3884 common state to diff builder instances during the diff rendering
3885 process.
3886
3887 Certain fsl_dibu implementations may require that some
3888 ostensibly optional fields be filled out. Documenting that is TODO,
3889 as the builders get developed.
3890*/
3892 /**
3893 Flags from the fsl_diff2_flag_e enum.
3894 */
3895 uint32_t diffFlags;
3896 /**
3897 Number of lines of diff context (number of lines common to the
3898 LHS and RHS of the diff). Library-wide default is 5.
3899 */
3900 unsigned short contextLines;
3901 /**
3902 Maximum column width hint for side-by-side, a.k.a. split, diffs.
3903
3904 FSL_DIBU_SPLIT_TEXT truncates its content columns (as
3905 opposed to line numbers and its modification marker) to, at most,
3906 this width. By default it uses as much width as is necessary to
3907 render whole lines. It treats this limit as UTF8 characters, not
3908 bytes.
3909
3910 This is a hint, not a rule. A given diff builder is free to
3911 ignore it or to ignore values which are arbitrarily deemed "too
3912 small" or "too large."
3913 */
3914 unsigned short columnWidth;
3915 /**
3916 The filename of the object represented by the LHS of the
3917 diff. This is intentended for, e.g., generating header-style
3918 output. This may be NULL.
3919 */
3920 const char * nameLHS;
3921 /**
3922 The hash of the object represented by the LHS of the diff. This
3923 is intentended for, e.g., generating header-style output. This
3924 may be NULL.
3925 */
3926 const char * hashLHS;
3927 /**
3928 The filename of the object represented by the LHS of the
3929 diff. This is intentended for, e.g., generating header-style
3930 output. If this is NULL but nameLHS is not then they are assumed
3931 to have the same name.
3932 */
3933 const char * nameRHS;
3934 /**
3935 The hash of the object represented by the RHS of the diff. This
3936 is intentended for, e.g., generating header-style output. This
3937 may be NULL.
3938 */
3939 const char * hashRHS;
3940 /**
3941 Output destination. Any given builder might, depending on how it
3942 actually constructs the diff, buffer output and delay calling
3943 this until its finish() method is called.
3944
3945 Note that not all diff builders use this. e.g. a diff builder
3946 which outputs to an ncurses widget cannot do so via this method
3947 and instead has to use the drawing methods of that API. Thus is
3948 is legal for this method to be NULL for some builders.
3949 */
3951 /**
3952 State for this->out(). Ownership is unspecified by this
3953 interface: it is for use by this->out() but what is supposed to
3954 happen to it after this object is done with it depends on
3955 higher-level code.
3956 */
3957 void * outState;
3958 /**
3959 EXPERIMENTAL AND SUBJECT TO CHANGE.
3960
3961 Optional ANSI color control sequences to be injected into
3962 text-mode diff output by diff builders which support them. All
3963 members of this struct must either be NULL, an empty string, or a
3964 valid ANSI escape sequence. The reset option must be the escape
3965 sequence to reset either just the color or to reset all ANSI
3966 control attributes, depending on how the other members are
3967 set. If any member other than reset is set, all must be set.
3968
3969 The diff driver will treat any members of this which are NULL as
3970 empty strings to simplify diff builder color integration. The
3971 exception is the reset member - see its docs for details.
3972 */
3974 /**
3975 Color escape sequence for inserted lines.
3976 */
3977 char const * insertion;
3978 /**
3979 Color escape sequence for edited or replaced lines. This option
3980 might be ignored, depending on how the renderer works. Some
3981 will render edits as a deletion/insertion pair.
3982 */
3983 char const * edit;
3984 /**
3985 Color escape sequence for inserted lines.
3986 */
3987 char const * deletion;
3988 /**
3989 Escape sequence to reset colors. If reset is empty or NULL and
3990 any others are not then reset is automatically treated as if it
3991 were the ANSI code to reset all color attributes.
3992 */
3993 char const * reset;
3995};
3996
3997/** Convenience typedef. */
3999
4000/** Initialized-with-defaults fsl_dibu_opt structure, intended for
4001 const-copy initialization. */
4002#define fsl_dibu_opt_empty_m {\
4003 0/*diffFlags*/, 5/*contextLines*/, 0/*columnWidth*/,\
4004 NULL/*nameLHS*/,NULL/*hashLHS*/, \
4005 NULL/*nameRHS*/, NULL/*hashRHS*/, \
4006 NULL/*out*/, NULL/*outState*/, \
4007 {/*ansiColor*/ ""/*insertion*/,""/*edit*/,""/*deletion*/,\
4008 ""/*reset*/} \
4009}
4010
4011/** Initialized-with-defaults fsl_dibu_opt structure, intended for
4012 non-const copy initialization. */
4013extern const fsl_dibu_opt fsl_dibu_opt_empty;
4014
4015/**
4016 Information about each line of a file being diffed.
4017
4018 This type is only in the public API for use by the fsl_dibu
4019 interface, specifically for use with fsl_dline_change_spans(). It
4020 is not otherwise intended for public use. None of its members are
4021 considered even remotely public except for this->z and this->n.
4022*/
4024 /**
4025 The text of the line. Owned by higher-level code. Not
4026 necessarily NUL-terminated: this->n holds its length.
4027 */
4028 const char *z;
4029 /** Number of bytes of z which belong to this line. */
4030 unsigned short n;
4031 // All members after this point are strictly for internal use only.
4032 /** Index of first non-space char. */
4033 unsigned short indent;
4034 /** Number of bytes without leading/trailing space. */
4035 unsigned short nw;
4036 /** Hash of the line. Lower X bits are the length. */
4037 uint64_t h;
4038 /** 1+(Index of next line with same the same hash) */
4039 unsigned int iNext;
4040 /**
4041 An array of fsl_dline elements serves two purposes. The fields
4042 above are one per line of input text. But each entry is also
4043 a bucket in a hash table, as follows:
4044 */
4045 unsigned int iHash; /* 1+(first entry in the hash chain) */
4046};
4047
4048/**
4049 Convenience typedef.
4050*/
4051typedef struct fsl_dline fsl_dline;
4052/** Initialized-with-defaults fsl_dline structure, intended for
4053 const-copy initialization. */
4054#define fsl_dline_empty_m {NULL,0U,0U,0U,0U,0U,0U}
4055/** Initialized-with-defaults fsl_dline structure, intended for
4056 non-const copy initialization. */
4057extern const fsl_dline fsl_dline_empty;
4058
4059/**
4060 Maximum number of change spans for fsl_dline_change.
4061*/
4062#define fsl_dline_change_max_spans 8
4063
4064/**
4065 This "mostly-internal" type describes zero or more (up to
4066 fsl_dline_change_max_spans) areas of difference between two lines
4067 of text. This type is only in the public API for use with concrete
4068 fsl_dibu implementations.
4069*/
4071 /** Number of change spans (number of used elements in this->a). */
4072 unsigned char n;
4073 /** Array of change spans, in left-to-right order */
4075 /* Reminder: int instead of uint b/c some ported-in algos use
4076 negatives. */
4077 /** Byte offset to start of a change on the left */
4079 /** Length of the left change in bytes */
4081 /** Byte offset to start of a change on the right */
4083 /** Length of the change on the right in bytes */
4085 /** True if this change is known to have no useful subdivs */
4088};
4089
4090/**
4091 Convenience typedef.
4092*/
4094
4095/** Initialized-with-defaults fsl_dline_change structure, intended for
4096 const-copy initialization. */
4097#define fsl_dline_change_empty_m { \
4098 0, { \
4099 {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, \
4100 {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} \
4101 } \
4102}
4103
4104/** Initialized-with-defaults fsl_dline_change structure, intended for
4105 non-const copy initialization. */
4107
4108/**
4109 Given two lines of a diff, this routine computes a set of changes
4110 between those lines for display purposes and writes a description
4111 of those changes into the 3rd argument. After returning, p->n
4112 contains the number of elements in p->a which were populated by
4113 this routine.
4114
4115 This function is only in the public API for use with
4116 fsl_dibu objects. It is not a requirement for such objects
4117 but can be used to provide more detailed diff changes than marking
4118 whole lines as simply changed or not.
4119*/
4121 const fsl_dline *pRight,
4122 fsl_dline_change * p);
4123
4124/**
4125 Compares two fsl_dline instances using memcmp() semantics,
4126 returning 0 if they are equivalent.
4127
4128 @see fsl_dline_cmp_ignore_ws()
4129*/
4131 const fsl_dline * pB);
4132
4133/**
4134 Counterpart of fsl_dline_cmp() but ignores all whitespace
4135 when comparing for equivalence.
4136*/
4138 const fsl_dline * pB);
4139
4140/**
4141 Breaks the first n bytes of z into an array of fsl_dline records,
4142 each of which refers back to z (so it must remain valid for their
4143 lifetime). If n is negative, fsl_strlen() is used to calculate
4144 z's length.
4145
4146 The final argument may be any flags from the fsl_diff2_flag_e
4147 enum, but only the following flags are honored:
4148
4149 - FSL_DIFF2_STRIP_EOLCR
4150 - FSL_DIFF2_IGNORE_EOLWS
4151 - FSL_DIFF2_IGNORE_ALLWS
4152
4153 On success, returns 0, assigns *pnLine to the number of lines, and
4154 sets *pOut to the array of fsl_dline objects, transfering ownership
4155 to the caller, who must eventually pass it to fsl_free() to free
4156 it.
4157
4158 If z is NULL or n is 0, the input is assumed to be empty, 0 is returned,
4159 (*pOut) will be set to NULL, and (*pnLine) will be set to 0.
4160
4161 On error, neither (*pnLine) nor (*pOut) are modified and returns one
4162 of:
4163
4164 - FSL_RC_DIFF_BINARY if the input appears to be non-text.
4165 - FSL_RC_OOM on allocation error.
4166*/
4168 uint32_t *pnLine,
4169 fsl_dline **pOut, uint64_t diff2Flags);
4170
4171/** Convenience typedef. */
4172typedef struct fsl_dibu fsl_dibu;
4173
4174/**
4175 This class is the basis of libfossil's port of the diff engine
4176 added to fossil(1) in 2021-09, colloquially known as the "diff
4177 builder."
4178
4179 A diff builder is an object responsible for formatting low-level
4180 diff info another form, typically for human readability but also
4181 for machine readability (patches). The library generates a
4182 low-level diff then feeds that through an algorithm which
4183 determines which methods of this class to call, delegating all
4184 rendering of the diff to an instance of this class.
4185
4186 The internal APIs which drive each instance of this class guaranty
4187 that if any method of this class returns non-0 (an error code) then
4188 no futher methods will be called except for finalize().
4189*/
4190struct fsl_dibu {
4191 /**
4192 Config info, owned by higher-level routines. Every diff builder
4193 requires one of these but not all options are relevant for all
4194 builders.
4195
4196 Note that the diff driver may make a bitwise copy of this object
4197 and use _that_ one for the actual diff generation. That is,
4198 methods of this class must never assume that this member's
4199 pointer refers to a specific object. (This leeway is necessary in
4200 order to implement diff inversion (swapping the LHS/RHS of a
4201 diff).)
4202 */
4204 /**
4205 Can optionally be set by factory functions to some internal
4206 opaque value, so that non-member routines specific to that type can determine
4207 whether any given builder is of the proper type.
4208 */
4209 void const * typeID;
4210 /**
4211 If not NULL, this is called once per pass per diff to give the
4212 builder a chance to perform any bootstrapping initialization or
4213 header output. At the point this is called, this->cfg is assumed
4214 to have been filled out properly. Diff builder implementations
4215 which require dynamic resource allocation may perform it here or
4216 in their factory routine(s).
4217
4218 b->lnLHS and b->lnRHS will be set to 0 before each call.
4219
4220 This method should also reset any dynamic state of a builder so
4221 that it may be reused for subsequent diffs. This enables the API
4222 to use a single builder for a collection of logically grouped
4223 files without having to destroy and reallocate the builder.
4224
4225 Must return 0 on success, non-0 on error. If it returns non-0,
4226 the only other method of the instance which may be legally called
4227 is finalize().
4228
4229 The diff driver sets this->lnLHS and this->lnRHS to 0 before
4230 calling this.
4231 */
4232 int (*start)(fsl_dibu * b);
4233
4234 /**
4235 If this is not NULL, it is called one time at the start of each
4236 chunk of diff for a given file and is passed the line number of
4237 each half of the diff and the number of lines in that chunk for
4238 that half (including insertions and deletions). This is primarily
4239 intended for generating conventional unified diff chunk headers
4240 in the form:
4241
4242 ```
4243 @@ -A,B +C,D @@
4244 ```
4245
4246 The inclusion of this method in an object might preclude certain
4247 other diff formatting changes which might otherwise apply.
4248 Notably, if the span between two diff chunks is smaller than the
4249 context lines count, the diff builder driver prefers to merge
4250 those two chunks together. That "readability optimization" is
4251 skipped when this method is set because this method may otherwise
4252 report that lines are being skipped which then subsequently get
4253 output by the driver.
4254
4255 Must return 0 on success, non-0 on error.
4256 */
4258 uint32_t A, uint32_t B,
4259 uint32_t C, uint32_t D);
4260
4261 /**
4262 Tells the builder that n lines of common output are to be
4263 skipped. How it represents this is up to the impl. Must return 0
4264 on success, non-0 on error.
4265
4266 Typical common implementation details:
4267
4268 - Increment both this->lnLHS and this->lnRHS by n.
4269 */
4270 int (*skip)(fsl_dibu* , uint32_t n);
4271 /**
4272 Tells the builder that the given line represents one line of
4273 common output. Must return 0 on success, non-0 on error.
4274
4275 Typical common implementation details:
4276
4277 - Increment both this->lnLHS and this->lnRHS by 1.
4278 */
4279 int (*common)(fsl_dibu* , fsl_dline const * line);
4280 /**
4281 Tells the builder that the given line represents an "insert" into
4282 the RHS. Must return 0 on success, non-0 on error.
4283
4284 Typical common implementation details:
4285
4286 - Increment this->lnRHS by 1.
4287 */
4288 int (*insertion)(fsl_dibu* , fsl_dline const * line);
4289 /**
4290 Tells the builder that the given line represents a "deletion" - a
4291 line removed from the LHS. Must return 0 on success, non-0 on
4292 error.
4293
4294 Typical common implementation details:
4295
4296 - Increment this->lnLHS by 1.
4297 */
4298 int (*deletion)(fsl_dibu* , fsl_dline const * line);
4299 /**
4300 Tells the builder that the given line represents a replacement
4301 from the LHS to the RHS. Must return 0 on success, non-0 on
4302 error. This differs from an "edit" in that the line being
4303 replaced seems to have on relationship to the replacement. Even
4304 so, builders are free to represent replacements and edits
4305 identically, and are free to represent either or both as a pair
4306 of deletion/insertion operations.
4307
4308 Typical common implementation details:
4309
4310 - Increment both this->lnLHS and this->lnRHS by 1.
4311 */
4312 int (*replacement)(fsl_dibu* , fsl_dline const * lineLhs,
4313 fsl_dline const * lineRhs);
4314 /**
4315 Tells the builder that the given line represents an "edit" from
4316 the LHS to the RHS. Must return 0 on success, non-0 on
4317 error. Builders are free, syntax permitting, to use the
4318 fsl_dline_change_spans() API to elaborate on edits for display
4319 purposes, to treat it identically to this->replacement(), or to
4320 treat this as a single pair of calls to this->deletion() and
4321 this->insertion(). In the latter case they simply need to pass
4322 lineLhs to this->deletion() and lineRhs to this->insertion().
4323
4324 Typical common implementation details:
4325
4326 - Increment both this->lnLHS and this->lnRHS by 1.
4327 */
4328 int (*edit)(fsl_dibu* , fsl_dline const * lineLhs,
4329 fsl_dline const * lineRhs);
4330 /**
4331 Must "finish" the diff process. Depending on the diff impl, this
4332 might flush any pending output or may be a no-op. This is only
4333 called if the rest of the diff was generated without producing an
4334 error result.
4335
4336 This member may be NULL.
4337
4338 Implementations are free to collect all of their output in an
4339 internal representation and delay flushing it until this routine
4340 is called.
4341
4342 Must return 0 on success, non-0 on error (e.g. output flushing
4343 fails).
4344
4345 Minor achtung: for a multi-file diff run, this gets called after
4346 each file. The library does not have enough information to know
4347 when a builder is "done for good" and if a custom builder
4348 requires, e.g., extra post-diff-loop processing, the client will
4349 have to take care of that themselves.
4350 */
4351 int (*finish)(fsl_dibu* b);
4352 /**
4353 This optional method is similar to this->finish() but it is not
4354 called by the library. It is intended to be called, if it's not
4355 NULL, by the client after they are done, e.g., looping over a
4356 series of diffs with the same builder. Some builders can use this
4357 to flush any final state, e.g. dumping out change count totals or
4358 some such.
4359
4360 As an example, the TCL/TK-based builder, when the FSL_DIBU_TCL_TK
4361 flag is set on this->implFlag, embeds a TK script in the output
4362 from this method.
4363 */
4364 int (*finally)(fsl_dibu* b);
4365 /**
4366 Must free any state owned by this builder, including the builder
4367 object. It must not generate any output.
4368 */
4369 void (*finalize)(fsl_dibu* );
4370 /**
4371 If true, this builder gets passed through the diff generation
4372 process twice. See this->passNumber for details.
4373 */
4375 /**
4376 Gets set to the "pass number" immediately before this->start() is
4377 called, starting with pass number 1. This value is only relevant
4378 for two-pass builders, which can use this to control their mode
4379 of operation, e.g. data collection in pass 1 and actual work in
4380 pass 2. Note that all of the diff-building API methods are called
4381 for both passes, including start() and finish(). Only finalize()
4382 and finally() are not affected by this.
4383 */
4384 unsigned short passNumber;
4385 /**
4386 Impl-specific diff-generation state. If it is owned by this
4387 instance then this->finalize() must clean it up.
4388 */
4389 void * pimpl;
4390 /**
4391 Space for private, implementation-specific flags, e.g. for
4392 tracking basic output state, e.g. of opening/closing tags. This
4393 must not be modified by clients.
4394 */
4395 unsigned int pimplFlags;
4396 /**
4397 Space for implementation-specific flags which clients may set to
4398 modify the dibu's behaviour. This is different from
4399 fsl_dibu_opt::diffFlags in that these flags are specific to a
4400 given dibu type. See the fsl_dibu_impl_flags_e enum for the list
4401 of flags for the library-provided diff builders.
4402 */
4403 unsigned int implFlags;
4404 /**
4405 A place to store the number of files seen by this builder so far,
4406 for builders which need to distinguish that somehow (e.g. adding
4407 a separator before each file after the first). Implementations
4408 which use this should increment it in their start() method.
4409
4410 Maintenance reminder/TODO: we can't increment this from the main
4411 diff driver because... we possibly could, but we'd need to patch
4412 the various diff builders which currently do this themselves.
4413 The main diff driver doesn't have enough info to know when to set
4414 it, though. That "could" be done in this->finally() but that
4415 method is optional.
4416 */
4417 uint32_t fileCount;
4418 /**
4419 Number of lines seen of the LHS content. It is up to the concrete
4420 builder impl to update this if it's needed. The core diff driver
4421 sets this to 0 before calling this->start().
4422 */
4423 uint32_t lnLHS;
4424 /**
4425 Number of lines seen of the RHS content. It is up to the concrete
4426 builder impl to update this if it's needed. The core diff driver
4427 sets this to 0 before calling this->start().
4428 */
4429 uint32_t lnRHS;
4430
4431 /**
4432 Metrics maintained by the core diff algorithm. These are updated
4433 during the first pass through a given fsl_diff_v2() run. They are
4434 NEVER reset by the builder algo because it cannot know if the
4435 user wants a running total or a per-file total. Clients running
4436 diffs in a loop may want to reset them on each loop. The simplest
4437 way is to cop fsl_dibu_empty.metrics over them. It is legal for a
4438 given builder to reset these in their start(), finish(), or
4439 finally() methods, depending on how the builder is used.
4440
4441 Note that all metrics apply to the RHS version, not the LHS.
4442 */
4443 struct {
4444 /** Number of lines inserted performed so far. */
4445 uint32_t insertions;
4446 /** Number of lines deleted so far. */
4447 uint32_t deletions;
4448 /** Number of line-level edits performed so far. */
4449 uint32_t edits;
4450 /** Number of line replacements performed so far.
4451 These are different from edits in that the whole line
4452 differs in the LHS/RHS. */
4455};
4456
4457/** Initialized-with-defaults fsl_dibu structure, intended for
4458 const-copy initialization. */
4459#define fsl_dibu_empty_m { \
4460 NULL/*opt*/,NULL/*typeID*/, \
4461 NULL/*start()*/,NULL/*chunkHeader()*/,NULL/*skip()*/, NULL/*common()*/, \
4462 NULL/*insertion()*/,NULL/*deletion()*/, NULL/*replacement()*/, \
4463 NULL/*edit()*/, NULL/*finish()*/, NULL/*finally()*/,NULL/*finalize()*/, \
4464 false/*twoPass*/,0U/*passNumber*/, \
4465 NULL/*pimpl*/, 0U/*pimplFlags*/,0U/*implFlags*/,0U/*fileCount*/, \
4466 0/*lnLHS*/,0/*lnRHS*/, \
4467 {/*metrics*/0,0,0,0} \
4468}
4469
4470/** Initialized-with-defaults fsl_dibu structure, intended for
4471 non-const copy initialization. */
4472extern const fsl_dibu fsl_dibu_empty;
4473
4474/**
4475 Type IDs for use with fsl_dibu_factory().
4476*/
4478/**
4479 Sentinel entry.
4480*/
4482/**
4483 A "dummy" diff builder intended only for testing the
4484 fsl_dibu interface and related APIs. It does not produce
4485 output which is generically useful.
4486*/
4488/**
4489 Generates diffs in a compact low(ist)-level form originally
4490 designed for use by diff renderers implemented in JavaScript.
4491
4492 This diff builder outputs a JSON object with the following
4493 properties:
4494
4495 - hashLHS, hashRHS: the hashes of the LHS/RHS content.
4496
4497 - nameLHS, nameRHS: the filenames of the LHS/RHS. By convention, if
4498 the RHS is NULL but the LHS is not, both sides have the same
4499 name.
4500
4501 - diff: raw diff content, an array with the structure described
4502 below.
4503
4504 Note that it is legal for the names and hashes to be "falsy" (null,
4505 not set, or empty strings).
4506
4507 The JSON array consists of integer opcodes with each opcode
4508 followed by zero or more arguments:
4509
4510 ```
4511 Syntax Mnemonic Description
4512
4513 ----------- -------- --------------------------
4514 0 END This is the end of the diff.
4515 1 INTEGER SKIP Skip N lines from both files.
4516 2 STRING COMMON The line STRING is in both files.
4517 3 STRING INSERT The line STRING is in only the right file.
4518 4 STRING DELETE The line STRING is in only the left file.
4519 5 SUBARRAY EDIT One line is different on left and right.
4520 ```
4521
4522 The SUBARRAY is an array of 3*N+1 strings with N>=0. The triples
4523 represent common-text, left-text, and right-text. The last string
4524 in SUBARRAY is the common-suffix. Any string can be empty if it
4525 does not apply.
4526*/
4528
4529/**
4530 A diff builder which produces output compatible with the patch(1)
4531 command. Its output is functionally identical to fossil(1)'s
4532 default diff output except that by default includes an Index line
4533 at the top of each file (use the FSL_DIFF2_NOINDEX flag in its
4534 fsl_dibu_opt::diffFlags to disable that).
4535
4536 Supported flags:
4537
4538 - FSL_DIFF2_LINE_NUMBERS (makes it incompatible with patch(1))
4539 - FSL_DIFF2_NOINDEX
4540*/
4542
4543/**
4544 A diff builder which outputs a description of the diff in a
4545 TCL-readable form. It requires external TCL code in order to
4546 function.
4547*/
4549/**
4550 A pain-text side-by-side (a.k.a. split) diff view. This diff always
4551 behaves as if the FSL_DIFF2_LINE_NUMBERS flag were set because its
4552 output is fairly useless without line numbers. It optionally
4553 supports ANSI coloring.
4554*/
4556};
4558
4559/**
4560 A factory for creating fsl_dibu instances of types which
4561 are built in to the library. This does not preclude the creation of
4562 client-side diff builders (e.g. ones which write to ncurses widgets
4563 or similar special-case output).
4564
4565 On success, returns 0 and assigns *pOut to a new builder instance
4566 which must eventually be freed by calling its pOut->finalize()
4567 method. On error, returns non-0 and *pOut is not modified. Error
4568 codes include FSL_RC_OOM (alloc failed) and FSL_RC_TYPE (unknown
4569 type ID), FSL_RC_TYPE (type is not (or not yet) implemented).
4570*/
4572 fsl_dibu **pOut );
4573
4574/**
4575 Base allocator for fsl_dibu instances. If extra is >0 then
4576 that much extra space is allocated as part of the same memory block
4577 and the pimpl member of the returned object is pointed to that
4578 space. Example (OOM handling elided for legibility):
4579
4580 ```
4581 struct MyState { int x; int y; };
4582 typedef struct MyState MyState;
4583 fsl_dibu * b = fsl_dibu_alloc(sizeof(MyState));
4584 MyState * my = (MyState*)b->pimpl;
4585 my->x = 1;
4586 my->y = 2;
4587 ... populate b's members ...
4588 ... use b, then clean it up ...
4589 b->finalize(b);
4590 ```
4591
4592 From within b's methods, the custom state can be accessed via its
4593 `pimpl` member.
4594
4595 @see fsl_dibu_finalizer()
4596*/
4598
4599/**
4600 This is a generic finalizer function for use as a
4601 fsl_dibu::finalize() method. It simply zeroes out b and
4602 passes it fsl_free(). This is suitable for builders created using
4603 fsl_dibu_alloc() _only_ if their custom state manages no
4604 extra memory. If they manage any custom memory then the require a
4605 custom, type-specific finalizer method.
4606*/
4608
4609/**
4610 This counterpart of fsl_diff_text() defines its output format in
4611 terms of a fsl_dibu instance which the caller must provide.
4612 The caller is responsible for pointing pBuilder->cfg to a
4613 configuration object suitable for the desired diff. In particular,
4614 pBuilder->cfg->out and (if necessary) pBuilder->cfg->outState must
4615 be set to non-NULL values.
4616
4617 This function generates a low-level diff of two versions of content,
4618 contained in the given buffers, and passes that diff through the
4619 given diff builder to format it.
4620
4621 Returns 0 on success. On error, it is not generally knowable whether
4622 or not any diff output was generated.
4623
4624 The builder may produce any error codes it wishes, in which case
4625 they are propagated back to the caller. Common error codes include:
4626
4627 - FSL_RC_OOM if an allocation fails.
4628
4629 - FSL_RC_RANGE if the diff is "too big" and
4630 pBuilder->config->diffFlags contains the FSL_DIFF2_NOTTOOBIG flag.
4631
4632 - FSL_RC_DIFF_BINARY if the to-diff content appears to be binary,
4633 noting that "appears to be" is heuristric-driven and subject to
4634 false positives. Specifically, files with extremely long lines will
4635 be recognized as binary (and are, in any case, generally less than
4636 useful for most graphical diff purposes).
4637
4638 @see fsl_dibu_factory()
4639 @see fsl_diff_text()
4640 @see fsl_diff_v2_raw()
4641*/
4643 fsl_buffer const * pv2,
4644 fsl_dibu * pBuilder);
4645
4646/**
4647 Performs a diff, as for fsl_diff_v2(), but returns the results in
4648 the form of an array of COPY, DELETE, INSERT triples terminated by
4649 3 entries with the value 0.
4650
4651 Each triple in the list specifies how many *lines* of each half of
4652 the diff (the first 2 arguments to this function) to COPY as-is
4653 (common code), DELETE (exists in the LHS but not in the RHS), and
4654 INSERT (exists in the RHS but not in the LHS). By breaking the
4655 input into lines and following these values, a line-level text-mode
4656 diff of the two blobs can be generated.
4657
4658 See fsl_diff_v2() for the details, all of which apply except for
4659 the output:
4660
4661 - cfg may be NULL, in which case fsl_dibu_opt_empty is used.
4662
4663 - cfg->out is ignored.
4664
4665 - On success, *outRaw is assigned to the output array and ownership
4666 of it is transfered to the caller, who must eventually pass it to
4667 fsl_free() to free it.
4668
4669*/
4671 fsl_buffer const * pv2,
4672 fsl_dibu_opt const * cfg,
4673 int **outRaw );
4674
4675/**
4676 If zDate is an ISO8601-format string, optionally with a .NNN
4677 fractional suffix, then this function returns true and sets
4678 *pOut (if pOut is not NULL) to the corresponding Julian
4679 value. If zDate is not an ISO8601-format string then this
4680 returns false and pOut is not modified.
4681
4682 This function does NOT confirm that zDate ends with a NUL
4683 byte. i.e. if passed a valid date string which has trailing
4684 bytes after it then those are simply ignored. This is so that it
4685 can be used to read subsets of larger strings.
4686
4687 Achtung: this calculation may, due to voodoo-level
4688 floating-point behaviours, differ by a small fraction of a point
4689 (at the millisecond level) for a given input compared to other
4690 implementations (e.g. sqlite's strftime() _might_ differ by a
4691 millisecond or two or _might_ not). Thus this routine should not
4692 be used when 100% round-trip fidelity is required, but is close
4693 enough for routines which do not require 100% millisecond-level
4694 fidelity in time conversions.
4695
4696 @see fsl_julian_to_iso8601()
4697*/
4698FSL_EXPORT bool fsl_iso8601_to_julian( char const * zDate, double * pOut );
4699
4700/**
4701 Converts the Julian Day J to an ISO8601 time string. If addMs is
4702 true then the string includes the '.NNN' fractional part, else
4703 it will not. This function writes (on success) either 20 or 24
4704 bytes (including the terminating NUL byte) to pOut, depending on
4705 the value of addMs, and it is up to the caller to ensure that
4706 pOut is at least that long.
4707
4708 Returns true (non-0) on success and the only error conditions
4709 [it can catch] are if pOut is NULL, J is less than 0, or
4710 evaluates to a time value which does not fit in ISO8601
4711 (e.g. only years 0-9999 are supported).
4712
4713 @see fsl_iso8601_to_julian()
4714*/
4715FSL_EXPORT bool fsl_julian_to_iso8601( double J, char * pOut, bool addMs );
4716
4717/**
4718 Returns the Julian Day time J value converted to a Unix Epoch
4719 timestamp. It assumes 86400 seconds per day and does not account
4720 for leap seconds, leap years, leap frogs, or any other kind of
4721 leap, up to and including leaps of faith.
4722*/
4724
4725/**
4726 Performs a chdir() to the directory named by zChDir.
4727
4728 Returns 0 on success. On error it tries to convert the
4729 underlying errno to one of the FSL_RC_xxx values, falling
4730 back to FSL_RC_IO if it cannot figure out anything more
4731 specific.
4732*/
4733FSL_EXPORT int fsl_chdir(const char *zChDir);
4734
4735/**
4736 Works like fsl_chdir(zTo) but passes (zCurrent,nCurrent,NULL) to
4737 fsl_getcwd() to save the current dir name. Returns non-0 if either
4738 fsl_getcwd() or fsl_chdir() fails. To "pop" the dir just
4739 fsl_chdir() to zCurrent.
4740*/
4741FSL_EXPORT int fsl_chdir2(const char *zTo, char * zCurrent, fsl_size_t nCurrent);
4742
4743/**
4744 A custom strftime() implementation.
4745
4746 dest must be valid memory at least destLen bytes long. The result
4747 will be written there.
4748
4749 fmt must contain the format string. See the source file strftime.c
4750 for the complete list of format specifiers and their descriptions.
4751
4752 timeptr must be the time the caller wants to format.
4753
4754 Returns 0 if any arguments are NULL.
4755
4756 On success it returns the number of bytes written to dest, not
4757 counting the terminating NUL byte (which it also writes). It
4758 returns 0 on any error, and the client may need to distinguish
4759 between real errors and (destLen==0 or !*fmt), both of which could
4760 also look like errors.
4761
4762 TODOs:
4763
4764 - Refactor this to take a callback or a fsl_buffer, so that we can
4765 format arbitrarily long output.
4766
4767 - Refactor it to return an integer error code.
4768
4769 (This implementation is derived from public domain sources
4770 dating back to the early 1990's.)
4771*/
4773 const char *format,
4774 const struct tm *timeptr);
4775
4776/**
4777 A convenience form of fsl_strftime() which takes its timestamp in
4778 the form of a Unix Epoch time. See fsl_strftime() for the
4779 semantics of the first 3 arguments and the return value. If
4780 convertToLocal is true then epochTime gets converted to local
4781 time (via, oddly enough, localtime(3)), otherwise gmtime(3) is
4782 used for the conversion.
4783*/
4785 char const * format,
4786 fsl_time_t epochTime,
4787 bool convertToLocal);
4788
4789
4790/**
4791 A convenience form of fsl_strftime() which assumes that the
4792 formatted string is of "some reasonable size" and appends its
4793 formatted representation to b. Returns 0 on success, non-0 on
4794 error. If any argument is NULL or !*format then FSL_RC_MISUSE is
4795 returned. FSL_RC_RANGE is returned if the underlying call to
4796 fsl_strftime() fails (which it will if the format string
4797 resolves to something "unususually long"). It returns FSL_RC_OOM
4798 if appending to b fails due to an allocation error.
4799*/
4801 char const * format,
4802 const struct tm *timeptr);
4803
4804/**
4805 "whence" values for use with fsl_buffer_seek(). They are analog to
4806 the "whence" argument of fseek(2) but are not guaranteed to have
4807 the same values.
4808*/
4815
4816/**
4817 "Seeks" b's internal cursor to a position specified by the given offset
4818 from either the current cursor position (FSL_BUFFER_SEEK_CUR), the start
4819 of the buffer (FSL_BUFFER_SEEK_SET), or the end (FSL_BUFFER_SEEK_END).
4820 If the cursor would be placed out of bounds, it will be placed at the start
4821 resp. end of the buffer.
4822
4823 The "end" of a buffer is the value of its fsl_buffer::used member,
4824 i.e. its one-after-the-end marker, as opposed to the at-the-end
4825 marker. That is: a seek to FSL_BUFFER_SEEK_END with an offset of -1
4826 would leave the cursor at the last available byte, not
4827 one-past-the-end.
4828
4829 Returns the new position.
4830
4831 Note that most buffer algorithms, e.g. fsl_buffer_append(), do not
4832 modify the cursor. Only certain special-case algorithms use it.
4833
4834 @see fsl_buffer_tell()
4835 @see fsl_buffer_rewind()
4836*/
4838 fsl_buffer_seek_e whence);
4839
4840/**
4841 Returns the buffer's current cursor position.
4842
4843 @see fsl_buffer_rewind()
4844 @see fsl_buffer_seek()
4845*/
4847
4848/**
4849 Resets b's cursor to the beginning of the buffer.
4850
4851 @see fsl_buffer_tell()
4852 @see fsl_buffer_seek()
4853*/
4855
4856/**
4857 Read from buf until consuming a character matching delim, which must
4858 be representable as an unsigned char. The consumed bytes, including any
4859 matching delim character, are stored in *ret, and a terminating NUL
4860 added when the delimiter or end-of-buffer is encountered.
4861
4862 If *retsz is non-zero, *ret must either be pre-allocated to at least
4863 *retsz bytes, or be a NULL pointer. *ret must be passable to fsl_free();
4864 it is grown as needed as if by fsl_realloc() and *retsz updated with
4865 its new size. It is the caller's responsiblity to fsl_free() *ret when
4866 it is no longer needed. Even on failure, *ret may be updated.
4867
4868 Return the number of bytes read, including any matched delim character.
4869 If no bytes were read and the stream is at end-of-buffer, return -1.
4870 If an error occurs, return -1 and set buf->errCode to indicate the error.
4871
4872 n.b. This routine matches getdelim(3) semantics. Callers must check
4873 buf->errCode to distinguish between end-of-buffer and error.
4874 https://pubs.opengroup.org/onlinepubs/9799919799/functions/getdelim.html
4875
4876 Example:
4877
4878 ```
4879 char *line = NULL;
4880 size_t sz = 0;
4881 ssize_t len;
4882
4883 while ((len = fsl_buffer_getdelim(&line, &sz, '\n', &buf)) != -1)
4884 fprintf(stdout, "line (%ld bytes): %s\n", len, line);
4885
4886 fsl_free(line);
4887 if (fsl_buffer_err(&buf))
4888 errx(buf.errCode, "fsl_buffer_getdelim: %s", fsl_rc_cstr(buf.errCode));
4889 ```
4890
4891 @see fsl_buffer_getline()
4892*/
4893FSL_EXPORT fsl_int_t fsl_buffer_getdelim(char **ret, size_t *retsz,
4894 int delim, fsl_buffer *buf);
4895
4896/**
4897 Equivalent to fsl_buffer_getdelim() with `delim` equal to '\n'.
4898
4899 @see fsl_buffer_getdelim()
4900*/
4901FSL_EXPORT fsl_int_t fsl_buffer_getline(char **ret, size_t *retsz,
4902 fsl_buffer *buf);
4903
4904/**
4905 The "Path Finder" class is a utility class for searching the
4906 filesystem for files matching a set of common prefixes and/or
4907 suffixes (i.e. directories and file extensions).
4908
4909 Example usage:
4910
4911 ```
4912 fsl_pathfinder pf = fsl_pathfinder_empty;
4913 int rc;
4914 char const * found = NULL;
4915 rc = fsl_pathfinder_ext_add( &pf, ".doc" );
4916 if(rc) { ...error... }
4917 // The following error checks are elided for readability:
4918 rc = fsl_pathfinder_ext_add( &pf, ".txt" );
4919 rc = fsl_pathfinder_ext_add( &pf, ".wri" );
4920 rc = fsl_pathfinder_dir_add( &pf, "." );
4921 rc = fsl_pathfinder_dir_add( &pf, "/my/doc/dir" );
4922 rc = fsl_pathfinder_dir_add( &pf, "/other/doc/dir" );
4923
4924 rc = fsl_pathfinder_search( &pf, "MyDoc", &found, NULL);
4925 if(0==rc){ assert(NULL!=found); }
4926
4927 // Eventually clean up:
4928 fsl_pathfinder_clear(&pf);
4929 ```
4930
4931 @see fsl_pathfinder_dir_add()
4932 @see fsl_pathfinder_ext_add()
4933 @see fsl_pathfinder_clear()
4934 @see fsl_pathfinder_search()
4935*/
4937 /**
4938 Holds the list of search extensions. Each entry
4939 is a (char *) owned by this object.
4940 */
4942 /**
4943 Holds the list of search directories. Each entry is a (char *)
4944 owned by this object.
4945 */
4947 /**
4948 Used to build up a path string during fsl_pathfinder_search(),
4949 and holds the result of a successful search. We use a buffer,
4950 as opposed to a simple string, because (A) it simplifies the
4951 search implementation and (B) reduces allocations (it gets
4952 reused for each search).
4953 */
4955};
4956
4958/**
4959 Initialized-with-defaults fsl_pathfinder instance, intended for
4960 const copy initialization.
4961*/
4962#define fsl_pathfinder_empty_m {\
4963 .ext = fsl_list_empty_m, \
4964 .dirs = fsl_list_empty_m, \
4965 .buf = fsl_buffer_empty_m \
4966}
4967
4968/**
4969 Initialized-with-defaults fsl_pathfinder instance, intended for
4970 copy initialization.
4971*/
4973
4974/**
4975 Frees all memory associated with pf, but does not free pf.
4976 Is a no-op if pf is NULL.
4977*/
4979
4980/**
4981 Equivalent to fsl_pathfinder_dir_add2() with -1 as a final
4982 argument.
4983
4984 @see fsl_pathfinder_ext_add()
4985 @see fsl_pathfinder_search()
4986*/
4988 char const * dir);
4989
4990/**
4991 Adds the given directory to pf's search path. Returns 0 on
4992 success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
4993 string), FSL_RC_OOM if copying the string or adding it to the
4994 list fails.
4995
4996 If strLen is negative, fsl_strlen() is used to calculate the length
4997 of the string.
4998
4999 @see fsl_pathfinder_ext_add()
5000 @see fsl_pathfinder_search()
5001*/
5003 fsl_int_t strLen);
5004
5005/**
5006 Adds the given directory to pf's search extensions. Returns 0 on
5007 success, FSL_RC_MISUSE if !pf or !dir (dir _may_ be an empty
5008 string), FSL_RC_OOM if copying the string or adding it to the
5009 list fails.
5010
5011 Note that the client is responsible for adding a "." to the
5012 extension, if needed, as this API does not apply any special
5013 meaning to any characters in a search extension. e.g. "-journal"
5014 and "~" are both perfectly valid extensions for this purpose.
5015
5016 @see fsl_pathfinder_dir_add()
5017 @see fsl_pathfinder_search()
5018*/
5020 fsl_int_t strLen);
5021
5022/**
5023 Equivalent to fsl_pathfinder_ext_add2() with -1 as a final
5024 argument.
5025
5026 @see fsl_pathfinder_dir_add()
5027 @see fsl_pathfinder_search()
5028*/
5030 char const * ext);
5031
5032/**
5033 Splits a conventional path-separator-delimited string into tokens
5034 and adds each as either a directory (if isDirs is true) or an
5035 extension in the given fsl_pathfinder object. Returns 0 on success,
5036 FSL_RC_OOM on allocation error. pathLen is the length of the path
5037 string. If it's negative, fsl_strlen() is used to calculate it.
5038
5039 See fsl_path_splitter for the semantics of the splitting.
5040*/
5042 bool isDirs,
5043 char const * path,
5044 fsl_int_t pathLen );
5045
5046/**
5047 Searches for a file whose name can be constructed by some
5048 combination of pf's directory/extension lists and the given base
5049 name.
5050
5051 It searches for files in the following manner:
5052
5053 If the 2nd parameter exists as-is in the filesystem, it is
5054 treated as a match, otherwise... Loop over all directories
5055 in pf->dirs. Create a path with DIR/base, or just base if
5056 the dir entry is empty (length of 0). Check for a match.
5057 If none is found, then... Loop over each extension in
5058 pf->ext, creating a path named DIR/baseEXT (note that it
5059 does not add any sort of separator between the base and the
5060 extensions, so "~" and "-foo" are legal extensions). Check
5061 for a match.
5062
5063 On success (a readable filesystem entry is found):
5064
5065 - It returns 0.
5066
5067 - If pOut is not NULL then `*pOut` is set to the NUL-terminated
5068 path it found. The bytes of the returned string are only valid
5069 until the next search operation on pf, so copy them if you need
5070 them. Note that the returned path is _not_ normalized via
5071 fsl_file_canonical_name() or similar, and it may very well return
5072 a relative path (if base or one of pf->dirs contains a relative
5073 path part). As a special case, if `base` is found as-is, without
5074 a lookup, `*pOut` is set to `base`, so has its lifetime.
5075
5076 - If outLen is not NULL, *outLen will be set to the length of the
5077 returned string.
5078
5079 On error:
5080
5081 - Returns FSL_RC_MISUSE if !pf, !base, !*base.
5082
5083 - Returns FSL_RC_OOM on allocation error (it uses a buffer to hold
5084 its path combinations and return value).
5085
5086 - Returns FSL_RC_NOT_FOUND if it finds no entry.
5087
5088 The host platform's customary path separator is used to separate
5089 directory/file parts ('\\' on Windows and '/' everywhere else).
5090
5091 Note that it _is_ legal for pOut and outLen to both be NULL, in
5092 which case a return of 0 signals that an entry was found, but the
5093 client has no way of knowing what path it might be (unless, of
5094 course, they rely on internal details of the fsl_pathfinder API,
5095 which they most certainly should not do).
5096
5097 Tip: if the client wants to be certain that this function will not
5098 allocate memory, simply use fsl_buffer_reserve() on pf->buf to
5099 reserve the desired amount of space in advance. As long as the
5100 search paths never surpass that length, this function will not need
5101 to allocate. (Until/unless the following TODO is implemented...)
5102
5103 Potential TODO: use fsl_file_canonical_name() so that the search
5104 dirs themselves do not need to be entered using
5105 platform-specific separators. The main reason it's not done now
5106 is that it requires another allocation. The secondary reason is
5107 because it's sometimes useful to use relative paths in this
5108 context (based on usage in previous trees from which this code
5109 derives).
5110
5111 @see fsl_pathfinder_dir_add()
5112 @see fsl_pathfinder_ext_add()
5113 @see fsl_pathfinder_clear()
5114*/
5116 char const * base,
5117 char const ** pOut,
5118 fsl_size_t * outLen );
5119
5120
5121/**
5122 A utility class for creating ZIP-format archives. All members
5123 are internal details and must not be mucked about with by the
5124 client. See fsl_zip_file_add() for an example of how to use it.
5125
5126 Note that it creates ZIP content in memory, as opposed to
5127 streaming it (it is not yet certain if abstractly streaming a
5128 ZIP is possible), so creating a ZIP file this way is exceedingly
5129 memory-hungry.
5130
5131 @see fsl_zip_file_add()
5132 @see fsl_zip_timestamp_set_julian()
5133 @see fsl_zip_timestamp_set_unix()
5134 @see fsl_zip_end()
5135 @see fsl_zip_body()
5136 @see fsl_zip_finalize()
5137*/
5139 /**
5140 Number of entries (files + dirs) added to the zip file so far.
5141 */
5143 /**
5144 Current DOS-format time of the ZIP.
5145 */
5146 int32_t dosTime;
5147 /**
5148 Current DOS-format date of the ZIP.
5149 */
5150 int32_t dosDate;
5151 /**
5152 Current Unix Epoch time of the ZIP.
5153 */
5155 /**
5156 An artificial root directory which gets prefixed
5157 to all inserted filenames.
5158 */
5159 char * rootDir;
5160 /**
5161 The buffer for the table of contents.
5162 */
5164 /**
5165 The buffer for the ZIP file body.
5166 */
5168 /**
5169 Internal scratchpad for ops which often allocate
5170 small buffers.
5171 */
5173 /**
5174 The current list of directory entries (as (char *)).
5175 */
5177};
5179
5180/**
5181 An initialized-with-defaults fsl_zip_writer instance, intended
5182 for in-struct or const-copy initialization.
5183*/
5184#define fsl_zip_writer_empty_m { \
5185 0/*entryCount*/, \
5186 0/*dosTime*/, \
5187 0/*dosDate*/, \
5188 0/*unixTime*/, \
5189 NULL/*rootDir*/, \
5190 fsl_buffer_empty_m/*toc*/, \
5191 fsl_buffer_empty_m/*body*/, \
5192 fsl_buffer_empty_m/*scratch*/, \
5193 fsl_list_empty_m/*dirs*/ \
5194}
5195
5196/**
5197 An initialized-with-defaults fsl_zip_writer instance,
5198 intended for copy-initialization.
5199*/
5201
5202/**
5203 Sets a virtual root directory in z, such that all files added
5204 with fsl_zip_file_add() will get this directory prefixed to
5205 it.
5206
5207 If zRoot is NULL or empty then this clears the virtual root,
5208 otherwise is injects any directory levels it needs to into the
5209 being-generated ZIP. Note that zRoot may contain multiple levels of
5210 directories, e.g. "foo/bar/baz", but it must be legal for use in a
5211 ZIP file.
5212
5213 This routine copies zRoot's bytes, so they may be transient.
5214
5215 Returns 0 on success, FSL_RC_MISUSE if !z, FSL_RC_OOM on
5216 allocation error. Returns FSL_RC_RANGE if zRoot is an absolute
5217 path or if zRoot cannot be normalized to a "simplified name" (as
5218 per fsl_is_simple_pathname(), with the note that this routine
5219 will pass a copy of zRoot through fsl_file_simplify_name()
5220 first).
5221
5222 @see fsl_zip_finalize()
5223*/
5225 char const * zRoot );
5226
5227/**
5228 Adds a file or directory to the ZIP writer z. zFilename is the
5229 virtual name of the file or directory. If pContent is NULL then
5230 it is assumed that we are creating one or more directories,
5231 otherwise the ZIP's entry is populated from pContent. The
5232 permsFlag argument specifies the fossil-specific permission
5233 flags from the fsl_fileperm_e enum, but currently ignores the
5234 permsFlag argument for directories. Not that this function
5235 creates directory entries for any files automatically, so there
5236 is rarely a need for client code to create them (unless they
5237 specifically want to ZIP an empty directory entry).
5238
5239 Notes of potential interest:
5240
5241 - The ZIP is created in memory, and thus creating ZIPs with this
5242 API is exceedingly memory-hungry.
5243
5244 - The timestamp of any given file must be set separately from
5245 this call using fsl_zip_timestamp_set_unix() or
5246 fsl_zip_timestamp_set_julian(). That value is then used for
5247 subsequent file-adds until a new time is set.
5248
5249 - If a root directory has been set using fsl_zip_root_set() then
5250 that name, plus '/' (if the root does not end with one) gets
5251 prepended to all files added via this routine.
5252
5253 An example of the ZIP-generation process:
5254
5255 ```
5256 int rc;
5257 fsl_zip_writer z = fsl_zip_writer_empty;
5258 fsl_buffer buf = fsl_buffer_empty;
5259 fsl_buffer const * zipBody;
5260
5261 // ...fill the buf buffer (not shown here)...
5262
5263 // Optionally set a virtual root dir for new files:
5264 rc = fsl_zip_root_set( &z, "myRootDir" ); // trailing slash is optional
5265 if(rc) { ... error ...; goto end; }
5266
5267 // We must set a timestamp which will be used until we set another:
5268 fsl_zip_timestamp_set_unix( &z, time(NULL) );
5269
5270 // Add a file:
5271 rc = fsl_zip_file_add( &z, "foo/bar.txt", &buf, FSL_FILE_PERM_REGULAR );
5272 // Clean up our content:
5273 fsl_buffer_reuse(&buf); // only needed if we want to re-use the buffer's memory
5274 if(rc) goto end;
5275
5276 // ... add more files the same way (not shown) ...
5277
5278 // Now "seal" the ZIP file:
5279 rc = fsl_zip_end( &z );
5280 if(rc) goto end;
5281
5282 // Fetch the ZIP content:
5283 zipBody = fsl_zip_body( &z );
5284 // zipBody now points to zipBody->used bytes of ZIP file content
5285 // which can be sent to an arbitrary destination, e.g.:
5286 rc = fsl_buffer_to_filename( zipBody, "my.zip" );
5287
5288 end:
5289 fsl_buffer_clear(&buf);
5290 // VERY important, once we're done with z:
5291 fsl_zip_finalize( &z );
5292 if(rc){...we had an error...}
5293 ```
5294
5295 @see fsl_zip_timestamp_set_julian()
5296 @see fsl_zip_timestamp_set_unix()
5297 @see fsl_zip_end()
5298 @see fsl_zip_body()
5299 @see fsl_zip_finalize()
5300*/
5302 char const * zFilename,
5303 fsl_buffer const * pContent,
5304 int permsFlag );
5305
5306/**
5307 Ends the ZIP-creation process, padding all buffers, writing all
5308 final required values, and freeing up most of the memory owned
5309 by z. After calling this, z->body contains the full generated
5310 ZIP file.
5311
5312 Returns 0 on success. On error z's contents may still be
5313 partially intact (for debugging purposes) and z->body will not
5314 hold complete/valid ZIP file contents. Results are undefined if
5315 !z or z has not been properly initialized.
5316
5317 The caller must eventually pass z to fsl_zip_finalize() to free
5318 up any remaining resources.
5319
5320 @see fsl_zip_timestamp_set_julian()
5321 @see fsl_zip_timestamp_set_unix()
5322 @see fsl_zip_file_add()
5323 @see fsl_zip_body()
5324 @see fsl_zip_finalize()
5325 @see fsl_zip_end_take()
5326*/
5328
5329/**
5330 This variant of fsl_zip_end() transfers the current contents
5331 of the zip's body to dest, replacing (freeing) any contents it may
5332 hold when this is called, then passes z to fsl_zip_finalize()
5333 to free any other resources (which are invalidated by the removal
5334 of the body).
5335
5336 Returns 0 on success, FSL_RC_MISUSE if either pointer is NULL,
5337 some non-0 code if the proxied fsl_zip_end() call fails. On
5338 error, the transfer of contents to dest does NOT take place, but
5339 z is finalized (if it is not NULL) regardless of success or
5340 failure (even if dest is NULL). i.e. on error z is still cleaned
5341 up.
5342*/
5344 fsl_buffer * dest );
5345
5346/**
5347 This variant of fsl_zip_end_take() passes z to fsl_zip_end(),
5348 write's the ZIP body to the given filename, passes
5349 z to fsl_zip_finalize(), and returns the result of
5350 either end/save combination. Saving is not attempted
5351 if ending the ZIP fails.
5352
5353 On success 0 is returned and the contents of the ZIP are in the
5354 given file. On error z is STILL cleaned up, and the file might
5355 have been partially populated (only on I/O error after writing
5356 started). In either case, z is cleaned up and ready for re-use or
5357 (in the case of a heap-allocated instance) freed.
5358*/
5360 char const * filename );
5361
5362
5363/**
5364 Returns a pointer to z's ZIP content buffer. The contents are ONLY
5365 valid after fsl_zip_end() returns 0.
5366
5367 @see fsl_zip_timestamp_set_julian()
5368 @see fsl_zip_timestamp_set_unix()
5369 @see fsl_zip_file_add()
5370 @see fsl_zip_end()
5371 @see fsl_zip_end_take()
5372 @see fsl_zip_finalize()
5373*/
5375
5376/**
5377 Frees all memory owned by z and resets it to a clean state, but
5378 does not free z. Any fsl_zip_writer instance which has been
5379 modified via the fsl_zip_xxx() family of functions MUST
5380 eventually be passed to this function to clean up any contents
5381 it might have accumulated during its life. After this returns,
5382 z is legal for re-use in creating a new ZIP archive.
5383
5384 @see fsl_zip_timestamp_set_julian()
5385 @see fsl_zip_timestamp_set_unix()
5386 @see fsl_zip_file_add()
5387 @see fsl_zip_end()
5388 @see fsl_zip_body()
5389*/
5391
5392/**
5393 Set z's date and time from a Julian Day number. Results are
5394 undefined if !z. Results will be invalid if rDate is negative. The
5395 timestamp is applied to all fsl_zip_file_add() operations until it
5396 is re-set.
5397
5398 @see fsl_zip_timestamp_set_unix()
5399 @see fsl_zip_file_add()
5400 @see fsl_zip_end()
5401 @see fsl_zip_body()
5402*/
5404 double rDate);
5405
5406/**
5407 Set z's date and time from a Unix Epoch time. Results are
5408 undefined if !z. Results will be invalid if rDate is negative. The
5409 timestamp is applied to all fsl_zip_file_add() operations until it
5410 is re-set.
5411*/
5413 fsl_time_t epochTime);
5414
5415/**
5416 State for the fsl_timer_xxx() family of functions.
5417
5418 Achtung: timer support is only enabled if the library is built with
5419 the proper clock support. Windows builds mostly support it
5420 automatically (all except wall clock time) and non-Windows builds
5421 do if the library is built with HAVE_CLOCK_GETTIME (for
5422 clock_gettime(2)) and HAVE_GETRUSAGE (for getrusage(2)) both set to
5423 true values. That said: the library currently _assumes_ that
5424 non-Windows builds have both of those POSIX-2008 functions. On
5425 Windows, building with HAVE_CLOCK_GETTIME is necessary only for
5426 fsl_timer::wall.
5427
5428 Example usage:
5429
5430 ```
5431 fsl_timer tTotal = fsl_timer_empty;
5432 fsl_timer tRun;
5433 fsl_timer_start(&tRun);
5434 ... do some work ...
5435 fsl_timer_add(&tRun, &tTotal);
5436 ```
5437
5438 After that, `tTotal` contains the microseconds of time which
5439 elapsed between the time `tRun` was started and the time
5440 fsl_timer_add() was called.
5441
5442 @see fsl_timer_start()
5443 @see fsl_timer_fetch()
5444 @see fsl_timer_add()
5445 @see fsl_timer_stop()
5446*/
5448 /**
5449 The amount of time (microseconds) spent in "user space".
5450 */
5451 uint64_t user;
5452
5453 /**
5454 The amount of time (microseconds) spent in "kernel space".
5455 */
5456 uint64_t system;
5457
5458 /**
5459 The microseconds of "wall clock" time. Only available if built
5460 with HAVE_CLOCK_GETTIME. (Patches for a Windows alternative would
5461 be welcomed.)
5462 */
5463 uint64_t wall;
5464};
5465typedef struct fsl_timer fsl_timer;
5466
5467/**
5468 Initialized-with-defaults fsl_timer instance,
5469 intended for const copy initialization.
5470*/
5471#define fsl_timer_empty_m {.user=0,.system=0,.wall=0}
5472
5473/**
5474 Initialized-with-defaults fsl_timer instance,
5475 intended for non-const copy initialization.
5476*/
5478
5479/**
5480 Sets t's counter state to the current CPU timer usage, as
5481 determined by the OS. It is legal to pass an uninitialized instance
5482 to this function, as this function will fully populate it.
5483
5484 @see fsl_timer_fetch()
5485 @see fsl_timer_add()
5486*/
5488
5489/**
5490 Sets each of pUser, pSys, and pWall to the number of
5491 microseconds which have elapsed since t was passed
5492 to fsl_timer_start().
5493*/
5495 uint64_t * pUser, uint64_t * pSys,
5496 uint64_t * pWall);
5497
5498/**
5499 Captures the current time and adds the difference of tStart and
5500 the current time to tgt's members. Intended for
5501 keeping track of interruptable running times.
5502
5503 Example usage:
5504
5505 ```
5506 fsl_timer timerTotal = fsl_timer_empty; // copy init is important
5507 fsl_timer timerWork; // here it's not
5508
5509 fsl_timer_start(&timerWork);
5510 ... do some timed work...
5511 fsl_timer_add(&timerWork, &timerTotal);
5512
5513 ... do some non-timed work ...
5514
5515 fsl_timer_start(&timerWork);
5516 ... do some timed work...
5517 fsl_timer_add(&timerWork, &timerTotal);
5518 ```
5519
5520 The end result will be that timerTotal holds the accumulated times
5521 between each start/add invocation.
5522*/
5524 fsl_timer * tgt);
5525
5526/**
5527 Returns the difference in _CPU_ times in microseconds since t was
5528 last passed to fsl_timer_start() or fsl_timer_reset(). It might
5529 return 0 due to system-level precision restrictions. Note that this
5530 is not useful for measuring wall times.
5531*/
5533
5534/**
5535 Resets t's state to contain relative times by subtracting its
5536 starting time from the current time. Returns the post-adjustment
5537 (t->system+t->user).
5538
5539 @see fsl_timer_start()
5540 @see fsl_timer_reset()
5541*/
5543
5544/**
5545 A convenience macro for timing a block of code (BODY) with the
5546 fsl_timer API. TGT is a (fsl_timer*) object which must initially
5547 start out zeroed out (e.g. initialied by copying from
5548 fsl_timer_empty or fsl_timer_empty_m). SUFFIX is a unique-per-scope
5549 name suffix for a scope-local temporary fsl_timer object, so must
5550 be suitable as the suffix of a C identifier. The run-time of BODY
5551 is fsl_timer_add()'d to (fsl_timer*) TGT.
5552
5553 Example usage:
5554
5555 ```
5556 fsl_timer_scope3(__COUNTER__,&myTimer,{
5557 ... your code to time ...
5558 });
5559 ```
5560
5561 For compilers which do not like `__COUNTER__`, just use any
5562 identifier suffix which is unique to the call scope, e.g. an
5563 integer.
5564*/
5565#define fsl_timer_scope3(SUFFIX,TGT,BODY) \
5566 fsl_timer _tm ## SUFFIX; \
5567 fsl_timer_start(&_tm ## SUFFIX); \
5568 BODY; \
5569 fsl_timer_add(&_tm ## SUFFIX, TGT)
5570
5571/**
5572 Convenience form of fsl_timer_scope3() which uses __COUNTER__ as
5573 its 2nd argument. Note that __COUNTER__ is a C extension but is
5574 believed to be supported on all modern (as of 2025) C compilers.
5575*/
5576#define fsl_timer_scope(TGT,BODY) \
5577 fsl_timer_scope3(__COUNTER__,TGT,BODY)
5578
5579
5580/**
5581 For the given red/green/blue values (all in the range of 0 to
5582 255, or truncated to be so!) this function returns the RGB
5583 encoded in the lower 24 bits of a single number. See
5584 fsl_gradient_color() for an explanation and example.
5585
5586 For those asking themselves, "why does an SCM API have a function
5587 for encoding RGB colors?" the answer is: fossil(1) has a long
5588 history of using HTML color codes to set the color of branches,
5589 and this is provided in support of such features.
5590
5591 @see fsl_rgb_decode()
5592 @see fsl_gradient_color()
5593*/
5594FSL_EXPORT unsigned int fsl_rgb_encode( int r, int g, int b );
5595
5596/**
5597 Given an RGB-encoded source value, this function decodes
5598 the lower 24 bits into r, g, and b. Any of r, g, and b may
5599 be NULL to skip over decoding of that part.
5600
5601 @see fsl_rgb_encode()
5602 @see fsl_gradient_color()
5603*/
5604FSL_EXPORT void fsl_rgb_decode( unsigned int src, int *r, int *g, int *b );
5605
5606/**
5607 For two color values encoded as RRGGBB values (see below for the
5608 structure), this function computes a gradient somewhere between
5609 those colors. c1 and c2 are the edges of the gradient.
5610 numberOfSteps is the number of steps in the gradient. stepNumber
5611 is a number less than numberOfSteps which specifies the "degree"
5612 of the gradients. If either numberOfSteps or stepNumber is 0, c1
5613 is returned. stepNumber of equal to or greater than c2 returns
5614 c2.
5615
5616 The return value is an RGB-encoded value in the lower 24 bits,
5617 ordered in big-endian. In other words, assuming rc is the return
5618 value:
5619
5620 - red = (rc&0xFF0000)>>16
5621 - green = (rc&0xFF00)>>8
5622 - blue = (rc&0xFF)
5623
5624 Or use fsl_rgb_decode() to break it into its component parts.
5625
5626 It can be passed directly to a printf-like function, using the
5627 hex-integer format specifier, e.g.:
5628
5629 ```
5630 fsl_buffer_appendf(&myBuf, "#%06x", rc);
5631 ```
5632
5633 Tip: for a given HTML RRGGBB value, its C representation is
5634 identical: HTML \#F0D0A0 is 0xF0D0A0 in C.
5635
5636 @see fsl_rgb_encode()
5637 @see fsl_rgb_decode()
5638*/
5639FSL_EXPORT unsigned int fsl_gradient_color(unsigned int c1, unsigned int c2,
5640 unsigned int numberOfSteps,
5641 unsigned int stepNumber);
5642
5643/**
5644 "Simplifies" an SQL string by making the following modifications
5645 inline:
5646
5647 - Consecutive non-newline spaces outside of an SQL string are
5648 collapsed into one space.
5649
5650 - Consecutive newlines outside of an SQL string are collapsed into
5651 one space.
5652
5653 Contents of SQL strings are not transformed in any way.
5654
5655 len must be the length of the sql string. If it is negative,
5656 fsl_strlen(sql) is used to calculate the length.
5657
5658 Returns the number of bytes in the modified string (its strlen) and
5659 NUL-terminates it at the new length. Thus the input string must be
5660 at least one byte longer than its virtual length (its NUL
5661 terminator byte suffices, provided it is NUL-terminated, as we can
5662 safely overwrite that byte).
5663
5664 If !sql or its length resolves to 0, this function returns 0
5665 without side effects.
5666*/
5668
5669/**
5670 Convenience form of fsl_simplify_sql() which assumes b holds an SQL
5671 string. It gets processed by fsl_simplify_sql() and its 'used'
5672 length potentially gets adjusted to match the adjusted SQL string.
5673*/
5675
5676/**
5677 Returns the result of calling the platform's equivalent of
5678 isatty(fd). e.g. on Windows this is _isatty() and on Unix
5679 isatty(). i.e. it returns true if it thinks that the given file
5680 descriptor value is attached to an interactive terminal, else it
5681 returns false.
5682
5683 The standard file descriptors are: 0=stdin, 1=stdout, and 2=stderr.
5684*/
5686
5687/**
5688
5689 A container type for lists of db record IDs. This is used in
5690 several places as a cache for record IDs, to keep track of ones
5691 we know about, ones we know that we don't know about, and to
5692 avoid duplicate processing in some contexts.
5693*/
5695 /**
5696 Number of entries of this->list which are in use (have a
5697 positive value). They need not be contiguous! Must be <=
5698 capacity.
5699 */
5701 /**
5702 The number of elements allocated for this->list.
5703 */
5705 /**
5706 The number of elements in this->list which have a zero or
5707 positive value. Must be <= capacity.
5708 */
5710 /**
5711 Array of IDs this->capacity elements long. "Used" elements
5712 have a positive value. Unused ones are set to 0.
5713 */
5715};
5716
5717/**
5718 Initialized-with-defaults fsl_id_bag structure,
5719 intended for copy initialization.
5720*/
5722
5723/**
5724 Initialized-with-defaults fsl_id_bag structure,
5725 intended for in-struct initialization.
5726*/
5727#define fsl_id_bag_empty_m { \
5728 .entryCount = 0, .capacity = 0, \
5729 .used = 0, .list = NULL \
5730}
5731
5732/**
5733
5734 Return the number of elements in the bag.
5735*/
5737
5738/**
5739
5740 Remove element e from the bag if it exists in the bag. If e is not
5741 in the bag, this is a no-op. Returns true if it removes an element,
5742 else false.
5743
5744 e must be positive. Results are undefined if e<=0.
5745*/
5747
5748/**
5749 Returns true if e is in the given bag. Returns false if it is
5750 not. It is illegal to pass an e value of 0, and that will trigger
5751 an assertion in debug builds. In non-debug builds, behaviour if
5752 passed 0 is undefined.
5753*/
5755
5756/**
5757 Insert element e into the bag if it is not there already. Returns
5758 0 if it actually inserts something or if it already contains such
5759 an entry, and some other value on error (namely FSL_RC_OOM on
5760 allocation error).
5761
5762 e must be positive or an assertion is triggered in debug builds. In
5763 non-debug builds, behaviour is undefined if passed 0.
5764*/
5766
5767/**
5768 Returns the ID of the first element in the bag. Returns 0 if the
5769 bag is empty.
5770
5771 ```
5772 fsl_id_t rid = fsl_id_bag_first(debag);
5773 int rc = 0;
5774 for( ; !rc && rid>0; rid = fsl_id_bag_next(debag, rid) ){
5775 rc = ...;
5776 }
5777 ```
5778
5779*/
5781
5782/**
5783 Returns the next element in the bag after e. Return 0 if e is
5784 the last element in the bag. Any insert or removal from the bag
5785 might reorder the bag. It is illegal to pass this 0 (and will
5786 trigger an assertion in debug builds). For the first call, pass
5787 it the non-0 return value from fsl_id_bag_first(). For
5788 subsequent calls, pass the previous return value from this
5789 function.
5790
5791 @see fsl_id_bag_first()
5792*/
5794
5795/**
5796 Swaps the contents of the given bags.
5797*/
5799
5800/**
5801 Copies all entries from src into dest. Returns 0 on success,
5802 FSL_RC_OOM on allocation error.
5803
5804 An alternative approach: if dest is empty then
5805 fsl_id_bag_swap(src,dest), perhaps followed by
5806 fsl_id_bag_clear(src) or fsl_id_bag_reuse(src), is more efficient
5807 (does not allocate).
5808*/
5810
5811/**
5812 Frees any memory owned by p, but does not free p.
5813*/
5815
5816/**
5817 Resets p's internal list, effectively emptying it for re-use, but
5818 does not free its memory. Immediately after calling this
5819 fsl_id_bag_count() will return 0. Returns p.
5820*/
5822
5823/** @deprecated
5824
5825 Older (deprecated) name of fsl_id_bag_reuse().
5826*/
5827#define fsl_id_bag_reset fsl_id_bag_reuse
5828
5829/**
5830 Returns true if p contains a fossil-format merge conflict marker,
5831 else returns false.
5832
5833 @see fsl_buffer_merge3()
5834*/
5836
5837/**
5838 Performs a three-way merge.
5839
5840 The merge is an edit against pV2. Both pV1 and pV2 have a common
5841 origin at pPivot. Apply the changes of pPivot ==> pV1 to pV2,
5842 appending them to pOut. (Pedantic side-note: the input buffers are
5843 not const because we need to manipulate their cursors, but their
5844 buffered memory is not modified.)
5845
5846 If merge conflicts are encountered, it continues as best as it can
5847 and injects "indiscrete" markers in the output to denote the nature
5848 of each conflict. If conflictCount is not NULL then on success the
5849 number of merge conflicts is written to *conflictCount.
5850
5851 Returns 0 on success, FSL_RC_OOM on OOM, FSL_RC_TYPE if any input
5852 appears to be binary.
5853
5854 FIXME/TODO: return FSL_RC_DIFF_BINARY instead of FSL_RC_TYPE when
5855 encountering binary inputs.
5856
5857 @see fsl_buffer_contains_merge_marker()
5858*/
5860 fsl_buffer * pV1,
5861 fsl_buffer * pV2,
5862 fsl_buffer * pOut,
5863 unsigned int * conflictCount);
5864
5865/**
5866 Appends the first n bytes of string z to buffer b in the form of
5867 TCL-format string literal. If n<0 then fsl_strlen() is used to
5868 determine the length. Returns 0 on success, FSL_RC_OOM on error.
5869
5870 If fsl_buffer_err() is true for the given buffer, that code is
5871 returned without other side effects.
5872
5873 If the 2nd argument is true, squiggly braces within the string are
5874 escaped, else they are not. Whether that's required or not depends
5875 on how the resulting TCL will be used. If it will be eval'd directly,
5876 it must be escaped. If it will be read as a file and tokenized, it
5877 needn't be.
5878 */
5880 bool escapeSquigglies,
5881 char const * z, fsl_int_t n);
5882
5883
5884/**
5885 Event IDs for use with fsl_confirm_callback_f implementations.
5886
5887 The idea here is to send, via callback, events from the library to
5888 the client when a potentially interactive response is necessary.
5889 We define a bare minimum of information needed for the client to
5890 prompt a user for a response. To that end, the interface passes on
5891 2 pieces of information to the client: the event ID and a filename.
5892 It is up to the application to translate that ID into a
5893 user-readable form, get a response (using a well-defined set of
5894 response IDs), and convey that back to the
5895 library via the callback's result pointer interface.
5896
5897 This enum will be extended as the library develops new requirements
5898 for interactive use.
5899
5900 @see fsl_confirm_response_e
5901*/
5903/**
5904 Sentinal value.
5905*/
5907/**
5908 An operation requests permission to overwrite a locally-modified
5909 file. e.g. when performing a checkout over a locally-edited
5910 version. Overwrites of files which are known to be in the previous
5911 (being-overwritten) checkout version are automatically overwritten.
5912*/
5914/**
5915 An operation requests permission to overwrite an SCM-unmanaged file
5916 with one which is managed by SCM. This can happen, e.g., when
5917 switching from a version which did not contain file X, but had file
5918 X on disk, to a version which contains file X.
5919*/
5921/**
5922 An operation requests permission to remove a LOCALLY-MODIFIED file
5923 which has been removed from SCM management. e.g. when performing a
5924 checkout over a locally-edited version and an edited file was
5925 removed from the SCM somewhere between those two versions.
5926 UMODIFIED files which are removed from the SCM between two
5927 checkouts are automatically removed on the grounds that it poses no
5928 data loss risk because the other version is "somewhere" in the SCM.
5929*/
5931
5932/**
5933 Indicates that the library cannot determine which of multiple
5934 potential versions to choose from and requires the user to
5935 select one.
5936*/
5938
5939};
5941
5942/**
5943 Answers to questions posed to clients via the
5944 fsl_confirm_callback_f() interface.
5945
5946 This enum will be extended as the library develops new requirements
5947 for interactive use.
5948
5949 @see fsl_confirm_event_e
5950*/
5952/**
5953 Sentinel/default value - not a valid answer. Guaranteed to have a
5954 value of 0. No other entries in this enum are guaranteed to have
5955 well-known/stable values: always use the enum symbols instead of
5956 integer values.
5957*/
5959/**
5960 Accept the current event and continue processes.
5961*/
5963/**
5964 Reject the current event and continue processes.
5965*/
5967/**
5968 Reject the current event and stop processesing. Cancellation is
5969 generally considered to be a recoverable error.
5970*/
5972/**
5973 Accept the current event and all identical event types for the
5974 current invocation of this particular SCM operation.
5975*/
5977/**
5978 Reject the current event and all identical event types for the
5979 current invocation of this particular SCM operation.
5980*/
5982/**
5983 For events which are documented as being multiple-choice,
5984 this answer indicates that the client has set the index of
5985 their choice in the fsl_confirm_response::multipleChoice
5986 field:
5987
5988 - FSL_CEVENT_MULTIPLE_VERSIONS
5989*/
5991};
5993
5994/**
5995 A response for use with the fsl_confirmer API. It is intended to
5996 encapsulate, with a great deal of abstraction, answers to typical
5997 questions which the library may need to interactively query a user
5998 for. e.g. confirmation about whether to overwrite a file or which
5999 one of 3 versions to select.
6000
6001 This type will be extended as the library develops new requirements
6002 for interactive use.
6003*/
6005 /**
6006 Client response to the current fsl_confirmer question.
6007 */
6009 /**
6010 If this->response is FSL_CRESPONSE_MULTI then this must be set to
6011 the index of the client's multiple-choice answer.
6012
6013 Events which except this in their response:
6014
6015 - FSL_CEVENT_MULTIPLE_VERSIONS
6016 */
6018};
6019/**
6020 Convenience typedef.
6021*/
6023
6024/**
6025 Empty-initialized fsl_confirm_detail instance to be used for
6026 const copy initialization.
6027*/
6028#define fsl_confirm_response_empty_m {FSL_CRESPONSE_INVALID, -1}
6029
6030/**
6031 Empty-initialized fsl_confirm_detail instance to be used for
6032 non-const copy initialization.
6033*/
6035
6036/**
6037 A struct for passing on interactive questions to
6038 fsl_confirmer_callback_f implementations.
6039*/
6041 /**
6042 The message ID of this confirmation request. This value
6043 determines how the rest of this struct's values are to
6044 be interpreted.
6045 */
6047 /**
6048 Depending on the eventId, this might be NULL or might refer to a
6049 filename. This will be a filename for following confirmations
6050 events:
6051
6052 - FSL_CEVENT_OVERWRITE_MOD_FILE
6053 - FSL_CEVENT_OVERWRITE_UNMGD_FILE
6054 - FSL_CEVENT_RM_MOD_UNMGD_FILE
6055
6056 For all others it will be NULL.
6057
6058 Whether this name refers to an absolute or relative path is
6059 context-dependent, and not specified by this API. In general,
6060 relative paths should be used if/when what they are relative to
6061 (e.g. a checkout root) is/should be clear to the user. The intent
6062 is that applications can display that name to the user in a UI
6063 control, so absolute paths "should" "generally" be avoided
6064 because they can be arbitrarily long.
6065 */
6066 const char * filename;
6067 /**
6068 Depending on the eventId, this might be NULL or might
6069 refer to a list of details of a type specified in the
6070 documentation for that eventId.
6071
6072 Implementation of such an event is still TODO, but we have at
6073 least one use case lined up (asking a user which of several
6074 versions is intended when the checkout-update operation is given
6075 an ambiguous hash prefix).
6076
6077 Events for which this list will be populated:
6078
6079 - FSL_CEVENT_MULTIPLE_VERSIONS: each list entry will be a (char
6080 const*) with a version number, branch name, or similar, perhaps
6081 with relevant metadata such as a checkin timestamp. The client is
6082 expected to pick one answer, set its list index to the
6083 fsl_confirm_response::multipleChoice member, and to set
6084 fsl_confirm_response::response to FSL_CRESPONSE_MULTI.
6085
6086 In all cases, a response of FSL_CRESPONSE_CANCEL will trigger a
6087 cancellation.
6088
6089 In all cases, the memory for the items in this list is owned by
6090 (or temporarily operated on the behalf of) the routine which has
6091 launched this query. fsl_confirm_callback_f implements must never
6092 manipulate the list's or its content's state.
6093 */
6095};
6097
6098/**
6099 Empty-initialized fsl_confirm_detail instance to be used for
6100 const-copy initialization.
6101*/
6102#define fsl_confirm_detail_empty_m \
6103 {FSL_CEVENT_INVALID, NULL, NULL}
6104
6105/**
6106 Empty-initialized fsl_confirm_detail instance to be used for
6107 non-const-copy initialization.
6108*/
6110
6111/**
6112 Should present the user (if appropriate) with an option of how to
6113 handle the given event write that answer to
6114 outAnswer->response. Return 0 on success, non-0 on error, in which
6115 case the current operation will fail with that result code.
6116 Answering with FSL_CRESPONSE_CANCEL is also considered failure but
6117 recoverably so, whereas a non-cancel failure is considered
6118 unrecoverable.
6119*/
6120typedef int (*fsl_confirm_callback_f)(fsl_confirm_detail const * detail,
6121 fsl_confirm_response *outAnswer,
6122 void * confirmerState);
6123
6124/**
6125 A fsl_confirm_callback_f and its callback state, packaged into a
6126 neat little struct for easy copy/replace/restore of confirmers.
6127*/
6129 /**
6130 Callback which can be used for basic interactive confirmation
6131 purposes, within the very libfossil-centric limits of the
6132 interface.
6133 */
6135 /**
6136 Opaque state pointer for this->callback. Its lifetime is not
6137 managed by this object and it is assumed, if not NULL, to live at
6138 least as long as this object.
6139 */
6141};
6143/** Empty-initialized fsl_confirmer instance for const-copy
6144 initialization. */
6145#define fsl_confirmer_empty_m {NULL,NULL}
6146/** Empty-initialized fsl_confirmer instance for non-const-copy
6147 initialization. */
6149
6150/**
6151 State for use with fsl_dircrawl_f() callbacks.
6152
6153 @see fsl_dircrawl()
6154*/
6156 /**
6157 Absolute directory name of the being-visited directory.
6158 */
6159 char const *absoluteDir;
6160 /**
6161 Name (no path part) of the entry being visited.
6162 */
6163 char const *entryName;
6164 /**
6165 Filesystem entry type.
6166 */
6168 /**
6169 Opaque client-specified pointer which was passed to
6170 fsl_dircrawl().
6171 */
6173
6174 /**
6175 Directory depth of the crawl process, starting at 1 with
6176 the directory passed to fsl_dircrawl().
6177 */
6178 unsigned int depth;
6179};
6181
6182/**
6183 Callback type for use with fsl_dircrawl(). Its argument contains
6184 all crawling-relevant state for entry being visited.
6185
6186 Implementations must return 0 on success or another FSL_RC_xxx
6187 value on error.
6188
6189 Special return values:
6190
6191 - FSL_RC_BREAK will cause directory-crawling to stop without an
6192 error (returning 0).
6193
6194 - Returning FSL_RC_NOOP will cause recursion into a directory to
6195 be skipped, but traversal to otherwise continue.
6196
6197 All pointers in the state argument are owned by fsl_dircrawl() and
6198 will be invalidated as soon as the callback returns, thus they must
6199 be copied if they are needed for later.
6200*/
6201typedef int (*fsl_dircrawl_f)(fsl_dircrawl_state const *);
6202
6203/**
6204 Recurses into a directory and calls a callback for each filesystem
6205 entry. It does not change working directories, but callbacks are
6206 free to do so as long as they restore the working directory before
6207 returning.
6208
6209 The first argument is the name of the directory to crawl. In order
6210 to avoid any dependence on a specific working directory, if it is
6211 not an absolute path then this function will expand it to an
6212 absolute path before crawling begins. For each entry under the
6213 given directory, it calls the given callback, passing it a
6214 fsl_dircrawl_state object holding various state. All pointers in
6215 that object, except for the callbackState pointer, are owned by
6216 this function and may be invalidated as soon as the callback
6217 returns.
6218
6219 For each directory entry, it recurses into that directory,
6220 depth-first _after_ passing it to the callback.
6221
6222 It DOES NOT resolve/follow symlinks, instead passing them on to the
6223 callback for processing. Note that passing a symlink to this
6224 function will not work because this function does not resolve
6225 symlinks. Thus it provides no way to traverse symlinks, as its
6226 scope is only features suited for the SCM and symlinks have no
6227 business being in an SCM. (Fossil supports symlinks, more or less,
6228 but libfossil does not.)
6229
6230 It silently skips any files for which stat() fails or is not of a
6231 "basic" file type (e.g. character devices and such).
6232
6233 Returns 0 on success, FSL_RC_TYPE if the given name is not a
6234 directory, and FSL_RC_RANGE if it recurses "too deep," (some
6235 "reasonable" internally hard-coded limit), in order to help avoid a
6236 stack overflow.
6237
6238 If the callback returns non-0, iteration stops and returns that
6239 result code unless the result is FSL_RC_BREAK or FSL_RC_NOOP, with
6240 those codes being treated specially, as documented for
6241 fsl_dircrawl_f() callbacks.
6242*/
6243FSL_EXPORT int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback,
6244 void * callbackState);
6245
6246/**
6247 Strips any trailing slashes ('/') from the given string by
6248 assigning those bytes to NUL and returns the number of slashes
6249 NUL'd out. nameLen must be the length of the string. If nameLen is
6250 negative, fsl_strlen() is used to calculate its length.
6251*/
6253
6254/**
6255 A convenience from of fsl_strip_trailing_slashes() which strips
6256 trailing slashes from the given buffer and changes its b->used
6257 value to account for any stripping. Results are undefined if b is
6258 not properly initialized.
6259*/
6261
6262/**
6263 Appends each ID from the given bag to the given buffer using the given
6264 separator string. Returns FSL_RC_OOM on allocation error.
6265
6266 If fsl_buffer_err() is true for the given buffer, that code is
6267 returned without other side effects.
6268*/
6270 fsl_buffer * b,
6271 char const * separator);
6272
6273/**
6274 Flags for use with the fsl_looks family of functions.
6275*/
6277/* Nothing special was found. */
6279/* One or more NUL chars were found. */
6281/* One or more CR chars were found. */
6282FSL_LOOKSLIKE_CR = 0x00000002,
6283/* An unpaired CR char was found. */
6285/* One or more LF chars were found. */
6286FSL_LOOKSLIKE_LF = 0x00000008,
6287/* An unpaired LF char was found. */
6289/* One or more CR/LF pairs were found. */
6291/* An over length line was found. */
6293/* An odd number of bytes was found. */
6295/* Unable to perform full check. */
6297/* Invalid sequence was found. */
6299/* Might be binary. */
6301 /* Line separators. */
6303};
6304
6305/**
6306 Returns true if b appears to contain "binary" (non-UTF8/16) content,
6307 else returns false.
6308*/
6310
6311/**
6312 If b appears to contain any non-UTF8 content, returns a truthy
6313 value: one or more values from the fsl_lookslike_e enum indicating
6314 which sort of data was seen which triggered its conclusion:
6315
6316 - FSL_LOOKSLIKE_BINARY means the content appears to be binary
6317 because it contains embedded NUL bytes or an "extremely long"
6318 line. This function may diagnose UTF-16 as binary.
6319
6320 - !FSL_LOOKSLIKE_BINARY means the content is non-binary but may
6321 not necessarily be valid UTF-8.
6322
6323 - 0 means the contents appear to be valid UTF-8.
6324
6325 It b's content is empty, returns 0.
6326
6327 The 2nd argument can be a mask of any values from fsl_lookslike_e
6328 and will cause this routine to stop inspecting the input once it
6329 encounters any content described by those flags.
6330
6331 The contents are examined until the end is reached or a condition
6332 described by the 2nd parameter's flags is encountered.
6333
6334 WARNINGS:
6335
6336 - This function does not validate that the blob content is properly
6337 formed UTF-8. It assumes that all code points are the same size.
6338 It does not validate any code points. It makes no attempt to
6339 detect if any [invalid] switches between UTF-8 and other
6340 encodings occur.
6341
6342 - The only code points that this function cares about are the NUL
6343 character, carriage-return, and line-feed.
6344*/
6345FSL_EXPORT int fsl_looks_like_utf8(fsl_buffer const * b, int stopFlags);
6346
6347/**
6348 Returns true if b's contents appear to contain anything other than valid
6349 UTF8.
6350
6351 It uses the approach described at:
6352
6353 http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences
6354
6355 except for the "overlong form" of \\u0000 which is not considered
6356 invalid here: Some languages, like Java and Tcl, use it. This function
6357 also considers valid the derivatives CESU-8 & WTF-8.
6358*/
6360
6361/**
6362 Returns a static pointer to bytes of a UTF8 BOM. If the argument is
6363 not NULL, it is set to the strlen of those bytes (always 3).
6364*/
6365FSL_EXPORT unsigned char const *fsl_utf8_bom(unsigned int *pnByte);
6366
6367/**
6368 Returns true if b starts with a UTF8 BOM. If the 2nd argument is
6369 not NULL, *pBomSize is set to the number of bytes in the BOM
6370 (always 3), regardless of whether or not the function returns true
6371 or false.
6372*/
6373FSL_EXPORT bool fsl_starts_with_bom_utf8(fsl_buffer const * b, unsigned int *pBomSize);
6374
6375/**
6376 Populates the first n bytes of tgt with random bytes. Note that n
6377 must be 31 bits or less (2GB). The exact source of randomness is
6378 not guaranteed by the API, but the implementation currently uses
6379 sqlite3_randomness().
6380*/
6381FSL_EXPORT void fsl_randomness(unsigned int n, void *tgt);
6382
6383
6384/**
6385 Given a filename and its length, this function returns a pointer to
6386 the last instance of a path separator character in that string,
6387 checking for both `/` and `\\`. If the length is negative,
6388 fsl_strlen() is used to calculate it. If no separator is found,
6389 NULL is returned.
6390*/
6391FSL_EXPORT char const * fsl_last_path_sep(char const * str, fsl_int_t slen );
6392
6393/**
6394 A helper type for tokenizing conventional PATH-style strings.
6395 Initialize them with fsl_path_splitter_init() and iterate over them
6396 with fsl_path_splitter_next().
6397*/
6399 /** Begining of the input range. */
6400 char const * begin;
6401 /** One-after-the-end of the input range. */
6402 char const * end;
6403 /** Position for the next token lookup. */
6404 char const * pos;
6405 /** List of token separator characters (ASCII only). */
6406 char const * separators;
6407};
6409/** @def fsl_path_splitter_empty_m
6410
6411 Default-initialized fsl_path_splitter instance, intended for const-copy
6412 initialization. On Windows builds its separators member is set to
6413 ";" and on other platforms it's set to ":;".
6414*/
6415#if FSL_PLATFORM_IS_WINDOWS
6416# define fsl_path_splitter_empty_m {NULL,NULL,NULL,";"}
6417#else
6418# define fsl_path_splitter_empty_m {NULL,NULL,NULL,":;"}
6419#endif
6420
6421/**
6422 Default-initialized fsl_path_splitter instance, intended for
6423 copy initialization.
6424
6425 @see fsl_path_splitter_empty_m
6426*/
6428
6429/**
6430 Wipes out pt's current state by copying fsl_path_splitter_empty
6431 over it and initializes pt to use the given path as its input. If
6432 len is 0 or more then it must be the length of the string, in
6433 bytes. If len is less than 0, fsl_strlen() is used to determine the
6434 path's length. (When dealing with inputs which are not
6435 NUL-terminated, it's critical that the user pass the correct
6436 non-negative length.)
6437
6438 If the client wants to modify pt->separators, it must be done
6439 *after* calling this.
6440
6441 Use fsl_path_splitter_next() to iterate over the path entries.
6442*/
6443void fsl_path_splitter_init( fsl_path_splitter * pt, char const * path,
6444 fsl_int_t len );
6445
6446/**
6447 Given a fsl_path_splitter which was formerly initialized using
6448 fsl_path_splitter_init(), this iterates over the next-available
6449 path component in the input, skipping over empty entries (leading,
6450 consecutive, or trailing separator characters).
6451
6452 The separator characters are specified by pt->separators, which must
6453 be a NUL-terminated string of 1 or more characters.
6454
6455 If a non-empty entry is found then:
6456
6457 - *token is set to the first byte of the entry.
6458
6459 - *len is assigned to the byte length of the entry.
6460
6461 If no entry is found then:
6462
6463 - *token, and *len are not modified.
6464
6465 - FSL_RC_NOT_FOUND is returned if the end of the path was found
6466 while tokenizing.
6467
6468 - FSL_RC_MISUSE is returned if pt->separators is NULL or empty or
6469 contains any non-ASCII characters.
6470
6471 - FSL_RC_RANGE is returned if called after the previous case, or
6472 if the input object's path has a length of 0.
6473
6474 In any non-0-return case, it's not a fatal error, it's simply
6475 information about why tokenization cannot continue, and can
6476 normally be ignored. After non-0 is returned, the tokenizer must be
6477 re-initialized if it is to be used again.
6478
6479 Example:
6480
6481 @code
6482 char const * t = 0;
6483 fsl_size_t tLen = 0;
6484 fsl_path_splitter pt = fsl_path_splitter_empty;
6485 fsl_path_splitter_init(&pt, path, pathLen);
6486 while(0==fsl_path_splitter_next(&pt, &t, &tLen)){
6487 // The next element is the tLen bytes of memory starting at t:
6488 printf("Path element: %.*s\n", (int)tLen, t);
6489 }
6490 @endcode
6491*/
6492int fsl_path_splitter_next( fsl_path_splitter * pt, char const ** token,
6493 fsl_size_t * len );
6494
6495/**
6496 Implements a cross-platform system(3) interface. It passes its
6497 argument, which must not be NULL or empty, to the equivalent of
6498 system(3). Returns 0 if that call returns 0, else it will return a
6499 FSL_RC code approximating the lower-level error code (noting that
6500 this system's man pages are a bit vague on the exact return
6501 semantics of system(3)). If it cannot convert an errno value to an
6502 approximate FSL_RC value, it will return FSL_RC_ERROR.
6503*/
6504int fsl_system(const char *zOrigCmd);
6505
6506typedef struct fsl_url fsl_url;
6507
6508/**
6509 A type for parsing URLs. Its memory is managed by fsl_url_parse()
6510 and fsl_url_cleanup().
6511*/
6512struct fsl_url {
6513 /** The raw, unparsed URL. */
6514 char const * raw;
6515 /** The URL's scheme. */
6516 char const * scheme;
6517 /** The URL's username or NULL. */
6518 char const * username;
6519 /** The URL's username's password or NULL. */
6520 char const * password;
6521 /** The remote host name. Is only NULL for file URLs. */
6522 char const * host;
6523 /** The :portNumber part or 0. */
6524 uint16_t port;
6525 /** The path. For file URLs, this is where the file's name is
6526 stored. */
6527 char const * path;
6528 /** The query string, including the '?' prefix. */
6529 char const * query;
6530 /** The fragment part, including the '#' prefix. */
6531 char const * fragment;
6532
6533 /**
6534 Private implementation details. fsl_url_parse() allocates this
6535 buffer a single time and points the other members into the memory
6536 owned by impl.b. Its approximate allocated size is a handful of
6537 bytes more than twice the strlen() of this->raw.
6538 */
6539 struct { fsl_buffer b; } impl;
6540};
6541
6542/** Initialized-with-defaults fsl_url structure, intended for
6543 const-copy initialization. */
6544#define fsl_url_empty_m { \
6545 .raw=0, .scheme=0, .username=0, .password=0, \
6546 .host=0, .port=0, .path=0, .query=0, \
6547 .fragment=0, .impl = {.b=fsl_buffer_empty_m} \
6548}
6549
6550/** Initialized-with-defaults fsl_url structure, intended for
6551 non-const copy initialization. */
6552extern const fsl_url fsl_url_empty;
6553
6554/**
6555 Attempts to parse zUrl as a URL, filling out u with the
6556 results.
6557
6558 It passes u to fsl_url_cleanup2(), with a false 2nd argument,
6559 before starting.
6560
6561 Results are undefined if zUrl is NULL.
6562
6563 On success, returns 0 and populates u. On error, returns FSL_RC_OOM
6564 or FSL_RC_SYNTAX and it passes u to fsl_url_cleanup() before
6565 returning.
6566
6567 All memory referenced by u's members is invalidated by any of
6568 the fsl_url APIs. Do not hold copies of pointers to a fsl_url
6569 member for later use.
6570
6571 For each missing component of the URL, the corresponding member of
6572 u will be NULL. A missing port is designated by 0, and a port value
6573 ouside of the range (1..65535) triggers a syntax error.
6574
6575 Quirks:
6576
6577 - It may mis-parse malformed URLs.
6578
6579 - It does no unescaping of the string. It "could" provide the query
6580 string in an unescaped form but that would require some
6581 refactoring.
6582
6583 - file URLs (in this API) do not support a host name, port, query
6584 string, or fragment. Everything after the scheme is available via
6585 u->path.
6586
6587 - zUrl may be a filesystem path, starting with either '/' or '.',
6588 in which case it is treated as if it were prefixed with
6589 "file://".
6590
6591 - file:/X and file:///X both resolve to /X. file://X, though
6592 technically illegal[^1] resolves to X.
6593
6594 - It does not recognize Windows drive letters as such. A URL in the
6595 form "file:/c:/..." or "file:///c:/..." will be assigned a
6596 u->path of "/c:/...", and "file:c:/..." will have a u->path of
6597 "c:/...". In non-file URLs, a drive letter will very probably be
6598 treated like a hostname with an invalid port (so will fail to
6599 parse).
6600
6601 [^1]: https://en.wikipedia.org/wiki/File_URI_scheme
6602*/
6603FSL_EXPORT int fsl_url_parse(fsl_url * u, char const * zUrl);
6604
6605/**
6606 Flags for use with fsl_url_render().
6607*/
6609
6610 /** Elide the scheme:// prefix. */
6612
6613 /** Elide the user name and password. */
6615
6616 /** Elide any password part of the URL. */
6618
6619 /**
6620 Render any password part of the URL as some unspecified number of
6621 "*" characters.
6622 */
6624
6625 /** Elide the query string and fragment. */
6627
6628 /** Elide the fragment. */
6630};
6631
6632/**
6633 Appends a rendering of the given parsed url object to the given
6634 buffer. The final argument can be used to modify how the rendering
6635 is done.
6636
6637 Returns pOut->errCode. If pOut->errCode is non-0 when this is
6638 called, this call is a no-op.
6639*/
6641 int flags);
6642
6643/**
6644 Equivalent to fsl_url_cleanup2(u, true).
6645*/
6647
6648/**
6649 Frees all memory owned by u, and zeroes it out, but does not free
6650 u. If freeBuffer is false then u's internal buffer is also freed
6651 otherwise it is retained, which will lead to a leak if u is not
6652 later either passed to fsl_url_cleanup() or to this function with a
6653 true freeBuffer value.
6654*/
6655FSL_EXPORT void fsl_url_cleanup2(fsl_url * u, bool freeBuffer);
6656
6657/**
6658 Swaps the contents of the given objects.
6659*/
6661
6662/**
6663 Parses key-value pairs from u->query. On the initial call, the
6664 second argument should be a pointer to a call-local NULL value.
6665
6666 If this returns true:
6667
6668 - It will have replaced bKey's contents with the
6669 next query string key, and bVal's contents to its value (if any).
6670
6671 - It sets `*zCursor` to the next parse position. The intent is that
6672 the caller pass the same pointer to each call until this function
6673 returns false.
6674
6675 It returns false if:
6676
6677 - No more URL args are found.
6678 - An allocation error while appending to bKey or bVal.
6679
6680 Regardless of success or failure, it calls fsl_buffer_reuse() on
6681 its output buffers before beginning work.
6682
6683 The query string is assumed to be URL-encoded and the parsed-out
6684 keys and values get URL-decoded when adding them to the output
6685 buffers.
6686
6687 Example:
6688
6689 ```
6690 fsl_buffer key = fsl_buffer_empty;
6691 fsl_buffer val = fsl_buffer_empty;
6692 char const * zTail = 0;
6693 while( fsl_url_next_query_arg(myUrl, &zTail, &key, &val) ){
6694 // key holds the key and val might hold a value
6695 // (else it will be empty)
6696 }
6697 fsl_buffer_clear(&key);
6698 fsl_buffer_clear(&val);
6699 ```
6700
6701 That example ignores alloc errors which happen during parsing but
6702 for completeness one should check key.errCode and val.errCode,
6703 either of which might be FSL_RC_OOM.
6704*/
6706 char const **zCursor,
6707 fsl_buffer * bKey,
6708 fsl_buffer * bVal);
6709
6710/**
6711 Converts the first nBytes bytes from pBytes to hex form, writing
6712 the result to pOut. pOut must have at least 2*nBytes+1 bytes of
6713 space, as this function writes 2*nBytes of hex and a NUL
6714 terminator to it.
6715*/
6716FSL_EXPORT void fsl_to_hex(unsigned char const *pBytes,
6717 fsl_size_t nBytes, char *pOut);
6718
6719
6720#if 0
6721/**
6722 The UTF16 counterpart of fsl_looks_like_utf8(), with the addition that the
6723 2nd argument, if true, specifies that the 2nd argument is true then
6724 the contents of the buffer are byte-swapped for checking purposes.
6725
6726 This does not validate that the blob is valid UTF16. It assumes that all
6727 code points are the same size and does not validate any of them, nor does
6728 it attempt to detect (invalid) switches between big-endian and little-endian.
6729 */
6730FSL_EXPORT int fsl_looks_like_utf16(fsl_buffer const * pContent,
6731 bool reverse, int stopFlags);
6732
6733/**
6734 Returns true if b'c contents begin with a UTF-16 BOM. If pBomSize is not NULL
6735 then it is set to the byte length of the UTF-16 BOM (2 bytes). If isReversed
6736 is not NULL, it gets assigned to true if the input appears to be in little-endian
6737 format and false if it appears to be in big-endian format.
6738*/
6739FSL_EXPORT bool fsl_starts_with_bom_utf16(fsl_buffer const * b, unsigned int *pBomSize,
6740 bool * isReversed);
6741/**
6742 Returns true if b's content _might_ be valid UTF-16. If the 2nd argument is not NULL,
6743 it gets set to true if the input appears to be little-endian and false if it appears
6744 to be big-endian.
6745*/
6746FSL_EXPORT bool fsl_might_be_utf16(fsl_buffer const * b, bool * isReversed);
6747#endif
6748/* ^^^^ UTF-16 interfaces */
6749
6750#if defined(__cplusplus)
6751} /*extern "C"*/
6752#endif
6753#endif
6754/* ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED */
int32_t fsl_id_t
fsl_id_t is a signed integer type used to store database record IDs.
Definition config.h:271
uint64_t fsl_size_t
fsl_size_t is an unsigned integer type used to denote absolute ranges and lengths.
Definition config.h:192
int64_t fsl_time_t
The type used to represent type values.
Definition config.h:296
int64_t fsl_int_t
fsl_int_t is a signed integer type used to denote "relative" ranges and lengths, or to tell a routine...
Definition config.h:143
#define FSL_EXPORT
Definition config.h:66
uint64_t fsl_uint_t
The unsigned counterpart of fsl_int_t.
Definition config.h:147
Holds an allocator function and its related state.
Definition util.h:403
void * state
State intended to be passed as the first argument to this->f().
Definition util.h:412
fsl_realloc_f f
Base allocator function.
Definition util.h:408
A general-purpose buffer class, analog to Fossil's Blob class, but it is not called fsl_blob to avoid...
Definition util.h:684
fsl_size_t cursor
Used by some routines to keep a cursor into this->mem.
Definition util.h:741
int errCode
When any buffer-related routines encounter an error, they set this flag so that the error can be prop...
Definition util.h:759
unsigned char * mem
The raw memory pointed to by this buffer.
Definition util.h:709
fsl_size_t used
Number of "used" bytes in the buffer.
Definition util.h:735
fsl_size_t capacity
Number of bytes allocated for this buffer.
Definition util.h:717
A struct for passing on interactive questions to fsl_confirmer_callback_f implementations.
Definition util.h:6040
const char * filename
Depending on the eventId, this might be NULL or might refer to a filename.
Definition util.h:6066
const fsl_list * multi
Depending on the eventId, this might be NULL or might refer to a list of details of a type specified ...
Definition util.h:6094
fsl_confirm_event_e eventId
The message ID of this confirmation request.
Definition util.h:6046
A response for use with the fsl_confirmer API.
Definition util.h:6004
fsl_confirm_response_e response
Client response to the current fsl_confirmer question.
Definition util.h:6008
uint16_t multipleChoice
If this->response is FSL_CRESPONSE_MULTI then this must be set to the index of the client's multiple-...
Definition util.h:6017
A fsl_confirm_callback_f and its callback state, packaged into a neat little struct for easy copy/rep...
Definition util.h:6128
void * callbackState
Opaque state pointer for this->callback.
Definition util.h:6140
fsl_confirm_callback_f callback
Callback which can be used for basic interactive confirmation purposes, within the very libfossil-cen...
Definition util.h:6134
EXPERIMENTAL AND SUBJECT TO CHANGE.
Definition util.h:3973
char const * edit
Color escape sequence for edited or replaced lines.
Definition util.h:3983
char const * insertion
Color escape sequence for inserted lines.
Definition util.h:3977
char const * deletion
Color escape sequence for inserted lines.
Definition util.h:3987
char const * reset
Escape sequence to reset colors.
Definition util.h:3993
An instance of this class is used to convey certain state to fsl_dibu objects.
Definition util.h:3891
unsigned short columnWidth
Maximum column width hint for side-by-side, a.k.a.
Definition util.h:3914
const char * hashRHS
The hash of the object represented by the RHS of the diff.
Definition util.h:3939
struct fsl_dibu_opt::fsl_dibu_opt_ansi ansiColor
uint32_t diffFlags
Flags from the fsl_diff2_flag_e enum.
Definition util.h:3895
const char * nameRHS
The filename of the object represented by the LHS of the diff.
Definition util.h:3933
const char * hashLHS
The hash of the object represented by the LHS of the diff.
Definition util.h:3926
const char * nameLHS
The filename of the object represented by the LHS of the diff.
Definition util.h:3920
fsl_output_f out
Output destination.
Definition util.h:3950
unsigned short contextLines
Number of lines of diff context (number of lines common to the LHS and RHS of the diff).
Definition util.h:3900
void * outState
State for this->out().
Definition util.h:3957
This class is the basis of libfossil's port of the diff engine added to fossil(1) in 2021-09,...
Definition util.h:4190
uint32_t fileCount
A place to store the number of files seen by this builder so far, for builders which need to distingu...
Definition util.h:4417
uint32_t lnRHS
Number of lines seen of the RHS content.
Definition util.h:4429
int(* chunkHeader)(fsl_dibu *, uint32_t A, uint32_t B, uint32_t C, uint32_t D)
If this is not NULL, it is called one time at the start of each chunk of diff for a given file and is...
Definition util.h:4257
unsigned int implFlags
Space for implementation-specific flags which clients may set to modify the dibu's behaviour.
Definition util.h:4403
void(* finalize)(fsl_dibu *)
Must free any state owned by this builder, including the builder object.
Definition util.h:4369
int(* edit)(fsl_dibu *, fsl_dline const *lineLhs, fsl_dline const *lineRhs)
Tells the builder that the given line represents an "edit" from the LHS to the RHS.
Definition util.h:4328
unsigned short passNumber
Gets set to the "pass number" immediately before this->start() is called, starting with pass number 1...
Definition util.h:4384
unsigned int pimplFlags
Space for private, implementation-specific flags, e.g.
Definition util.h:4395
uint32_t edits
Number of line-level edits performed so far.
Definition util.h:4449
int(* insertion)(fsl_dibu *, fsl_dline const *line)
Tells the builder that the given line represents an "insert" into the RHS.
Definition util.h:4288
fsl_dibu_opt const * opt
Config info, owned by higher-level routines.
Definition util.h:4203
void const * typeID
Can optionally be set by factory functions to some internal opaque value, so that non-member routines...
Definition util.h:4209
int(* start)(fsl_dibu *b)
If not NULL, this is called once per pass per diff to give the builder a chance to perform any bootst...
Definition util.h:4232
bool twoPass
If true, this builder gets passed through the diff generation process twice.
Definition util.h:4374
uint32_t insertions
Number of lines inserted performed so far.
Definition util.h:4445
uint32_t lnLHS
Number of lines seen of the LHS content.
Definition util.h:4423
int(* common)(fsl_dibu *, fsl_dline const *line)
Tells the builder that the given line represents one line of common output.
Definition util.h:4279
struct fsl_dibu::@254044115043113031362313315375067017031033007272 metrics
Metrics maintained by the core diff algorithm.
int(* skip)(fsl_dibu *, uint32_t n)
Tells the builder that n lines of common output are to be skipped.
Definition util.h:4270
void * pimpl
Impl-specific diff-generation state.
Definition util.h:4389
int(* finish)(fsl_dibu *b)
Must "finish" the diff process.
Definition util.h:4351
int(* deletion)(fsl_dibu *, fsl_dline const *line)
Tells the builder that the given line represents a "deletion" - a line removed from the LHS.
Definition util.h:4298
int(* replacement)(fsl_dibu *, fsl_dline const *lineLhs, fsl_dline const *lineRhs)
Tells the builder that the given line represents a replacement from the LHS to the RHS.
Definition util.h:4312
uint32_t replacements
Number of line replacements performed so far.
Definition util.h:4453
uint32_t deletions
Number of lines deleted so far.
Definition util.h:4447
State for use with fsl_dircrawl_f() callbacks.
Definition util.h:6155
fsl_fstat_type_e entryType
Filesystem entry type.
Definition util.h:6167
char const * entryName
Name (no path part) of the entry being visited.
Definition util.h:6163
char const * absoluteDir
Absolute directory name of the being-visited directory.
Definition util.h:6159
void * callbackState
Opaque client-specified pointer which was passed to fsl_dircrawl().
Definition util.h:6172
unsigned int depth
Directory depth of the crawl process, starting at 1 with the directory passed to fsl_dircrawl().
Definition util.h:6178
Array of change spans, in left-to-right order.
Definition util.h:4074
int iStart1
Byte offset to start of a change on the left.
Definition util.h:4078
int iLen1
Length of the left change in bytes.
Definition util.h:4080
int iLen2
Length of the change on the right in bytes.
Definition util.h:4084
int iStart2
Byte offset to start of a change on the right.
Definition util.h:4082
int isMin
True if this change is known to have no useful subdivs.
Definition util.h:4086
This "mostly-internal" type describes zero or more (up to fsl_dline_change_max_spans) areas of differ...
Definition util.h:4070
struct fsl_dline_change::fsl_dline_change_span a[fsl_dline_change_max_spans]
unsigned char n
Number of change spans (number of used elements in this->a).
Definition util.h:4072
Information about each line of a file being diffed.
Definition util.h:4023
const char * z
The text of the line.
Definition util.h:4028
unsigned int iHash
An array of fsl_dline elements serves two purposes.
Definition util.h:4045
unsigned short indent
Index of first non-space char.
Definition util.h:4033
unsigned short nw
Number of bytes without leading/trailing space.
Definition util.h:4035
unsigned int iNext
1+(Index of next line with same the same hash)
Definition util.h:4039
unsigned short n
Number of bytes of z which belong to this line.
Definition util.h:4030
uint64_t h
Hash of the line.
Definition util.h:4037
A container for storing generic error state.
Definition util.h:781
int code
Error code, generally assumed to be a fsl_rc_e value.
Definition util.h:791
fsl_buffer msg
Error message text is stored in this->msg.mem.
Definition util.h:786
Generic interface for memory finalizers.
Definition util.h:208
fsl_finalizer_f f
Finalizer function.
Definition util.h:216
void * state
State to be passed as the first argument to f().
Definition util.h:212
A simple wrapper around the stat(2) structure resp.
Definition util.h:3321
fsl_time_t mtime
Last modification time.
Definition util.h:3336
int perm
Contains the filesystem entry's permissions as a bitmask of fsl_fstat_perm_e values.
Definition util.h:3346
fsl_size_t size
The size of the stat'd file, in bytes.
Definition util.h:3340
fsl_fstat_type_e type
Indicates the type of filesystem object.
Definition util.h:3325
fsl_time_t ctime
The time of the last file metadata change (owner, permissions, etc.).
Definition util.h:3332
A container type for lists of db record IDs.
Definition util.h:5694
fsl_size_t entryCount
Number of entries of this->list which are in use (have a positive value).
Definition util.h:5700
fsl_id_t * list
Array of IDs this->capacity elements long.
Definition util.h:5714
fsl_size_t capacity
The number of elements allocated for this->list.
Definition util.h:5704
fsl_size_t used
The number of elements in this->list which have a zero or positive value.
Definition util.h:5709
Generic list container type.
Definition util.h:156
fsl_size_t capacity
Number of slots allocated in this->list.
Definition util.h:171
fsl_size_t used
Number of "used" entries in the list.
Definition util.h:165
void ** list
Array of entries.
Definition util.h:161
An interface which encapsulates data for managing an output destination, primarily intended for use w...
Definition util.h:337
fsl_output_f out
Output channel.
Definition util.h:341
void * state
State to be used when calling this->out(), namely: this->out( this->state, ... ) and this->flush(this...
Definition util.h:352
fsl_flush_f flush
flush() implementation.
Definition util.h:347
A helper type for tokenizing conventional PATH-style strings.
Definition util.h:6398
char const * begin
Begining of the input range.
Definition util.h:6400
char const * separators
List of token separator characters (ASCII only).
Definition util.h:6406
char const * pos
Position for the next token lookup.
Definition util.h:6404
char const * end
One-after-the-end of the input range.
Definition util.h:6402
The "Path Finder" class is a utility class for searching the filesystem for files matching a set of c...
Definition util.h:4936
fsl_buffer buf
Used to build up a path string during fsl_pathfinder_search(), and holds the result of a successful s...
Definition util.h:4954
fsl_list ext
Holds the list of search extensions.
Definition util.h:4941
fsl_list dirs
Holds the list of search directories.
Definition util.h:4946
Generic state-with-finalizer holder.
Definition util.h:238
fsl_finalizer finalize
Finalizer for this->state.
Definition util.h:253
void * state
Arbitrary context-dependent state.
Definition util.h:242
State for the fsl_timer_xxx() family of functions.
Definition util.h:5447
uint64_t wall
The microseconds of "wall clock" time.
Definition util.h:5463
uint64_t user
The amount of time (microseconds) spent in "user space".
Definition util.h:5451
uint64_t system
The amount of time (microseconds) spent in "kernel space".
Definition util.h:5456
A type for parsing URLs.
Definition util.h:6512
fsl_buffer b
Definition util.h:6539
char const * username
The URL's username or NULL.
Definition util.h:6518
char const * raw
The raw, unparsed URL.
Definition util.h:6514
char const * fragment
The fragment part, including the '#' prefix.
Definition util.h:6531
uint16_t port
The :portNumber part or 0.
Definition util.h:6524
char const * scheme
The URL's scheme.
Definition util.h:6516
struct fsl_url::@106362302377216014057344117270115016120004110352 impl
Private implementation details.
char const * query
The query string, including the '?
Definition util.h:6529
char const * host
The remote host name.
Definition util.h:6522
char const * path
The path.
Definition util.h:6527
char const * password
The URL's username's password or NULL.
Definition util.h:6520
A utility class for creating ZIP-format archives.
Definition util.h:5138
int32_t dosDate
Current DOS-format date of the ZIP.
Definition util.h:5150
char * rootDir
An artificial root directory which gets prefixed to all inserted filenames.
Definition util.h:5159
fsl_time_t unixTime
Current Unix Epoch time of the ZIP.
Definition util.h:5154
fsl_size_t entryCount
Number of entries (files + dirs) added to the zip file so far.
Definition util.h:5142
fsl_buffer body
The buffer for the ZIP file body.
Definition util.h:5167
fsl_list dirs
The current list of directory entries (as (char *)).
Definition util.h:5176
int32_t dosTime
Current DOS-format time of the ZIP.
Definition util.h:5146
fsl_buffer toc
The buffer for the table of contents.
Definition util.h:5163
fsl_buffer scratch
Internal scratchpad for ops which often allocate small buffers.
Definition util.h:5172
const fsl_dibu_opt fsl_dibu_opt_empty
Initialized-with-defaults fsl_dibu_opt structure, intended for non-const copy initialization.
FSL_EXPORT int fsl_buffer_compare(fsl_buffer const *lhs, fsl_buffer const *rhs)
Compares the contents of buffers lhs and rhs using memcmp(3) semantics.
FSL_EXPORT void * fsl_malloc(fsl_size_t n)
Semantically behaves like malloc(3), but may introduce instrumentation, error checking,...
FSL_EXPORT const fsl_zip_writer fsl_zip_writer_empty
An initialized-with-defaults fsl_zip_writer instance, intended for copy-initialization.
Definition util.h:5200
FSL_EXPORT fsl_int_t fsl_data_uncompressed_size(unsigned char const *mem, fsl_size_t len)
If fsl_data_is_compressed(mem,len) returns true then this function returns the uncompressed size of t...
FSL_EXPORT fsl_int_t fsl_str_to_int(char const *str, fsl_int_t dflt)
Expects str to be a string containing a decimal value, optionally with a leading sign.
FSL_EXPORT int fsl_buffer_delta_apply2(fsl_buffer const *pOriginal, fsl_buffer const *pDelta, fsl_buffer *pTarget, fsl_error *pErr)
Identical to fsl_buffer_delta_apply() except that if delta application fails then any error messages/...
FSL_EXPORT const char * fsl_file_tail(const char *z)
Return the tail of a NUL-terminated file pathname.
FSL_EXPORT int fsl_error_setv(fsl_error *err, int code, char const *fmt, va_list args)
va_list counterpart to fsl_error_set().
FSL_EXPORT void fsl_glob_list_clear(fsl_list *globList)
If globList is not NULL this is equivalent to fsl_list_visit_free(globList, 1), otherwise it is a no-...
FSL_EXPORT bool fsl_is_symlink(const char *zFilename)
Returns true if the given file is a symlink, else false.
FSL_EXPORT fsl_buffer const * fsl_zip_body(fsl_zip_writer const *z)
Returns a pointer to z's ZIP content buffer.
FSL_EXPORT char * fsl_unicode_to_utf8(const void *zUnicode)
Translates Unicode text into UTF-8.
FSL_EXPORT fsl_size_t fsl_strlen_utf8(char const *str, fsl_int_t n)
Returns the number of UTF8 characters which begin within the first n bytes of str (noting that it's p...
FSL_EXPORT bool fsl_str_is_date(const char *z)
Returns true if the first 10 digits of z appear to form the start of an ISO date string (YYYY-MM-DD).
FSL_EXPORT int fsl_output_f_fsl_cx(void *state, void const *src, fsl_size_t n)
fsl_output_f() implementation which requires state to be a (fsl_cx*) to which this routine simply red...
FSL_EXPORT void fsl_temp_dirs_free(char **aDirs)
If aDirs is not NULL then it is expected to be an array created by fsl_temp_dirs_get() and it frees t...
FSL_EXPORT int fsl_url_render(fsl_url const *u, fsl_buffer *pOut, int flags)
Appends a rendering of the given parsed url object to the given buffer.
FSL_EXPORT fsl_int_t fsl_buffer_getline(char **ret, size_t *retsz, fsl_buffer *buf)
Equivalent to fsl_buffer_getdelim() with delim equal to ' '.
FSL_EXPORT bool fsl_starts_with_bom_utf8(fsl_buffer const *b, unsigned int *pBomSize)
Returns true if b starts with a UTF8 BOM.
FSL_EXPORT int fsl_buffer_compare_file(fsl_buffer const *b, char const *zFile)
Bitwise-compares the contents of b against the file named by zFile.
fsl_fstat_perm_e
Bitmask values for use with the fsl_fstat::perms field.
Definition util.h:3301
@ FSL_FSTAT_PERM_UNKNOWN
Sentinel value.
Definition util.h:3305
@ FSL_FSTAT_PERM_EXE
The executable bit, as understood by Fossil.
Definition util.h:3310
FSL_EXPORT int fsl_delta_create2(unsigned char const *zV1, fsl_size_t lenV1, unsigned char const *zV2, fsl_size_t lenV2, fsl_output_f out, void *outState)
Works identically to fsl_delta_create() but sends its output to the given output function.
FSL_EXPORT void fsl_error_propagate(fsl_error *from, fsl_error *to)
Swaps the state between two fsl_error objects and then resets the error state on the from object.
FSL_EXPORT void * fsl_realloc_f_stdalloc(void *state, void *mem, fsl_size_t n)
A fsl_realloc_f() implementation which uses the standard malloc()/free()/realloc().
FSL_EXPORT int fsl_snprintfv(char *dest, fsl_size_t n, char const *fmt, va_list args)
va_list counterpart to fsl_snprintf()
FSL_EXPORT int fsl_zip_end(fsl_zip_writer *z)
Ends the ZIP-creation process, padding all buffers, writing all final required values,...
#define fsl_buffer_capacity(b)
Returns the current capacity of b, or 0 if !b.
Definition util.h:1536
FSL_EXPORT int fsl_fprintfv(FILE *fp, char const *fmt, va_list args)
The va_list counterpart of fsl_fprintf().
#define fsl_dline_change_max_spans
Maximum number of change spans for fsl_dline_change.
Definition util.h:4062
FSL_EXPORT int fsl_list_reserve(fsl_list *self, fsl_size_t n)
Possibly reallocates self->list, changing its size.
fsl_confirm_response_e
Answers to questions posed to clients via the fsl_confirm_callback_f() interface.
Definition util.h:5951
@ FSL_CRESPONSE_YES
Accept the current event and continue processes.
Definition util.h:5962
@ FSL_CRESPONSE_MULTI
For events which are documented as being multiple-choice, this answer indicates that the client has s...
Definition util.h:5990
@ FSL_CRESPONSE_CANCEL
Reject the current event and stop processesing.
Definition util.h:5971
@ FSL_CRESPONSE_ALWAYS
Accept the current event and all identical event types for the current invocation of this particular ...
Definition util.h:5976
@ FSL_CRESPONSE_INVALID
Sentinel/default value - not a valid answer.
Definition util.h:5958
@ FSL_CRESPONSE_NEVER
Reject the current event and all identical event types for the current invocation of this particular ...
Definition util.h:5981
@ FSL_CRESPONSE_NO
Reject the current event and continue processes.
Definition util.h:5966
FSL_EXPORT int fsl_buffer_ensure_eol(fsl_buffer *b)
Add an EOL to b if it has content (i.e.
FSL_EXPORT fsl_id_t fsl_id_bag_next(fsl_id_bag const *p, fsl_id_t e)
Returns the next element in the bag after e.
FSL_EXPORT int fsl_zip_end_take(fsl_zip_writer *z, fsl_buffer *dest)
This variant of fsl_zip_end() transfers the current contents of the zip's body to dest,...
FSL_EXPORT char * fsl_htmlize_str(const char *zIn, fsl_int_t n)
Equivalent to fsl_htmlize_to_buffer() but returns the result as a new string which must eventually be...
FSL_EXPORT const fsl_timer fsl_timer_empty
Initialized-with-defaults fsl_timer instance, intended for non-const copy initialization.
Definition util.h:5477
FSL_EXPORT int fsl_stricmp(const char *zA, const char *zB)
Case-insensitive form of fsl_strcmp().
FSL_EXPORT int fsl_symlink_read(fsl_buffer *tgt, char const *zFilename)
This function expects its second argument to refer to a symlink (and that the caller has already vali...
FSL_EXPORT int fsl_glob_list_append(fsl_list *tgt, char const *zGlob)
Appends a single blob pattern to tgt, in the form of a new (char *) owned by tgt.
FSL_EXPORT int fsl_find_home_dir(fsl_buffer *tgt, bool requireWriteAccess)
Tries to find the user's home directory.
int fsl_system(const char *zOrigCmd)
Implements a cross-platform system(3) interface.
FSL_EXPORT int fsl_buffer_materialize(fsl_buffer *b)
If b is a "managed" buffer, this is a no-op and returns 0, else b is an "external" buffer and it....
FSL_EXPORT int fsl_buffer_reserve(fsl_buffer *b, fsl_size_t n)
Reserves at least n bytes of capacity in buf.
FSL_EXPORT void fsl_free(void *mem)
Semantically behaves like free(3), but may introduce instrumentation, error checking,...
FSL_EXPORT void fsl_buffer_chomp(fsl_buffer *b)
If b ends with a \n character or a pair of \r\n, the \n or \r\n pair are "chomped" (to use Perl's ter...
FSL_EXPORT bool fsl_is_file(const char *zFilename)
Returns true if the named file is an ordinary file.
FSL_EXPORT int fsl_chdir2(const char *zTo, char *zCurrent, fsl_size_t nCurrent)
Works like fsl_chdir(zTo) but passes (zCurrent,nCurrent,NULL) to fsl_getcwd() to save the current dir...
FSL_EXPORT char * fsl_mprintf(char const *fmt,...)
Works like fsl_appendfv(), but appends all output to a dynamically-allocated string,...
FSL_EXPORT int fsl_tolower(int c)
Returns the upper-case form of c if c is an ASCII alphabet letter, else returns c.
FSL_EXPORT int fsl_output_f_buffer(void *state, void const *src, fsl_size_t n)
A fsl_output_f() impl which requires state to be-a (fsl_buffer*), which this function passes to fsl_b...
FSL_EXPORT char * fsl_filename_to_utf8(const void *zFilename)
Translate text from the OS's character set into UTF-8.
FSL_EXPORT char * fsl_strdup(char const *src)
Equivalent to fsl_strndup(src,-1).
FSL_EXPORT char * fsl_buffer_str(fsl_buffer const *b)
Equivalent to ((char *)b->mem) except that if b->errCode is non-0 then NULL is returned.
FSL_EXPORT int fsl_strcmp_cmp(void const *lhs, void const *rhs)
Equivalent to fsl_strcmp(), but with a signature suitable for use as a generic comparison function (e...
FSL_EXPORT int fsl_dline_cmp_ignore_ws(const fsl_dline *pA, const fsl_dline *pB)
Counterpart of fsl_dline_cmp() but ignores all whitespace when comparing for equivalence.
FSL_EXPORT void fsl_dibu_finalizer(fsl_dibu *b)
This is a generic finalizer function for use as a fsl_dibu::finalize() method.
FSL_EXPORT int fsl_file_rename(const char *zFrom, const char *zTo)
Renames file zFrom to zTo using the OS's equivalent of rename(2).
FSL_EXPORT void fsl_dline_change_spans(const fsl_dline *pLeft, const fsl_dline *pRight, fsl_dline_change *p)
Given two lines of a diff, this routine computes a set of changes between those lines for display pur...
FSL_EXPORT void fsl_id_bag_clear(fsl_id_bag *p)
Frees any memory owned by p, but does not free p.
FSL_EXPORT fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash)
Simplify a filename by:
FSL_EXPORT int fsl_fprintf(FILE *fp, char const *fmt,...)
Emulates fprintf() using fsl_appendf().
FSL_EXPORT int fsl_rmdir(const char *zFilename)
Deletes an empty directory from the filesystem.
FSL_EXPORT const fsl_buffer fsl_buffer_empty
Empty-initialized fsl_buffer instance, intended for copy initialization.
Definition util.h:769
FSL_EXPORT int fsl_dline_cmp(const fsl_dline *pA, const fsl_dline *pB)
Compares two fsl_dline instances using memcmp() semantics, returning 0 if they are equivalent.
FSL_EXPORT fsl_id_bag * fsl_id_bag_reuse(fsl_id_bag *p)
Resets p's internal list, effectively emptying it for re-use, but does not free its memory.
FSL_EXPORT int fsl_pathfinder_split(fsl_pathfinder *tgt, bool isDirs, char const *path, fsl_int_t pathLen)
Splits a conventional path-separator-delimited string into tokens and adds each as either a directory...
FSL_EXPORT bool fsl_looks_like_binary(fsl_buffer const *b)
Returns true if b appears to contain "binary" (non-UTF8/16) content, else returns false.
FSL_EXPORT int fsl_snprintf(char *dest, fsl_size_t n, char const *fmt,...)
An sprintf(3) clone which uses fsl_appendf() for the formatting.
FSL_EXPORT int fsl_dir_is_empty(const char *path)
Check the given path to determine whether it is an empty directory.
FSL_EXPORT int fsl_zip_root_set(fsl_zip_writer *z, char const *zRoot)
Sets a virtual root directory in z, such that all files added with fsl_zip_file_add() will get this d...
FSL_EXPORT int fsl_appendfv(fsl_output_f pfAppend, void *pfAppendArg, const char *fmt, va_list ap)
This function works similarly to classical printf implementations, but instead of outputing somewhere...
FSL_EXPORT void fsl_buffer_err_clear(fsl_buffer *b)
Resets the error code of the given buffer to 0.
FSL_EXPORT int fsl_strnicmp(const char *zA, const char *zB, fsl_int_t nByte)
fsl_strcmp() variant which compares at most nByte bytes of the given strings, case-insensitively.
FSL_EXPORT int fsl_bytes_fossilize(unsigned char const *inp, fsl_int_t len, fsl_buffer *out)
"Fossilizes" the first len bytes of the given input string.
void(* fsl_finalizer_f)(void *state, void *mem)
Generic interface for finalizing/freeing memory.
Definition util.h:203
void *(* fsl_realloc_f)(void *state, void *mem, fsl_size_t n)
Generic stateful alloc/free/realloc() interface.
Definition util.h:398
FSL_EXPORT void fsl_list_swap(fsl_list *lhs, fsl_list *rhs)
Swaps all contents of both lhs and rhs.
FSL_EXPORT int fsl_finalizer_f_buffer(void *state, void *mem)
fsl_finalizer_f() impl which requires that mem be-a (fsl_buffer*).
FSL_EXPORT int fsl_input_f_buffer(void *state, void *dest, fsl_size_t *n)
A fsl_input_f() implementation which requires that state be a readable (fsl_buffer*) handle.
FSL_EXPORT int fsl_delta_apply2(unsigned char const *zSrc, fsl_size_t lenSrc, unsigned char const *zDelta, fsl_size_t lenDelta, unsigned char *zOut, fsl_error *pErr)
Functionally identical to fsl_delta_apply() but any errors generated during application of the delta ...
FSL_EXPORT int fsl_stricmp_cmp(void const *lhs, void const *rhs)
Equivalent to fsl_stricmp(), but with a signature suitable for use as a generic comparison function (...
FSL_EXPORT int fsl_buffer_strftime(fsl_buffer *b, char const *format, const struct tm *timeptr)
A convenience form of fsl_strftime() which assumes that the formatted string is of "some reasonable s...
FSL_EXPORT bool fsl_is_file_or_link(const char *zFilename)
Returns true if the given filename refers to a plain file or symlink, else returns false.
FSL_EXPORT const fsl_list fsl_list_empty
Empty-initialized fsl_list structure, intended for copy initialization.
Definition util.h:184
FSL_EXPORT int fsl_appendn(fsl_output_f pfAppend, void *pfAppendArg, const char *str, fsl_int_t n)
Works like fsl_appendf() except that it sends the first n bytes of str as-is to pfAppend().
FSL_EXPORT fsl_size_t fsl_buffer_tell(fsl_buffer const *b)
Returns the buffer's current cursor position.
FSL_EXPORT bool fsl_islower(int c)
Returns true if c is a lower-case ASCII alphabet character.
FSL_EXPORT const fsl_confirm_detail fsl_confirm_detail_empty
Empty-initialized fsl_confirm_detail instance to be used for non-const-copy initialization.
Definition util.h:6109
fsl_fstat_type_e
Values for use with the fsl_fstat::type field.
Definition util.h:3276
@ FSL_FSTAT_TYPE_DIR
Indicates a directory filesystem entry.
Definition util.h:3280
@ FSL_FSTAT_TYPE_LINK
Indicates a symlink filesystem entry.
Definition util.h:3288
@ FSL_FSTAT_TYPE_FILE
Indicates a non-directory, non-symlink filesystem entry.
Definition util.h:3286
@ FSL_FSTAT_TYPE_UNKNOWN
Sentinel value for unknown/invalid filesystem entry types.
Definition util.h:3278
FSL_EXPORT int fsl_buffer_append_hex(fsl_buffer *b, void const *src, fsl_uint_t n, bool upperCase)
Hex-encodes n bytes of src into n*2 hex-digit bytes appended to b.
FSL_EXPORT int fsl_toupper(int c)
Returns the lower-case form of c if c is an ASCII alphabet letter, else returns c.
FSL_EXPORT void fsl_buffer_defossilize(fsl_buffer *b)
Defossilizes the contents of b.
FSL_EXPORT int fsl_zip_end_to_filename(fsl_zip_writer *z, char const *filename)
This variant of fsl_zip_end_take() passes z to fsl_zip_end(), write's the ZIP body to the given filen...
const fsl_dibu fsl_dibu_empty
Initialized-with-defaults fsl_dibu structure, intended for non-const copy initialization.
FSL_EXPORT bool fsl_is_simple_pathname(const char *z, bool bStrictUtf8)
Return true if the filename given is a valid filename for a file in a repository.
FSL_EXPORT int fsl_glob_list_parse(fsl_list *tgt, char const *zPatternList)
Parses zPatternList as a comma-and/or-fsl_isspace()-delimited list of glob patterns (as supported by ...
FSL_EXPORT fsl_size_t fsl_strftime(char *dest, fsl_size_t destLen, const char *format, const struct tm *timeptr)
A custom strftime() implementation.
FSL_EXPORT bool fsl_id_bag_remove(fsl_id_bag *p, fsl_id_t e)
Remove element e from the bag if it exists in the bag.
FSL_EXPORT int fsl_is_uuid(char const *str)
If the NUL-terminated input str is exactly FSL_STRLEN_SHA1 or FSL_STRLEN_K256 bytes long and contains...
FSL_EXPORT bool fsl_buffer_eq(fsl_buffer const *b, char const *str, fsl_int_t nStr)
Compares b and the first nStr bytes of the given string.
FSL_EXPORT bool fsl_invalid_utf8(fsl_buffer const *b)
Returns true if b's contents appear to contain anything other than valid UTF8.
FSL_EXPORT int fsl_id_bag_copy(fsl_id_bag const *src, fsl_id_bag *dest)
Copies all entries from src into dest.
FSL_EXPORT bool fsl_str_bool(char const *s)
Returns false if s is NULL or starts with any of (0 (NUL), '0' (ASCII character zero),...
FSL_EXPORT int fsl_file_canonical_name2(const char *zRoot, const char *zOrigName, fsl_buffer *pOut, bool slash)
Computes a canonical pathname for a file or directory.
int(* fsl_list_visitor_f)(void *obj, void *visitorState)
Generic visitor interface for fsl_list lists.
Definition util.h:2238
fsl_dibu_e
Type IDs for use with fsl_dibu_factory().
Definition util.h:4477
@ FSL_DIBU_TCL
A diff builder which outputs a description of the diff in a TCL-readable form.
Definition util.h:4548
@ FSL_DIBU_INVALID
Sentinel entry.
Definition util.h:4481
@ FSL_DIBU_DEBUG
A "dummy" diff builder intended only for testing the fsl_dibu interface and related APIs.
Definition util.h:4487
@ FSL_DIBU_JSON1
Generates diffs in a compact low(ist)-level form originally designed for use by diff renderers implem...
Definition util.h:4527
@ FSL_DIBU_SPLIT_TEXT
A pain-text side-by-side (a.k.a.
Definition util.h:4555
@ FSL_DIBU_UNIFIED_TEXT
A diff builder which produces output compatible with the patch(1) command.
Definition util.h:4541
FSL_EXPORT void fsl_buffer_swap_free(fsl_buffer *left, fsl_buffer *right, int clearWhich)
Similar fsl_buffer_swap() but it also optionally frees one of the buffer's memories after swapping th...
FSL_EXPORT fsl_id_t fsl_id_bag_first(fsl_id_bag const *p)
Returns the ID of the first element in the bag.
FSL_EXPORT int fsl_id_bag_to_buffer(fsl_id_bag const *bag, fsl_buffer *b, char const *separator)
Appends each ID from the given bag to the given buffer using the given separator string.
FSL_EXPORT int fsl_error_copy(fsl_error const *src, fsl_error *dest)
Copies the error state from src to dest.
FSL_EXPORT void fsl_pathfinder_clear(fsl_pathfinder *pf)
Frees all memory associated with pf, but does not free pf.
FSL_EXPORT int fsl_list_visit_p(fsl_list *self, int order, bool shiftIfNulled, fsl_list_visitor_f visitor, void *visitorState)
Works similarly to the visit operation without the _p suffix except that the pointer the visitor func...
FSL_EXPORT int fsl_htmlize_to_buffer(fsl_buffer *p, const char *zIn, fsl_int_t n)
Functionally equivalent to fsl_htmlize() but optimized to perform only a single allocation.
FSL_EXPORT const fsl_outputer fsl_outputer_FILE
A fsl_outputer instance which is initialized to output to a (FILE*).
Definition util.h:368
FSL_EXPORT int fsl_buffer_to_filename(fsl_buffer const *b, char const *fname)
Writes the given buffer to the given filename.
FSL_EXPORT char const * fsl_last_path_sep(char const *str, fsl_int_t slen)
Given a filename and its length, this function returns a pointer to the last instance of a path separ...
FSL_EXPORT int fsl_list_visit(fsl_list const *self, int order, fsl_list_visitor_f visitor, void *visitorState)
For each item in self->list, visitor(item,visitorState) is called.
FSL_EXPORT void fsl_id_bag_swap(fsl_id_bag *lhs, fsl_id_bag *rhs)
Swaps the contents of the given bags.
char * fsl_uuid_str
fsl_uuid_str and fsl_uuid_cstr are "for documentation andreadability purposes" typedefs used to denot...
Definition util.h:72
FSL_EXPORT void fsl_url_swap(fsl_url *lhs, fsl_url *rhs)
Swaps the contents of the given objects.
FSL_EXPORT int fsl_str_is_date2(const char *z)
Checks if z is syntactically a time-format string in the format:
FSL_EXPORT void fsl_buffer_external(fsl_buffer *b, void const *mem, fsl_int_t n)
Initializes b to be an "external" buffer pointing to n bytes of the given memory.
FSL_EXPORT void fsl_os_str_free(void *pOld)
Deallocate pOld, which must be NULL or must have been allocated by fsl_filename_to_utf8(),...
FSL_EXPORT fsl_size_t fsl_strip_trailing_slashes(char *name, fsl_int_t nameLen)
Strips any trailing slashes ('/') from the given string by assigning those bytes to NUL and returns t...
FSL_EXPORT int fsl_getcwd(char *zBuf, fsl_size_t nBuf, fsl_size_t *outLen)
Writes the absolute path name of the current directory to zBuf, which must be at least nBuf bytes lon...
FSL_EXPORT int fsl_id_bag_insert(fsl_id_bag *p, fsl_id_t e)
Insert element e into the bag if it is not there already.
#define fsl_buffer_size(b)
Returns the "used" size of b, or 0 if !b.
Definition util.h:1528
FSL_EXPORT int fsl_buffer_delta_apply(fsl_buffer const *pOriginal, fsl_buffer const *pDelta, fsl_buffer *pTarget)
Apply the delta in pDelta to the original content pOriginal to generate the target content pTarget.
FSL_EXPORT int fsl_delta_apply(unsigned char const *zSrc, fsl_size_t lenSrc, unsigned char const *zDelta, fsl_size_t lenDelta, unsigned char *zOut)
Apply a delta created using fsl_delta_create().
FSL_EXPORT int fsl_dircrawl(char const *dirName, fsl_dircrawl_f callback, void *callbackState)
Recurses into a directory and calls a callback for each filesystem entry.
FSL_EXPORT bool fsl_str_glob(const char *zGlob, const char *z)
Return true if string z matches glob pattern zGlob and false if the pattern does not match.
FSL_EXPORT void fsl_buffer_swap(fsl_buffer *left, fsl_buffer *right)
Swaps the entire state of the left and right arguments.
void fsl_state_finalize(fsl_state *fst)
If fst is not NULL then:
FSL_EXPORT int fsl_decode16(const unsigned char *zIn, unsigned char *pOut, fsl_size_t N)
Decode a N-character base-16 number into base-256.
FSL_EXPORT char const * fsl_glob_list_matches(fsl_list const *globList, char const *zNeedle)
Assumes globList is a list of (char [const] *) glob values and tries to match each one against zNeedl...
FSL_EXPORT char * fsl_getenv(const char *zName)
Returns a (possible) copy of the environment variable with the given key, or NULL if no entry is foun...
FSL_EXPORT int fsl_buffer_appendch(fsl_buffer *b, char c)
Appends the given byte to b.
fsl_url_render_e
Flags for use with fsl_url_render().
Definition util.h:6608
@ FSL_URL_RENDER_NO_USER
Elide the user name and password.
Definition util.h:6614
@ FSL_URL_RENDER_MASK_PASSWORD
Render any password part of the URL as some unspecified number of "*" characters.
Definition util.h:6623
@ FSL_URL_RENDER_NO_PASSWORD
Elide any password part of the URL.
Definition util.h:6617
@ FSL_URL_RENDER_NO_QUERY
Elide the query string and fragment.
Definition util.h:6626
@ FSL_URL_RENDER_NO_FRAGMENT
Elide the fragment.
Definition util.h:6629
@ FSL_URL_RENDER_NO_SCHEME
Elide the scheme:// prefix.
Definition util.h:6611
FSL_EXPORT int fsl_pathfinder_ext_add2(fsl_pathfinder *pf, char const *ext, fsl_int_t strLen)
Adds the given directory to pf's search extensions.
FSL_EXPORT bool fsl_file_isexec(const char *zFilename)
Returns true if the argument is fsl_stat()'able and has the executable bit set, else false.
FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const **xlate)
If c is a character Fossil likes to HTML-escape, assigns *xlate to its transformed form,...
FSL_EXPORT int fsl_diff_v2(fsl_buffer const *pv1, fsl_buffer const *pv2, fsl_dibu *pBuilder)
This counterpart of fsl_diff_text() defines its output format in terms of a fsl_dibu instance which t...
FSL_EXPORT int fsl_dir_check(const char *zFilename)
Returns a positive value if zFilename is a directory, 0 if zFilename does not exist,...
fsl_confirm_event_e
Event IDs for use with fsl_confirm_callback_f implementations.
Definition util.h:5902
@ FSL_CEVENT_MULTIPLE_VERSIONS
Indicates that the library cannot determine which of multiple potential versions to choose from and r...
Definition util.h:5937
@ FSL_CEVENT_OVERWRITE_MOD_FILE
An operation requests permission to overwrite a locally-modified file.
Definition util.h:5913
@ FSL_CEVENT_OVERWRITE_UNMGD_FILE
An operation requests permission to overwrite an SCM-unmanaged file with one which is managed by SCM.
Definition util.h:5920
@ FSL_CEVENT_RM_MOD_UNMGD_FILE
An operation requests permission to remove a LOCALLY-MODIFIED file which has been removed from SCM ma...
Definition util.h:5930
@ FSL_CEVENT_INVALID
Sentinal value.
Definition util.h:5906
FSL_EXPORT void fsl_canonical16(char *z, fsl_size_t n)
The input string is a base16 value.
FSL_EXPORT void fsl_randomness(unsigned int n, void *tgt)
Populates the first n bytes of tgt with random bytes.
const fsl_url fsl_url_empty
Initialized-with-defaults fsl_url structure, intended for non-const copy initialization.
FSL_EXPORT fsl_size_t fsl_str_to_size(char const *str)
Expects str to be a string containing an unsigned decimal value.
FSL_EXPORT int fsl_diff_v2_raw(fsl_buffer const *pv1, fsl_buffer const *pv2, fsl_dibu_opt const *cfg, int **outRaw)
Performs a diff, as for fsl_diff_v2(), but returns the results in the form of an array of COPY,...
FSL_EXPORT int fsl_appendf(fsl_output_f pfAppend, void *pfAppendArg, const char *fmt,...)
Identical to fsl_appendfv() but takes an ellipses list (...) instead of a va_list.
FSL_EXPORT void fsl_timer_start(fsl_timer *t)
Sets t's counter state to the current CPU timer usage, as determined by the OS.
FSL_EXPORT int fsl_looks_like_utf8(fsl_buffer const *b, int stopFlags)
If b appears to contain any non-UTF8 content, returns a truthy value: one or more values from the fsl...
FSL_EXPORT int fsl_buffer_merge3(fsl_buffer *pPivot, fsl_buffer *pV1, fsl_buffer *pV2, fsl_buffer *pOut, unsigned int *conflictCount)
Performs a three-way merge.
FSL_EXPORT int fsl_symlink_create(char const *zTargetFile, char const *zLinkFile, bool realLink)
Creates a symlink or pseudo-symlink named zLinkFile linking to zTargetFile.
FSL_EXPORT void fsl_zip_finalize(fsl_zip_writer *z)
Frees all memory owned by z and resets it to a clean state, but does not free z.
FSL_EXPORT void * fsl_realloc(void *mem, fsl_size_t n)
Behaves like realloc(3).
FSL_EXPORT const fsl_state fsl_state_empty
Empty-initialized fsl_state struct, intended for copy-initializing.
Definition util.h:263
FSL_EXPORT unsigned int fsl_rgb_encode(int r, int g, int b)
For the given red/green/blue values (all in the range of 0 to 255, or truncated to be so!...
FSL_EXPORT int fsl_pathfinder_dir_add(fsl_pathfinder *pf, char const *dir)
Equivalent to fsl_pathfinder_dir_add2() with -1 as a final argument.
FSL_EXPORT void * fsl_utf8_to_unicode(const char *zUtf8)
Translate UTF-8 to Unicode for use in system calls.
FSL_EXPORT int fsl_list_v_fsl_free(void *obj, void *visitorState)
A fsl_list_visitor_f() implementation which requires that obj be arbitrary memory which can legally b...
FSL_EXPORT fsl_size_t fsl_simplify_sql(char *sql, fsl_int_t len)
"Simplifies" an SQL string by making the following modifications inline:
FSL_EXPORT int fsl_file_unlink(const char *zFilename)
Deletes the given file from the filesystem.
FSL_EXPORT fsl_int_t fsl_buffer_getdelim(char **ret, size_t *retsz, int delim, fsl_buffer *buf)
Read from buf until consuming a character matching delim, which must be representable as an unsigned ...
FSL_EXPORT int fsl_pathfinder_search(fsl_pathfinder *pf, char const *base, char const **pOut, fsl_size_t *outLen)
Searches for a file whose name can be constructed by some combination of pf's directory/extension lis...
FSL_EXPORT FILE * fsl_fopen(char const *name, char const *mode)
Almost equivalent to fopen(3) but:
FSL_EXPORT bool fsl_isalnum(int c)
Equivalent to fsl_isdigit(c) || fsl_isalpha().
FSL_EXPORT int fsl_break_into_dlines(const char *z, fsl_int_t n, uint32_t *pnLine, fsl_dline **pOut, uint64_t diff2Flags)
Breaks the first n bytes of z into an array of fsl_dline records, each of which refers back to z (so ...
FSL_EXPORT void fsl_list_visit_free(fsl_list *list, bool freeListMem)
Similar to fsl_list_clear(list, fsl_list_v_fsl_free, NULL), but only frees list->list if the second a...
FSL_EXPORT int fsl_mkdir(const char *zName, bool forceFlag)
Create the directory with the given name if it does not already exist.
FSL_EXPORT fsl_int_t fsl_list_index_of(fsl_list const *li, void const *value, fsl_generic_cmp_f cmpf)
Searches for a value in the given list, using the given comparison function to determine equivalence.
FSL_EXPORT const fsl_fstat fsl_fstat_empty
Empty-initialized fsl_fstat instance, intended for non-const copy construction.
Definition util.h:3355
FSL_EXPORT unsigned int fsl_gradient_color(unsigned int c1, unsigned int c2, unsigned int numberOfSteps, unsigned int stepNumber)
For two color values encoded as RRGGBB values (see below for the structure), this function computes a...
FSL_EXPORT bool fsl_isalpha(int c)
Returns true if the given letter is an ASCII alphabet character.
FSL_EXPORT void fsl_bytes_defossilize(unsigned char *inp, fsl_size_t *resultLen)
"Defossilizes" bytes encoded by fsl_bytes_fossilize() in-place.
FSL_EXPORT int fsl_buffer_fill_from(fsl_buffer *dest, fsl_input_f src, void *state)
Uses a fsl_input_f() function to buffer input into a fsl_buffer.
FSL_EXPORT const fsl_pathfinder fsl_pathfinder_empty
Initialized-with-defaults fsl_pathfinder instance, intended for copy initialization.
Definition util.h:4972
FSL_EXPORT int fsl_file_copy(char const *zFrom, char const *zTo)
Makes a bitwise copy of the file zFrom to file zTo, creating any directories needed for the target fi...
FSL_EXPORT int fsl_is_uuid_len(int x)
If x is a valid fossil UUID length, it is returned, else 0 is returned.
FSL_EXPORT void fsl_buffer_strip_slashes(fsl_buffer *b)
A convenience from of fsl_strip_trailing_slashes() which strips trailing slashes from the given buffe...
int fsl_path_splitter_next(fsl_path_splitter *pt, char const **token, fsl_size_t *len)
Given a fsl_path_splitter which was formerly initialized using fsl_path_splitter_init(),...
FSL_EXPORT int fsl_file_exec_set(const char *zFilename, bool isExec)
On non-Windows platforms, this function sets or unsets the executable bits on the given filename.
FSL_EXPORT fsl_size_t fsl_id_bag_count(fsl_id_bag const *p)
Return the number of elements in the bag.
FSL_EXPORT char ** fsl_temp_dirs_get(void)
Collects a list of directories intended to use as temp dirs in the current environment.
FSL_EXPORT fsl_size_t fsl_buffer_seek(fsl_buffer *b, fsl_int_t offset, fsl_buffer_seek_e whence)
"Seeks" b's internal cursor to a position specified by the given offset from either the current curso...
FSL_EXPORT void fsl_zip_timestamp_set_julian(fsl_zip_writer *z, double rDate)
Set z's date and time from a Julian Day number.
const fsl_dline_change fsl_dline_change_empty
Initialized-with-defaults fsl_dline_change structure, intended for non-const copy initialization.
FSL_EXPORT int fsl_mkdir_for_file(char const *zName, bool forceFlag)
A convenience form of fsl_mkdir() which can recursively create directories.
FSL_EXPORT int fsl_buffer_stream_lines(fsl_output_f fTo, void *toState, fsl_buffer *pFrom, fsl_size_t N)
Works identically to fsl_buffer_copy_lines() except that it sends its output to the fTo output functi...
fsl_diff2_flag_e
Flags for use with the 2021-era text-diff generation APIs (fsl_dibu and friends).
Definition util.h:3784
@ FSL_DIFF2_NOTTOOBIG
Only calculate diff if it's not "too big." Applies to all diff builders and will cause the public API...
Definition util.h:3803
@ FSL_DIFF2_IGNORE_ALLWS
Ignore all whitespace.
Definition util.h:3788
@ FSL_DIFF2_IGNORE_EOLWS
Ignore end-of-line whitespace.
Definition util.h:3786
@ FSL_DIFF2_NOINDEX
Tells diff builders which optionally support an "index" line to NOT include it in their output.
Definition util.h:3826
@ FSL_DIFF2_CLIENT4
Reserved for client-defined diff builder use.
Definition util.h:3843
@ FSL_DIFF2_CLIENT3
Reserved for client-defined diff builder use.
Definition util.h:3839
@ FSL_DIFF2_SLOW_SBS
More precise but slower side-by-side diff algorithm, for diffs which use that.
Definition util.h:3816
@ FSL_DIFF2_LINE_NUMBERS
Tells diff builders which support it to include line numbers in their output.
Definition util.h:3821
@ FSL_DIFF2_CLIENT2
Reserved for client-defined diff builder use.
Definition util.h:3835
@ FSL_DIFF2_CLIENT1
Reserved for client-defined diff builder use.
Definition util.h:3831
@ FSL_DIFF2_CONTEXT_ZERO
Use context line count even if it's zero.
Definition util.h:3797
@ FSL_DIFF2_NOOPT
Suppress optimizations (debug).
Definition util.h:3791
@ FSL_DIFF2_INVERT
Invert the diff.
Definition util.h:3793
@ FSL_DIFF2_STRIP_EOLCR
Strip trailing CR before diffing.
Definition util.h:3807
FSL_EXPORT char * fsl_mprintfv(char const *fmt, va_list vargs)
va_list counterpart to fsl_mprintf().
FSL_EXPORT int fsl_buffer_esc_arg(fsl_buffer *b, char const *z, bool isFilename)
Equivalent to fsl_buffer_esc_arg_v2() with NULL as its second argument.
FSL_EXPORT void fsl_timer_fetch(fsl_timer const *t, uint64_t *pUser, uint64_t *pSys, uint64_t *pWall)
Sets each of pUser, pSys, and pWall to the number of microseconds which have elapsed since t was pass...
int(* fsl_input_f)(void *state, void *dest, fsl_size_t *n)
Generic interface for streaming in data.
Definition util.h:318
FSL_EXPORT void fsl_fclose(FILE *f)
Passes f to fclose(3) unless f is NULL or one of the C-standard (stdin, stdout, stderr) handles,...
FSL_EXPORT void fsl_url_cleanup(fsl_url *u)
Equivalent to fsl_url_cleanup2(u, true).
FSL_EXPORT int fsl_list_clear(fsl_list *list, fsl_list_visitor_f childFinalizer, void *finalizerState)
A list clean-up routine which takes a callback to clean up its contents.
FSL_EXPORT const fsl_path_splitter fsl_path_splitter_empty
Default-initialized fsl_path_splitter instance, intended for copy initialization.
Definition util.h:6427
FSL_EXPORT int fsl_error_get(fsl_error const *err, char const **str, fsl_size_t *len)
Fetches the error state from err.
FSL_EXPORT bool fsl_isspace(int c)
Returns true if c is ' ', '\r' (ASCII 13dec), or '\t' (ASCII 9 dec).
FSL_EXPORT void fsl_error_reset(fsl_error *err)
Sets err->code to 0 and resets its buffer, but keeps any err->msg memory around for later re-use.
fsl_buffer_seek_e
"whence" values for use with fsl_buffer_seek().
Definition util.h:4809
@ FSL_BUFFER_SEEK_CUR
Definition util.h:4811
@ FSL_BUFFER_SEEK_SET
Definition util.h:4810
@ FSL_BUFFER_SEEK_END
Definition util.h:4812
FSL_EXPORT int fsl_buffer_delta_create(fsl_buffer const *src, fsl_buffer const *newVers, fsl_buffer *delta)
A fsl_delta_create() wrapper which uses the first two arguments as the original and "new" content ver...
FSL_EXPORT const fsl_error fsl_error_empty
Empty-initialized fsl_error instance, intended for copy initialization.
Definition util.h:800
FSL_EXPORT void fsl_finalizer_f_FILE(void *state, void *mem)
A fsl_finalizer_f() impl which requires that mem be-a (FILE*).
FSL_EXPORT char const * fsl_buffer_cstr(fsl_buffer const *b)
Equivalent to ((char const *)b->mem) except that if b->errCode is non-0, this returns NULL.
FSL_EXPORT void fsl_buffer_clear(fsl_buffer *b)
Convenience equivalent of fsl_buffer_reserve(b,0).
FSL_EXPORT void fsl_error_clear(fsl_error *err)
If err is not NULL, frees up any resources owned by err and sets its error code to 0,...
FSL_EXPORT fsl_time_t fsl_file_mtime(const char *zFilename)
Return the modification time for a file.
FSL_EXPORT bool fsl_isatty(int fd)
Returns the result of calling the platform's equivalent of isatty(fd).
FSL_EXPORT void fsl_list_sort(fsl_list *li, fsl_generic_cmp_f cmp)
Sorts the given list using the given comparison function.
FSL_EXPORT fsl_int_t fsl_file_size(const char *zFilename)
Return the size of a file in bytes.
FSL_EXPORT char * fsl_user_name_guess(void)
Uses fsl_getenv() to look for the environment variables (FOSSIL_USER, (Windows: USERNAME),...
FSL_EXPORT int fsl_file_mtime_set(const char *zFilename, fsl_time_t newMTime)
Sets the mtime (Unix epoch) for a file.
FSL_EXPORT int fsl_delta_applied_size(unsigned char const *zDelta, fsl_size_t lenDelta, fsl_size_t *appliedSize)
Calculates the size (in bytes) of the output from applying a the given delta.
FSL_EXPORT double fsl_unix_to_julian(fsl_time_t unixEpoch)
Old, misleading name for fsl_error_propagate() *‍/ define fsl_error_swap fsl_error_propagate.
FSL_EXPORT bool fsl_url_next_query_arg(fsl_url const *u, char const **zCursor, fsl_buffer *bKey, fsl_buffer *bVal)
Parses key-value pairs from u->query.
FSL_EXPORT int fsl_buffer_uncompress(fsl_buffer const *pIn, fsl_buffer *pOut)
Uncompress buffer pIn and store the result in pOut.
FSL_EXPORT int fsl_filename_preferred_case(bool isCaseSensitive, const char *zDir, const char *zPath, char **zOut)
Attempts to ensure that the name of a file in the filesystem matches the same case as one provided by...
FSL_EXPORT fsl_size_t fsl_strftime_unix(char *dest, fsl_size_t destLen, char const *format, fsl_time_t epochTime, bool convertToLocal)
A convenience form of fsl_strftime() which takes its timestamp in the form of a Unix Epoch time.
FSL_EXPORT int fsl_pathfinder_ext_add(fsl_pathfinder *pf, char const *ext)
Equivalent to fsl_pathfinder_ext_add2() with -1 as a final argument.
FSL_EXPORT int fsl_input_f_fd(void *state, void *dest, fsl_size_t *n)
A fsl_input_f() implementation which requires that state be a readable file descriptor,...
FSL_EXPORT int fsl_stream(fsl_input_f inF, void *inState, fsl_output_f outF, void *outState)
A generic streaming routine which copies data from an fsl_input_f() to an fsl_outpuf_f().
fsl_dibu_impl_flags_e
Flags for use with various concrete fsl_dibu implementations.
Definition util.h:3855
@ FSL_DIBU_TCL_TK
Tells the TCL diff builder to generate a complete TCL/TK app as output.
Definition util.h:3876
@ FSL_DIBU_TCL_BRACES
Tells the TCL diff builder that the complete output and each line should be wrapped in {....
Definition util.h:3860
@ FSL_DIBU_TCL_BRACES_ESC
Tells the TCL diff builder that the squiggly braces embedded in any output (as opposed to the braces ...
Definition util.h:3867
FSL_EXPORT int fsl_delta_create(unsigned char const *zSrc, fsl_size_t lenSrc, unsigned char const *zOut, fsl_size_t lenOut, unsigned char *zDelta, fsl_size_t *deltaSize)
Create a new fossil-format delta between the memory zIn and zOut.
FSL_EXPORT bool fsl_id_bag_contains(fsl_id_bag const *p, fsl_id_t e)
Returns true if e is in the given bag.
FSL_EXPORT bool fsl_is_absolute_path(const char *zPath)
Returns true if the given path appears to be absolute, else false.
FSL_EXPORT int fsl_file_dirpart(char const *zFilename, fsl_int_t nLen, fsl_buffer *pOut, bool leaveSlash)
Calculates the "directory part" of zFilename and appends it to pOut.
FSL_EXPORT void fsl_rgb_decode(unsigned int src, int *r, int *g, int *b)
Given an RGB-encoded source value, this function decodes the lower 24 bits into r,...
FSL_EXPORT void fsl_timer_add(fsl_timer const *tStart, fsl_timer *tgt)
Captures the current time and adds the difference of tStart and the current time to tgt's members.
FSL_EXPORT int fsl_chdir(const char *zChDir)
Performs a chdir() to the directory named by zChDir.
FSL_EXPORT int fsl_zip_file_add(fsl_zip_writer *z, char const *zFilename, fsl_buffer const *pContent, int permsFlag)
Adds a file or directory to the ZIP writer z.
FSL_EXPORT int fsl_buffer_compress(fsl_buffer const *pIn, fsl_buffer *pOut)
Compresses the first pIn->used bytes of pIn to pOut.
FSL_EXPORT int fsl_buffer_append(fsl_buffer *b, void const *src, fsl_int_t n)
Appends the first n bytes of src, plus a NUL byte, to b, expanding b as necessary and incrementing b-...
FSL_EXPORT int fsl_stat(const char *zFilename, fsl_fstat *fst, bool derefSymlinks)
Runs the OS's stat(2) equivalent to populate fst (if not NULL) with information about the given file.
int(* fsl_dircrawl_f)(fsl_dircrawl_state const *)
Callback type for use with fsl_dircrawl().
Definition util.h:6201
FSL_EXPORT fsl_int_t fsl_list_index_of_cstr(fsl_list const *li, char const *key)
Equivalent to fsl_list_index_of(li, key, fsl_strcmp_cmp).
fsl_lookslike_e
Flags for use with the fsl_looks family of functions.
Definition util.h:6276
@ FSL_LOOKSLIKE_SHORT
Definition util.h:6296
@ FSL_LOOKSLIKE_INVALID
Definition util.h:6298
@ FSL_LOOKSLIKE_NUL
Definition util.h:6280
@ FSL_LOOKSLIKE_ODD
Definition util.h:6294
@ FSL_LOOKSLIKE_BINARY
Definition util.h:6300
@ FSL_LOOKSLIKE_LONE_LF
Definition util.h:6288
@ FSL_LOOKSLIKE_NONE
Definition util.h:6278
@ FSL_LOOKSLIKE_LONG
Definition util.h:6292
@ FSL_LOOKSLIKE_LF
Definition util.h:6286
@ FSL_LOOKSLIKE_CR
Definition util.h:6282
@ FSL_LOOKSLIKE_LONE_CR
Definition util.h:6284
@ FSL_LOOKSLIKE_EOL
Definition util.h:6302
@ FSL_LOOKSLIKE_CRLF
Definition util.h:6290
FSL_EXPORT void * fsl_utf8_to_filename(const char *zUtf8)
Translate text from UTF-8 to the OS's filename character set.
FSL_EXPORT char * fsl_strndup(char const *src, fsl_int_t len)
Similar to strndup(3) but returns NULL if !src.
FSL_EXPORT int fsl_buffer_appendf(fsl_buffer *dest, char const *fmt,...)
Uses fsl_appendf() to append formatted output to the given buffer.
FSL_EXPORT fsl_time_t fsl_julian_to_unix(double J)
Returns the Julian Day time J value converted to a Unix Epoch timestamp.
FSL_EXPORT bool fsl_julian_to_iso8601(double J, char *pOut, bool addMs)
Converts the Julian Day J to an ISO8601 time string.
FSL_EXPORT bool fsl_iso8601_to_julian(char const *zDate, double *pOut)
If zDate is an ISO8601-format string, optionally with a .NNN fractional suffix, then this function re...
FSL_EXPORT void fsl_buffer_rewind(fsl_buffer *b)
Resets b's cursor to the beginning of the buffer.
FSL_EXPORT double fsl_julian_now(void)
Returns the current Unix Epoch time converted to its approximate Julian form.
FSL_EXPORT fsl_dibu * fsl_dibu_alloc(fsl_size_t extra)
Base allocator for fsl_dibu instances.
FSL_EXPORT int fsl_encode16(const unsigned char *pIn, unsigned char *zOut, fsl_size_t N)
Encode a N-digit base-256 in base-16.
FSL_EXPORT int fsl_stream_compare(fsl_input_f in1, void *in1State, fsl_input_f in2, void *in2State)
Consumes two input streams looking for differences.
char const * fsl_uuid_cstr
The const counterpart of fsl_uuid_str.
Definition util.h:80
FSL_EXPORT int fsl_buffer_append_tcl_literal(fsl_buffer *b, bool escapeSquigglies, char const *z, fsl_int_t n)
Appends the first n bytes of string z to buffer b in the form of TCL-format string literal.
FSL_EXPORT const fsl_confirm_response fsl_confirm_response_empty
Empty-initialized fsl_confirm_detail instance to be used for non-const copy initialization.
Definition util.h:6034
FSL_EXPORT int fsl_input_f_FILE(void *state, void *dest, fsl_size_t *n)
A fsl_input_f() implementation which requires that state be a readable (FILE*) handle.
const fsl_dline fsl_dline_empty
Initialized-with-defaults fsl_dline structure, intended for non-const copy initialization.
FSL_EXPORT bool fsl_validate16(const char *zIn, fsl_size_t nIn)
Returns true if the input string contains only valid lower-case base-16 digits.
FSL_EXPORT int fsl_buffer_fill_from_FILE(fsl_buffer *dest, FILE *src)
A fsl_buffer_fill_from() proxy which overwrite's dest->mem with the contents of the given FILE handle...
FSL_EXPORT int fsl_errno_to_rc(int errNo, int dflt)
Tries to convert the value of errNo, which is assumed to come from the global errno,...
FSL_EXPORT bool fsl_buffer_is_compressed(fsl_buffer const *buf)
Equivalent to fsl_data_is_compressed(buf->mem, buf->used).
FSL_EXPORT uint64_t fsl_timer_cpu(fsl_timer const *t)
Returns the difference in CPU times in microseconds since t was last passed to fsl_timer_start() or f...
FSL_EXPORT char const * fsl_buffer_cstr2(fsl_buffer const *b, fsl_size_t *len)
If b has any memory allocated to it and b->errCode is non-0, that memory is returned.
FSL_EXPORT bool fsl_buffer_contains_merge_marker(fsl_buffer const *p)
Returns true if p contains a fossil-format merge conflict marker, else returns false.
FSL_EXPORT int fsl_strncmp(const char *zA, const char *zB, fsl_size_t nByte)
fsl_strcmp() variant which compares at most nByte bytes of the given strings, case-sensitively.
FSL_EXPORT const fsl_outputer fsl_outputer_empty
Empty-initialized fsl_outputer instance, intended for copy-initializing.
Definition util.h:360
FSL_EXPORT char * fsl_buffer_take(fsl_buffer *b)
"Takes" the memory refered to by the given buffer, transfering ownership to the caller.
FSL_EXPORT uint64_t fsl_timer_stop(fsl_timer *t)
Resets t's state to contain relative times by subtracting its starting time from the current time.
FSL_EXPORT void fsl_zip_timestamp_set_unix(fsl_zip_writer *z, fsl_time_t epochTime)
Set z's date and time from a Unix Epoch time.
int(* fsl_generic_cmp_f)(void const *lhs, void const *rhs)
A typedef for comparison function used by standard C routines such as qsort().
Definition util.h:93
FSL_EXPORT unsigned char const * fsl_utf8_bom(unsigned int *pnByte)
Returns a static pointer to bytes of a UTF8 BOM.
FSL_EXPORT int fsl_strcmp(char const *lhs, char const *rhs)
Like strcmp(3) except that it accepts NULL pointers.
FSL_EXPORT int fsl_buffer_resize(fsl_buffer *buf, fsl_size_t n)
Similar to fsl_buffer_reserve() except that...
FSL_EXPORT int fsl_buffer_esc_arg_v2(fsl_buffer *b, fsl_error *err, char const *z, bool isFilename)
Expects z to be a single argument intended for future call to system()-like function.
FSL_EXPORT int fsl_url_parse(fsl_url *u, char const *zUrl)
Attempts to parse zUrl as a URL, filling out u with the results.
FSL_EXPORT int fsl_output_f_FILE(void *state, void const *src, fsl_size_t n)
A fsl_output_f() impl which requires state to be-a (FILE*), which this function passes the call on to...
FSL_EXPORT fsl_size_t fsl_strlcpy(char *dst, const char *src, fsl_size_t dstsz)
BSD strlcpy() variant which is less error prone than strncpy.
FSL_EXPORT int fsl_file_access(const char *zFilename, int flags)
Returns 0 if the given file is readable.
FSL_EXPORT int fsl_flush_f_FILE(void *_FILE)
A fsl_flush_f() impl which expects _FILE to be-a (FILE*) opened for writing, which this function pass...
FSL_EXPORT int fsl_buffer_compress2(fsl_buffer const *pIn1, fsl_buffer const *pIn2, fsl_buffer *pOut)
Compress the concatenation of a blobs pIn1 and pIn2 into pOut.
FSL_EXPORT bool fsl_isupper(int c)
Returns true if c is an upper-case ASCII alphabet character.
FSL_EXPORT int fsl_buffer_compare_O1(fsl_buffer const *lhs, fsl_buffer const *rhs)
Compare two buffers in constant (a.k.a.
FSL_EXPORT int fsl_dibu_factory(fsl_dibu_e type, fsl_dibu **pOut)
A factory for creating fsl_dibu instances of types which are built in to the library.
int(* fsl_flush_f)(void *state)
Generic interface for flushing arbitrary output streams.
Definition util.h:303
FSL_EXPORT int fsl_buffer_appendfv(fsl_buffer *dest, char const *fmt, va_list args)
va_list counterpart to fsl_buffer_appendf().
FSL_EXPORT void fsl_to_hex(unsigned char const *pBytes, fsl_size_t nBytes, char *pOut)
Converts the first nBytes bytes from pBytes to hex form, writing the result to pOut.
FSL_EXPORT int fsl_error_set(fsl_error *err, int code, char const *fmt,...)
If err is not NULL, populates err with the given code and formatted string, replacing any existing st...
FSL_EXPORT int fsl_htmlize(fsl_output_f out, void *oState, const char *zIn, fsl_int_t n)
Make the given string safe for HTML by converting every "<" into "<", every ">" into ">",...
FSL_EXPORT int fsl_pathfinder_dir_add2(fsl_pathfinder *pf, char const *dir, fsl_int_t strLen)
Adds the given directory to pf's search path.
FSL_EXPORT int fsl_buffer_fill_from_filename(fsl_buffer *dest, char const *filename)
A wrapper for fsl_buffer_fill_from_FILE() which gets its input from the given file name.
FSL_EXPORT int fsl_output_f_fd(void *state, void const *src, fsl_size_t n)
A fsl_output_f() impl which requires state to be-a (int*) referring to a writable file descriptor,...
FSL_EXPORT int fsl_list_append(fsl_list *self, void *cp)
Appends a bitwise copy of cp to self->list, expanding the list as necessary and adjusting self->used.
FSL_EXPORT int fsl_symlink_copy(char const *zFrom, char const *zTo, bool realLink)
Reads symlink zFrom, as per fsl_symlink_read(), then creates a copy named zTo, as per fsl_symlink_cre...
FSL_EXPORT int fsl_buffer_copy(fsl_buffer *dest, fsl_buffer const *src)
Overwrites dest's contents with a copy of those from src (reusing dest's memory if it has any).
void fsl_path_splitter_init(fsl_path_splitter *pt, char const *path, fsl_int_t len)
Wipes out pt's current state by copying fsl_path_splitter_empty over it and initializes pt to use the...
FSL_EXPORT void fsl_url_cleanup2(fsl_url *u, bool freeBuffer)
Frees all memory owned by u, and zeroes it out, but does not free u.
FSL_EXPORT int fsl_file_tempname(fsl_buffer *tgt, char const *zPrefix, char *const *dirs)
Creates a semi-random temp filename and appends it to the given buffer.
FSL_EXPORT int fsl_file_canonical_name(const char *zOrigName, fsl_buffer *pOut, bool slash)
Equivalent to fsl_file_canonical_name2(NULL, zOrigName, pOut, slash).
FSL_EXPORT fsl_size_t fsl_strlcat(char *dst, const char *src, fsl_size_t dstsz)
BSD strlcat() variant which is less error prone than strncat.
FSL_EXPORT const fsl_confirmer fsl_confirmer_empty
Empty-initialized fsl_confirmer instance for non-const-copy initialization.
Definition util.h:6148
FSL_EXPORT int fsl_buffer_err(fsl_buffer const *b)
Returns the current error code of the given buffer.
FSL_EXPORT fsl_size_t fsl_strlen(char const *src)
Equivalent to strlen(3) but returns 0 if src is NULL.
FSL_EXPORT const fsl_id_bag fsl_id_bag_empty
Initialized-with-defaults fsl_id_bag structure, intended for copy initialization.
Definition util.h:5721
int(* fsl_output_f)(void *state, void const *src, fsl_size_t n)
Generic interface for streaming out data.
Definition util.h:292
FSL_EXPORT bool fsl_isdigit(int c)
Returns true if c is an ASCII digit in the range '0' to '9'.
FSL_EXPORT bool fsl_data_is_compressed(unsigned char const *mem, fsl_size_t len)
Returns true if this function believes that mem (which must be at least len bytes of valid memory lon...
FSL_EXPORT void fsl_unicode_free(void *)
Deallocates the given memory, which must have been allocated from fsl_unicode_to_utf8(),...
FSL_EXPORT fsl_int_t fsl_buffer_uncompressed_size(fsl_buffer const *b)
The fsl_buffer counterpart of fsl_data_uncompressed_size().
int(* fsl_confirm_callback_f)(fsl_confirm_detail const *detail, fsl_confirm_response *outAnswer, void *confirmerState)
Should present the user (if appropriate) with an option of how to handle the given event write that a...
Definition util.h:6120
FSL_EXPORT fsl_size_t fsl_simplify_sql_buffer(fsl_buffer *b)
Convenience form of fsl_simplify_sql() which assumes b holds an SQL string.
FSL_EXPORT fsl_buffer * fsl_buffer_reuse(fsl_buffer *b)
If b is a managed buffer, this resets b->used, b->cursor, and b->mem[0] (if b->mem is not NULL) to 0.
FSL_EXPORT int fsl_uuidcmp(fsl_uuid_cstr lhs, fsl_uuid_cstr rhs)
Equivalent to fsl_strncmp(lhs, rhs, X), where X is either FSL_STRLEN_SHA1 or FSL_STRLEN_K256: if both...
FSL_EXPORT int fsl_buffer_copy_lines(fsl_buffer *pTo, fsl_buffer *pFrom, fsl_size_t N)
Copy N lines of text from pFrom into pTo.