OSDN Git Service

merge in m-wireless-internal-release history after reset to m-wireless-internal-dev
[android-x86/system-bt.git] / doc / style_guide.md
1 # Bluedroid Style Guide
2 This document outlines the coding conventions and code style used in Bluedroid.
3 Its primary purpose is to provide explicit guidance on style so that developers
4 are consistent with one another and spend less time debating style.
5
6 ## Directory structure
7 Directories at the top-level should consist of major subsystems in Bluedroid.
8 Each subsystem's purpose should be documented in the `doc/directory_layout.md`
9 file, even if it seems obvious from the name.
10
11 For a subsystem that contains code, its directory structure should look like:
12 ```
13   Android.mk
14   include/
15   src/
16   test/
17 ```
18 Further, the directory structure inside `src/` and `include/` should be
19 mirrored. In other words, if `src/` contains a subdirectory called `foo/`,
20 `include/` must also have a subdirectory named `foo/`.
21
22 ## Target architecture
23 Bluedroid targets a variety of hardware and cannot make many assumptions about
24 memory layout, sizes, byte order, etc. As a result, some operations are
25 considered unsafe and this section outlines the most important ones to watch out
26 for.
27
28 ### Pointer / integer casts
29 In general, do not cast pointers to integers or vice versa.
30
31 The one exception is if an integer needs to be temporarily converted to a
32 pointer and then back to the original integer. This style of code is typically
33 needed when providing an integral value as the context to a callback, as in the
34 following example.
35 ```
36 void my_callback(void *context) {
37   uintptr_t arg = context;
38 }
39
40 set_up_callback(my_callback, (uintptr_t)5);
41 ```
42 Note, however, that the integral value was written into the pointer and read
43 from the pointer as a `uintptr_t` to avoid a loss of precision (or to make the
44 loss explicit).
45
46 ### Byte order
47 It is not safe to assume any particular byte order. When serializing or
48 deserializing data, it is unsafe to memcpy unless both source and destination
49 pointers have the same type.
50
51 ## Language
52 Bluedroid is written in C99 and should take advantage of the features offered by
53 it. However, not all language features lend themselves well to the type of
54 development required by Bluedroid. This section provides guidance on some of the
55 features to embrace or avoid.
56
57 ### C Preprocessor
58 The use of the C preprocessor should be minimized. In particular:
59 * use functions or, if absolutely necessary, inline functions instead of macros
60 * use `static const` variables instead of `#define`
61 * use `enum` for enumerations, not a collection of `#define`s
62 * minimize the use of feature / conditional macros
63
64 The last point is perhaps the most contentious. It's well-understood that
65 feature macros are useful in reducing code size but it leads to an exponential
66 explosion in build configurations. Setting up, testing, and verifying each of
67 the `2^n` build configurations is untenable for `n` greater than, say, 4.
68
69 ### C++
70 Although C++ offers constructs that may make Bluedroid development faster,
71 safer, more pleasant, etc. the decision _for the time being_ is to stick with
72 pure C99. The exceptions are when linking against libraries that are written
73 in C++. At the time of writing these libraries are `gtest` and `tinyxml2`,
74 where the latter is a dependency that should be eliminated in favor of simpler,
75 non-XML formats.
76
77 ### Variadic functions
78 Variadic functions are dangerous and should be avoided for most code. The
79 exception is when implementing logging since the benefits of readability
80 outweigh the cost of safety.
81
82 ### Functions with zero arguments
83 Functions that do not take any arguments (0 arity) should be declared like so:
84 ```
85 void function(void);
86 ```
87 Note that the function explicitly includes `void` in its parameter list to
88 indicate to the compiler that it takes no arguments.
89
90 ### Variable declarations
91 Variables should be declared one per line as close to initialization as possible.
92 In nearly all cases, variables should be declared and initialized on the same line.
93 Variable declarations should not include extra whitespace to line up fields. For
94 example, the following style is preferred:
95 ```
96   int my_long_variable_name = 0;
97   int x = 5;
98 ```
99 whereas this code is not acceptable:
100 ```
101   int my_long_variable_name = 0;
102   int                     x = 5;
103 ```
104
105 As a result of the above rule to declare and initialize variables together,
106 `for` loops should declare and initialize their iterator variable in the
107 initializer statement:
108 ```
109   for (int i = 0; i < 10; ++i) {
110     // use i
111   }
112 ```
113
114 ### Contiguous memory structs
115 Use C99 flexible arrays as the last member of a struct if the array needs
116 to be allocated in contiguous memory with its containing struct.
117 A flexible array member is writen as `array_name[]` without a specified size.
118 For example:
119 ```
120 typedef struct {
121   size_t length;
122   uint8_t data[];
123 } buffer_t;
124
125 // Allocate a buffer with 128 bytes available for my_buffer->data.
126 buffer_t *my_buffer = malloc(sizeof(buffer_t) + 128);
127 uint8_t *data = my_buffer->data;
128 ```
129
130 ### Pointer arithmetic
131 Avoid pointer arithmetic when possible as it results in difficult to read code.
132 Prefer array-indexing syntax over pointer arithmetic.
133
134 In particular, do not write code like this:
135 ```
136 typedef struct {
137   size_t length;
138 } buffer_t;
139
140 buffer_t *my_buffer = malloc(sizeof(buffer_t) + 128);
141 uint8_t *data = (uint8_t *)(my_buffer + 1);
142 ```
143 Instead, use zero-length arrays as described above to avoid pointer arithmetic
144 and array indexing entirely.
145
146 ### Boolean type
147 Use the C99 `bool` type with values `true` and `false` defined in `stdbool.h`.
148 Not only is this a standardized type, it is also safer and provides more
149 compile-time checks.
150
151 ### Booleans instead of bitfields
152 Use booleans to represent boolean state, instead of a set of masks into an
153 integer. It's more transparent and readable, and less error prone.
154
155 ## Bluedroid conventions
156 This section describes coding conventions that are specific to Bluedroid.
157 Whereas the _Language_ section describes the use of language features, this
158 section describes idioms, best practices, and conventions that are independent
159 of language features.
160
161 ### Memory management
162 Use `osi_malloc` or `osi_calloc` to allocate bytes instead of plain `malloc`.
163 Likewise, use `osi_free` over `free`. These wrapped functions provide additional
164 lightweight memory bounds checks that can help track down memory errors.
165
166 By convention, functions that contain `*_new` in their name are allocation
167 routines and objects returned from those functions must be freed with the
168 corresponding `*_free` function. For example, list objects returned from
169 `list_new` should be freed with `list_free` and no other freeing routine.
170
171 ### Asserts
172 Use `assert` liberally throughout the code to enforce invariants. Assertions
173 should not have any side-effects and should be used to detect programming logic
174 errors.
175
176 At minimum, every function should assert expectations on its arguments. The
177 following example demonstrates the kinds of assertions one should make on
178 function arguments.
179 ```
180   size_t open_and_read_file(const char *filename, void *target_buffer, size_t max_bytes) {
181     assert(filename != NULL);
182     assert(filename[0] != '\0');
183     assert(target_buffer != NULL);
184     assert(max_bytes > 0);
185
186     // function implementation begins here
187   }
188 ```
189
190 ## Header files
191 In general, every source file (`.c` or `.cpp`) in a `src/` directory should
192 have a corresponding header (`.h`) in the `include/` directory.
193
194 ### Template header file
195 ```
196 [copyright header]
197
198 #pragma once
199
200 #include <system/a.h>
201 #include <system/b.h>
202
203 #include "subsystem/include/a.h"
204 #include "subsystem/include/b.h"
205
206 typedef struct alarm_t alarm_t;
207 typedef struct list_t list_t;
208
209 // This comment describes the following function. It is not a structured
210 // comment, it's English prose. Function arguments can be referred to as
211 // |param|. This function returns true if a new object was created, false
212 // otherwise.
213 bool template_new(const list_t *param);
214
215 // Each public function must have a comment describing its semantics. In
216 // particular, edge cases, and whether a pointer argument may or may not be
217 // NULL.
218 void template_use_alarm(alarm_t *alarm);
219 ```
220
221 ### License header
222 Each header file must begin with the following Apache 2.0 License with `<year>`
223 and `<owner>` replaced with the year in which the file was authored and the
224 owner of the copyright, respectively.
225 ```
226 /******************************************************************************
227  *
228  *  Copyright (C) <year> <owner>
229  *
230  *  Licensed under the Apache License, Version 2.0 (the "License");
231  *  you may not use this file except in compliance with the License.
232  *  You may obtain a copy of the License at:
233  *
234  *  http://www.apache.org/licenses/LICENSE-2.0
235  *
236  *  Unless required by applicable law or agreed to in writing, software
237  *  distributed under the License is distributed on an "AS IS" BASIS,
238  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
239  *  See the License for the specific language governing permissions and
240  *  limitations under the License.
241  *
242  ******************************************************************************/
243 ```
244
245 ### Include guard
246 After the license header, each header file must contain the include guard:
247 ```
248 #pragma once
249 ```
250 This form is used over traditional `#define`-based include guards as it is less
251 error-prone, doesn't pollute the global namespace, is more compact, and can
252 result in faster compilation.
253
254 ## Formatting
255 Code formatting is pretty arbitrary, but the codebase is easier to follow if
256 everyone uses the same style. Individuals may not agree with every aspect of
257 the formatting rules, and some of the rules may take some getting used to,
258 but it is important that all engineers follow the formatting rules so we can all
259 understand and read the code easily.
260
261 ### White space
262 * use only spaces, indent 2 spaces at a time
263 * no trailing whitespaces at the end of a line
264 * no tab characters
265 * use one blank line to separate logical code blocks, function definitions,
266   and sections of a file
267
268 ```
269 // Space after keyword in conditionals and loops.
270 // No space immeidately before or after parentheses.
271 if (foo)
272
273 // Space surrounding binary operators.
274 if (foo < 5)
275
276 // Space after comma.
277 for (int x = 0, y = 0; x; ++y)
278
279 // No space between unary operators and their argument.
280 ++x;
281 z = -y;
282
283 // No space between function name and open parenthesis.
284 call_my_fn(arg1, arg2);
285
286 // Space before * in variable declaration.
287 int *x = NULL;
288
289 // Space after // beginning a comment.
290 // Notice the space between "//" and "N".
291 ```
292
293 Use only spaces, and indent 2 spaces at a time. Do not use tab characters in the
294 codebase.
295
296 Use a single blank line to separate logical code blocks, function definitions,
297 and sections of a file.
298
299 ### Brace style
300 ```
301 // Open curly braces are never on a line by themselves.
302 void my_function(void) {
303   // Conditional statements with only one child statement should elide braces.
304   // The child statement must be on a new line, indented by 2 spaces.
305   if (foo)
306     do_bar();
307   else
308     do_baz();
309
310   // Conditionals with a branch containing more than one child statement forces
311   // braces on both branches.
312   if (foo) {
313     do_bar();
314   } else {
315     do_baz();
316     ++var1;
317   }
318 }
319 ```