Artifactspublic-v0

curl

master
ply4 git calls241 ms291 KiB2 cachedprotocol v2
437 lines9.6 KiBRaw

curl C code style

Source code that has a common style is easier to read than code that uses different styles in different places. It helps making the code feel like one single code base. Easy-to-read is an important property of code and helps making it easier to review when new things are added and it helps debugging code when developers are trying to figure out why things go wrong. A unified style is more important than individual contributors having their own personal tastes satisfied.

Our C code has a few style rules. Most of them are verified and upheld by the scripts/checksrc.pl script. Invoked with make checksrc or even by default by the build system when built after ./configure --enable-debug has been used.

It is normally not a problem for anyone to follow the guidelines, copy the style already used in the source code and there are no particularly unusual rules in our set of rules.

We also work hard on writing code that are warning-free on all the major platforms and in general on as many platforms as possible. Code that causes warnings is not accepted as-is.

Readability

A primary characteristic for code is readability. The intent and meaning of the code should be visible to the reader. Being clear and unambiguous beats being clever and saving two lines of code. Write simple code. You and others who come back to this code over the coming decades want to be able to quickly understand it when debugging.

Naming

Try using a non-confusing naming scheme for your new functions and variable names. It does not necessarily have to mean that you should use the same as in other places of the code, only that the names should be logical, understandable and be named according to what they are used for. File-local functions should be made static. We like lower case names.

See the INTERNALS document on how we name non-exported library-global symbols.

Indenting

We use only spaces for indentation, never TABs. We use two spaces for each new open brace.

c
if(something_is_true) {
  while(second_statement == fine) {
    moo();
  }
}

Comments

Since we write C89 code, // comments are not allowed. They were not introduced in the C standard until C99. We use only /* comments */.

c
/* this is a comment */

Long lines

Source code in curl may never be wider than 79 columns and there are two reasons for maintaining this even in the modern era of large and high resolution screens:

  1. Narrower columns are easier to read than wide ones. There is a reason newspapers have used columns for decades or centuries.

  2. Narrower columns allow developers to easier show multiple pieces of code next to each other in different windows. It allows two or three source code windows next to each other on the same screen - as well as multiple terminal and debugging windows.

Braces

In if/while/do/for expressions, we write the open brace on the same line as the keyword and we then set the closing brace on the same indentation level as the initial keyword. Like this:

c
if(age < 40) {
  /* clearly a youngster */
}

You may omit the braces if they would contain only a one-line statement:

c
if(!x)
  continue;

For functions the opening brace should be on a separate line:

c
int main(int argc, char *argv[])
{
  return 1;
}

'else' on the following line

When adding an else clause to a conditional expression using braces, we add it on a new line after the closing brace. Like this:

c
if(age < 40) {
  /* clearly a youngster */
}
else {
  /* probably grumpy */
}

No space before parentheses

When writing expressions using if/while/do/for, there shall be no space between the keyword and the open parenthesis. Like this:

c
while(1) {
  /* loop forever */
}

Use boolean conditions

Rather than test a conditional value such as a bool against TRUE or FALSE, a pointer against NULL or != NULL and an int against zero or not zero in if/while conditions we prefer:

c
result = do_something();
if(!result) {
  /* something went wrong */
  return result;
}

No assignments in conditions

To increase readability and reduce complexity of conditionals, we avoid assigning variables within if/while conditions. We frown upon this style:

c
if((ptr = malloc(100)) == NULL)
  return NULL;

and instead we encourage the above version to be spelled out more clearly:

c
ptr = malloc(100);
if(!ptr)
  return NULL;

New block on a new line

We never write multiple statements on the same source line, even for short if() conditions.

c
if(a)
  return TRUE;
else if(b)
  return FALSE;

and NEVER:

c
if(a) return TRUE;
else if(b) return FALSE;

Space around operators

Please use spaces on both sides of operators in C expressions. Postfix (), [], ->, ., ++, -- and Unary +, -, !, ~, & operators excluded they should have no space.

Examples:

c
bla = func();
who = name[0];
age += 1;
true = !false;
size += -2 + 3 * (a + b);
ptr->member = a++;
struct.field = b--;
ptr = &address;
contents = *pointer;
complement = ~bits;
empty = (!*string) ? TRUE : FALSE;

No space following typecasts

As far as possible, we write code to avoid typecasts. When we do use them, We write typecasts "glued" to the following expression, with no space after the closing parenthesis:

c
int value = (int)foobar;
char *ptr = (char *)random_func();

No parentheses for return values

We use the 'return' statement without extra parentheses around the value:

c
int works(void)
{
  return TRUE;
}

Parentheses for sizeof arguments

When using the sizeof operator in code, we prefer it to be written with parentheses around its argument:

c
int size = sizeof(int);

Column alignment

Some statements cannot be completed on a single line because the line would be too long, the statement too hard to read, or due to other style guidelines above. In such a case the statement spans multiple lines.

If a continuation line is part of an expression or sub-expression then you should align on the appropriate column so that it is easy to tell what part of the statement it is. Operators should not start continuation lines. In other cases follow the 2-space indent guideline. Here are some examples from libcurl:

c
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
   (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
   (handle->set.httpreq == HTTPREQ_GET ||
    handle->set.httpreq == HTTPREQ_HEAD))
  /* did not ask for HTTP/1.0 and a GET or HEAD */
  return TRUE;

If no parenthesis, use the default indent:

c
data->set.http_disable_hostname_check_before_authentication =
  va_arg(param, long) ? TRUE : FALSE;

Function invoke with an open parenthesis:

c
if(option) {
  result = parse_login_details(option, strlen(option),
                               (userp ? &user : NULL),
                               (passwdp ? &passwd : NULL),
                               NULL);
}

Align with the "current open" parenthesis:

c
DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
             "server response left\n",
             (int)clipamount));

Platform dependent code

Use #ifdef HAVE_FEATURE to do conditional code. We avoid checking for particular operating systems or hardware in the #ifdef lines. The HAVE_FEATURE shall be generated by the configure script for Unix-like systems and they are hard-coded in the config-[system].h files for the others.

We also encourage use of macros/functions that possibly are empty or defined to constants when libcurl is built without that feature, to make the code seamless. Like this example where the magic() function works differently depending on a build-time conditional:

c
#ifdef HAVE_MAGIC
void magic(int a)
{
  return a + 2;
}
#else
#define magic(x) 1
#endif

int content = magic(3);

No typedefed structs

Use structs by all means, but do not typedef them. Use the struct name way of identifying them:

c
struct something {
   void *valid;
   size_t way_to_write;
};
struct something instance;

Not okay:

c
typedef struct {
   void *wrong;
   size_t way_to_write;
} something;
something instance;

Banned functions

To avoid footguns and unintended consequences we forbid the use of a number of C functions. The checksrc script finds and yells about them if used. This makes us write better code.

This is the full list of functions generally banned.

_access
_fstati64
_lseeki64
_mbscat
_mbsncat
_open
_tcscat
_tcsdup
_tcsncat
_tcsncpy
_waccess
_wcscat
_wcsdup
_wcsncat
_wfopen
_wfreopen
_wopen
abort
accept
accept4
access
aprintf
assert
atoi
atol
calloc
close
CreateFile
CreateFileA
CreateFileW
fclose
fdopen
fopen
fprintf
free
freeaddrinfo
freopen
fstat
getaddrinfo
gets
gmtime
inet_ntop
inet_pton
llseek
LoadLibrary
LoadLibraryA
LoadLibraryEx
LoadLibraryExA
LoadLibraryExW
LoadLibraryW
localtime
lseek
malloc
mbstowcs
MoveFileEx
MoveFileExA
MoveFileExW
msnprintf
mvsnprintf
open
printf
realloc
recv
rename
send
snprintf
socket
socketpair
sprintf
sscanf
stat
strcat
strcpy
strdup
strerror
strncat
strncpy
strtok
strtok_r
strtol
strtoul
vaprintf
vfprintf
vprintf
vsnprintf
vsprintf
wcscpy
wcsdup
wcsncpy
wcstombs
WSASocket
WSASocketA
WSASocketW
1<!--
2Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
4SPDX-License-Identifier: curl
5-->
7# curl C code style
9Source code that has a common style is easier to read than code that uses
10different styles in different places. It helps making the code feel like one
11single code base. Easy-to-read is an important property of code and helps
12making it easier to review when new things are added and it helps debugging
13code when developers are trying to figure out why things go wrong. A unified
14style is more important than individual contributors having their own personal
15tastes satisfied.
17Our C code has a few style rules. Most of them are verified and upheld by the
18`scripts/checksrc.pl` script. Invoked with `make checksrc` or even by default
19by the build system when built after `./configure --enable-debug` has been
20used.
22It is normally not a problem for anyone to follow the guidelines, copy
23the style already used in the source code and there are no particularly
24unusual rules in our set of rules.
26We also work hard on writing code that are warning-free on all the major
27platforms and in general on as many platforms as possible. Code that causes
28warnings is not accepted as-is.
30## Readability
32A primary characteristic for code is readability. The intent and meaning of
33the code should be visible to the reader. Being clear and unambiguous beats
34being clever and saving two lines of code. Write simple code. You and others
35who come back to this code over the coming decades want to be able to quickly
36understand it when debugging.
38## Naming
40Try using a non-confusing naming scheme for your new functions and variable
41names. It does not necessarily have to mean that you should use the same as in
42other places of the code, only that the names should be logical,
43understandable and be named according to what they are used for. File-local
44functions should be made static. We like lower case names.
46See the [INTERNALS](https://curl.se/dev/internals.html#symbols) document on
47how we name non-exported library-global symbols.
49## Indenting
51We use only spaces for indentation, never TABs. We use two spaces for each new
52open brace.
54```c
55if(something_is_true) {
56 while(second_statement == fine) {
57 moo();
58 }
60```
62## Comments
64Since we write C89 code, **//** comments are not allowed. They were not
65introduced in the C standard until C99. We use only __/* comments */__.
67```c
68/* this is a comment */
69```
71## Long lines
73Source code in curl may never be wider than 79 columns and there are two
74reasons for maintaining this even in the modern era of large and high
75resolution screens:
771. Narrower columns are easier to read than wide ones. There is a reason
78 newspapers have used columns for decades or centuries.
802. Narrower columns allow developers to easier show multiple pieces of code
81 next to each other in different windows. It allows two or three source
82 code windows next to each other on the same screen - as well as multiple
83 terminal and debugging windows.
85## Braces
87In if/while/do/for expressions, we write the open brace on the same line as
88the keyword and we then set the closing brace on the same indentation level as
89the initial keyword. Like this:
91```c
92if(age < 40) {
93 /* clearly a youngster */
95```
97You may omit the braces if they would contain only a one-line statement:
99```c
100if(!x)
101 continue;
102```
104For functions the opening brace should be on a separate line:
106```c
107int main(int argc, char *argv[])
109 return 1;
111```
113## 'else' on the following line
115When adding an **else** clause to a conditional expression using braces, we
116add it on a new line after the closing brace. Like this:
118```c
119if(age < 40) {
120 /* clearly a youngster */
122else {
123 /* probably grumpy */
125```
127## No space before parentheses
129When writing expressions using if/while/do/for, there shall be no space
130between the keyword and the open parenthesis. Like this:
132```c
133while(1) {
134 /* loop forever */
136```
138## Use boolean conditions
140Rather than test a conditional value such as a bool against TRUE or FALSE, a
141pointer against NULL or != NULL and an int against zero or not zero in
142if/while conditions we prefer:
144```c
145result = do_something();
146if(!result) {
147 /* something went wrong */
148 return result;
150```
152## No assignments in conditions
154To increase readability and reduce complexity of conditionals, we avoid
155assigning variables within if/while conditions. We frown upon this style:
157```c
158if((ptr = malloc(100)) == NULL)
159 return NULL;
160```
162and instead we encourage the above version to be spelled out more clearly:
164```c
165ptr = malloc(100);
166if(!ptr)
167 return NULL;
168```
170## New block on a new line
172We never write multiple statements on the same source line, even for short
173if() conditions.
175```c
176if(a)
177 return TRUE;
178else if(b)
179 return FALSE;
180```
182and NEVER:
184```c
185if(a) return TRUE;
186else if(b) return FALSE;
187```
189## Space around operators
191Please use spaces on both sides of operators in C expressions. Postfix **(),
192[], ->, ., ++, --** and Unary **+, -, !, ~, &** operators excluded they should
193have no space.
195Examples:
197```c
198bla = func();
199who = name[0];
200age += 1;
201true = !false;
202size += -2 + 3 * (a + b);
203ptr->member = a++;
204struct.field = b--;
205ptr = &address;
206contents = *pointer;
207complement = ~bits;
208empty = (!*string) ? TRUE : FALSE;
209```
211## No space following typecasts
213As far as possible, we write code to avoid typecasts. When we do use them, We
214write typecasts "glued" to the following expression, with no space after the
215closing parenthesis:
217```c
218int value = (int)foobar;
219char *ptr = (char *)random_func();
220```
222## No parentheses for return values
224We use the 'return' statement without extra parentheses around the value:
226```c
227int works(void)
229 return TRUE;
231```
233## Parentheses for sizeof arguments
235When using the sizeof operator in code, we prefer it to be written with
236parentheses around its argument:
238```c
239int size = sizeof(int);
240```
242## Column alignment
244Some statements cannot be completed on a single line because the line would be
245too long, the statement too hard to read, or due to other style guidelines
246above. In such a case the statement spans multiple lines.
248If a continuation line is part of an expression or sub-expression then you
249should align on the appropriate column so that it is easy to tell what part of
250the statement it is. Operators should not start continuation lines. In other
251cases follow the 2-space indent guideline. Here are some examples from
252libcurl:
254```c
255if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
256 (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
257 (handle->set.httpreq == HTTPREQ_GET ||
258 handle->set.httpreq == HTTPREQ_HEAD))
259 /* did not ask for HTTP/1.0 and a GET or HEAD */
260 return TRUE;
261```
263If no parenthesis, use the default indent:
265```c
266data->set.http_disable_hostname_check_before_authentication =
267 va_arg(param, long) ? TRUE : FALSE;
268```
270Function invoke with an open parenthesis:
272```c
273if(option) {
274 result = parse_login_details(option, strlen(option),
275 (userp ? &user : NULL),
276 (passwdp ? &passwd : NULL),
277 NULL);
279```
281Align with the "current open" parenthesis:
283```c
284DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
285 "server response left\n",
286 (int)clipamount));
287```
289## Platform dependent code
291Use **#ifdef HAVE_FEATURE** to do conditional code. We avoid checking for
292particular operating systems or hardware in the #ifdef lines. The HAVE_FEATURE
293shall be generated by the configure script for Unix-like systems and they are
294hard-coded in the `config-[system].h` files for the others.
296We also encourage use of macros/functions that possibly are empty or defined
297to constants when libcurl is built without that feature, to make the code
298seamless. Like this example where the **magic()** function works differently
299depending on a build-time conditional:
301```c
302#ifdef HAVE_MAGIC
303void magic(int a)
305 return a + 2;
307#else
308#define magic(x) 1
309#endif
311int content = magic(3);
312```
314## No typedefed structs
316Use structs by all means, but do not typedef them. Use the `struct name` way
317of identifying them:
319```c
320struct something {
321 void *valid;
322 size_t way_to_write;
323};
324struct something instance;
325```
327**Not okay**:
329```c
330typedef struct {
331 void *wrong;
332 size_t way_to_write;
333} something;
334something instance;
335```
337## Banned functions
339To avoid footguns and unintended consequences we forbid the use of a number of
340C functions. The `checksrc` script finds and yells about them if used. This
341makes us write better code.
343This is the full list of functions generally banned.
345 _access
346 _fstati64
347 _lseeki64
348 _mbscat
349 _mbsncat
350 _open
351 _tcscat
352 _tcsdup
353 _tcsncat
354 _tcsncpy
355 _waccess
356 _wcscat
357 _wcsdup
358 _wcsncat
359 _wfopen
360 _wfreopen
361 _wopen
362 abort
363 accept
364 accept4
365 access
366 aprintf
367 assert
368 atoi
369 atol
370 calloc
371 close
372 CreateFile
373 CreateFileA
374 CreateFileW
375 fclose
376 fdopen
377 fopen
378 fprintf
379 free
380 freeaddrinfo
381 freopen
382 fstat
383 getaddrinfo
384 gets
385 gmtime
386 inet_ntop
387 inet_pton
388 llseek
389 LoadLibrary
390 LoadLibraryA
391 LoadLibraryEx
392 LoadLibraryExA
393 LoadLibraryExW
394 LoadLibraryW
395 localtime
396 lseek
397 malloc
398 mbstowcs
399 MoveFileEx
400 MoveFileExA
401 MoveFileExW
402 msnprintf
403 mvsnprintf
404 open
405 printf
406 realloc
407 recv
408 rename
409 send
410 snprintf
411 socket
412 socketpair
413 sprintf
414 sscanf
415 stat
416 strcat
417 strcpy
418 strdup
419 strerror
420 strncat
421 strncpy
422 strtok
423 strtok_r
424 strtol
425 strtoul
426 vaprintf
427 vfprintf
428 vprintf
429 vsnprintf
430 vsprintf
431 wcscpy
432 wcsdup
433 wcsncpy
434 wcstombs
435 WSASocket
436 WSASocketA
437 WSASocketW
Diagnostics4 git calls · 241 ms
CallStatusSizeTime0241 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=149
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=149
git.pkt.payload.max=78
git.ls_refs.count=2
git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=293470
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=10
git.pkt.data=8
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=293470
git.pkt.payload.max=65516
git.sideband.band1.bytes=293354
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=87
git.pack.bytes=293354
git.pack.ofs_delta=0
git.pack.ref_delta=1
git.pack.chain.max=1
git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0
git.pack.full=86
Open pack map
fetch2004.3 KiB235 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=231
git.response.bytes=4426
git.response.cache=MISS
git.response.duration_ms=235
git.fetch.wants=95e532f35aee9b13fdd5e6876093d1730768ce27
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=4426
git.pkt.payload.max=4405
git.sideband.band1.bytes=4404
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
Ref
refs/heads/master
Commit
31c911efe5652725e930f4d2e60c9060e5f6646d
cf-ray
a5e2cf5f6f27efad
Request
7fdb3bf1…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format