1================ 2C++ Coding style 3================ 4 5 6This document attempts to explain the basic styles and patterns used in 7the Mozilla codebase. New code should try to conform to these standards, 8so it is as easy to maintain as existing code. There are exceptions, but 9it's still important to know the rules! 10 11This article is particularly for those new to the Mozilla codebase, and 12in the process of getting their code reviewed. Before requesting a 13review, please read over this document, making sure that your code 14conforms to recommendations. 15 16.. container:: blockIndicator warning 17 18 Firefox code base uses the `Google Coding style for C++ 19 code <https://google.github.io/styleguide/cppguide.html>`__ 20 21 22Formatting code 23--------------- 24 25Formatting is done automatically via clang-format, and controlled via in-tree 26configuration files. See :ref:`Formatting C++ Code With clang-format` 27for more information. 28 29Unix-style linebreaks (``\n``), not Windows-style (``\r\n``). You can 30convert patches, with DOS newlines to Unix via the ``dos2unix`` utility, 31or your favorite text editor. 32 33Static analysis 34--------------- 35 36Several of the rules in the Google C++ coding styles and the additions mentioned below 37can be checked via clang-tidy (some rules are from the upstream clang-tidy, some are 38provided via a mozilla-specific plugin). Some of these checks also allow fixes to 39be automatically applied. 40 41``mach static-analysis`` provides a convenient way to run these checks. For example, 42for the check called ``google-readability-braces-around-statements``, you can run: 43 44.. code-block:: shell 45 46 ./mach static-analysis check --checks="-*,google-readability-braces-around-statements" --fix <file> 47 48It may be necessary to reformat the files after automatically applying fixes, see 49:ref:`Formatting C++ Code With clang-format`. 50 51Additional rules 52---------------- 53 54*The norms in this section should be followed for new code. For existing code, 55use the prevailing style in a file or module, ask the owner if you are 56in another team's codebase or it's not clear what style to use.* 57 58 59 60 61Control structures 62~~~~~~~~~~~~~~~~~~ 63 64Always brace controlled statements, even a single-line consequent of 65``if else else``. This is redundant, typically, but it avoids dangling 66else bugs, so it's safer at scale than fine-tuning. 67 68Examples: 69 70.. code-block:: cpp 71 72 if (...) { 73 } else if (...) { 74 } else { 75 } 76 77 while (...) { 78 } 79 80 do { 81 } while (...); 82 83 for (...; ...; ...) { 84 } 85 86 switch (...) { 87 case 1: { 88 // When you need to declare a variable in a switch, put the block in braces. 89 int var; 90 break; 91 } 92 case 2: 93 ... 94 break; 95 default: 96 break; 97 } 98 99``else`` should only ever be followed by ``{`` or ``if``; i.e., other 100control keywords are not allowed and should be placed inside braces. 101 102.. note:: 103 104 For this rule, clang-tidy provides the ``google-readability-braces-around-statements`` 105 check with autofixes. 106 107 108C++ namespaces 109~~~~~~~~~~~~~~ 110 111Mozilla project C++ declarations should be in the ``mozilla`` 112namespace. Modules should avoid adding nested namespaces under 113``mozilla``, unless they are meant to contain names which have a high 114probability of colliding with other names in the code base. For example, 115``Point``, ``Path``, etc. Such symbols can be put under 116module-specific namespaces, under ``mozilla``, with short 117all-lowercase names. Other global namespaces besides ``mozilla`` are 118not allowed. 119 120No ``using`` directives are allowed in header files, except inside class 121definitions or functions. (We don't want to pollute the global scope of 122compilation units that use the header file.) 123 124.. note:: 125 126 For parts of this rule, clang-tidy provides the ``google-global-names-in-headers`` 127 check. It only detects ``using namespace`` directives in the global namespace. 128 129 130``using namespace ...;`` is only allowed in ``.cpp`` files after all 131``#include``\ s. Prefer to wrap code in ``namespace ... { ... };`` 132instead, if possible. ``using namespace ...;``\ should always specify 133the fully qualified namespace. That is, to use ``Foo::Bar`` do not 134write ``using namespace Foo; using namespace Bar;``, write 135``using namespace Foo::Bar;`` 136 137Use nested namespaces (ex: ``namespace mozilla::widget {`` 138 139.. note:: 140 141 clang-tidy provides the ``modernize-concat-nested-namespaces`` 142 check with autofixes. 143 144 145Anonymous namespaces 146~~~~~~~~~~~~~~~~~~~~ 147 148We prefer using ``static``, instead of anonymous C++ namespaces. This may 149change once there is better debugger support (especially on Windows) for 150placing breakpoints, etc. on code in anonymous namespaces. You may still 151use anonymous namespaces for things that can't be hidden with ``static``, 152such as types, or certain objects which need to be passed to template 153functions. 154 155 156C++ classes 157~~~~~~~~~~~~ 158 159.. code-block:: cpp 160 161 namespace mozilla { 162 163 class MyClass : public A 164 { 165 ... 166 }; 167 168 class MyClass 169 : public X 170 , public Y 171 { 172 public: 173 MyClass(int aVar, int aVar2) 174 : mVar(aVar) 175 , mVar2(aVar2) 176 { 177 ... 178 } 179 180 // Special member functions, like constructors, that have default bodies 181 // should use '= default' annotation instead. 182 MyClass() = default; 183 184 // Unless it's a copy or move constructor or you have a specific reason to allow 185 // implicit conversions, mark all single-argument constructors explicit. 186 explicit MyClass(OtherClass aArg) 187 { 188 ... 189 } 190 191 // This constructor can also take a single argument, so it also needs to be marked 192 // explicit. 193 explicit MyClass(OtherClass aArg, AnotherClass aArg2 = AnotherClass()) 194 { 195 ... 196 } 197 198 int LargerFunction() 199 { 200 ... 201 ... 202 } 203 204 private: 205 int mVar; 206 }; 207 208 } // namespace mozilla 209 210Define classes using the style given above. 211 212.. note:: 213 214 For the rule on ``= default``, clang-tidy provides the ``modernize-use-default`` 215 check with autofixes. 216 217 For the rule on explicit constructors and conversion operators, clang-tidy 218 provides the ``mozilla-implicit-constructor`` check. 219 220Existing classes in the global namespace are named with a short prefix 221(For example, ``ns``) as a pseudo-namespace. 222 223 224Methods and functions 225~~~~~~~~~~~~~~~~~~~~~ 226 227 228C/C++ 229^^^^^ 230 231In C/C++, method names should use ``UpperCamelCase``. 232 233Getters that never fail, and never return null, are named ``Foo()``, 234while all other getters use ``GetFoo()``. Getters can return an object 235value, via a ``Foo** aResult`` outparam (typical for an XPCOM getter), 236or as an ``already_AddRefed<Foo>`` (typical for a WebIDL getter, 237possibly with an ``ErrorResult& rv`` parameter), or occasionally as a 238``Foo*`` (typical for an internal getter for an object with a known 239lifetime). See `the bug 223255 <https://bugzilla.mozilla.org/show_bug.cgi?id=223255>`_ 240for more information. 241 242XPCOM getters always return primitive values via an outparam, while 243other getters normally use a return value. 244 245Method declarations must use, at most, one of the following keywords: 246``virtual``, ``override``, or ``final``. Use ``virtual`` to declare 247virtual methods, which do not override a base class method with the same 248signature. Use ``override`` to declare virtual methods which do 249override a base class method, with the same signature, but can be 250further overridden in derived classes. Use ``final`` to declare virtual 251methods which do override a base class method, with the same signature, 252but can NOT be further overridden in the derived classes. This should 253help the person reading the code fully understand what the declaration 254is doing, without needing to further examine base classes. 255 256.. note:: 257 258 For the rule on ``virtual/override/final``, clang-tidy provides the 259 ``modernize-use-override`` check with autofixes. 260 261 262Operators 263~~~~~~~~~ 264 265The unary keyword operator ``sizeof``, should have its operand parenthesized 266even if it is an expression; e.g. ``int8_t arr[64]; memset(arr, 42, sizeof(arr));``. 267 268 269Literals 270~~~~~~~~ 271 272Use ``\uXXXX`` unicode escapes for non-ASCII characters. The character 273set for XUL, DTD, script, and properties files is UTF-8, which is not easily 274readable. 275 276 277Prefixes 278~~~~~~~~ 279 280Follow these naming prefix conventions: 281 282 283Variable prefixes 284^^^^^^^^^^^^^^^^^ 285 286- k=constant (e.g. ``kNC_child``). Not all code uses this style; some 287 uses ``ALL_CAPS`` for constants. 288- g=global (e.g. ``gPrefService``) 289- a=argument (e.g. ``aCount``) 290- C++ Specific Prefixes 291 292 - s=static member (e.g. ``sPrefChecked``) 293 - m=member (e.g. ``mLength``) 294 - e=enum variants (e.g. ``enum Foo { eBar, eBaz }``). Enum classes 295 should use ``CamelCase`` instead (e.g. 296 ``enum class Foo { Bar, Baz }``). 297 298 299Global functions/macros/etc 300^^^^^^^^^^^^^^^^^^^^^^^^^^^ 301 302- Macros begin with ``MOZ_``, and are all caps (e.g. 303 ``MOZ_WOW_GOODNESS``). Note that older code uses the ``NS_`` prefix; 304 while these aren't being changed, you should only use ``MOZ_`` for 305 new macros. The only exception is if you're creating a new macro, 306 which is part of a set of related macros still using the old ``NS_`` 307 prefix. Then you should be consistent with the existing macros. 308 309 310Error Variables 311^^^^^^^^^^^^^^^ 312 313- Local variables that are assigned ``nsresult`` result codes should be named ``rv`` 314 (i.e., e.g., not ``res``, not ``result``, not ``foo``). `rv` should not be 315 used for bool or other result types. 316- Local variables that are assigned ``bool`` result codes should be named `ok`. 317 318 319C/C++ practices 320--------------- 321 322- **Have you checked for compiler warnings?** Warnings often point to 323 real bugs. `Many of them <https://searchfox.org/mozilla-central/source/build/moz.configure/warnings.configure>`__ 324 are enabled by default in the build system. 325- In C++ code, use ``nullptr`` for pointers. In C code, using ``NULL`` 326 or ``0`` is allowed. 327 328.. note:: 329 330 For the C++ rule, clang-tidy provides the ``modernize-use-nullptr`` check 331 with autofixes. 332 333- Don't use ``PRBool`` and ``PRPackedBool`` in C++, use ``bool`` 334 instead. 335- For checking if a ``std`` container has no items, don't use 336 ``size()``, instead use ``empty()``. 337- When testing a pointer, use ``(!myPtr)`` or ``(myPtr)``; 338 don't use ``myPtr != nullptr`` or ``myPtr == nullptr``. 339- Do not compare ``x == true`` or ``x == false``. Use ``(x)`` or 340 ``(!x)`` instead. ``if (x == true)`` may have semantics different from 341 ``if (x)``! 342 343.. note:: 344 345 clang-tidy provides the ``readability-simplify-boolean-expr`` check 346 with autofixes that checks for these and some other boolean expressions 347 that can be simplified. 348 349- In general, initialize variables with ``nsFoo aFoo = bFoo,`` and not 350 ``nsFoo aFoo(bFoo)``. 351 352 - For constructors, initialize member variables with : ``nsFoo 353 aFoo(bFoo)`` syntax. 354 355- To avoid warnings created by variables used only in debug builds, use 356 the 357 `DebugOnly<T> <https://developer.mozilla.org/docs/Mozilla/Debugging/DebugOnly%3CT%3E>`__ 358 helper when declaring them. 359- You should `use the static preference 360 API <https://developer.mozilla.org/docs/Mozilla/Preferences/Using_preferences_from_application_code>`__ for 361 working with preferences. 362- One-argument constructors, that are not copy or move constructors, 363 should generally be marked explicit. Exceptions should be annotated 364 with ``MOZ_IMPLICIT``. 365- Use ``char32_t`` as the return type or argument type of a method that 366 returns or takes as argument a single Unicode scalar value. (Don't 367 use UTF-32 strings, though.) 368- Forward-declare classes in your header files, instead of including 369 them, whenever possible. For example, if you have an interface with a 370 ``void DoSomething(nsIContent* aContent)`` function, forward-declare 371 with ``class nsIContent;`` instead of ``#include "nsIContent.h"`` 372- Include guards are named per the Google coding style and should not 373 include a leading ``MOZ_`` or ``MOZILLA_``. For example 374 ``dom/media/foo.h`` would use the guard ``DOM_MEDIA_FOO_H_``. 375- Avoid the usage of ``typedef``, instead, please use ``using`` instead. 376 377.. note:: 378 379 For parts of this rule, clang-tidy provides the ``modernize-use-using`` 380 check with autofixes. 381 382 383COM and pointers 384---------------- 385 386- Use ``nsCOMPtr<>`` 387 If you don't know how to use it, start looking in the code for 388 examples. The general rule, is that the very act of typing 389 ``NS_RELEASE`` should be a signal to you to question your code: 390 "Should I be using ``nsCOMPtr`` here?". Generally the only valid use 391 of ``NS_RELEASE`` is when you are storing refcounted pointers in a 392 long-lived datastructure. 393- Declare new XPCOM interfaces using `XPIDL <https://developer.mozilla.org/docs/Mozilla/Tech/XPIDL>`__, so they 394 will be scriptable. 395- Use `nsCOMPtr <https://developer.mozilla.org/docs/Mozilla/Tech/XPCOM/Reference/Glue_classes/nsCOMPtr>`__ for strong references, and 396 `nsWeakPtr <https://developer.mozilla.org/docs/Mozilla/Tech/XPCOM/Weak_reference>`__ for weak references. 397- Don't use ``QueryInterface`` directly. Use ``CallQueryInterface`` or 398 ``do_QueryInterface`` instead. 399- Use `Contract 400 IDs <news://news.mozilla.org/3994AE3E.D96EF810@netscape.com>`__, 401 instead of CIDs with ``do_CreateInstance``/``do_GetService``. 402- Use pointers, instead of references for function out parameters, even 403 for primitive types. 404 405 406IDL 407--- 408 409 410Use leading-lowercase, or "interCaps" 411~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 412 413When defining a method or attribute in IDL, the first letter should be 414lowercase, and each following word should be capitalized. For example: 415 416.. code-block:: cpp 417 418 long updateStatusBar(); 419 420 421Use attributes wherever possible 422~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 423 424Whenever you are retrieving or setting a single value, without any 425context, you should use attributes. Don't use two methods when you could 426use an attribute. Using attributes logically connects the getting and 427setting of a value, and makes scripted code look cleaner. 428 429This example has too many methods: 430 431.. code-block:: cpp 432 433 interface nsIFoo : nsISupports 434 { 435 long getLength(); 436 void setLength(in long length); 437 long getColor(); 438 }; 439 440The code below will generate the exact same C++ signature, but is more 441script-friendly. 442 443.. code-block:: cpp 444 445 interface nsIFoo : nsISupports 446 { 447 attribute long length; 448 readonly attribute long color; 449 }; 450 451 452Use Java-style constants 453~~~~~~~~~~~~~~~~~~~~~~~~ 454 455When defining scriptable constants in IDL, the name should be all 456uppercase, with underscores between words: 457 458.. code-block:: cpp 459 460 const long ERROR_UNDEFINED_VARIABLE = 1; 461 462 463See also 464~~~~~~~~ 465 466For details on interface development, as well as more detailed style 467guides, see the `Interface development 468guide <https://developer.mozilla.org/docs/Mozilla/Developer_guide/Interface_development_guide>`__. 469 470 471Error handling 472-------------- 473 474 475Check for errors early and often 476~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 477 478Every time you make a call into an XPCOM function, you should check for 479an error condition. You need to do this even if you know that call will 480never fail. Why? 481 482- Someone may change the callee in the future to return a failure 483 condition. 484- The object in question may live on another thread, another process, 485 or possibly even another machine. The proxy could have failed to make 486 your call in the first place. 487 488Also, when you make a new function which is failable (i.e. it will 489return a ``nsresult`` or a ``bool`` that may indicate an error), you should 490explicitly mark the return value should always be checked. For example: 491 492:: 493 494 // for IDL. 495 [must_use] nsISupports 496 create(); 497 498 // for C++, add this in *declaration*, do not add it again in implementation. 499 [[nodiscard]] nsresult 500 DoSomething(); 501 502There are some exceptions: 503 504- Predicates or getters, which return ``bool`` or ``nsresult``. 505- IPC method implementation (For example, ``bool RecvSomeMessage()``). 506- Most callers will check the output parameter, see below. 507 508.. code-block:: cpp 509 510 nsresult 511 SomeMap::GetValue(const nsString& key, nsString& value); 512 513If most callers need to check the output value first, then adding 514``[[nodiscard]]`` might be too verbose. In this case, change the return value 515to void might be a reasonable choice. 516 517There is also a static analysis attribute ``MOZ_MUST_USE_TYPE``, which can 518be added to class declarations, to ensure that those declarations are 519always used when they are returned. 520 521 522Use the NS_WARN_IF macro when errors are unexpected. 523~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 524 525The ``NS_WARN_IF`` macro can be used to issue a console warning, in debug 526builds if the condition fails. This should only be used when the failure 527is unexpected and cannot be caused by normal web content. 528 529If you are writing code which wants to issue warnings when methods fail, 530please either use ``NS_WARNING`` directly, or use the new ``NS_WARN_IF`` macro. 531 532.. code-block:: cpp 533 534 if (NS_WARN_IF(somethingthatshouldbefalse)) { 535 return NS_ERROR_INVALID_ARG; 536 } 537 538 if (NS_WARN_IF(NS_FAILED(rv))) { 539 return rv; 540 } 541 542Previously, the ``NS_ENSURE_*`` macros were used for this purpose, but 543those macros hide return statements, and should not be used in new code. 544(This coding style rule isn't generally agreed, so use of ``NS_ENSURE_*`` 545can be valid.) 546 547 548Return from errors immediately 549~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 550 551In most cases, your knee-jerk reaction should be to return from the 552current function, when an error condition occurs. Don't do this: 553 554.. code-block:: cpp 555 556 rv = foo->Call1(); 557 if (NS_SUCCEEDED(rv)) { 558 rv = foo->Call2(); 559 if (NS_SUCCEEDED(rv)) { 560 rv = foo->Call3(); 561 } 562 } 563 return rv; 564 565Instead, do this: 566 567.. code-block:: cpp 568 569 rv = foo->Call1(); 570 if (NS_FAILED(rv)) { 571 return rv; 572 } 573 574 rv = foo->Call2(); 575 if (NS_FAILED(rv)) { 576 return rv; 577 } 578 579 rv = foo->Call3(); 580 if (NS_FAILED(rv)) { 581 return rv; 582 } 583 584Why? Error handling should not obfuscate the logic of the code. The 585author's intent, in the first example, was to make 3 calls in 586succession. Wrapping the calls in nested if() statements, instead 587obscured the most likely behavior of the code. 588 589Consider a more complicated example to hide a bug: 590 591.. code-block:: cpp 592 593 bool val; 594 rv = foo->GetBooleanValue(&val); 595 if (NS_SUCCEEDED(rv) && val) { 596 foo->Call1(); 597 } else { 598 foo->Call2(); 599 } 600 601The intent of the author, may have been, that ``foo->Call2()`` would only 602happen when val had a false value. In fact, ``foo->Call2()`` will also be 603called, when ``foo->GetBooleanValue(&val)`` fails. This may, or may not, 604have been the author's intent. It is not clear from this code. Here is 605an updated version: 606 607.. code-block:: cpp 608 609 bool val; 610 rv = foo->GetBooleanValue(&val); 611 if (NS_FAILED(rv)) { 612 return rv; 613 } 614 if (val) { 615 foo->Call1(); 616 } else { 617 foo->Call2(); 618 } 619 620In this example, the author's intent is clear, and an error condition 621avoids both calls to ``foo->Call1()`` and ``foo->Call2();`` 622 623*Possible exceptions:* Sometimes it is not fatal if a call fails. For 624instance, if you are notifying a series of observers that an event has 625fired, it might be trivial that one of these notifications failed: 626 627.. code-block:: cpp 628 629 for (size_t i = 0; i < length; ++i) { 630 // we don't care if any individual observer fails 631 observers[i]->Observe(foo, bar, baz); 632 } 633 634Another possibility, is you are not sure if a component exists or is 635installed, and you wish to continue normally, if the component is not 636found. 637 638.. code-block:: cpp 639 640 nsCOMPtr<nsIMyService> service = do_CreateInstance(NS_MYSERVICE_CID, &rv); 641 // if the service is installed, then we'll use it. 642 if (NS_SUCCEEDED(rv)) { 643 // non-fatal if this fails too, ignore this error. 644 service->DoSomething(); 645 646 // this is important, handle this error! 647 rv = service->DoSomethingImportant(); 648 if (NS_FAILED(rv)) { 649 return rv; 650 } 651 } 652 653 // continue normally whether or not the service exists. 654 655 656Strings 657------- 658 659- String arguments to functions should be declared as ``nsAString``. 660- Use ``EmptyString()`` and ``EmptyCString()`` instead of 661 ``NS_LITERAL_STRING("")`` or ``nsAutoString empty;``. 662- Use ``str.IsEmpty()`` instead of ``str.Length() == 0``. 663- Use ``str.Truncate()`` instead of ``str.SetLength(0)`` or 664 ``str.Assign(EmptyString())``. 665- For constant strings, use ``NS_LITERAL_STRING("...")`` instead of 666 ``NS_ConvertASCIItoUCS2("...")``, ``AssignWithConversion("...")``, 667 ``EqualsWithConversion("...")``, or ``nsAutoString()`` 668- To compare a string with a literal, use ``.EqualsLiteral("...")``. 669- Don't use functions from ``ctype.h`` (``isdigit()``, ``isalpha()``, 670 etc.) or from ``strings.h`` (``strcasecmp()``, ``strncasecmp()``). 671 These are locale-sensitive, which makes them inappropriate for 672 processing protocol text. At the same time, they are too limited to 673 work properly for processing natural-language text. Use the 674 alternatives in ``mozilla/TextUtils.h`` and in ``nsUnicharUtils.h`` 675 in place of ``ctype.h``. In place of ``strings.h``, prefer the 676 ``nsStringComparator`` facilities for comparing strings or if you 677 have to work with zero-terminated strings, use ``nsCRT.h`` for 678 ASCII-case-insensitive comparison. 679 680 681Use the ``Auto`` form of strings for local values 682~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 683 684When declaring a local, short-lived ``nsString`` class, always use 685``nsAutoString`` or ``nsAutoCString``. These pre-allocate a 64-byte 686buffer on the stack, and avoid fragmenting the heap. Don't do this: 687 688.. code-block:: cpp 689 690 nsresult 691 foo() 692 { 693 nsCString bar; 694 .. 695 } 696 697instead: 698 699.. code-block:: cpp 700 701 nsresult 702 foo() 703 { 704 nsAutoCString bar; 705 .. 706 } 707 708 709Be wary of leaking values from non-XPCOM functions that return char\* or PRUnichar\* 710~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 711 712It is an easy trap to return an allocated string, from an internal 713helper function, and then using that function inline in your code, 714without freeing the value. Consider this code: 715 716.. code-block:: cpp 717 718 static char* 719 GetStringValue() 720 { 721 .. 722 return resultString.ToNewCString(); 723 } 724 725 .. 726 WarnUser(GetStringValue()); 727 728In the above example, ``WarnUser`` will get the string allocated from 729``resultString.ToNewCString()`` and throw away the pointer. The 730resulting value is never freed. Instead, either use the string classes, 731to make sure your string is automatically freed when it goes out of 732scope, or make sure that your string is freed. 733 734Automatic cleanup: 735 736.. code-block:: cpp 737 738 static void 739 GetStringValue(nsAWritableCString& aResult) 740 { 741 .. 742 aResult.Assign("resulting string"); 743 } 744 745 .. 746 nsAutoCString warning; 747 GetStringValue(warning); 748 WarnUser(warning.get()); 749 750Free the string manually: 751 752.. code-block:: cpp 753 754 static char* 755 GetStringValue() 756 { 757 .. 758 return resultString.ToNewCString(); 759 } 760 761 .. 762 char* warning = GetStringValue(); 763 WarnUser(warning); 764 nsMemory::Free(warning); 765 766 767Use MOZ_UTF16() or NS_LITERAL_STRING() to avoid runtime string conversion 768~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 769 770It is very common to need to assign the value of a literal string, such 771as ``"Some String"``, into a unicode buffer. Instead of using ``nsString``'s 772``AssignLiteral`` and ``AppendLiteral``, use ``NS_LITERAL_STRING()`` 773instead. On most platforms, this will force the compiler to compile in a 774raw unicode string, and assign it directly. 775 776Incorrect: 777 778.. code-block:: cpp 779 780 nsAutoString warning; 781 warning.AssignLiteral("danger will robinson!"); 782 ... 783 foo->SetStringValue(warning); 784 ... 785 bar->SetUnicodeValue(warning.get()); 786 787Correct: 788 789.. code-block:: cpp 790 791 NS_NAMED_LITERAL_STRING(warning, "danger will robinson!"); 792 ... 793 // if you'll be using the 'warning' string, you can still use it as before: 794 foo->SetStringValue(warning); 795 ... 796 bar->SetUnicodeValue(warning.get()); 797 798 // alternatively, use the wide string directly: 799 foo->SetStringValue(NS_LITERAL_STRING("danger will robinson!")); 800 ... 801 bar->SetUnicodeValue(MOZ_UTF16("danger will robinson!")); 802 803.. note:: 804 805 Note: Named literal strings cannot yet be static. 806 807 808Usage of PR_(MAX|MIN|ABS|ROUNDUP) macro calls 809--------------------------------------------- 810 811Use the standard-library functions (``std::max``), instead of 812``PR_(MAX|MIN|ABS|ROUNDUP)``. 813 814Use ``mozilla::Abs`` instead of ``PR_ABS``. All ``PR_ABS`` calls in C++ code have 815been replaced with ``mozilla::Abs`` calls, in `bug 816847480 <https://bugzilla.mozilla.org/show_bug.cgi?id=847480>`__. All new 817code in ``Firefox/core/toolkit`` needs to ``#include "nsAlgorithm.h"`` and 818use the ``NS_foo`` variants instead of ``PR_foo``, or 819``#include "mozilla/MathAlgorithms.h"`` for ``mozilla::Abs``. 820