miniblink49 Documentation

A lighter, faster browser kernel of blink to integrate HTML UI in your app. 一个小巧、轻量的浏览器内核,用来取代wke和libcef

7,829 stars C++ C++ 1 file · ~571,376 tokens #blink#chromium#electron#nodejs
RAW Doc

Technical Documentation: weolar/miniblink49

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)

声明

miniblink 108内核版本和华为达成战略合作,已经在华为欧拉系统里开源https://gitee.com/openeuler/liteview 。

而本仓库收藏的是较老的49内核版本。如果需要更新的,可以参考上述108内核版本。

miniblink132内核也即将开源,大家敬请期待。

可执行文件及头文件下载地址(含最新的132版本):https://github.com/weolar/miniblink49/releases

希望大家尊重开源,尊重作者全职几年持续更新付出的劳动。

如需获得后续技术支持,请使用以下联系方式:

开发者论坛:https://bbs.miniblink.com/ (注册后,需要加我QQ告诉我,我才能验证通过)

加微信群:

Telegram群:https://t.me/miniblink

Q群:738349226(可加)、94093808(已满勿加)

QQ(weolar):93527630

email:[email protected]

微信:可发邮箱咨询我微信号。暂时不放到github了

简介 Abstract

miniblink is a open source, one file, small browser widget base on chromium.

By using C interface, you can create a browser just some line code.

more information at http://miniblink.net


miniblink是一个开源的、单文件、且目前已知的最小的基于chromium的,浏览器控件。

通过其导出的纯C接口,几行代码即可创建一个浏览器控件。

您可以通过官网http://miniblink.net 来获取更多的关于miniblink的信息。


特性 Features

  • 极致小巧的体积 (small size)
  • C++,C#,Delphi等语言调用 (support C++,C#,Delphi language to call)
  • 内嵌Nodejs,支持electron (with Nodejs, can run electron)
  • 随心所欲的定制功能、模拟环境 (simulate other browser environment)
  • 支持Windows xp、npapi (support windows xp and npapi)
  • 完善的HTML5支持,对各种前端库友好 (support HTML5, and friendly to front framework)
  • 关闭跨域开关后,可以使用各种跨域功能 (support cross domain)
  • 网络资源拦截,替换任意网站任意js为本地文件 (network intercept, you can replace any resource to local file)
  • headless模式,极大节省资源,适用于爬虫 (headless mode, be suitable for Web Crawler)

文档 Document

关于miniblink的介绍见这篇文章:https://zhuanlan.zhihu.com/p/22611497?group_id=764036386641707008

API文档见:https://miniblink.net/views/doc/index.html


使用 Usage

请前往https://github.com/weolar/miniblink49/releases 下载最新编译后的SDK,里面的demo_src是个完整的用例。

或者前往 https://github.com/weolar/mb-demo 下载

最简单的创建一个窗口:

Usage

cpp
// 无边框窗体 borderless window
wkeWebView window = wkeCreateWebWindow(WKE_WINDOW_TYPE_TRANSPARENT, NULL, 0, 0, 640, 480);  
wkeLoadURLW(window, L"miniblink.net");

编译 Build

不推荐自己编译。请前往https://github.com/weolar/miniblink49/releases 下载编译好的文件使用。

因为每天有大量更新,我无法确保每次更新都能保证编译通过。如果有编译错误,请不要来提问,耐心等待我的下次提交。


mini-electron

mini-electron项目是一个基于miniblink的独立项目,旨在创建一个更小的electron运行环境。目前已经实现了这一目标。

通过替换mini-electron,打包完后的文件仅仅6m左右。


联系方式

大家有问题可以选择:


致谢 Thanks

特别感谢网友zero,他是miniblink的代码的重要贡献者。

感谢网友core,感谢网友“大清知府”。

感谢网友boxue( https://www.zhihu.com/people/coltor/ ),他致力于对miniblink架构的研究及推广。


V8 5 1 Docs README (`v8_5_1/docs/README.md`)

The documentation for V8 can be found at the
V8 Wiki.


V8 7 5 Tools Mb Docs README (`v8_7_5/tools/mb/docs/README.md`)

The MB (Meta-Build wrapper) documentation


Node Openssl Doc UPGRADING (`node/openssl/doc/UPGRADING.md`)

How to upgrade openssl library in Node.js

This document describes the procedure to upgrade openssl from 1.0.2e
to 1.0.2f in Node.js. This procedure might be applied to upgrading
any versions in 1.0.2.

Build System and Upgrading Overview

The openssl build system is based on the Configure perl script in
deps/openssl/openssl. For example, running Configure linux_x86-64
in the openssl repository generates Makefile and opensslconf.h for
the linux_x86_64 target architecture.

The Makefile contains the list of asm files which are generated by
perl scripts during build so that we can get the most of use of the
hardware performance according to the type of cpus.

Configure TABLE shows various build parameters that depend on each
os and arch.

In Node.js, build target is defined as --dest-os and --dest-cpu in
configure options which are different from the one that is defined in
openssl and it's build system is gyp that is based on python,
therefore we cannot use the openssl build system directly.

In order to build openssl with gyp in node, files of opensslconf.h and
asm are generated in advance for several supported platforms.

Here is a map table to show conf(opensslconf.h) and asm between
the openssl target and configuration parameters of os and cpu in node.
The tested platform in CI are also listed.

--dest-os --dest-cpu conf asm openssl target CI
aix ppc o x(*2) aix-gcc o
aix ppc64 o x(*2) aix64-gcc o
linux ia32 o o linux-elf o
linux x32 o x(*2) linux-x32 x
linux x64 o o linux-x86_64 o
linux arm o o linux-arm o
linux arm64 o o linux-aarch64 o
mac ia32 o o darwin-i386-cc -
mac x64 o o darwin64-x86_64-cc o
win ia32 o o(*3) VC-WIN32 x
win x64 o o VC-WIN64A o
solaris ia32 o o solaris-x86-gcc o
solaris x64 o o solaris64-x86_64-gcc o
freebsd ia32 o o BSD-x86 o
freebsd x64 o o BSD-x86_64 o
openbsd ia32 o o BSD-x86 x
openbsd x64 o o BSD-x86_64 x
others ia32 x(*1) o - x
others x64 x(*1) o - x
others arm x(*1) o - x
others arm64 x(*1) o - x
others others x(*1) x(*2) - x
  • (*1) use linux-elf as a fallback configuration
  • (*2) no-asm used
  • (*3) currently masm (Microsoft Macro Assembler) is used but it's no
    longer supported in openssl. We need to move to use nasm or yasm.

All parameters such as sources, defines, cflags and others generated
in openssl Makefile are written down into deps/openssl/openssl.gypi.

The header file of deps/openssl/openssl/crypto/opensslconf.h are
generated by Configure and varies on each os and arch so that we
made a new deps/openssl/config/opensslconf.h, where it includes each
conf file from deps/openssl/config/archs/*/opensslconf.h by using
pre-defined compiler macros. This procedure can be processed
automatically with deps/openssl/config/Makefile

Assembler support is one of the key features in openssl, but asm files
are dynamically generated with
deps/openssl/openssl/crypto/*/asm/*.pl by perl during
build. Furthermore, these perl scripts check the version of assembler
and generate asm files according to the supported instructions in each
compiler.

Since perl is not a build requirement in node, they all should be
generated in advance and statically stored in the repository. We
provide two sets of asm files, one is asm_latest(avx2 and addx
supported) in deps/openssl/asm and the other asm_obsolete(without
avx1/2 and addx) in deps/openssl/asm_obsolute, which depends on
supported features in assemblers. Each directory has a Makefile
to generate asm files with perl scripts in openssl sources.

configure and gyp check the version of assemblers such as gnu
as(gas), llvm and Visual Studio. deps/openssl/openssl.gypi
determines what asm files should be used, in which the asm_latest
needs the version of gas >= 2.23, llvm >= 3.3 or MSVS_VERSION>='2012'
(ml64 >= 12) as defined in
https://github.com/openssl/openssl/blob/OpenSSL_1_0_2-stable/crypto/sha/asm/sha512-x86_64.pl#L112-L129,
otherwise asm_obsolete are used.

The following is the detail instruction steps how to upgrade openssl
version from 1.0.2e to 1.0.2f in node.

This needs to run Linux
enviroment.

1. Replace openssl source in `deps/openssl/openssl`

Remove old openssl sources in deps/openssl/openssl .
Get original openssl sources from
https://www.openssl.org/source/openssl-1.0.2f.tar.gz and extract all
files into deps/openssl/openssl .

sh
ohtsu@ubuntu:~/github/node$ cd deps/openssl/
ohtsu@ubuntu:~/github/node/deps/openssl$ rm -rf openssl
ohtsu@ubuntu:~/github/node/deps/openssl$ tar zxf ~/tmp/openssl-1.0.2f.tar.gz
ohtsu@ubuntu:~/github/node/deps/openssl$ mv openssl-1.0.2f openssl
ohtsu@ubuntu:~/github/node/deps/openssl$ git add --all openssl
ohtsu@ubuntu:~/github/node/deps/openssl$ git commit openssl

The commit message can be

deps: upgrade openssl sources to 1.0.2f

This replaces all sources of openssl-1.0.2f.tar.gz into
deps/openssl/openssl

2. Replace openssl header files in `deps/openssl/openssl/include/openssl`

all header files in deps/openssl/openssl/include/openssl/*.h are
symbolic links in the distributed release tar.gz. They cause issues in
Windows. They are copied from the real files of symlink origin into
the include directory. During installation, they also copied into
PREFIX/node/include by tools/install.py.
deps/openssl/openssl/include/openssl/opensslconf.h and
deps/openssl/openssl/crypto/opensslconf.h needs to be changed so as
to refer the platform independent file of deps/openssl/config/opensslconf.h

The following shell script (copy_symlink.sh) is my tool for working
this procedures to invoke it in the deps/openssl/openssl/include/openssl/.

sh
#!/bin/bash
for var in "$@"
do
    if [ -L $var ]; then
	origin=`readlink $var`
	rm $var
	cp $origin $var
    fi
done
rm opensslconf.h
echo '#include "../../crypto/opensslconf.h"' >  opensslconf.h
rm ../../crypto/opensslconf.h
echo '#include "../../config/opensslconf.h"' > ../../crypto/opensslconf.h

This step somehow gets troublesome since openssl-1.0.2f because
symlink headers are removed in tar.gz file and we have to execute
./config script to generate them. The config script also generate
unnecessary platform dependent files in the repository so that we have
to clean up them after committing header files.

sh
ohtsu@ubuntu:~/github/node/deps/openssl$ cd openssl/
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ ./config

make[1]: Leaving directory `/home/ohtsu/github/node/deps/openssl/openssl/test'

Configured for linux-x86_64.
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ cd include/openssl/
ohtsu@ubuntu:~/github/node/deps/openssl/openssl/include/openssl$ ~/copy_symlink.sh *.h
ohtsu@ubuntu:~/github/node/deps/openssl/openssl/include/openssl$ cd ../..
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ git add include
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ git commit include/ crypto/opensslconf.h
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ git clean -f
ohtsu@ubuntu:~/github/node/deps/openssl/openssl$ git checkout Makefile Makefile.bak

The commit message can be

deps: copy all openssl header files to include dir

All symlink files in deps/openssl/openssl/include/openssl/
are removed and replaced with real header files to avoid
issues on Windows. Two files of opensslconf.h in crypto and
include dir are replaced to refer config/opensslconf.h.

3. Apply floating patches

At the time of writing, there are four floating patches to be applied
to openssl.

  • Two fixes for assembly errors on ia32 win32.

  • One fix for openssl-cli built on win. Key press requirement of
    openssl-cli in win causes timeout failures of several tests.

  • Adding a new -no_rand_screen option to openssl s_client. This
    makes test time of test-tls-server-verify be much faster.

These fixes can be applied via cherry-pick. The first three will merge without conflict.
The last commit can be landed using a recursive strategy that prefers newer changes.

sh
git cherry-pick c66c3d9fa3f5bab0bdfe363dd947136cf8a3907f
git cherry-pick 42a8de2ac66b6953cbc731fdb0b128b8019643b2
git cherry-pick 2eb170874aa5e84e71b62caab7ac9792fd59c10f
git cherry-pick --strategy=recursive -X theirs 664a659

If you attempted to cherry-pick the last commit you would have the following conflict

text
# do not do this
git cherry-pick 664a6596960655e214fef25e74d3285097703e95
error: could not apply 664a659... deps: add -no_rand_screen to openssl s_client
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
git cherry-pi

the conflict is in deps/openssl/openssl/apps/app_rand.c as below.

sh
ohtsu@omb:openssl$ git diff
diff --cc deps/openssl/openssl/apps/app_rand.c
index 7f40bba,b6fe294..0000000
--- a/deps/openssl/openssl/apps/app_rand.c
+++ b/deps/openssl/openssl/apps/app_rand.c
@@@ -124,7 -124,16 +124,20 @@@ int app_RAND_load_file(const char *file
      char buffer[200];

  #ifdef OPENSSL_SYS_WINDOWS
  ++<<<<<<< HEAD
   +    RAND_screen();
   ++=======
   +     /*
   +      * allocate 2 to dont_warn not to use RAND_screen() via
   +      * -no_rand_screen option in s_client
   +      */
   +     if (dont_warn != 2) {
   +       BIO_printf(bio_e, "Loading 'screen' into random state -");
   +       BIO_flush(bio_e);
   +       RAND_screen();
   +       BIO_printf(bio_e, " done\n");
   +     }
   ++>>>>>>> 664a659... deps: add -no_rand_screen to openssl s_client
     #endif

      if (file == NULL)

We want to opt for the changes from 664a659 instead of the changes present on HEAD.
git cherry-pick --strategy=recursive -X theirs will do just that!

4. Change `opensslconf.h` so as to fit each platform.

opensslconf.h includes defines and macros which are platform
dependent. Each files can be generated via deps/openssl/config/Makefile
We can regenerate them and commit them if any diffs exist.

sh
ohtsu@ubuntu:~/github/node/deps/openssl$ cd config
ohtsu@ubuntu:~/github/node/deps/openssl/config$ make clean
find archs -name opensslconf.h -exec rm "{}" \;
ohtsu@ubuntu:~/github/node/deps/openssl/config$ make
cd ../openssl; perl ./Configure no-shared no-symlinks aix-gcc > /dev/null
ohtsu@ubuntu:~/github/node/deps/openssl/config$ git diff
ohtsu@ubuntu:~/github/node/deps/openssl/config$ git commit .

The commit message can be

deps: update openssl config files

Regenerate config files for supported platforms with Makefile.

5. Update openssl.gyp and openssl.gypi

This process is needed when source files are removed, renamed and added.
It seldom happen in the minor bug fix release. Build errors would be
thrown if it happens. In case of build errors, we need to check source
files in Makefiles of its platform and change openssl.gyp or
openssl.gypi according to the changes of source files. Please contact
@shigeki if it is needed.

6. ASM files for openssl

We provide two sets of asm files. One is for the latest assembler
and the other is the older one. sections 6.1 and 6.2 describe the two
types of files. Section 6.3 explains the steps to update the files.
In the case of upgrading 1.0.2f there were no changes to the asm files.

6.1. asm files for the latest compiler

This was made in deps/openssl/asm/Makefile

  • Updated asm files for each platforms which are required in
    openssl-1.0.2f.
  • Some perl files need CC and ASM envs. Added a check if these envs
    exist. Followed asm files are to be generated with CC=gcc and
    ASM=nasm on Linux. See
    deps/openssl/openssl/crypto/sha/asm/sha512-x86_64.pl
  • Added new 32bit targets/rules with a sse2 flag (OPENSSL_IA32_SSE2)
    to generate asm for use SSE2.
  • Generating sha512 asm files in x86_64 need output filename which
    has 512. Added new rules so as not to use stdout for outputs.
  • PERLASM_SCHEME of linux-armv4 is void as defined in openssl
    Configure. Changed its target/rule and all directories are moved
    from arm-elf-gas to arm-void-gas.
  • add a new rule for armv8 asm generation

With export environments of CC=gcc and ASM=nasm, then type make
command and check if new asm files are generated.
If you don't have nasm please install it such as apt-get install nasm.

6.2. asm files for the older compiler

For older assembler, the version check of CC and ASM should be
skipped in generating asm file with perl scripts.
Copy files from deps/openssl/asm into
deps/openssl/asm/asm_obsolete and change rules to generate asm files
into this directories and remove the check of CC and ASM envs.

Without environments of CC and ASM, then type make command and check
if new asm files for older compilers are generated.

The following steps includes version check of gcc and nasm.

6.3 steps

sh
ohtsu@ubuntu:~/github/node/deps/openssl/config$ cd ../asm
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

ohtsu@ubuntu:~/github/node/deps/openssl/asm$ nasm -v
NASM version 2.10.09 compiled on Dec 29 2013
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ export CC=gcc
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ export ASM=nasm
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ make clean
find . -iname '*.asm' -exec rm "{}" \;
find . -iname '*.s' -exec rm "{}" \;
find . -iname '*.S' -exec rm "{}" \;
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ make
ohtsu@ubuntu:~/github/node/deps/openssl/asm$ cd ../asm_obsolete/
ohtsu@ubuntu:~/github/node/deps/openssl/asm_obsolete$ unset CC
ohtsu@ubuntu:~/github/node/deps/openssl/asm_obsolete$ unset ASM
ohtsu@ubuntu:~/github/node/deps/openssl/asm_obsolete$ make clean
find . -iname '*.asm' -exec rm "{}" \;
find . -iname '*.s' -exec rm "{}" \;
find . -iname '*.S' -exec rm "{}" \;
ohtsu@ubuntu:~/github/node/deps/openssl$ git status
ohtsu@ubuntu:~/github/node/deps/openssl$ git commit asm asm_obsolete

The commit message can be

deps: update openssl asm and asm_obsolete files

Regenerate asm files with Makefile and CC=gcc and ASM=gcc where
gcc-4.8.4. Also asm files in asm_obsolete dir to support old compiler
and assembler are regenerated without CC and ASM envs.


Third Party Ffmpeg Doc Build System (`third_party/ffmpeg/doc/build_system.txt`)

FFmpeg currently uses a custom build system, this text attempts to document
some of its obscure features and options.

Makefile variables:

V
Disable the default terse mode, the full command issued by make and its
output will be shown on the screen.

DBG
Preprocess x86 external assembler files to a .dbg.asm file in the object
directory, which then gets compiled. Helps in developing those assembler
files.

DESTDIR
Destination directory for the install targets, useful to prepare packages
or install FFmpeg in cross-environments.

GEN
Set to ‘1’ to generate the missing or mismatched references.

Makefile targets:

all
Default target, builds all the libraries and the executables.

fate
Run the fate test suite, note that you must have installed it.

fate-list
List all fate/regression test targets.

install
Install headers, libraries and programs.

examples
Build all examples located in doc/examples.

libavformat/output-example
Build the libavformat basic example.

libavcodec/api-example
Build the libavcodec basic example.

libswscale/swscale-test
Build the swscale self-test (useful also as an example).

config
Reconfigure the project with the current configuration.

Useful standard make commands:
make -t
Touch all files that otherwise would be built, this is useful to reduce
unneeded rebuilding when changing headers, but note that you must force rebuilds
of files that actually need it by hand then.

make -j
Rebuild with multiple jobs at the same time. Faster on multi processor systems.

make -k
Continue build in case of errors, this is useful for the regression tests
sometimes but note that it will still not run all reg tests.


Third Party Ffmpeg Doc Errno (`third_party/ffmpeg/doc/errno.txt`)

The following table lists most error codes found in various operating
systems supported by FFmpeg.

text
OS

Code Std F LBMWwb Text (YMMV)

E2BIG POSIX ++++++ Argument list too long
EACCES POSIX ++++++ Permission denied
EADDRINUSE POSIX +++..+ Address in use
EADDRNOTAVAIL POSIX +++..+ Cannot assign requested address
EADV +..... Advertise error
EAFNOSUPPORT POSIX +++..+ Address family not supported
EAGAIN POSIX + ++++++ Resource temporarily unavailable
EALREADY POSIX +++..+ Operation already in progress
EAUTH .++... Authentication error
EBADARCH ..+... Bad CPU type in executable
EBADE +..... Invalid exchange
EBADEXEC ..+... Bad executable
EBADF POSIX ++++++ Bad file descriptor
EBADFD +..... File descriptor in bad state
EBADMACHO ..+... Malformed Macho file
EBADMSG POSIX ++4... Bad message
EBADR +..... Invalid request descriptor
EBADRPC .++... RPC struct is bad
EBADRQC +..... Invalid request code
EBADSLT +..... Invalid slot
EBFONT +..... Bad font file format
EBUSY POSIX - ++++++ Device or resource busy
ECANCELED POSIX +++... Operation canceled
ECHILD POSIX ++++++ No child processes
ECHRNG +..... Channel number out of range
ECOMM +..... Communication error on send
ECONNABORTED POSIX +++..+ Software caused connection abort
ECONNREFUSED POSIX - +++ss+ Connection refused
ECONNRESET POSIX +++..+ Connection reset
EDEADLK POSIX ++++++ Resource deadlock avoided
EDEADLOCK +..++. File locking deadlock error
EDESTADDRREQ POSIX +++... Destination address required
EDEVERR ..+... Device error
EDOM C89 - ++++++ Numerical argument out of domain
EDOOFUS .F.... Programming error
EDOTDOT +..... RFS specific error
EDQUOT POSIX +++... Disc quota exceeded
EEXIST POSIX ++++++ File exists
EFAULT POSIX - ++++++ Bad address
EFBIG POSIX - ++++++ File too large
EFTYPE .++... Inappropriate file type or format
EHOSTDOWN +++... Host is down
EHOSTUNREACH POSIX +++..+ No route to host
EHWPOISON +..... Memory page has hardware error
EIDRM POSIX +++... Identifier removed
EILSEQ C99 ++++++ Illegal byte sequence
EINPROGRESS POSIX - +++ss+ Operation in progress
EINTR POSIX - ++++++ Interrupted system call
EINVAL POSIX + ++++++ Invalid argument
EIO POSIX + ++++++ I/O error
EISCONN POSIX +++..+ Socket is already connected
EISDIR POSIX ++++++ Is a directory
EISNAM +..... Is a named type file
EKEYEXPIRED +..... Key has expired
EKEYREJECTED +..... Key was rejected by service
EKEYREVOKED +..... Key has been revoked
EL2HLT +..... Level 2 halted
EL2NSYNC +..... Level 2 not synchronized
EL3HLT +..... Level 3 halted
EL3RST +..... Level 3 reset
ELIBACC +..... Can not access a needed shared library
ELIBBAD +..... Accessing a corrupted shared library
ELIBEXEC +..... Cannot exec a shared library directly
ELIBMAX +..... Too many shared libraries
ELIBSCN +..... .lib section in a.out corrupted
ELNRNG +..... Link number out of range
ELOOP POSIX +++..+ Too many levels of symbolic links
EMEDIUMTYPE +..... Wrong medium type
EMFILE POSIX ++++++ Too many open files
EMLINK POSIX ++++++ Too many links
EMSGSIZE POSIX +++..+ Message too long
EMULTIHOP POSIX ++4... Multihop attempted
ENAMETOOLONG POSIX - ++++++ File name too long
ENAVAIL +..... No XENIX semaphores available
ENEEDAUTH .++... Need authenticator
ENETDOWN POSIX +++..+ Network is down
ENETRESET SUSv3 +++..+ Network dropped connection on reset
ENETUNREACH POSIX +++..+ Network unreachable
ENFILE POSIX ++++++ Too many open files in system
ENOANO +..... No anode
ENOATTR .++... Attribute not found
ENOBUFS POSIX - +++..+ No buffer space available
ENOCSI +..... No CSI structure available
ENODATA XSR +N4... No message available
ENODEV POSIX - ++++++ No such device
ENOENT POSIX - ++++++ No such file or directory
ENOEXEC POSIX ++++++ Exec format error
ENOFILE ...++. No such file or directory
ENOKEY +..... Required key not available
ENOLCK POSIX ++++++ No locks available
ENOLINK POSIX ++4... Link has been severed
ENOMEDIUM +..... No medium found
ENOMEM POSIX ++++++ Not enough space
ENOMSG POSIX +++..+ No message of desired type
ENONET +..... Machine is not on the network
ENOPKG +..... Package not installed
ENOPROTOOPT POSIX +++..+ Protocol not available
ENOSPC POSIX ++++++ No space left on device
ENOSR XSR +N4... No STREAM resources
ENOSTR XSR +N4... Not a STREAM
ENOSYS POSIX + ++++++ Function not implemented
ENOTBLK +++... Block device required
ENOTCONN POSIX +++..+ Socket is not connected
ENOTDIR POSIX ++++++ Not a directory
ENOTEMPTY POSIX ++++++ Directory not empty
ENOTNAM +..... Not a XENIX named type file
ENOTRECOVERABLE SUSv4 - +..... State not recoverable
ENOTSOCK POSIX +++..+ Socket operation on non-socket
ENOTSUP POSIX +++... Operation not supported
ENOTTY POSIX ++++++ Inappropriate I/O control operation
ENOTUNIQ +..... Name not unique on network
ENXIO POSIX ++++++ No such device or address
EOPNOTSUPP POSIX +++..+ Operation not supported (on socket)
EOVERFLOW POSIX +++..+ Value too large to be stored in data type
EOWNERDEAD SUSv4 +..... Owner died
EPERM POSIX - ++++++ Operation not permitted
EPFNOSUPPORT +++..+ Protocol family not supported
EPIPE POSIX - ++++++ Broken pipe
EPROCLIM .++... Too many processes
EPROCUNAVAIL .++... Bad procedure for program
EPROGMISMATCH .++... Program version wrong
EPROGUNAVAIL .++... RPC prog. not avail
EPROTO POSIX ++4... Protocol error
EPROTONOSUPPORT POSIX - +++ss+ Protocol not supported
EPROTOTYPE POSIX +++..+ Protocol wrong type for socket
EPWROFF ..+... Device power is off
ERANGE C89 - ++++++ Result too large
EREMCHG +..... Remote address changed
EREMOTE +++... Object is remote
EREMOTEIO +..... Remote I/O error
ERESTART +..... Interrupted system call should be restarted
ERFKILL +..... Operation not possible due to RF-kill
EROFS POSIX ++++++ Read-only file system
ERPCMISMATCH .++... RPC version wrong
ESHLIBVERS ..+... Shared library version mismatch
ESHUTDOWN +++..+ Cannot send after socket shutdown
ESOCKTNOSUPPORT +++... Socket type not supported
ESPIPE POSIX ++++++ Illegal seek
ESRCH POSIX ++++++ No such process
ESRMNT +..... Srmount error
ESTALE POSIX +++..+ Stale NFS file handle
ESTRPIPE +..... Streams pipe error
ETIME XSR +N4... Stream ioctl timeout
ETIMEDOUT POSIX - +++ss+ Connection timed out
ETOOMANYREFS +++... Too many references: cannot splice
ETXTBSY POSIX +++... Text file busy
EUCLEAN +..... Structure needs cleaning
EUNATCH +..... Protocol driver not attached
EUSERS +++... Too many users
EWOULDBLOCK POSIX +++..+ Operation would block
EXDEV POSIX ++++++ Cross-device link
EXFULL +..... Exchange full

Notations:

F: used in FFmpeg (-: a few times, +: a lot)

SUSv3: Single Unix Specification, version 3
SUSv4: Single Unix Specification, version 4
XSR: XSI STREAMS (obsolete)

OS: availability on some supported operating systems
L: GNU/Linux
B: BSD (F: FreeBSD, N: NetBSD)
M: MacOS X
W: Microsoft Windows (s: emulated with winsock, see libavformat/network.h)
w: Mingw32 (3.17) and Mingw64 (2.0.1)
b: BeOS


Third Party Ffmpeg Doc Ffmpeg (`third_party/ffmpeg/doc/ffmpeg.txt`)

:
ffmpeg.c : libav*
======== : ======
:
:
--------------------------------:---> AVStream...
InputStream input_streams[] / :
/ :
InputFile input_files[] +==========================+ / ^ :
------> 0 | : st ---:-----------:--/ : :
^ +------+-----------+-----+ / +--------------------------+ : :
: | :ist_index--:-----:---------/ 1 | : st : | : :
: +------+-----------+-----+ +==========================+ : :
nb_input_files : | :ist_index--:-----:------------------> 2 | : st : | : :
: +------+-----------+-----+ +--------------------------+ : nb_input_streams :
: | :ist_index : | 3 | ... | : :
v +------+-----------+-----+ +--------------------------+ : :
--> 4 | | : :
| +--------------------------+ : :
| 5 | | : :
| +==========================+ v :
| :
| :
| :
| :
--------- --------------------------------:---> AVStream...
\ / :
OutputStream output_streams[] / :
\ / :
+============================/======+ ^ :
------> 0 | : source_index : st-:--- | : :
OutputFile output_files[] / +------------------------------------+ : :
/ 1 | : : : | : :
^ +------+------------+-----+ / +------------------------------------+ : :
: | : ost_index -:-----:------/ 2 | : : : | : :
nb_output_files : +------+------------+-----+ +====================================+ : :
: | : ost_index -:-----|-----------------> 3 | : : : | : :
: +------+------------+-----+ +------------------------------------+ : nb_output_streams :
: | : : | 4 | | : :
: +------+------------+-----+ +------------------------------------+ : :
: | : : | 5 | | : :
v +------+------------+-----+ +------------------------------------+ : :
6 | | : :
+------------------------------------+ : :
7 | | : :
+====================================+ v :
:


Third Party Ffmpeg Doc Filter Design (`third_party/ffmpeg/doc/filter_design.txt`)

Filter design

This document explains guidelines that should be observed (or ignored with
good reason) when writing filters for libavfilter.

In this document, the word “frame” indicates either a video frame or a group
of audio samples, as stored in an AVFilterBuffer structure.

Format negotiation

The query_formats method should set, for each input and each output links,
the list of supported formats.

For video links, that means pixel format. For audio links, that means
channel layout, sample format (the sample packing is implied by the sample
format) and sample rate.

The lists are not just lists, they are references to shared objects. When
the negotiation mechanism computes the intersection of the formats
supported at each end of a link, all references to both lists are replaced
with a reference to the intersection. And when a single format is
eventually chosen for a link amongst the remaining list, again, all
references to the list are updated.

That means that if a filter requires that its input and output have the
same format amongst a supported list, all it has to do is use a reference
to the same list of formats.

query_formats can leave some formats unset and return AVERROR(EAGAIN) to
cause the negotiation mechanism to try again later. That can be used by
filters with complex requirements to use the format negotiated on one link
to set the formats supported on another.

Buffer references ownership and permissions

Principle

text
Audio and video data are voluminous; the buffer and buffer reference
mechanism is intended to avoid, as much as possible, expensive copies of
that data while still allowing the filters to produce correct results.

The data is stored in buffers represented by AVFilterBuffer structures.
They must not be accessed directly, but through references stored in
AVFilterBufferRef structures. Several references can point to the
same buffer; the buffer is automatically deallocated once all
corresponding references have been destroyed.

The characteristics of the data (resolution, sample rate, etc.) are
stored in the reference; different references for the same buffer can
show different characteristics. In particular, a video reference can
point to only a part of a video buffer.

A reference is usually obtained as input to the start_frame or
filter_frame method or requested using the ff_get_video_buffer or
ff_get_audio_buffer functions. A new reference on an existing buffer can
be created with the avfilter_ref_buffer. A reference is destroyed using
the avfilter_unref_bufferp function.

Reference ownership

text
At any time, a reference “belongs” to a particular piece of code,
usually a filter. With a few caveats that will be explained below, only
that piece of code is allowed to access it. It is also responsible for
destroying it, although this is sometimes done automatically (see the
section on link reference fields).

Here are the (fairly obvious) rules for reference ownership:

* A reference received by the filter_frame method (or its start_frame
  deprecated version) belongs to the corresponding filter.

  Special exception: for video references: the reference may be used
  internally for automatic copying and must not be destroyed before
  end_frame; it can be given away to ff_start_frame.

* A reference passed to ff_filter_frame (or the deprecated
  ff_start_frame) is given away and must no longer be used.

* A reference created with avfilter_ref_buffer belongs to the code that
  created it.

* A reference obtained with ff_get_video_buffer or ff_get_audio_buffer
  belongs to the code that requested it.

* A reference given as return value by the get_video_buffer or
  get_audio_buffer method is given away and must no longer be used.
text
The AVFilterLink structure has a few AVFilterBufferRef fields. The
cur_buf and out_buf were used with the deprecated
start_frame/draw_slice/end_frame API and should no longer be used.
src_buf and partial_buf are used by libavfilter internally
and must not be accessed by filters.

Reference permissions

text
The AVFilterBufferRef structure has a perms field that describes what
the code that owns the reference is allowed to do to the buffer data.
Different references for the same buffer can have different permissions.

For video filters that implement the deprecated
start_frame/draw_slice/end_frame API, the permissions only apply to the
parts of the buffer that have already been covered by the draw_slice
method.

The value is a binary OR of the following constants:

* AV_PERM_READ: the owner can read the buffer data; this is essentially
  always true and is there for self-documentation.

* AV_PERM_WRITE: the owner can modify the buffer data.

* AV_PERM_PRESERVE: the owner can rely on the fact that the buffer data
  will not be modified by previous filters.

* AV_PERM_REUSE: the owner can output the buffer several times, without
  modifying the data in between.

* AV_PERM_REUSE2: the owner can output the buffer several times and
  modify the data in between (useless without the WRITE permissions).

* AV_PERM_ALIGN: the owner can access the data using fast operations
  that require data alignment.

The READ, WRITE and PRESERVE permissions are about sharing the same
buffer between several filters to avoid expensive copies without them
doing conflicting changes on the data.

The REUSE and REUSE2 permissions are about special memory for direct
rendering. For example a buffer directly allocated in video memory must
not modified once it is displayed on screen, or it will cause tearing;
it will therefore not have the REUSE2 permission.

The ALIGN permission is about extracting part of the buffer, for
copy-less padding or cropping for example.


References received on input pads are guaranteed to have all the
permissions stated in the min_perms field and none of the permissions
stated in the rej_perms.

References obtained by ff_get_video_buffer and ff_get_audio_buffer are
guaranteed to have at least all the permissions requested as argument.

References created by avfilter_ref_buffer have the same permissions as
the original reference minus the ones explicitly masked; the mask is
usually ~0 to keep the same permissions.

Filters should remove permissions on reference they give to output
whenever necessary. It can be automatically done by setting the
rej_perms field on the output pad.

Here are a few guidelines corresponding to common situations:

* Filters that modify and forward their frame (like drawtext) need the
  WRITE permission.

* Filters that read their input to produce a new frame on output (like
  scale) need the READ permission on input and must request a buffer
  with the WRITE permission.

* Filters that intend to keep a reference after the filtering process
  is finished (after filter_frame returns) must have the PRESERVE
  permission on it and remove the WRITE permission if they create a new
  reference to give it away.

* Filters that intend to modify a reference they have kept after the end
  of the filtering process need the REUSE2 permission and must remove
  the PRESERVE permission if they create a new reference to give it
  away.

Frame scheduling

The purpose of these rules is to ensure that frames flow in the filter
graph without getting stuck and accumulating somewhere.

Simple filters that output one frame for each input frame should not have
to worry about it.

filter_frame

text
This method is called when a frame is pushed to the filter's input. It
can be called at any time except in a reentrant way.

If the input frame is enough to produce output, then the filter should
push the output frames on the output link immediately.

As an exception to the previous rule, if the input frame is enough to
produce several output frames, then the filter needs output only at
least one per link. The additional frames can be left buffered in the
filter; these buffered frames must be flushed immediately if a new input
produces new output.

(Example: frame rate-doubling filter: filter_frame must (1) flush the
second copy of the previous frame, if it is still there, (2) push the
first copy of the incoming frame, (3) keep the second copy for later.)

If the input frame is not enough to produce output, the filter must not
call request_frame to get more. It must just process the frame or queue
it. The task of requesting more frames is left to the filter's
request_frame method or the application.

If a filter has several inputs, the filter must be ready for frames
arriving randomly on any input. Therefore, any filter with several inputs
will most likely require some kind of queuing mechanism. It is perfectly
acceptable to have a limited queue and to drop frames when the inputs
are too unbalanced.

request_frame

text
This method is called when a frame is wanted on an output.

For an input, it should directly call filter_frame on the corresponding
output.

For a filter, if there are queued frames already ready, one of these
frames should be pushed. If not, the filter should request a frame on
one of its inputs, repeatedly until at least one frame has been pushed.

Return values:
if request_frame could produce a frame, or at least make progress
towards producing a frame, it should return 0;
if it could not for temporary reasons, it should return AVERROR(EAGAIN);
if it could not because there are no more frames, it should return
AVERROR_EOF.

The typical implementation of request_frame for a filter with several
inputs will look like that:

    if (frames_queued) {
        push_one_frame();
        return 0;
    }
    input = input_where_a_frame_is_most_needed();
    ret = ff_request_frame(input);
    if (ret == AVERROR_EOF) {
        process_eof_on_input();
    } else if (ret < 0) {
        return ret;
    }
    return 0;

Note that, except for filters that can have queued frames, request_frame
does not push frames: it requests them to its input, and as a reaction,
the filter_frame method possibly will be called and do the work.

Legacy API

Until libavfilter 3.23, the filter_frame method was split:

  • for video filters, it was made of start_frame, draw_slice (that could be
    called several times on distinct parts of the frame) and end_frame;

  • for audio filters, it was called filter_samples.


Third Party Ffmpeg Doc Issue Tracker (`third_party/ffmpeg/doc/issue_tracker.txt`)

FFmpeg's bug/feature request tracker manual

Overview:

FFmpeg uses Trac for tracking issues, new issues and changes to
existing issues can be done through a web interface.

Issues can be different kinds of things we want to keep track of
but that do not belong into the source tree itself. This includes
bug reports, feature requests and license violations. We
might add more items to this list in the future, so feel free to
propose a new `type of issue' on the ffmpeg-devel mailing list if
you feel it is worth tracking.

It is possible to subscribe to individual issues by adding yourself to the
Cc list or to subscribe to the ffmpeg-trac mailing list which receives
a mail for every change to every issue.
(the above does all work already after light testing)

The subscription URL for the ffmpeg-trac list is:
https://lists.ffmpeg.org/mailman/listinfo/ffmpeg-trac
The URL of the webinterface of the tracker is:
https://trac.ffmpeg.org

Type:

art
Artwork such as photos, music, banners, and logos.

bug / defect
An error, flaw, mistake, failure, or fault in FFmpeg or libav* that
prevents it from behaving as intended.

feature request / enhancement
Request of support for encoding or decoding of a new codec, container
or variant.
Request of support for more, less or plain different output or behavior
where the current implementation cannot be considered wrong.

license violation
Ticket to keep track of (L)GPL violations of ffmpeg by others.

sponsoring request
Developer requests for hardware, software, specifications, money,
refunds, etc.

task
A task/reminder such as setting up a FATE client, adding filters to
Trac, etc.

Priority:

critical
Bugs about data loss and security issues.
No feature request can be critical.

important
Bugs which make FFmpeg unusable for a significant number of users.
Examples here might be completely broken MPEG-4 decoding or a build issue
on Linux.
While broken 4xm decoding or a broken OS/2 build would not be important,
the separation to normal is somewhat fuzzy.
For feature requests this priority would be used for things many people
want.
Regressions also should be marked as important, regressions are bugs that
don't exist in a past revision or another branch.

normal
Default setting. Use this if the bug does not match the other
priorities or if you are unsure of what priority to choose.

minor
Bugs about things like spelling errors, "mp2" instead of
"mp3" being shown and such.
Feature requests about things few people want or which do not make a big
difference.

wish
Something that is desirable to have but that there is no urgency at
all to implement, e.g. something completely cosmetic like a website
restyle or a personalized doxy template or the FFmpeg logo.
This priority is not valid for bugs.

Status:

new
initial state

open
intermediate states

closed
final state

Analyzed flag:

Bugs which have been analyzed and where it is understood what causes them
and which exact chain of events triggers them. This analysis should be
available as a message in the bug report.
Note, do not change the status to analyzed without also providing a clear
and understandable analysis.
This state implicates that the bug either has been reproduced or that
reproduction is not needed as the bug is already understood.

Type/Status:

*/new
Initial state of new bugs and feature requests submitted by
users.

*/open
Issues which have been briefly looked at and which did not look outright
invalid.
This implicates that no real more detailed state applies yet. Conversely,
the more detailed states below implicate that the issue has been briefly
looked at.

*/closed/duplicate
Bugs or feature requests which are duplicates.
Note, if you mark something as duplicate, do not forget setting the
superseder so bug reports are properly linked.

*/closed/invalid
Bugs caused by user errors, random ineligible or otherwise nonsense stuff.

*/closed/needs_more_info
Issues for which some information has been requested by the developers,
but which has not been provided by anyone within reasonable time.

bug/closed/fixed
Bugs which have to the best of our knowledge been fixed.

bug/closed/wontfix
Bugs which we will not fix. Possible reasons include legality, high
complexity for the sake of supporting obscure corner cases, speed loss
for similarly esoteric purposes, et cetera.
This also means that we would reject a patch.
If we are just too lazy to fix a bug then the correct state is open
and unassigned. Closed means that the case is closed which is not
the case if we are just waiting for a patch.

bug/closed/works_for_me
Bugs for which sufficient information was provided to reproduce but
reproduction failed - that is the code seems to work correctly to the
best of our knowledge.

feature_request/closed/fixed
Feature requests which have been implemented.

feature_request/closed/wontfix
Feature requests which will not be implemented. The reasons here could
be legal, philosophical or others.

Note2, if you provide the requested info do not forget to remove the
needs_more_info resolution.

Component:

avcodec
issues in libavcodec/*

avdevice
issues in libavdevice/*

avfilter
issues in libavfilter/*

avformat
issues in libavformat/*

avutil
issues in libavutil/*

build system
issues in or related to configure/Makefile

documentation
issues in or related to doc/*

ffmpeg
issues in or related to ffmpeg.c

ffplay
issues in or related to ffplay.c

ffprobe
issues in or related to ffprobe.c

ffserver
issues in or related to ffserver.c

postproc
issues in libpostproc/*

swresample
issues in libswresample/*

swscale
issues in libswscale/*

trac
issues related to our issue tracker

undetermined
default component; choose this if unsure

website
issues related to the website

wiki
issues related to the wiki


Third Party Ffmpeg Doc Mips (`third_party/ffmpeg/doc/mips.txt`)

MIPS optimizations info

MIPS optimizations of codecs are targeting MIPS 74k family of
CPUs. Some of these optimizations are relying more on properties of
this architecture and some are relying less (and can be used on most
MIPS architectures without degradation in performance).

Along with FFMPEG copyright notice, there is MIPS copyright notice in
all the files that are created by people from MIPS Technologies.

/*

  • Copyright (c) 2012
  • text
    MIPS Technologies, Inc., California.
  • Redistribution and use in source and binary forms, with or without
  • modification, are permitted provided that the following conditions
  • are met:
    1. Redistributions of source code must retain the above copyright
  • notice, this list of conditions and the following disclaimer.
    1. Redistributions in binary form must reproduce the above copyright
  • notice, this list of conditions and the following disclaimer in the
  • documentation and/or other materials provided with the distribution.
    1. Neither the name of the MIPS Technologies, Inc., nor the names of its
  • contributors may be used to endorse or promote products derived from
  • this software without specific prior written permission.
  • THIS SOFTWARE IS PROVIDED BY THE MIPS TECHNOLOGIES, INC. ``AS IS'' AND
  • ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  • IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  • ARE DISCLAIMED. IN NO EVENT SHALL THE MIPS TECHNOLOGIES, INC. BE LIABLE
  • FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  • DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  • OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  • HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  • LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  • OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  • SUCH DAMAGE.
  • Author: Author Name (author_name@@mips.com)
    */
  • libavutil/mips/
    float_dsp_mips.c
    libm_mips.h
    softfloat_tables.h
  • libavcodec/
    fft_fixed_32.c
    fft_init_table.c
    fft_table.h
    mdct_fixed_32.c
  • libavcodec/mips/
    aacdec_fixed.c
    aacsbr_fixed.c
    aacsbr_template.c
    aaccoder_mips.c
    aacpsy_mips.h
    ac3dsp_mips.c
    acelp_filters_mips.c
    acelp_vectors_mips.c
    amrwbdec_mips.c
    amrwbdec_mips.h
    celp_filters_mips.c
    celp_math_mips.c
    compute_antialias_fixed.h
    compute_antialias_float.h
    lsp_mips.h
    dsputil_mips.c
    fft_mips.c
    fft_table.h
    fft_init_table.c
    fmtconvert_mips.c
    iirfilter_mips.c
    mpegaudiodsp_mips_fixed.c
    mpegaudiodsp_mips_float.c

Third Party Ffmpeg Doc Multithreading (`third_party/ffmpeg/doc/multithreading.txt`)

FFmpeg multithreading methods

FFmpeg provides two methods for multithreading codecs.

Slice threading decodes multiple parts of a frame at the same time, using
AVCodecContext execute() and execute2().

Frame threading decodes multiple frames at the same time.
It accepts N future frames and delays decoded pictures by N-1 frames.
The later frames are decoded in separate threads while the user is
displaying the current one.

Restrictions on clients

Slice threading -

  • The client's draw_horiz_band() must be thread-safe according to the comment
    in avcodec.h.

Frame threading -

  • Restrictions with slice threading also apply.
  • For best performance, the client should set thread_safe_callbacks if it
    provides a thread-safe get_buffer() callback.
  • There is one frame of delay added for every thread beyond the first one.
    Clients must be able to handle this; the pkt_dts and pkt_pts fields in
    AVFrame will work as usual.

Restrictions on codec implementations

Slice threading -
None except that there must be something worth executing in parallel.

Frame threading -

  • Codecs can only accept entire pictures per packet.

  • Codecs similar to ffv1, whose streams don't reset across frames,
    will not work because their bitstreams cannot be decoded in parallel.

  • The contents of buffers must not be read before ff_thread_await_progress()
    has been called on them. reget_buffer() and buffer age optimizations no longer work.

  • The contents of buffers must not be written to after ff_thread_report_progress()
    has been called on them. This includes draw_edges().

Porting codecs to frame threading

Find all context variables that are needed by the next frame. Move all
code changing them, as well as code calling get_buffer(), up to before
the decode process starts. Call ff_thread_finish_setup() afterwards. If
some code can't be moved, have update_thread_context() run it in the next
thread.

If the codec allocates writable tables in its init(), add an init_thread_copy()
which re-allocates them for other threads.

Add AV_CODEC_CAP_FRAME_THREADS to the codec capabilities. There will be very little
speed gain at this point but it should work.

If there are inter-frame dependencies, so the codec calls
ff_thread_report/await_progress(), set AVCodecInternal.allocate_progress. The
frames must then be freed with ff_thread_release_buffer().
Otherwise leave it at zero and decode directly into the user-supplied frames.

Call ff_thread_report_progress() after some part of the current picture has decoded.
A good place to put this is where draw_horiz_band() is called - add this if it isn't
called anywhere, as it's useful too and the implementation is trivial when you're
doing this. Note that draw_edges() needs to be called before reporting progress.

Before accessing a reference frame or its MVs, call ff_thread_await_progress().


Third Party Ffmpeg Doc Optimization (`third_party/ffmpeg/doc/optimization.txt`)

optimization Tips (for libavcodec):

What to optimize:

If you plan to do non-x86 architecture specific optimizations (SIMD normally),
then take a look in the x86/ directory, as most important functions are
already optimized for MMX.

If you want to do x86 optimizations then you can either try to finetune the
stuff in the x86 directory or find some other functions in the C source to
optimize, but there aren't many left.

Understanding these overoptimized functions:

As many functions tend to be a bit difficult to understand because
of optimizations, it can be hard to optimize them further, or write
architecture-specific versions. It is recommended to look at older
revisions of the interesting files (web frontends for the various FFmpeg
branches are listed at http://ffmpeg.org/download.html).
Alternatively, look into the other architecture-specific versions in
the x86/, ppc/, alpha/ subdirectories. Even if you don't exactly
comprehend the instructions, it could help understanding the functions
and how they can be optimized.

NOTE: If you still don't understand some function, ask at our mailing list!!!
(http://lists.ffmpeg.org/mailman/listinfo/ffmpeg-devel)

When is an optimization justified?

Normally, clean and simple optimizations for widely used codecs are
justified even if they only achieve an overall speedup of 0.1%. These
speedups accumulate and can make a big difference after awhile. Also, if
none of the following factors get worse due to an optimization -- speed,
binary code size, source size, source readability -- and at least one
factor improves, then an optimization is always a good idea even if the
overall gain is less than 0.1%. For obscure codecs that are not often
used, the goal is more toward keeping the code clean, small, and
readable instead of making it 1% faster.

WTF is that function good for ....:

The primary purpose of this list is to avoid wasting time optimizing functions
which are rarely used.

put(_no_rnd)_pixels{,_x2,_y2,_xy2}
Used in motion compensation (en/decoding).

avg_pixels{,_x2,_y2,_xy2}
Used in motion compensation of B-frames.
These are less important than the put*pixels functions.

avg_no_rnd_pixels*
unused

pix_abs16x16{,_x2,_y2,_xy2}
Used in motion estimation (encoding) with SAD.

pix_abs8x8{,_x2,_y2,_xy2}
Used in motion estimation (encoding) with SAD of MPEG-4 4MV only.
These are less important than the pix_abs16x16* functions.

put_mspel8_mc* / wmv2_mspel8*
Used only in WMV2.
it is not recommended that you waste your time with these, as WMV2
is an ugly and relatively useless codec.

mpeg4_qpel* / qpel_mc
Used in MPEG-4 qpel motion compensation (encoding & decoding).
The qpel8 functions are used only for 4mv,
the avg_* functions are used only for B-frames.
Optimizing them should have a significant impact on qpel
encoding & decoding.

qpel{8,16}_mc??_old_c / *pixels{8,16}_l4
Just used to work around a bug in an old libavcodec encoder version.
Don't optimize them.

add_bytes/diff_bytes
For huffyuv only, optimize if you want a faster ffhuffyuv codec.

get_pixels / diff_pixels
Used for encoding, easy.

clear_blocks
easiest to optimize

gmc
Used for MPEG-4 gmc.
Optimizing this should have a significant effect on the gmc decoding
speed.

gmc1
Used for chroma blocks in MPEG-4 gmc with 1 warp point
(there are 4 luma & 2 chroma blocks per macroblock, so
only 1/3 of the gmc blocks use this, the other 2/3
use the normal put_pixel* code, but only if there is
just 1 warp point).
Note: DivX5 gmc always uses just 1 warp point.

pix_sum
Used for encoding.

hadamard8_diff / sse / sad == pix_norm1 / dct_sad / quant_psnr / rd / bit
Specific compare functions used in encoding, it depends upon the
command line switches which of these are used.
Don't waste your time with dct_sad & quant_psnr, they aren't
really useful.

put_pixels_clamped / add_pixels_clamped
Used for en/decoding in the IDCT, easy.
Note, some optimized IDCTs have the add/put clamped code included and
then put_pixels_clamped / add_pixels_clamped will be unused.

idct/fdct
idct (encoding & decoding)
fdct (encoding)
difficult to optimize

dct_quantize_trellis
Used for encoding with trellis quantization.
difficult to optimize

dct_quantize
Used for encoding.

dct_unquantize_mpeg1
Used in MPEG-1 en/decoding.

dct_unquantize_mpeg2
Used in MPEG-2 en/decoding.

dct_unquantize_h263
Used in MPEG-4/H.263 en/decoding.

Alignment:
Some instructions on some architectures have strict alignment restrictions,
for example most SSE/SSE2 instructions on x86.
The minimum guaranteed alignment is written in the .h files, for example:
void (*put_pixels_clamped)(const int16_t *block/align 16/, UINT8 *pixels/align 8/, int line_size);

General Tips:

Use asm loops like:
asm(
"1: ....
...
"jump_instruction ....
Do not use C loops:
do{
asm(
...
}while()

For x86, mark registers that are clobbered in your asm. This means both
general x86 registers (e.g. eax) as well as XMM registers. This last one is
particularly important on Win64, where xmm6-15 are callee-save, and not
restoring their contents leads to undefined results. In external asm (e.g.
yasm), you do this by using:
cglobal functon_name, num_args, num_regs, num_xmm_regs
In inline asm, you specify clobbered registers at the end of your asm:
asm(".." ::: "%eax").
If gcc is not set to support sse (-msse) it will not accept xmm registers
in the clobber list. For that we use two macros to declare the clobbers.
XMM_CLOBBERS should be used when there are other clobbers, for example:
asm(".." ::: XMM_CLOBBERS("xmm0",) "eax");
and XMM_CLOBBERS_ONLY should be used when the only clobbers are xmm registers:
asm(".." :: XMM_CLOBBERS_ONLY("xmm0"));

Do not expect a compiler to maintain values in your registers between separate
(inline) asm code blocks. It is not required to. For example, this is bad:
asm("movdqa %0, %%xmm7" : src);
/* do something */
asm("movdqa %%xmm7, %1" : dst);

  • first of all, you're assuming that the compiler will not use xmm7 in
    between the two asm blocks. It probably won't when you test it, but it's
    a poor assumption that will break at some point for some --cpu compiler flag
  • secondly, you didn't mark xmm7 as clobbered. If you did, the compiler would
    have restored the original value of xmm7 after the first asm block, thus
    rendering the combination of the two blocks of code invalid
    Code that depends on data in registries being untouched, should be written as
    a single asm() statement. Ideally, a single function contains only one
    asm() block.

Use external asm (nasm/yasm) or inline asm (asm()), do not use intrinsics.
The latter requires a good optimizing compiler which gcc is not.

When debugging a x86 external asm compilation issue, if lost in the macro
expansions, add DBG=1 to your make command-line: the input file will be
preprocessed, stripped of the debug/empty lines, then compiled, showing the
actual lines causing issues.

Inline asm vs. external asm

Both inline asm (asm("..") in a .c file, handled by a compiler such as gcc)
and external asm (.s or .asm files, handled by an assembler such as yasm/nasm)
are accepted in FFmpeg. Which one to use differs per specific case.

  • if your code is intended to be inlined in a C function, inline asm is always
    better, because external asm cannot be inlined
  • if your code calls external functions, yasm is always better
  • if your code takes huge and complex structs as function arguments (e.g.
    MpegEncContext; note that this is not ideal and is discouraged if there
    are alternatives), then inline asm is always better, because predicting
    member offsets in complex structs is almost impossible. It's safest to let
    the compiler take care of that
  • in many cases, both can be used and it just depends on the preference of the
    person writing the asm. For new asm, the choice is up to you. For existing
    asm, you'll likely want to maintain whatever form it is currently in unless
    there is a good reason to change it.
  • if, for some reason, you believe that a particular chunk of existing external
    asm could be improved upon further if written in inline asm (or the other
    way around), then please make the move from external asm <-> inline asm a
    separate patch before your patches that actually improve the asm.

http://www.aggregate.org/MAGIC/

x86-specific:

http://developer.intel.com/design/pentium4/manuals/248966.htm

The IA-32 Intel Architecture Software Developer's Manual, Volume 2:
Instruction Set Reference
http://developer.intel.com/design/pentium4/manuals/245471.htm

http://www.agner.org/assem/

AMD Athlon Processor x86 Code Optimization Guide:
http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/22007.pdf

ARM-specific:

ARM Architecture Reference Manual (up to ARMv5TE):
http://www.arm.com/community/university/eulaarmarm.html

Procedure Call Standard for the ARM Architecture:
http://www.arm.com/pdfs/aapcs.pdf

Optimization guide for ARM9E (used in Nokia 770 Internet Tablet):
http://infocenter.arm.com/help/topic/com.arm.doc.ddi0240b/DDI0240A.pdf
Optimization guide for ARM11 (used in Nokia N800 Internet Tablet):
http://infocenter.arm.com/help/topic/com.arm.doc.ddi0211j/DDI0211J_arm1136_r1p5_trm.pdf
Optimization guide for Intel XScale (used in Sharp Zaurus PDA):
http://download.intel.com/design/intelxscale/27347302.pdf
Intel Wireless MMX 2 Coprocessor: Programmers Reference Manual
http://download.intel.com/design/intelxscale/31451001.pdf

PowerPC-specific:

PowerPC32/AltiVec PIM:
www.freescale.com/files/32bit/doc/ref_manual/ALTIVECPEM.pdf

PowerPC32/AltiVec PEM:
www.freescale.com/files/32bit/doc/ref_manual/ALTIVECPIM.pdf

CELL/SPU:
http://www-01.ibm.com/chips/techlib/techlib.nsf/techdocs/30B3520C93F437AB87257060006FFE5E/$file/Language_Extensions_for_CBEA_2.4.pdf
http://www-01.ibm.com/chips/techlib/techlib.nsf/techdocs/9F820A5FFA3ECE8C8725716A0062585F/$file/CBE_Handbook_v1.1_24APR2007_pub.pdf

official doc but quite ugly
http://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html

a bit old (note "+" is valid for input-output, even though the next disagrees)
http://www.cs.virginia.edu/~clc5q/gcc-inline-asm.pdf


Third Party Ffmpeg Doc Rate Distortion (`third_party/ffmpeg/doc/rate_distortion.txt`)

A Quick Description Of Rate Distortion Theory.

We want to encode a video, picture or piece of music optimally. What does
"optimally" really mean? It means that we want to get the best quality at a
given filesize OR we want to get the smallest filesize at a given quality
(in practice, these 2 goals are usually the same).

Solving this directly is not practical; trying all byte sequences 1
megabyte in length and selecting the "best looking" sequence will yield
256^1000000 cases to try.

But first, a word about quality, which is also called distortion.
Distortion can be quantified by almost any quality measurement one chooses.
Commonly, the sum of squared differences is used but more complex methods
that consider psychovisual effects can be used as well. It makes no
difference in this discussion.

First step: that rate distortion factor called lambda...
Let's consider the problem of minimizing:

distortion + lambda*rate

rate is the filesize
distortion is the quality
lambda is a fixed value chosen as a tradeoff between quality and filesize
Is this equivalent to finding the best quality for a given max
filesize? The answer is yes. For each filesize limit there is some lambda
factor for which minimizing above will get you the best quality (using your
chosen quality measurement) at the desired (or lower) filesize.

Second step: splitting the problem.
Directly splitting the problem of finding the best quality at a given
filesize is hard because we do not know how many bits from the total
filesize should be allocated to each of the subproblems. But the formula
from above:

distortion + lambda*rate

can be trivially split. Consider:

(distortion0 + distortion1) + lambda*(rate0 + rate1)

This creates a problem made of 2 independent subproblems. The subproblems
might be 2 16x16 macroblocks in a frame of 32x16 size. To minimize:

(distortion0 + distortion1) + lambda*(rate0 + rate1)

we just have to minimize:

distortion0 + lambda*rate0

and

distortion1 + lambda*rate1

I.e, the 2 problems can be solved independently.

Author: Michael Niedermayer
Copyright: LGPL


Third Party Ffmpeg Doc Snow (`third_party/ffmpeg/doc/snow.txt`)

============================================= Snow Video Codec Specification Draft 20080110

Introduction:

This specification describes the Snow bitstream syntax and semantics as
well as the formal Snow decoding process.

The decoding process is described precisely and any compliant decoder
MUST produce the exact same output for a spec-conformant Snow stream.
For encoding, though, any process which generates a stream compliant to
the syntactical and semantic requirements and which is decodable by
the process described in this spec shall be considered a conformant
Snow encoder.

Definitions:

MUST the specific part must be done to conform to this standard
SHOULD it is recommended to be done that way, but not strictly required

ilog2(x) is the rounded down logarithm of x with basis 2
ilog2(0) = 0

Type definitions:

b 1-bit range coded
u unsigned scalar value range coded
s signed scalar value range coded

Bitstream syntax:

frame:
header
prediction
residual

header:
keyframe b MID_STATE
if(keyframe || always_reset)
reset_contexts
if(keyframe){
version u header_state
always_reset b header_state
temporal_decomposition_type u header_state
temporal_decomposition_count u header_state
spatial_decomposition_count u header_state
colorspace_type u header_state
if (nb_planes > 2) {
chroma_h_shift u header_state
chroma_v_shift u header_state
}
spatial_scalability b header_state
max_ref_frames-1 u header_state
qlogs
}
if(!keyframe){
update_mc b header_state
if(update_mc){
for(plane=0; plane<nb_plane_types; plane++){
diag_mc b header_state
htaps/2-1 u header_state
for(i= p->htaps/2; i; i--)
|hcoeff[i]| u header_state
}
}
update_qlogs b header_state
if(update_qlogs){
spatial_decomposition_count u header_state
qlogs
}
}

text
spatial_decomposition_type          s   header_state
qlog                                s   header_state
mv_scale                            s   header_state
qbias                               s   header_state
block_max_depth                     s   header_state

qlogs:
for(plane=0; plane<nb_plane_types; plane++){
quant_table[plane][0][0] s header_state
for(level=0; level < spatial_decomposition_count; level++){
quant_table[plane][level][1]s header_state
quant_table[plane][level][3]s header_state
}
}

reset_contexts
_state[]= MID_STATE

prediction:
for(y=0; ylevel + 2top->level + topleft->level + topright->level
leaf b block_state[4 + s_context]
}
if(level==max_block_depth || leaf){
intra b block_state[1 + left->intra + top->intra]
if(intra){
y_diff s block_state[32]
cb_diff s block_state[64]
cr_diff s block_state[96]
}else{
ref_context= ilog2(2
left->ref) + ilog2(2top->ref)
if(ref_frames > 1)
ref u block_state[128 + 1024 + 32
ref_context]
mx_context= ilog2(2abs(left->mx - top->mx))
my_context= ilog2(2
abs(left->my - top->my))
mvx_diff s block_state[128 + 32*(mx_context + 16*!!ref)]
mvy_diff s block_state[128 + 32*(my_context + 16*!!ref)]
}
}else{
block(level+1)
block(level+1)
block(level+1)
block(level+1)
}
}

residual:
residual2(luma)
if (nb_planes > 2) {
residual2(chroma_cr)
residual2(chroma_cb)
}

residual2:
for(level=0; level<spatial_decomposition_count; level++){
if(level==0)
subband(LL, 0)
subband(HL, level)
subband(LH, level)
subband(HH, level)
}

subband:
FIXME

nb_plane_types = gray ? 1 : 2;

Tag description:

version
0
this MUST NOT change within a bitstream

always_reset
if 1 then the range coder contexts will be reset after each frame

temporal_decomposition_type
0

temporal_decomposition_count
0

spatial_decomposition_count
FIXME

colorspace_type
0 unspecified YcbCr
1 Gray
2 Gray + Alpha
3 GBR
4 GBRA
this MUST NOT change within a bitstream

chroma_h_shift
log2(luma.width / chroma.width)
this MUST NOT change within a bitstream

chroma_v_shift
log2(luma.height / chroma.height)
this MUST NOT change within a bitstream

spatial_scalability
0

max_ref_frames
maximum number of reference frames
this MUST NOT change within a bitstream

update_mc
indicates that motion compensation filter parameters are stored in the
header

diag_mc
flag to enable faster diagonal interpolation
this SHOULD be 1 unless it turns out to be covered by a valid patent

htaps
number of half pel interpolation filter taps, MUST be even, >0 and <10

hcoeff
half pel interpolation filter coefficients, hcoeff[0] are the 2 middle
coefficients [1] are the next outer ones and so on, resulting in a filter
like: ...eff[2], hcoeff[1], hcoeff[0], hcoeff[0], hcoeff[1], hcoeff[2] ...
the sign of the coefficients is not explicitly stored but alternates
after each coeff and coeff[0] is positive, so ...,+,-,+,-,+,+,-,+,-,+,...
hcoeff[0] is not explicitly stored but found by subtracting the sum
of all stored coefficients with signs from 32
hcoeff[0]= 32 - hcoeff[1] - hcoeff[2] - ...
a good choice for hcoeff and htaps is
htaps= 6
hcoeff={40,-10,2}
an alternative which requires more computations at both encoder and
decoder side and may or may not be better is
htaps= 8
hcoeff={42,-14,6,-2}

ref_frames
minimum of the number of available reference frames and max_ref_frames
for example the first frame after a key frame always has ref_frames=1

spatial_decomposition_type
wavelet type
0 is a 9/7 symmetric compact integer wavelet
1 is a 5/3 symmetric compact integer wavelet
others are reserved
stored as delta from last, last is reset to 0 if always_reset || keyframe

qlog
quality (logarthmic quantizer scale)
stored as delta from last, last is reset to 0 if always_reset || keyframe

mv_scale
stored as delta from last, last is reset to 0 if always_reset || keyframe
FIXME check that everything works fine if this changes between frames

qbias
dequantization bias
stored as delta from last, last is reset to 0 if always_reset || keyframe

block_max_depth
maximum depth of the block tree
stored as delta from last, last is reset to 0 if always_reset || keyframe

quant_table
quantiztation table

Highlevel bitstream structure:


| ------------------------------------ |
| | Block0 | |
| | split? | |
| | yes no | |
| | ......... intra? | |
| | : Block01 : yes no | |
| | : Block02 : ....... .......... | |
| | : Block03 : : y DC : : ref index: | |
| | : Block04 : : cb DC : : motion x : | |
| | ......... : cr DC : : motion y : | |

| | ....... .......... | |

------------------------------------
...

| ------------ ------------ ------------ |
|| Y subbands | | Cb subbands| | Cr subbands||
|| --- --- | | --- --- | | --- --- ||
|| |LL0||HL0| | | |LL0||HL0| | | |LL0||HL0| ||
|| --- --- | | --- --- | | --- --- ||
|| --- --- | | --- --- | | --- --- ||
|| |LH0||HH0| | | |LH0||HH0| | | |LH0||HH0| ||
|| --- --- | | --- --- | | --- --- ||
|| --- --- | | --- --- | | --- --- ||
|| |HL1||LH1| | | |HL1||LH1| | | |HL1||LH1| ||
|| --- --- | | --- --- | | --- --- ||
|| --- --- | | --- --- | | --- --- ||
|| |HH1||HL2| | | |HH1||HL2| | | |HH1||HL2| ||
|| ... | | ... | | ... ||

| ------------ ------------ ------------ |


Decoding process:

text
------------
                                    |            |
                                    |  Subbands  |
               ------------         |            |
              |            |         ------------
              |  Intra DC  |               |
              |            |    LL0 subband prediction
               ------------                |
                            \        Dequantizaton

------------------- \ |
| Reference frames | \ IDWT
| ------- ------- | Motion \ |
||Frame 0| |Frame 1|| Compensation . OBMC v -------
| ------- ------- | --------------. ------> + --->|Frame n|-->output
| ------- ------- | -------
||Frame 2| |Frame 3||<----------------------------------/

| ... |

Range Coder:

Binary Range Coder:

The implemented range coder is an adapted version based upon "Range encoding:
an algorithm for removing redundancy from a digitised message." by G. N. N.
Martin.
The symbols encoded by the Snow range coder are bits (0|1). The
associated probabilities are not fix but change depending on the symbol mix
seen so far.

bit seen | new state
---------+-----------------------------------------------
0 | 256 - state_transition_table[256 - old_state];
1 | state_transition_table[ old_state];

state_transition_table = {
0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 190, 191, 192, 194, 194,
195, 196, 197, 198, 199, 200, 201, 202, 202, 204, 205, 206, 207, 208, 209, 209,
210, 211, 212, 213, 215, 215, 216, 217, 218, 219, 220, 220, 222, 223, 224, 225,
226, 227, 227, 229, 229, 230, 231, 232, 234, 234, 235, 236, 237, 238, 239, 240,
241, 242, 243, 244, 245, 246, 247, 248, 248, 0, 0, 0, 0, 0, 0, 0};

FIXME

Range Coding of integers:

FIXME

Neighboring Blocks:

left and top are set to the respective blocks unless they are outside of
the image in which case they are set to the Null block

top-left is set to the top left block unless it is outside of the image in
which case it is set to the left block

if this block has no larger parent block or it is at the left side of its
parent block and the top right block is not outside of the image then the
top right block is used for top-right else the top-left block is used

Null block
y,cb,cr are 128
level, ref, mx and my are 0

Motion Vector Prediction:

  1. the motion vectors of all the neighboring blocks are scaled to
    compensate for the difference of reference frames

scaled_mv= (mv * (256 * (current_reference+1) / (mv.reference+1)) + 128)>>8

  1. the median of the scaled left, top and top-right vectors is used as
    motion vector prediction

  2. the used motion vector is the sum of the predictor and
    (mvx_diff, mvy_diff)*mv_scale

Intra DC Predicton:

the luma and chroma values of the left block are used as predictors

the used luma and chroma is the sum of the predictor and y_diff, cb_diff, cr_diff
to reverse this in the decoder apply the following:
block[y][x].dc[0] = block[y][x-1].dc[0] + y_diff;
block[y][x].dc[1] = block[y][x-1].dc[1] + cb_diff;
block[y][x].dc[2] = block[y][x-1].dc[2] + cr_diff;
block[][-1].dc[]= 128;

Motion Compensation:

Halfpel interpolation:

halfpel interpolation is done by convolution with the halfpel filter stored
in the header:

horizontal halfpel samples are found by
H1[y][x] = hcoeff[0](F[y][x ] + F[y][x+1])
+ hcoeff[1]
(F[y][x-1] + F[y][x+2])
+ hcoeff[2]*(F[y][x-2] + F[y][x+3])
+ ...
h1[y][x] = (H1[y][x] + 32)>>6;

vertical halfpel samples are found by
H2[y][x] = hcoeff[0](F[y ][x] + F[y+1][x])
+ hcoeff[1]
(F[y-1][x] + F[y+2][x])
+ ...
h2[y][x] = (H2[y][x] + 32)>>6;

vertical+horizontal halfpel samples are found by
H3[y][x] = hcoeff[0](H2[y][x ] + H2[y][x+1])
+ hcoeff[1]
(H2[y][x-1] + H2[y][x+2])
+ ...
H3[y][x] = hcoeff[0](H1[y ][x] + H1[y+1][x])
+ hcoeff[1]
(H1[y+1][x] + H1[y+2][x])
+ ...
h3[y][x] = (H3[y][x] + 2048)>>12;

text
F   H1  F
               |   |   |
               |   |   |
               |   |   |
               F   H1  F
               |   |   |
               |   |   |
               |   |   |

F-------F-------F-> H1<-F-------F-------F
v v v
H2 H3 H2
^ ^ ^
F-------F-------F-> H1<-F-------F-------F
| | |
| | |
| | |
F H1 F
| | |
| | |
| | |
F H1 F

unavailable fullpel samples (outside the picture for example) shall be equal
to the closest available fullpel sample

Smaller pel interpolation:

if diag_mc is set then points which lie on a line between 2 vertically,
horiziontally or diagonally adjacent halfpel points shall be interpolated
linearls with rounding to nearest and halfway values rounded up.
points which lie on 2 diagonals at the same time should only use the one
diagonal not containing the fullpel point

text
F-->O---q---O<--h1->O---q---O<--F
       v \           / v \           / v
       O   O       O   O   O       O   O
       |         /     |     \         |
       q       q       q       q       q
       |     /         |         \     |
       O   O       O   O   O       O   O
       ^ /           \ ^ /           \ ^
      h2-->O---q---O<--h3->O---q---O<--h2
       v \           / v \           / v
       O   O       O   O   O       O   O
       |     \         |         /     |
       q       q       q       q       q
       |         \     |     /         |
       O   O       O   O   O       O   O
       ^ /           \ ^ /           \ ^
       F-->O---q---O<--h1->O---q---O<--F

the remaining points shall be bilinearly interpolated from the
up to 4 surrounding halfpel and fullpel points, again rounding should be to
nearest and halfway values rounded up

compliant Snow decoders MUST support 1-1/8 pel luma and 1/2-1/16 pel chroma
interpolation at least

Overlapped block motion compensation:

FIXME

LL band prediction:

Each sample in the LL0 subband is predicted by the median of the left, top and
left+top-topleft samples, samples outside the subband shall be considered to
be 0. To reverse this prediction in the decoder apply the following.
for(y=0; y<height; y++){
for(x=0; x<width; x++){
sample[y][x] += median(sample[y-1][x],
sample[y][x-1],
sample[y-1][x]+sample[y][x-1]-sample[y-1][x-1]);
}
}
sample[-1][]=sample[][-1]= 0;
width,height here are the width and height of the LL0 subband not of the final
video

Dequantizaton:

FIXME

Wavelet Transform:

Snow supports 2 wavelet transforms, the symmetric biorthogonal 5/3 integer
transform and a integer approximation of the symmetric biorthogonal 9/7
daubechies wavelet.

2D IDWT (inverse discrete wavelet transform)

The 2D IDWT applies a 2D filter recursively, each time combining the
4 lowest frequency subbands into a single subband until only 1 subband
remains.
The 2D filter is done by first applying a 1D filter in the vertical direction
and then applying it in the horizontal one.


|LL0|HL0| | | | | | | | | | | |
|---+---| HL1 | | L0|H0 | HL1 | | LL1 | HL1 | | | |
|LH0|HH0| | | | | | | | | | | |
|-------+-------|->|-------+-------|->|-------+-------|->| L1 | H1 |->...
| | | | | | | | | | | |
| LH1 | HH1 | | LH1 | HH1 | | LH1 | HH1 | | | |
| | | | | | | | | | | |


1D Filter:

  1. interleave the samples of the low and high frequency subbands like
    s={L0, H0, L1, H1, L2, H2, L3, H3, ... }
    note, this can end with a L or a H, the number of elements shall be w
    s[-1] shall be considered equivalent to s[1 ]
    s[w ] shall be considered equivalent to s[w-2]

  2. perform the lifting steps in order as described below

5/3 Integer filter:

  1. s[i] -= (s[i-1] + s[i+1] + 2)>>2; for all even i < w
  2. s[i] += (s[i-1] + s[i+1] )>>1; for all odd i < w

\ | /|\ | /|\ | /|\ | /|
|/ | |/ | |/ | |/ |

  • | + | + | + | -1/4
    /|\ | /|\ | /|\ | /|\ |
    / | |/ | |/ | |/ | |/
    | + | + | + | + +1/2

Snow's 9/7 Integer filter:

  1. s[i] -= (3*(s[i-1] + s[i+1]) + 4)>>3; for all even i < w
  2. s[i] -= s[i-1] + s[i+1] ; for all odd i < w
  3. s[i] += ( s[i-1] + s[i+1] + 4*s[i] + 8)>>4; for all even i < w
  4. s[i] += (3*(s[i-1] + s[i+1]) )>>1; for all odd i < w

\ | /|\ | /|\ | /|\ | /|
|/ | |/ | |/ | |/ |

  • | + | + | + | -3/8
    /|\ | /|\ | /|\ | /|\ |
    / | |/ | |/ | |/ | |/
    (| + (| + (| + (| + -1
    \ + /|\ + /|\ + /|\ + /|\ +1/4
    |/ | |/ | |/ | |/ |
  • | + | + | + | +1/16
    /|\ | /|\ | /|\ | /|\ |
    / | |/ | |/ | |/ | |/
    | + | + | + | + +3/2

optimization tips:
following are exactly identical
(3a)>>1 == a + (a>>1)
(a + 4b + 8)>>4 == ((a>>2) + b + 2)>>2

16bit implementation note:
The IDWT can be implemented with 16bits, but this requires some care to
prevent overflows, the following list, lists the minimum number of bits needed
for some terms

  1. lifting step
    A= s[i-1] + s[i+1] 16bit
    3*A + 4 18bit
    A + (A>>1) + 2 17bit

  2. lifting step
    s[i-1] + s[i+1] 17bit

  3. lifiting step
    3*(s[i-1] + s[i+1]) 17bit

TODO:

Important:
finetune initial contexts
flip wavelet?
try to use the wavelet transformed predicted image (motion compensated image) as context for coding the residual coefficients
try the MV length as context for coding the residual coefficients
use extradata for stuff which is in the keyframes now?
implement per picture halfpel interpolation
try different range coder state transition tables for different contexts

Not Important:
compare the 6 tap and 8 tap hpel filters (psnr/bitrate and subjective quality)
spatial_scalability b vs u (!= 0 breaks syntax anyway so we can add a u later)

Credits:

Michael Niedermayer
Loren Merritt

GPL + GFDL + whatever is needed to make this a RFC


Third Party Ffmpeg Doc Swresample (`third_party/ffmpeg/doc/swresample.txt`)

The official guide to swresample for confused developers.

Current (simplified) Architecture:

text
Input
                      v
   __________________/|\___________
  /                   |            \
 /    input sample format convert   v
/                     | ___________/
|                     |/
|                     v
|         ___________/|\___________              _____________
|        /            |            \            |             |
|   Rematrix          |          resample <---->|   Buffers   |
|        \___________ | ___________/            |_____________|
v                    \|/

Special Converter v
v /|_ _____________
| / | \ | |
| Rematrix | resample <---->| Buffers |
| _
_________ | / ||
| |/
| v
| |_
_______
\ |
\ output sample format convert v
______________
__ | ___________/
|/
v
Output

Planar/Packed conversion is done when needed during sample format conversion.
Every step can be skipped without memcpy when it is not needed.
Either Resampling and Rematrixing can be performed first depending on which
way it is faster.
The Buffers are needed for resampling due to resamplng being a process that
requires future and past data, it thus also introduces inevitably a delay when
used.
Internally 32bit float and 16bit int is supported currently, other formats can
easily be added.
Externally all sample formats in packed and planar configuration are supported
It's also trivial to add special converters for common cases.
If only sample format and/or packed/planar conversion is needed, it
is performed from input to output directly in a single pass with no intermediates.


Third Party Ffmpeg Doc Swscale (`third_party/ffmpeg/doc/swscale.txt`)

The official guide to swscale for confused developers.

Current (simplified) Architecture:

text
Input
                      v
               _______OR_________
             /                   \
           /                       \
   special converter     [Input to YUV converter]
          |                         |
          |          (8bit YUV 4:4:4 / 4:2:2 / 4:2:0 / 4:0:0 )
          |                         |
          |                         v
          |                  Horizontal scaler
          |                         |
          |      (15bit YUV 4:4:4 / 4:2:2 / 4:2:0 / 4:1:1 / 4:0:0 )
          |                         |
          |                         v
          |          Vertical scaler and output converter
          |                         |
          v                         v
                     output

Swscale has 2 scaler paths. Each side must be capable of handling
slices, that is, consecutive non-overlapping rectangles of dimension
(0,slice_top) - (picture_width, slice_bottom).

special converter
These generally are unscaled converters of common
formats, like YUV 4:2:0/4:2:2 -> RGB12/15/16/24/32. Though it could also
in principle contain scalers optimized for specific common cases.

Main path
The main path is used when no special converter can be used. The code
is designed as a destination line pull architecture. That is, for each
output line the vertical scaler pulls lines from a ring buffer. When
the ring buffer does not contain the wanted line, then it is pulled from
the input slice through the input converter and horizontal scaler.
The result is also stored in the ring buffer to serve future vertical
scaler requests.
When no more output can be generated because lines from a future slice
would be needed, then all remaining lines in the current slice are
converted, horizontally scaled and put in the ring buffer.
[This is done for luma and chroma, each with possibly different numbers
of lines per picture.]

Input to YUV Converter
When the input to the main path is not planar 8 bits per component YUV or
8-bit gray, it is converted to planar 8-bit YUV. Two sets of converters
exist for this currently: One performs horizontal downscaling by 2
before the conversion, the other leaves the full chroma resolution,
but is slightly slower. The scaler will try to preserve full chroma
when the output uses it. It is possible to force full chroma with
SWS_FULL_CHR_H_INP even for cases where the scaler thinks it is useless.

Horizontal scaler
There are several horizontal scalers. A special case worth mentioning is
the fast bilinear scaler that is made of runtime-generated MMXEXT code
using specially tuned pshufw instructions.
The remaining scalers are specially-tuned for various filter lengths.
They scale 8-bit unsigned planar data to 16-bit signed planar data.
Future >8 bits per component inputs will need to add a new horizontal
scaler that preserves the input precision.

Vertical scaler and output converter
There is a large number of combined vertical scalers + output converters.
Some are:
* unscaled output converters
* unscaled output converters that average 2 chroma lines
* bilinear converters (C, MMX and accurate MMX)
* arbitrary filter length converters (C, MMX and accurate MMX)
And
* Plain C 8-bit 4:2:2 YUV -> RGB converters using LUTs
* Plain C 17-bit 4:4:4 YUV -> RGB converters using multiplies
* MMX 11-bit 4:2:2 YUV -> RGB converters
* Plain C 16-bit Y -> 16-bit gray
...

text
RGB with less than 8 bits per component uses dither to improve the
subjective quality and low-frequency accuracy.

Filter coefficients:

There are several different scalers (bilinear, bicubic, lanczos, area,
sinc, ...). Their coefficients are calculated in initFilter().
Horizontal filter coefficients have a 1.0 point at 1 << 14, vertical ones at
1 << 12. The 1.0 points have been chosen to maximize precision while leaving
a little headroom for convolutional filters like sharpening filters and
minimizing SIMD instructions needed to apply them.
It would be trivial to use a different 1.0 point if some specific scaler
would benefit from it.
Also, as already hinted at, initFilter() accepts an optional convolutional
filter as input that can be used for contrast, saturation, blur, sharpening
shift, chroma vs. luma shift, ...


Third Party Ffmpeg Doc Tablegen (`third_party/ffmpeg/doc/tablegen.txt`)

Writing a table generator

This documentation is preliminary.
Parts of the API are not good and should be changed.

Basic concepts

A table generator consists of two files, *_tablegen.c and *_tablegen.h.
The .h file will provide the variable declarations and initialization
code for the tables, the .c calls the initialization code and then prints
the tables as a header file using the tableprint.h helpers.
Both of these files will be compiled for the host system, so to avoid
breakage with cross-compilation neither of them may include, directly
or indirectly, config.h or avconfig.h.
This means that e.g. libavutil/mathematics.h is ok but libavutil/libm.h is not.
Due to this, the .c file or Makefile may have to provide additional defines
or stubs, though if possible this should be avoided.
In particular, CONFIG_HARDCODED_TABLES should always be defined to 0.

The .c file

This file should include the *_tablegen.h and tableprint.h files and
anything else it needs as long as it does not depend on config.h or
avconfig.h.
In addition to that it must contain a main() function which initializes
all tables by calling the init functions from the .h file and then prints
them.
The printing code typically looks like this:
write_fileheader();
printf("static const uint8_t my_array[100] = {\n");
write_uint8_t_array(my_array, 100);
printf("};\n");

This is the more generic form, in case you need to do something special.
Usually you should instead use the short form:
write_fileheader();
WRITE_ARRAY("static const", uint8_t, my_array);

write_fileheader() adds some minor things like a "this is a generated file"
comment and some standard includes.
tablegen.h defines some write functions for one- and two-dimensional arrays
for standard types - they print only the "core" parts so they are easier
to reuse for multi-dimensional arrays so the outermost {} must be printed
separately.
If there's no standard function for printing the type you need, the
WRITE_1D_FUNC_ARGV macro is a very quick way to create one.
See libavcodec/dv_tablegen.c for an example.

The .h file

This file should contain:

  • one or more initialization functions
  • the table variable declarations
    If CONFIG_HARDCODED_TABLES is set, the initialization functions should
    not do anything, and instead of the variable declarations the
    generated *_tables.h file should be included.
    Since that will be generated in the build directory, the path must be
    included, i.e.

#include "libavcodec/example_tables.h"
not
#include "example_tables.h"

Makefile changes

To make the automatic table creation work, you must manually declare the
new dependency.
For this add a line similar to this:
$(SUBDIR)example.o: $(SUBDIR)example_tables.h
under the "ifdef CONFIG_HARDCODED_TABLES" section in the Makefile.


Third Party Ffmpeg Doc Writing Filters (`third_party/ffmpeg/doc/writing_filters.txt`)

This document is a tutorial/initiation for writing simple filters in
libavfilter.

Foreword: just like everything else in FFmpeg, libavfilter is monolithic, which
means that it is highly recommended that you submit your filters to the FFmpeg
development mailing-list and make sure that they are applied. Otherwise, your filters
are likely to have a very short lifetime due to more or less regular internal API
changes, and a limited distribution, review, and testing.

Bootstrap

Let's say you want to write a new simple video filter called "foobar" which
takes one frame in input, changes the pixels in whatever fashion you fancy, and
outputs the modified frame. The most simple way of doing this is to take a
similar filter. We'll pick edgedetect, but any other should do. You can look
for others using the ./ffmpeg -v 0 -filters|grep ' V->V ' command.

  • sed 's/edgedetect/foobar/g;s/EdgeDetect/Foobar/g' libavfilter/vf_edgedetect.c > libavfilter/vf_foobar.c
  • edit libavfilter/Makefile, and add an entry for "foobar" following the
    pattern of the other filters.
  • edit libavfilter/allfilters.c, and add an entry for "foobar" following the
    pattern of the other filters.
  • ./configure ...
  • make -j ffmpeg
  • ./ffmpeg -i http://samples.ffmpeg.org/image-samples/lena.pnm -vf foobar foobar.png
    Note here: you can obviously use a random local image instead of a remote URL.

If everything went right, you should get a foobar.png with Lena edge-detected.

That's it, your new playground is ready.

Some little details about what's going on:
libavfilter/allfilters.c:avfilter_register_all() is called at runtime to create
a list of the available filters, but it's important to know that this file is
also parsed by the configure script, which in turn will define variables for
the build system and the C:

text
--- after running configure ---

$ grep FOOBAR config.mak
CONFIG_FOOBAR_FILTER=yes
$ grep FOOBAR config.h
#define CONFIG_FOOBAR_FILTER 1

CONFIG_FOOBAR_FILTER=yes from the config.mak is later used to enable the filter in
libavfilter/Makefile and CONFIG_FOOBAR_FILTER=1 from the config.h will be used
for registering the filter in libavfilter/allfilters.c.

Filter code layout

You now need some theory about the general code layout of a filter. Open your
libavfilter/vf_foobar.c. This section will detail the important parts of the
code you need to understand before messing with it.

First chunk is the copyright. Most filters are LGPL, and we are assuming
vf_foobar is as well. We are also assuming vf_foobar is not an edge detector
filter, so you can update the boilerplate with your credits.

Doxy

Next chunk is the Doxygen about the file. See https://ffmpeg.org/doxygen/trunk/.
Detail here what the filter is, does, and add some references if you feel like
it.

Context

Skip the headers and scroll down to the definition of FoobarContext. This is
your local state context. It is already filled with 0 when you get it so do not
worry about uninitialized reads into this context. This is where you put all
"global" information that you need; typically the variables storing the user options.
You'll notice the first field "const AVClass *class"; it's the only field you
need to keep assuming you have a context. There is some magic you don't need to
care about around this field, just let it be (in the first position) for now.

Options

Then comes the options array. This is what will define the user accessible
options. For example, -vf foobar=mode=colormix:high=0.4:low=0.1. Most options
have the following pattern:
name, description, offset, type, default value, minimum value, maximum value, flags

  • name is the option name, keep it simple and lowercase
  • description are short, in lowercase, without period, and describe what they
    do, for example "set the foo of the bar"
  • offset is the offset of the field in your local context, see the OFFSET()
    macro; the option parser will use that information to fill the fields
    according to the user input
  • type is any of AV_OPT_TYPE_* defined in libavutil/opt.h
  • default value is an union where you pick the appropriate type; "{.dbl=0.3}",
    "{.i64=0x234}", "{.str=NULL}", ...
  • min and max values define the range of available values, inclusive
  • flags are AVOption generic flags. See AV_OPT_FLAG_* definitions

When in doubt, just look at the other AVOption definitions all around the codebase,
there are tons of examples.

Class

AVFILTER_DEFINE_CLASS(foobar) will define a unique foobar_class with some kind
of signature referencing the options, etc. which will be referenced in the
definition of the AVFilter.

Filter definition

At the end of the file, you will find foobar_inputs, foobar_outputs and
the AVFilter ff_vf_foobar. Don't forget to update the AVFilter.description with
a description of what the filter does, starting with a capitalized letter and
ending with a period. You'd better drop the AVFilter.flags entry for now, and
re-add them later depending on the capabilities of your filter.

Callbacks

Let's now study the common callbacks. Before going into details, note that all
these callbacks are explained in details in libavfilter/avfilter.h, so in
doubt, refer to the doxy in that file.

init()

text
First one to be called is init(). It's flagged as cold because not called
often. Look for "cold" on
http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html for more
information.

As the name suggests, init() is where you eventually initialize and allocate
your buffers, pre-compute your data, etc. Note that at this point, your local
context already has the user options initialized, but you still haven't any
clue about the kind of data input you will get, so this function is often
mainly used to sanitize the user options.

Some init()s will also define the number of inputs or outputs dynamically
according to the user options. A good example of this is the split filter, but
we won't cover this here since vf_foobar is just a simple 1:1 filter.

uninit()

Similarly, there is the uninit() callback, doing what the name suggests. Free
everything you allocated here.

query_formats()

text
This follows the init() and is used for the format negotiation. Basically
you specify here what pixel format(s) (gray, rgb 32, yuv 4:2:0, ...) you accept
for your inputs, and what you can output. All pixel formats are defined in
libavutil/pixfmt.h. If you don't change the pixel format between the input and
the output, you just have to define a pixel formats array and call
ff_set_common_formats(). For more complex negotiation, you can refer to other
filters such as vf_scale.

config_props()
~~~~~~~~~~~~~~

This callback is not necessary, but you will probably have one or more
config_props() anyway. It's not a callback for the filter itself but for its
inputs or outputs (they're called "pads" - AVFilterPad - in libavfilter's
lexicon).

Inside the input config_props(), you are at a point where you know which pixel
format has been picked after query_formats(), and more information such as the
video width and height (inlink->{w,h}). So if you need to update your internal
context state depending on your input you can do it here. In edgedetect you can
see that this callback is used to allocate buffers depending on these
information. They will be destroyed in uninit().

Inside the output config_props(), you can define what you want to change in the
output. Typically, if your filter is going to double the size of the video, you
will update outlink->w and outlink->h.

filter_frame()
~~~~~~~~~~~~~~

This is the callback you are waiting for from the beginning: it is where you
process the received frames. Along with the frame, you get the input link from
where the frame comes from.

    static int filter_frame(AVFilterLink *inlink, AVFrame *in) { ... }

You can get the filter context through that input link:

    AVFilterContext *ctx = inlink->dst;

Then access your internal state context:

    FoobarContext *foobar = ctx->priv;

And also the output link where you will send your frame when you are done:

    AVFilterLink *outlink = ctx->outputs[0];

Here, we are picking the first output. You can have several, but in our case we
only have one since we are in a 1:1 input-output situation.

If you want to define a simple pass-through filter, you can just do:

    return ff_filter_frame(outlink, in);

But of course, you probably want to change the data of that frame.

This can be done by accessing frame->data[] and frame->linesize[].  Important
note here: the width does NOT match the linesize. The linesize is always
greater or equal to the width. The padding created should not be changed or
even read. Typically, keep in mind that a previous filter in your chain might
have altered the frame dimension but not the linesize. Imagine a crop filter
that halves the video size: the linesizes won't be changed, just the width.

    <-------------- linesize ------------------------>
    +-------------------------------+----------------+ ^
    |                               |                | |
    |                               |                | |
    |           picture             |    padding     | | height
    |                               |                | |
    |                               |                | |
    +-------------------------------+----------------+ v
    <----------- width ------------->

Before modifying the "in" frame, you have to make sure it is writable, or get a
new one. Multiple scenarios are possible here depending on the kind of
processing you are doing.

Let's say you want to change one pixel depending on multiple pixels (typically
the surrounding ones) of the input. In that case, you can't do an in-place
processing of the input so you will need to allocate a new frame, with the same
properties as the input one, and send that new frame to the next filter:

    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
    if (!out) {
        av_frame_free(&in);
        return AVERROR(ENOMEM);
    }
    av_frame_copy_props(out, in);

    // out->data[...] = foobar(in->data[...])

    av_frame_free(&in);
    return ff_filter_frame(outlink, out);

In-place processing

If you can just alter the input frame, you probably just want to do that
instead:

text
av_frame_make_writable(in);
// in->data[...] = foobar(in->data[...])
return ff_filter_frame(outlink, in);

You may wonder why a frame might not be writable. The answer is that for
example a previous filter might still own the frame data: imagine a filter
prior to yours in the filtergraph that needs to cache the frame. You must not
alter that frame, otherwise it will make that previous filter buggy. This is
where av_frame_make_writable() helps (it won't have any effect if the frame
already is writable).

The problem with using av_frame_make_writable() is that in the worst case it
will copy the whole input frame before you change it all over again with your
filter: if the frame is not writable, av_frame_make_writable() will allocate
new buffers, and copy the input frame data. You don't want that, and you can
avoid it by just allocating a new buffer if necessary, and process from in to
out in your filter, saving the memcpy. Generally, this is done following this
scheme:

text
int direct = 0;
AVFrame *out;

if (av_frame_is_writable(in)) {
    direct = 1;
    out = in;
} else {
    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
    if (!out) {
        av_frame_free(&in);
        return AVERROR(ENOMEM);
    }
    av_frame_copy_props(out, in);
}

// out->data[...] = foobar(in->data[...])

if (!direct)
    av_frame_free(&in);
return ff_filter_frame(outlink, out);

Of course, this will only work if you can do in-place processing. To test if
your filter handles well the permissions, you can use the perms filter. For
example with:

text
-vf perms=random,foobar

Make sure no automatic pixel conversion is inserted between perms and foobar,
otherwise the frames permissions might change again and the test will be
meaningless: add av_log(0,0,"direct=%d\n",direct) in your code to check that.
You can avoid the issue with something like:

text
-vf format=rgb24,perms=random,foobar

...assuming your filter accepts rgb24 of course. This will make sure the
necessary conversion is inserted before the perms filter.

Timeline

text
Adding timeline support
(http://ffmpeg.org/ffmpeg-filters.html#Timeline-editing) is often an easy
feature to add. In the most simple case, you just have to add
AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC to the AVFilter.flags. You can typically
do this when your filter does not need to save the previous context frames, or
basically if your filter just alters whatever goes in and doesn't need
previous/future information. See for instance commit 86cb986ce that adds
timeline support to the fieldorder filter.

In some cases, you might need to reset your context somehow. This is handled by
the AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL flag which is used if the filter
must not process the frames but still wants to keep track of the frames going
through (to keep them in cache for when it's enabled again). See for example
commit 69d72140a that adds timeline support to the phase filter.

Threading

libavfilter does not yet support frame threading, but you can add slice
threading to your filters.

Let's say the foobar filter has the following frame processing function:

text
dst = out->data[0];
src = in ->data[0];

for (y = 0; y < inlink->h; y++) {
    for (x = 0; x < inlink->w; x++)
        dst[x] = foobar(src[x]);
    dst += out->linesize[0];
    src += in ->linesize[0];
}

The first thing is to make this function work into slices. The new code will
look like this:

text
for (y = slice_start; y < slice_end; y++) {
    for (x = 0; x < inlink->w; x++)
        dst[x] = foobar(src[x]);
    dst += out->linesize[0];
    src += in ->linesize[0];
}

The source and destination pointers, and slice_start/slice_end will be defined
according to the number of jobs. Generally, it looks like this:

text
const int slice_start = (in->height *  jobnr   ) / nb_jobs;
const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;
uint8_t       *dst = out->data[0] + slice_start * out->linesize[0];
const uint8_t *src =  in->data[0] + slice_start *  in->linesize[0];

This new code will be isolated in a new filter_slice():

text
static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ... }

Note that we need our input and output frame to define slice_{start,end} and
dst/src, which are not available in that callback. They will be transmitted
through the opaque void *arg. You have to define a structure which contains
everything you need:

text
typedef struct ThreadData {
    AVFrame *in, *out;
} ThreadData;

If you need some more information from your local context, put them here.

In you filter_slice function, you access it like that:

text
const ThreadData *td = arg;

Then in your filter_frame() callback, you need to call the threading
distributor with something like this:

text
ThreadData td;

// ...

td.in  = in;
td.out = out;
ctx->internal->execute(ctx, filter_slice, &td, NULL, FFMIN(outlink->h, ctx->graph->nb_threads));

// ...

return ff_filter_frame(outlink, out);

Last step is to add AVFILTER_FLAG_SLICE_THREADS flag to AVFilter.flags.

For more example of slice threading additions, you can try to run git log -p
--grep 'slice threading' libavfilter/

Finalization

text
When your awesome filter is finished, you have a few more steps before you're
done:

 - write its documentation in doc/filters.texi, and test the output with make
   doc/ffmpeg-filters.html.
 - add a FATE test, generally by adding an entry in
   tests/fate/filter-video.mak, add running make fate-filter-foobar GEN=1 to
   generate the data.
 - add an entry in the Changelog
 - edit libavfilter/version.h and increase LIBAVFILTER_VERSION_MINOR by one
   (and reset LIBAVFILTER_VERSION_MICRO to 100)
 - git add ... && git commit -m "avfilter: add foobar filter." && git format-patch -1

When all of this is done, you can submit your patch to the ffmpeg-devel
mailing-list for review.  If you need any help, feel free to come on our IRC
channel, #ffmpeg-devel on irc.freenode.net.

---

### Orig Chrome Gpu Command Buffer Docs Gles2 Cmd Format Docs (`orig_chrome/gpu/command_buffer/docs/gles2_cmd_format_docs.txt`)

//! \file
//!
//! The public interface for 3D graphics is based on a command buffer.
//!
//! This was chosen because it provides an easy way to separate the process of
//! writing commands from the process of reading those commands without
//! requiring too much overhead to keep the two processes in sync.
//!
//! You can use this info to write commands yourself. Most developers will use
//! the provided OpenGL ES 2.0 implementation that issues these commands for
//! them.
//!
//! Each command starts with a header. The header is 32 bits, where the first 21
//! bits define the number of 32 bit entries, including the header, the command
//! represents. The last 11 bits specify the command.
//!
//! Commands that send a variable amount of data have 1 to 3 ways to send that
//! data.
//!
//! Many commands can send their data in shared memory. The command will take
//! an id of the shared memory and an offset into that shared memory of where
//! the data lives. Commands are executed asynchronously, so the client
//! program must be careful to leave the data available until the command has
//! executed.
//!
//! Some commands have an 'immediate' version where the data appears directly
//! after the command in memory.
//!
//! A 3rd way of passing data is through Buckets. Buckets are identified by
//! number. You create a bucket with the command SetBucketSize, you can then
//! fill the bucket with SetBucketData commands. Once you've sent all your
//! data you can then issue a command that uses the bucket and takes a bucket
//! id for which bucket to use.
//!
//! Receiving data works similarly. Some commands return their data to shared
//! memory. Other commands return their data through buckets which can then be
//! queried with the GetBucketSize and GetBucketData commands. In either case
//! the data will not be available until the command executes.
//!
//! All commands and arguments are validated. If a command fails validation the
//! service will stop processing commands. It is the responsibility of the
//! client to never issue an invalid command.
//!
//! Examples of invalid commands.
//!  - A command's size does not match the command.
//!  - A command's size would address memory outside the command buffer
//!  - A shared memory id is invalid
//!  - A shared memory offset is out of range for the given shared memory
//!  - The size of the data a command would access in shared memory is out of
//!    range for the given shared memory buffer.
//!  - A result (in the transfer buffer) is not initialized to the
//!    failure case. For example, any command that returns a SizedResult
//!    will take a shared memory id and offset to where to store the result.
//!    That size field of the result must be set to 0 before issuing the
//!    the command. That way, if the command buffer service fails the
//!    client will see a 0 size.
//!
//! The docs are a little terse. For any command that corresponds to an OpenGL
//! ES 2.0 function the arguments should be clear by looking at the OpenGL ES
//! 2.0 documentation with minor caveats.
//!
//!  - Client side arrays are not supported at the command buffer level
//!    so DrawArrays and VertexAttribPointer only take offsets into buffers.
//!  - The commands GenBuffers, GetTextures, CreateProgram, CreateShader, etc
//!    take client side ids and register them with the service. It's up to the
//!    client to make up the ids.
//!  - For shared resources, it's still up to the client to make up ids.
//!    but to help keep them in sync with other threads the commands
//!    GenSharedIds, RegisterSharedIds and DeleteSharedIds can be used.
//!

//! The command header.
struct CommandHeader {
  Uint32 size:21;
  Uint32 command:11;
};


//! Used for some glGetXXX commands that return a result through a pointer. We
//! need to know if the command succeeded or not and the size of the result. If
//! the command failed its result size will 0.  You must set the size to 0
//! before issuing the command.
//!
//! To retrieve the data you might do something like this pseudo code:
//!
//!   GetAttachedShaders::Result* result = address-of-shared-memory
//!   int num_results = result->size / sizeof(GLuint);  // the type returned
//!   GLuint* results = &result->data;
//!   for (int ii = 0; ii < num_results; ++ii) {
//!     printf("%d\n", results[ii]);
//!   }
//!
template <typename T>
struct SizedResult {
  uint32 size;  // in bytes.
  T data;  // this is just here to get an offset.
};


//! A Noop command.
struct Noop {
  static const CommandId kCmdId = 0;

  CommandHeader header;
};

//! The SetToken command puts a token in the command stream that you can
//! use to check if that token has been passed in the command stream.
struct SetToken {
  static const CommandId kCmdId = 1;

  CommandHeader header;
  uint32 token;
};

//! The Jump command jumps to another place in the command buffer.
struct Jump {
  static const CommandId kCmdId = 3;

  CommandHeader header;
  uint32 offset;
};

//! The JumpRelative command jumps to another place in the command buffer
//! relative to the end of this command. In other words. JumpRelative with an
//! offset of zero is effectively a no-op.
struct JumpRelative {
  static const CommandId kCmdId = 4;

  CommandHeader header;
  int32 offset;
};

//! The Call command jumps to a subroutine which can be returned from with the
//! Return command.
struct Call {
  static const CommandId kCmdId = 5;

  CommandHeader header;
  uint32 offset;
};

//! The CallRelative command jumps to a subroutine using a relative offset. The
//! offset is relative to the end of this command..
struct CallRelative {
  static const CommandId kCmdId = 6;

  CommandHeader header;
  int32 offset;
};

//! Returns from a subroutine called by the Call or CallRelative commands.
struct Return {
  static const CommandId kCmdId = 7;

  CommandHeader header;
};

//! Sets the size of a bucket for collecting data on the service side.
//! This is a utility for gathering data on the service side so it can be used
//! all at once when some service side API is called. It removes the need to
//! add special commands just to support a particular API. For example, any API
//! command that needs a string needs a way to send that string to the API over
//! the command buffers. While you can require that the command buffer or
//! transfer buffer be large enough to hold the largest string you can send,
//! using this command removes that restriction by letting you send smaller
//! pieces over and build up the data on the service side.
//!
//! You can clear a bucket on the service side and thereby free memory by
//! sending a size of 0.
struct SetBucketSize {
  static const CommandId kCmdId = 8;

  CommandHeader header;
  uint32 bucket_id;
  uint32 size;
};

//! Sets the contents of a portion of a bucket on the service side from data in
//! shared memory.
//! See SetBucketSize.
struct SetBucketData {
  static const CommandId kCmdId = 9;

  CommandHeader header;
  uint32 bucket_id;
  uint32 offset;
  uint32 size;
  uint32 shared_memory_id;
  uint32 shared_memory_offset;
};

//! Sets the contents of a portion of a bucket on the service side from data in
//! the command buffer.
//! See SetBucketSize.
struct SetBucketDataImmediate {
  static const CommandId kCmdId = 10;

  CommandHeader header;
  uint32 bucket_id;
  uint32 offset;
  uint32 size;
};

//! Gets the size of a bucket the service has available. Sending a variable
//! size result back to the client, for example any API that returns a string,
//! is problematic since the largest thing you can send back is the size of
//! your shared memory. This command along with GetBucketData implements a way
//! to get a result a piece at a time to help solve that problem in a generic
//! way.
struct GetBucketSize {
  static const CommandId kCmdId = 11;

  typedef uint32 Result;

  CommandHeader header;
  uint32 bucket_id;
  uint32 shared_memory_id;
  uint32 shared_memory_offset;
};

//! Gets a piece of a result the service has available.
//! See GetBucketSize.
struct GetBucketData {
  static const CommandId kCmdId = 12;

  CommandHeader header;
  uint32 bucket_id;
  uint32 offset;
  uint32 size;
  uint32 shared_memory_id;
  uint32 shared_memory_offset;
};

// OpenGL ES 2.0 related commands.

//! Command that corresponds to glActiveTexture.
struct ActiveTexture {
  static const CommandId kCmdId = 256;

  CommandHeader header;
  uint32 texture;  //!< GLenum
};

//! Command that corresponds to glAttachShader.
struct AttachShader {
  static const CommandId kCmdId = 257;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 shader;  //!< GLuint
};

//! Command that corresponds to glBindAttribLocation.
struct BindAttribLocation {
  static const CommandId kCmdId = 258;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 index;  //!< GLuint
  uint32 name_shm_id;  //!< uint32
  uint32 name_shm_offset;  //!< uint32
  uint32 data_size;  //!< uint32
};

//! Immediate version of command that corresponds to glBindAttribLocation.
struct BindAttribLocationImmediate {
  static const CommandId kCmdId = 259;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 index;  //!< GLuint
  uint32 data_size;  //!< uint32
};

//! Bucket version of command that corresponds to glBindAttribLocation.
struct BindAttribLocationBucket {
  static const CommandId kCmdId = 432;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 index;  //!< GLuint
  uint32 name_bucket_id;  //!< uint32
};

//! Command that corresponds to glBindBuffer.
struct BindBuffer {
  static const CommandId kCmdId = 260;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 buffer;  //!< GLuint
};

//! Command that corresponds to glBindFramebuffer.
struct BindFramebuffer {
  static const CommandId kCmdId = 261;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 framebuffer;  //!< GLuint
};

//! Command that corresponds to glBindRenderbuffer.
struct BindRenderbuffer {
  static const CommandId kCmdId = 262;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 renderbuffer;  //!< GLuint
};

//! Command that corresponds to glBindTexture.
struct BindTexture {
  static const CommandId kCmdId = 263;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 texture;  //!< GLuint
};

//! Command that corresponds to glBlendColor.
struct BlendColor {
  static const CommandId kCmdId = 264;

  CommandHeader header;
  float red;  //!< GLclampf
  float green;  //!< GLclampf
  float blue;  //!< GLclampf
  float alpha;  //!< GLclampf
};

//! Command that corresponds to glBlendEquation.
struct BlendEquation {
  static const CommandId kCmdId = 265;

  CommandHeader header;
  uint32 mode;  //!< GLenum
};

//! Command that corresponds to glBlendEquationSeparate.
struct BlendEquationSeparate {
  static const CommandId kCmdId = 266;

  CommandHeader header;
  uint32 modeRGB;  //!< GLenum
  uint32 modeAlpha;  //!< GLenum
};

//! Command that corresponds to glBlendFunc.
struct BlendFunc {
  static const CommandId kCmdId = 267;

  CommandHeader header;
  uint32 sfactor;  //!< GLenum
  uint32 dfactor;  //!< GLenum
};

//! Command that corresponds to glBlendFuncSeparate.
struct BlendFuncSeparate {
  static const CommandId kCmdId = 268;

  CommandHeader header;
  uint32 srcRGB;  //!< GLenum
  uint32 dstRGB;  //!< GLenum
  uint32 srcAlpha;  //!< GLenum
  uint32 dstAlpha;  //!< GLenum
};

//! Command that corresponds to glBufferData.
struct BufferData {
  static const CommandId kCmdId = 269;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 size;  //!< GLsizeiptr
  uint32 data_shm_id;  //!< uint32
  uint32 data_shm_offset;  //!< uint32
  uint32 usage;  //!< GLenum
};

//! Immediate version of command that corresponds to glBufferData.
struct BufferDataImmediate {
  static const CommandId kCmdId = 270;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 size;  //!< GLsizeiptr
  uint32 usage;  //!< GLenum
};

//! Command that corresponds to glBufferSubData.
struct BufferSubData {
  static const CommandId kCmdId = 271;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 offset;  //!< GLintptr
  int32 size;  //!< GLsizeiptr
  uint32 data_shm_id;  //!< uint32
  uint32 data_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glBufferSubData.
struct BufferSubDataImmediate {
  static const CommandId kCmdId = 272;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 offset;  //!< GLintptr
  int32 size;  //!< GLsizeiptr
};

//! Command that corresponds to glCheckFramebufferStatus.
struct CheckFramebufferStatus {
  static const CommandId kCmdId = 273;

  typedef GLenum Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glClear.
struct Clear {
  static const CommandId kCmdId = 274;

  CommandHeader header;
  uint32 mask;  //!< GLbitfield
};

//! Command that corresponds to glClearColor.
struct ClearColor {
  static const CommandId kCmdId = 275;

  CommandHeader header;
  float red;  //!< GLclampf
  float green;  //!< GLclampf
  float blue;  //!< GLclampf
  float alpha;  //!< GLclampf
};

//! Command that corresponds to glClearDepthf.
struct ClearDepthf {
  static const CommandId kCmdId = 276;

  CommandHeader header;
  float depth;  //!< GLclampf
};

//! Command that corresponds to glClearStencil.
struct ClearStencil {
  static const CommandId kCmdId = 277;

  CommandHeader header;
  int32 s;  //!< GLint
};

//! Command that corresponds to glColorMask.
struct ColorMask {
  static const CommandId kCmdId = 278;

  CommandHeader header;
  uint32 red;  //!< GLboolean
  uint32 green;  //!< GLboolean
  uint32 blue;  //!< GLboolean
  uint32 alpha;  //!< GLboolean
};

//! Command that corresponds to glCompileShader.
struct CompileShader {
  static const CommandId kCmdId = 279;

  CommandHeader header;
  uint32 shader;  //!< GLuint
};

//! Command that corresponds to glCompressedTexImage2D.
struct CompressedTexImage2D {
  static const CommandId kCmdId = 280;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  uint32 internalformat;  //!< GLenum
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
  int32 imageSize;  //!< GLsizei
  uint32 data_shm_id;  //!< uint32
  uint32 data_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glCompressedTexImage2D.
struct CompressedTexImage2DImmediate {
  static const CommandId kCmdId = 281;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  uint32 internalformat;  //!< GLenum
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
  int32 imageSize;  //!< GLsizei
};

//! Bucket version of command that corresponds to glCompressedTexImage2D.
struct CompressedTexImage2DBucket {
  static const CommandId kCmdId = 443;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  uint32 internalformat;  //!< GLenum
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
  uint32 bucket_id;  //!< GLuint
};

//! Command that corresponds to glCompressedTexSubImage2D.
struct CompressedTexSubImage2D {
  static const CommandId kCmdId = 282;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  int32 imageSize;  //!< GLsizei
  uint32 data_shm_id;  //!< uint32
  uint32 data_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glCompressedTexSubImage2D.
struct CompressedTexSubImage2DImmediate {
  static const CommandId kCmdId = 283;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  int32 imageSize;  //!< GLsizei
};

//! Bucket version of command that corresponds to glCompressedTexSubImage2D.
struct CompressedTexSubImage2DBucket {
  static const CommandId kCmdId = 444;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  uint32 bucket_id;  //!< GLuint
};

//! Command that corresponds to glCopyTexImage2D.
struct CopyTexImage2D {
  static const CommandId kCmdId = 284;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  uint32 internalformat;  //!< GLenum
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
};

//! Command that corresponds to glCopyTexSubImage2D.
struct CopyTexSubImage2D {
  static const CommandId kCmdId = 285;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
};

//! Command that corresponds to glCreateProgram.
struct CreateProgram {
  static const CommandId kCmdId = 286;

  CommandHeader header;
  uint32 client_id;  //!< uint32
};

//! Command that corresponds to glCreateShader.
struct CreateShader {
  static const CommandId kCmdId = 287;

  CommandHeader header;
  uint32 type;  //!< GLenum
  uint32 client_id;  //!< uint32
};

//! Command that corresponds to glCullFace.
struct CullFace {
  static const CommandId kCmdId = 288;

  CommandHeader header;
  uint32 mode;  //!< GLenum
};

//! Command that corresponds to glDeleteBuffers.
struct DeleteBuffers {
  static const CommandId kCmdId = 289;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 buffers_shm_id;  //!< uint32
  uint32 buffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glDeleteBuffers.
struct DeleteBuffersImmediate {
  static const CommandId kCmdId = 290;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glDeleteFramebuffers.
struct DeleteFramebuffers {
  static const CommandId kCmdId = 291;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 framebuffers_shm_id;  //!< uint32
  uint32 framebuffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glDeleteFramebuffers.
struct DeleteFramebuffersImmediate {
  static const CommandId kCmdId = 292;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glDeleteProgram.
struct DeleteProgram {
  static const CommandId kCmdId = 293;

  CommandHeader header;
  uint32 program;  //!< GLuint
};

//! Command that corresponds to glDeleteRenderbuffers.
struct DeleteRenderbuffers {
  static const CommandId kCmdId = 294;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 renderbuffers_shm_id;  //!< uint32
  uint32 renderbuffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glDeleteRenderbuffers.
struct DeleteRenderbuffersImmediate {
  static const CommandId kCmdId = 295;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glDeleteShader.
struct DeleteShader {
  static const CommandId kCmdId = 296;

  CommandHeader header;
  uint32 shader;  //!< GLuint
};

//! Command that corresponds to glDeleteTextures.
struct DeleteTextures {
  static const CommandId kCmdId = 297;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 textures_shm_id;  //!< uint32
  uint32 textures_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glDeleteTextures.
struct DeleteTexturesImmediate {
  static const CommandId kCmdId = 298;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glDepthFunc.
struct DepthFunc {
  static const CommandId kCmdId = 299;

  CommandHeader header;
  uint32 func;  //!< GLenum
};

//! Command that corresponds to glDepthMask.
struct DepthMask {
  static const CommandId kCmdId = 300;

  CommandHeader header;
  uint32 flag;  //!< GLboolean
};

//! Command that corresponds to glDepthRangef.
struct DepthRangef {
  static const CommandId kCmdId = 301;

  CommandHeader header;
  float zNear;  //!< GLclampf
  float zFar;  //!< GLclampf
};

//! Command that corresponds to glDetachShader.
struct DetachShader {
  static const CommandId kCmdId = 302;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 shader;  //!< GLuint
};

//! Command that corresponds to glDisable.
struct Disable {
  static const CommandId kCmdId = 303;

  CommandHeader header;
  uint32 cap;  //!< GLenum
};

//! Command that corresponds to glDisableVertexAttribArray.
struct DisableVertexAttribArray {
  static const CommandId kCmdId = 304;

  CommandHeader header;
  uint32 index;  //!< GLuint
};

//! Command that corresponds to glDrawArrays.
struct DrawArrays {
  static const CommandId kCmdId = 305;

  CommandHeader header;
  uint32 mode;  //!< GLenum
  int32 first;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glDrawElements.
struct DrawElements {
  static const CommandId kCmdId = 306;

  CommandHeader header;
  uint32 mode;  //!< GLenum
  int32 count;  //!< GLsizei
  uint32 type;  //!< GLenum
  uint32 index_offset;  //!< GLuint
};

//! Command that corresponds to glEnable.
struct Enable {
  static const CommandId kCmdId = 307;

  CommandHeader header;
  uint32 cap;  //!< GLenum
};

//! Command that corresponds to glEnableVertexAttribArray.
struct EnableVertexAttribArray {
  static const CommandId kCmdId = 308;

  CommandHeader header;
  uint32 index;  //!< GLuint
};

//! Command that corresponds to glFinish.
struct Finish {
  static const CommandId kCmdId = 309;

  CommandHeader header;
};

//! Command that corresponds to glFlush.
struct Flush {
  static const CommandId kCmdId = 310;

  CommandHeader header;
};

//! Command that corresponds to glFramebufferRenderbuffer.
struct FramebufferRenderbuffer {
  static const CommandId kCmdId = 311;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 attachment;  //!< GLenum
  uint32 renderbuffertarget;  //!< GLenum
  uint32 renderbuffer;  //!< GLuint
};

//! Command that corresponds to glFramebufferTexture2D.
struct FramebufferTexture2D {
  static const CommandId kCmdId = 312;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 attachment;  //!< GLenum
  uint32 textarget;  //!< GLenum
  uint32 texture;  //!< GLuint
  int32 level;  //!< GLint
};

//! Command that corresponds to glFrontFace.
struct FrontFace {
  static const CommandId kCmdId = 313;

  CommandHeader header;
  uint32 mode;  //!< GLenum
};

//! Command that corresponds to glGenBuffers.
struct GenBuffers {
  static const CommandId kCmdId = 314;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 buffers_shm_id;  //!< uint32
  uint32 buffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glGenBuffers.
struct GenBuffersImmediate {
  static const CommandId kCmdId = 315;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glGenerateMipmap.
struct GenerateMipmap {
  static const CommandId kCmdId = 316;

  CommandHeader header;
  uint32 target;  //!< GLenum
};

//! Command that corresponds to glGenFramebuffers.
struct GenFramebuffers {
  static const CommandId kCmdId = 317;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 framebuffers_shm_id;  //!< uint32
  uint32 framebuffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glGenFramebuffers.
struct GenFramebuffersImmediate {
  static const CommandId kCmdId = 318;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glGenRenderbuffers.
struct GenRenderbuffers {
  static const CommandId kCmdId = 319;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 renderbuffers_shm_id;  //!< uint32
  uint32 renderbuffers_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glGenRenderbuffers.
struct GenRenderbuffersImmediate {
  static const CommandId kCmdId = 320;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glGenTextures.
struct GenTextures {
  static const CommandId kCmdId = 321;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 textures_shm_id;  //!< uint32
  uint32 textures_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glGenTextures.
struct GenTexturesImmediate {
  static const CommandId kCmdId = 322;

  CommandHeader header;
  int32 n;  //!< GLsizei
};

//! Command that corresponds to glGetActiveAttrib.
struct GetActiveAttrib {
  static const CommandId kCmdId = 323;

  struct Result {
    int32 success;
    int32 size;
    uint32 type;
  };

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 index;  //!< GLuint
  uint32 name_bucket_id;  //!< uint32
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetActiveUniform.
struct GetActiveUniform {
  static const CommandId kCmdId = 324;

  struct Result {
    int32 success;
    int32 size;
    uint32 type;
  };

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 index;  //!< GLuint
  uint32 name_bucket_id;  //!< uint32
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetAttachedShaders.
struct GetAttachedShaders {
  static const CommandId kCmdId = 325;

  typedef SizedResult<GLuint> Result;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
  uint32 result_size;  //!< uint32
};

//! Command that corresponds to glGetAttribLocation.
struct GetAttribLocation {
  static const CommandId kCmdId = 326;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 name_shm_id;
  uint32 name_shm_offset;
  uint32 location_shm_id;
  uint32 location_shm_offset;
  uint32 data_size;
};

//! Immediate version of command that corresponds to glGetAttribLocation.
struct GetAttribLocationImmediate {
  static const CommandId kCmdId = 327;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 location_shm_id;
  uint32 location_shm_offset;
  uint32 data_size;
};

//! Bucket version of command that corresponds to glGetAttribLocation.
struct GetAttribLocationBucket {
  static const CommandId kCmdId = 434;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 name_bucket_id;
  uint32 location_shm_id;
  uint32 location_shm_offset;
};

//! Command that corresponds to glGetBooleanv.
struct GetBooleanv {
  static const CommandId kCmdId = 328;

  typedef SizedResult<GLboolean> Result;

  CommandHeader header;
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetBufferParameteriv.
struct GetBufferParameteriv {
  static const CommandId kCmdId = 329;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetError.
struct GetError {
  static const CommandId kCmdId = 330;

  typedef GLenum Result;

  CommandHeader header;
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetFloatv.
struct GetFloatv {
  static const CommandId kCmdId = 331;

  typedef SizedResult<GLfloat> Result;

  CommandHeader header;
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetFramebufferAttachmentParameteriv.
struct GetFramebufferAttachmentParameteriv {
  static const CommandId kCmdId = 332;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 attachment;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetIntegerv.
struct GetIntegerv {
  static const CommandId kCmdId = 333;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetProgramiv.
struct GetProgramiv {
  static const CommandId kCmdId = 334;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetProgramInfoLog.
struct GetProgramInfoLog {
  static const CommandId kCmdId = 335;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 bucket_id;  //!< uint32
};

//! Command that corresponds to glGetRenderbufferParameteriv.
struct GetRenderbufferParameteriv {
  static const CommandId kCmdId = 336;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetShaderiv.
struct GetShaderiv {
  static const CommandId kCmdId = 337;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetShaderInfoLog.
struct GetShaderInfoLog {
  static const CommandId kCmdId = 338;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 bucket_id;  //!< uint32
};

//! Command that corresponds to glGetShaderPrecisionFormat.
struct GetShaderPrecisionFormat {
  static const CommandId kCmdId = 339;

  struct Result {
    int32 success;
    int32 min_range;
    int32 max_range;
    int32 precision;
  };

  CommandHeader header;
  uint32 shadertype;  //!< GLenum
  uint32 precisiontype;  //!< GLenum
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetShaderSource.
struct GetShaderSource {
  static const CommandId kCmdId = 340;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 bucket_id;  //!< uint32
};

//! Command that corresponds to glGetString.
struct GetString {
  static const CommandId kCmdId = 341;

  CommandHeader header;
  uint32 name;  //!< GLenum
  uint32 bucket_id;  //!< uint32
};

//! Command that corresponds to glGetTexParameterfv.
struct GetTexParameterfv {
  static const CommandId kCmdId = 342;

  typedef SizedResult<GLfloat> Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetTexParameteriv.
struct GetTexParameteriv {
  static const CommandId kCmdId = 343;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetUniformLocation.
struct GetUniformLocation {
  static const CommandId kCmdId = 346;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 name_shm_id;
  uint32 name_shm_offset;
  uint32 location_shm_id;
  uint32 location_shm_offset;
  uint32 data_size;
};

//! Immediate version of command that corresponds to glGetUniformLocation.
struct GetUniformLocationImmediate {
  static const CommandId kCmdId = 347;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 location_shm_id;
  uint32 location_shm_offset;
  uint32 data_size;
};

//! Bucket version of command that corresponds to glGetUniformLocation.
struct GetUniformLocationBucket {
  static const CommandId kCmdId = 433;

  typedef GLint Result;

  CommandHeader header;
  uint32 program;
  uint32 name_bucket_id;
  uint32 location_shm_id;
  uint32 location_shm_offset;
};


//! Command that corresponds to glGetUniformfv.
struct GetUniformfv {
  static const CommandId kCmdId = 344;

  typedef SizedResult<GLfloat> Result;

  CommandHeader header;
  uint32 program;  //!< GLuint
  int32 location;  //!< GLint
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetUniformiv.
struct GetUniformiv {
  static const CommandId kCmdId = 345;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 program;  //!< GLuint
  int32 location;  //!< GLint
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetVertexAttribfv.
struct GetVertexAttribfv {
  static const CommandId kCmdId = 348;

  typedef SizedResult<GLfloat> Result;

  CommandHeader header;
  uint32 index;  //!< GLuint
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetVertexAttribiv.
struct GetVertexAttribiv {
  static const CommandId kCmdId = 349;

  typedef SizedResult<GLint> Result;

  CommandHeader header;
  uint32 index;  //!< GLuint
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Command that corresponds to glGetVertexAttribPointerv.
struct GetVertexAttribPointerv {
  static const CommandId kCmdId = 350;

  typedef SizedResult<GLuint> Result;

  CommandHeader header;
  uint32 index;  //!< GLuint
  uint32 pname;  //!< GLenum
  uint32 pointer_shm_id;  //!< uint32
  uint32 pointer_shm_offset;  //!< uint32
};

//! Command that corresponds to glHint.
struct Hint {
  static const CommandId kCmdId = 351;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 mode;  //!< GLenum
};

//! Command that corresponds to glIsBuffer.
struct IsBuffer {
  static const CommandId kCmdId = 352;

  typedef uint32 Result;

  CommandHeader header;
  uint32 buffer;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsEnabled.
struct IsEnabled {
  static const CommandId kCmdId = 353;

  typedef uint32 Result;

  CommandHeader header;
  uint32 cap;  //!< GLenum
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsFramebuffer.
struct IsFramebuffer {
  static const CommandId kCmdId = 354;

  typedef uint32 Result;

  CommandHeader header;
  uint32 framebuffer;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsProgram.
struct IsProgram {
  static const CommandId kCmdId = 355;

  typedef uint32 Result;

  CommandHeader header;
  uint32 program;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsRenderbuffer.
struct IsRenderbuffer {
  static const CommandId kCmdId = 356;

  typedef uint32 Result;

  CommandHeader header;
  uint32 renderbuffer;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsShader.
struct IsShader {
  static const CommandId kCmdId = 357;

  typedef uint32 Result;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glIsTexture.
struct IsTexture {
  static const CommandId kCmdId = 358;

  typedef uint32 Result;

  CommandHeader header;
  uint32 texture;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glLineWidth.
struct LineWidth {
  static const CommandId kCmdId = 359;

  CommandHeader header;
  float width;  //!< GLfloat
};

//! Command that corresponds to glLinkProgram.
struct LinkProgram {
  static const CommandId kCmdId = 360;

  CommandHeader header;
  uint32 program;  //!< GLuint
};

//! Command that corresponds to glPixelStorei.
struct PixelStorei {
  static const CommandId kCmdId = 361;

  CommandHeader header;
  uint32 pname;  //!< GLenum
  int32 param;  //!< GLint
};

//! Command that corresponds to glPolygonOffset.
struct PolygonOffset {
  static const CommandId kCmdId = 362;

  CommandHeader header;
  float factor;  //!< GLfloat
  float units;  //!< GLfloat
};

//! Command that corresponds to glReadPixels.
//! ReadPixels has the result separated from the pixel buffer so that
//! it is easier to specify the result going to some specific place
//! that exactly fits the rectangle of pixels.
struct ReadPixels {
  static const CommandId kCmdId = 363;

  typedef uint32 Result;

  CommandHeader header;
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  uint32 type;  //!< GLenum
  uint32 pixels_shm_id;  //!< uint32
  uint32 pixels_shm_offset;  //!< uint32
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that corresponds to glReleaseShaderCompiler.
struct ReleaseShaderCompiler {
  static const CommandId kCmdId = 437;

  CommandHeader header;
};

//! Command that corresponds to glRenderbufferStorage.
struct RenderbufferStorage {
  static const CommandId kCmdId = 364;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 internalformat;  //!< GLenum
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
};

//! Command that corresponds to glSampleCoverage.
struct SampleCoverage {
  static const CommandId kCmdId = 365;

  CommandHeader header;
  float value;  //!< GLclampf
  uint32 invert;  //!< GLboolean
};

//! Command that corresponds to glScissor.
struct Scissor {
  static const CommandId kCmdId = 366;

  CommandHeader header;
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
};

//! Command that corresponds to glShaderBinary.
struct ShaderBinary {
  static const CommandId kCmdId = 436;

  CommandHeader header;
  int32 n;  //!< GLsizei
  uint32 shaders_shm_id;  //!< uint32
  uint32 shaders_shm_offset;  //!< uint32
  uint32 binaryformat;  //!< GLenum
  uint32 binary_shm_id;  //!< uint32
  uint32 binary_shm_offset;  //!< uint32
  int32 length;  //!< GLsizei
};

//! Command that corresponds to glShaderSource.
struct ShaderSource {
  static const CommandId kCmdId = 367;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 data_shm_id;  //!< uint32
  uint32 data_shm_offset;  //!< uint32
  uint32 data_size;  //!< uint32
};

//! Immediate version of command that corresponds to glShaderSource.
struct ShaderSourceImmediate {
  static const CommandId kCmdId = 368;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 data_size;  //!< uint32
};

//! Bucket version of command that corresponds to glShaderSource.
struct ShaderSourceBucket {
  static const CommandId kCmdId = 435;

  CommandHeader header;
  uint32 shader;  //!< GLuint
  uint32 data_bucket_id;  //!< uint32
};

//! Command that corresponds to glStencilFunc.
struct StencilFunc {
  static const CommandId kCmdId = 369;

  CommandHeader header;
  uint32 func;  //!< GLenum
  int32 ref;  //!< GLint
  uint32 mask;  //!< GLuint
};

//! Command that corresponds to glStencilFuncSeparate.
struct StencilFuncSeparate {
  static const CommandId kCmdId = 370;

  CommandHeader header;
  uint32 face;  //!< GLenum
  uint32 func;  //!< GLenum
  int32 ref;  //!< GLint
  uint32 mask;  //!< GLuint
};

//! Command that corresponds to glStencilMask.
struct StencilMask {
  static const CommandId kCmdId = 371;

  CommandHeader header;
  uint32 mask;  //!< GLuint
};

//! Command that corresponds to glStencilMaskSeparate.
struct StencilMaskSeparate {
  static const CommandId kCmdId = 372;

  CommandHeader header;
  uint32 face;  //!< GLenum
  uint32 mask;  //!< GLuint
};

//! Command that corresponds to glStencilOp.
struct StencilOp {
  static const CommandId kCmdId = 373;

  CommandHeader header;
  uint32 fail;  //!< GLenum
  uint32 zfail;  //!< GLenum
  uint32 zpass;  //!< GLenum
};

//! Command that corresponds to glStencilOpSeparate.
struct StencilOpSeparate {
  static const CommandId kCmdId = 374;

  CommandHeader header;
  uint32 face;  //!< GLenum
  uint32 fail;  //!< GLenum
  uint32 zfail;  //!< GLenum
  uint32 zpass;  //!< GLenum
};

//! Command that corresponds to glTexImage2D.
struct TexImage2D {
  static const CommandId kCmdId = 375;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 internalformat;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
  uint32 format;  //!< GLenum
  uint32 type;  //!< GLenum
  uint32 pixels_shm_id;  //!< uint32
  uint32 pixels_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glTexImage2D.
struct TexImage2DImmediate {
  static const CommandId kCmdId = 376;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 internalformat;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  int32 border;  //!< GLint
  uint32 format;  //!< GLenum
  uint32 type;  //!< GLenum
};

//! Command that corresponds to glTexParameterf.
struct TexParameterf {
  static const CommandId kCmdId = 377;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  float param;  //!< GLfloat
};

//! Command that corresponds to glTexParameterfv.
struct TexParameterfv {
  static const CommandId kCmdId = 378;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glTexParameterfv.
struct TexParameterfvImmediate {
  static const CommandId kCmdId = 379;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
};

//! Command that corresponds to glTexParameteri.
struct TexParameteri {
  static const CommandId kCmdId = 380;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  int32 param;  //!< GLint
};

//! Command that corresponds to glTexParameteriv.
struct TexParameteriv {
  static const CommandId kCmdId = 381;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
  uint32 params_shm_id;  //!< uint32
  uint32 params_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glTexParameteriv.
struct TexParameterivImmediate {
  static const CommandId kCmdId = 382;

  CommandHeader header;
  uint32 target;  //!< GLenum
  uint32 pname;  //!< GLenum
};

//! Command that corresponds to glTexSubImage2D.
struct TexSubImage2D {
  static const CommandId kCmdId = 383;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  uint32 type;  //!< GLenum
  uint32 pixels_shm_id;  //!< uint32
  uint32 pixels_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glTexSubImage2D.
struct TexSubImage2DImmediate {
  static const CommandId kCmdId = 384;

  CommandHeader header;
  uint32 target;  //!< GLenum
  int32 level;  //!< GLint
  int32 xoffset;  //!< GLint
  int32 yoffset;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
  uint32 format;  //!< GLenum
  uint32 type;  //!< GLenum
};

//! Command that corresponds to glUniform1f.
struct Uniform1f {
  static const CommandId kCmdId = 385;

  CommandHeader header;
  int32 location;  //!< GLint
  float x;  //!< GLfloat
};

//! Command that corresponds to glUniform1fv.
struct Uniform1fv {
  static const CommandId kCmdId = 386;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform1fv.
struct Uniform1fvImmediate {
  static const CommandId kCmdId = 387;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform1i.
struct Uniform1i {
  static const CommandId kCmdId = 388;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 x;  //!< GLint
};

//! Command that corresponds to glUniform1iv.
struct Uniform1iv {
  static const CommandId kCmdId = 389;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform1iv.
struct Uniform1ivImmediate {
  static const CommandId kCmdId = 390;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform2f.
struct Uniform2f {
  static const CommandId kCmdId = 391;

  CommandHeader header;
  int32 location;  //!< GLint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
};

//! Command that corresponds to glUniform2fv.
struct Uniform2fv {
  static const CommandId kCmdId = 392;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform2fv.
struct Uniform2fvImmediate {
  static const CommandId kCmdId = 393;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform2i.
struct Uniform2i {
  static const CommandId kCmdId = 394;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 x;  //!< GLint
  int32 y;  //!< GLint
};

//! Command that corresponds to glUniform2iv.
struct Uniform2iv {
  static const CommandId kCmdId = 395;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform2iv.
struct Uniform2ivImmediate {
  static const CommandId kCmdId = 396;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform3f.
struct Uniform3f {
  static const CommandId kCmdId = 397;

  CommandHeader header;
  int32 location;  //!< GLint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
  float z;  //!< GLfloat
};

//! Command that corresponds to glUniform3fv.
struct Uniform3fv {
  static const CommandId kCmdId = 398;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform3fv.
struct Uniform3fvImmediate {
  static const CommandId kCmdId = 399;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform3i.
struct Uniform3i {
  static const CommandId kCmdId = 400;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 z;  //!< GLint
};

//! Command that corresponds to glUniform3iv.
struct Uniform3iv {
  static const CommandId kCmdId = 401;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform3iv.
struct Uniform3ivImmediate {
  static const CommandId kCmdId = 402;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform4f.
struct Uniform4f {
  static const CommandId kCmdId = 403;

  CommandHeader header;
  int32 location;  //!< GLint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
  float z;  //!< GLfloat
  float w;  //!< GLfloat
};

//! Command that corresponds to glUniform4fv.
struct Uniform4fv {
  static const CommandId kCmdId = 404;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform4fv.
struct Uniform4fvImmediate {
  static const CommandId kCmdId = 405;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniform4i.
struct Uniform4i {
  static const CommandId kCmdId = 406;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 z;  //!< GLint
  int32 w;  //!< GLint
};

//! Command that corresponds to glUniform4iv.
struct Uniform4iv {
  static const CommandId kCmdId = 407;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 v_shm_id;  //!< uint32
  uint32 v_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniform4iv.
struct Uniform4ivImmediate {
  static const CommandId kCmdId = 408;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
};

//! Command that corresponds to glUniformMatrix2fv.
struct UniformMatrix2fv {
  static const CommandId kCmdId = 409;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
  uint32 value_shm_id;  //!< uint32
  uint32 value_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniformMatrix2fv.
struct UniformMatrix2fvImmediate {
  static const CommandId kCmdId = 410;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
};

//! Command that corresponds to glUniformMatrix3fv.
struct UniformMatrix3fv {
  static const CommandId kCmdId = 411;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
  uint32 value_shm_id;  //!< uint32
  uint32 value_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniformMatrix3fv.
struct UniformMatrix3fvImmediate {
  static const CommandId kCmdId = 412;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
};

//! Command that corresponds to glUniformMatrix4fv.
struct UniformMatrix4fv {
  static const CommandId kCmdId = 413;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
  uint32 value_shm_id;  //!< uint32
  uint32 value_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glUniformMatrix4fv.
struct UniformMatrix4fvImmediate {
  static const CommandId kCmdId = 414;

  CommandHeader header;
  int32 location;  //!< GLint
  int32 count;  //!< GLsizei
  uint32 transpose;  //!< GLboolean
};

//! Command that corresponds to glUseProgram.
struct UseProgram {
  static const CommandId kCmdId = 415;

  CommandHeader header;
  uint32 program;  //!< GLuint
};

//! Command that corresponds to glValidateProgram.
struct ValidateProgram {
  static const CommandId kCmdId = 416;

  CommandHeader header;
  uint32 program;  //!< GLuint
};

//! Command that corresponds to glVertexAttrib1f.
struct VertexAttrib1f {
  static const CommandId kCmdId = 417;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  float x;  //!< GLfloat
};

//! Command that corresponds to glVertexAttrib1fv.
struct VertexAttrib1fv {
  static const CommandId kCmdId = 418;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  uint32 values_shm_id;  //!< uint32
  uint32 values_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glVertexAttrib1fv.
struct VertexAttrib1fvImmediate {
  static const CommandId kCmdId = 419;

  CommandHeader header;
  uint32 indx;  //!< GLuint
};

//! Command that corresponds to glVertexAttrib2f.
struct VertexAttrib2f {
  static const CommandId kCmdId = 420;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
};

//! Command that corresponds to glVertexAttrib2fv.
struct VertexAttrib2fv {
  static const CommandId kCmdId = 421;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  uint32 values_shm_id;  //!< uint32
  uint32 values_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glVertexAttrib2fv.
struct VertexAttrib2fvImmediate {
  static const CommandId kCmdId = 422;

  CommandHeader header;
  uint32 indx;  //!< GLuint
};

//! Command that corresponds to glVertexAttrib3f.
struct VertexAttrib3f {
  static const CommandId kCmdId = 423;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
  float z;  //!< GLfloat
};

//! Command that corresponds to glVertexAttrib3fv.
struct VertexAttrib3fv {
  static const CommandId kCmdId = 424;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  uint32 values_shm_id;  //!< uint32
  uint32 values_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glVertexAttrib3fv.
struct VertexAttrib3fvImmediate {
  static const CommandId kCmdId = 425;

  CommandHeader header;
  uint32 indx;  //!< GLuint
};

//! Command that corresponds to glVertexAttrib4f.
struct VertexAttrib4f {
  static const CommandId kCmdId = 426;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  float x;  //!< GLfloat
  float y;  //!< GLfloat
  float z;  //!< GLfloat
  float w;  //!< GLfloat
};

//! Command that corresponds to glVertexAttrib4fv.
struct VertexAttrib4fv {
  static const CommandId kCmdId = 427;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  uint32 values_shm_id;  //!< uint32
  uint32 values_shm_offset;  //!< uint32
};

//! Immediate version of command that corresponds to glVertexAttrib4fv.
struct VertexAttrib4fvImmediate {
  static const CommandId kCmdId = 428;

  CommandHeader header;
  uint32 indx;  //!< GLuint
};

//! Command that corresponds to glVertexAttribPointer.
struct VertexAttribPointer {
  static const CommandId kCmdId = 429;

  CommandHeader header;
  uint32 indx;  //!< GLuint
  int32 size;  //!< GLint
  uint32 type;  //!< GLenum
  uint32 normalized;  //!< GLboolean
  int32 stride;  //!< GLsizei
  uint32 offset;  //!< GLuint
};

//! Command that corresponds to glViewport.
struct Viewport {
  static const CommandId kCmdId = 430;

  CommandHeader header;
  int32 x;  //!< GLint
  int32 y;  //!< GLint
  int32 width;  //!< GLsizei
  int32 height;  //!< GLsizei
};

//! Command that corresponds to SwapBuffers.
struct SwapBuffers {
  static const CommandId kCmdId = 431;

  CommandHeader header;
};

//! Command that corresponds to GetMaxValueInBuffer.
struct GetMaxValueInBuffer {
  static const CommandId kCmdId = 436;

  typedef GLuint Result;

  CommandHeader header;
  uint32 buffer_id;  //!< GLuint
  int32 count;  //!< GLsizei
  uint32 type;  //!< GLenum
  uint32 offset;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

//! Command that generates shared ids for contexts that share resources.
struct GenSharedIds {
  static const CommandId kCmdId = 439;

  CommandHeader header;
  uint32 namespace_id;  //!< GLuint
  uint32 id_offset;  //!< GLuint
  int32 n;  //!< GLsizei
  uint32 ids_shm_id;  //!< uint32
  uint32 ids_shm_offset;  //!< uint32
};

//! Command that deletes shared ids.
struct DeleteSharedIds {
  static const CommandId kCmdId = 440;

  CommandHeader header;
  uint32 namespace_id;  //!< GLuint
  int32 n;  //!< GLsizei
  uint32 ids_shm_id;  //!< uint32
  uint32 ids_shm_offset;  //!< uint32
};

//! Command that registers shared ids. It is an error to attempt
//! to register an id that is already registered.
struct RegisterSharedIds {
  static const CommandId kCmdId = 441;

  CommandHeader header;
  uint32 namespace_id;  //!< GLuint
  int32 n;  //!< GLsizei
  uint32 ids_shm_id;  //!< uint32
  uint32 ids_shm_offset;  //!< uint32
};

//! Command that enables features. The bucket should contain the feature string.
struct CommandBufferEnable {
  static const CommandId kCmdId = 442;

  typedef GLint Result;

  CommandHeader header;
  uint32 bucket_id;  //!< GLuint
  uint32 result_shm_id;  //!< uint32
  uint32 result_shm_offset;  //!< uint32
};

---

### Third Party Freetype Src Docs FTL (`third_party/freetype/src/docs/FTL.TXT`)

The FreeType Project LICENSE
                    ----------------------------

                            2006-Jan-27

                    Copyright 1996-2002, 2006 by
          David Turner, Robert Wilhelm, and Werner Lemberg



Introduction
============

  The FreeType  Project is distributed in  several archive packages;
  some of them may contain, in addition to the FreeType font engine,
  various tools and  contributions which rely on, or  relate to, the
  FreeType Project.

  This  license applies  to all  files found  in such  packages, and
  which do not  fall under their own explicit  license.  The license
  affects  thus  the  FreeType   font  engine,  the  test  programs,
  documentation and makefiles, at the very least.

  This  license   was  inspired  by  the  BSD,   Artistic,  and  IJG
  (Independent JPEG  Group) licenses, which  all encourage inclusion
  and  use of  free  software in  commercial  and freeware  products
  alike.  As a consequence, its main points are that:

    o We don't promise that this software works. However, we will be
      interested in any kind of bug reports. (`as is' distribution)

    o You can  use this software for whatever you  want, in parts or
      full form, without having to pay us. (`royalty-free' usage)

    o You may not pretend that  you wrote this software.  If you use
      it, or  only parts of it,  in a program,  you must acknowledge
      somewhere  in  your  documentation  that  you  have  used  the
      FreeType code. (`credits')

  We  specifically  permit  and  encourage  the  inclusion  of  this
  software, with  or without modifications,  in commercial products.
  We  disclaim  all warranties  covering  The  FreeType Project  and
  assume no liability related to The FreeType Project.


  Finally,  many  people  asked  us  for  a  preferred  form  for  a
  credit/disclaimer to use in compliance with this license.  We thus
  encourage you to use the following text:

   """
    Portions of this software are copyright © <year> The FreeType
    Project (www.freetype.org).  All rights reserved.
   """

  Please replace <year> with the value from the FreeType version you
  actually use.


Legal Terms
===========

0. Definitions
--------------

  Throughout this license,  the terms `package', `FreeType Project',
  and  `FreeType  archive' refer  to  the  set  of files  originally
  distributed  by the  authors  (David Turner,  Robert Wilhelm,  and
  Werner Lemberg) as the `FreeType Project', be they named as alpha,
  beta or final release.

  `You' refers to  the licensee, or person using  the project, where
  `using' is a generic term including compiling the project's source
  code as  well as linking it  to form a  `program' or `executable'.
  This  program is  referred to  as  `a program  using the  FreeType
  engine'.

  This  license applies  to all  files distributed  in  the original
  FreeType  Project,   including  all  source   code,  binaries  and
  documentation,  unless  otherwise  stated   in  the  file  in  its
  original, unmodified form as  distributed in the original archive.
  If you are  unsure whether or not a particular  file is covered by
  this license, you must contact us to verify this.

  The FreeType  Project is copyright (C) 1996-2000  by David Turner,
  Robert Wilhelm, and Werner Lemberg.  All rights reserved except as
  specified below.

1. No Warranty
--------------

  THE FREETYPE PROJECT  IS PROVIDED `AS IS' WITHOUT  WARRANTY OF ANY
  KIND, EITHER  EXPRESS OR IMPLIED,  INCLUDING, BUT NOT  LIMITED TO,
  WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR
  PURPOSE.  IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE  FOR ANY DAMAGES CAUSED  BY THE USE OR  THE INABILITY TO
  USE, OF THE FREETYPE PROJECT.

2. Redistribution
-----------------

  This  license  grants  a  worldwide, royalty-free,  perpetual  and
  irrevocable right  and license to use,  execute, perform, compile,
  display,  copy,   create  derivative  works   of,  distribute  and
  sublicense the  FreeType Project (in  both source and  object code
  forms)  and  derivative works  thereof  for  any  purpose; and  to
  authorize others  to exercise  some or all  of the  rights granted
  herein, subject to the following conditions:

    o Redistribution of  source code  must retain this  license file
      (`FTL.TXT') unaltered; any  additions, deletions or changes to
      the original  files must be clearly  indicated in accompanying
      documentation.   The  copyright   notices  of  the  unaltered,
      original  files must  be  preserved in  all  copies of  source
      files.

    o Redistribution in binary form must provide a  disclaimer  that
      states  that  the software is based in part of the work of the
      FreeType Team,  in  the  distribution  documentation.  We also
      encourage you to put an URL to the FreeType web page  in  your
      documentation, though this isn't mandatory.

  These conditions  apply to any  software derived from or  based on
  the FreeType Project,  not just the unmodified files.   If you use
  our work, you  must acknowledge us.  However, no  fee need be paid
  to us.

3. Advertising
--------------

  Neither the  FreeType authors and  contributors nor you  shall use
  the name of the  other for commercial, advertising, or promotional
  purposes without specific prior written permission.

  We suggest,  but do not require, that  you use one or  more of the
  following phrases to refer  to this software in your documentation
  or advertising  materials: `FreeType Project',  `FreeType Engine',
  `FreeType library', or `FreeType Distribution'.

  As  you have  not signed  this license,  you are  not  required to
  accept  it.   However,  as  the FreeType  Project  is  copyrighted
  material, only  this license, or  another one contracted  with the
  authors, grants you  the right to use, distribute,  and modify it.
  Therefore,  by  using,  distributing,  or modifying  the  FreeType
  Project, you indicate that you understand and accept all the terms
  of this license.

4. Contacts
-----------

  There are two mailing lists related to FreeType:

    o [email protected]

      Discusses general use and applications of FreeType, as well as
      future and  wanted additions to the  library and distribution.
      If  you are looking  for support,  start in  this list  if you
      haven't found anything to help you in the documentation.

    o [email protected]

      Discusses bugs,  as well  as engine internals,  design issues,
      specific licenses, porting, etc.

  Our home page can be found at

    https://www.freetype.org


--- end of FTL.TXT ---

---

### Third Party Freetype Src Docs GPLv2 (`third_party/freetype/src/docs/GPLv2.TXT`)

GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year  name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

---

### Third Party Freetype Src Docs VERSIONS (`third_party/freetype/src/docs/VERSIONS.TXT`)

Due  to our  use of  `libtool' to  generate and  install the  FreeType 2
libraries on  Unix systems, as  well as  other historical events,  it is
generally very  difficult to  know precisely which  release of  the font
engine is installed on a given system.

This file tries  to explain why and to document  ways to properly detect
FreeType on Unix.


1. Version and Release numbers
------------------------------

For each new  public release of FreeType 2, there  are generally *three*
distinct `version' numbers to consider:

  * The official FreeType 2 release number, like 2.3.1 or 2.4.10.

  * The libtool (and  Unix) specific version number,  like 13.0.7.  This
    is what `freetype-config --version' returns.

  * The platform-specific  shared object  number, used for  example when
    the library is installed as `/usr/lib/libfreetype.so.6.7.1'.

The platform-specific  number is, unsurprisingly,  platform-specific and
varies  with the  operating system  you are  using (several  variants of
Linux, FreeBSD,  Solaris, etc.).  You  should thus _never_ use  it, even
for simple tests.

The libtool-specific  number does  not equal the  release number  but is
tied to it.

The release number is available  at *compile* time through the following
macros defined in FT_FREETYPE_H:

  - FREETYPE_MAJOR: major release number
  - FREETYPE_MINOR: minor release number
  - FREETYPE_PATCH: patch release number

See below for a small autoconf fragment.

The  release  number   is  also  available  at   *runtime*  through  the
`FT_Library_Version' API.


2. History
----------

The  following   table  gives,  for   all  releases  since   2.4.0,  the
corresponding libtool number, as well  as the shared object number found
on _most_ systems, but not all of them:


    release     libtool     so
  -------------------------------
     2.9.1      22.1.16   6.16.1
     2.9.0      22.0.16   6.16.0
     2.8.1      21.0.15   6.15.0
     2.8.0      20.0.14   6.14.0
     2.7.1      19.0.13   6.13.0
     2.7.0      18.6.12   6.12.6
     2.6.5      18.5.12   6.12.5
     2.6.4      18.4.12   6.12.4
     2.6.3      18.3.12   6.12.3
     2.6.2      18.2.12   6.12.2
     2.6.1      18.1.12   6.12.1
     2.6.0      18.0.12   6.12.0
     2.5.5      17.4.11   6.11.4
     2.5.4      17.3.11   6.11.3
     2.5.3      17.2.11   6.11.2
     2.5.2      17.1.11   6.11.1
     2.5.1      17.0.11   6.11.0
     2.5.0      16.2.10   6.10.2
     2.4.12     16.1.10   6.10.1
     2.4.11     16.0.10   6.10.0
     2.4.10     15.0.9    6.9.0
     2.4.9      14.1.8    6.8.1
     2.4.8      14.0.8    6.8.0
     2.4.7      13.2.7    6.7.2
     2.4.6      13.1.7    6.7.1
     2.4.5      13.0.7    6.7.0
     2.4.4      12.2.6    6.6.2
     2.4.3      12.1.6    6.6.1
     2.4.2      12.0.6    6.6.0
     2.4.1      11.1.5    6.5.1
     2.4.0      11.0.5    6.5.0


3. Autoconf Code Fragment
-------------------------

Lars Clausen contributed the following autoconf fragment to detect which
version of  FreeType is  installed on  a system.  This  one tests  for a
version that  is at least 2.0.9;  you should change it  to check against
other release numbers.


  AC_MSG_CHECKING([whether FreeType version is 2.0.9 or higher])
  old_CPPFLAGS="$CPPFLAGS"
  CPPFLAGS=`freetype-config --cflags`
  AC_TRY_CPP([

#include <ft2build.h>
#include FT_FREETYPE_H
#if (FREETYPE_MAJOR*1000 + FREETYPE_MINOR)*1000 + FREETYPE_PATCH < 2000009
#error FreeType version too low.
#endif
  ],
  [AC_MSG_RESULT(yes)
   FREETYPE_LIBS=`freetype-config --libs`
   AC_SUBST(FREETYPE_LIBS)
   AC_DEFINE(HAVE_FREETYPE,1,[Define if you have the FreeType2 library])
   CPPFLAGS="$old_CPPFLAGS"],
  [AC_MSG_ERROR([Need FreeType library version 2.0.9 or higher])])

------------------------------------------------------------------------

Copyright 2002-2018 by
David Turner, Robert Wilhelm, and Werner Lemberg.

This  file is  part  of the  FreeType  project, and  may  only be  used,
modified,  and  distributed under  the  terms  of  the FreeType  project
license, LICENSE.TXT.  By continuing  to use, modify, or distribute this
file  you indicate that  you have  read the  license and  understand and
accept it fully.


--- end of VERSIONS.TXT ---

---

### Third Party Freetype Src Docs Formats (`third_party/freetype/src/docs/formats.txt`)

This  file contains  a list  of various  font formats.   It gives  the
reference document and whether it is supported in FreeType 2.

Table fields
------------

  wrapper format
    The format used to represent the font data.  In the table below it
    is  used only  if the  font format  differs.  Possible  values are

      SFNT  binary
      PFB   binary
      PS    a text header, followed by  binary or text data
      LZW   compressed with  either `gzip' or `compress'
      BZ2   compressed with `bzip2'.

  font format
    How the font is to be accessed, possibly after converting the file
    type and wrapper  format into a generic form.   Bitmap formats are
    `BDF',  `PCF', and  one form  of `WINFNT';  all others  are vector
    formats.   `PS' indicates  third-order,  `TT' second-order  Bézier
    curves.

  font type
    Sub-formats of the  font format.  `SBIT' and  `MACSBIT' are bitmap
    formats,  `MM' and  `VAR' support  optical axes.   `CFF2' supports
    optical axes also.

  glyph access
    If  not specified,  the glyph  access  is `standard'  to the  font
    format.   Values are  `CID' for  CID-keyed fonts,  `SYNTHETIC' for
    fonts that  are modified  versions of  other fonts  by means  of a
    transformation matrix, and  `TYPE_0' for PS fonts which  are to be
    accessed in a tree-like structure.

  FreeType driver
    The module in the FreeType library which handles the specific font
    format.  A missing  entry means that FreeType  doesn't support the
    font format (yet).


Notes
-----

  The  SFNT  container  format also  provides  `collections'  (usually
  having the file extension `.ttc'  or `.otc').  A collection contains
  multiple font faces that share some tables to avoid redundancy, thus
  reducing the file  size.  In FreeType, elements of  a collection can
  be accessed with a proper face index.

  Both  the GX  and the  OpenType 1.8  variation fonts  provide `named
  instances'.  FreeType  maps them to  face indices (they can  also be
  accessed with the standard MM interface).

  Other  font  formats  (not  using the  SFNT  wrapper)  also  provide
  multiple faces  within one  file; they are  marked with  an asterisk
  (`*') in the table below.

  FreeType can  be configured to  support Mac  files (on older  Mac OS
  versions, a `file' is stored as a data and a resource fork, this is,
  within two  separate data chunks).  If  a file can't be  opened as a
  font, FreeType then checks whether it  is a resource fork, trying to
  extract  the contained  font data  from  either a  `POST' or  `sfnt'
  resource.


Please  send additions  and/or  corrections to  [email protected]  or to  the
FreeType   developer's   list    at   [email protected]   (for
subscribers only).   If you can  provide a  font example for  a format
which isn't supported yet please send a mail too.


  wrapper font    font    glyph      FreeType reference
  format  format  type    access     driver   documents
 -----------------------------------------------------------------------------

  ---     BDF     ---     ---        bdf      5005.BDF_Spec.pdf, X11


  SFNT    PS      TYPE_1  ---        type1    Type 1 GX Font Format
                                              (for the Mac) [3]
  SFNT    PS      TYPE_1  CID        cid      5180.sfnt.pdf (for the Mac)
                                              [3]
  SFNT    PS      CFF     ---        cff      OT spec, 5176.CFF.pdf
                                              (`OTTO' format)
  SFNT    PS      CFF     CID        cff      OT spec, 5176.CFF.pdf
  SFNT    PS      CFF     SYNTHETIC  ---      OT spec, 5176.CFF.pdf
  SFNT    PS      CFF2    ---        cff      OT spec 1.8

  SFNT    TT      SBIT    ---        sfnt     XFree86 (bitmaps only;
                                              with `head' table)
  SFNT    TT      MACSBIT ---        sfnt     OT spec (for the Mac;
                                              bitmaps only; `bhed' table)
  SFNT    TT      ---     ---        truetype OT spec (`normal' TT font)
  SFNT    TT      VAR     ---        truetype GX spec (`?var' tables)
  SFNT    TT      VAR     ---        truetype OT spec 1.8
                                              (`?var' + `?VAR' tables)


  ---     PS      TYPE_1  ---        type1    T1_SPEC.pdf
                                              (PFA, Type 1 font resource)
  PFB     PS      TYPE_1  ---        type1    T1_SPEC.pdf,
                                              5040.Download_Fonts.pdf
                                              (`normal' Type 1 font)
  ---     PS      TYPE_1  CID        cid      PLRM.pdf (CID Font Type 0;
                                              Type 9 font)
  ---     PS      MM      ---        type1    5015.Type1_Supp.pdf
                                              (Multiple Masters)
  ---     PS      CFF     ---        cff      5176.CFF.pdf (`pure' CFF)
  ---     PS*     CFF     CID        cff      5176.CFF.pdf (`pure' CFF)
  ---     PS      CFF     SYNTHETIC  ---      5176.CFF.pdf (`pure' CFF)
  ---     PS      CFF/MM  ---        cff      old 5167.CFF.pdf (`pure' CFF)
                                              [3]
  ---     PS*     CFF/MM  CID        cff      old 5167.CFF.pdf (`pure' CFF)
                                              [3]
  ---     PS      CFF/MM  SYNTHETIC  ---      old 5167.CFF.pdf (`pure' CFF)
                                              [3]
  PS      PS      CFF     ---        ---      PLRM.pdf (Type 2) [1]
  PS      PS*     CFF     CID        ---      PLRM.pdf (Type 2) [1]
  PS      PS      CFF     SYNTHETIC  ---      PLRM.pdf (Type 2) [1]
  PS      PS      CFF/MM  ---        ---      PLRM.pdf (Type 2) [1]
  PS      PS*     CFF/MM  CID        ---      PLRM.pdf (Type 2) [1]
  PS      PS      CFF/MM  SYNTHETIC  ---      PLRM.pdf (Type 2) [1]
  ---     PS      ---     TYPE_0     ---      PLRM.pdf
  ---     PS      TYPE_3  ---        ---      PLRM.pdf (never supported)
  ---     PS      TYPE_3  CID        ---      PLRM.pdf (CID Font Type 1;
                                              Type 10 font; never supported)
  PS      PS      TYPE_14 ---        ---      PLRM.pdf (Chameleon font;
                                              Type 14 font; never supported?)
  ---     PS      TYPE_32 CID        ---      PLRM.pdf (CID Font Type 4;
                                              Type 32 font; never supported?)
  PS      TT      ---     ---        type42   5012.Type42_Spec.pdf
                                              (Type 42 font)
  PS      TT      ---     CID        ---      PLRM.pdf (CID Font Type 2;
                                              Type 11 font)


  ?       ?       CEF     ?          cff      ?


  ---     PCF     ---     ---        pcf      X11 [4]
  LZW     PCF     ---     ---        pcf      X11 [4]
  BZ2     PCF     ---     ---        pcf      X11 [4]


  ---     PFR*    PFR0    ---        pfr      [2]
  ---     PFR     PFR1    ---        ---      (undocumented, proprietary;
                                              probably never supported)


  ---     WINFNT* ---     ---        winfonts Windows developer's notes [5]
  ---     WINFNT  VECTOR  ---        ---      Windows developer's notes [5]


[1] Support should  be rather simple since this is  identical to `CFF'
    but in a PS wrapper.

[2] The  official  PFR  specification  is  no  longer  available,  but
    archive.org has archived it:

      https://web.archive.org/web/20091014062300/http://www.bitstream.com/font_rendering/products/truedoc/pfrspec.html
      https://web.archive.org/web/20081115152605/http://www.bitstream.com/font_rendering/pdfs/pfrspec1.3.pdf

    The syntax  of the  auxiliary data  is not  defined there,  but is
    partially defined in MHP 1.0.3 (also called ETSI TS 101812 V1.3.1)
    section 7.4.

      https://www.etsi.org/
      https://webapp.etsi.org/workprogram/Report_WorkItem.asp?WKI_ID=18799

[3] Support  is rudimentary  currently; some  tables or  data are  not
    loaded yet.

[4] See

      THE X WINDOW SYSTEM SERVER: X VERSION 11, RELEASE 5
      Elias Israel, Erik Fortune, Digital Press, 1992
      ISBN 1-55558-096-3

    for a specification given in Appendix D on pgs. 436-450.  However,
    this information might be out  of date; unfortunately, there is no
    PCF specification available online, and this book is out of print.
    George Williams deduced  the font format from the  X11 sources and
    documented it for his FontForge font editor:

      https://fontforge.github.io/pcf-format.html

[5] This is from MS Windows 3; see Microsoft's Knowledge Base article at

      https://support.microsoft.com/kb/65123

------------------------------------------------------------------------

Copyright 2004-2018 by
David Turner, Robert Wilhelm, and Werner Lemberg.

This  file is  part  of the  FreeType  project, and  may  only be  used,
modified,  and  distributed under  the  terms  of  the FreeType  project
license, LICENSE.TXT.  By continuing  to use, modify, or distribute this
file  you indicate that  you have  read the  license and  understand and
accept it fully.


--- end of formats.txt ---

Local Variables:
coding: utf-8
End:

---

### Third Party Freetype Src Docs Raster (`third_party/freetype/src/docs/raster.txt`)

How FreeType's rasterizer work

                          by David Turner

                        Revised 2007-Feb-01


This file  is an  attempt to explain  the internals of  the FreeType
rasterizer.  The  rasterizer is of  quite general purpose  and could
easily be integrated into other programs.


  I. Introduction

 II. Rendering Technology
     1. Requirements
     2. Profiles and Spans
        a. Sweeping the Shape
        b. Decomposing Outlines into Profiles
        c. The Render Pool
        d. Computing Profiles Extents
        e. Computing Profiles Coordinates
        f. Sweeping and Sorting the Spans


I. Introduction
===============

  A  rasterizer is  a library  in charge  of converting  a vectorial
  representation of a shape  into a bitmap.  The FreeType rasterizer
  has  been  originally developed  to  render  the  glyphs found  in
  TrueType  files, made  up  of segments  and second-order  Béziers.
  Meanwhile it has been extended to render third-order Bézier curves
  also.   This  document  is   an  explanation  of  its  design  and
  implementation.

  While  these explanations start  from the  basics, a  knowledge of
  common rasterization techniques is assumed.


II. Rendering Technology
========================

1. Requirements
---------------

  We  assume that  all scaling,  rotating, hinting,  etc.,  has been
  already done.  The glyph is thus  described by a list of points in
  the device space.

  - All point coordinates  are in the 26.6 fixed  float format.  The
    used orientation is:


       ^ y
       |         reference orientation
       |
       *----> x
      0


    `26.6' means  that 26 bits  are used for  the integer part  of a
    value   and  6   bits  are   used  for   the   fractional  part.
    Consequently, the `distance'  between two neighbouring pixels is
    64 `units' (1 unit = 1/64th of a pixel).

    Note  that, for  the rasterizer,  pixel centers  are  located at
    integer   coordinates.   The   TrueType   bytecode  interpreter,
    however, assumes that  the lower left edge of  a pixel (which is
    taken  to be  a square  with  a length  of 1  unit) has  integer
    coordinates.


        ^ y                                        ^ y
        |                                          |
        |            (1,1)                         |      (0.5,0.5)
        +-----------+                        +-----+-----+
        |           |                        |     |     |
        |           |                        |     |     |
        |           |                        |     o-----+-----> x
        |           |                        |   (0,0)   |
        |           |                        |           |
        o-----------+-----> x                +-----------+
      (0,0)                             (-0.5,-0.5)

   TrueType bytecode interpreter          FreeType rasterizer


    A pixel line in the target bitmap is called a `scanline'.

  - A  glyph  is  usually  made  of several  contours,  also  called
    `outlines'.  A contour is simply a closed curve that delimits an
    outer or inner region of the glyph.  It is described by a series
    of successive points of the points table.

    Each point  of the glyph  has an associated flag  that indicates
    whether  it is  `on' or  `off' the  curve.  Two  successive `on'
    points indicate a line segment joining the two points.

    One `off' point amidst two `on' points indicates a second-degree
    (conic)  Bézier parametric  arc, defined  by these  three points
    (the `off' point being the  control point, and the `on' ones the
    start and end points).  Similarly, a third-degree (cubic) Bézier
    curve  is described  by four  points (two  `off'  control points
    between two `on' points).

    Finally,  for  second-order curves  only,  two successive  `off'
    points  forces the  rasterizer to  create, during  rendering, an
    `on'  point amidst them,  at their  exact middle.   This greatly
    facilitates the  definition of  successive Bézier arcs.

  The parametric form of a second-order Bézier curve is:

      P(t) = (1-t)^2*P1 + 2*t*(1-t)*P2 + t^2*P3

      (P1 and P3 are the end points, P2 the control point.)

  The parametric form of a third-order Bézier curve is:

      P(t) = (1-t)^3*P1 + 3*t*(1-t)^2*P2 + 3*t^2*(1-t)*P3 + t^3*P4

      (P1 and P4 are the end points, P2 and P3 the control points.)

  For both formulae, t is a real number in the range [0..1].

  Note  that the rasterizer  does not  use these  formulae directly.
  They exhibit,  however, one very  useful property of  Bézier arcs:
  Each  point of  the curve  is a  weighted average  of  the control
  points.

  As all weights  are positive and always sum up  to 1, whatever the
  value  of t,  each arc  point lies  within the  triangle (polygon)
  defined by the arc's three (four) control points.

  In  the following,  only second-order  curves are  discussed since
  rasterization of third-order curves is completely identical.

  Here some samples for second-order curves.


                                        *            # on curve
                                                     * off curve
                                     __---__
        #-__                      _--       -_
            --__                _-            -
                --__           #               \
                    --__                        #
                        -#
                                 Two `on' points
         Two `on' points       and one `off' point
                                  between them

                      *
        #            __      Two `on' points with two `off'
         \          -  -     points between them. The point
          \        /    \    marked `0' is the middle of the
           -      0      \   `off' points, and is a `virtual
            -_  _-       #   on' point where the curve passes.
              --             It does not appear in the point
              *              list.


2. Profiles and Spans
---------------------

  The following is a basic explanation of the _kind_ of computations
  made  by  the   rasterizer  to  build  a  bitmap   from  a  vector
  representation.  Note  that the actual  implementation is slightly
  different, due to performance tuning and other factors.

  However, the following ideas remain  in the same category, and are
  more convenient to understand.


  a. Sweeping the Shape

    The best way to fill a shape is to decompose it into a number of
    simple  horizontal segments,  then turn  them on  in  the target
    bitmap.  These segments are called `spans'.

                __---__
             _--       -_
           _-            -
          -               \
         /                 \
        /                   \
       |                     \

                __---__         Example: filling a shape
             _----------_                with spans.
           _--------------
          ----------------\
         /-----------------\    This is typically done from the top
        /                   \   to the bottom of the shape, in a
       |           |         \  movement called a `sweep'.
                   V

                __---__
             _----------_
           _--------------
          ----------------\
         /-----------------\
        /-------------------\
       |---------------------\


    In  order  to draw  a  span,  the  rasterizer must  compute  its
    coordinates, which  are simply the x coordinates  of the shape's
    contours, taken on the y scanlines.


                   /---/    |---|   Note that there are usually
                  /---/     |---|   several spans per scanline.
        |        /---/      |---|
        |       /---/_______|---|   When rendering this shape to the
        V      /----------------|   current scanline y, we must
              /-----------------|   compute the x values of the
           a /----|         |---|   points a, b, c, and d.
      - - - *     * - - - - *   * - - y -
           /     / b       c|   |d


                   /---/    |---|
                  /---/     |---|  And then turn on the spans a-b
                 /---/      |---|  and c-d.
                /---/_______|---|
               /----------------|
              /-----------------|
           a /----|         |---|
      - - - ####### - - - - ##### - - y -
           /     / b       c|   |d


  b. Decomposing Outlines into Profiles

    For  each  scanline during  the  sweep,  we  need the  following
    information:

    o The  number of  spans on  the current  scanline, given  by the
      number of  shape points  intersecting the scanline  (these are
      the points a, b, c, and d in the above example).

    o The x coordinates of these points.

    x coordinates are  computed before the sweep, in  a phase called
    `decomposition' which converts the glyph into *profiles*.

    Put it simply, a `profile'  is a contour's portion that can only
    be either ascending or descending,  i.e., it is monotonic in the
    vertical direction (we also say  y-monotonic).  There is no such
    thing as a horizontal profile, as we shall see.

    Here are a few examples:


      this square
                                          1         2
         ---->----     is made of two
        |         |                       |         |
        |         |       profiles        |         |
        ^         v                       ^    +    v
        |         |                       |         |
        |         |                       |         |
         ----<----

                                         up        down


      this triangle

             P2                             1          2

             |\        is made of two       |         \
          ^  | \  \                         |          \
          | |   \  \      profiles         |            \      |
         |  |    \  v                  ^   |             \     |
           |      \                    |  |         +     \    v
           |       \                   |  |                \
        P1 ---___   \                     ---___            \
                 ---_\                          ---_         \
             <--__     P3                   up           down



      A more general contour can be made of more than two profiles:

              __     ^
             /  |   /  ___          /    |
            /   |     /   |        /     |       /     |
           |    |    /   /    =>  |      v      /     /
           |    |   |   |         |      |     ^     |
        ^  |    |___|   |  |      ^   +  |  +  |  +  v
        |  |           |   v      |                 |
           |           |          |           up    |
           |___________|          |    down         |

                <--               up              down


    Successive  profiles are  always joined  by  horizontal segments
    that are not part of the profiles themselves.

    For  the  rasterizer,  a  profile  is  simply  an  *array*  that
    associates  one  horizontal *pixel*  coordinate  to each  bitmap
    *scanline*  crossed  by  the  contour's section  containing  the
    profile.  Note that profiles are *oriented* up or down along the
    glyph's original flow orientation.

    In other graphics libraries, profiles are also called `edges' or
    `edgelists'.


  c. The Render Pool

    FreeType  has been designed  to be  able to  run well  on _very_
    light systems, including embedded systems with very few memory.

    A render pool  will be allocated once; the  rasterizer uses this
    pool for all  its needs by managing this  memory directly in it.
    The  algorithms that are  used for  profile computation  make it
    possible to use  the pool as a simple  growing heap.  This means
    that this  memory management is  actually quite easy  and faster
    than any kind of malloc()/free() combination.

    Moreover,  we'll see  later that  the rasterizer  is  able, when
    dealing with profiles too large  and numerous to lie all at once
    in  the render  pool, to  immediately decompose  recursively the
    rendering process  into independent sub-tasks,  each taking less
    memory to be performed (see `sub-banding' below).

    The  render pool doesn't  need to  be large.   A 4KByte  pool is
    enough for nearly all renditions, though nearly 100% slower than
    a more comfortable 16KByte or 32KByte pool (that was tested with
    complex glyphs at sizes over 500 pixels).


  d. Computing Profiles Extents

    Remember that a profile is an array, associating a _scanline_ to
    the x pixel coordinate of its intersection with a contour.

    Though it's not exactly how the FreeType rasterizer works, it is
    convenient  to think  that  we need  a  profile's height  before
    allocating it in the pool and computing its coordinates.

    The profile's height  is the number of scanlines  crossed by the
    y-monotonic section of a contour.  We thus need to compute these
    sections from  the vectorial description.  In order  to do that,
    we are  obliged to compute all  (local and global)  y extrema of
    the glyph (minima and maxima).


           P2             For instance, this triangle has only
                          two y-extrema, which are simply
           |\
           | \               P2.y  as a vertical maximum
          |   \              P3.y  as a vertical minimum
          |    \
         |      \            P1.y is not a vertical extremum (though
         |       \           it is a horizontal minimum, which we
      P1 ---___   \          don't need).
               ---_\
                     P3


    Note  that the  extrema are  expressed  in pixel  units, not  in
    scanlines.   The triangle's  height  is certainly  (P3.y-P2.y+1)
    pixel  units,   but  its  profiles'  heights   are  computed  in
    scanlines.  The exact conversion is simple:

      - min scanline = FLOOR  ( min y )
      - max scanline = CEILING( max y )

    A problem  arises with Bézier  Arcs.  While a segment  is always
    necessarily y-monotonic (i.e.,  flat, ascending, or descending),
    which makes extrema computations easy,  the ascent of an arc can
    vary between its control points.


                          P2
                         *
                                       # on curve
                                       * off curve
                   __-x--_
                _--       -_
          P1  _-            -          A non y-monotonic Bézier arc.
             #               \
                              -        The arc goes from P1 to P3.
                               \
                                \  P3
                                 #


    We first  need to be  able to easily detect  non-monotonic arcs,
    according to  their control points.  I will  state here, without
    proof, that the monotony condition can be expressed as:

      P1.y <= P2.y <= P3.y   for an ever-ascending arc

      P1.y >= P2.y >= P3.y   for an ever-descending arc

    with the special case of

      P1.y = P2.y = P3.y     where the arc is said to be `flat'.

    As  you can  see, these  conditions can  be very  easily tested.
    They are, however, extremely important, as any arc that does not
    satisfy them necessarily contains an extremum.

    Note  also that  a monotonic  arc can  contain an  extremum too,
    which is then one of its `on' points:


        P1           P2
          #---__   *         P1P2P3 is ever-descending, but P1
                -_           is an y-extremum.
                  -
           ---_    \
               ->   \
                     \  P3
                      #


    Let's go back to our previous example:


                          P2
                         *
                                       # on curve
                                       * off curve
                   __-x--_
                _--       -_
          P1  _-            -          A non-y-monotonic Bézier arc.
             #               \
                              -        Here we have
                               \              P2.y >= P1.y &&
                                \  P3         P2.y >= P3.y      (!)
                                 #


    We need to  compute the vertical maximum of this  arc to be able
    to compute a profile's height (the point marked by an `x').  The
    arc's equation indicates that  a direct computation is possible,
    but  we rely  on a  different technique,  which use  will become
    apparent soon.

    Bézier  arcs have  the  special property  of  being very  easily
    decomposed into two sub-arcs,  which are themselves Bézier arcs.
    Moreover, it is easy to prove that there is at most one vertical
    extremum on  each Bézier arc (for  second-degree curves; similar
    conditions can be found for third-order arcs).

    For instance,  the following arc  P1P2P3 can be  decomposed into
    two sub-arcs Q1Q2Q3 and R1R2R3:


                    P2
                   *
                                    # on  curve
                                    * off curve


                                    original Bézier arc P1P2P3.
                __---__
             _--       --_
           _-             -_
          -                 -
         /                   \
        /                     \
       #                       #
     P1                         P3



                    P2
                   *



                   Q3                 Decomposed into two subarcs
          Q2                R2        Q1Q2Q3 and R1R2R3
            *   __-#-__   *
             _--       --_
           _-       R1    -_          Q1 = P1         R3 = P3
          -                 -         Q2 = (P1+P2)/2  R2 = (P2+P3)/2
         /                   \
        /                     \            Q3 = R1 = (Q2+R2)/2
       #                       #
     Q1                         R3    Note that Q2, R2, and Q3=R1
                                      are on a single line which is
                                      tangent to the curve.


    We have then decomposed  a non-y-monotonic Bézier curve into two
    smaller sub-arcs.  Note that in the above drawing, both sub-arcs
    are monotonic, and that the extremum is then Q3=R1.  However, in
    a  more general  case,  only  one sub-arc  is  guaranteed to  be
    monotonic.  Getting back to our former example:


                    Q2
                   *

                   __-x--_ R1
                _--       #_
          Q1  _-        Q3  -   R2
             #               \ *
                              -
                               \
                                \  R3
                                 #


    Here, we see that,  though Q1Q2Q3 is still non-monotonic, R1R2R3
    is ever  descending: We  thus know that  it doesn't  contain the
    extremum.  We can then re-subdivide Q1Q2Q3 into two sub-arcs and
    go  on recursively,  stopping  when we  encounter two  monotonic
    subarcs, or when the subarcs become simply too small.

    We  will finally  find  the vertical  extremum.   Note that  the
    iterative process of finding an extremum is called `flattening'.


  e. Computing Profiles Coordinates

    Once we have the height of each profile, we are able to allocate
    it in the render pool.   The next task is to compute coordinates
    for each scanline.

    In  the case  of segments,  the computation  is straightforward,
    using  the  Euclidean   algorithm  (also  known  as  Bresenham).
    However, for Bézier arcs, the job is a little more complicated.

    We assume  that all Béziers that  are part of a  profile are the
    result of  flattening the curve,  which means that they  are all
    y-monotonic (ascending  or descending, and never  flat).  We now
    have  to compute the  intersections of  arcs with  the profile's
    scanlines.  One  way is  to use a  similar scheme  to flattening
    called `stepping'.


                                 Consider this arc, going from P1 to
      ---------------------      P3.  Suppose that we need to
                                 compute its intersections with the
                                 drawn scanlines.  As already
      ---------------------      mentioned this can be done
                                 directly, but the involved
          * P2         _---# P3  algorithm is far too slow.
      ------------- _--  --
                  _-
                _/               Instead, it is still possible to
      ---------/-----------      use the decomposition property in
              /                  the same recursive way, i.e.,
             |                   subdivide the arc into subarcs
      ------|--------------      until these get too small to cross
            |                    more than one scanline!
           |
      -----|---------------      This is very easily done using a
          |                      rasterizer-managed stack of
          |                      subarcs.
          # P1


  f. Sweeping and Sorting the Spans

    Once all our profiles have  been computed, we begin the sweep to
    build (and fill) the spans.

    As both the  TrueType and Type 1 specifications  use the winding
    fill  rule (but  with opposite  directions), we  place,  on each
    scanline, the present profiles in two separate lists.

    One  list,  called  the  `left'  one,  only  contains  ascending
    profiles, while  the other `right' list  contains the descending
    profiles.

    As  each glyph  is made  of  closed curves,  a simple  geometric
    property ensures that  the two lists contain the  same number of
    elements.

    Creating spans is thus straightforward:

    1. We sort each list in increasing horizontal order.

    2. We pair  each value of  the left list with  its corresponding
       value in the right list.


                   /     /  |   |          For example, we have here
                  /     /   |   |          four profiles.  Two of
                >/     /    |   |  |       them are ascending (1 &
              1//     /   ^ |   |  | 2     3), while the two others
              //     //  3| |   |  v       are descending (2 & 4).
              /     //4   | |   |          On the given scanline,
           a /     /<       |   |          the left list is (1,3),
      - - - *-----* - - - - *---* - - y -  and the right one is
           /     / b       c|   |d         (4,2) (sorted).

                                   There are then two spans, joining
                                   1 to 4 (i.e. a-b) and 3 to 2
                                   (i.e. c-d)!


    Sorting doesn't necessarily  take much time, as in  99 cases out
    of 100, the lists' order is  kept from one scanline to the next.
    We can  thus implement it  with two simple  singly-linked lists,
    sorted by a classic bubble-sort, which takes a minimum amount of
    time when the lists are already sorted.

    A  previous  version  of  the  rasterizer  used  more  elaborate
    structures, like arrays to  perform `faster' sorting.  It turned
    out that  this old scheme is  not faster than  the one described
    above.

    Once the spans  have been `created', we can  simply draw them in
    the target bitmap.

------------------------------------------------------------------------

Copyright 2003-2018 by
David Turner, Robert Wilhelm, and Werner Lemberg.

This  file  is  part  of the  FreeType  project, and may  only be  used,
modified,  and  distributed  under  the  terms of  the FreeType  project
license, LICENSE.TXT.   By continuing to use, modify, or distribute this
file you  indicate that  you have  read the  license and understand  and
accept it fully.


--- end of raster.txt ---

Local Variables:
coding: utf-8
End:

---

### V8 5 7 Testing Gmock Docs CheatSheet (`v8_5_7/testing/gmock/docs/CheatSheet.md`)

# Defining a Mock Class #

## Mocking a Normal Class ##

Given
```
class Foo {
  ...
  virtual ~Foo();
  virtual int GetSize() const = 0;
  virtual string Describe(const char* name) = 0;
  virtual string Describe(int type) = 0;
  virtual bool Process(Bar elem, int count) = 0;
};
```
(note that `~Foo()` **must** be virtual) we can define its mock as
```
#include "gmock/gmock.h"

class MockFoo : public Foo {
  MOCK_CONST_METHOD0(GetSize, int());
  MOCK_METHOD1(Describe, string(const char* name));
  MOCK_METHOD1(Describe, string(int type));
  MOCK_METHOD2(Process, bool(Bar elem, int count));
};
```

To create a "nice" mock object which ignores all uninteresting calls,
or a "strict" mock object, which treats them as failures:
```
NiceMock<MockFoo> nice_foo;     // The type is a subclass of MockFoo.
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
```

## Mocking a Class Template ##

To mock
```
template <typename Elem>
class StackInterface {
 public:
  ...
  virtual ~StackInterface();
  virtual int GetSize() const = 0;
  virtual void Push(const Elem& x) = 0;
};
```
(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
```
template <typename Elem>
class MockStack : public StackInterface<Elem> {
 public:
  ...
  MOCK_CONST_METHOD0_T(GetSize, int());
  MOCK_METHOD1_T(Push, void(const Elem& x));
};
```

## Specifying Calling Conventions for Mock Functions ##

If your mock function doesn't use the default calling convention, you
can specify it by appending `_WITH_CALLTYPE` to any of the macros
described in the previous two sections and supplying the calling
convention as the first argument to the macro. For example,
```
  MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
  MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
```
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.

# Using Mocks in Tests #

The typical flow is:
  1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
  1. Create the mock objects.
  1. Optionally, set the default actions of the mock objects.
  1. Set your expectations on the mock objects (How will they be called? What wil they do?).
  1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](../../googletest/) assertions.
  1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.

Here is an example:
```
using ::testing::Return;                            // #1

TEST(BarTest, DoesThis) {
  MockFoo foo;                                    // #2

  ON_CALL(foo, GetSize())                         // #3
      .WillByDefault(Return(1));
  // ... other default actions ...

  EXPECT_CALL(foo, Describe(5))                   // #4
      .Times(3)
      .WillRepeatedly(Return("Category 5"));
  // ... other expectations ...

  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
}                                                 // #6
```

# Setting Default Actions #

Google Mock has a **built-in default action** for any function that
returns `void`, `bool`, a numeric value, or a pointer.

To customize the default action for functions with return type `T` globally:
```
using ::testing::DefaultValue;

// Sets the default value to be returned. T must be CopyConstructible.
DefaultValue<T>::Set(value);
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
//   T MakeT();
DefaultValue<T>::SetFactory(&MakeT);
// ... use the mocks ...
// Resets the default value.
DefaultValue<T>::Clear();
```

To customize the default action for a particular method, use `ON_CALL()`:
```
ON_CALL(mock_object, method(matchers))
    .With(multi_argument_matcher)  ?
    .WillByDefault(action);
```

# Setting Expectations #

`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
called? What will it do?):
```
EXPECT_CALL(mock_object, method(matchers))
    .With(multi_argument_matcher)  ?
    .Times(cardinality)            ?
    .InSequence(sequences)         *
    .After(expectations)           *
    .WillOnce(action)              *
    .WillRepeatedly(action)        ?
    .RetiresOnSaturation();        ?
```

If `Times()` is omitted, the cardinality is assumed to be:

  * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
  * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
  * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.

A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.

# Matchers #

A **matcher** matches a _single_ argument.  You can use it inside
`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
directly:

| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
|:------------------------------|:----------------------------------------|
| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |

Built-in matchers (where `argument` is the function argument) are
divided into several categories:

## Wildcard ##
|`_`|`argument` can be any value of the correct type.|
|:--|:-----------------------------------------------|
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`.     |

## Generic Comparison ##

|`Eq(value)` or `value`|`argument == value`|
|:---------------------|:------------------|
|`Ge(value)`           |`argument >= value`|
|`Gt(value)`           |`argument > value` |
|`Le(value)`           |`argument <= value`|
|`Lt(value)`           |`argument < value` |
|`Ne(value)`           |`argument != value`|
|`IsNull()`            |`argument` is a `NULL` pointer (raw or smart).|
|`NotNull()`           |`argument` is a non-null pointer (raw or smart).|
|`Ref(variable)`       |`argument` is a reference to `variable`.|
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|

Except `Ref()`, these matchers make a _copy_ of `value` in case it's
modified or destructed later. If the compiler complains that `value`
doesn't have a public copy constructor, try wrap it in `ByRef()`,
e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
`non_copyable_value` is not changed afterwards, or the meaning of your
matcher will be changed.

## Floating-Point Matchers ##

|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
|:-------------------|:----------------------------------------------------------------------------------------------|
|`FloatEq(a_float)`  |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal.  |
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal.  |
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal.    |

The above matchers use ULP-based comparison (the same as used in
[Google Test](../../googletest/)). They
automatically pick a reasonable error bound based on the absolute
value of the expected value.  `DoubleEq()` and `FloatEq()` conform to
the IEEE standard, which requires comparing two NaNs for equality to
return false. The `NanSensitive*` version instead treats two NaNs as
equal, which is often what a user wants.

|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------|
|`FloatNear(a_float, max_abs_error)`  |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.  |
|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.  |
|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.    |

## String Matchers ##

The `argument` can be either a C string or a C++ string object:

|`ContainsRegex(string)`|`argument` matches the given regular expression.|
|:----------------------|:-----------------------------------------------|
|`EndsWith(suffix)`     |`argument` ends with string `suffix`.           |
|`HasSubstr(string)`    |`argument` contains `string` as a sub-string.   |
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
|`StartsWith(prefix)`   |`argument` starts with string `prefix`.         |
|`StrCaseEq(string)`    |`argument` is equal to `string`, ignoring case. |
|`StrCaseNe(string)`    |`argument` is not equal to `string`, ignoring case.|
|`StrEq(string)`        |`argument` is equal to `string`.                |
|`StrNe(string)`        |`argument` is not equal to `string`.            |

`ContainsRegex()` and `MatchesRegex()` use the regular expression
syntax defined
[here](../../googletest/docs/AdvancedGuide.md#regular-expression-syntax).
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
strings as well.

## Container Matchers ##

Most STL-style containers support `==`, so you can use
`Eq(expected_container)` or simply `expected_container` to match a
container exactly.   If you want to write the elements in-line,
match them more flexibly, or get more informative messages, you can use:

| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------|
| `Contains(e)`            | `argument` contains an element that matches `e`, which can be either a value or a matcher.                                       |
| `Each(e)`                | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher.                           |
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `IsEmpty()`              | `argument` is an empty container (`container.empty()`).                                                                          |
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
| `SizeIs(m)`              | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`.                                           |
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `WhenSorted(m)`          | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |

Notes:

  * These matchers can also match:
    1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
    1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
  * The array being matched may be multi-dimensional (i.e. its elements can be arrays).
  * `m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:

```
using ::testing::get;
MATCHER(FooEq, "") {
  return get<0>(arg).Equals(get<1>(arg));
}
...
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
```

## Member Matchers ##

|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
|`Key(e)`                 |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
|`Pair(m1, m2)`           |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.                                                |
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|

## Matching the Result of a Function or Functor ##

|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
|:---------------|:---------------------------------------------------------------------|

## Pointer Matchers ##

|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
|:-----------|:-----------------------------------------------------------------------------------------------|
|`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`.                 |

## Multiargument Matchers ##

Technically, all matchers match a _single_ value. A "multi-argument"
matcher is just one that matches a _tuple_. The following matchers can
be used to match a tuple `(x, y)`:

|`Eq()`|`x == y`|
|:-----|:-------|
|`Ge()`|`x >= y`|
|`Gt()`|`x > y` |
|`Le()`|`x <= y`|
|`Lt()`|`x < y` |
|`Ne()`|`x != y`|

You can use the following selectors to pick a subset of the arguments
(or reorder them) to participate in the matching:

|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
|:-----------|:-------------------------------------------------------------------|
|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|

## Composite Matchers ##

You can make a matcher from one or more other matchers:

|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
|:-----------------------|:---------------------------------------------------|
|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
|`Not(m)`                |`argument` doesn't match matcher `m`.               |

## Adapters for Matchers ##

|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
|:------------------|:--------------------------------------|
|`SafeMatcherCast<T>(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher<T>`. |
|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|

## Matchers as Predicates ##

|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.|
|:------------------|:---------------------------------------------------------------------------------------------|
|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.       |
|`Value(value, m)`  |evaluates to `true` if `value` matches `m`.                                                   |

## Defining Matchers ##

| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
|:-------------------------------------------------|:------------------------------------------------------|
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |

**Notes:**

  1. The `MATCHER*` macros cannot be used inside a function or class.
  1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
  1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.

## Matchers as Test Assertions ##

|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/Primer.md#assertions) if the value of `expression` doesn't match matcher `m`.|
|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------|
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.                                                          |

# Actions #

**Actions** specify what a mock function should do when invoked.

## Returning a Value ##

|`Return()`|Return from a `void` mock function.|
|:---------|:----------------------------------|
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type *at the time the expectation is set*, not when the action is executed.|
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
|`ReturnNull()`|Return a null pointer.             |
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
|`ReturnRef(variable)`|Return a reference to `variable`.  |
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|

## Side Effects ##

|`Assign(&variable, value)`|Assign `value` to variable.|
|:-------------------------|:--------------------------|
| `DeleteArg<N>()`         | Delete the `N`-th (0-based) argument, which must be a pointer. |
| `SaveArg<N>(pointer)`    | Save the `N`-th (0-based) argument to `*pointer`. |
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
| `SetArgReferee<N>(value)` |	Assign value to the variable referenced by the `N`-th (0-based) argument. |
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
|`Throw(exception)`        |Throws the given exception, which can be any copyable value. Available since v1.1.0.|

## Using a Function or a Functor as an Action ##

|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
|:----------|:-----------------------------------------------------------------------------------------------------------------|
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.                                  |
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.                       |
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.                                                        |
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|

The return value of the invoked function is used as the return value
of the action.

When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
```
  double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
  ...
  EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
```

In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
```
  InvokeArgument<2>(5, string("Hi"), ByRef(foo))
```
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.

## Default Action ##

|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
|:------------|:--------------------------------------------------------------------|

**Note:** due to technical reasons, `DoDefault()` cannot be used inside  a composite action - trying to do so will result in a run-time error.

## Composite Actions ##

|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
|`IgnoreResult(a)`       |Perform action `a` and ignore its result. `a` must not return void.                                                           |
|`WithArg<N>(a)`         |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it.                                         |
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it.                                      |
|`WithoutArgs(a)`        |Perform action `a` without any arguments.                                                                                     |

## Defining Actions ##

| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
|:--------------------------------------|:---------------------------------------------------------------------------------------|
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`.   |

The `ACTION*` macros cannot be used inside a function or class.

# Cardinalities #

These are used in `Times()` to specify how many times a mock function will be called:

|`AnyNumber()`|The function can be called any number of times.|
|:------------|:----------------------------------------------|
|`AtLeast(n)` |The call is expected at least `n` times.       |
|`AtMost(n)`  |The call is expected at most `n` times.        |
|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|

# Expectation Order #

By default, the expectations can be matched in _any_ order.  If some
or all expectations must be matched in a given order, there are two
ways to specify it.  They can be used either independently or
together.

## The After Clause ##

```
using ::testing::Expectation;
...
Expectation init_x = EXPECT_CALL(foo, InitX());
Expectation init_y = EXPECT_CALL(foo, InitY());
EXPECT_CALL(foo, Bar())
    .After(init_x, init_y);
```
says that `Bar()` can be called only after both `InitX()` and
`InitY()` have been called.

If you don't know how many pre-requisites an expectation has when you
write it, you can use an `ExpectationSet` to collect them:

```
using ::testing::ExpectationSet;
...
ExpectationSet all_inits;
for (int i = 0; i < element_count; i++) {
  all_inits += EXPECT_CALL(foo, InitElement(i));
}
EXPECT_CALL(foo, Bar())
    .After(all_inits);
```
says that `Bar()` can be called only after all elements have been
initialized (but we don't care about which elements get initialized
before the others).

Modifying an `ExpectationSet` after using it in an `.After()` doesn't
affect the meaning of the `.After()`.

## Sequences ##

When you have a long chain of sequential expectations, it's easier to
specify the order using **sequences**, which don't require you to given
each expectation in the chain a different name.  All expected
calls in the same sequence must occur in the order they are
specified.

```
using ::testing::Sequence;
Sequence s1, s2;
...
EXPECT_CALL(foo, Reset())
    .InSequence(s1, s2)
    .WillOnce(Return(true));
EXPECT_CALL(foo, GetSize())
    .InSequence(s1)
    .WillOnce(Return(1));
EXPECT_CALL(foo, Describe(A<const char*>()))
    .InSequence(s2)
    .WillOnce(Return("dummy"));
```
says that `Reset()` must be called before _both_ `GetSize()` _and_
`Describe()`, and the latter two can occur in any order.

To put many expectations in a sequence conveniently:
```
using ::testing::InSequence;
{
  InSequence dummy;

  EXPECT_CALL(...)...;
  EXPECT_CALL(...)...;
  ...
  EXPECT_CALL(...)...;
}
```
says that all expected calls in the scope of `dummy` must occur in
strict order. The name `dummy` is irrelevant.)

# Verifying and Resetting a Mock #

Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
```
using ::testing::Mock;
...
// Verifies and removes the expectations on mock_obj;
// returns true iff successful.
Mock::VerifyAndClearExpectations(&mock_obj);
...
// Verifies and removes the expectations on mock_obj;
// also removes the default actions set by ON_CALL();
// returns true iff successful.
Mock::VerifyAndClear(&mock_obj);
```

You can also tell Google Mock that a mock object can be leaked and doesn't
need to be verified:
```
Mock::AllowLeak(&mock_obj);
```

# Mock Classes #

Google Mock defines a convenient mock class template
```
class MockFunction<R(A1, ..., An)> {
 public:
  MOCK_METHODn(Call, R(A1, ..., An));
};
```
See this [recipe](CookBook.md#using-check-points) for one application of it.

# Flags #

| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
|:-------------------------------|:----------------------------------------------|
| `--gmock_verbose=LEVEL`        | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |

---

### V8 5 7 Testing Gmock Docs CookBook (`v8_5_7/testing/gmock/docs/CookBook.md`)

You can find recipes for using Google Mock here. If you haven't yet,
please read the [ForDummies](ForDummies.md) document first to make sure you understand
the basics.

**Note:** Google Mock lives in the `testing` name space. For
readability, it is recommended to write `using ::testing::Foo;` once in
your file before using the name `Foo` defined by Google Mock. We omit
such `using` statements in this page for brevity, but you should do it
in your own code.

# Creating Mock Classes #

## Mocking Private or Protected Methods ##

You must always put a mock method definition (`MOCK_METHOD*`) in a
`public:` section of the mock class, regardless of the method being
mocked being `public`, `protected`, or `private` in the base class.
This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
from outside of the mock class.  (Yes, C++ allows a subclass to change
the access level of a virtual function in the base class.)  Example:

```
class Foo {
 public:
  ...
  virtual bool Transform(Gadget* g) = 0;

 protected:
  virtual void Resume();

 private:
  virtual int GetTimeOut();
};

class MockFoo : public Foo {
 public:
  ...
  MOCK_METHOD1(Transform, bool(Gadget* g));

  // The following must be in the public section, even though the
  // methods are protected or private in the base class.
  MOCK_METHOD0(Resume, void());
  MOCK_METHOD0(GetTimeOut, int());
};
```

## Mocking Overloaded Methods ##

You can mock overloaded functions as usual. No special attention is required:

```
class Foo {
  ...

  // Must be virtual as we'll inherit from Foo.
  virtual ~Foo();

  // Overloaded on the types and/or numbers of arguments.
  virtual int Add(Element x);
  virtual int Add(int times, Element x);

  // Overloaded on the const-ness of this object.
  virtual Bar& GetBar();
  virtual const Bar& GetBar() const;
};

class MockFoo : public Foo {
  ...
  MOCK_METHOD1(Add, int(Element x));
  MOCK_METHOD2(Add, int(int times, Element x);

  MOCK_METHOD0(GetBar, Bar&());
  MOCK_CONST_METHOD0(GetBar, const Bar&());
};
```

**Note:** if you don't mock all versions of the overloaded method, the
compiler will give you a warning about some methods in the base class
being hidden. To fix that, use `using` to bring them in scope:

```
class MockFoo : public Foo {
  ...
  using Foo::Add;
  MOCK_METHOD1(Add, int(Element x));
  // We don't want to mock int Add(int times, Element x);
  ...
};
```

## Mocking Class Templates ##

To mock a class template, append `_T` to the `MOCK_*` macros:

```
template <typename Elem>
class StackInterface {
  ...
  // Must be virtual as we'll inherit from StackInterface.
  virtual ~StackInterface();

  virtual int GetSize() const = 0;
  virtual void Push(const Elem& x) = 0;
};

template <typename Elem>
class MockStack : public StackInterface<Elem> {
  ...
  MOCK_CONST_METHOD0_T(GetSize, int());
  MOCK_METHOD1_T(Push, void(const Elem& x));
};
```

## Mocking Nonvirtual Methods ##

Google Mock can mock non-virtual functions to be used in what we call _hi-perf
dependency injection_.

In this case, instead of sharing a common base class with the real
class, your mock class will be _unrelated_ to the real class, but
contain methods with the same signatures.  The syntax for mocking
non-virtual methods is the _same_ as mocking virtual methods:

```
// A simple packet stream class.  None of its members is virtual.
class ConcretePacketStream {
 public:
  void AppendPacket(Packet* new_packet);
  const Packet* GetPacket(size_t packet_number) const;
  size_t NumberOfPackets() const;
  ...
};

// A mock packet stream class.  It inherits from no other, but defines
// GetPacket() and NumberOfPackets().
class MockPacketStream {
 public:
  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
  ...
};
```

Note that the mock class doesn't define `AppendPacket()`, unlike the
real class. That's fine as long as the test doesn't need to call it.

Next, you need a way to say that you want to use
`ConcretePacketStream` in production code, and use `MockPacketStream`
in tests.  Since the functions are not virtual and the two classes are
unrelated, you must specify your choice at _compile time_ (as opposed
to run time).

One way to do it is to templatize your code that needs to use a packet
stream.  More specifically, you will give your code a template type
argument for the type of the packet stream.  In production, you will
instantiate your template with `ConcretePacketStream` as the type
argument.  In tests, you will instantiate the same template with
`MockPacketStream`.  For example, you may write:

```
template <class PacketStream>
void CreateConnection(PacketStream* stream) { ... }

template <class PacketStream>
class PacketReader {
 public:
  void ReadPackets(PacketStream* stream, size_t packet_num);
};
```

Then you can use `CreateConnection<ConcretePacketStream>()` and
`PacketReader<ConcretePacketStream>` in production code, and use
`CreateConnection<MockPacketStream>()` and
`PacketReader<MockPacketStream>` in tests.

```
  MockPacketStream mock_stream;
  EXPECT_CALL(mock_stream, ...)...;
  .. set more expectations on mock_stream ...
  PacketReader<MockPacketStream> reader(&mock_stream);
  ... exercise reader ...
```

## Mocking Free Functions ##

It's possible to use Google Mock to mock a free function (i.e. a
C-style function or a static method).  You just need to rewrite your
code to use an interface (abstract class).

Instead of calling a free function (say, `OpenFile`) directly,
introduce an interface for it and have a concrete subclass that calls
the free function:

```
class FileInterface {
 public:
  ...
  virtual bool Open(const char* path, const char* mode) = 0;
};

class File : public FileInterface {
 public:
  ...
  virtual bool Open(const char* path, const char* mode) {
    return OpenFile(path, mode);
  }
};
```

Your code should talk to `FileInterface` to open a file.  Now it's
easy to mock out the function.

This may seem much hassle, but in practice you often have multiple
related functions that you can put in the same interface, so the
per-function syntactic overhead will be much lower.

If you are concerned about the performance overhead incurred by
virtual functions, and profiling confirms your concern, you can
combine this with the recipe for [mocking non-virtual methods](#mocking-nonvirtual-methods).

## The Nice, the Strict, and the Naggy ##

If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
will print a warning about the "uninteresting call". The rationale is:

  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.

However, sometimes you may want to suppress all "uninteresting call"
warnings, while sometimes you may want the opposite, i.e. to treat all
of them as errors. Google Mock lets you make the decision on a
per-mock-object basis.

Suppose your test uses a mock class `MockFoo`:

```
TEST(...) {
  MockFoo mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

If a method of `mock_foo` other than `DoThis()` is called, it will be
reported by Google Mock as a warning. However, if you rewrite your
test to use `NiceMock<MockFoo>` instead, the warning will be gone,
resulting in a cleaner test output:

```
using ::testing::NiceMock;

TEST(...) {
  NiceMock<MockFoo> mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
wherever `MockFoo` is accepted.

It also works if `MockFoo`'s constructor takes some arguments, as
`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:

```
using ::testing::NiceMock;

TEST(...) {
  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

The usage of `StrictMock` is similar, except that it makes all
uninteresting calls failures:

```
using ::testing::StrictMock;

TEST(...) {
  StrictMock<MockFoo> mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...

  // The test will fail if a method of mock_foo other than DoThis()
  // is called.
}
```

There are some caveats though (I don't like them just as much as the
next guy, but sadly they are side effects of C++'s limitations):

  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
  1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict.  This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual.  In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class.  This rule is required for safety.  Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.)

Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort.

## Simplifying the Interface without Breaking Existing Code ##

Sometimes a method has a long list of arguments that is mostly
uninteresting. For example,

```
class LogSink {
 public:
  ...
  virtual void send(LogSeverity severity, const char* full_filename,
                    const char* base_filename, int line,
                    const struct tm* tm_time,
                    const char* message, size_t message_len) = 0;
};
```

This method's argument list is lengthy and hard to work with (let's
say that the `message` argument is not even 0-terminated). If we mock
it as is, using the mock will be awkward. If, however, we try to
simplify this interface, we'll need to fix all clients depending on
it, which is often infeasible.

The trick is to re-dispatch the method in the mock class:

```
class ScopedMockLog : public LogSink {
 public:
  ...
  virtual void send(LogSeverity severity, const char* full_filename,
                    const char* base_filename, int line, const tm* tm_time,
                    const char* message, size_t message_len) {
    // We are only interested in the log severity, full file name, and
    // log message.
    Log(severity, full_filename, std::string(message, message_len));
  }

  // Implements the mock method:
  //
  //   void Log(LogSeverity severity,
  //            const string& file_path,
  //            const string& message);
  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
                         const string& message));
};
```

By defining a new mock method with a trimmed argument list, we make
the mock class much more user-friendly.

## Alternative to Mocking Concrete Classes ##

Often you may find yourself using classes that don't implement
interfaces. In order to test your code that uses such a class (let's
call it `Concrete`), you may be tempted to make the methods of
`Concrete` virtual and then mock it.

Try not to do that.

Making a non-virtual function virtual is a big decision. It creates an
extension point where subclasses can tweak your class' behavior. This
weakens your control on the class because now it's harder to maintain
the class' invariants. You should make a function virtual only when
there is a valid reason for a subclass to override it.

Mocking concrete classes directly is problematic as it creates a tight
coupling between the class and the tests - any small change in the
class may invalidate your tests and make test maintenance a pain.

To avoid such problems, many programmers have been practicing "coding
to interfaces": instead of talking to the `Concrete` class, your code
would define an interface and talk to it. Then you implement that
interface as an adaptor on top of `Concrete`. In tests, you can easily
mock that interface to observe how your code is doing.

This technique incurs some overhead:

  * You pay the cost of virtual function calls (usually not a problem).
  * There is more abstraction for the programmers to learn.

However, it can also bring significant benefits in addition to better
testability:

  * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.
  * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.

Some people worry that if everyone is practicing this technique, they
will end up writing lots of redundant code. This concern is totally
understandable. However, there are two reasons why it may not be the
case:

  * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code.
  * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it.

You need to weigh the pros and cons carefully for your particular
problem, but I'd like to assure you that the Java community has been
practicing this for a long time and it's a proven effective technique
applicable in a wide variety of situations. :-)

## Delegating Calls to a Fake ##

Some times you have a non-trivial fake implementation of an
interface. For example:

```
class Foo {
 public:
  virtual ~Foo() {}
  virtual char DoThis(int n) = 0;
  virtual void DoThat(const char* s, int* p) = 0;
};

class FakeFoo : public Foo {
 public:
  virtual char DoThis(int n) {
    return (n > 0) ? '+' :
        (n < 0) ? '-' : '0';
  }

  virtual void DoThat(const char* s, int* p) {
    *p = strlen(s);
  }
};
```

Now you want to mock this interface such that you can set expectations
on it. However, you also want to use `FakeFoo` for the default
behavior, as duplicating it in the mock object is, well, a lot of
work.

When you define the mock class using Google Mock, you can have it
delegate its default action to a fake class you already have, using
this pattern:

```
using ::testing::_;
using ::testing::Invoke;

class MockFoo : public Foo {
 public:
  // Normal mock method definitions using Google Mock.
  MOCK_METHOD1(DoThis, char(int n));
  MOCK_METHOD2(DoThat, void(const char* s, int* p));

  // Delegates the default actions of the methods to a FakeFoo object.
  // This must be called *before* the custom ON_CALL() statements.
  void DelegateToFake() {
    ON_CALL(*this, DoThis(_))
        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
    ON_CALL(*this, DoThat(_, _))
        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
  }
 private:
  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
};
```

With that, you can use `MockFoo` in your tests as usual. Just remember
that if you don't explicitly set an action in an `ON_CALL()` or
`EXPECT_CALL()`, the fake will be called upon to do it:

```
using ::testing::_;

TEST(AbcTest, Xyz) {
  MockFoo foo;
  foo.DelegateToFake(); // Enables the fake for delegation.

  // Put your ON_CALL(foo, ...)s here, if any.

  // No action specified, meaning to use the default action.
  EXPECT_CALL(foo, DoThis(5));
  EXPECT_CALL(foo, DoThat(_, _));

  int n = 0;
  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
  EXPECT_EQ(2, n);
}
```

**Some tips:**

  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
  * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.).
  * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code.

Regarding the tip on mixing a mock and a fake, here's an example on
why it may be a bad sign: Suppose you have a class `System` for
low-level system operations. In particular, it does file and I/O
operations. And suppose you want to test how your code uses `System`
to do I/O, and you just want the file operations to work normally. If
you mock out the entire `System` class, you'll have to provide a fake
implementation for the file operation part, which suggests that
`System` is taking on too many roles.

Instead, you can define a `FileOps` interface and an `IOOps` interface
and split `System`'s functionalities into the two. Then you can mock
`IOOps` without mocking `FileOps`.

## Delegating Calls to a Real Object ##

When using testing doubles (mocks, fakes, stubs, and etc), sometimes
their behaviors will differ from those of the real objects. This
difference could be either intentional (as in simulating an error such
that you can test the error handling code) or unintentional. If your
mocks have different behaviors than the real objects by mistake, you
could end up with code that passes the tests but fails in production.

You can use the _delegating-to-real_ technique to ensure that your
mock has the same behavior as the real object while retaining the
ability to validate calls. This technique is very similar to the
delegating-to-fake technique, the difference being that we use a real
object instead of a fake. Here's an example:

```
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;

class MockFoo : public Foo {
 public:
  MockFoo() {
    // By default, all calls are delegated to the real object.
    ON_CALL(*this, DoThis())
        .WillByDefault(Invoke(&real_, &Foo::DoThis));
    ON_CALL(*this, DoThat(_))
        .WillByDefault(Invoke(&real_, &Foo::DoThat));
    ...
  }
  MOCK_METHOD0(DoThis, ...);
  MOCK_METHOD1(DoThat, ...);
  ...
 private:
  Foo real_;
};
...

  MockFoo mock;

  EXPECT_CALL(mock, DoThis())
      .Times(3);
  EXPECT_CALL(mock, DoThat("Hi"))
      .Times(AtLeast(1));
  ... use mock in test ...
```

With this, Google Mock will verify that your code made the right calls
(with the right arguments, in the right order, called the right number
of times, etc), and a real object will answer the calls (so the
behavior will be the same as in production). This gives you the best
of both worlds.

## Delegating Calls to a Parent Class ##

Ideally, you should code to interfaces, whose methods are all pure
virtual. In reality, sometimes you do need to mock a virtual method
that is not pure (i.e, it already has an implementation). For example:

```
class Foo {
 public:
  virtual ~Foo();

  virtual void Pure(int n) = 0;
  virtual int Concrete(const char* str) { ... }
};

class MockFoo : public Foo {
 public:
  // Mocking a pure method.
  MOCK_METHOD1(Pure, void(int n));
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
  MOCK_METHOD1(Concrete, int(const char* str));
};
```

Sometimes you may want to call `Foo::Concrete()` instead of
`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
action, or perhaps your test doesn't need to mock `Concrete()` at all
(but it would be oh-so painful to have to define a new mock class
whenever you don't need to mock one of its methods).

The trick is to leave a back door in your mock class for accessing the
real methods in the base class:

```
class MockFoo : public Foo {
 public:
  // Mocking a pure method.
  MOCK_METHOD1(Pure, void(int n));
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
  MOCK_METHOD1(Concrete, int(const char* str));

  // Use this to call Concrete() defined in Foo.
  int FooConcrete(const char* str) { return Foo::Concrete(str); }
};
```

Now, you can call `Foo::Concrete()` inside an action by:

```
using ::testing::_;
using ::testing::Invoke;
...
  EXPECT_CALL(foo, Concrete(_))
      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
```

or tell the mock object that you don't want to mock `Concrete()`:

```
using ::testing::Invoke;
...
  ON_CALL(foo, Concrete(_))
      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
```

(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
that, `MockFoo::Concrete()` will be called (and cause an infinite
recursion) since `Foo::Concrete()` is virtual. That's just how C++
works.)

# Using Matchers #

## Matching Argument Values Exactly ##

You can specify exactly which arguments a mock method is expecting:

```
using ::testing::Return;
...
  EXPECT_CALL(foo, DoThis(5))
      .WillOnce(Return('a'));
  EXPECT_CALL(foo, DoThat("Hello", bar));
```

## Using Simple Matchers ##

You can use matchers to match arguments that have a certain property:

```
using ::testing::Ge;
using ::testing::NotNull;
using ::testing::Return;
...
  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
      .WillOnce(Return('a'));
  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
  // The second argument must not be NULL.
```

A frequently used matcher is `_`, which matches anything:

```
using ::testing::_;
using ::testing::NotNull;
...
  EXPECT_CALL(foo, DoThat(_, NotNull()));
```

## Combining Matchers ##

You can build complex matchers from existing ones using `AllOf()`,
`AnyOf()`, and `Not()`:

```
using ::testing::AllOf;
using ::testing::Gt;
using ::testing::HasSubstr;
using ::testing::Ne;
using ::testing::Not;
...
  // The argument must be > 5 and != 10.
  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
                                Ne(10))));

  // The first argument must not contain sub-string "blah".
  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
                          NULL));
```

## Casting Matchers ##

Google Mock matchers are statically typed, meaning that the compiler
can catch your mistake if you use a matcher of the wrong type (for
example, if you use `Eq(5)` to match a `string` argument). Good for
you!

Sometimes, however, you know what you're doing and want the compiler
to give you some slack. One example is that you have a matcher for
`long` and the argument you want to match is `int`. While the two
types aren't exactly the same, there is nothing really wrong with
using a `Matcher<long>` to match an `int` - after all, we can first
convert the `int` argument to a `long` before giving it to the
matcher.

To support this need, Google Mock gives you the
`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
type `m` accepts):

  1. Type `T` can be implicitly cast to type `U`;
  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).

The code won't compile if any of these conditions isn't met.

Here's one example:

```
using ::testing::SafeMatcherCast;

// A base class and a child class.
class Base { ... };
class Derived : public Base { ... };

class MockFoo : public Foo {
 public:
  MOCK_METHOD1(DoThis, void(Derived* derived));
};
...

  MockFoo foo;
  // m is a Matcher<Base*> we got from somewhere.
  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
```

If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
as long as you can `static_cast` type `T` to type `U`.

`MatcherCast` essentially lets you bypass C++'s type system
(`static_cast` isn't always safe as it could throw away information,
for example), so be careful not to misuse/abuse it.

## Selecting Between Overloaded Functions ##

If you expect an overloaded function to be called, the compiler may
need some help on which overloaded version it is.

To disambiguate functions overloaded on the const-ness of this object,
use the `Const()` argument wrapper.

```
using ::testing::ReturnRef;

class MockFoo : public Foo {
  ...
  MOCK_METHOD0(GetBar, Bar&());
  MOCK_CONST_METHOD0(GetBar, const Bar&());
};
...

  MockFoo foo;
  Bar bar1, bar2;
  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
      .WillOnce(ReturnRef(bar1));
  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
      .WillOnce(ReturnRef(bar2));
```

(`Const()` is defined by Google Mock and returns a `const` reference
to its argument.)

To disambiguate overloaded functions with the same number of arguments
but different argument types, you may need to specify the exact type
of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
etc):

```
using ::testing::An;
using ::testing::Lt;
using ::testing::Matcher;
using ::testing::TypedEq;

class MockPrinter : public Printer {
 public:
  MOCK_METHOD1(Print, void(int n));
  MOCK_METHOD1(Print, void(char c));
};

TEST(PrinterTest, Print) {
  MockPrinter printer;

  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);

  printer.Print(3);
  printer.Print(6);
  printer.Print('a');
}
```

## Performing Different Actions Based on the Arguments ##

When a mock method is called, the _last_ matching expectation that's
still active will be selected (think "newer overrides older"). So, you
can make a method do different things depending on its argument values
like this:

```
using ::testing::_;
using ::testing::Lt;
using ::testing::Return;
...
  // The default case.
  EXPECT_CALL(foo, DoThis(_))
      .WillRepeatedly(Return('b'));

  // The more specific case.
  EXPECT_CALL(foo, DoThis(Lt(5)))
      .WillRepeatedly(Return('a'));
```

Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
be returned; otherwise `'b'` will be returned.

## Matching Multiple Arguments as a Whole ##

Sometimes it's not enough to match the arguments individually. For
example, we may want to say that the first argument must be less than
the second argument. The `With()` clause allows us to match
all arguments of a mock function as a whole. For example,

```
using ::testing::_;
using ::testing::Lt;
using ::testing::Ne;
...
  EXPECT_CALL(foo, InRange(Ne(0), _))
      .With(Lt());
```

says that the first argument of `InRange()` must not be 0, and must be
less than the second argument.

The expression inside `With()` must be a matcher of type
`Matcher< ::testing::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
types of the function arguments.

You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
than `.With(Lt())`.

You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
(as a tuple) against `m`. For example,

```
using ::testing::_;
using ::testing::AllOf;
using ::testing::Args;
using ::testing::Lt;
...
  EXPECT_CALL(foo, Blah(_, _, _))
      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
```

says that `Blah()` will be called with arguments `x`, `y`, and `z` where
`x < y < z`.

As a convenience and example, Google Mock provides some matchers for
2-tuples, including the `Lt()` matcher above. See the [CheatSheet](CheatSheet.md) for
the complete list.

Note that if you want to pass the arguments to a predicate of your own
(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be
written to take a `::testing::tuple` as its argument; Google Mock will pass the `n` selected arguments as _one_ single tuple to the predicate.

## Using Matchers as Predicates ##

Have you noticed that a matcher is just a fancy predicate that also
knows how to describe itself? Many existing algorithms take predicates
as arguments (e.g. those defined in STL's `<algorithm>` header), and
it would be a shame if Google Mock matchers are not allowed to
participate.

Luckily, you can use a matcher where a unary predicate functor is
expected by wrapping it inside the `Matches()` function. For example,

```
#include <algorithm>
#include <vector>

std::vector<int> v;
...
// How many elements in v are >= 10?
const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
```

Since you can build complex matchers from simpler ones easily using
Google Mock, this gives you a way to conveniently construct composite
predicates (doing the same using STL's `<functional>` header is just
painful). For example, here's a predicate that's satisfied by any
number that is >= 0, <= 100, and != 50:

```
Matches(AllOf(Ge(0), Le(100), Ne(50)))
```

## Using Matchers in Google Test Assertions ##

Since matchers are basically predicates that also know how to describe
themselves, there is a way to take advantage of them in
[Google Test](../../googletest/) assertions. It's
called `ASSERT_THAT` and `EXPECT_THAT`:

```
  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
  EXPECT_THAT(value, matcher);  // The non-fatal version.
```

For example, in a Google Test test you can write:

```
#include "gmock/gmock.h"

using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::MatchesRegex;
using ::testing::StartsWith;
...

  EXPECT_THAT(Foo(), StartsWith("Hello"));
  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
```

which (as you can probably guess) executes `Foo()`, `Bar()`, and
`Baz()`, and verifies that:

  * `Foo()` returns a string that starts with `"Hello"`.
  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
  * `Baz()` returns a number in the range [5, 10].

The nice thing about these macros is that _they read like
English_. They generate informative messages too. For example, if the
first `EXPECT_THAT()` above fails, the message will be something like:

```
Value of: Foo()
  Actual: "Hi, world!"
Expected: starts with "Hello"
```

**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
[Hamcrest](https://github.com/hamcrest/) project, which adds
`assertThat()` to JUnit.

## Using Predicates as Matchers ##

Google Mock provides a built-in set of matchers. In case you find them
lacking, you can use an arbitray unary predicate function or functor
as a matcher - as long as the predicate accepts a value of the type
you want. You do this by wrapping the predicate inside the `Truly()`
function, for example:

```
using ::testing::Truly;

int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
...

  // Bar() must be called with an even number.
  EXPECT_CALL(foo, Bar(Truly(IsEven)));
```

Note that the predicate function / functor doesn't have to return
`bool`. It works as long as the return value can be used as the
condition in statement `if (condition) ...`.

## Matching Arguments that Are Not Copyable ##

When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
away a copy of `bar`. When `Foo()` is called later, Google Mock
compares the argument to `Foo()` with the saved copy of `bar`. This
way, you don't need to worry about `bar` being modified or destroyed
after the `EXPECT_CALL()` is executed. The same is true when you use
matchers like `Eq(bar)`, `Le(bar)`, and so on.

But what if `bar` cannot be copied (i.e. has no copy constructor)? You
could define your own matcher function and use it with `Truly()`, as
the previous couple of recipes have shown. Or, you may be able to get
away from it if you can guarantee that `bar` won't be changed after
the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
save a reference to `bar`, instead of a copy of it. Here's how:

```
using ::testing::Eq;
using ::testing::ByRef;
using ::testing::Lt;
...
  // Expects that Foo()'s argument == bar.
  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));

  // Expects that Foo()'s argument < bar.
  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
```

Remember: if you do this, don't change `bar` after the
`EXPECT_CALL()`, or the result is undefined.

## Validating a Member of an Object ##

Often a mock function takes a reference to object as an argument. When
matching the argument, you may not want to compare the entire object
against a fixed object, as that may be over-specification. Instead,
you may need to validate a certain member variable or the result of a
certain getter method of the object. You can do this with `Field()`
and `Property()`. More specifically,

```
Field(&Foo::bar, m)
```

is a matcher that matches a `Foo` object whose `bar` member variable
satisfies matcher `m`.

```
Property(&Foo::baz, m)
```

is a matcher that matches a `Foo` object whose `baz()` method returns
a value that satisfies matcher `m`.

For example:

> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
|:-----------------------------|:-----------------------------------|
> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |

Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
argument and be declared as `const`.

BTW, `Field()` and `Property()` can also match plain pointers to
objects. For instance,

```
Field(&Foo::number, Ge(3))
```

matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
the match will always fail regardless of the inner matcher.

What if you want to validate more than one members at the same time?
Remember that there is `AllOf()`.

## Validating the Value Pointed to by a Pointer Argument ##

C++ functions often take pointers as arguments. You can use matchers
like `IsNull()`, `NotNull()`, and other comparison matchers to match a
pointer, but what if you want to make sure the value _pointed to_ by
the pointer, instead of the pointer itself, has a certain property?
Well, you can use the `Pointee(m)` matcher.

`Pointee(m)` matches a pointer iff `m` matches the value the pointer
points to. For example:

```
using ::testing::Ge;
using ::testing::Pointee;
...
  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
```

expects `foo.Bar()` to be called with a pointer that points to a value
greater than or equal to 3.

One nice thing about `Pointee()` is that it treats a `NULL` pointer as
a match failure, so you can write `Pointee(m)` instead of

```
  AllOf(NotNull(), Pointee(m))
```

without worrying that a `NULL` pointer will crash your test.

Also, did we tell you that `Pointee()` works with both raw pointers
**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
etc)?

What if you have a pointer to pointer? You guessed it - you can use
nested `Pointee()` to probe deeper inside the value. For example,
`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
that points to a number less than 3 (what a mouthful...).

## Testing a Certain Property of an Object ##

Sometimes you want to specify that an object argument has a certain
property, but there is no existing matcher that does this. If you want
good error messages, you should define a matcher. If you want to do it
quick and dirty, you could get away with writing an ordinary function.

Let's say you have a mock function that takes an object of type `Foo`,
which has an `int bar()` method and an `int baz()` method, and you
want to constrain that the argument's `bar()` value plus its `baz()`
value is a given number. Here's how you can define a matcher to do it:

```
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;

class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
 public:
  explicit BarPlusBazEqMatcher(int expected_sum)
      : expected_sum_(expected_sum) {}

  virtual bool MatchAndExplain(const Foo& foo,
                               MatchResultListener* listener) const {
    return (foo.bar() + foo.baz()) == expected_sum_;
  }

  virtual void DescribeTo(::std::ostream* os) const {
    *os << "bar() + baz() equals " << expected_sum_;
  }

  virtual void DescribeNegationTo(::std::ostream* os) const {
    *os << "bar() + baz() does not equal " << expected_sum_;
  }
 private:
  const int expected_sum_;
};

inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
}

...

  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
```

## Matching Containers ##

Sometimes an STL container (e.g. list, vector, map, ...) is passed to
a mock function and you may want to validate it. Since most STL
containers support the `==` operator, you can write
`Eq(expected_container)` or simply `expected_container` to match a
container exactly.

Sometimes, though, you may want to be more flexible (for example, the
first element must be an exact match, but the second element can be
any positive number, and so on). Also, containers used in tests often
have a small number of elements, and having to define the expected
container out-of-line is a bit of a hassle.

You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in
such cases:

```
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Gt;
...

  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
...

  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
```

The above matcher says that the container must have 4 elements, which
must be 1, greater than 0, anything, and 5 respectively.

If you instead write:

```
using ::testing::_;
using ::testing::Gt;
using ::testing::UnorderedElementsAre;
...

  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
...

  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));
```

It means that the container must have 4 elements, which under some
permutation must be 1, greater than 0, anything, and 5 respectively.

`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0
to 10 arguments. If more are needed, you can place them in a C-style
array and use `ElementsAreArray()` or `UnorderedElementsAreArray()`
instead:

```
using ::testing::ElementsAreArray;
...

  // ElementsAreArray accepts an array of element values.
  const int expected_vector1[] = { 1, 5, 2, 4, ... };
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));

  // Or, an array of element matchers.
  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
```

In case the array needs to be dynamically created (and therefore the
array size cannot be inferred by the compiler), you can give
`ElementsAreArray()` an additional argument to specify the array size:

```
using ::testing::ElementsAreArray;
...
  int* const expected_vector3 = new int[count];
  ... fill expected_vector3 with values ...
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
```

**Tips:**

  * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
  * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers.
  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).

## Sharing Matchers ##

Under the hood, a Google Mock matcher object consists of a pointer to
a ref-counted implementation object. Copying matchers is allowed and
very efficient, as only the pointer is copied. When the last matcher
that references the implementation object dies, the implementation
object will be deleted.

Therefore, if you have some complex matcher that you want to use again
and again, there is no need to build it everytime. Just assign it to a
matcher variable and use that variable repeatedly! For example,

```
  Matcher<int> in_range = AllOf(Gt(5), Le(10));
  ... use in_range as a matcher in multiple EXPECT_CALLs ...
```

# Setting Expectations #

## Knowing When to Expect ##

`ON_CALL` is likely the single most under-utilized construct in Google Mock.

There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too).

Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints.

This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests?

The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed.

Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself.

So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them).

If you are bothered by the "Uninteresting mock function call" message printed when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test that's a pain to maintain.

## Ignoring Uninteresting Calls ##

If you are not interested in how a mock method is called, just don't
say anything about it. In this case, if the method is ever called,
Google Mock will perform its default action to allow the test program
to continue. If you are not happy with the default action taken by
Google Mock, you can override it using `DefaultValue<T>::Set()`
(described later in this document) or `ON_CALL()`.

Please note that once you expressed interest in a particular mock
method (via `EXPECT_CALL()`), all invocations to it must match some
expectation. If this function is called but the arguments don't match
any `EXPECT_CALL()` statement, it will be an error.

## Disallowing Unexpected Calls ##

If a mock method shouldn't be called at all, explicitly say so:

```
using ::testing::_;
...
  EXPECT_CALL(foo, Bar(_))
      .Times(0);
```

If some calls to the method are allowed, but the rest are not, just
list all the expected calls:

```
using ::testing::AnyNumber;
using ::testing::Gt;
...
  EXPECT_CALL(foo, Bar(5));
  EXPECT_CALL(foo, Bar(Gt(10)))
      .Times(AnyNumber());
```

A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
statements will be an error.

## Understanding Uninteresting vs Unexpected Calls ##

_Uninteresting_ calls and _unexpected_ calls are different concepts in Google Mock. _Very_ different.

A call `x.Y(...)` is **uninteresting** if there's _not even a single_ `EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the `x.Y()` method at all, as evident in that the test doesn't care to say anything about it.

A call `x.Y(...)` is **unexpected** if there are some `EXPECT_CALL(x, Y(...))s` set, but none of them matches the call. Put another way, the test is interested in the `x.Y()` method (therefore it _explicitly_ sets some `EXPECT_CALL` to verify how it's called); however, the verification fails as the test doesn't expect this particular call to happen.

**An unexpected call is always an error,** as the code under test doesn't behave the way the test expects it to behave.

**By default, an uninteresting call is not an error,** as it violates no constraint specified by the test. (Google Mock's philosophy is that saying nothing means there is no constraint.) However, it leads to a warning, as it _might_ indicate a problem (e.g. the test author might have forgotten to specify a constraint).

In Google Mock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or "strict". How does this affect uninteresting calls and unexpected calls?

A **nice mock** suppresses uninteresting call warnings. It is less chatty than the default mock, but otherwise is the same. If a test fails with a default mock, it will also fail using a nice mock instead. And vice versa. Don't expect making a mock nice to change the test's result.

A **strict mock** turns uninteresting call warnings into errors. So making a mock strict may change the test's result.

Let's look at an example:

```
TEST(...) {
  NiceMock<MockDomainRegistry> mock_registry;
  EXPECT_CALL(mock_registry, GetDomainOwner("google.com"))
          .WillRepeatedly(Return("Larry Page"));

  // Use mock_registry in code under test.
  ... &mock_registry ...
}
```

The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have `"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it will be an unexpected call, and thus an error. Having a nice mock doesn't change the severity of an unexpected call.

So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`:

```
  EXPECT_CALL(mock_registry, GetDomainOwner(_))
        .Times(AnyNumber());  // catches all other calls to this method.
  EXPECT_CALL(mock_registry, GetDomainOwner("google.com"))
        .WillRepeatedly(Return("Larry Page"));
```

Remember that `_` is the wildcard matcher that matches anything. With this, if `GetDomainOwner("google.com")` is called, it will do what the second `EXPECT_CALL` says; if it is called with a different argument, it will do what the first `EXPECT_CALL` says.

Note that the order of the two `EXPECT_CALLs` is important, as a newer `EXPECT_CALL` takes precedence over an older one.

For more on uninteresting calls, nice mocks, and strict mocks, read ["The Nice, the Strict, and the Naggy"](#the-nice-the-strict-and-the-naggy).

## Expecting Ordered Calls ##

Although an `EXPECT_CALL()` statement defined earlier takes precedence
when Google Mock tries to match a function call with an expectation,
by default calls don't have to happen in the order `EXPECT_CALL()`
statements are written. For example, if the arguments match the
matchers in the third `EXPECT_CALL()`, but not those in the first two,
then the third expectation will be used.

If you would rather have all calls occur in the order of the
expectations, put the `EXPECT_CALL()` statements in a block where you
define a variable of type `InSequence`:

```
  using ::testing::_;
  using ::testing::InSequence;

  {
    InSequence s;

    EXPECT_CALL(foo, DoThis(5));
    EXPECT_CALL(bar, DoThat(_))
        .Times(2);
    EXPECT_CALL(foo, DoThis(6));
  }
```

In this example, we expect a call to `foo.DoThis(5)`, followed by two
calls to `bar.DoThat()` where the argument can be anything, which are
in turn followed by a call to `foo.DoThis(6)`. If a call occurred
out-of-order, Google Mock will report an error.

## Expecting Partially Ordered Calls ##

Sometimes requiring everything to occur in a predetermined order can
lead to brittle tests. For example, we may care about `A` occurring
before both `B` and `C`, but aren't interested in the relative order
of `B` and `C`. In this case, the test should reflect our real intent,
instead of being overly constraining.

Google Mock allows you to impose an arbitrary DAG (directed acyclic
graph) on the calls. One way to express the DAG is to use the
[After](CheatSheet.md#the-after-clause) clause of `EXPECT_CALL`.

Another way is via the `InSequence()` clause (not the same as the
`InSequence` class), which we borrowed from jMock 2. It's less
flexible than `After()`, but more convenient when you have long chains
of sequential calls, as it doesn't require you to come up with
different names for the expectations in the chains.  Here's how it
works:

If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
edge from node A to node B wherever A must occur before B, we can get
a DAG. We use the term "sequence" to mean a directed path in this
DAG. Now, if we decompose the DAG into sequences, we just need to know
which sequences each `EXPECT_CALL()` belongs to in order to be able to
reconstruct the orginal DAG.

So, to specify the partial order on the expectations we need to do two
things: first to define some `Sequence` objects, and then for each
`EXPECT_CALL()` say which `Sequence` objects it is part
of. Expectations in the same sequence must occur in the order they are
written. For example,

```
  using ::testing::Sequence;

  Sequence s1, s2;

  EXPECT_CALL(foo, A())
      .InSequence(s1, s2);
  EXPECT_CALL(bar, B())
      .InSequence(s1);
  EXPECT_CALL(bar, C())
      .InSequence(s2);
  EXPECT_CALL(foo, D())
      .InSequence(s2);
```

specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
C -> D`):

```
       +---> B
       |
  A ---|
       |
       +---> C ---> D
```

This means that A must occur before B and C, and C must occur before
D. There's no restriction about the order other than these.

## Controlling When an Expectation Retires ##

When a mock method is called, Google Mock only consider expectations
that are still active. An expectation is active when created, and
becomes inactive (aka _retires_) when a call that has to occur later
has occurred. For example, in

```
  using ::testing::_;
  using ::testing::Sequence;

  Sequence s1, s2;

  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
      .Times(AnyNumber())
      .InSequence(s1, s2);
  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
      .InSequence(s1);
  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
      .InSequence(s2);
```

as soon as either #2 or #3 is matched, #1 will retire. If a warning
`"File too large."` is logged after this, it will be an error.

Note that an expectation doesn't retire automatically when it's
saturated. For example,

```
using ::testing::_;
...
  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
```

says that there will be exactly one warning with the message `"File
too large."`. If the second warning contains this message too, #2 will
match again and result in an upper-bound-violated error.

If this is not what you want, you can ask an expectation to retire as
soon as it becomes saturated:

```
using ::testing::_;
...
  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
      .RetiresOnSaturation();
```

Here #2 can be used only once, so if you have two warnings with the
message `"File too large."`, the first will match #2 and the second
will match #1 - there will be no error.

# Using Actions #

## Returning References from Mock Methods ##

If a mock function's return type is a reference, you need to use
`ReturnRef()` instead of `Return()` to return a result:

```
using ::testing::ReturnRef;

class MockFoo : public Foo {
 public:
  MOCK_METHOD0(GetBar, Bar&());
};
...

  MockFoo foo;
  Bar bar;
  EXPECT_CALL(foo, GetBar())
      .WillOnce(ReturnRef(bar));
```

## Returning Live Values from Mock Methods ##

The `Return(x)` action saves a copy of `x` when the action is
_created_, and always returns the same value whenever it's
executed. Sometimes you may want to instead return the _live_ value of
`x` (i.e. its value at the time when the action is _executed_.).

If the mock function's return type is a reference, you can do it using
`ReturnRef(x)`, as shown in the previous recipe ("Returning References
from Mock Methods"). However, Google Mock doesn't let you use
`ReturnRef()` in a mock function whose return type is not a reference,
as doing that usually indicates a user error. So, what shall you do?

You may be tempted to try `ByRef()`:

```
using testing::ByRef;
using testing::Return;

class MockFoo : public Foo {
 public:
  MOCK_METHOD0(GetValue, int());
};
...
  int x = 0;
  MockFoo foo;
  EXPECT_CALL(foo, GetValue())
      .WillRepeatedly(Return(ByRef(x)));
  x = 42;
  EXPECT_EQ(42, foo.GetValue());
```

Unfortunately, it doesn't work here. The above code will fail with error:

```
Value of: foo.GetValue()
  Actual: 0
Expected: 42
```

The reason is that `Return(value)` converts `value` to the actual
return type of the mock function at the time when the action is
_created_, not when it is _executed_. (This behavior was chosen for
the action to be safe when `value` is a proxy object that references
some temporary objects.) As a result, `ByRef(x)` is converted to an
`int` value (instead of a `const int&`) when the expectation is set,
and `Return(ByRef(x))` will always return 0.

`ReturnPointee(pointer)` was provided to solve this problem
specifically. It returns the value pointed to by `pointer` at the time
the action is _executed_:

```
using testing::ReturnPointee;
...
  int x = 0;
  MockFoo foo;
  EXPECT_CALL(foo, GetValue())
      .WillRepeatedly(ReturnPointee(&x));  // Note the & here.
  x = 42;
  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.
```

## Combining Actions ##

Want to do more than one thing when a function is called? That's
fine. `DoAll()` allow you to do sequence of actions every time. Only
the return value of the last action in the sequence will be used.

```
using ::testing::DoAll;

class MockFoo : public Foo {
 public:
  MOCK_METHOD1(Bar, bool(int n));
};
...

  EXPECT_CALL(foo, Bar(_))
      .WillOnce(DoAll(action_1,
                      action_2,
                      ...
                      action_n));
```

## Mocking Side Effects ##

Sometimes a method exhibits its effect not via returning a value but
via side effects. For example, it may change some global state or
modify an output argument. To mock side effects, in general you can
define your own action by implementing `::testing::ActionInterface`.

If all you need to do is to change an output argument, the built-in
`SetArgPointee()` action is convenient:

```
using ::testing::SetArgPointee;

class MockMutator : public Mutator {
 public:
  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
  ...
};
...

  MockMutator mutator;
  EXPECT_CALL(mutator, Mutate(true, _))
      .WillOnce(SetArgPointee<1>(5));
```

In this example, when `mutator.Mutate()` is called, we will assign 5
to the `int` variable pointed to by argument #1
(0-based).

`SetArgPointee()` conveniently makes an internal copy of the
value you pass to it, removing the need to keep the value in scope and
alive. The implication however is that the value must have a copy
constructor and assignment operator.

If the mock method also needs to return a value as well, you can chain
`SetArgPointee()` with `Return()` using `DoAll()`:

```
using ::testing::_;
using ::testing::Return;
using ::testing::SetArgPointee;

class MockMutator : public Mutator {
 public:
  ...
  MOCK_METHOD1(MutateInt, bool(int* value));
};
...

  MockMutator mutator;
  EXPECT_CALL(mutator, MutateInt(_))
      .WillOnce(DoAll(SetArgPointee<0>(5),
                      Return(true)));
```

If the output argument is an array, use the
`SetArrayArgument<N>(first, last)` action instead. It copies the
elements in source range `[first, last)` to the array pointed to by
the `N`-th (0-based) argument:

```
using ::testing::NotNull;
using ::testing::SetArrayArgument;

class MockArrayMutator : public ArrayMutator {
 public:
  MOCK_METHOD2(Mutate, void(int* values, int num_values));
  ...
};
...

  MockArrayMutator mutator;
  int values[5] = { 1, 2, 3, 4, 5 };
  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
      .WillOnce(SetArrayArgument<0>(values, values + 5));
```

This also works when the argument is an output iterator:

```
using ::testing::_;
using ::testing::SeArrayArgument;

class MockRolodex : public Rolodex {
 public:
  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
  ...
};
...

  MockRolodex rolodex;
  vector<string> names;
  names.push_back("George");
  names.push_back("John");
  names.push_back("Thomas");
  EXPECT_CALL(rolodex, GetNames(_))
      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
```

## Changing a Mock Object's Behavior Based on the State ##

If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:

```
using ::testing::InSequence;
using ::testing::Return;

...
  {
    InSequence seq;
    EXPECT_CALL(my_mock, IsDirty())
        .WillRepeatedly(Return(true));
    EXPECT_CALL(my_mock, Flush());
    EXPECT_CALL(my_mock, IsDirty())
        .WillRepeatedly(Return(false));
  }
  my_mock.FlushIfDirty();
```

This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.

If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:

```
using ::testing::_;
using ::testing::SaveArg;
using ::testing::Return;

ACTION_P(ReturnPointee, p) { return *p; }
...
  int previous_value = 0;
  EXPECT_CALL(my_mock, GetPrevValue())
      .WillRepeatedly(ReturnPointee(&previous_value));
  EXPECT_CALL(my_mock, UpdateValue(_))
      .WillRepeatedly(SaveArg<0>(&previous_value));
  my_mock.DoSomethingToUpdateValue();
```

Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.

## Setting the Default Value for a Return Type ##

If a mock method's return type is a built-in C++ type or pointer, by
default it will return 0 when invoked. Also, in C++ 11 and above, a mock
method whose return type has a default constructor will return a default-constructed
value by default.  You only need to specify an
action if this default value doesn't work for you.

Sometimes, you may want to change this default value, or you may want
to specify a default value for types Google Mock doesn't know
about. You can do this using the `::testing::DefaultValue` class
template:

```
class MockFoo : public Foo {
 public:
  MOCK_METHOD0(CalculateBar, Bar());
};
...

  Bar default_bar;
  // Sets the default return value for type Bar.
  DefaultValue<Bar>::Set(default_bar);

  MockFoo foo;

  // We don't need to specify an action here, as the default
  // return value works for us.
  EXPECT_CALL(foo, CalculateBar());

  foo.CalculateBar();  // This should return default_bar.

  // Unsets the default return value.
  DefaultValue<Bar>::Clear();
```

Please note that changing the default value for a type can make you
tests hard to understand. We recommend you to use this feature
judiciously. For example, you may want to make sure the `Set()` and
`Clear()` calls are right next to the code that uses your mock.

## Setting the Default Actions for a Mock Method ##

You've learned how to change the default value of a given
type. However, this may be too coarse for your purpose: perhaps you
have two mock methods with the same return type and you want them to
have different behaviors. The `ON_CALL()` macro allows you to
customize your mock's behavior at the method level:

```
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Gt;
using ::testing::Return;
...
  ON_CALL(foo, Sign(_))
      .WillByDefault(Return(-1));
  ON_CALL(foo, Sign(0))
      .WillByDefault(Return(0));
  ON_CALL(foo, Sign(Gt(0)))
      .WillByDefault(Return(1));

  EXPECT_CALL(foo, Sign(_))
      .Times(AnyNumber());

  foo.Sign(5);   // This should return 1.
  foo.Sign(-9);  // This should return -1.
  foo.Sign(0);   // This should return 0.
```

As you may have guessed, when there are more than one `ON_CALL()`
statements, the news order take precedence over the older ones. In
other words, the **last** one that matches the function arguments will
be used. This matching order allows you to set up the common behavior
in a mock object's constructor or the test fixture's set-up phase and
specialize the mock's behavior later.

## Using Functions/Methods/Functors as Actions ##

If the built-in actions don't suit you, you can easily use an existing
function, method, or functor as an action:

```
using ::testing::_;
using ::testing::Invoke;

class MockFoo : public Foo {
 public:
  MOCK_METHOD2(Sum, int(int x, int y));
  MOCK_METHOD1(ComplexJob, bool(int x));
};

int CalculateSum(int x, int y) { return x + y; }

class Helper {
 public:
  bool ComplexJob(int x);
};
...

  MockFoo foo;
  Helper helper;
  EXPECT_CALL(foo, Sum(_, _))
      .WillOnce(Invoke(CalculateSum));
  EXPECT_CALL(foo, ComplexJob(_))
      .WillOnce(Invoke(&helper, &Helper::ComplexJob));

  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
```

The only requirement is that the type of the function, etc must be
_compatible_ with the signature of the mock function, meaning that the
latter's arguments can be implicitly converted to the corresponding
arguments of the former, and the former's return type can be
implicitly converted to that of the latter. So, you can invoke
something whose type is _not_ exactly the same as the mock function,
as long as it's safe to do so - nice, huh?

## Invoking a Function/Method/Functor Without Arguments ##

`Invoke()` is very useful for doing actions that are more complex. It
passes the mock function's arguments to the function or functor being
invoked such that the callee has the full context of the call to work
with. If the invoked function is not interested in some or all of the
arguments, it can simply ignore them.

Yet, a common pattern is that a test author wants to invoke a function
without the arguments of the mock function. `Invoke()` allows her to
do that using a wrapper function that throws away the arguments before
invoking an underlining nullary function. Needless to say, this can be
tedious and obscures the intent of the test.

`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
that it doesn't pass the mock function's arguments to the
callee. Here's an example:

```
using ::testing::_;
using ::testing::InvokeWithoutArgs;

class MockFoo : public Foo {
 public:
  MOCK_METHOD1(ComplexJob, bool(int n));
};

bool Job1() { ... }
...

  MockFoo foo;
  EXPECT_CALL(foo, ComplexJob(_))
      .WillOnce(InvokeWithoutArgs(Job1));

  foo.ComplexJob(10);  // Invokes Job1().
```

## Invoking an Argument of the Mock Function ##

Sometimes a mock function will receive a function pointer or a functor
(in other words, a "callable") as an argument, e.g.

```
class MockFoo : public Foo {
 public:
  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
};
```

and you may want to invoke this callable argument:

```
using ::testing::_;
...
  MockFoo foo;
  EXPECT_CALL(foo, DoThis(_, _))
      .WillOnce(...);
  // Will execute (*fp)(5), where fp is the
  // second argument DoThis() receives.
```

Arghh, you need to refer to a mock function argument but C++ has no
lambda (yet), so you have to define your own action. :-( Or do you
really?

Well, Google Mock has an action to solve _exactly_ this problem:

```
  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
```

will invoke the `N`-th (0-based) argument the mock function receives,
with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
a function pointer or a functor, Google Mock handles them both.

With that, you could write:

```
using ::testing::_;
using ::testing::InvokeArgument;
...
  EXPECT_CALL(foo, DoThis(_, _))
      .WillOnce(InvokeArgument<1>(5));
  // Will execute (*fp)(5), where fp is the
  // second argument DoThis() receives.
```

What if the callable takes an argument by reference? No problem - just
wrap it inside `ByRef()`:

```
...
  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
...
using ::testing::_;
using ::testing::ByRef;
using ::testing::InvokeArgument;
...

  MockFoo foo;
  Helper helper;
  ...
  EXPECT_CALL(foo, Bar(_))
      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
  // will be passed to the callable.
```

What if the callable takes an argument by reference and we do **not**
wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
copy_ of the argument, and pass a _reference to the copy_, instead of
a reference to the original value, to the callable. This is especially
handy when the argument is a temporary value:

```
...
  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
...
using ::testing::_;
using ::testing::InvokeArgument;
...

  MockFoo foo;
  ...
  EXPECT_CALL(foo, DoThat(_))
      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
  // it's fine to perform this action later, since a copy of the values
  // are kept inside the InvokeArgument action.
```

## Ignoring an Action's Result ##

Sometimes you have an action that returns _something_, but you need an
action that returns `void` (perhaps you want to use it in a mock
function that returns `void`, or perhaps it needs to be used in
`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
you do that. For example:

```
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;

int Process(const MyData& data);
string DoSomething();

class MockFoo : public Foo {
 public:
  MOCK_METHOD1(Abc, void(const MyData& data));
  MOCK_METHOD0(Xyz, bool());
};
...

  MockFoo foo;
  EXPECT_CALL(foo, Abc(_))
  // .WillOnce(Invoke(Process));
  // The above line won't compile as Process() returns int but Abc() needs
  // to return void.
      .WillOnce(IgnoreResult(Invoke(Process)));

  EXPECT_CALL(foo, Xyz())
      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
      // Ignores the string DoSomething() returns.
                      Return(true)));
```

Note that you **cannot** use `IgnoreResult()` on an action that already
returns `void`. Doing so will lead to ugly compiler errors.

## Selecting an Action's Arguments ##

Say you have a mock function `Foo()` that takes seven arguments, and
you have a custom action that you want to invoke when `Foo()` is
called. Trouble is, the custom action only wants three arguments:

```
using ::testing::_;
using ::testing::Invoke;
...
  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
                         const map<pair<int, int>, double>& weight,
                         double min_weight, double max_wight));
...

bool IsVisibleInQuadrant1(bool visible, int x, int y) {
  return visible && x >= 0 && y >= 0;
}
...

  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
```

To please the compiler God, you can to define an "adaptor" that has
the same signature as `Foo()` and calls the custom action with the
right arguments:

```
using ::testing::_;
using ::testing::Invoke;

bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
                            const map<pair<int, int>, double>& weight,
                            double min_weight, double max_wight) {
  return IsVisibleInQuadrant1(visible, x, y);
}
...

  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
```

But isn't this awkward?

Google Mock provides a generic _action adaptor_, so you can spend your
time minding more important business than writing your own
adaptors. Here's the syntax:

```
  WithArgs<N1, N2, ..., Nk>(action)
```

creates an action that passes the arguments of the mock function at
the given indices (0-based) to the inner `action` and performs
it. Using `WithArgs`, our original example can be written as:

```
using ::testing::_;
using ::testing::Invoke;
using ::testing::WithArgs;
...
  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
      // No need to define your own adaptor.
```

For better readability, Google Mock also gives you:

  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.

As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
sugar for `WithoutArgs(Invoke(...))`.

Here are more tips:

  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.

## Ignoring Arguments in Action Functions ##

The selecting-an-action's-arguments recipe showed us one way to make a
mock function and an action with incompatible argument lists fit
together. The downside is that wrapping the action in
`WithArgs<...>()` can get tedious for people writing the tests.

If you are defining a function, method, or functor to be used with
`Invoke*()`, and you are not interested in some of its arguments, an
alternative to `WithArgs` is to declare the uninteresting arguments as
`Unused`. This makes the definition less cluttered and less fragile in
case the types of the uninteresting arguments change. It could also
increase the chance the action function can be reused. For example,
given

```
  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  MOCK_METHOD3(Bar, double(int index, double x, double y));
```

instead of

```
using ::testing::_;
using ::testing::Invoke;

double DistanceToOriginWithLabel(const string& label, double x, double y) {
  return sqrt(x*x + y*y);
}

double DistanceToOriginWithIndex(int index, double x, double y) {
  return sqrt(x*x + y*y);
}
...

  EXEPCT_CALL(mock, Foo("abc", _, _))
      .WillOnce(Invoke(DistanceToOriginWithLabel));
  EXEPCT_CALL(mock, Bar(5, _, _))
      .WillOnce(Invoke(DistanceToOriginWithIndex));
```

you could write

```
using ::testing::_;
using ::testing::Invoke;
using ::testing::Unused;

double DistanceToOrigin(Unused, double x, double y) {
  return sqrt(x*x + y*y);
}
...

  EXEPCT_CALL(mock, Foo("abc", _, _))
      .WillOnce(Invoke(DistanceToOrigin));
  EXEPCT_CALL(mock, Bar(5, _, _))
      .WillOnce(Invoke(DistanceToOrigin));
```

## Sharing Actions ##

Just like matchers, a Google Mock action object consists of a pointer
to a ref-counted implementation object. Therefore copying actions is
also allowed and very efficient. When the last action that references
the implementation object dies, the implementation object will be
deleted.

If you have some complex action that you want to use again and again,
you may not have to build it from scratch everytime. If the action
doesn't have an internal state (i.e. if it always does the same thing
no matter how many times it has been called), you can assign it to an
action variable and use that variable repeatedly. For example:

```
  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
                                      Return(true));
  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
```

However, if the action has its own state, you may be surprised if you
share the action object. Suppose you have an action factory
`IncrementCounter(init)` which creates an action that increments and
returns a counter whose initial value is `init`, using two actions
created from the same expression and using a shared action will
exihibit different behaviors. Example:

```
  EXPECT_CALL(foo, DoThis())
      .WillRepeatedly(IncrementCounter(0));
  EXPECT_CALL(foo, DoThat())
      .WillRepeatedly(IncrementCounter(0));
  foo.DoThis();  // Returns 1.
  foo.DoThis();  // Returns 2.
  foo.DoThat();  // Returns 1 - Blah() uses a different
                 // counter than Bar()'s.
```

versus

```
  Action<int()> increment = IncrementCounter(0);

  EXPECT_CALL(foo, DoThis())
      .WillRepeatedly(increment);
  EXPECT_CALL(foo, DoThat())
      .WillRepeatedly(increment);
  foo.DoThis();  // Returns 1.
  foo.DoThis();  // Returns 2.
  foo.DoThat();  // Returns 3 - the counter is shared.
```

# Misc Recipes on Using Google Mock #

## Mocking Methods That Use Move-Only Types ##

C++11 introduced *move-only types*.  A move-only-typed value can be moved from one object to another, but cannot be copied.  `std::unique_ptr<T>` is probably the most commonly used move-only type.

Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable.  This recipe shows you how you can do it.

Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”.  Your code uses these types:

```
enum class AccessLevel { kInternal, kPublic };

class Buzz {
 public:
  explicit Buzz(AccessLevel access) { … }
  ...
};

class Buzzer {
 public:
  virtual ~Buzzer() {}
  virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0;
  virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0;
  ...
};
```

A `Buzz` object represents a snippet being posted.  A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`.  Methods in `Buzzer` may return a `unique_ptr` or take a `unique_ptr`.  Now we need to mock `Buzzer` in our tests.

To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual:

```
class MockBuzzer : public Buzzer {
 public:
  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
  …
};
```

However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently:

```
  // Does NOT compile!
  MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp));
```

While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet.  Fortunately, there is a trick you can apply today to get something that works nearly as well as this.

The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters:

```
class MockBuzzer : public Buzzer {
 public:
  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
  MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
  bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
    return DoShareBuzz(buzz.get(), timestamp);
  }
};
```

Note that there's no need to define or declare `DoShareBuzz()` in a base class.  You only need to define it as a `MOCK_METHOD` in the mock class.

Now that we have the mock class defined, we can use it in tests.  In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`:

```
  MockBuzzer mock_buzzer_;
```

First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr`.

As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken.  Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an action:

```
  // Use the default action.
  EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));

  // Triggers the previous EXPECT_CALL.
  EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
```

If you are not happy with the default action, you can tweak it.  Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type.  The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type).  You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API:

```
  // Sets the default action for return type std::unique_ptr<Buzz> to
  // creating a new Buzz every time.
  DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
      [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });

  // When this fires, the default action of MakeBuzz() will run, which
  // will return a new Buzz object.
  EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());

  auto buzz1 = mock_buzzer_.MakeBuzz("hello");
  auto buzz2 = mock_buzzer_.MakeBuzz("hello");
  EXPECT_NE(nullptr, buzz1);
  EXPECT_NE(nullptr, buzz2);
  EXPECT_NE(buzz1, buzz2);

  // Resets the default action for return type std::unique_ptr<Buzz>,
  // to avoid interfere with other tests.
  DefaultValue<std::unique_ptr<Buzz>>::Clear();
```

What if you want the method to do something other than the default action?  If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action:

```
  // When this fires, the unique_ptr<> specified by ByMove(...) will
  // be returned.
  EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
      .WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));

  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
```

Note that `ByMove()` is essential here - if you drop it, the code won’t compile.

Quiz time!  What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)?  Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once.

If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want:

```
  EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
      .WillRepeatedly(Invoke([](const std::string& text) {
        return std::make_unique<Buzz>(AccessLevel::kInternal);
      }));

  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
```

Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created and returned.  You cannot do this with `Return(ByMove(...))`.

Now there’s one topic we haven’t covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter?  The answer is you don’t.  Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`):

```
  EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _));

  // When one calls ShareBuzz() on the MockBuzzer like this, the call is
  // forwarded to DoShareBuzz(), which is mocked.  Therefore this statement
  // will trigger the above EXPECT_CALL.
  mock_buzzer_.ShareBuzz(MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal),
                         ::base::Now());
```

Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns.  What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called?  Indeed, you'd be stuck.

Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`.

Fortunately, these problems can be fixed with a bit more code.  Let's try to get it right this time:

```
class MockBuzzer : public Buzzer {
 public:
  MockBuzzer() {
    // Since DoShareBuzz(buzz, time) is supposed to take ownership of
    // buzz, define a default behavior for DoShareBuzz(buzz, time) to
    // delete buzz.
    ON_CALL(*this, DoShareBuzz(_, _))
        .WillByDefault(Invoke([](Buzz* buzz, Time timestamp) {
          delete buzz;
          return true;
        }));
  }

  MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));

  // Takes ownership of buzz.
  MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
  bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
    return DoShareBuzz(buzz.release(), timestamp);
  }
};
```

Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want:

```
  std::unique_ptr<Buzz> intercepted_buzz;
  EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _))
      .WillOnce(Invoke([&amp;intercepted_buzz](Buzz* buzz, Time timestamp) {
        // Save buzz in intercepted_buzz for analysis later.
        intercepted_buzz.reset(buzz);
        return false;
      }));

  mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal),
                         Now());
  EXPECT_NE(nullptr, intercepted_buzz);
```

Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types.  Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests.

## Making the Compilation Faster ##

Believe it or not, the _vast majority_ of the time spent on compiling
a mock class is in generating its constructor and destructor, as they
perform non-trivial tasks (e.g. verification of the
expectations). What's more, mock methods with different signatures
have different types and thus their constructors/destructors need to
be generated by the compiler separately. As a result, if you mock many
different types of methods, compiling your mock class can get really
slow.

If you are experiencing slow compilation, you can move the definition
of your mock class' constructor and destructor out of the class body
and into a `.cpp` file. This way, even if you `#include` your mock
class in N files, the compiler only needs to generate its constructor
and destructor once, resulting in a much faster compilation.

Let's illustrate the idea using an example. Here's the definition of a
mock class before applying this recipe:

```
// File mock_foo.h.
...
class MockFoo : public Foo {
 public:
  // Since we don't declare the constructor or the destructor,
  // the compiler will generate them in every translation unit
  // where this mock class is used.

  MOCK_METHOD0(DoThis, int());
  MOCK_METHOD1(DoThat, bool(const char* str));
  ... more mock methods ...
};
```

After the change, it would look like:

```
// File mock_foo.h.
...
class MockFoo : public Foo {
 public:
  // The constructor and destructor are declared, but not defined, here.
  MockFoo();
  virtual ~MockFoo();

  MOCK_METHOD0(DoThis, int());
  MOCK_METHOD1(DoThat, bool(const char* str));
  ... more mock methods ...
};
```
and
```
// File mock_foo.cpp.
#include "path/to/mock_foo.h"

// The definitions may appear trivial, but the functions actually do a
// lot of things through the constructors/destructors of the member
// variables used to implement the mock methods.
MockFoo::MockFoo() {}
MockFoo::~MockFoo() {}
```

## Forcing a Verification ##

When it's being destoyed, your friendly mock object will automatically
verify that all expectations on it have been satisfied, and will
generate [Google Test](../../googletest/) failures
if not. This is convenient as it leaves you with one less thing to
worry about. That is, unless you are not sure if your mock object will
be destoyed.

How could it be that your mock object won't eventually be destroyed?
Well, it might be created on the heap and owned by the code you are
testing. Suppose there's a bug in that code and it doesn't delete the
mock object properly - you could end up with a passing test when
there's actually a bug.

Using a heap checker is a good idea and can alleviate the concern, but
its implementation may not be 100% reliable. So, sometimes you do want
to _force_ Google Mock to verify a mock object before it is
(hopefully) destructed. You can do this with
`Mock::VerifyAndClearExpectations(&mock_object)`:

```
TEST(MyServerTest, ProcessesRequest) {
  using ::testing::Mock;

  MockFoo* const foo = new MockFoo;
  EXPECT_CALL(*foo, ...)...;
  // ... other expectations ...

  // server now owns foo.
  MyServer server(foo);
  server.ProcessRequest(...);

  // In case that server's destructor will forget to delete foo,
  // this will verify the expectations anyway.
  Mock::VerifyAndClearExpectations(foo);
}  // server is destroyed when it goes out of scope here.
```

**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
`bool` to indicate whether the verification was successful (`true` for
yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
there is no point going further when the verification has failed.

## Using Check Points ##

Sometimes you may want to "reset" a mock object at various check
points in your test: at each check point, you verify that all existing
expectations on the mock object have been satisfied, and then you set
some new expectations on it as if it's newly created. This allows you
to work with a mock object in "phases" whose sizes are each
manageable.

One such scenario is that in your test's `SetUp()` function, you may
want to put the object you are testing into a certain state, with the
help from a mock object. Once in the desired state, you want to clear
all expectations on the mock, such that in the `TEST_F` body you can
set fresh expectations on it.

As you may have figured out, the `Mock::VerifyAndClearExpectations()`
function we saw in the previous recipe can help you here. Or, if you
are using `ON_CALL()` to set default actions on the mock object and
want to clear the default actions as well, use
`Mock::VerifyAndClear(&mock_object)` instead. This function does what
`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
same `bool`, **plus** it clears the `ON_CALL()` statements on
`mock_object` too.

Another trick you can use to achieve the same effect is to put the
expectations in sequences and insert calls to a dummy "check-point"
function at specific places. Then you can verify that the mock
function calls do happen at the right time. For example, if you are
exercising code:

```
Foo(1);
Foo(2);
Foo(3);
```

and want to verify that `Foo(1)` and `Foo(3)` both invoke
`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:

```
using ::testing::MockFunction;

TEST(FooTest, InvokesBarCorrectly) {
  MyMock mock;
  // Class MockFunction<F> has exactly one mock method.  It is named
  // Call() and has type F.
  MockFunction<void(string check_point_name)> check;
  {
    InSequence s;

    EXPECT_CALL(mock, Bar("a"));
    EXPECT_CALL(check, Call("1"));
    EXPECT_CALL(check, Call("2"));
    EXPECT_CALL(mock, Bar("a"));
  }
  Foo(1);
  check.Call("1");
  Foo(2);
  check.Call("2");
  Foo(3);
}
```

The expectation spec says that the first `Bar("a")` must happen before
check point "1", the second `Bar("a")` must happen after check point "2",
and nothing should happen between the two check points. The explicit
check points make it easy to tell which `Bar("a")` is called by which
call to `Foo()`.

## Mocking Destructors ##

Sometimes you want to make sure a mock object is destructed at the
right time, e.g. after `bar->A()` is called but before `bar->B()` is
called. We already know that you can specify constraints on the order
of mock function calls, so all we need to do is to mock the destructor
of the mock function.

This sounds simple, except for one problem: a destructor is a special
function with special syntax and special semantics, and the
`MOCK_METHOD0` macro doesn't work for it:

```
  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
```

The good news is that you can use a simple pattern to achieve the same
effect. First, add a mock function `Die()` to your mock class and call
it in the destructor, like this:

```
class MockFoo : public Foo {
  ...
  // Add the following two lines to the mock class.
  MOCK_METHOD0(Die, void());
  virtual ~MockFoo() { Die(); }
};
```

(If the name `Die()` clashes with an existing symbol, choose another
name.) Now, we have translated the problem of testing when a `MockFoo`
object dies to testing when its `Die()` method is called:

```
  MockFoo* foo = new MockFoo;
  MockBar* bar = new MockBar;
  ...
  {
    InSequence s;

    // Expects *foo to die after bar->A() and before bar->B().
    EXPECT_CALL(*bar, A());
    EXPECT_CALL(*foo, Die());
    EXPECT_CALL(*bar, B());
  }
```

And that's that.

## Using Google Mock and Threads ##

**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on
platforms where Google Mock is thread-safe. Currently these are only
platforms that support the pthreads library (this includes Linux and Mac).
To make it thread-safe on other platforms we only need to implement
some synchronization operations in `"gtest/internal/gtest-port.h"`.

In a **unit** test, it's best if you could isolate and test a piece of
code in a single-threaded context. That avoids race conditions and
dead locks, and makes debugging your test much easier.

Yet many programs are multi-threaded, and sometimes to test something
we need to pound on it from more than one thread. Google Mock works
for this purpose too.

Remember the steps for using a mock:

  1. Create a mock object `foo`.
  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
  1. The code under test calls methods of `foo`.
  1. Optionally, verify and reset the mock.
  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.

If you follow the following simple rules, your mocks and threads can
live happily together:

  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
  * Obviously, you can do step #1 without locking.
  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.

If you violate the rules (for example, if you set expectations on a
mock while another thread is calling its methods), you get undefined
behavior. That's not fun, so don't do it.

Google Mock guarantees that the action for a mock function is done in
the same thread that called the mock function. For example, in

```
  EXPECT_CALL(mock, Foo(1))
      .WillOnce(action1);
  EXPECT_CALL(mock, Foo(2))
      .WillOnce(action2);
```

if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
Google Mock will execute `action1` in thread 1 and `action2` in thread
2.

Google Mock does _not_ impose a sequence on actions performed in
different threads (doing so may create deadlocks as the actions may
need to cooperate). This means that the execution of `action1` and
`action2` in the above example _may_ interleave. If this is a problem,
you should add proper synchronization logic to `action1` and `action2`
to make the test thread-safe.


Also, remember that `DefaultValue<T>` is a global resource that
potentially affects _all_ living mock objects in your
program. Naturally, you won't want to mess with it from multiple
threads or when there still are mocks in action.

## Controlling How Much Information Google Mock Prints ##

When Google Mock sees something that has the potential of being an
error (e.g. a mock function with no expectation is called, a.k.a. an
uninteresting call, which is allowed but perhaps you forgot to
explicitly ban the call), it prints some warning messages, including
the arguments of the function and the return value. Hopefully this
will remind you to take a look and see if there is indeed a problem.

Sometimes you are confident that your tests are correct and may not
appreciate such friendly messages. Some other times, you are debugging
your tests or learning about the behavior of the code you are testing,
and wish you could observe every mock call that happens (including
argument values and the return value). Clearly, one size doesn't fit
all.

You can control how much Google Mock tells you using the
`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
with three possible values:

  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
  * `error`: Google Mock will print errors only (least verbose).

Alternatively, you can adjust the value of that flag from within your
tests like so:

```
  ::testing::FLAGS_gmock_verbose = "error";
```

Now, judiciously use the right flag to enable Google Mock serve you better!

## Gaining Super Vision into Mock Calls ##

You have a test using Google Mock. It fails: Google Mock tells you
that some expectations aren't satisfied. However, you aren't sure why:
Is there a typo somewhere in the matchers? Did you mess up the order
of the `EXPECT_CALL`s? Or is the code under test doing something
wrong?  How can you find out the cause?

Won't it be nice if you have X-ray vision and can actually see the
trace of all `EXPECT_CALL`s and mock method calls as they are made?
For each call, would you like to see its actual argument values and
which `EXPECT_CALL` Google Mock thinks it matches?

You can unlock this power by running your test with the
`--gmock_verbose=info` flag. For example, given the test program:

```
using testing::_;
using testing::HasSubstr;
using testing::Return;

class MockFoo {
 public:
  MOCK_METHOD2(F, void(const string& x, const string& y));
};

TEST(Foo, Bar) {
  MockFoo mock;
  EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return());
  EXPECT_CALL(mock, F("a", "b"));
  EXPECT_CALL(mock, F("c", HasSubstr("d")));

  mock.F("a", "good");
  mock.F("a", "b");
}
```

if you run it with `--gmock_verbose=info`, you will see this output:

```
[ RUN      ] Foo.Bar

foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked
foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked
foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked
foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...
    Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good")
foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))...
    Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b")
foo_test.cc:16: Failure
Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
[  FAILED  ] Foo.Bar
```

Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo
and should actually be `"a"`. With the above message, you should see
that the actual `F("a", "good")` call is matched by the first
`EXPECT_CALL`, not the third as you thought. From that it should be
obvious that the third `EXPECT_CALL` is written wrong. Case solved.

## Running Tests in Emacs ##

If you build and run your tests in Emacs, the source file locations of
Google Mock and [Google Test](../../googletest/)
errors will be highlighted. Just press `<Enter>` on one of them and
you'll be taken to the offending line. Or, you can just type `C-x ``
to jump to the next error.

To make it even easier, you can add the following lines to your
`~/.emacs` file:

```
(global-set-key "\M-m"   'compile)  ; m is for make
(global-set-key [M-down] 'next-error)
(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
```

Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
back and forth between errors.

## Fusing Google Mock Source Files ##

Google Mock's implementation consists of dozens of files (excluding
its own tests).  Sometimes you may want them to be packaged up in
fewer files instead, such that you can easily copy them to a new
machine and start hacking there.  For this we provide an experimental
Python script `fuse_gmock_files.py` in the `scripts/` directory
(starting with release 1.2.0).  Assuming you have Python 2.4 or above
installed on your machine, just go to that directory and run
```
python fuse_gmock_files.py OUTPUT_DIR
```

and you should see an `OUTPUT_DIR` directory being created with files
`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
These three files contain everything you need to use Google Mock (and
Google Test).  Just copy them to anywhere you want and you are ready
to write tests and use mocks.  You can use the
[scrpts/test/Makefile](../scripts/test/Makefile) file as an example on how to compile your tests
against them.

# Extending Google Mock #

## Writing New Matchers Quickly ##

The `MATCHER*` family of macros can be used to define custom matchers
easily.  The syntax:

```
MATCHER(name, description_string_expression) { statements; }
```

will define a matcher with the given name that executes the
statements, which must return a `bool` to indicate if the match
succeeds.  Inside the statements, you can refer to the value being
matched by `arg`, and refer to its type by `arg_type`.

The description string is a `string`-typed expression that documents
what the matcher does, and is used to generate the failure message
when the match fails.  It can (and should) reference the special
`bool` variable `negation`, and should evaluate to the description of
the matcher when `negation` is `false`, or that of the matcher's
negation when `negation` is `true`.

For convenience, we allow the description string to be empty (`""`),
in which case Google Mock will use the sequence of words in the
matcher name as the description.

For example:
```
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
```
allows you to write
```
  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
```
or,
```
using ::testing::Not;
...
  EXPECT_THAT(some_expression, IsDivisibleBy7());
  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
```
If the above assertions fail, they will print something like:
```
  Value of: some_expression
  Expected: is divisible by 7
    Actual: 27
...
  Value of: some_other_expression
  Expected: not (is divisible by 7)
    Actual: 21
```
where the descriptions `"is divisible by 7"` and `"not (is divisible
by 7)"` are automatically calculated from the matcher name
`IsDivisibleBy7`.

As you may have noticed, the auto-generated descriptions (especially
those for the negation) may not be so great. You can always override
them with a string expression of your own:
```
MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
                        " divisible by 7") {
  return (arg % 7) == 0;
}
```

Optionally, you can stream additional information to a hidden argument
named `result_listener` to explain the match result. For example, a
better definition of `IsDivisibleBy7` is:
```
MATCHER(IsDivisibleBy7, "") {
  if ((arg % 7) == 0)
    return true;

  *result_listener << "the remainder is " << (arg % 7);
  return false;
}
```

With this definition, the above assertion will give a better message:
```
  Value of: some_expression
  Expected: is divisible by 7
    Actual: 27 (the remainder is 6)
```

You should let `MatchAndExplain()` print _any additional information_
that can help a user understand the match result. Note that it should
explain why the match succeeds in case of a success (unless it's
obvious) - this is useful when the matcher is used inside
`Not()`. There is no need to print the argument value itself, as
Google Mock already prints it for you.

**Notes:**

  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.

## Writing New Parameterized Matchers Quickly ##

Sometimes you'll want to define a matcher that has parameters.  For that you
can use the macro:
```
MATCHER_P(name, param_name, description_string) { statements; }
```
where the description string can be either `""` or a string expression
that references `negation` and `param_name`.

For example:
```
MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
```
will allow you to write:
```
  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
```
which may lead to this message (assuming `n` is 10):
```
  Value of: Blah("a")
  Expected: has absolute value 10
    Actual: -9
```

Note that both the matcher description and its parameter are
printed, making the message human-friendly.

In the matcher definition body, you can write `foo_type` to
reference the type of a parameter named `foo`.  For example, in the
body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
`value_type` to refer to the type of `value`.

Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
`MATCHER_P10` to support multi-parameter matchers:
```
MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
```

Please note that the custom description string is for a particular
**instance** of the matcher, where the parameters have been bound to
actual values.  Therefore usually you'll want the parameter values to
be part of the description.  Google Mock lets you do that by
referencing the matcher parameters in the description string
expression.

For example,
```
  using ::testing::PrintToString;
  MATCHER_P2(InClosedRange, low, hi,
             std::string(negation ? "isn't" : "is") + " in range [" +
             PrintToString(low) + ", " + PrintToString(hi) + "]") {
    return low <= arg && arg <= hi;
  }
  ...
  EXPECT_THAT(3, InClosedRange(4, 6));
```
would generate a failure that contains the message:
```
  Expected: is in range [4, 6]
```

If you specify `""` as the description, the failure message will
contain the sequence of words in the matcher name followed by the
parameter values printed as a tuple.  For example,
```
  MATCHER_P2(InClosedRange, low, hi, "") { ... }
  ...
  EXPECT_THAT(3, InClosedRange(4, 6));
```
would generate a failure that contains the text:
```
  Expected: in closed range (4, 6)
```

For the purpose of typing, you can view
```
MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
```
as shorthand for
```
template <typename p1_type, ..., typename pk_type>
FooMatcherPk<p1_type, ..., pk_type>
Foo(p1_type p1, ..., pk_type pk) { ... }
```

When you write `Foo(v1, ..., vk)`, the compiler infers the types of
the parameters `v1`, ..., and `vk` for you.  If you are not happy with
the result of the type inference, you can specify the types by
explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
As said earlier, you don't get to (or need to) specify
`arg_type` as that's determined by the context in which the matcher
is used.

You can assign the result of expression `Foo(p1, ..., pk)` to a
variable of type `FooMatcherPk`.  This can be
useful when composing matchers.  Matchers that don't have a parameter
or have only one parameter have special types: you can assign `Foo()`
to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
`FooMatcherP`-typed variable.

While you can instantiate a matcher template with reference types,
passing the parameters by pointer usually makes your code more
readable.  If, however, you still want to pass a parameter by
reference, be aware that in the failure message generated by the
matcher you will see the value of the referenced object but not its
address.

You can overload matchers with different numbers of parameters:
```
MATCHER_P(Blah, a, description_string_1) { ... }
MATCHER_P2(Blah, a, b, description_string_2) { ... }
```

While it's tempting to always use the `MATCHER*` macros when defining
a new matcher, you should also consider implementing
`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
the recipes that follow), especially if you need to use the matcher a
lot.  While these approaches require more work, they give you more
control on the types of the value being matched and the matcher
parameters, which in general leads to better compiler error messages
that pay off in the long run.  They also allow overloading matchers
based on parameter types (as opposed to just based on the number of
parameters).

## Writing New Monomorphic Matchers ##

A matcher of argument type `T` implements
`::testing::MatcherInterface<T>` and does two things: it tests whether a
value of type `T` matches the matcher, and can describe what kind of
values it matches. The latter ability is used for generating readable
error messages when expectations are violated.

The interface looks like this:

```
class MatchResultListener {
 public:
  ...
  // Streams x to the underlying ostream; does nothing if the ostream
  // is NULL.
  template <typename T>
  MatchResultListener& operator<<(const T& x);

  // Returns the underlying ostream.
  ::std::ostream* stream();
};

template <typename T>
class MatcherInterface {
 public:
  virtual ~MatcherInterface();

  // Returns true iff the matcher matches x; also explains the match
  // result to 'listener'.
  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;

  // Describes this matcher to an ostream.
  virtual void DescribeTo(::std::ostream* os) const = 0;

  // Describes the negation of this matcher to an ostream.
  virtual void DescribeNegationTo(::std::ostream* os) const;
};
```

If you need a custom matcher but `Truly()` is not a good option (for
example, you may not be happy with the way `Truly(predicate)`
describes itself, or you may want your matcher to be polymorphic as
`Eq(value)` is), you can define a matcher to do whatever you want in
two steps: first implement the matcher interface, and then define a
factory function to create a matcher instance. The second step is not
strictly needed but it makes the syntax of using the matcher nicer.

For example, you can define a matcher to test whether an `int` is
divisible by 7 and then use it like this:
```
using ::testing::MakeMatcher;
using ::testing::Matcher;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;

class DivisibleBy7Matcher : public MatcherInterface<int> {
 public:
  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
    return (n % 7) == 0;
  }

  virtual void DescribeTo(::std::ostream* os) const {
    *os << "is divisible by 7";
  }

  virtual void DescribeNegationTo(::std::ostream* os) const {
    *os << "is not divisible by 7";
  }
};

inline Matcher<int> DivisibleBy7() {
  return MakeMatcher(new DivisibleBy7Matcher);
}
...

  EXPECT_CALL(foo, Bar(DivisibleBy7()));
```

You may improve the matcher message by streaming additional
information to the `listener` argument in `MatchAndExplain()`:

```
class DivisibleBy7Matcher : public MatcherInterface<int> {
 public:
  virtual bool MatchAndExplain(int n,
                               MatchResultListener* listener) const {
    const int remainder = n % 7;
    if (remainder != 0) {
      *listener << "the remainder is " << remainder;
    }
    return remainder == 0;
  }
  ...
};
```

Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
```
Value of: x
Expected: is divisible by 7
  Actual: 23 (the remainder is 2)
```

## Writing New Polymorphic Matchers ##

You've learned how to write your own matchers in the previous
recipe. Just one problem: a matcher created using `MakeMatcher()` only
works for one particular type of arguments. If you want a
_polymorphic_ matcher that works with arguments of several types (for
instance, `Eq(x)` can be used to match a `value` as long as `value` ==
`x` compiles -- `value` and `x` don't have to share the same type),
you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit
involved.

Fortunately, most of the time you can define a polymorphic matcher
easily with the help of `MakePolymorphicMatcher()`. Here's how you can
define `NotNull()` as an example:

```
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
using ::testing::NotNull;
using ::testing::PolymorphicMatcher;

class NotNullMatcher {
 public:
  // To implement a polymorphic matcher, first define a COPYABLE class
  // that has three members MatchAndExplain(), DescribeTo(), and
  // DescribeNegationTo(), like the following.

  // In this example, we want to use NotNull() with any pointer, so
  // MatchAndExplain() accepts a pointer of any type as its first argument.
  // In general, you can define MatchAndExplain() as an ordinary method or
  // a method template, or even overload it.
  template <typename T>
  bool MatchAndExplain(T* p,
                       MatchResultListener* /* listener */) const {
    return p != NULL;
  }

  // Describes the property of a value matching this matcher.
  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }

  // Describes the property of a value NOT matching this matcher.
  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
};

// To construct a polymorphic matcher, pass an instance of the class
// to MakePolymorphicMatcher().  Note the return type.
inline PolymorphicMatcher<NotNullMatcher> NotNull() {
  return MakePolymorphicMatcher(NotNullMatcher());
}
...

  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
```

**Note:** Your polymorphic matcher class does **not** need to inherit from
`MatcherInterface` or any other class, and its methods do **not** need
to be virtual.

Like in a monomorphic matcher, you may explain the match result by
streaming additional information to the `listener` argument in
`MatchAndExplain()`.

## Writing New Cardinalities ##

A cardinality is used in `Times()` to tell Google Mock how many times
you expect a call to occur. It doesn't have to be exact. For example,
you can say `AtLeast(5)` or `Between(2, 4)`.

If the built-in set of cardinalities doesn't suit you, you are free to
define your own by implementing the following interface (in namespace
`testing`):

```
class CardinalityInterface {
 public:
  virtual ~CardinalityInterface();

  // Returns true iff call_count calls will satisfy this cardinality.
  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;

  // Returns true iff call_count calls will saturate this cardinality.
  virtual bool IsSaturatedByCallCount(int call_count) const = 0;

  // Describes self to an ostream.
  virtual void DescribeTo(::std::ostream* os) const = 0;
};
```

For example, to specify that a call must occur even number of times,
you can write

```
using ::testing::Cardinality;
using ::testing::CardinalityInterface;
using ::testing::MakeCardinality;

class EvenNumberCardinality : public CardinalityInterface {
 public:
  virtual bool IsSatisfiedByCallCount(int call_count) const {
    return (call_count % 2) == 0;
  }

  virtual bool IsSaturatedByCallCount(int call_count) const {
    return false;
  }

  virtual void DescribeTo(::std::ostream* os) const {
    *os << "called even number of times";
  }
};

Cardinality EvenNumber() {
  return MakeCardinality(new EvenNumberCardinality);
}
...

  EXPECT_CALL(foo, Bar(3))
      .Times(EvenNumber());
```

## Writing New Actions Quickly ##

If the built-in actions don't work for you, and you find it
inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
family to quickly define a new action that can be used in your code as
if it's a built-in action.

By writing
```
ACTION(name) { statements; }
```
in a namespace scope (i.e. not inside a class or function), you will
define an action with the given name that executes the statements.
The value returned by `statements` will be used as the return value of
the action.  Inside the statements, you can refer to the K-th
(0-based) argument of the mock function as `argK`.  For example:
```
ACTION(IncrementArg1) { return ++(*arg1); }
```
allows you to write
```
... WillOnce(IncrementArg1());
```

Note that you don't need to specify the types of the mock function
arguments.  Rest assured that your code is type-safe though:
you'll get a compiler error if `*arg1` doesn't support the `++`
operator, or if the type of `++(*arg1)` isn't compatible with the mock
function's return type.

Another example:
```
ACTION(Foo) {
  (*arg2)(5);
  Blah();
  *arg1 = 0;
  return arg0;
}
```
defines an action `Foo()` that invokes argument #2 (a function pointer)
with 5, calls function `Blah()`, sets the value pointed to by argument
#1 to 0, and returns argument #0.

For more convenience and flexibility, you can also use the following
pre-defined symbols in the body of `ACTION`:

| `argK_type` | The type of the K-th (0-based) argument of the mock function |
|:------------|:-------------------------------------------------------------|
| `args`      | All arguments of the mock function as a tuple                |
| `args_type` | The type of all arguments of the mock function as a tuple    |
| `return_type` | The return type of the mock function                         |
| `function_type` | The type of the mock function                                |

For example, when using an `ACTION` as a stub action for mock function:
```
int DoSomething(bool flag, int* ptr);
```
we have:
| **Pre-defined Symbol** | **Is Bound To** |
|:-----------------------|:----------------|
| `arg0`                 | the value of `flag` |
| `arg0_type`            | the type `bool` |
| `arg1`                 | the value of `ptr` |
| `arg1_type`            | the type `int*` |
| `args`                 | the tuple `(flag, ptr)` |
| `args_type`            | the type `::testing::tuple` |
| `return_type`          | the type `int`  |
| `function_type`        | the type `int(bool, int*)` |

## Writing New Parameterized Actions Quickly ##

Sometimes you'll want to parameterize an action you define.  For that
we have another macro
```
ACTION_P(name, param) { statements; }
```

For example,
```
ACTION_P(Add, n) { return arg0 + n; }
```
will allow you to write
```
// Returns argument #0 + 5.
... WillOnce(Add(5));
```

For convenience, we use the term _arguments_ for the values used to
invoke the mock function, and the term _parameters_ for the values
used to instantiate an action.

Note that you don't need to provide the type of the parameter either.
Suppose the parameter is named `param`, you can also use the
Google-Mock-defined symbol `param_type` to refer to the type of the
parameter as inferred by the compiler.  For example, in the body of
`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.

Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
multi-parameter actions.  For example,
```
ACTION_P2(ReturnDistanceTo, x, y) {
  double dx = arg0 - x;
  double dy = arg1 - y;
  return sqrt(dx*dx + dy*dy);
}
```
lets you write
```
... WillOnce(ReturnDistanceTo(5.0, 26.5));
```

You can view `ACTION` as a degenerated parameterized action where the
number of parameters is 0.

You can also easily define actions overloaded on the number of parameters:
```
ACTION_P(Plus, a) { ... }
ACTION_P2(Plus, a, b) { ... }
```

## Restricting the Type of an Argument or Parameter in an ACTION ##

For maximum brevity and reusability, the `ACTION*` macros don't ask
you to provide the types of the mock function arguments and the action
parameters.  Instead, we let the compiler infer the types for us.

Sometimes, however, we may want to be more explicit about the types.
There are several tricks to do that.  For example:
```
ACTION(Foo) {
  // Makes sure arg0 can be converted to int.
  int n = arg0;
  ... use n instead of arg0 here ...
}

ACTION_P(Bar, param) {
  // Makes sure the type of arg1 is const char*.
  ::testing::StaticAssertTypeEq<const char*, arg1_type>();

  // Makes sure param can be converted to bool.
  bool flag = param;
}
```
where `StaticAssertTypeEq` is a compile-time assertion in Google Test
that verifies two types are the same.

## Writing New Action Templates Quickly ##

Sometimes you want to give an action explicit template parameters that
cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
supports that and can be viewed as an extension to `ACTION()` and
`ACTION_P*()`.

The syntax:
```
ACTION_TEMPLATE(ActionName,
                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
```

defines an action template that takes _m_ explicit template parameters
and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
between 0 and 10.  `name_i` is the name of the i-th template
parameter, and `kind_i` specifies whether it's a `typename`, an
integral constant, or a template.  `p_i` is the name of the i-th value
parameter.

Example:
```
// DuplicateArg<k, T>(output) converts the k-th argument of the mock
// function to type T and copies it to *output.
ACTION_TEMPLATE(DuplicateArg,
                // Note the comma between int and k:
                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
                AND_1_VALUE_PARAMS(output)) {
  *output = T(::testing::get<k>(args));
}
```

To create an instance of an action template, write:
```
  ActionName<t1, ..., t_m>(v1, ..., v_n)
```
where the `t`s are the template arguments and the
`v`s are the value arguments.  The value argument
types are inferred by the compiler.  For example:
```
using ::testing::_;
...
  int n;
  EXPECT_CALL(mock, Foo(_, _))
      .WillOnce(DuplicateArg<1, unsigned char>(&n));
```

If you want to explicitly specify the value argument types, you can
provide additional template arguments:
```
  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
```
where `u_i` is the desired type of `v_i`.

`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
number of value parameters, but not on the number of template
parameters.  Without the restriction, the meaning of the following is
unclear:

```
  OverloadedAction<int, bool>(x);
```

Are we using a single-template-parameter action where `bool` refers to
the type of `x`, or a two-template-parameter action where the compiler
is asked to infer the type of `x`?

## Using the ACTION Object's Type ##

If you are writing a function that returns an `ACTION` object, you'll
need to know its type.  The type depends on the macro used to define
the action and the parameter types.  The rule is relatively simple:
| **Given Definition** | **Expression** | **Has Type** |
|:---------------------|:---------------|:-------------|
| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |	`Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` |
| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` |
| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
| ...                  | ...            | ...          |

Note that we have to pick different suffixes (`Action`, `ActionP`,
`ActionP2`, and etc) for actions with different numbers of value
parameters, or the action definitions cannot be overloaded on the
number of them.

## Writing New Monomorphic Actions ##

While the `ACTION*` macros are very convenient, sometimes they are
inappropriate.  For example, despite the tricks shown in the previous
recipes, they don't let you directly specify the types of the mock
function arguments and the action parameters, which in general leads
to unoptimized compiler error messages that can baffle unfamiliar
users.  They also don't allow overloading actions based on parameter
types without jumping through some hoops.

An alternative to the `ACTION*` macros is to implement
`::testing::ActionInterface<F>`, where `F` is the type of the mock
function in which the action will be used. For example:

```
template <typename F>class ActionInterface {
 public:
  virtual ~ActionInterface();

  // Performs the action.  Result is the return type of function type
  // F, and ArgumentTuple is the tuple of arguments of F.
  //
  // For example, if F is int(bool, const string&), then Result would
  // be int, and ArgumentTuple would be ::testing::tuple<bool, const string&>.
  virtual Result Perform(const ArgumentTuple& args) = 0;
};

using ::testing::_;
using ::testing::Action;
using ::testing::ActionInterface;
using ::testing::MakeAction;

typedef int IncrementMethod(int*);

class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
 public:
  virtual int Perform(const ::testing::tuple<int*>& args) {
    int* p = ::testing::get<0>(args);  // Grabs the first argument.
    return *p++;
  }
};

Action<IncrementMethod> IncrementArgument() {
  return MakeAction(new IncrementArgumentAction);
}
...

  EXPECT_CALL(foo, Baz(_))
      .WillOnce(IncrementArgument());

  int n = 5;
  foo.Baz(&n);  // Should return 5 and change n to 6.
```

## Writing New Polymorphic Actions ##

The previous recipe showed you how to define your own action. This is
all good, except that you need to know the type of the function in
which the action will be used. Sometimes that can be a problem. For
example, if you want to use the action in functions with _different_
types (e.g. like `Return()` and `SetArgPointee()`).

If an action can be used in several types of mock functions, we say
it's _polymorphic_. The `MakePolymorphicAction()` function template
makes it easy to define such an action:

```
namespace testing {

template <typename Impl>
PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);

}  // namespace testing
```

As an example, let's define an action that returns the second argument
in the mock function's argument list. The first step is to define an
implementation class:

```
class ReturnSecondArgumentAction {
 public:
  template <typename Result, typename ArgumentTuple>
  Result Perform(const ArgumentTuple& args) const {
    // To get the i-th (0-based) argument, use ::testing::get<i>(args).
    return ::testing::get<1>(args);
  }
};
```

This implementation class does _not_ need to inherit from any
particular class. What matters is that it must have a `Perform()`
method template. This method template takes the mock function's
arguments as a tuple in a **single** argument, and returns the result of
the action. It can be either `const` or not, but must be invokable
with exactly one template argument, which is the result type. In other
words, you must be able to call `Perform<R>(args)` where `R` is the
mock function's return type and `args` is its arguments in a tuple.

Next, we use `MakePolymorphicAction()` to turn an instance of the
implementation class into the polymorphic action we need. It will be
convenient to have a wrapper for this:

```
using ::testing::MakePolymorphicAction;
using ::testing::PolymorphicAction;

PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
  return MakePolymorphicAction(ReturnSecondArgumentAction());
}
```

Now, you can use this polymorphic action the same way you use the
built-in ones:

```
using ::testing::_;

class MockFoo : public Foo {
 public:
  MOCK_METHOD2(DoThis, int(bool flag, int n));
  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
};
...

  MockFoo foo;
  EXPECT_CALL(foo, DoThis(_, _))
      .WillOnce(ReturnSecondArgument());
  EXPECT_CALL(foo, DoThat(_, _, _))
      .WillOnce(ReturnSecondArgument());
  ...
  foo.DoThis(true, 5);         // Will return 5.
  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
```

## Teaching Google Mock How to Print Your Values ##

When an uninteresting or unexpected call occurs, Google Mock prints the
argument values and the stack trace to help you debug.  Assertion
macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in
question when the assertion fails.  Google Mock and Google Test do this using
Google Test's user-extensible value printer.

This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator.  For other
types, it prints the raw bytes in the value and hopes that you the
user can figure it out.
[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values)
explains how to extend the printer to do a better job at
printing your particular type than to dump the bytes.

---

### V8 5 7 Testing Gmock Docs DesignDoc (`v8_5_7/testing/gmock/docs/DesignDoc.md`)

This page discusses the design of new Google Mock features.



# Macros for Defining Actions #

## Problem ##

Due to the lack of closures in C++, it currently requires some
non-trivial effort to define a custom action in Google Mock.  For
example, suppose you want to "increment the value pointed to by the
second argument of the mock function and return it", you could write:

```
int IncrementArg1(Unused, int* p, Unused) {
  return ++(*p);
}

... WillOnce(Invoke(IncrementArg1));
```

There are several things unsatisfactory about this approach:

  * Even though the action only cares about the second argument of the mock function, its definition needs to list other arguments as dummies.  This is tedious.
  * The defined action is usable only in mock functions that takes exactly 3 arguments - an unnecessary restriction.
  * To use the action, one has to say `Invoke(IncrementArg1)`, which isn't as nice as `IncrementArg1()`.

The latter two problems can be overcome using `MakePolymorphicAction()`,
but it requires much more boilerplate code:

```
class IncrementArg1Action {
 public:
  template <typename Result, typename ArgumentTuple>
  Result Perform(const ArgumentTuple& args) const {
    return ++(*tr1::get<1>(args));
  }
};

PolymorphicAction<IncrementArg1Action> IncrementArg1() {
  return MakePolymorphicAction(IncrementArg1Action());
}

... WillOnce(IncrementArg1());
```

Our goal is to allow defining custom actions with the least amount of
boiler-plate C++ requires.

## Solution ##

We propose to introduce a new macro:
```
ACTION(name) { statements; }
```

Using this in a namespace scope will define an action with the given
name that executes the statements.  Inside the statements, you can
refer to the K-th (0-based) argument of the mock function as `argK`.
For example:
```
ACTION(IncrementArg1) { return ++(*arg1); }
```
allows you to write
```
... WillOnce(IncrementArg1());
```

Note that you don't need to specify the types of the mock function
arguments, as brevity is a top design goal here.  Rest assured that
your code is still type-safe though: you'll get a compiler error if
`*arg1` doesn't support the `++` operator, or if the type of
`++(*arg1)` isn't compatible with the mock function's return type.

Another example:
```
ACTION(Foo) {
  (*arg2)(5);
  Blah();
  *arg1 = 0;
  return arg0;
}
```
defines an action `Foo()` that invokes argument #2 (a function pointer)
with 5, calls function `Blah()`, sets the value pointed to by argument
#1 to 0, and returns argument #0.

For more convenience and flexibility, you can also use the following
pre-defined symbols in the body of `ACTION`:

| `argK_type` | The type of the K-th (0-based) argument of the mock function |
|:------------|:-------------------------------------------------------------|
| `args`      | All arguments of the mock function as a tuple                |
| `args_type` | The type of all arguments of the mock function as a tuple    |
| `return_type` | The return type of the mock function                         |
| `function_type` | The type of the mock function                                |

For example, when using an `ACTION` as a stub action for mock function:
```
int DoSomething(bool flag, int* ptr);
```
we have:
| **Pre-defined Symbol** | **Is Bound To** |
|:-----------------------|:----------------|
| `arg0`                 | the value of `flag` |
| `arg0_type`            | the type `bool` |
| `arg1`                 | the value of `ptr` |
| `arg1_type`            | the type `int*` |
| `args`                 | the tuple `(flag, ptr)` |
| `args_type`            | the type `std::tr1::tuple` |
| `return_type`          | the type `int`  |
| `function_type`        | the type `int(bool, int*)` |

## Parameterized actions ##

Sometimes you'll want to parameterize the action.   For that we propose
another macro
```
ACTION_P(name, param) { statements; }
```

For example,
```
ACTION_P(Add, n) { return arg0 + n; }
```
will allow you to write
```
// Returns argument #0 + 5.
... WillOnce(Add(5));
```

For convenience, we use the term _arguments_ for the values used to
invoke the mock function, and the term _parameters_ for the values
used to instantiate an action.

Note that you don't need to provide the type of the parameter either.
Suppose the parameter is named `param`, you can also use the
Google-Mock-defined symbol `param_type` to refer to the type of the
parameter as inferred by the compiler.

We will also provide `ACTION_P2`, `ACTION_P3`, and etc to support
multi-parameter actions.  For example,
```
ACTION_P2(ReturnDistanceTo, x, y) {
  double dx = arg0 - x;
  double dy = arg1 - y;
  return sqrt(dx*dx + dy*dy);
}
```
lets you write
```
... WillOnce(ReturnDistanceTo(5.0, 26.5));
```

You can view `ACTION` as a degenerated parameterized action where the
number of parameters is 0.

## Advanced Usages ##

### Overloading Actions ###

You can easily define actions overloaded on the number of parameters:
```
ACTION_P(Plus, a) { ... }
ACTION_P2(Plus, a, b) { ... }
```

### Restricting the Type of an Argument or Parameter ###

For maximum brevity and reusability, the `ACTION*` macros don't let
you specify the types of the mock function arguments and the action
parameters.  Instead, we let the compiler infer the types for us.

Sometimes, however, we may want to be more explicit about the types.
There are several tricks to do that.  For example:
```
ACTION(Foo) {
  // Makes sure arg0 can be converted to int.
  int n = arg0;
  ... use n instead of arg0 here ...
}

ACTION_P(Bar, param) {
  // Makes sure the type of arg1 is const char*.
  ::testing::StaticAssertTypeEq<const char*, arg1_type>();

  // Makes sure param can be converted to bool.
  bool flag = param;
}
```
where `StaticAssertTypeEq` is a compile-time assertion we plan to add to
Google Test (the name is chosen to match `static_assert` in C++0x).

### Using the ACTION Object's Type ###

If you are writing a function that returns an `ACTION` object, you'll
need to know its type.  The type depends on the macro used to define
the action and the parameter types.  The rule is relatively simple:
| **Given Definition** | **Expression** | **Has Type** |
|:---------------------|:---------------|:-------------|
| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` |
| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` |
| ...                  | ...            | ...          |

Note that we have to pick different suffixes (`Action`, `ActionP`,
`ActionP2`, and etc) for actions with different numbers of parameters,
or the action definitions cannot be overloaded on the number of
parameters.

## When to Use ##

While the new macros are very convenient, please also consider other
means of implementing actions (e.g. via `ActionInterface` or
`MakePolymorphicAction()`), especially if you need to use the defined
action a lot.  While the other approaches require more work, they give
you more control on the types of the mock function arguments and the
action parameters, which in general leads to better compiler error
messages that pay off in the long run.  They also allow overloading
actions based on parameter types, as opposed to just the number of
parameters.

## Related Work ##

As you may have realized, the `ACTION*` macros resemble closures (also
known as lambda expressions or anonymous functions).  Indeed, both of
them seek to lower the syntactic overhead for defining a function.

C++0x will support lambdas, but they are not part of C++ right now.
Some non-standard libraries (most notably BLL or Boost Lambda Library)
try to alleviate this problem.  However, they are not a good choice
for defining actions as:

  * They are non-standard and not widely installed.  Google Mock only depends on standard libraries and `tr1::tuple`, which is part of the new C++ standard and comes with gcc 4+.  We want to keep it that way.
  * They are not trivial to learn.
  * They will become obsolete when C++0x's lambda feature is widely supported.  We don't want to make our users use a dying library.
  * Since they are based on operators, they are rather ad hoc: you cannot use statements, and you cannot pass the lambda arguments to a function, for example.
  * They have subtle semantics that easily confuses new users.  For example, in expression `_1++ + foo++`, `foo` will be incremented only once where the expression is evaluated, while `_1` will be incremented every time the unnamed function is invoked.  This is far from intuitive.

`ACTION*` avoid all these problems.

## Future Improvements ##

There may be a need for composing `ACTION*` definitions (i.e. invoking
another `ACTION` inside the definition of one `ACTION*`).  We are not
sure we want it yet, as one can get a similar effect by putting
`ACTION` definitions in function templates and composing the function
templates.  We'll revisit this based on user feedback.

The reason we don't allow `ACTION*()` inside a function body is that
the current C++ standard doesn't allow function-local types to be used
to instantiate templates.  The upcoming C++0x standard will lift this
restriction.  Once this feature is widely supported by compilers, we
can revisit the implementation and add support for using `ACTION*()`
inside a function.

C++0x will also support lambda expressions.  When they become
available, we may want to support using lambdas as actions.

# Macros for Defining Matchers #

Once the macros for defining actions are implemented, we plan to do
the same for matchers:

```
MATCHER(name) { statements; }
```

where you can refer to the value being matched as `arg`.  For example,
given:

```
MATCHER(IsPositive) { return arg > 0; }
```

you can use `IsPositive()` as a matcher that matches a value iff it is
greater than 0.

We will also add `MATCHER_P`, `MATCHER_P2`, and etc for parameterized
matchers.

---

### V8 5 7 Testing Gmock Docs DevGuide (`v8_5_7/testing/gmock/docs/DevGuide.md`)

If you are interested in understanding the internals of Google Mock,
building from source, or contributing ideas or modifications to the
project, then this document is for you.

# Introduction #

First, let's give you some background of the project.

## Licensing ##

All Google Mock source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php).

## The Google Mock Community ##

The Google Mock community exists primarily through the [discussion group](http://groups.google.com/group/googlemock), the
[issue tracker](https://github.com/google/googletest/issues) and, to a lesser extent, the [source control repository](../). You are definitely encouraged to contribute to the
discussion and you can also help us to keep the effectiveness of the
group high by following and promoting the guidelines listed here.

### Please Be Friendly ###

Showing courtesy and respect to others is a vital part of the Google
culture, and we strongly encourage everyone participating in Google
Mock development to join us in accepting nothing less. Of course,
being courteous is not the same as failing to constructively disagree
with each other, but it does mean that we should be respectful of each
other when enumerating the 42 technical reasons that a particular
proposal may not be the best choice. There's never a reason to be
antagonistic or dismissive toward anyone who is sincerely trying to
contribute to a discussion.

Sure, C++ testing is serious business and all that, but it's also
a lot of fun. Let's keep it that way. Let's strive to be one of the
friendliest communities in all of open source.

### Where to Discuss Google Mock ###

As always, discuss Google Mock in the official [Google C++ Mocking Framework discussion group](http://groups.google.com/group/googlemock).  You don't have to actually submit
code in order to sign up. Your participation itself is a valuable
contribution.

# Working with the Code #

If you want to get your hands dirty with the code inside Google Mock,
this is the section for you.

## Checking Out the Source from Subversion ##

Checking out the Google Mock source is most useful if you plan to
tweak it yourself.  You check out the source for Google Mock using a
[Subversion](http://subversion.tigris.org/) client as you would for any
other project hosted on Google Code.  Please see the instruction on
the [source code access page](../) for how to do it.

## Compiling from Source ##

Once you check out the code, you can find instructions on how to
compile it in the [README](../README.md) file.

## Testing ##

A mocking framework is of no good if itself is not thoroughly tested.
Tests should be written for any new code, and changes should be
verified to not break existing tests before they are submitted for
review. To perform the tests, follow the instructions in [README](http://code.google.com/p/googlemock/source/browse/trunk/README) and
verify that there are no failures.

# Contributing Code #

We are excited that Google Mock is now open source, and hope to get
great patches from the community. Before you fire up your favorite IDE
and begin hammering away at that new feature, though, please take the
time to read this section and understand the process. While it seems
rigorous, we want to keep a high standard of quality in the code
base.

## Contributor License Agreements ##

You must sign a Contributor License Agreement (CLA) before we can
accept any code.  The CLA protects you and us.

  * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
  * If you work for a company that wants to allow you to contribute your work to Google Mock, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).

Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it.

## Coding Style ##

To keep the source consistent, readable, diffable and easy to merge,
we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project.  All patches will be expected
to conform to the style outlined [here](https://github.com/google/styleguide/blob/gh-pages/cppguide.xml).

## Submitting Patches ##

Please do submit code. Here's what you need to do:

  1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only.
  1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Mock issue tracker](http://code.google.com/p/googlemock/issues/list). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one.
  1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches.
  1. Ensure that your code adheres to the [Google Mock source code style](#Coding_Style.md).
  1. Ensure that there are unit tests for your code.
  1. Sign a Contributor License Agreement.
  1. Create a patch file using `svn diff`.
  1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews.  You can read about the tool [here](https://github.com/rietveld-codereview/rietveld/wiki).  When you are ready, upload your patch via Rietveld and notify `[email protected]` to review it.  There are several ways to upload the patch.  We recommend using the [upload\_gmock.py](../scripts/upload_gmock.py) script, which you can find in the `scripts/` folder in the SVN trunk.

## Google Mock Committers ##

The current members of the Google Mock engineering team are the only
committers at present. In the great tradition of eating one's own
dogfood, we will be requiring each new Google Mock engineering team
member to earn the right to become a committer by following the
procedures in this document, writing consistently great code, and
demonstrating repeatedly that he or she truly gets the zen of Google
Mock.

# Release Process #

We follow the typical release process for Subversion-based projects:

  1. A release branch named `release-X.Y` is created.
  1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable.
  1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch.
  1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time).
  1. Go back to step 1 to create another release branch and so on.


---

This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project.  Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/).

---

### V8 5 7 Testing Gmock Docs Documentation (`v8_5_7/testing/gmock/docs/Documentation.md`)

This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)**
- **if you use a released version of Google Mock, please read the documentation for that specific version instead.**

  * [ForDummies](ForDummies.md) -- start here if you are new to Google Mock.
  * [CheatSheet](CheatSheet.md) -- a quick reference.
  * [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock.
  * [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.

To contribute code to Google Mock, read:

  * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch.
  * [Pump Manual](../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files.

---

### V8 5 7 Testing Gmock Docs ForDummies (`v8_5_7/testing/gmock/docs/ForDummies.md`)

(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](FrequentlyAskedQuestions.md#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors).)

# What Is Google C++ Mocking Framework? #
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).

**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:

  * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
  * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.

If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.

**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.

Using Google Mock involves three basic steps:

  1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
  1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
  1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.

# Why Google Mock? #
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:

  * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it.
  * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions.
  * The knowledge you gained from using one mock doesn't transfer to the next.

In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.

Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:

  * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
  * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
  * Your tests are brittle as some resources they use are unreliable (e.g. the network).
  * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
  * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
  * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.

We encourage you to use Google Mock as:

  * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
  * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.

# Getting Started #
Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.

# A Case for Mock Turtles #
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:

```
class Turtle {
  ...
  virtual ~Turtle() {}
  virtual void PenUp() = 0;
  virtual void PenDown() = 0;
  virtual void Forward(int distance) = 0;
  virtual void Turn(int degrees) = 0;
  virtual void GoTo(int x, int y) = 0;
  virtual int GetX() const = 0;
  virtual int GetY() const = 0;
};
```

(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)

You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.

Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.

# Writing the Mock Class #
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)

## How to Define It ##
Using the `Turtle` interface as example, here are the simple steps you need to follow:

  1. Derive a class `MockTurtle` from `Turtle`.
  1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](CookBook.md#mocking-nonvirtual-methods), it's much more involved). Count how many arguments it has.
  1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
  1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
  1. Repeat until all virtual functions you want to mock are done.

After the process, you should have something like:

```
#include "gmock/gmock.h"  // Brings in Google Mock.
class MockTurtle : public Turtle {
 public:
  ...
  MOCK_METHOD0(PenUp, void());
  MOCK_METHOD0(PenDown, void());
  MOCK_METHOD1(Forward, void(int distance));
  MOCK_METHOD1(Turn, void(int degrees));
  MOCK_METHOD2(GoTo, void(int x, int y));
  MOCK_CONST_METHOD0(GetX, int());
  MOCK_CONST_METHOD0(GetY, int());
};
```

You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.

**Tip:** If even this is too much work for you, you'll find the
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful.  This command-line
tool requires that you have Python 2.4 installed.  You give it a C++ file and the name of an abstract class defined in it,
and it will print the definition of the mock class for you.  Due to the
complexity of the C++ language, this script may not always work, but
it can be quite handy when it does.  For more details, read the [user documentation](../scripts/generator/README).

## Where to Put It ##
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)

So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.

Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.

# Using Mocks in Tests #
Once you have a mock class, using it is easy. The typical work flow is:

  1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
  1. Create some mock objects.
  1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
  1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
  1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.

Here's an example:

```
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;                     // #1

TEST(PainterTest, CanDrawSomething) {
  MockTurtle turtle;                          // #2
  EXPECT_CALL(turtle, PenDown())              // #3
      .Times(AtLeast(1));

  Painter painter(&turtle);                   // #4

  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}                                             // #5

int main(int argc, char** argv) {
  // The following line must be executed to initialize Google Mock
  // (and Google Test) before running the tests.
  ::testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}
```

As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:

```
path/to/my_test.cc:119: Failure
Actual function call count doesn't match this expectation:
Actually: never called;
Expected: called at least once.
```

**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.

**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.

**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.

This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.

Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.

## Using Google Mock with Any Testing Framework ##
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
```
int main(int argc, char** argv) {
  // The following line causes Google Mock to throw an exception on failure,
  // which will be interpreted by your testing framework as a test failure.
  ::testing::GTEST_FLAG(throw_on_failure) = true;
  ::testing::InitGoogleMock(&argc, argv);
  ... whatever your testing framework requires ...
}
```

This approach has a catch: it makes Google Mock throw an exception
from a mock object's destructor sometimes.  With some compilers, this
sometimes causes the test program to crash.  You'll still be able to
notice that the test has failed, but it's not a graceful failure.

A better solution is to use Google Test's
[event listener API](../../googletest/docs/AdvancedGuide.md#extending-google-test-by-handling-test-events)
to report a test failure to your testing framework properly.  You'll need to
implement the `OnTestPartResult()` method of the event listener interface, but it
should be straightforward.

If this turns out to be too much work, we suggest that you stick with
Google Test, which works with Google Mock seamlessly (in fact, it is
technically part of Google Mock.).  If there is a reason that you
cannot use Google Test, please let us know.

# Setting Expectations #
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."

## General Syntax ##
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:

```
EXPECT_CALL(mock_object, method(matchers))
    .Times(cardinality)
    .WillOnce(action)
    .WillRepeatedly(action);
```

The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)

The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.

This syntax is designed to make an expectation read like English. For example, you can probably guess that

```
using ::testing::Return;...
EXPECT_CALL(turtle, GetX())
    .Times(5)
    .WillOnce(Return(100))
    .WillOnce(Return(150))
    .WillRepeatedly(Return(200));
```

says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).

**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.

## Matchers: What Arguments Do We Expect? ##
When a mock function takes arguments, we must specify what arguments we are expecting; for example:

```
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle, Forward(100));
```

Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":

```
using ::testing::_;
...
// Expects the turtle to move forward.
EXPECT_CALL(turtle, Forward(_));
```

`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.

A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:

```
using ::testing::Ge;...
EXPECT_CALL(turtle, Forward(Ge(100)));
```

This checks that the turtle will be told to go forward by at least 100 units.

## Cardinalities: How Many Times Will It Be Called? ##
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.

An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.

We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md).

The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:

  * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
  * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
  * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.

**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?

## Actions: What Should It Do? ##
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.

First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value.  If you don't say anything, this behavior will be used.

Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,

```
using ::testing::Return;...
EXPECT_CALL(turtle, GetX())
    .WillOnce(Return(100))
    .WillOnce(Return(200))
    .WillOnce(Return(300));
```

This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.

```
using ::testing::Return;...
EXPECT_CALL(turtle, GetY())
    .WillOnce(Return(100))
    .WillOnce(Return(200))
    .WillRepeatedly(Return(300));
```

says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.

Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).

What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](CheatSheet.md#actions).

**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:

```
int n = 100;
EXPECT_CALL(turtle, GetX())
.Times(4)
.WillRepeatedly(Return(n++));
```

Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md).

Time for another quiz! What do you think the following means?

```
using ::testing::Return;...
EXPECT_CALL(turtle, GetY())
.Times(4)
.WillOnce(Return(100));
```

Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.

## Using Multiple Expectations ##
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.

By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:

```
using ::testing::_;...
EXPECT_CALL(turtle, Forward(_));  // #1
EXPECT_CALL(turtle, Forward(10))  // #2
    .Times(2);
```

If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.

**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.

## Ordered vs Unordered Calls ##
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.

Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:

```
using ::testing::InSequence;...
TEST(FooTest, DrawsLineSegment) {
  ...
  {
    InSequence dummy;

    EXPECT_CALL(turtle, PenDown());
    EXPECT_CALL(turtle, Forward(100));
    EXPECT_CALL(turtle, PenUp());
  }
  Foo();
}
```

By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.

In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.

(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook#Expecting_Partially_Ordered_Calls.md).)

## All Expectations Are Sticky (Unless Said Otherwise) ##
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?

After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):

```
using ::testing::_;...
EXPECT_CALL(turtle, GoTo(_, _))  // #1
    .Times(AnyNumber());
EXPECT_CALL(turtle, GoTo(0, 0))  // #2
    .Times(2);
```

Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.

This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).

Simple? Let's see if you've really understood it: what does the following code say?

```
using ::testing::Return;
...
for (int i = n; i > 0; i--) {
  EXPECT_CALL(turtle, GetX())
      .WillOnce(Return(10*i));
}
```

If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!

One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:

```
using ::testing::Return;
...
for (int i = n; i > 0; i--) {
  EXPECT_CALL(turtle, GetX())
    .WillOnce(Return(10*i))
    .RetiresOnSaturation();
}
```

And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:

```
using ::testing::InSequence;
using ::testing::Return;
...
{
  InSequence s;

  for (int i = 1; i <= n; i++) {
    EXPECT_CALL(turtle, GetX())
        .WillOnce(Return(10*i))
        .RetiresOnSaturation();
  }
}
```

By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).

## Uninteresting Calls ##
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.

In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.

# What Now? #
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.

Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.

---

### V8 5 7 Testing Gmock Docs FrequentlyAskedQuestions (`v8_5_7/testing/gmock/docs/FrequentlyAskedQuestions.md`)

Please send your questions to the
[googlemock](http://groups.google.com/group/googlemock) discussion
group. If you need help with compiler errors, make sure you have
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.

## When I call a method on my mock object, the method for the real object is invoked instead.  What's the problem? ##

In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](CookBook.md#mocking-nonvirtual-methods).

## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##

After version 1.4.0 of Google Mock was released, we had an idea on how
to make it easier to write matchers that can generate informative
messages efficiently.  We experimented with this idea and liked what
we saw.  Therefore we decided to implement it.

Unfortunately, this means that if you have defined your own matchers
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
your definitions will no longer compile.  Matchers defined using the
`MATCHER*` family of macros are not affected.

Sorry for the hassle if your matchers are affected.  We believe it's
in everyone's long-term interest to make this change sooner than
later.  Fortunately, it's usually not hard to migrate an existing
matcher to the new API.  Here's what you need to do:

If you wrote your matcher like this:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MatcherInterface;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }
  ...
};
```

you'll need to change it to:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool MatchAndExplain(MyType value,
                               MatchResultListener* listener) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }
  ...
};
```
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
argument of type `MatchResultListener*`.)

If you were also using `ExplainMatchResultTo()` to improve the matcher
message:
```
// Old matcher definition that doesn't work with the lastest
// Google Mock.
using ::testing::MatcherInterface;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }

  virtual void ExplainMatchResultTo(MyType value,
                                    ::std::ostream* os) const {
    // Prints some helpful information to os to help
    // a user understand why value matches (or doesn't match).
    *os << "the Foo property is " << value.GetFoo();
  }
  ...
};
```

you should move the logic of `ExplainMatchResultTo()` into
`MatchAndExplain()`, using the `MatchResultListener` argument where
the `::std::ostream` was used:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool MatchAndExplain(MyType value,
                               MatchResultListener* listener) const {
    // Returns true if value matches.
    *listener << "the Foo property is " << value.GetFoo();
    return value.GetFoo() > 5;
  }
  ...
};
```

If your matcher is defined using `MakePolymorphicMatcher()`:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MakePolymorphicMatcher;
...
class MyGreatMatcher {
 public:
  ...
  bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

you should rename the `Matches()` method to `MatchAndExplain()` and
add a `MatchResultListener*` argument (the same as what you need to do
for matchers defined by implementing `MatcherInterface`):
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
...
class MyGreatMatcher {
 public:
  ...
  bool MatchAndExplain(MyType value,
                       MatchResultListener* listener) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

If your polymorphic matcher uses `ExplainMatchResultTo()` for better
failure messages:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MakePolymorphicMatcher;
...
class MyGreatMatcher {
 public:
  ...
  bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
void ExplainMatchResultTo(const MyGreatMatcher& matcher,
                          MyType value,
                          ::std::ostream* os) {
  // Prints some helpful information to os to help
  // a user understand why value matches (or doesn't match).
  *os << "the Bar property is " << value.GetBar();
}
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

you'll need to move the logic inside `ExplainMatchResultTo()` to
`MatchAndExplain()`:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
...
class MyGreatMatcher {
 public:
  ...
  bool MatchAndExplain(MyType value,
                       MatchResultListener* listener) const {
    // Returns true if value matches.
    *listener << "the Bar property is " << value.GetBar();
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

For more information, you can read these
[two](CookBook.md#writing-new-monomorphic-matchers)
[recipes](CookBook.md#writing-new-polymorphic-matchers)
from the cookbook.  As always, you
are welcome to post questions on `[email protected]` if you
need any help.

## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##

Google Mock works out of the box with Google Test.  However, it's easy
to configure it to work with any testing framework of your choice.
[Here](ForDummies.md#using-google-mock-with-any-testing-framework) is how.

## How am I supposed to make sense of these horrible template errors? ##

If you are confused by the compiler errors gcc threw at you,
try consulting the _Google Mock Doctor_ tool first.  What it does is to
scan stdin for gcc error messages, and spit out diagnoses on the
problems (we call them diseases) your code has.

To "install", run command:
```
alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
```

To use it, do:
```
<your-favorite-build-command> <your-test> 2>&1 | gmd
```

For example:
```
make my_test 2>&1 | gmd
```

Or you can run `gmd` and copy-n-paste gcc's error messages to it.

## Can I mock a variadic function? ##

You cannot mock a variadic function (i.e. a function taking ellipsis
(`...`) arguments) directly in Google Mock.

The problem is that in general, there is _no way_ for a mock object to
know how many arguments are passed to the variadic method, and what
the arguments' types are.  Only the _author of the base class_ knows
the protocol, and we cannot look into his head.

Therefore, to mock such a function, the _user_ must teach the mock
object how to figure out the number of arguments and their types.  One
way to do it is to provide overloaded versions of the function.

Ellipsis arguments are inherited from C and not really a C++ feature.
They are unsafe to use and don't work with arguments that have
constructors or destructors.  Therefore we recommend to avoid them in
C++ as much as possible.

## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##

If you compile this using Microsoft Visual C++ 2005 SP1:
```
class Foo {
  ...
  virtual void Bar(const int i) = 0;
};

class MockFoo : public Foo {
  ...
  MOCK_METHOD1(Bar, void(const int i));
};
```
You may get the following warning:
```
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
```

This is a MSVC bug.  The same code compiles fine with gcc ,for
example.  If you use Visual C++ 2008 SP1, you would get the warning:
```
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
```

In C++, if you _declare_ a function with a `const` parameter, the
`const` modifier is _ignored_.  Therefore, the `Foo` base class above
is equivalent to:
```
class Foo {
  ...
  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
};
```

In fact, you can _declare_ Bar() with an `int` parameter, and _define_
it with a `const int` parameter.  The compiler will still match them
up.

Since making a parameter `const` is meaningless in the method
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
That should workaround the VC bug.

Note that we are talking about the _top-level_ `const` modifier here.
If the function parameter is passed by pointer or reference, declaring
the _pointee_ or _referee_ as `const` is still meaningful.  For
example, the following two declarations are _not_ equivalent:
```
void Bar(int* p);        // Neither p nor *p is const.
void Bar(const int* p);  // p is not const, but *p is.
```

## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##

We've noticed that when the `/clr` compiler flag is used, Visual C++
uses 5~6 times as much memory when compiling a mock class.  We suggest
to avoid `/clr` when compiling native C++ mocks.

## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##

You might want to run your test with
`--gmock_verbose=info`.  This flag lets Google Mock print a trace
of every mock function call it receives.  By studying the trace,
you'll gain insights on why the expectations you set are not met.

## How can I assert that a function is NEVER called? ##

```
EXPECT_CALL(foo, Bar(_))
    .Times(0);
```

## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##

When Google Mock detects a failure, it prints relevant information
(the mock function arguments, the state of relevant expectations, and
etc) to help the user debug.  If another failure is detected, Google
Mock will do the same, including printing the state of relevant
expectations.

Sometimes an expectation's state didn't change between two failures,
and you'll see the same description of the state twice.  They are
however _not_ redundant, as they refer to _different points in time_.
The fact they are the same _is_ interesting information.

## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##

Does the class (hopefully a pure interface) you are mocking have a
virtual destructor?

Whenever you derive from a base class, make sure its destructor is
virtual.  Otherwise Bad Things will happen.  Consider the following
code:

```
class Base {
 public:
  // Not virtual, but should be.
  ~Base() { ... }
  ...
};

class Derived : public Base {
 public:
  ...
 private:
  std::string value_;
};

...
  Base* p = new Derived;
  ...
  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
             // - value_ is leaked.
```

By changing `~Base()` to virtual, `~Derived()` will be correctly
called when `delete p` is executed, and the heap checker
will be happy.

## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##

When people complain about this, often they are referring to code like:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.  However, I have to write the expectations in the
// reverse order.  This sucks big time!!!
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(2))
    .RetiresOnSaturation();
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(1))
    .RetiresOnSaturation();
```

The problem is that they didn't pick the **best** way to express the test's
intent.

By default, expectations don't have to be matched in _any_ particular
order.  If you want them to match in a certain order, you need to be
explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
easy to accidentally over-specify your tests, and we want to make it
harder to do so.

There are two better ways to write the test spec.  You could either
put the expectations in sequence:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.  Using a sequence, we can write the expectations
// in their natural order.
{
  InSequence s;
  EXPECT_CALL(foo, Bar())
      .WillOnce(Return(1))
      .RetiresOnSaturation();
  EXPECT_CALL(foo, Bar())
      .WillOnce(Return(2))
      .RetiresOnSaturation();
}
```

or you can put the sequence of actions in the same expectation:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(1))
    .WillOnce(Return(2))
    .RetiresOnSaturation();
```

Back to the original questions: why does Google Mock search the
expectations (and `ON_CALL`s) from back to front?  Because this
allows a user to set up a mock's behavior for the common case early
(e.g. in the mock's constructor or the test fixture's set-up phase)
and customize it with more specific rules later.  If Google Mock
searches from front to back, this very useful pattern won't be
possible.

## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##

When choosing between being neat and being safe, we lean toward the
latter.  So the answer is that we think it's better to show the
warning.

Often people write `ON_CALL`s in the mock object's
constructor or `SetUp()`, as the default behavior rarely changes from
test to test.  Then in the test body they set the expectations, which
are often different for each test.  Having an `ON_CALL` in the set-up
part of a test doesn't mean that the calls are expected.  If there's
no `EXPECT_CALL` and the method is called, it's possibly an error.  If
we quietly let the call go through without notifying the user, bugs
may creep in unnoticed.

If, however, you are sure that the calls are OK, you can write

```
EXPECT_CALL(foo, Bar(_))
    .WillRepeatedly(...);
```

instead of

```
ON_CALL(foo, Bar(_))
    .WillByDefault(...);
```

This tells Google Mock that you do expect the calls and no warning should be
printed.

Also, you can control the verbosity using the `--gmock_verbose` flag.
If you find the output too noisy when debugging, just choose a less
verbose level.

## How can I delete the mock function's argument in an action? ##

If you find yourself needing to perform some action that's not
supported by Google Mock directly, remember that you can define your own
actions using
[MakeAction()](CookBook.md#writing-new-actions) or
[MakePolymorphicAction()](CookBook.md#writing_new_polymorphic_actions),
or you can write a stub function and invoke it using
[Invoke()](CookBook.md#using-functions_methods_functors).

## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##

What?!  I think it's beautiful. :-)

While which syntax looks more natural is a subjective matter to some
extent, Google Mock's syntax was chosen for several practical advantages it
has.

Try to mock a function that takes a map as an argument:
```
virtual int GetSize(const map<int, std::string>& m);
```

Using the proposed syntax, it would be:
```
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
```

Guess what?  You'll get a compiler error as the compiler thinks that
`const map& m` are **two**, not one, arguments. To work
around this you can use `typedef` to give the map type a name, but
that gets in the way of your work.  Google Mock's syntax avoids this
problem as the function's argument types are protected inside a pair
of parentheses:
```
// This compiles fine.
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
```

You still need a `typedef` if the return type contains an unprotected
comma, but that's much rarer.

Other advantages include:
  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!

## My code calls a static/global function.  Can I mock it? ##

You can, but you need to make some changes.

In general, if you find yourself needing to mock a static function,
it's a sign that your modules are too tightly coupled (and less
flexible, less reusable, less testable, etc).  You are probably better
off defining a small interface and call the function through that
interface, which then can be easily mocked.  It's a bit of work
initially, but usually pays for itself quickly.

This Google Testing Blog
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
says it excellently.  Check it out.

## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##

I know it's not a question, but you get an answer for free any way. :-)

With Google Mock, you can create mocks in C++ easily.  And people might be
tempted to use them everywhere. Sometimes they work great, and
sometimes you may find them, well, a pain to use. So, what's wrong in
the latter case?

When you write a test without using mocks, you exercise the code and
assert that it returns the correct value or that the system is in an
expected state.  This is sometimes called "state-based testing".

Mocks are great for what some call "interaction-based" testing:
instead of checking the system state at the very end, mock objects
verify that they are invoked the right way and report an error as soon
as it arises, giving you a handle on the precise context in which the
error was triggered.  This is often more effective and economical to
do than state-based testing.

If you are doing state-based testing and using a test double just to
simulate the real object, you are probably better off using a fake.
Using a mock in this case causes pain, as it's not a strong point for
mocks to perform complex actions.  If you experience this and think
that mocks suck, you are just not using the right tool for your
problem. Or, you might be trying to solve the wrong problem. :-)

## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##

By all means, NO!  It's just an FYI.

What it means is that you have a mock function, you haven't set any
expectations on it (by Google Mock's rule this means that you are not
interested in calls to this function and therefore it can be called
any number of times), and it is called.  That's OK - you didn't say
it's not OK to call the function!

What if you actually meant to disallow this function to be called, but
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
one can argue that it's the user's fault, Google Mock tries to be nice and
prints you a note.

So, when you see the message and believe that there shouldn't be any
uninteresting calls, you should investigate what's going on.  To make
your life easier, Google Mock prints the function name and arguments
when an uninteresting call is encountered.

## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##

Either way is fine - you want to choose the one that's more convenient
for your circumstance.

Usually, if your action is for a particular function type, defining it
using `Invoke()` should be easier; if your action can be used in
functions of different types (e.g. if you are defining
`Return(value)`), `MakePolymorphicAction()` is
easiest.  Sometimes you want precise control on what types of
functions the action can be used in, and implementing
`ActionInterface` is the way to go here. See the implementation of
`Return()` in `include/gmock/gmock-actions.h` for an example.

## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##

You got this error as Google Mock has no idea what value it should return
when the mock method is called.  `SetArgPointee()` says what the
side effect is, but doesn't say what the return value should be.  You
need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.

See this [recipe](CookBook.md#mocking_side_effects) for more details and an example.


## My question is not in your FAQ! ##

If you cannot find the answer to your question in this FAQ, there are
some other resources you can use:

  1. read other [documentation](Documentation.md),
  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
  1. ask it on [[email protected]](mailto:[email protected]) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).

Please note that creating an issue in the
[issue tracker](https://github.com/google/googletest/issues) is _not_
a good way to get your answer, as it is monitored infrequently by a
very small number of people.

When asking a question, it's helpful to provide as much of the
following information as possible (people cannot help you if there's
not enough information in your question):

  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
  * your operating system,
  * the name and version of your compiler,
  * the complete command line flags you give to your compiler,
  * the complete compiler error messages (if the question is about compilation),
  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.

---

### V8 5 7 Testing Gmock Docs KnownIssues (`v8_5_7/testing/gmock/docs/KnownIssues.md`)

As any non-trivial software system, Google Mock has some known limitations and problems.  We are working on improving it, and welcome your help!  The follow is a list of issues we know about.



## README contains outdated information on Google Mock's compatibility with other testing frameworks ##

The `README` file in release 1.1.0 still says that Google Mock only works with Google Test.  Actually, you can configure Google Mock to work with any testing framework you choose.

## Tests failing on machines using Power PC CPUs (e.g. some Macs) ##

`gmock_output_test` and `gmock-printers_test` are known to fail with Power PC CPUs.  This is due to portability issues with these tests, and is not an indication of problems in Google Mock itself.  You can safely ignore them.

## Failed to resolve libgtest.so.0 in tests when built against installed Google Test ##

This only applies if you manually built and installed Google Test, and then built a Google Mock against it (either explicitly, or because gtest-config was in your path post-install). In this situation, Libtool has a known issue with certain systems' ldconfig setup:

http://article.gmane.org/gmane.comp.sysutils.automake.general/9025

This requires a manual run of "sudo ldconfig" after the "sudo make install" for Google Test before any binaries which link against it can be executed. This isn't a bug in our install, but we should at least have documented it or hacked a work-around into our install. We should have one of these solutions in our next release.

---

### V8 5 7 Testing Gtest Docs AdvancedGuide (`v8_5_7/testing/gtest/docs/AdvancedGuide.md`)

Now that you have read [Primer](Primer.md) and learned how to write tests
using Google Test, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex
failure messages, propagate fatal failures, reuse and speed up your
test fixtures, and use various flags with your tests.

# More Assertions #

This section covers some less frequently used, but still significant,
assertions.

## Explicit Success and Failure ##

These three assertions do not actually test a value or expression. Instead,
they generate a success or failure directly. Like the macros that actually
perform a test, you may stream a custom failure message into the them.

| `SUCCEED();` |
|:-------------|

Generates a success. This does NOT make the overall test succeed. A test is
considered successful only if none of its assertions fail during its execution.

Note: `SUCCEED()` is purely documentary and currently doesn't generate any
user-visible output. However, we may add `SUCCEED()` messages to Google Test's
output in the future.

| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
|:-----------|:-----------------|:------------------------------------------------------|

`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
failure. These are useful when control flow, rather than a Boolean expression,
deteremines the test's success or failure. For example, you might want to write
something like:

```
switch(expression) {
  case 1: ... some checks ...
  case 2: ... some other checks
  ...
  default: FAIL() << "We shouldn't get here.";
}
```

Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information.

_Availability_: Linux, Windows, Mac.

## Exception Assertions ##

These are for verifying that a piece of code throws (or does not
throw) an exception of the given type:

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |

Examples:

```
ASSERT_THROW(Foo(5), bar_exception);

EXPECT_NO_THROW({
  int n = 5;
  Bar(&n);
});
```

_Availability_: Linux, Windows, Mac; since version 1.1.0.

## Predicate Assertions for Better Error Messages ##

Even though Google Test has a rich set of assertions, they can never be
complete, as it's impossible (nor a good idea) to anticipate all the scenarios
a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
to check a complex expression, for lack of a better macro. This has the problem
of not showing you the values of the parts of the expression, making it hard to
understand what went wrong. As a workaround, some users choose to construct the
failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.

Google Test gives you three different options to solve this problem:

### Using an Existing Boolean Function ###

If you already have a function or a functor that returns `bool` (or a type
that can be implicitly converted to `bool`), you can use it in a _predicate
assertion_ to get the function arguments printed for free:

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
|  ...                | ...                    | ...          |

In the above, _predn_ is an _n_-ary predicate function or functor, where
_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
if the predicate returns `true` when applied to the given arguments, and fails
otherwise. When the assertion fails, it prints the value of each argument. In
either case, the arguments are evaluated exactly once.

Here's an example. Given

```
// Returns true iff m and n have no common divisors except 1.
bool MutuallyPrime(int m, int n) { ... }
const int a = 3;
const int b = 4;
const int c = 10;
```

the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message


!MutuallyPrime(b, c) is false, where
b is 4
c is 10


**Notes:**

  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it.
  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.

_Availability_: Linux, Windows, Mac

### Using a Function That Returns an AssertionResult ###

While `EXPECT_PRED*()` and friends are handy for a quick job, the
syntax is not satisfactory: you have to use different macros for
different arities, and it feels more like Lisp than C++.  The
`::testing::AssertionResult` class solves this problem.

An `AssertionResult` object represents the result of an assertion
(whether it's a success or a failure, and an associated message).  You
can create an `AssertionResult` using one of these factory
functions:

```
namespace testing {

// Returns an AssertionResult object to indicate that an assertion has
// succeeded.
AssertionResult AssertionSuccess();

// Returns an AssertionResult object to indicate that an assertion has
// failed.
AssertionResult AssertionFailure();

}
```

You can then use the `<<` operator to stream messages to the
`AssertionResult` object.

To provide more readable messages in Boolean assertions
(e.g. `EXPECT_TRUE()`), write a predicate function that returns
`AssertionResult` instead of `bool`. For example, if you define
`IsEven()` as:

```
::testing::AssertionResult IsEven(int n) {
  if ((n % 2) == 0)
    return ::testing::AssertionSuccess();
  else
    return ::testing::AssertionFailure() << n << " is odd";
}
```

instead of:

```
bool IsEven(int n) {
  return (n % 2) == 0;
}
```

the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:


Value of: IsEven(Fib(4))
Actual: false (*3 is odd*)
Expected: true


instead of a more opaque


Value of: IsEven(Fib(4))
Actual: false
Expected: true


If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
as well, and are fine with making the predicate slower in the success
case, you can supply a success message:

```
::testing::AssertionResult IsEven(int n) {
  if ((n % 2) == 0)
    return ::testing::AssertionSuccess() << n << " is even";
  else
    return ::testing::AssertionFailure() << n << " is odd";
}
```

Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print


Value of: IsEven(Fib(6))
Actual: true (8 is even)
Expected: false


_Availability_: Linux, Windows, Mac; since version 1.4.1.

### Using a Predicate-Formatter ###

If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
predicate do not support streaming to `ostream`, you can instead use the
following _predicate-formatter assertions_ to _fully_ customize how the
message is formatted:

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful |
| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
| `...`               | `...`                  | `...`        |

The difference between this and the previous two groups of macros is that instead of
a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
(_pred\_formatn_), which is a function or functor with the signature:

`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`

where _val1_, _val2_, ..., and _valn_ are the values of the predicate
arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
expressions as they appear in the source code. The types `T1`, `T2`, ..., and
`Tn` can be either value types or reference types. For example, if an
argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
whichever is appropriate.

A predicate-formatter returns a `::testing::AssertionResult` object to indicate
whether the assertion has succeeded or not. The only way to create such an
object is to call one of these factory functions:

As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:

```
// Returns the smallest prime common divisor of m and n,
// or 1 when m and n are mutually prime.
int SmallestPrimeCommonDivisor(int m, int n) { ... }

// A predicate-formatter for asserting that two integers are mutually prime.
::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
                                               const char* n_expr,
                                               int m,
                                               int n) {
  if (MutuallyPrime(m, n))
    return ::testing::AssertionSuccess();

  return ::testing::AssertionFailure()
      << m_expr << " and " << n_expr << " (" << m << " and " << n
      << ") are not mutually prime, " << "as they have a common divisor "
      << SmallestPrimeCommonDivisor(m, n);
}
```

With this predicate-formatter, we can use

```
EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
```

to generate the message


b and c (4 and 10) are not mutually prime, as they have a common divisor 2.


As you may have realized, many of the assertions we introduced earlier are
special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.

_Availability_: Linux, Windows, Mac.


## Floating-Point Comparison ##

Comparing floating-point numbers is tricky. Due to round-off errors, it is
very unlikely that two floating-points will match exactly. Therefore,
`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
can have a wide value range, no single fixed error bound works. It's better to
compare by a fixed relative error bound, except for values close to 0 due to
the loss of precision there.

In general, for floating-point comparison to make sense, the user needs to
carefully choose the error bound. If they don't want or care to, comparing in
terms of Units in the Last Place (ULPs) is a good default, and Google Test
provides assertions to do this. Full details about ULPs are quite long; if you
want to learn more, see
[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).

### Floating-Point Macros ###

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_FLOAT_EQ(`_val1, val2_`);`  | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal |
| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal |

By "almost equal", we mean the two values are within 4 ULP's from each
other.

The following assertions allow you to choose the acceptable error bound:

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error |

_Availability_: Linux, Windows, Mac.

### Floating-Point Predicate-Format Functions ###

Some floating-point operations are useful, but not that often used. In order
to avoid an explosion of new macros, we provide them as predicate-format
functions that can be used in predicate assertion macros (e.g.
`EXPECT_PRED_FORMAT2`, etc).

```
EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
```

Verifies that _val1_ is less than, or almost equal to, _val2_. You can
replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.

_Availability_: Linux, Windows, Mac.

## Windows HRESULT assertions ##

These assertions test for `HRESULT` success or failure.

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |

The generated output contains the human-readable error message
associated with the `HRESULT` code returned by _expression_.

You might use them like this:

```
CComPtr shell;
ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
CComVariant empty;
ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
```

_Availability_: Windows.

## Type Assertions ##

You can call the function
```
::testing::StaticAssertTypeEq<T1, T2>();
```
to assert that types `T1` and `T2` are the same.  The function does
nothing if the assertion is satisfied.  If the types are different,
the function call will fail to compile, and the compiler error message
will likely (depending on the compiler) show you the actual values of
`T1` and `T2`.  This is mainly useful inside template code.

_Caveat:_ When used inside a member function of a class template or a
function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
the function is instantiated.  For example, given:
```
template <typename T> class Foo {
 public:
  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
};
```
the code:
```
void Test1() { Foo<bool> foo; }
```
will _not_ generate a compiler error, as `Foo::Bar()` is never
actually instantiated.  Instead, you need:
```
void Test2() { Foo<bool> foo; foo.Bar(); }
```
to cause a compiler error.

_Availability:_ Linux, Windows, Mac; since version 1.3.0.

## Assertion Placement ##

You can use assertions in any C++ function. In particular, it doesn't
have to be a method of the test fixture class. The one constraint is
that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
can only be used in void-returning functions. This is a consequence of
Google Test not using exceptions. By placing it in a non-void function
you'll get a confusing compile error like
`"error: void value not ignored as it ought to be"`.

If you need to use assertions in a function that returns non-void, one option
is to make the function return the value in an out parameter instead. For
example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
need to make sure that `*result` contains some sensible value even when the
function returns prematurely. As the function now returns `void`, you can use
any assertion inside of it.

If changing the function's type is not an option, you should just use
assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
`EXPECT_*`.

_Note_: Constructors and destructors are not considered void-returning
functions, according to the C++ language specification, and so you may not use
fatal assertions in them. You'll get a compilation error if you try. A simple
workaround is to transfer the entire body of the constructor or destructor to a
private void-returning method. However, you should be aware that a fatal
assertion failure in a constructor does not terminate the current test, as your
intuition might suggest; it merely returns from the constructor early, possibly
leaving your object in a partially-constructed state. Likewise, a fatal
assertion failure in a destructor may leave your object in a
partially-destructed state. Use assertions carefully in these situations!

# Teaching Google Test How to Print Your Values #

When a test assertion such as `EXPECT_EQ` fails, Google Test prints the
argument values to help you debug.  It does this using a
user-extensible value printer.

This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator.  For other
types, it prints the raw bytes in the value and hopes that you the
user can figure it out.

As mentioned earlier, the printer is _extensible_.  That means
you can teach it to do a better job at printing your particular type
than to dump the bytes.  To do that, define `<<` for your type:

```
#include <iostream>

namespace foo {

class Bar { ... };  // We want Google Test to be able to print instances of this.

// It's important that the << operator is defined in the SAME
// namespace that defines Bar.  C++'s look-up rules rely on that.
::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
  return os << bar.DebugString();  // whatever needed to print bar to os
}

}  // namespace foo
```

Sometimes, this might not be an option: your team may consider it bad
style to have a `<<` operator for `Bar`, or `Bar` may already have a
`<<` operator that doesn't do what you want (and you cannot change
it).  If so, you can instead define a `PrintTo()` function like this:

```
#include <iostream>

namespace foo {

class Bar { ... };

// It's important that PrintTo() is defined in the SAME
// namespace that defines Bar.  C++'s look-up rules rely on that.
void PrintTo(const Bar& bar, ::std::ostream* os) {
  *os << bar.DebugString();  // whatever needed to print bar to os
}

}  // namespace foo
```

If you have defined both `<<` and `PrintTo()`, the latter will be used
when Google Test is concerned.  This allows you to customize how the value
appears in Google Test's output without affecting code that relies on the
behavior of its `<<` operator.

If you want to print a value `x` using Google Test's value printer
yourself, just call `::testing::PrintToString(`_x_`)`, which
returns an `std::string`:

```
vector<pair<Bar, int> > bar_ints = GetBarIntVector();

EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
    << "bar_ints = " << ::testing::PrintToString(bar_ints);
```

# Death Tests #

In many applications, there are assertions that can cause application failure
if a condition is not met. These sanity checks, which ensure that the program
is in a known good state, are there to fail at the earliest possible time after
some program state is corrupted. If the assertion checks the wrong condition,
then the program may proceed in an erroneous state, which could lead to memory
corruption, security holes, or worse. Hence it is vitally important to test
that such assertion statements work as expected.

Since these precondition checks cause the processes to die, we call such tests
_death tests_. More generally, any test that checks that a program terminates
(except by throwing an exception) in an expected fashion is also a death test.

Note that if a piece of code throws an exception, we don't consider it "death"
for the purpose of death tests, as the caller of the code could catch the exception
and avoid the crash. If you want to verify exceptions thrown by your code,
see [Exception Assertions](#exception-assertions).

If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures).

## How to Write a Death Test ##

Google Test has the following macros to support death tests:

| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error |
| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing |
| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ |

where _statement_ is a statement that is expected to cause the process to
die, _predicate_ is a function or function object that evaluates an integer
exit status, and _regex_ is a regular expression that the stderr output of
_statement_ is expected to match. Note that _statement_ can be _any valid
statement_ (including _compound statement_) and doesn't have to be an
expression.

As usual, the `ASSERT` variants abort the current test function, while the
`EXPECT` variants do not.

**Note:** We use the word "crash" here to mean that the process
terminates with a _non-zero_ exit status code.  There are two
possibilities: either the process has called `exit()` or `_exit()`
with a non-zero value, or it may be killed by a signal.

This means that if _statement_ terminates the process with a 0 exit
code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
`EXPECT_EXIT` instead if this is the case, or if you want to restrict
the exit code more precisely.

A predicate here must accept an `int` and return a `bool`. The death test
succeeds only if the predicate returns `true`. Google Test defines a few
predicates that handle the most common cases:

```
::testing::ExitedWithCode(exit_code)
```

This expression is `true` if the program exited normally with the given exit
code.

```
::testing::KilledBySignal(signal_number)  // Not available on Windows.
```

This expression is `true` if the program was killed by the given signal.

The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
that verifies the process' exit code is non-zero.

Note that a death test only cares about three things:

  1. does _statement_ abort or exit the process?
  1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_?  Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero?  And
  1. does the stderr output match _regex_?

In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process.

To write a death test, simply use one of the above macros inside your test
function. For example,

```
TEST(MyDeathTest, Foo) {
  // This death test uses a compound statement.
  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
}
TEST(MyDeathTest, NormalExit) {
  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
}
TEST(MyDeathTest, KillMyself) {
  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
}
```

verifies that:

  * calling `Foo(5)` causes the process to die with the given error message,
  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
  * calling `KillMyself()` kills the process with signal `SIGKILL`.

The test function body may contain other assertions and statements as well, if
necessary.

_Important:_ We strongly recommend you to follow the convention of naming your
test case (not test) `*DeathTest` when it contains a death test, as
demonstrated in the above example. The `Death Tests And Threads` section below
explains why.

If a test fixture class is shared by normal tests and death tests, you
can use typedef to introduce an alias for the fixture class and avoid
duplicating its code:
```
class FooTest : public ::testing::Test { ... };

typedef FooTest FooDeathTest;

TEST_F(FooTest, DoesThis) {
  // normal test
}

TEST_F(FooDeathTest, DoesThat) {
  // death test
}
```

_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0).  `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0.

## Regular Expression Syntax ##

On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).

On Windows, Google Test uses its own simple regular expression
implementation. It lacks many features you can find in POSIX extended
regular expressions.  For example, we don't support union (`"x|y"`),
grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a
literal character, period (`.`), or a single `\\` escape sequence; `x`
and `y` denote regular expressions.):

| `c` | matches any literal character `c` |
|:----|:----------------------------------|
| `\\d` | matches any decimal digit         |
| `\\D` | matches any character that's not a decimal digit |
| `\\f` | matches `\f`                      |
| `\\n` | matches `\n`                      |
| `\\r` | matches `\r`                      |
| `\\s` | matches any ASCII whitespace, including `\n` |
| `\\S` | matches any character that's not a whitespace |
| `\\t` | matches `\t`                      |
| `\\v` | matches `\v`                      |
| `\\w` | matches any letter, `_`, or decimal digit |
| `\\W` | matches any character that `\\w` doesn't match |
| `\\c` | matches any literal character `c`, which must be a punctuation |
| `\\.` | matches the `.` character         |
| `.` | matches any single character except `\n` |
| `A?` | matches 0 or 1 occurrences of `A` |
| `A*` | matches 0 or many occurrences of `A` |
| `A+` | matches 1 or many occurrences of `A` |
| `^` | matches the beginning of a string (not that of each line) |
| `$` | matches the end of a string (not that of each line) |
| `xy` | matches `x` followed by `y`       |

To help you determine which capability is available on your system,
Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when