# Technical Documentation: microsoft/react-native-windows

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/microsoft/react-native-windows)

### Overview (`README.md`)

<h1 align="center"> React Native for Windows </h1>

<p align="center">
  <a href="https://twitter.com/intent/follow?&screen_name=ReactNativeMSFT">
    <img src="https://img.shields.io/twitter/follow/ReactNativeMSFT?style=for-the-badge&logo=X&labelColor=black&color=white" alt="Follow @ReactNativeMSFT" />
  </a>
</p>

<h3 align="center">
  <a href="https://microsoft.github.io/react-native-windows">Website</a>
  <span> · </span>
  <a href="https://microsoft.github.io/react-native-windows/docs/getting-started">Documentation</a>
  <span> · </span>
  <a href="https://github.com/microsoft/react-native-windows/releases">Release notes</a>
</h3>

> See the official [React Native website](https://reactnative.dev/) for an introduction to React Native.

[React Native](https://reactnative.dev) is a framework developed by Meta that enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and [React](https://reactjs.org/). The focus of React Native is on developer efficiency across all the platforms you care about - learn once, write anywhere.

This repository adds support for the [Windows 10 SDK](https://developer.microsoft.com/en-us/windows/downloads), which allows you to build apps for [all devices supported by Windows 10](https://developer.microsoft.com/en-us/windows/get-started-windows-10) including PCs, tablets, 2-in-1s, Xbox, Mixed reality devices etc.

Visit the official [React Native for Windows + macOS website](https://microsoft.github.io/react-native-windows) to learn more.

## 🛣️ Roadmap
[Check out our blog](https://microsoft.github.io/react-native-windows/blog/) if you'd like to stay up to date on the status of React Native for Windows and check out current and past roadmaps.

### New Architecture
[Fabric](https://reactnative.dev/architecture/fabric-renderer) is the new rendering system for React Native, designed to share more rendering logic cross-platform. RNW's existing Paper renderer is built on UWP XAML, dropping down into native Composition as need be; the new RNW Fabric renderer targets Composition from the start but has the ability to host islands of XAML for advanced native controls. Apps on the new architecture will be [WinAppSDK](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/) Win32 by default. For more details on our roadmap to Fabric, check out [this pinned issue](https://github.com/microsoft/react-native-windows/issues/12042).

## 🖼️ React Native Gallery
Make sure to also check out the [React Native Gallery](https://github.com/microsoft/react-native-gallery), our interactive sample experience showing everything you can do with React Native for Windows.

<p align="center">
<img src="docs/img/rn-gallery.png" alt="WinUI 3 Gallery" width="400"/>
</p>
<p align="center">
<a href="https://www.microsoft.com/en-us/p/react-native-gallery/9npg0b292h4r?launch=true
	&mode=mini">
	<img src="docs/img/storeBadge.png" width="200"/>
</a>
</p>
</br>

## 📋 Getting Started
See the [Getting Started Guide](https://microsoft.github.io/react-native-windows/docs/getting-started) on our React Native for Windows + macOS website to build your first React Native for Windows app.

### Requirements
You can run React Native Windows apps only on devices supported by the [Windows 10 SDK](https://developer.microsoft.com/en-us/windows/downloads).

For a full and detailed list of the system requirements and how to set up your development platform, see our [System Requirements](https://microsoft.github.io/react-native-windows/docs/rnw-dependencies) documentation on our website.

### Logging Issues
Search the [existing issues](https://github.com/microsoft/react-native-windows/issues) and try to make sure your problem doesn’t already exist before opening a new issue. If your issue doesn't exist yet, provide as much information as possible so we can better help you. Include the information requested by the [appropriate issue template](https://github.com/microsoft/react-native-windows/issues/new/choose).

## Documentation
React Native has [great documentation](https://reactnative.dev/docs/getting-started). React Native for Windows adds its own separate [Windows and macOS documentation](https://microsoft.github.io/react-native-windows/) for desktop platform information like API docs and blog updates.

### Examples
- Using the CLI in the [Getting Started](https://microsoft.github.io/react-native-windows/docs/getting-started) guide will set you up with a sample React Native for Windows app that you can begin editing right away.
- Check the [samples repo](https://github.com/microsoft/react-native-windows-samples) for more standalone samples.
- The [React Native Gallery](https://github.com/microsoft/react-native-gallery) app demonstrates various components in an interactive way.
- Check out the [React Native Developer Blog](https://devblogs.microsoft.com/react-native/) to see examples from past conference talks, blog posts, and more.
- For more sample code browse the [RNTester folder](https://github.com/microsoft/react-native-windows/tree/main/packages/e2e-test-app-fabric/windows/RNTesterApp-Fabric) in the GitHub web UI.

## 📢 Contributing
See [Contributing guidelines](https://github.com/microsoft/react-native-windows/blob/main/CONTRIBUTING.md) for how to setup your fork of the repo and start a PR to contribute to React Native for Windows.

Not sure where to start? The [good first issue](https://github.com/microsoft/react-native-windows/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22) and [help wanted](https://github.com/microsoft/react-native-windows/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22help%20wanted%22) labels are the best starting points.

## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

---

### Overview (`.ado/README.md`)

# React Native Windows Azure DevOps pipelines

This folder holds the Azure Pipelines definitions for React Native Windows. For a
high-level tour of the stages and release flow, see
[docs/build-pipelines.md](../docs/build-pipelines.md). This README documents the
`.ado`-specific wiring that isn't obvious from the YAML: the Office/ISS template
setup and the network-isolation workarounds.

## Entry points

| Pipeline | Entry file | ADO project | 1ES template | Notes |
|----------|------------|-------------|--------------|-------|
| CI | `ci-pipeline.yml` | `ISS` | `Office.Official` | signed Official build; `trigger` branch filters and a monthly keep-alive `schedule` on `main` are defined in YAML |
| PR | `pr-pipeline.yml` | public (`ms`) | `1ES.Unofficial` | validation build for GitHub PRs; monthly keep-alive on `main` |
| Release | `release-pipeline.yml` | `ISS` | `Office.Official` | triggered by CI completion; publishes packages and symbols |
| Feed warm-up | `warm-feed-pipeline.yml` | `ISS` | `Office.Unofficial` | scheduled; keeps `ms/react-native-public` populated for anonymous PR restores |

CI and PR share all build/test/pack logic through `build-template.yml`; the
`buildEnvironment` parameter (`Continuous` vs `PullRequest`) gates the
environment-specific steps.

## Supported branches

CI, PR, Release, and the prepare-release bot all run against the same set of
branches, all driven from YAML. Keep the branch lists in `ci-pipeline.yml`,
`pr-pipeline.yml`, `release-pipeline.yml`, and `prepare-release-bot.yml` (its
`trigger` and the `targetBranch` dropdown) in sync with this table.

| Branch | Status |
|--------|--------|
| `main` | Active development |
| `0.81-stable` | LTS — last release supporting both Fabric and Paper UI |
| `0.83-stable` | Latest release − 1 |
| `0.84-stable` | Current release |
| `0.85-stable` | Preview |
| `0.86-stable` | In upstream React Native, not yet integrated |
| `0.87-stable` | In upstream React Native, not yet integrated |

`0.82-stable` is deprecated and removed from all pipelines. `0.80-stable` and
earlier are not built.

Feed warm-up (`warm-feed-pipeline.yml`, scheduled on `main`) has two passes: the
latest-patch enumeration is branch-agnostic (feed-centric), while the closure pass
reproduces the `create-react-native-library` CLI-init graph **per built release
branch**. That branch list lives in
[`warm-feed.config.json`](../packages/@rnw-scripts/warm-feed/warm-feed.config.json)
(`closure.modules.create-react-native-library.branches`) — keep it in sync with the
built branches above (it omits the not-yet-integrated ones). Branch *creation* is
governed separately by the ruleset in
[`repo-rules/`](./repo-rules/README.md).

## Template-repository wiring (per-entry `PipelineTemplates` alias)

CI runs in the internal **ISS** project and extends the **Office** 1ES templates.
PR runs in the **public** project, which cannot reach `OfficePipelineTemplates`, so
it extends the **general** 1ES templates. Azure DevOps forbids a template
expression (`${{ if }}`) on a `resources.repositories` entry, so the template repo
cannot be selected conditionally inside the shared `build-template.yml`.

The resolution: each **entry** pipeline declares the repository itself, all under a
single alias `PipelineTemplates`:

- `ci-pipeline.yml` → `1ESPipelineTemplates/OfficePipelineTemplates`
- `pr-pipeline.yml` → `1ESPipelineTemplates/1ESPipelineTemplates`
- `release-pipeline.yml` → `OfficePipelineTemplates` (standalone; does not use `build-template.yml`)

`build-template.yml` then only selects the template **path** (a template expression
*is* allowed on `extends`):

- `Continuous` → `v1/Office.Official.PipelineTemplate.yml@PipelineTemplates`
- `PullRequest` → `v1/1ES.Unofficial.PipelineTemplate.yml@PipelineTemplates`

All repository resources pin `ref: refs/tags/release`.

## Agent pools

- **CI:** `fabric-internal-pool-large` (ISS), with image `rnw-img-vs2026-node24`
  selected via `demands: ImageOverride`.
- **PR:** public `rnw-pool-4` (default) and `rnw-pool-8` (native builds), same image.

## Package feed and network isolation

ISS agents run under 1ES **Network Isolation**, which blocks egress to public CDNs.
The pipelines source packages only from the `ms/react-native-public` Azure Artifacts
feed and neutralize three background egress attempts that green builds would
otherwise hide:

- **Feed registry:** `variables/shared.yml` points npm and Yarn at the
  `ms/react-native-public` feed (`NPM_CONFIG_REGISTRY` / `YARN_NPM_REGISTRY_SERVER`).
  On CI, `templates/auth-npm-feed.yml` mints a managed-identity token and writes it
  to `~/.npmrc` and `~/.yarnrc.yml` before any install.
- **Verdaccio (CLI init tests):** `verdaccio/generate-config.js` emits the config at
  runtime, so the uplink targets the feed (with the CI token when present) while
  local packages still publish offline. The former static `config.yaml` was removed.
- **React Native DevTools:** `RNDT_DEV: 1` stops DevTools from fetching its
  standalone shell binary from a Facebook CDN when Metro starts. The debugger is
  never opened in CI, so this has no effect on tests.
- **VS Installer:** the `rnw-img-vs2026-node24` agent image sets the
  `BackgroundDownloadDisabled` policy so the VS Installer's background auto-update
  never contacts the Microsoft CDN mid-build. `templates/prepare-build-env.yml`
  reapplies the same policy per job as an interim belt until the updated image
  ships; it can be dropped once a rebuilt image is confirmed clean.

Public PR builds read this feed **anonymously**, so they can only restore versions
an authenticated identity has already saved. `warm-feed-pipeline.yml` (the
`@rnw-scripts/warm-feed` tool) runs on a schedule to re-pull the latest patch of
every npm/NuGet line already in the feed and keep those anonymous restores working.

## SDL and Component Governance

The Office template runs SDL (CredScan, BinSkim, CodeQL, Component Governance,
ESLint). PREfast, SpotBugs, and Bandit are disabled (no actionable findings for
this repo). `guardian/sdl/.gdnsuppress` is an **empty** suppression set: all
Component Governance alerts are fixed at the source (dependency `resolutions` in the
root `package.json`), so nothing is suppressed.

## Release publishing targets

`release-pipeline.yml` publishes from ISS to all five destinations:

- npm → npmjs.com via `EsrpRelease@11`
- NuGet → `ms/react-native` (private) and `ms/react-native-public` (public) feeds
- NuGet → nuget.org (API key from `OGX-JSHost-KV`)
- PDB symbols → Microsoft Symbol Server (`templates/publish-symbols.yml`)

The nuget.org publish runs 1ES Network Isolation in report-only mode
(`settings.networkIsolationMode: Audit`): `Enforce` blocks `api.nuget.org`, and the
per-domain allow-list is not plumbed for release jobs, so mode is the only
in-pipeline lever. Returning to `Enforce` requires adding nuget.org to the
`CFSClean` isolation policy for this pipeline (follow-up).

One item remains deferred: a more authoritative npm publish-eligibility check (the
current check reads the feed anonymously and sees only cached versions).

---

### Overview (`packages/README.md`)

This directory contains the npm packages hosted by the react-native-windows repo. 

## Scoped Packages

Several packages are organized into specific package scopes:

- `@office-iss`: Office internal packages
- `@react-native`: Copies of private upstream packages already using the `@react-native` scope. E.g. `@react-native/tester` for the RNTester package.
- `@react-native-windows`: Internal packages used by react-native-windows itself. Versioned and published alongside RNW.
- `@rnw-scripts`: Scripts for repository tooling. Published as part of the main branch.

## Unscoped packages

Several packages do not belong to a scope for intentional (or historical) reasons. E.g. `react-native-platform-override` isn't RNW-specific and
is unscoped. `react-native-windows-init` is run by name, and as such makes sense to be unscoped.

## Adding a new scope

> ⚠ Caution: Failing to create and give access to an NPM organization will break CI.

New package scopes for related packages can be added by adding a new directory with the scope name and prefixing the
packages name in `package.json` with the scope.

E.g. for `packages/@example-scope/create-widgets/package.json`:
```jsonc
{
  "name": "@example-scope/create-widgets",
  ...
}
```

After adding a scope directory, add the scope to the list of yarn workspaces in the repo-root `package.json`.
```jsonc
  "workspaces": {
    "packages": [
      ...
      "packages/@example-scope/*",
      ...
    ]
  },
```

Publishing a scoped package requires that the **rnbot** NPM user is an owner of an **npm organization** with the
same name as the scope. You can check whether an organization exists by viewing [npmjs.com/org/<scope>](https://www.npmjs.com/org/rnw-scripts).
See acoates for granting permissions to rnbot.

---

### Overview (`.ado/repo-rules/README.md`)

# Repository rules (rulesets)

Infrastructure-as-code for the GitHub **repository rulesets** applied to
`microsoft/react-native-windows`. Each `*.json` file in this folder is the exact
request body for GitHub's create/update ruleset REST API, so the live policy
always has a reviewable history in git. Edit the JSON, get it reviewed, then
apply it with the commands below.

## Files

| File | Ruleset name | Purpose |
|------|--------------|---------|
| [`branch-namespace-ruleset.json`](./branch-namespace-ruleset.json) | Require namespaced branches | Stops new **top-level** branches. New branches must live under an approved namespace (personal work goes under `user/<alias>/…`). |

## What `branch-namespace-ruleset.json` does

- Targets **all branches** (`~ALL`) *except* the approved patterns under
  `conditions.ref_name.exclude`.
- Applies the **`creation`** rule ("Restrict creations"): a branch whose name is
  not in the allow list cannot be created by anyone without bypass permission.
- **Creation only.** Existing branches and pushes to them are untouched — this
  refuses only *new* non-conforming branch names. The ~90 legacy top-level
  branches keep working; nobody can add more like them.
- `bypass_actors` is empty on purpose: **no one is exempt**, not even repo
  admins. (An admin can still edit or delete the ruleset itself.)

### Approved branch namespaces

| Branch pattern | Who / what uses it |
|----------------|--------------------|
| `user/<alias>/…` | Humans — the required home for personal and PR branches |
| `users/merlinbot/…` | 1ES PT auto-baselining bot |
| `dependabot/…` | Dependabot |
| `copilot/…` | Copilot coding agent |
| `chore/weekly-lock-refresh-*` | `compliance-yarn-lock.yml` weekly bot |
| `*-stable` | Release branches (e.g. `0.85-stable`) |
| `preview-*-test` | Preview test branches (e.g. `preview-0.84-test`) |
| `prepare-release/…` | Release preparation |
| `release/…`, `hotfix/…`, `archive/…` | Reserved by the [branch lifecycle policy](../../docs/branch-lifecycle-policy.md) (`archive/` is the documented way to preserve a branch) |
| `integrate/…` | React Native nightly integration (`integrate/nightly-*`) |
| `cherry-pick/…` | Cherry-pick branches |
| `revert-*` | GitHub "Revert" button on merged PRs |
| `gh-readonly-queue/…` | Merge queue (only if enabled) |
| `gh-pages` | Docs site publishing |

### Pattern syntax & gotchas

GitHub matches ref patterns with Ruby's `File.fnmatch` under the
`File::FNM_PATHNAME` flag. It has sharp edges — each point below was verified
against that engine:

- **A single `*` never crosses `/`.** `foo/*` matches exactly one level
  (`foo/bar`), never `foo/a/b`. Inside a single segment `*` is greedy, so
  `*-stable` matches both `0.85-stable` and `0.58-vnext-stable`, and
  `preview-*-test` requires the literal `-test` suffix (plain `preview-0.84` is
  blocked).
- **A bare trailing `**` does *not* cross `/` either.** `foo/**` behaves like
  `foo/*` and silently misses nested branches — never use it to mean "everything
  under `foo/`".
- **Use `foo/**/*` for a whole namespace.** The `**/` piece matches *zero or
  more* directories, so a single `foo/**/*` matches both single-level (`foo/bar`)
  and deep (`foo/a/b/c`). That is why each folder namespace needs only this one
  entry.
- **`~ALL` — not `refs/heads/**` — means "all branches".** The `include` uses the
  special `~ALL` token; a trailing `**` cannot express it (see above).
- **Every `exclude` entry keeps the `refs/heads/` prefix**; patterns match the
  full ref path, not the short branch name.
- **Reverts can contain slashes.** GitHub's "Revert" button creates
  `revert-<PR#>-<original-branch>` and preserves slashes when the original was
  namespaced (e.g. `revert-15633-user/WatsonFix/0.81`). That is why revert takes
  two entries: `revert-*` (flat) and `revert-*/**/*` (nested).
- **Matching is case-sensitive.** `fix-*` does not match `Fix-lint`.
- **Unsupported syntax:** no negated character classes (`[^…]`), no brace/extglob
  expansion (`{a,b}`, `File::FNM_EXTGLOB`), and backslash is not an escape
  character.
- **Creation-only.** The rule blocks new non-conforming branch *names*; it never
  touches existing branches or pushes to them.

## Prerequisites

1. **Admin on the repo.** Rulesets are an admin-only setting. Elevate through
   just-in-time (JIT) admin access to get the **Admin** role on
   `microsoft/react-native-windows`, and drop it when you're done.
2. **GitHub CLI**, authenticated as the elevated account:
   ```powershell
   gh --version
   gh auth login   # or set $env:GH_TOKEN
   ```

## Apply (first time)

```powershell
cd .ado/repo-rules
gh api --method POST repos/microsoft/react-native-windows/rulesets --input branch-namespace-ruleset.json
```

## Update an existing ruleset

Look up the ruleset id, then `PUT` the edited file:

```powershell
gh api repos/microsoft/react-native-windows/rulesets --jq '.[] | "\(.id): \(.name)"'
gh api --method PUT repos/microsoft/react-native-windows/rulesets/RULESET_ID --input branch-namespace-ruleset.json
```

## Change the allowed patterns

Edit `conditions.ref_name.exclude` in the JSON, commit for review, then run the
**update** command above. Add a single `refs/heads/foo/**/*` entry per folder
namespace — it matches that namespace at any depth. Mind the
[pattern gotchas](#pattern-syntax--gotchas): keep the `refs/heads/` prefix and
never use a bare `foo/**` (it will not cross `/`).

## Verify

```powershell
# A non-namespaced name should be rejected:
git push upstream HEAD:policy-smoke-test

# A namespaced name should succeed, then clean it up:
git push upstream HEAD:user/<your-alias>/policy-smoke-test
git push upstream --delete user/<your-alias>/policy-smoke-test
```

Or inspect which rules would apply to a candidate branch name (it need not exist):

```powershell
gh api repos/microsoft/react-native-windows/rules/branches/policy-smoke-test
```

## Roll back

```powershell
# Soft-disable: set "enforcement": "disabled" in the JSON and PUT it, or delete it:
gh api --method DELETE repos/microsoft/react-native-windows/rulesets/RULESET_ID
```

## Notes

- To trial the policy without blocking anyone, set `"enforcement": "evaluate"`
  first (violations are logged, not enforced), then switch to `"active"`.
- The allow list was derived from the repo's live branches plus the tooling that
  creates them: Dependabot, Copilot, [`compliance-yarn-lock.yml`](../../.github/workflows/compliance-yarn-lock.yml),
  [`integrate-rn`](../../packages/@rnw-scripts/integrate-rn), the release process,
  and the protected prefixes in the [branch lifecycle policy](../../docs/branch-lifecycle-policy.md).
- If you later want an emergency bypass, add an entry to `bypass_actors` (for
  example an `OrganizationAdmin` or a specific `Team`) rather than loosening the
  patterns.

---

### Overview (`.github/workflows/README.md`)

# GitHub Actions Workflows

This directory contains GitHub Actions workflows for the React Native Windows repository.

## Available Workflows

### Cherry-pick Commit to Branch

**File:** `cherry-pick-commit.yml`

Cherry-picks a specific commit into a target branch.

**Usage:**

1. Go to the Actions tab in the GitHub repository
2. Select "Cherry-pick Commit to Branch" workflow
3. Click "Run workflow"
4. Enter the required inputs:
   - **Commit SHA or ID**: The full commit hash or short SHA of the commit to cherry-pick
   - **Target branch name**: The branch where you want to cherry-pick the commit

**Example:**

- Commit ID: `d1a95351e5203a6c0651cf73885cd7ea99e7d2b9`
- Target branch: `0.79-stable`

**Notes:**

- The workflow will fail if there are merge conflicts during cherry-pick
- If conflicts occur, you'll need to resolve them manually
- The commit will be pushed directly to the target branch after successful cherry-pick
### Trigger AZP on Dependabot PRs

**File:** `dependabot-azp-trigger.yml`

Automatically comments `/azp run PR` on pull requests opened or updated by Dependabot, triggering Azure Pipelines CI without manual intervention. The comment is posted using rnbot's PAT (`RNBOT_GITHUB_PAT`) so AZP recognizes the trigger.

**Trigger:** Runs on `pull_request_target` events (`opened`, `synchronize`, `reopened`) when the PR author is `dependabot[bot]`.

**Setup:** Requires a `RNBOT_GITHUB_PAT` GitHub Actions secret containing rnbot's personal access token with `repo` scope.

**Notes:**

- Checks `github.event.pull_request.user.login` (not `github.actor`) so it still triggers when a maintainer clicks "Update branch"
- Fires on `opened`, `synchronize` (new pushes/rebases), and `reopened` events

---

### Overview (`packages/debug-test/README.md`)

# debug-test project

This folder contains tests to verify that the JavaScript (JS) code in ReactNative for Windows (RNW) packages can be debugged. The test
code is intended for RNW contributors; it is not meant to be published. Currently, test execution needs to be triggered manually. In
the future, CI steps should get authored to ensure that these tests get performed automatically.

## Manually Triggering Test Execution

1. Ensure the UWP Playground app has been built and its app package has been registered (i.e. the Windows Start menu contains an entry
for it). This can be achieved by building and launching the UWP Playground app from Visual Studio.
2. In a RNW dev command prompt, change into the debug-test folder.
3. With neither Metro nor the UWP Playground app running, invoke `yarn debugtest`.

This should start the UWP Playground app and Metro, and perform jest tests automating both. The jest test code contains a CDP debugger
frontend implementation through which it performs test validation steps. Test success or failure is indicated by the jest command-line
output. As the test automates the Playground app via UI automation, avoid keyboard and mouse interactions during
test execution.

## Test Design Considerations

- The RNW project is not responsible for the debugger backend implementations of JS engines. The debugging scenarios implemented in this
project do not need to be exhaustive with respect to debugging features. They should rather focus on RNW features or workflows that can
impact debuggability and debugging modes (e.g. engine- or debug-related instance options, reload/refresh operations).

- Ultimately, the test matrix should include multiple JS engines (e.g. Hermes, V8), multiple package-provisioning schemes (e.g. Metro
bundler, file-based bundles), multiple debug modes (e.g. direct debugging, web debugging) and package operations such as reloads or
refreshes. The test setup/framework should be flexible enough to accommodate these variations.

- It is assumed that a functional (debuggable) React instance requires functional native modules (in particular, a UI manager).
For that reason, the tests operate a against a "real" React host app rather than a "headless" React instance using mock native modules.

- To enable certain debugging scenarios such as top-level `debugger` statements or throwing top-level JS code, a multi-package host app
is required instead of a multi-page host app. This is the reason why the tests currently operate against the Playground app rather than
the integration test app.

## Future Improvements

- Add CI steps to automatically execute these tests.

- Enable the integration test app to load different bundles at runtime; then change tests to target integration test app instead of
Playground app.

- Investigate whether the jest test code can directly invoke the Metro JS code rather than spawning a separate Metro process.

- Automate the host app through a non-UIA channel (perhaps the same automation channel used for verification of the visual tree).

---

### Overview (`packages/e2e-test-app-fabric/README.md`)

# e2e-test-app-fabric project

This package is not published, and is just used to verify a standalone app

For information on how to run and debug this project, see [e2e-testing](https://github.com/microsoft/react-native-windows/wiki/E2E-Testing-(Fabric)).

---

### Overview (`packages/playground/README.md`)

# Playground-composition

Playground is a sample standalone application that allows testing of various JS files, including RNTester.

# Launching and Editing
## Launching the app

1. Clone [this (react-native-windows)](https://github.com/microsoft/react-native-windows) repository (or your own fork of it, if you intend on submitting PRs)

1. Make sure your development machine has been set up with all the system requirements and dependencies.  These can be verified/installed by running `.\vnext\Scripts\rnw-dependencies.ps1 -Tags 'rnwDev'` from an elevated powershell prompt.
    > **Note:** The script defaults to Visual Studio Community Edition. If you're using (or want to use) Visual Studio Enterprise Edition, run `.\vnext\Scripts\rnw-dependencies.ps1 -Tags 'rnwDev' -Enterprise`.

1. Install JavaScript dependencies within the repo by running `yarn` at the root of the repo.

1. Navigate to the `playground` folder  (`cd packages\playground`)

1. Start Metro from within **package\playground** by running `yarn start` - This dev process must be running for the application to be able to load javascript files.

1. Open the app solution file in Visual Studio `packages\playground\windows\playground-composition.sln`

1. Ensure **playground-composition.Package** project is set as startup project

1. Hit F5


## Using the app

### Configure lifted vs system compostion

Currently the application will run on either lifted composition using WinAppSDK, or using system compostion.  -- You can switch between the two from the `file -> Options` dialog.  Note this must be done before you open a javascript file from the playground app. You have to restart the application to switch between the two modes.

You can find several sample .tsx files under the `/playground/samples` folder. You can load any of these files from `file -> Open JavaScript File` in the menu bar at the top of the app.  The `Samples\rntester` javascript file is the main RNTester application provided by react-native, which has been extended with additional test pages.

### Interesting test pages for Islands work

In the `Samples\rntester` app there are a couple of test pages that host XAML controls within composition.  These are labeled `Fabric Native Component` and `Fabric Native Component Yoga`.  If you run these test pages with lifted composition you will get a "Unimplemented Component" placeholder in place of the XAML island - since Xaml islands are not hostable within lifted composition today.


## How to debug Playground

Native code can be debugged as normal through Visual Studio.  

To debug the javascript code: 

1. enable "Direct Debugger" from the `file -> options` dialog.
1. Navigate to `edge://inspect` within Microsoft Edge.  
1. Ensure `localhost:9229` is in the list of network targets within the "Discover Network Targets" configuration.
1. A remote target for "Hermes" should show up.  Click on "inspect"
1. In the Microsoft Edge Devtools window that pops up, you can hit Ctrl+p and type the name of a file to set a break point in.

---

### Overview (`packages/react-native-platform-override/README.md`)

# react-native-platform-override
Tools to manage "platform overrides" for out of tree React Native platforms.
Facilities for inventorying changes and integrating new upstream changes are included.

## Override Manifests

`react-native-platform-override` operates on a JSON "override manifest" placed
at the root of an npm package. It is expected that these are named
`overrides.json`.

An example override manifest
```json
{
  "includePatterns": [
    "src/**"
  ],
  "excludePatterns": [
    "src/README.md"
  ],
  "baseVersion": "0.0.0-10b4b9505",
  "overrides": [
    {
      "type": "derived",
      "file": ".flowconfig",
      "baseFile": ".flowconfig",
      "baseVersion": "0.0.0-56cf99a96",
      "baseHash": "8eab29258f5ad573e478324f10f850b7ccfb49c7"
    },
  ]
}
```

| Name              | Required | Description                                                     | Default  |
|-------------------|----------|-----------------------------------------------------------------|----------|
| `includePatterns` | Optional | A list of globs of files to enforce are listed in the manifest. | `["**"]` |
| `excludePatterns` | Optional | Globs to be excluded from the above list.                       | `[]`     |
| `baseVersion`     | Optional | The default react-native version of an override                 |          |
| `overrides`       | Required | List of registered overrides, added by the tooling              |          |

## Override Types
Overrides can be registered as different types, each with differing behavior.

|          |                                                                                                                  |
|----------|------------------------------------------------------------------------------------------------------------------|
| Platform | Platform-specific logic that doesn't map to an upstream file                                                     |
| Derived  | An override derived from an upstream file. Changes to the original file will be merged into the override.        |
| Patch    | An upstream file with changes made to it. Changes to the original file will be merged into the override.         |
| Copy     | An exact copy of an upstream file or directory. Overrides of this type will remain identical to their originals. |

## CLI
`react-native-platform-override` offers multiple commands to manipulate and verify the override manifest.

### `validate`
Verifies that overrides are recorded and up-to-date.

| Option              | Required | Description                                        | Default                         |
|---------------------|----------|----------------------------------------------------|---------------------------------|
| `--manifest <file>` | Optional | Path to an override manifest to validate           | Package root above cwd          |
| `--version <v>`     | Optional | A version of React Native to check against         | The currently installed version |


### `add <override>`
Adds an override to the manifest, prompting for details.

| Option            | Required | Description               |
|-------------------|----------|---------------------------|
| `<override>`      | Required | The override to add       |

### `remove <override>`
Removes an override to the manifest.

| Option            | Required | Description               |
|-------------------|----------|---------------------------|
| `<override>`      | Required | The override to remove    |

### `upgrade`
Attempts to automatically merge new changes into out-of-date overrides.

| Option              | Required | Description                                                | Default                         |
|---------------------|----------|------------------------------------------------------------|---------------------------------|
| `--manifest <file>` | Optional | Path to an override manifest to validate                   | Package root above cwd          |
| `--version <v>`     | Optional | A version of React Native to check against                 | The currently installed version |
| `--no-conflicts`    | Optional | Whether to allow upgraded files to contain conlict markers | `--conflicts`                   |

### `diff <override>`
Diffs an override against its base file. It it compared to the base file of the override's current version, even if a newer verison of
react-native is installed.

| Option                 | Required | Description                                                                                                    | Default |
|------------------------|----------|----------------------------------------------------------------------------------------------------------------|---------|
| `<override>`           | Required | The override to diff against                                                                                   |         |

## GitHub Tokens
`react-native-platform-override` makes requests to GitHub's API. An OAuth token may optionally be provided by using the `--githubToken`
parameter or setting the PLATFORM_OVERRIDE_GITHUB_TOKEN environment variable.

## Programmatic Use
`react-native-platform-override` offers a programmatic API with similar capabilities to the CLI. Take a look [here](./src/APi.ts) for details.

E.g.
```js
import {validateManifest} from 'react-native-platform-override';

const validationErrors = await validateManifest({manifestPath: 'src/overrides.json'});
```

---

### Overview (`packages/react-native-windows-init/README.md`)

# react-native-windows-init

CLI to bootstrap the addition of the Windows platform to `react-native` projects.

## Usage

Run this from an existing `react-native` project, to install `react-native-windows` and generate initial project files for windows.


Example usage
```
npx react-native-windows-init --language cpp
```

Options:
| option      | description                                    | type                                             |
|-------------|------------------------------------------------|--------------------------------------------------|
| `--help`      | Show help                                      | [boolean]                                        |
| `--version`   | The version of react-native-windows to use.    | [string]                                         |
| `--namespace` | The native project namespace.                  | [string]                                         |
| `--verbose`   | Enables logging.                               | [boolean]                                        |
| `--language`  | Which language the app is written in.          | [string] [choices: "cs", "cpp"] [default: "cpp"] |
| `--overwrite` | Overwrite any existing files without prompting | [boolean]                                        |
| `--useWinUI3`         | Targets WinUI 3 (through the [Windows App SDK](https://docs.microsoft.com/windows/apps/windows-app-sdk/)) instead of UWP XAML. | [boolean] |
| `--no-telemetry` | Disables sending telemetry that allows analysis of failures of the react-native-windows CLI | [boolean] |


## Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

This data collection notice only applies to the process of **creating** a new React Native for Windows app with the CLI.

---

### Overview (`packages/sample-app-fabric/README.md`)

# Sample Fabric App

This package is used to verify a standalone New Architecture app. It consists of a vanilla application generated using the `cpp-app` template.

# Building the app

Before starting, make sure that you have the dev dependencies installed: https://microsoft.github.io/react-native-windows/docs/rnw-dependencies

Here are the steps in order to build the sample app :
```sh
yarn
yarn windows --logging
```

The app should launch successfully, and you should see the following:

---

### Overview (`vnext/Microsoft.ReactNative.Cxx/README.md`)

# Development Note

## Important

In order to make `REACT_MODULE` cross-platform,
some C++ source files need to be shared between `react-native-windows` repo and `react-native-macos` repo.

Whenever:
- new files need to be shared

Please add this comment as in other files:
```C++
// IMPORTANT: Before updating this file
// please read react-native-windows repo:
// vnext/Microsoft.ReactNative.Cxx/README.md
```

Whenever:
- files are added to the following folders
- listed files are edited

You are required to create a pull request in `react-native-macos` to prove that your change is compatible with macOS by doing:

- Update this file: https://github.com/microsoft/react-native-macos/blob/master/ReactTurboModuleCxx/React-TurboModuleCxx-RNW.podspec
  - Change `s.source` to your own fork and commit
  - Follow the instruction to build and test `RNTester/RNTester-macOS` by running the `Snapshot/Screenshot` test page
  - Create a PR in `react-native-macos` to show the result
  - In some cases, you will also need to update files in https://github.com/microsoft/react-native-macos/tree/master/ReactTurboModuleCxx to make your change work in macOS
- Submit your change to `react-native-windows`
- Update the podspec file again with `s.source` pointing to the commit that is just submitted to `react-native-windows`
- Submit your change to `react-native-macos`

## Affected Files

- vnext\Microsoft.ReactNative.Cxx
  - StructInfo.h
  - JSValue.h
  - JSValue.cpp
  - JSValueTreeReader.h
  - JSValueTreeReader.cpp
  - JSValueTreeWriter.h
  - JSValueTreeWriter.cpp
  - JSValueReader.h
  - JSValueWriter.h
  - ModuleRegistration.h
  - ModuleRegistration.cpp
  - ReactPropertyBag.h
  - ReactHandleHelper.h
  - ReactNonAbiValue.h
  - ReactDispatcher.h
  - ReactNotificationService.h
  - ReactContext.h
  - ReactError.h
  - ReactPromise.h
  - ReactPromise.cpp
  - NativeModules.h
- vnext\Microsoft.ReactNative
  - JsiReader.h
  - JsiReader.cpp
  - JsiWriter.h
  - JsiWriter.cpp
  - TurboModulesProvider.h
  - TurboModulesProvider.cpp
- vnext\Shared
  - TurboModuleRegistry

---

### Overview (`vnext/Shared/README.md`)

# DO NOT ADD NEW SOURCES INTO THIS DIRECTORY

This directory will be removed, and its sources will be relocated.\
It is kept for compatibility purposes and is scheduled for removal when React Native Windows moves to React Native 0.63.

---

### Overview (`vnext/TestWebSite/README.md`)

# Integration Test Website

This is a generic ASP.NET Core application that provides arbitrary HTTP responses and WebSocket endpoints to validate React Native Windows's functionality.

It is meant to complement (and partially replace) the in-process C++ test servers used for integration  which have very limited functionality and are hard to program against.

This application enhances web testing via a number of features such as:
- Server-side Origin Policy (CORS) enforcement
- Static file serving
- HTTP authentication and authorization
- HTTP sessions
- Response caching
- Cookie handling

Deploying this website in Continuous Integration/Delivery environments also removes the dependency on remote web endpoints for end to end scenarios.

## Usage

### Developer Workflow

1.  Build React Native Windows.
1.  Start the Node Packager.
    ```pwsh
    Set-Location vnext
    npm run start
    ```
1.  Trust the .NET-provided development SSL certificate:\
    This should be a one-time step per .NET version.\
    See https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl#trust-the-aspnet-core-https-development-certificate-on-windows-and-macos.
    ```cmd
    dotnet dev-certs https --trust
    ```
1.  Start this website.
    ```cmd
    dotnet run --project vnext\TestWebSite
    ```
1.  Run integration tests.

### Continuous Integration Workflow
The website gets deployed to a web server.\
This reduces the process management overhead and increases stability and availability in CI environments.

The website can also be installed on a development environment.\
*Note: This would require to update the website's publish directory with any new changes, but removes the need to manage the additonal process and terminal window.*

Here are the steps for Micrososoft's IIS:
1.  Publish the website.
    ```pwsh
    Set-Location vnext\TestWebSite
    dotnet publish
    ```
1.  Install IIS.
1.  Install the .NET 7 SDK.\
    https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-7.0.407-windows-x64-installer
1.  Install the ASP.NET Core Hosting Bundle.\
    https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-8.0.3-windows-hosting-bundle-installer
1.  Create or update a website that binds ports `5555` to `http` and `5543` to `https`.\
    *For `https`, any trusted SSL certificate will work. There is no need to install `localhost.cicert`.*
    1.  Set the location to the publish directory (i.e. `C:\repo\react-native-windows\vnext\target\x64\Debug\Microsoft.ReactNative.Test.Website\Publish`)

## Technical Information

- The website is meant to run on ports `5555` (`http`, `ws`) and `5543` (`https`, `wss`).\
  This can be modified via command line arguments or in [Properties/launchSettings.json](Properties/launchSettings.json).
- For encryption, self-signed PKCS12 certificate `localhost.cicert` is used (DevOps only).
  The certificate is set to expire on January 1st, 2030.\
  After that date, new one must be generated.

### Replacing the DevOps SSL certificate

1.  Generate a new self-signed x509 web certificate.\
    Use common name `CN=localhost`.
1.  Replace the `localhost.cicert` with the new certificate.
1.  Update the password in the Continuous Integration system.\
    *The certificate password is mapped to DevOps variable `$(TestWebsiteCertPassword)`.*

---

### Overview (`vnext/proposals/readme.md`)

# Proposals for React Native for Windows

This folder contains archived and in-progress proposals for features that are more substantial than simple bug fixes and would benefit from additional review and documentation specific to `react-native-windows @vnext`. 

[Active Proposal List](https://github.com/microsoft/react-native-windows/pulls?q=is%3Aopen+is%3Apr+label%3AProposal)

## Some notes:
The proposal process here takes its inspiration from the react-native-community [discussions-and-proposals](https://github.com/react-native-community/discussions-and-proposals) as well as the [Windows UI Library](https://github.com/microsoft/microsoft-ui-xaml-specs) spec processes.

- For features that could be submitted to `react-native` and are not specific to _Windows_, please follow the workflow outlined in [discussions-and-proposals](https://github.com/react-native-community/discussions-and-proposals). 
   - We are currently staging feature improvement proposals that will accrue value to `react-native` and are originating from `react-native-windows` in a fork here - [ReactWindows/discussions-and-proposals](https://github.com/ReactWindows/discussions-and-proposals)
- For features that need to be addressed by the native Windows platform, please follow the [Windows UI Library](https://github.com/microsoft/microsoft-ui-xaml-specs) proposal process.

## Proposal process

1. Follow the steps outlined in [Contribution guidelines](../../docs/contributing.md) to set up your fork and branch to begin contributing.

2. Create a new folder for your proposal under the [active](active/readme.md) folder

3. Author your proposal using the [proposal template](https://github.com/react-native-community/discussions-and-proposals/blob/master/proposals/0000-template.md).  

4. When your proposal is ready for review:
   * Open a new pull request to merge your proposal to the ```main``` branch
   * Update the related issue(s) with a link to the proposal PR
   * Add the label - `Proposal` - to your PR so it shows up in the active proposals list.

5. For react-native-windows team members : Review proposal in checkpoint meetings to close open issues. 
   For community members submitting proposals : The team will pick up an active proposal to do more internal reviews if there are outstanding questions and loop back on the PR.

6. When your proposal is complete and signed off, merge the PR.

7. Once the feature has been implemented and shipped:
   * Add the following header to your proposal:
     > This proposal is archived and the feature was shipped as part of `<insert react-native-windows @vnext version number>`
   * Move your proposal from [active](active/readme.md) to [archive](archive/readme.md)

---

### Overview (`.github/skills/rnw-integration/README.md`)

# RNW Integration Skill

Automates upgrading React Native Windows to newer upstream React Native nightly builds.

## What This Skill Does

This skill guides GitHub Copilot through the full RNW integration workflow — from finding the next nightly version to building and deploying the Playground app. It handles version updates, override upgrades, merge conflict resolution, and build validation.

## Prerequisites

Before running this skill, ensure you have:

- **Node.js** >= 22 installed
- **Yarn** package manager (the repo uses Yarn Berry / v4)
- **Visual Studio 2022** with:
  - C++ Desktop development workload
  - Windows App SDK
  - Windows 10/11 SDK
- **Git** configured with access to:
  - Your RNW fork (origin)
  - `https://github.com/Microsoft/react-native-windows` (upstream)
- **Developer Mode** enabled in Windows Settings (for app sideloading)

## How to Use

### Option 1: Run the Full Integration

Type in VS Code Copilot Chat:
```
/rnw-integration run all steps
```

### Option 2: Run Specific Steps

```
/rnw-integration run step 1 to 5
/rnw-integration run step 11
/rnw-integration run step 12
```

### Option 3: Just Find the Next Version

```
/rnw-integration find next nightly version
```

## Steps Overview

| Step | Description | Automated? |
|------|-------------|-----------|
| 1-5 | Find current version, calculate target date, query npm | Yes |
| 6 | Run `yarn integrate-rn <version>` | Yes |
| 7 | Update remaining package.json files | Yes |
| 8 | Clean node_modules and reinstall dependencies | Yes |
| 9 | Run `npx react-native-platform-override upgrade` | Interactive |
| 10 | Commit changes | Yes |
| 11 | Replace failing overrides from upstream | Yes |
| 12 | Resolve merge conflicts (human-in-the-loop) | Per-hunk approval |
| 13 | Update yarn.lock, build Playground composition app | Yes (long build) |
| 14 | Deploy and launch Playground | Yes |

## Key Concepts

### Nightly Versions
React Native publishes nightly builds with the format:
```
0.XX.0-nightly-YYYYMMDD-<commit-hash>
```
RNW integrates every ~7 days by advancing to a newer nightly.

### Overrides
RNW maintains platform-specific copies of upstream files (`.windows.js`, `.win32.js`). The override system tracks which upstream files are copied and detects when they change.

### Merge Conflicts
When upstream changes conflict with RNW's Windows-specific modifications, conflicts appear as `<<<<<<< Upstream` / `>>>>>>> Override` markers. Step 11 resolves these with human approval.

### Conflict Resolution Patterns
Historical patterns are documented in `references/conflict-patterns.md`. The skill uses these to propose resolutions with confidence levels (Low/Medium/High).

## File Structure

```
.github/skills/rnw-integration/
├── README.md                          # This file
├── SKILL.md                           # Main skill instructions
├── references/
│   └── conflict-patterns.md           # Historical conflict resolution patterns
└── scripts/                           # (future automation scripts)
```

## Common Issues

### Build fails with "Yarn packages are out of date"
Run `yarn install` in the repo root before building.

### Build fails with missing Boost headers
Run NuGet restore:
```powershell
msbuild <solution.sln> /t:Restore /p:Configuration=Debug /p:Platform=x64
```

### MSIX install fails with "No signature was present" (0x800B0100)
Debug builds are not signed. Use loose layout registration instead:
```powershell
Add-AppxPackage -Register <path>\AppxManifest.xml -ForceApplicationShutdown
```

### MSBuild file locking errors (midl.exe)
A previous build process is still running. Clean the build directory:
```powershell
Remove-Item -Recurse -Force vnext\build -ErrorAction SilentlyContinue
```

### Override validation fails after integration
Run Step 10 to replace failing overrides from upstream, then Step 11 to resolve remaining conflicts.

## Tips

- The build (Step 12) takes 15-30 minutes for a clean build
- When resolving conflicts, respond "Yes to all remaining" if all hunks are High confidence
- Always check the upstream compare URL before accepting conflict resolutions
- The major version (e.g., 0.84 → 0.85) may change between nightlies

---

### Overview (`packages/@office-iss/react-native-win32/README.md`)

# @office-iss/react-native-win32

**Internal use only**

To better support some of our open source efforts, we are publishing this @office-iss/react-native-win32 JS package that office uses on win32. This is not a package that is generally consumable by other since it requires Office's UI framework which isn't open source. But it does allow some of our other cross platform efforts to be able to open source their work where previously its been unable to if Office win32 was one of the target platforms. This will enable projects such as our cross platform component libraries to be able to be published to open source.

# Running react-native on win32.

We do have a solution for running react-native in a win32 app.  You can run react-native-windows on win32 using Xaml Islands.  We are working on expanding the set of supported Windows versions to broaden the support of that, and provide more samples of how to do that.

---

### Overview (`packages/@react-native-windows/automation-channel/README.md`)

# @react-native-windows/automation-channel

@react-native-windows/automation-channel adds support for remote procedure calls from a node client to react-native-windows server on the same machine.

## Example

_node app_
```ts
import {waitForConnection} from '@react-native-windows/automation-channel'

const rpcConnection = await waitForConnection({port: 8305});
const result = await rpcConnection.invoke("add", [2, 2])
```

_react-native-windows app_
```c++
#include "winrt/AutomationChannel.Server.h"

// AutomationChannel::CommandHandler allows registering methods
winrt::AutomationChannel::CommandHandler handler();

// Binding to a simple method
handler.BindOperation("add", [](const JSonValue& params) noexcept {
  auto addends = params.GetArray();

  auto sum = 0;
  for (const auto& addend : addends) {
    sum += addend.GetNumber();
  }
  
  return JSonValue::CreateNumberValue(sum);
});

// Methods may be bound to IAsyncAction or IAsyncOperation
handler.BindAsyncAction("performAsyncOperation", [](const JSonValue& params) noexcept -> IAsyncAction {
  co_await performLongOperation();
});

// Start server
winrt::AutomationChannel::Server rpcServer(handler);
co_await rpcServer.ProcessAllClientRequests(8305, 50ms);
```

## Installing
@react-native-windows/automation-channel supports [auto-linking](https://microsoft.github.io/react-native-windows/docs/native-modules-autolinking) to allow installation into react-native-windows applications.


## Architecture
**Reverse TCP server:** Traditional server/client roles are reversed, where the node client creates a TCP server to connect to. This helps to bypass restrictions on inbound loopback traffic to UWP apps. This low-effort solution allows bypassing the UWP AppContainer.

### Alternative approaches
- **Named pipe created inside AppContainer:** Node provides first-class support for named-pipes through `net.socket`. It is possible to create a named pipe from a UWP process which a Win32 process can then connect to, allowing traditional server/client roles. Doing this requires locating the resource local to the AppContainer, using an API like `GetAppContainerNamedObjectPath`. This likely requires FFI (with node-gyp) or native extenssions.
- **Proxy to full-trust process** The RNW application could create a full-trust process which proxies from TCP to named-pipe internal to the AppContainer. This bypasses inbound loopback restrictions, but adds complexity of deploying a separate process, requires two IPC channels.

### Protocol
@react-native-windows/automation-channel uses a TCP channel, sending JSON messages across the wire prefixed with length. Messages themselves are conformant to the [JSON-RPC](https://en.wikipedia.org/wiki/JSON-RPC) version 2.0 protocol.

---

### Overview (`packages/@react-native-windows/automation-commands/README.md`)

# @react-native-windows/automation-commands

`@react-native-windows/automation-commands` provides built-in commands that may
be used with `@react-native-windows/automation-channel` to make it easier to
test your application.

**This package is a work in progress**

## Adding to your application

**TBD**

## Commands

### dumpVisualTree

The `dumpVisualTree` command creates a JSON object corresponding to the XAML
tree under a given testID. This can be used in conjunction with snapshot
testing to validate that your native UI looks how you could expect.

```ts
import {dumpVisualTree} from '@react-native-windows/automation-commands';

test('Widget', async () => {
  const dump = await dumpVisualTree('widget-test-id');
  expect(dump).toMatchSnapshot();
});
```

#### Options
**TBD**

---

### Overview (`packages/@react-native-windows/automation/README.md`)

# @react-native-windows/automation

`@react-native-windows/automation` makes it easy to perform UI tests against
your `react-native-windows` application using Jest. 

**This package is a work in progress**

## System Requirements

`@react-native-windows/automation` relies on [WinAppDriver 1.2.1](https://github.com/microsoft/WinAppDriver/releases/tag/v1.2.1)
or later to manipulate and inspect your application via [Windows UI Automation](https://docs.microsoft.com/en-us/dotnet/framework/ui-automation/ui-automation-overview).
This is already installed in common CI environments like GitHub Actions or
Azure Pipelines hosted images.

## Configuring Jest

First, ensure that `@react-native-windows/automation` is included as a
dependency in your package:

```json
{
  "devDependencies": {
    "@react-native-windows/automation": "<version>",
  }
}
```

Next, edit your [Jest configuration](https://jestjs.io/docs/configuration) to
use `@react-native-windows/automation` as your test environment. Add the
following to your `jest.config.js` or `jest.config.ts` file:

```js
module.exports = {
...
  // Set up the automation environment before running tests
  testEnvironment: '@react-native-windows/automation',

  // Only run a single test at a time
  maxWorkers: 1,

  // Set up @react-native-windows/automation specific options (see below)
  testEnvironmentOptions: {
    app: '<AppName>',
  },
};
```

## Environment Options

`@react-native-windows/automation` is configured via the
`testEnvironmentOptions` property in your Jest configuration. The following
options are valid:

```js
testEnvironmentOptions: {
  // Required: Your application to launch, as either an AppX package identity,
  // or path to an .exe for an unpackaged application.
  app: 'Microsoft.WindowsAlarms',

  /**
   * Optional: Arguments to be passed to your application when launched
   */
  appArguments: '--bundle testBundle.js';

  // Optional: Explicit path to WinAppDriver. By default,
  // `@react-native-windows/automation` tries to use
  // "%PROGRAMFILES(X86)%\Windows Application Driver\WinAppDriver.exe"
  winAppDriverBin: 'D:\\WinAppDriver.exe',

  // Optional: Whether to break on app launch, before starting tests 
  breakOnStart: false,

  // Optional: Options to be passed to WebDriverIO
  // See https://webdriver.io/docs/options/
  webdriverOptions: {
      // Port to use for WebDriver server (Default 4723)
      port: 4444

      // Level of logging verbosity: trace | debug | info | warn | error
      logLevel: 'error',

      // Default timeout for all waitFor* commands.
      waitforTimeout: 60000,

      // Default timeout in milliseconds for request
      connectionRetryTimeout: 90000,

      // Default request retries count
      connectionRetryCount: 10,
    },
},
```

## Writing Tests

`@react-native-windows/automation` exports an `app` member with functions to
perform globally scoped WebDriver commands, such as locating an element or
waiting for a condition. Several strategies are present to locate an element,
with the reccomended being to use React Native's `testID` property.

A located `AutomationElement` exposes methods to allow application interaction
and introspection, such as clicking or typing.

```js
import {app} from '@react-native-windows/automation';

beforeAll(async () => {
  const appHeader = await app.findElementByTestID('app-header');

  await app.waitUntil(async () => {
    const headerText = await appHeader.getText();
    return headerText.includes('Welcome');
  }) 
});

test('Type abc', async () => {
  const textInput = await app.findElementByTestID('textinput-field');
  await textInput.setValue('abc');
  expect(await textInput.getText()).toBe('abc');
});
```

## Performing Additional Actions

**WIP Not yet exposed**

Sometimes it is useful to exmaine or manipulate the application in ways that
are not exposed to Windows UI Automation. An additional package,
`@react-native-windows/automation-channel` can be included in your application
as a native module to allow writing custom commands performed by your
application in-process. Some pre-built commands can be included using the
`@react-native-windows/automation-commands` package.

## Visual Comparison

**WIP Not yet exposed**

A common use-case of UI testing is to ensure your components look the way you
expect. Tools like [enzyme](https://github.com/enzymejs/enzyme) allow
inspecting your React component tree, but are oblivious to the native UI tree.

`@react-native-windows/automation-commands` exposes a `dumpVisualTree` command
which creates a JSON object corresponding to the XAML tree under a given
testID. This can be used in conjunction with snapshot testing to validate
native component logic stays consistent.

```js
import {dumpVisualTree} from '@react-native-windows/automation-commands';

test('Widget', async () => {
  const dump = await dumpVisualTree('widget-test-id');
  expect(dump).toMatchSnapshot();
});
```

---

### Overview (`packages/@react-native-windows/cli/README.md`)

# @react-native-windows/cli

CLI to build and run React Native for Windows apps.

## `autolink-windows`

The `autolink-windows` CLI command is used to link the native code and build systems for a React Native for Windows app with any native community modules it uses.

**Note:** Autolinking runs automatically as part of running the `run-windows` CLI command, unless the `--no-autolink` argument is used.

### Usage
Runs Windows-specific autolinking for your RNW project.
  
```bat
npx @react-native-community/cli autolink-windows
```
### Options

Here are the options that `npx @react-native-community/cli autolink-windows` takes:
| Option                | Input Type | Description                                      |
|-----------------------|------------|--------------------------------------------------|
| `--logging`           | boolean    | Verbose output logging                           |
| `--check`             | boolean    | Only check whether any autolinked files need to change |
| `--sln`               | string     | Override the app solution file determined by 'npx @react-native-community/cli config', i.e. `windows\myApp.sln` |
| `--proj`              | string     | Override the app project file determined by 'npx @react-native-community/cli config', i.e. `windows\myApp\myApp.vcxproj` |
| `--no-telemetry`      | boolean    | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI |
| `-h`, `--help`        | boolean    | Display help for command                         |

## `codegen-windows`

The `codegen-windows` CLI command is used to generate some necessary Windows-specific native code for native modules.

### Usage
Runs Windows-specific codegen for native modules.
  
```bat
npx @react-native-community/cli codegen-windows
```
### Options

Here are the options that `npx @react-native-community/cli codegen-windows` takes:
| Option                | Input Type | Description                                      |
|-----------------------|------------|--------------------------------------------------|
| `--logging`           | boolean    | Verbose output logging                           |
| `--check`             | boolean    | Only check whether any codegen files need to change |
| `--no-telemetry`      | boolean    | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI |
| `-h`, `--help`        | boolean    | Display help for command                         |

## `init-windows`

The `init-windows` CLI command is used to initialize a new React Native for Windows project inside an existing React Native project. 

### Usage
Initializes a new RNW project from a given template.
  
```bat
npx @react-native-community/cli init-windows
```
### Options

Here are the options that `npx @react-native-community/cli init-windows` takes:
| Option                | Input Type | Description                                      |
|-----------------------|------------|--------------------------------------------------|
| `--logging`           | boolean    | Verbose output logging                           |
| `--template`          | string     | Specify the template to use                      |
| `--name`              | string     | The native project name. Defaults to the name property in `app.json` or `package.json` |
| `--namespace`         | string     | The native project namespace, expressed using dots as separators, i.e. `Level1.Level2.Level3`. Defaults to the same as name |
| `--overwrite`         | boolean    | Overwrite any existing files without prompting  |
| `--no-telemetry`      | boolean    | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI |
| `-h`, `--help`        | boolean    | Display help for command                         |

## `run-windows`

The `run-windows` CLI command is used to build and run React Native for Windows apps. 

### Usage
Builds your RNW app and starts it on a connected Windows desktop, emulator or device.
  
```bat
npx @react-native-community/cli run-windows
```
### Options

> **Note:** Remote Debugging was officially marked as [deprecated](https://github.com/react-native-community/discussions-and-proposals/discussions/734) in RN 0.73 and will be removed in a later release.

Here are the options that `npx @react-native-community/cli run-windows` takes:
| Option                | Input Type | Description                                      |
|-----------------------|------------|--------------------------------------------------|
| `--release`           | boolean    | Specifies a Release build                        |
| `--root`              | string     | Override the root directory for the project which contains the `windows` folder |
| `--arch`              | string     | The build architecture, i.e. `ARM64`, `x86`, `x64`. Defaults to system architecture |
| `--singleproc`        | boolean    | Disables multi-proc build                        |
| `--emulator`          | boolean    | Deploys the app to an emulator                   |
| `--device`            | boolean    | Deploys the app to a connected device            |
| `--target`            | string     | Deploys the app to the specified `GUID` for a device |
| `--logging`           | boolean    | Verbose output logging                           |
| `--no-packager`       | boolean    | Do not launch the packager while building        |
| `--bundle`            | boolean    | Enable Bundle configuration, i.e. `ReleaseBundle`/`DebugBundle` rather than `Release`/`Debug` |
| `--no-launch`         | boolean    | Do not launch the app after deployment           |
| `--no-autolink`       | boolean    | Do not run autolinking                           |
| `--no-build`          | boolean    | Do not build the solution                        |
| `--no-deploy`         | boolean    | Do not deploy the app                            |
| `--deploy-from-layout`| boolean    | Force deploy from layout even in Release builds |
| `--sln`               | string     | Override the app solution file determined by 'npx @react-native-community/cli config', i.e. `windows\myApp.sln` |
| `--proj`              | string     | Override the app project file determined by 'npx @react-native-community/cli config', i.e. `windows\myApp\myApp.vcxproj` |
| `--msbuildprops`      | string     | Comma separated props to pass to MSBuild, i.e. `prop1=value1,prop2=value2` |
| `--buildLogDirectory` | string     | Optional directory where MSBuild log files should be stored |
| `--info`              | boolean    | Dump environment information                     |
| `--direct-debugging`  | number     | Enable direct debugging on specified port        |
| `--no-telemetry`      | boolean    | Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI |
| `-h`, `--help`        | boolean    | Display help for command                         |
| `--client-logs`       | boolean    | Enable plain text JavaScript log streaming for all connected apps |

## Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

This data collection notice only applies to the process of running the react-native-windows CLI (i.e. the commands above).

---

### Overview (`packages/@react-native-windows/codegen/README.md`)

# @react-native-windows/codegen

Generators for @react-native/codegen targeting react-native-windows

## Usage

Coming soon..

---

### Overview (`packages/@react-native-windows/find-dotnet-tools/README.md`)

# @react-native-windows/find-dotnet-tools

Helpers to locate .NET-based tools (e.g. PowerShell) restored via `dotnet tool restore` or
available on PATH.

Used to resolve tool paths consistently across local development and CI
environments.

## Usage

Add the package as a dependency:

```json
{
  "dependencies": {
    "@react-native-windows/find-dotnet-tools": "<version>"
  }
}
```

### findPowerShell

Locates a PowerShell executable by checking, in order:

1. A `dotnet-tool`-restored copy of `pwsh.exe` (skipped in CI builds)
2. `pwsh.exe` on the system PATH

Throws an error if `pwsh.exe` cannot be found.

```js
import {findPowerShell} from '@react-native-windows/find-dotnet-tools';

const pwsh = findPowerShell();
// e.g. "C:\\Users\\user\\.nuget\\packages\\PowerShell\\7.6.1\\tools\\net10.0\\any\\win\\pwsh.exe"
```

### getNugetGlobalPackagesFolder

Returns the path to the global NuGet packages folder by checking, in order:

1. The `NUGET_PACKAGES` environment variable
2. The output of `dotnet nuget locals global-packages --list`
3. The default `~/.nuget/packages` location

```js
import {getNugetGlobalPackagesFolder} from '@react-native-windows/find-dotnet-tools';

const packagesDir = getNugetGlobalPackagesFolder();
// e.g. "C:\\Users\\user\\.nuget\\packages"
```

---

### Overview (`packages/@react-native-windows/fs/README.md`)

# @react-native-windows/fs

`@react-native-windows/fs` is a minimal-dependency drop-in replacement to `fs` with changes for
resiliency, promises, and convenience. It has several opinionated changes, targeted towards CLI
applications handling JavaScript-oriented files.



## Async Usage (Default)

`@react-native-windows/fs` exposes a Promise-based API, mostly matching that of `fs.promises`, with
several methods added [extra methods](#Extra-Methods).

```ts
// import {promises as fs} from 'fs'
import fs from '@react-native-windows/fs';

const fileContent = await fs.readFile('foo.txt');
```

## Sync Usage

`@react-native-windows/fs` exports all `fs.*Sync` Where an async version has a graceful
implementation, and the synchronous version does not, the method is marked as deprecated.

```ts
// import fs from 'fs'
import fs from '@react-native-windows/fs';

const fileContent = fs.readFileSync('foo.txt');
```

## Extra Methods

### `exists`
NodeJS deprecated `fs.exists`, and removed `fs.promises.exists`. The recommendation is to instead
acquire a lock to the file via `fs.open` for the duration of file-use. One-shot existence checks are
still useful, and because `fs.existsSync`is not deprecated, more likely means usage of blocking
synchronous APIs.

```ts
import fs from '@react-native-windows/fs';

const fooExists = await fs.exists('foo.txt');
```

### `readJsonFile` and `readJsonFileSync`

`@react-native-windows/fs` provides convenience methods to handle JSON files. The following methods
are added:

| Method | Return type |
|-|-|
| `readJsonFile<T>` | `Promise<T>` or `Promise<Record<string, unknown>>` |
| `readJsonFileSync<T>` | `T` or `Record<string, unknown>` |

```ts
import fs from '@react-native-windows/fs';

// foo is type: Record<string, unknown> by default
const foo = await fs.readJsonFile('foo.json');

// foo is type: FooProps
type FooProps = { name: string, version: string };
const foo = await fs.readJsonFile<FooProps>('foo.json');
```

## Resiliency

`@react-native-windows/fs` uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to
gracefully handle transient filesystem conditions, at the cost of extra latency. This includes
transient `EPERM`, `EACCESS`, `EMFILE`, `ENFILE`. This can be important when handling files that a
subject to antivirus, which may temporarily lock mutation of files on Windows.

## eslint
We reccomend adding the following rules to your eslint config if you would like to use
`@react-native-windows/fs` everywhere:
```js
module.exports = {
  rules: {
    'no-restricted-imports': [
      'error', {
        name: 'fs',
        message: 'Please use `@react-native-windows/fs` instead of `fs`'
      }
    ],
  }
}
```

---

### Overview (`packages/@react-native-windows/perf-testing/README.md`)

# @react-native-windows/perf-testing

Performance testing utilities for React Native Windows components.

## Overview

This package provides infrastructure for measuring and tracking performance of React Native components. It enables:

- **Automated performance regression detection** on every PR
- **Component-wise performance baselines** (mount, unmount, re-render times)
- **Lightweight perf snapshots** similar to Jest snapshots
- **Easy extensibility** for new components via base classes

## Installation

```bash
npm install @react-native-windows/perf-testing --save-dev
# or
yarn add @react-native-windows/perf-testing --dev
```

## Quick Start

### 1. Create a Performance Test

```typescript
import { ComponentPerfTestBase, IScenario } from '@react-native-windows/perf-testing';
import { View } from 'react-native';

class ViewPerfTest extends ComponentPerfTestBase {
  readonly componentName = 'View';
  readonly category = 'core' as const;
  readonly testId = 'perf-test-view';

  createComponent(props?: Record<string, unknown>) {
    return <View testID={this.testId} {...props} />;
  }

  getCustomScenarios(): IScenario[] {
    return [
      {
        name: 'nested-views',
        description: 'Test nested views performance',
        run: () => this.measureNestedViews(50),
      },
    ];
  }
}
```

### 2. Write Tests

```typescript
const viewPerfTest = new ViewPerfTest();

describe('View Performance', () => {
  test('mount time', async () => {
    const perf = await viewPerfTest.measureMount();
    expect(perf).toMatchPerfSnapshot();
  });

  test('rerender time', async () => {
    const perf = await viewPerfTest.measureRerender();
    expect(perf).toMatchPerfSnapshot();
  });
});
```

### 3. Run Tests

```bash
# Run perf tests
yarn perf

# Update baselines
yarn perf:update
```

## API Reference

### Core Functions

| Function | Description |
|----------|-------------|
| `measurePerf(component, options)` | Core measurement function |
| `toMatchPerfSnapshot(threshold?)` | Jest matcher for perf snapshots |

### Base Classes

| Class | Description |
|-------|-------------|
| `ComponentPerfTestBase` | Abstract base class for component perf tests |

### Interfaces

| Interface | Description |
|-----------|-------------|
| `PerfMetrics` | Measurement results |
| `PerfThreshold` | Pass/fail thresholds |
| `IComponentPerfTest` | Contract for component tests |
| `IScenario` | Custom scenario interface |

### Threshold Presets

```typescript
import { ThresholdPresets } from '@react-native-windows/perf-testing';

// Available presets
ThresholdPresets.core       // 10% regression threshold
ThresholdPresets.list       // 15% for list components
ThresholdPresets.interactive // 20% for animated components
ThresholdPresets.community  // 25% relaxed threshold for external use
```

## Extending for Custom Components

Community developers can create perf tests for their custom native components:

```typescript
import { ComponentPerfTestBase } from '@react-native-windows/perf-testing';
import { MyCustomSlider } from 'my-custom-component';

class MyCustomSliderPerfTest extends ComponentPerfTestBase {
  readonly componentName = 'MyCustomSlider';
  readonly category = 'custom' as const;
  readonly testId = 'perf-test-slider';

  createComponent(props?: Record<string, unknown>) {
    return <MyCustomSlider testID={this.testId} {...props} />;
  }
}
```

## Configuration

### Jest Setup

Add to your Jest setup file:

```typescript
import '@react-native-windows/perf-testing/matchers';
```

### Custom Thresholds

```typescript
expect(perf).toMatchPerfSnapshot({
  maxDurationIncrease: 15,  // Allow 15% regression
  maxRenderCount: 5,
});
```

## License

MIT

---

### Overview (`packages/@react-native-windows/telemetry/README.md`)

# @react-native-windows/telemetry

Telemetry library for the react-native-windows CLI

## Usage

## Data Collection
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

---

### Overview (`packages/@rnw-scripts/doxysaurus/README.md`)

# @rnw-scripts/doxysaurus

The new Doxysaurus tool converts Doxygen generated XML to markdown files for Docusaurus.

The main goal for the tool is to generate docs for public C++ APIs defined in `Microsoft.ReactNative.Cxx` project.
Doxygen can process code comments and generate HTML, LaTeX and other formats.
To make the generated docs working with our RNW Docusaurus documentation system, we have created the new Doxysaurus tool that runs Doxygen to generate documentation XML and then converts it to the Docusaurus markdown files.

In this PR we add `cpp_generate_documentation_comments = doxygen_double_slash_exclamation` to `.editorconfig` to instruct Visual Studio and VS Code to use `//!` style comments for C++ Doxygen documentation. The `//!` makes it easy to use, while it is different from the `///` which is typically used for C# XML comments. This option enables VS to use `//!` style comments in IntelliSense and to provide autogenerated tags when we type `//!` on top of a function.

Run this command from the root of the repo to generate docs:
```
yarn doc --output ..\react-native-windows-samples\docs
```
It does the following:
- downloads Doxygen executable on-demand;
- runs Doxygen to generate XML files;
- converts the Doxygen XML into an in-memory document model;
- generates Docusaurus markdown files by applying Mustache templates to the model in the provided `output` folder;
- if the `output` folder is not provided then the markdown files are generated in the `out` folder next to the `xml` folder in the `buildDir`.

Run the Doxysaurus tool in the 'watch' mode for interactive documentation development:
```
yarn doc --watch --output ..\react-native-windows-samples\docs
```
Now we can edit C++ comments, save the file, and see the docs in the browser updated after a small delay.

---

### Overview (`packages/@rnw-scripts/generate-release-notes/ReadMe.md`)

### Type of Change
Automate release notes creation by adding a new yarn script. Automating the process of creating release notes so that we don't have to manually copy paste the commits. 


### Why
To save us some time when generating release notes. Fetches commit from start and end date range, ignores bots and creates the release notes md file. It also categorizes the commits. Please cross-check the generated release-notes.md file and update it manually if required like regrouping commits or updating the Summary/Explanation for the PR commit.

## Format

`Explanation. [PRName (#11168) · microsoft/react-native-windows@aaaaaaa (github.com)](link)`

### Steps to follow

#### 1. Set up your personal access token

- Go to GitHub and log in: https://github.com/
- Click on your profile picture (top-right corner), then click Settings
- On the left sidebar, click Developer settings
- Then click Personal access tokens > Tokens (classic)
- Click Generate new token > Generate new token (classic)
- Give it a name like "Release Notes Script"
- Set an expiration (choose less than 90 days)
- Under Scopes, select the permissions your script needs. For fetching commits and repo info, you typically need:
repo (full control of private repositories)
or at least repo:status, repo_deployment, public_repo (for public repos)
- Click Generate token
- Find the token you're using (whichever token you created).
- You should see a message or option to "Grant access to your organization" or "Authorize SAML SSO" for your token.
- Click that button to authorize the token with the organization.
- Copy the generated token

#### 2. Set variables as params and run "yarn release-notes"

```
Usage:
  yarn release-notes --token <GITHUB_TOKEN> --start <START_DATE> --end <END_DATE> [--repo <OWNER/REPO>] [--tag <RELEASE_TAG>]

Options:
  --token       (required) GitHub personal access token.
  --start       (required) Start date in YYYY-MM-DD.
  --end         (required) End date in YYYY-MM-DD.
  --repo        Repository in OWNER/REPO format. Default: microsoft/react-native-windows
  --tag         Release tag label. Default: Unreleased. Expected: 0.80 or similar
  --help        Show this help message.
```

#### 3. You will see a release-notes.md file generated at packages\@rnw-scripts\generate-release-notes\release_notes.md which will have all the data you need.

#### 4. Verify the release notes generated from all commits section and delete the "All Commits" and "Excluded" sections after validation

---

### Overview (`packages/@rnw-scripts/metro-dev-config/README.md`)

# @rnw-scripts/metro-dev-config

This package allows generating metro configs layered on top of [rnx-kit](https://github.com/microsoft/rnx-kit), to be
used by RNW development packages. This allows reduced duplication, better
diagnostics, and generic package symlinking support.

## Usage

```js
// metro.config.js
const { makeMetroConfig } = require("@rnw-scripts/metro-dev-config");

module.exports = makeMetroConfig({
  projectRoot: __dirname,
});
```

---

### Overview (`packages/@rnw-scripts/stamp-version/README.md`)

# @rnw-scripts/stamp-version

This script is responsible for stamping version and semver segments into source files within our package.

## Usage:
```cmd
yarn stamp-version <packageVersion>
```

---

### Overview (`packages/@rnw-scripts/warm-feed/README.md`)

# @rnw-scripts/warm-feed

Warms the `ms/react-native-public` Azure DevOps upstream feed so that
network-isolated PR/CI builds — which read the feed **anonymously** — can restore
the package versions they need.

An Azure Artifacts upstream feed only serves a version once an **authenticated**
identity has pulled it from upstream (which *saves* it into the feed). This tool
performs those authenticated pulls.

## How it works

The warmer is **feed-centric** — it needs no repo checkouts or lockfiles, so one
run serves every repo that shares the feed:

1. **Enumerate** the feed with the ADO Get Packages API — every npm and NuGet
   package already in the feed, plus each package's already-saved versions.
2. **Expand** each package to the latest stable patch of every `major.minor`
   line already in use (and, by default, the newest stable version overall). The
   candidate versions come from the authenticated packument / flat2 index, which
   includes not-yet-saved upstream versions.
3. **Skip** versions the feed already has (the enumeration result is the
   authoritative "already cached" set — no separate cache is needed).
4. **Warm** the rest with an authenticated GET of the tarball / `.nupkg`, which
   triggers the upstream save. The response body is streamed and discarded.

## Local usage

Auth is resolved in order: `--pat`, `$env:ADO_PAT` / `$env:AZURE_DEVOPS_EXT_PAT`,
`$env:WARM_FEED_TOKEN`, then an AAD token from `az account get-access-token`
(run `az login` first).

```powershell
# Preview what a full warm would do (no writes):
yarn warm-feed --dry-run

# Preview just one ecosystem:
yarn warm-feed --dry-run --only nuget

# Warm a specific version on demand (one-off; skips enumeration):
yarn warm-feed --packages "npm:left-pad@1.3.0"
yarn warm-feed --packages "nuget:Newtonsoft.Json@13.0.3"

# Warm everything the feed needs (mutates the feed):
yarn warm-feed
```

`yarn warm-feed` builds the package and then runs it. Common flags: `--only
npm|nuget`, `--dry-run`, `--verify` (warm even already-cached targets),
`--concurrency <n>`, `-v` / `--verbose`. See `--help` for the full list.

## Closure (graph) warming

Enumeration keeps **known** package lines fresh but can't introduce a **brand-new**
name the feed has never seen — e.g. the packages a bumped
`create-react-native-library` pulls into a generated project. Closure warming
closes that gap: it resolves a dependency **graph** and warms every version in it.

The graph is resolved with `npm install --package-lock-only` (metadata only; the
feed save still happens per version). The lockfile covers the **resolve host's own
platform** (Windows x64 in CI). It can also list other-OS/CPU optional variants, but
not dependably against an Azure Artifacts upstream proxy: npm 11+ writes
not-yet-cached, non-current-platform optional deps without a `version`
(npm/cli#9342) and the parser drops version-less entries. Warming every platform's
optional deps would need a per-OS/CPU resolve.

Three ways to feed it a graph:

```powershell
# 1. Roots — warm the full npm graph of one or more packages:
yarn warm-feed --closure npm:create-react-native-library@0.63.0

# 2. Manifest — warm the external-dependency graph of a package.json:
yarn warm-feed --closure-manifest ./some/package.json

# 3. Special module — a registered reproducer for a case enumeration can't see:
yarn warm-feed --closure-module create-react-native-library
yarn warm-feed --closure-module all      # every enabled module
```

### Special modules (pluggable)

A **special module** reproduces a specific install closure and turns it into a
dependency graph to warm. They live in `src/specialModules/` and are registered
in `src/specialModules/index.ts`; add a module there and it's available to config
(`closure.modules.<name>`) and `--closure-module <name>`.

The first module, **`create-react-native-library`**, reproduces the CLI-init lib
test: the test scaffolds a library (+ vanilla example app) and installs *that
generated project*, so its closure — not cRNL's own dependencies — is what the
feed needs. warm-feed runs only from `main`, but the test runs on every release
branch pinned to a different React Native, so the module's config manifest lists
all branches and, per branch, derives the RN/CLI versions (nightly for `main`
from the working-tree `vnext/package.json`; for `0.NN-stable`, the exact
`react-native` that branch pins in its own `vnext/package.json`, read via git),
scaffolds, and reads the generated manifests. Mirrors
`vnext/Scripts/creaternwlib.cmd`.

For a nightly library, both paths run
`vnext/Scripts/GetReactNativeLibraryScaffoldVersion.js`. Its bootstrap is the
generator's own supported React Native version: cRNL 0.63.0 declares
`SUPPORTED_REACT_NATIVE_VERSION = 0.85.0`. The resolver checks that exact
`react-native` and matching `@react-native-community/template` through the
caller's configured npm registry; it never selects a dist-tag. A lookup failure
stops that branch rather than falling back. The resolver runs from the selected
checkout, so `--repo-root` accepts absolute or relative paths, including checkout
names with spaces. When upgrading cRNL, update and
smoke-test this bootstrap alongside the generator version in the CLI and config.
Stable branches still scaffold their exact RN version. After a nightly scaffold,
the library and example dependencies are rewritten to the requested RN/CLI before
resolving their separate closures. The scaffold itself downloads the bootstrap
generator/template through the same registry, so these must also be available to
anonymous CI; authenticated warming remains an out-of-band maintainer operation.

The second module, **`create-react-native-app`**, is the app counterpart: it
reproduces the CLI-init *app* test, which scaffolds a standalone app with
`@react-native-community/cli init` (pulling `@react-native-community/template`)
and installs *that generated app* — so its closure (e.g.
`react-native-safe-area-context`) is what the feed needs. It reuses the same
per-branch RN/CLI/RNW version resolution and mirrors
`vnext/Scripts/creaternwapp.cmd`, including that script's template selection: a
stable branch lets the CLI pick the template matching its React Native, while a
nightly RN overrides it to a fixed stable `@react-native-community/template`
(`nightlyTemplate`, default `@react-native-community/template@0.86.0`). Keep that
default in sync with the `#15124` override in `creaternwapp.cmd`.

The scheduled pipeline run warms every **enabled** configured module in addition
to the latest-patch sync, so brand-new closures stay warm automatically.

### NuGet lock closure

The special modules above are npm-only. NuGet has the same gap — enumeration only
refreshes lines already in the feed — for which the repo's committed
`packages.lock.json` files are the source of truth: they pin the full resolved
NuGet closure (incl. transitives) every project restores. warm-feed scans them and
warms every `name@resolved` they list, so a brand-new NuGet package (or an exact
non-latest pinned version) restores under isolation.

The scheduled pass does this automatically (unless `closure.nugetLocks.enabled` is
`false`, or `--only npm`); `--nuget-locks` runs just this pass one-off. Scanning is
local (no feed access), so it is included in a `--dry-run` plan. By default it
scans the repo root (`--repo-root`, default cwd), pruning `node_modules`; narrow it
with `closure.nugetLocks.roots`.

## Pipeline usage

`.ado/warm-feed-pipeline.yml` runs the tool on a schedule (and on manual queue)
in the office/ISS project, on the isolated pool, extending the Office Unofficial
1ES template. An `AzureCLI@2` step logs in as the managed identity and mints its
feed token into `WARM_FEED_TOKEN`, then runs `npx warm-feed`.

Warming runs **out of band** — never in a PR build — because saving into the feed
needs the managed identity. To warm a version a PR/Dependabot introduced, a
maintainer queues the pipeline with the `packages` parameter
(`npm:foo@1.2.3 nuget:Bar@4.0.0`); the rights gate is ADO "Queue builds".

## Config

`warm-feed.config.json`:

| Key | Meaning |
| --- | --- |
| `feeds.npm.registry` / `feeds.nuget.index` | Feed endpoints to warm. |
| `enumerate.feedManagementBase` | Feed Management base (`https://feeds.dev.azure.com/<org>/<project>/_apis/packaging/Feeds/<feed>`). |
| `enumerate.apiVersion` / `enumerate.pageSize` | Get Packages API version and page size. |
| `expand.scope` | `in-use-lines` (latest patch per `major.minor`) or `in-use-majors` (latest per major). |
| `expand.includeLatest` | Also warm the newest stable version overall. |
| `expand.includePrerelease` | Include prerelease versions. |
| `expand.maxMajorsBack` | Limit to the N most-recent majors already in use (0 = no limit). |
| `concurrency` | Parallel requests. |
| `ignore` | `id`, `id@version`, or `eco:id@version` entries to skip. |
| `closure.registry` | npm registry for closure resolution (defaults to `feeds.npm.registry`). |
| `closure.modules` | Per-module config blocks (e.g. `create-react-native-library`), keyed by module name; each may set `enabled: false`. |
| `closure.nugetLocks` | NuGet `packages.lock.json` closure: `enabled` (default true) and `roots` (repo-relative dirs to scan; default repo root). |

## Scope and limitations

- The enumeration pass warms **latest patch per in-use line**, not a specific
  build's exact lockfile-pinned closure. A build pinning an older patch is not
  guaranteed by that pass alone — use closure warming for exact graphs.
- Enumeration cannot introduce a **brand-new package name** the feed has never
  seen, nor an exact non-latest pinned version. Covered instead by closure warming:
  for **npm** a special module, `--closure`, or `--closure-manifest`; for **NuGet**
  the `packages.lock.json` closure (above). The authenticated CI build that first
  restores a package, or a one-off `--packages` warm, also cover it.
- Closure resolution needs `npm` on `PATH` (bundled with Node) and, for special
  modules that scaffold, network access to the feed for the generator.

---

### Overview (`vnext/Mso/dispatchQueue/README.md`)

# dispatchQueue liblet

The **dispatchQueue** liblet implements concurrent and serial dispatcher queues.

The *serial* dispatcher queues execute items sequentially one-by-one. They can
be used as a replacement for threads. Unlike threads they provide more control
over the execution and are not so expensive because in most common cases
dispatch queues only use threads while performing work, and release threads
when there is no pending work.

The default *concurrent* dispatcher queue is a thin wrapper over the platform
specific thread pool. There is also a custom concurrent queue that limits number
of simultaneously running tasks.

## Scheduling tasks for execution

There are two ways how a task can be scheduled for execution: post task to the
end of queue, and to try to execute task immediately if it is possible or else
post to the end of queue.

## Task execution

Tasks are invoked using the underlying platform execution mechanism such as a
thread or a thread pool. For each task queue establishes its context in the
thread local storage.

## Yielding tasks

Some tasks may require more time to execute, but it is important to 'play by the
rules' and allow other tasks in the application to make progress. For the long
running tasks or tasks with lower priority it is suggested to periodically call
ShouldYield() function that indicates that task should yield. It may become true
for one the following reasons: queue is shutting down, the time quota is expired,
or task execution is suspended.

## Task batching

Sometimes it is expensive to execute tasks one-by-one, or there is a requirement
that all tasks in a group are completed. For such scenarios, the dispatch queues
are offering batching mechanism. It is important to understand that a task batch
created in a thread that is posting tasks to the target queue to ensure the
atomic execution guarantee. From the point of view of the target dispatcher
queue, the batch is a just a single task. The batch is created in the thread
local storage and must be submitted or canceled before next batch is started.

## dispatchQueue shutdown

After a queue is shutdown, all newly submitted tasks are canceled. When we
start shutdown we have a choice what to do with the pending tasks in the queue.
They can be either completed or canceled. We cannot cancel a task that is being
executed. We notify yielding task about the queue shutdown, but we must wait
until task is finished.

## dispatchQueue local storage

The dispatch queues allow to associate thread local variables with a queue.
When task is executed, it can lock a queue local value (QLV) that swaps it with a
TLS variable. Unlocking the queue local value swaps it back with the TLS value.
While the QLV is locked it can be read or written to.
When queue is shutdown, it calls destructors for all registered TLS
variables. The QLV is destroyed in a thread that destroys dispatch queue.

## Suspending task execution

A dispatch queue has an API that allows to suspend and resume task execution.
This mechanism can be used for low priority tasks that could be suspended during
perf critical operations such as application boot or when user interacting with
the application.

---

### Overview (`vnext/Mso/future/README.md`)

# The future liblet

The **future** liblet implements support for task coordination.
It allows specify a continuation for the current future in case if it is
completed successfully or failed. It also allows to coordinate groups of futures
such as observing if all futures in the group are completed, or at least one is
completed.

---

### Overview (`vnext/external/fast-float/README.md`)

## fast_float number parsing library: 4x faster than strtod

[](https://github.com/fastfloat/fast_float/actions/workflows/ubuntu22.yml)

The fast_float library provides fast header-only implementations for the C++
from_chars functions for `float` and `double` types as well as integer types.
These functions convert ASCII strings representing decimal values (e.g.,
`1.3e10`) into binary types. We provide exact rounding (including round to
even). In our experience, these `fast_float` functions many times faster than
comparable number-parsing functions from existing C++ standard libraries.

Specifically, `fast_float` provides the following two functions to parse
floating-point numbers with a C++17-like syntax (the library itself only
requires C++11):

```C++
from_chars_result from_chars(char const *first, char const *last, float &value, ...);
from_chars_result from_chars(char const *first, char const *last, double &value, ...);
```

You can also parse integer types:

```C++
from_chars_result from_chars(char const *first, char const *last, int &value, ...);
from_chars_result from_chars(char const *first, char const *last, unsigned &value, ...);
```

The return type (`from_chars_result`) is defined as the struct:

```C++
struct from_chars_result {
  char const *ptr;
  std::errc ec;
};
```

It parses the character sequence `[first, last)` for a number. It parses
floating-point numbers expecting a locale-independent format equivalent to the
C++17 from_chars function. The resulting floating-point value is the closest
floating-point values (using either `float` or `double`), using the "round to
even" convention for values that would otherwise fall right in-between two
values. That is, we provide exact parsing according to the IEEE standard.

Given a successful parse, the pointer (`ptr`) in the returned value is set to
point right after the parsed number, and the `value` referenced is set to the
parsed value. In case of error, the returned `ec` contains a representative
error, otherwise the default (`std::errc()`) value is stored.

The implementation does not throw and does not allocate memory (e.g., with `new`
or `malloc`).

It will parse infinity and nan values.

Example:

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "3.1416 xyz ";
  double result;
  auto answer = fast_float::from_chars(input.data(), input.data() + input.size(), result);
  if (answer.ec != std::errc()) { std::cerr << "parsing failure\n"; return EXIT_FAILURE; }
  std::cout << "parsed the number " << result << std::endl;
  return EXIT_SUCCESS;
}
```

You can parse delimited numbers:

```C++
  std::string input = "234532.3426362,7869234.9823,324562.645";
  double result;
  auto answer = fast_float::from_chars(input.data(), input.data() + input.size(), result);
  if (answer.ec != std::errc()) {
    // check error
  }
  // we have result == 234532.3426362.
  if (answer.ptr[0] != ',') {
    // unexpected delimiter
  }
  answer = fast_float::from_chars(answer.ptr + 1, input.data() + input.size(), result);
  if (answer.ec != std::errc()) {
    // check error
  }
  // we have result == 7869234.9823.
  if (answer.ptr[0] != ',') {
    // unexpected delimiter
  }
  answer = fast_float::from_chars(answer.ptr + 1, input.data() + input.size(), result);
  if (answer.ec != std::errc()) {
    // check error
  }
  // we have result == 324562.645.
```

Like the C++17 standard, the `fast_float::from_chars` functions take an optional
last argument of the type `fast_float::chars_format`. It is a bitset value: we
check whether `fmt & fast_float::chars_format::fixed` and `fmt &
fast_float::chars_format::scientific` are set to determine whether we allow the
fixed point and scientific notation respectively. The default is
`fast_float::chars_format::general` which allows both `fixed` and `scientific`.

The library seeks to follow the C++17 (see
[28.2.3.(6.1)](https://eel.is/c++draft/charconv.from.chars#6.1)) specification.

* The `from_chars` function does not skip leading white-space characters (unless
  `fast_float::chars_format::skip_white_space` is set).
* [A leading `+` sign](https://en.cppreference.com/w/cpp/utility/from_chars) is
  forbidden (unless `fast_float::chars_format::allow_leading_plus` is set).
* It is generally impossible to represent a decimal value exactly as binary
  floating-point number (`float` and `double` types). We seek the nearest value.
  We round to an even mantissa when we are in-between two binary floating-point
  numbers.

Furthermore, we have the following restrictions:

* We support `float` and `double`, but not `long double`. We also support
  fixed-width floating-point types such as `std::float64_t`, `std::float32_t`,
  `std::float16_t`, and `std::bfloat16_t`.
* We only support the decimal format: we do not support hexadecimal strings.
* For values that are either very large or very small (e.g., `1e9999`), we
  represent it using the infinity or negative infinity value and the returned
  `ec` is set to `std::errc::result_out_of_range`.

We support Visual Studio, macOS, Linux, freeBSD. We support big and little
endian. We support 32-bit and 64-bit systems.

We assume that the rounding mode is set to nearest (`std::fegetround() ==
FE_TONEAREST`).

## Integer types

You can also parse integer types using different bases (e.g., 2, 10, 16). The
following code will print the number 22250738585072012 three times:

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  uint64_t i;
  std::string str = "22250738585072012";
  auto answer = fast_float::from_chars(str.data(), str.data() + str.size(), i);
  if (answer.ec != std::errc()) {
    std::cerr << "parsing failure\n";
    return EXIT_FAILURE;
  }
  std::cout << "parsed the number " << i << std::endl;

  std::string binstr = "1001111000011001110110111001001010110100111000110001100";

  answer = fast_float::from_chars(binstr.data(), binstr.data() + binstr.size(), i, 2);
  if (answer.ec != std::errc()) {
    std::cerr << "parsing failure\n";
    return EXIT_FAILURE;
  }
  std::cout << "parsed the number " << i << std::endl;

  std::string hexstr = "4f0cedc95a718c";

  answer = fast_float::from_chars(hexstr.data(), hexstr.data() + hexstr.size(), i, 16);
  if (answer.ec != std::errc()) {
    std::cerr << "parsing failure\n";
    return EXIT_FAILURE;
  }
  std::cout << "parsed the number " << i << std::endl;
  return EXIT_SUCCESS;
}
```

## Behavior of result_out_of_range

When parsing floating-point values, the numbers can sometimes be too small
(e.g., `1e-1000`) or too large (e.g., `1e1000`). The C language established the
precedent that these small values are out of range. In such cases, it is
customary to parse small values to zero and large values to infinity. That is
the behaviour of the C language (e.g., `stdtod`). That is the behaviour followed
by the fast_float library.

Specifically, we follow Jonathan Wakely's interpretation of the standard:

> In any case, the resulting value is one of at most two floating-point values
> closest to the value of the string matching the pattern.

It is also the approach taken by the [Microsoft C++
library](https://github.com/microsoft/STL/blob/62205ab155d093e71dd9588a78f02c5396c3c14b/tests/std/tests/P0067R5_charconv/test.cpp#L943-L946).

Hence, we have the following examples:

```cpp
  double result = -1;
  std::string str = "3e-1000";
  auto r = fast_float::from_chars(str.data(), str.data() + str.size(), result);
  // r.ec == std::errc::result_out_of_range
  // r.ptr == str.data() + 7
  // result == 0
```

```cpp
  double result = -1;
  std::string str = "3e1000";
  auto r = fast_float::from_chars(str.data(), str.data() + str.size(), result);
  // r.ec == std::errc::result_out_of_range
  // r.ptr == str.data() + 6
  // result == std::numeric_limits<double>::infinity()
```

Users who wish for the value to be left unmodified given
`std::errc::result_out_of_range` may do so by adding two lines of code:

```cpp
  double old_result = result; // make copy
  auto r = fast_float::from_chars(start, end, result);
  if (r.ec == std::errc::result_out_of_range) { result = old_result; }
```

## C++20: compile-time evaluation (constexpr)

In C++20, you may use `fast_float::from_chars` to parse strings at compile-time,
as in the following example:

```C++
// consteval forces compile-time evaluation of the function in C++20.
consteval double parse(std::string_view input) {
  double result;
  auto answer = fast_float::from_chars(input.data(), input.data() + input.size(), result);
  if (answer.ec != std::errc()) { return -1.0; }
  return result;
}

// This function should compile to a function which
// merely returns 3.1415.
constexpr double constexptest() {
  return parse("3.1415 input");
}
```

## C++23: Fixed width floating-point types

The library also supports fixed-width floating-point types such as
`std::float64_t`, `std::float32_t`, `std::float16_t`, and `std::bfloat16_t`.
E.g., you can write:

```C++
std::float32_t result;
auto answer = fast_float::from_chars(f.data(), f.data() + f.size(), result);
```

## Non-ASCII Inputs

We also support UTF-16 and UTF-32 inputs, as well as ASCII/UTF-8, as in the
following example:

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::u16string input = u"3.1416 xyz ";
  double result;
  auto answer = fast_float::from_chars(input.data(), input.data() + input.size(), result);
  if (answer.ec != std::errc()) { std::cerr << "parsing failure\n"; return EXIT_FAILURE; }
  std::cout << "parsed the number " << result << std::endl;
  return EXIT_SUCCESS;
}
```

## Advanced options: using commas as decimal separator, JSON and Fortran

The C++ standard stipulate that `from_chars` has to be locale-independent. In
particular, the decimal separator has to be the period (`.`). However, some
users still want to use the `fast_float` library with in a locale-dependent
manner. Using a separate function called `from_chars_advanced`, we allow the
users to pass a `parse_options` instance which contains a custom decimal
separator (e.g., the comma). You may use it as follows.

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "3,1416 xyz ";
  double result;
  fast_float::parse_options options{fast_float::chars_format::general, ','};
  auto answer = fast_float::from_chars_advanced(input.data(), input.data() + input.size(), result, options);
  if ((answer.ec != std::errc()) || ((result != 3.1416))) { std::cerr << "parsing failure\n"; return EXIT_FAILURE; }
  std::cout << "parsed the number " << result << std::endl;
  return EXIT_SUCCESS;
}
```

### You can also parse Fortran-like inputs

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "1d+4";
  double result;
  fast_float::parse_options options{fast_float::chars_format::fortran};
  auto answer = fast_float::from_chars_advanced(input.data(), input.data() + input.size(), result, options);
  if ((answer.ec != std::errc()) || ((result != 10000))) { std::cerr << "parsing failure\n"; return EXIT_FAILURE; }
  std::cout << "parsed the number " << result << std::endl;
  return EXIT_SUCCESS;
}
```

### You may also enforce the JSON format ([RFC 8259](https://datatracker.ietf.org/doc/html/rfc8259#section-6))

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "+.1"; // not valid
  double result;
  fast_float::parse_options options{fast_float::chars_format::json};
  auto answer = fast_float::from_chars_advanced(input.data(), input.data() + input.size(), result, options);
  if (answer.ec == std::errc()) { std::cerr << "should have failed\n"; return EXIT_FAILURE; }
  return EXIT_SUCCESS;
}
```

By default the JSON format does not allow `inf`:

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "inf"; // not valid in JSON
  double result;
  fast_float::parse_options options{fast_float::chars_format::json};
  auto answer = fast_float::from_chars_advanced(input.data(), input.data() + input.size(), result, options);
  if (answer.ec == std::errc()) { std::cerr << "should have failed\n"; return EXIT_FAILURE; }
  return EXIT_SUCCESS;
}
```

You can allow it with a non-standard `json_or_infnan` variant:

```C++
#include "fast_float/fast_float.h"
#include <iostream>

int main() {
  std::string input = "inf"; // not valid in JSON but we allow it with json_or_infnan
  double result;
  fast_float::parse_options options{fast_float::chars_format::json_or_infnan};
  auto answer = fast_float::from_chars_advanced(input.data(), input.data() + input.size(), result, options);
  if (answer.ec != std::errc() || (!std::isinf(result))) { std::cerr << "should have parsed infinity\n"; return EXIT_FAILURE; }
  return EXIT_SUCCESS;
}
```

## Users and Related Work

The fast_float library is part of:

* GCC (as of version 12): the `from_chars` function in GCC relies on fast_float,
* [Chromium](https://github.com/Chromium/Chromium), the engine behind Google
  Chrome, Microsoft Edge, and Opera,
* [WebKit](https://github.com/WebKit/WebKit), the engine behind Safari (Apple's
  web browser),
* [DuckDB](https://duckdb.org),
* [Redis](https://github.com/redis/redis) and [Valkey](https://github.com/valkey-io/valkey),
* [Apache Arrow](https://github.com/apache/arrow/pull/8494) where it multiplied
  the number parsing speed by two or three times,
* [Google Jsonnet](https://github.com/google/jsonnet),
* [ClickHouse](https://github.com/ClickHouse/ClickHouse).

The fastfloat algorithm is part of the [LLVM standard
libraries](https://github.com/llvm/llvm-project/commit/87c016078ad72c46505461e4ff8bfa04819fe7ba).
There is a [derived implementation part of
AdaCore](https://github.com/AdaCore/VSS).

The fast_float library provides a performance similar to that of the
[fast_double_parser](https://github.com/lemire/fast_double_parser) library but
using an updated algorithm reworked from the ground up, and while offering an
API more in line with the expectations of C++ programmers. The
fast_double_parser library is part of the [Microsoft LightGBM machine-learning
framework](https://github.com/microsoft/LightGBM).

## References

* Daniel Lemire, [Number Parsing at a Gigabyte per
  Second](https://arxiv.org/abs/2101.11408), Software: Practice and Experience
  51 (8), 2021.
* Noble Mushtak, Daniel Lemire, [Fast Number Parsing Without
  Fallback](https://arxiv.org/abs/2212.06644), Software: Practice and Experience
  53 (7), 2023.

## Other programming languages

* [There is an R binding](https://github.com/eddelbuettel/rcppfastfloat) called
  `rcppfastfloat`.
* [There is a Rust port of the fast_float
  library](https://github.com/aldanor/fast-float-rust/) called
  `fast-float-rust`.
* [There is a Java port of the fast_float
  library](https://github.com/wrandelshofer/FastDoubleParser) called
  `FastDoubleParser`. It used for important systems such as
  [Jackson](https://github.com/FasterXML/jackson-core).
* [There is a C# port of the fast_float
  library](https://github.com/CarlVerret/csFastFloat) called `csFastFloat`.

## How fast is it?

It can parse random floating-point numbers at a speed of 1 GB/s on some systems.
We find that it is often twice as fast as the best available competitor, and
many times faster than many standard-library implementations.

<img src="https://lemire.me/blog/wp-content/uploads/2020/11/fastfloat_speed.png"
width="400" alt="fast_float is many times faster than many standard-library
implementations">

```bash
$ ./build/benchmarks/benchmark
# parsing random integers in the range [0,1)
volume = 2.09808 MB
netlib                                  :   271.18 MB/s (+/- 1.2 %)    12.93 Mfloat/s
doubleconversion                        :   225.35 MB/s (+/- 1.2 %)    10.74 Mfloat/s
strtod                                  :   190.94 MB/s (+/- 1.6 %)     9.10 Mfloat/s
abseil                                  :   430.45 MB/s (+/- 2.2 %)    20.52 Mfloat/s
fastfloat                               :  1042.38 MB/s (+/- 9.9 %)    49.68 Mfloat/s
```

See the [Benchmarking](#benchmarking) Section for instructions on how to run our benchmarks.

## Video

[](https://www.youtube.com/watch?v=AVXgvlMeIm4)

## Using as a CMake dependency

This library is header-only by design. The CMake file provides the `fast_float`
target which is merely a pointer to the `include` directory.

If you drop the `fast_float` repository in your CMake project, you should be
able to use it in this manner:

```cmake
add_subdirectory(fast_float)
target_link_libraries(myprogram PUBLIC fast_float)
```

Or you may want to retrieve the dependency automatically if you have a
sufficiently recent version of CMake (3.11 or better at least):

```cmake
FetchContent_Declare(
  fast_float
  GIT_REPOSITORY https://github.com/fastfloat/fast_float.git
  GIT_TAG tags/v8.0.0
  GIT_SHALLOW TRUE)

FetchContent_MakeAvailable(fast_float)
target_link_libraries(myprogram PUBLIC fast_float)
```

You should change the `GIT_TAG` line so that you recover the version you wish to
use.

You may also use [CPM](https://github.com/cpm-cmake/CPM.cmake), like so:

```cmake
CPMAddPackage(
  NAME fast_float
  GITHUB_REPOSITORY "fastfloat/fast_float"
  GIT_TAG v8.0.0)
```

## Using as single header

The script `script/amalgamate.py` may be used to generate a single header
version of the library if so desired. Just run the script from the root
directory of this repository. You can customize the license type and output file
if desired as described in the command line help.

You may directly download automatically generated single-header files:

<https://github.com/fastfloat/fast_float/releases/download/v8.0.0/fast_float.h>

## Benchmarking

The project has its own benchmarks with realistic data inputs. Under Linux or macOS,
you can use it as follows if your system supports C++17:

```
cmake -B build -D FASTFLOAT_BENCHMARKS=ON
cmake --build build
./build/benchmarks/realbenchmark
```

Importantly, by default, the benchmark is built in Release mode.

The instructions are similar under Windows.

Under Linux and macOS, it is recommended to run the benchmarks in a privileged manner to get access
to hardware performance counters. You may be able to do so with the `sudo` command
in some cases:

```
sudo ./build/benchmarks/realbenchmark
```

## Packages

* The fast_float library is part of the [Conan package
  manager](https://conan.io/center/recipes/fast_float).
* It is part of the [brew package
  manager](https://formulae.brew.sh/formula/fast_float).
* Some Linux distribution like Fedora include fast_float (e.g., as
  `fast_float-devel`).

## Credit

Though this work is inspired by many different people, this work benefited
especially from exchanges with Michael Eisel, who motivated the original
research with his key insights, and with Nigel Tao who provided invaluable
feedback. Rémy Oudompheng first implemented a fast path we use in the case of
long digits.

The library includes code adapted from Google Wuffs (written by Nigel Tao) which
was originally published under the Apache 2.0 license.

## License

<sup>
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
2.0</a> or <a href="LICENSE-MIT">MIT license</a> or <a
href="LICENSE-BOOST">BOOST license</a>.
</sup>

<br/>

<sub>
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this repository by you, as defined in the Apache-2.0 license,
shall be triple licensed as above, without any additional terms or conditions.
</sub>

---

### Overview (`vnext/external/fmt/README.md`)

<img src="https://user-images.githubusercontent.com/576385/156254208-f5b743a9-88cf-439d-b0c0-923d53e8d551.png" alt="{fmt}" width="25%"/>

[](https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux)
[](https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos)
[](https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows)
[](https://bugs.chromium.org/p/oss-fuzz/issues/list?\%0Acolspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\%0ASummary&q=proj%3Dfmt&can=1)
[](https://stackoverflow.com/questions/tagged/fmt)
[](https://securityscorecards.dev/viewer/?uri=github.com/fmtlib/fmt)

**{fmt}** is an open-source formatting library providing a fast and safe
alternative to C stdio and C++ iostreams.

If you like this project, please consider donating to one of the funds
that help victims of the war in Ukraine: <https://www.stopputin.net/>.

[Documentation](https://fmt.dev)

[Cheat Sheets](https://hackingcpp.com/cpp/libs/fmt.html)

Q&A: ask questions on [StackOverflow with the tag
fmt](https://stackoverflow.com/questions/tagged/fmt).

Try {fmt} in [Compiler Explorer](https://godbolt.org/z/8Mx1EW73v).

# Features

- Simple [format API](https://fmt.dev/latest/api/) with positional
  arguments for localization
- Implementation of [C++20
  std::format](https://en.cppreference.com/w/cpp/utility/format) and
  [C++23 std::print](https://en.cppreference.com/w/cpp/io/print)
- [Format string syntax](https://fmt.dev/latest/syntax/) similar
  to Python\'s
  [format](https://docs.python.org/3/library/stdtypes.html#str.format)
- Fast IEEE 754 floating-point formatter with correct rounding,
  shortness and round-trip guarantees using the
  [Dragonbox](https://github.com/jk-jeon/dragonbox) algorithm
- Portable Unicode support
- Safe [printf
  implementation](https://fmt.dev/latest/api/#printf-formatting)
  including the POSIX extension for positional arguments
- Extensibility: [support for user-defined
  types](https://fmt.dev/latest/api/#formatting-user-defined-types)
- High performance: faster than common standard library
  implementations of `(s)printf`, iostreams, `to_string` and
  `to_chars`, see [Speed tests](#speed-tests) and [Converting a
  hundred million integers to strings per
  second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html)
- Small code size both in terms of source code with the minimum
  configuration consisting of just three files, `core.h`, `format.h`
  and `format-inl.h`, and compiled code; see [Compile time and code
  bloat](#compile-time-and-code-bloat)
- Reliability: the library has an extensive set of
  [tests](https://github.com/fmtlib/fmt/tree/master/test) and is
  [continuously fuzzed](https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1)
- Safety: the library is fully type-safe, errors in format strings can
  be reported at compile time, automatic memory management prevents
  buffer overflow errors
- Ease of use: small self-contained code base, no external
  dependencies, permissive MIT
  [license](https://github.com/fmtlib/fmt/blob/master/LICENSE)
- [Portability](https://fmt.dev/latest/#portability) with
  consistent output across platforms and support for older compilers
- Clean warning-free codebase even on high warning levels such as
  `-Wall -Wextra -pedantic`
- Locale independence by default
- Optional header-only configuration enabled with the
  `FMT_HEADER_ONLY` macro

See the [documentation](https://fmt.dev) for more details.

# Examples

**Print to stdout** ([run](https://godbolt.org/z/Tevcjh))

``` c++
#include <fmt/core.h>

int main() {
  fmt::print("Hello, world!\n");
}
```

**Format a string** ([run](https://godbolt.org/z/oK8h33))

``` c++
std::string s = fmt::format("The answer is {}.", 42);
// s == "The answer is 42."
```

**Format a string using positional arguments**
([run](https://godbolt.org/z/Yn7Txe))

``` c++
std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
// s == "I'd rather be happy than right."
```

**Print dates and times** ([run](https://godbolt.org/z/c31ExdY3W))

``` c++
#include <fmt/chrono.h>

int main() {
  auto now = std::chrono::system_clock::now();
  fmt::print("Date and time: {}\n", now);
  fmt::print("Time: {:%H:%M}\n", now);
}
```

Output:

    Date and time: 2023-12-26 19:10:31.557195597
    Time: 19:10

**Print a container** ([run](https://godbolt.org/z/MxM1YqjE7))

``` c++
#include <vector>
#include <fmt/ranges.h>

int main() {
  std::vector<int> v = {1, 2, 3};
  fmt::print("{}\n", v);
}
```

Output:

    [1, 2, 3]

**Check a format string at compile time**

``` c++
std::string s = fmt::format("{:d}", "I am not a number");
```

This gives a compile-time error in C++20 because `d` is an invalid
format specifier for a string.

**Write a file from a single thread**

``` c++
#include <fmt/os.h>

int main() {
  auto out = fmt::output_file("guide.txt");
  out.print("Don't {}", "Panic");
}
```

This can be [5 to 9 times faster than
fprintf](http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html).

**Print with colors and text styles**

``` c++
#include <fmt/color.h>

int main() {
  fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
             "Hello, {}!\n", "world");
  fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
             fmt::emphasis::underline, "Olá, {}!\n", "Mundo");
  fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
             "你好{}！\n", "世界");
}
```

Output on a modern terminal with Unicode support:



# Benchmarks

## Speed tests

| Library           | Method        | Run Time, s |
|-------------------|---------------|-------------|
| libc              | printf        |   0.91      |
| libc++            | std::ostream  |   2.49      |
| {fmt} 9.1         | fmt::print    |   0.74      |
| Boost Format 1.80 | boost::format |   6.26      |
| Folly Format      | folly::format |   1.87      |

{fmt} is the fastest of the benchmarked methods, \~20% faster than
`printf`.

The above results were generated by building `tinyformat_test.cpp` on
macOS 12.6.1 with `clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT`, and
taking the best of three runs. In the test, the format string
`"%0.10f:%04d:%+g:%s:%p:%c:%%\n"` or equivalent is filled 2,000,000
times with output sent to `/dev/null`; for further details refer to the
[source](https://github.com/fmtlib/format-benchmark/blob/master/src/tinyformat-test.cc).

{fmt} is up to 20-30x faster than `std::ostringstream` and `sprintf` on
IEEE754 `float` and `double` formatting
([dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark)) and faster
than [double-conversion](https://github.com/google/double-conversion)
and [ryu](https://github.com/ulfjack/ryu):

[](https://fmt.dev/unknown_mac64_clang12.0.html)

## Compile time and code bloat

The script [bloat-test.py][test] from [format-benchmark][bench] tests compile
time and code bloat for nontrivial projects. It generates 100 translation units
and uses `printf()` or its alternative five times in each to simulate a
medium-sized project. The resulting executable size and compile time (Apple
clang version 15.0.0 (clang-1500.1.0.2.5), macOS Sonoma, best of three) is shown
in the following tables.

[test]: https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py
[bench]: https://github.com/fmtlib/format-benchmark

**Optimized build (-O3)**

| Method        | Compile Time, s | Executable size, KiB | Stripped size, KiB |
|---------------|-----------------|----------------------|--------------------|
| printf        |             1.6 |                   54 |                 50 |
| IOStreams     |            25.9 |                   98 |                 84 |
| fmt 83652df   |             4.8 |                   54 |                 50 |
| tinyformat    |            29.1 |                  161 |                136 |
| Boost Format  |            55.0 |                  530 |                317 |

{fmt} is fast to compile and is comparable to `printf` in terms of per-call
binary size (within a rounding error on this system).

**Non-optimized build**

| Method        | Compile Time, s | Executable size, KiB | Stripped size, KiB |
|---------------|-----------------|----------------------|--------------------|
| printf        |             1.4 |                   54 |                 50 |
| IOStreams     |            23.4 |                   92 |                 68 |
| {fmt} 83652df |             4.4 |                   89 |                 85 |
| tinyformat    |            24.5 |                  204 |                161 |
| Boost Format  |            36.4 |                  831 |                462 |

`libc`, `lib(std)c++`, and `libfmt` are all linked as shared libraries
to compare formatting function overhead only. Boost Format is a
header-only library so it doesn\'t provide any linkage options.

## Running the tests

Please refer to [Building the
library](https://fmt.dev/latest/get-started/#building-from-source) for
instructions on how to build the library and run the unit tests.

Benchmarks reside in a separate repository,
[format-benchmarks](https://github.com/fmtlib/format-benchmark), so to
run the benchmarks you first need to clone this repository and generate
Makefiles with CMake:

    $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
    $ cd format-benchmark
    $ cmake .

Then you can run the speed test:

    $ make speed-test

or the bloat test:

    $ make bloat-test

# Migrating code

[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v18 provides the
[modernize-use-std-print](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-std-print.html)
check that is capable of converting occurrences of `printf` and
`fprintf` to `fmt::print` if configured to do so. (By default it
converts to `std::print`.)

# Notable projects using this library

- [0 A.D.](https://play0ad.com/): a free, open-source, cross-platform
  real-time strategy game
- [AMPL/MP](https://github.com/ampl/mp): an open-source library for
  mathematical programming
- [Apple's FoundationDB](https://github.com/apple/foundationdb): an open-source,
  distributed, transactional key-value store
- [Aseprite](https://github.com/aseprite/aseprite): animated sprite
  editor & pixel art tool
- [AvioBook](https://www.aviobook.aero/en): a comprehensive aircraft
  operations suite
- [Blizzard Battle.net](https://battle.net/): an online gaming
  platform
- [Celestia](https://celestia.space/): real-time 3D visualization of
  space
- [Ceph](https://ceph.com/): a scalable distributed storage system
- [ccache](https://ccache.dev/): a compiler cache
- [ClickHouse](https://github.com/ClickHouse/ClickHouse): an
  analytical database management system
- [Contour](https://github.com/contour-terminal/contour/): a modern
  terminal emulator
- [CUAUV](https://cuauv.org/): Cornell University\'s autonomous
  underwater vehicle
- [Drake](https://drake.mit.edu/): a planning, control, and analysis
  toolbox for nonlinear dynamical systems (MIT)
- [Envoy](https://github.com/envoyproxy/envoy): C++ L7 proxy and
  communication bus (Lyft)
- [FiveM](https://fivem.net/): a modification framework for GTA V
- [fmtlog](https://github.com/MengRao/fmtlog): a performant
  fmtlib-style logging library with latency in nanoseconds
- [Folly](https://github.com/facebook/folly): Facebook open-source
  library
- [GemRB](https://gemrb.org/): a portable open-source implementation
  of Bioware's Infinity Engine
- [Grand Mountain
  Adventure](https://store.steampowered.com/app/1247360/Grand_Mountain_Adventure/):
  a beautiful open-world ski & snowboarding game
- [HarpyWar/pvpgn](https://github.com/pvpgn/pvpgn-server): Player vs
  Player Gaming Network with tweaks
- [KBEngine](https://github.com/kbengine/kbengine): an open-source
  MMOG server engine
- [Keypirinha](https://keypirinha.com/): a semantic launcher for
  Windows
- [Kodi](https://kodi.tv/) (formerly xbmc): home theater software
- [Knuth](https://kth.cash/): high-performance Bitcoin full-node
- [libunicode](https://github.com/contour-terminal/libunicode/): a
  modern C++17 Unicode library
- [MariaDB](https://mariadb.org/): relational database management
  system
- [Microsoft Verona](https://github.com/microsoft/verona): research
  programming language for concurrent ownership
- [MongoDB](https://mongodb.com/): distributed document database
- [MongoDB Smasher](https://github.com/duckie/mongo_smasher): a small
  tool to generate randomized datasets
- [OpenSpace](https://openspaceproject.com/): an open-source
  astrovisualization framework
- [PenUltima Online (POL)](https://www.polserver.com/): an MMO server,
  compatible with most Ultima Online clients
- [PyTorch](https://github.com/pytorch/pytorch): an open-source
  machine learning library
- [quasardb](https://www.quasardb.net/): a distributed,
  high-performance, associative database
- [Quill](https://github.com/odygrd/quill): asynchronous low-latency
  logging library
- [QKW](https://github.com/ravijanjam/qkw): generalizing aliasing to
  simplify navigation, and execute complex multi-line terminal
  command sequences
- [redis-cerberus](https://github.com/HunanTV/redis-cerberus): a Redis
  cluster proxy
- [redpanda](https://vectorized.io/redpanda): a 10x faster Kafka®
  replacement for mission-critical systems written in C++
- [rpclib](http://rpclib.net/): a modern C++ msgpack-RPC server and
  client library
- [Salesforce Analytics
  Cloud](https://www.salesforce.com/analytics-cloud/overview/):
  business intelligence software
- [Scylla](https://www.scylladb.com/): a Cassandra-compatible NoSQL
  data store that can handle 1 million transactions per second on a
  single server
- [Seastar](http://www.seastar-project.org/): an advanced, open-source
  C++ framework for high-performance server applications on modern
  hardware
- [spdlog](https://github.com/gabime/spdlog): super fast C++ logging
  library
- [Stellar](https://www.stellar.org/): financial platform
- [Touch Surgery](https://www.touchsurgery.com/): surgery simulator
- [TrinityCore](https://github.com/TrinityCore/TrinityCore):
  open-source MMORPG framework
- [🐙 userver framework](https://userver.tech/): open-source
  asynchronous framework with a rich set of abstractions and database
  drivers
- [Windows Terminal](https://github.com/microsoft/terminal): the new
  Windows terminal

[More\...](https://github.com/search?q=fmtlib&type=Code)

If you are aware of other projects using this library, please let me
know by [email](mailto:victor.zverovich@gmail.com) or by submitting an
[issue](https://github.com/fmtlib/fmt/issues).

# Motivation

So why yet another formatting library?

There are plenty of methods for doing this task, from standard ones like
the printf family of function and iostreams to Boost Format and
FastFormat libraries. The reason for creating a new library is that
every existing solution that I found either had serious issues or
didn\'t provide all the features I needed.

## printf

The good thing about `printf` is that it is pretty fast and readily
available being a part of the C standard library. The main drawback is
that it doesn\'t support user-defined types. `printf` also has safety
issues although they are somewhat mitigated with [\_\_attribute\_\_
((format (printf,
\...))](https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) in
GCC. There is a POSIX extension that adds positional arguments required
for
[i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization)
to `printf` but it is not a part of C99 and may not be available on some
platforms.

## iostreams

The main issue with iostreams is best illustrated with an example:

``` c++
std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
```

which is a lot of typing compared to printf:

``` c++
printf("%.2f\n", 1.23456);
```

Matthew Wilson, the author of FastFormat, called this \"chevron hell\".
iostreams don\'t support positional arguments by design.

The good part is that iostreams support user-defined types and are safe
although error handling is awkward.

## Boost Format

This is a very powerful library that supports both `printf`-like format
strings and positional arguments. Its main drawback is performance.
According to various benchmarks, it is much slower than other methods
considered here. Boost Format also has excessive build times and severe
code bloat issues (see [Benchmarks](#benchmarks)).

## FastFormat

This is an interesting library that is fast, safe and has positional
arguments. However, it has significant limitations, citing its author:

> Three features that have no hope of being accommodated within the
> current design are:
>
> - Leading zeros (or any other non-space padding)
> - Octal/hexadecimal encoding
> - Runtime width/alignment specification

It is also quite big and has a heavy dependency, on STLSoft, which might be
too restrictive for use in some projects.

## Boost Spirit.Karma

This is not a formatting library but I decided to include it here for
completeness. As iostreams, it suffers from the problem of mixing
verbatim text with arguments. The library is pretty fast, but slower on
integer formatting than `fmt::format_to` with format string compilation
on Karma\'s own benchmark, see [Converting a hundred million integers to
strings per
second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html).

# License

{fmt} is distributed under the MIT
[license](https://github.com/fmtlib/fmt/blob/master/LICENSE).

# Documentation License

The [Format String Syntax](https://fmt.dev/latest/syntax/) section
in the documentation is based on the one from Python [string module
documentation](https://docs.python.org/3/library/string.html#module-string).
For this reason, the documentation is distributed under the Python
Software Foundation license available in
[doc/python-license.txt](https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt).
It only applies if you distribute the documentation of {fmt}.

# Maintainers

The {fmt} library is maintained by Victor Zverovich
([vitaut](https://github.com/vitaut)) with contributions from many other
people. See
[Contributors](https://github.com/fmtlib/fmt/graphs/contributors) and
[Releases](https://github.com/fmtlib/fmt/releases) for some of the
names. Let us know if your contribution is not listed or mentioned
incorrectly and we\'ll make it right.

# Security Policy

To report a security issue, please disclose it at [security
advisory](https://github.com/fmtlib/fmt/security/advisories/new).

This project is maintained by a team of volunteers on a
reasonable-effort basis. As such, please give us at least *90* days to
work on a fix before public exposure.

---

### Overview (`vnext/external/folly/README.md`)

Folly: Facebook Open-source Library
===================================

<a href="https://opensource.facebook.com/support-ukraine">
  <img src="https://img.shields.io/badge/Support-Ukraine-FFD500?style=flat&labelColor=005BBB" alt="Support Ukraine - Help Provide Humanitarian Aid to Ukraine." />
</a>

# What is `folly`?

<img src="static/logo.svg" alt="Logo Folly" width="15%" align="right" />

Folly (acronymed loosely after Facebook Open Source Library) is a
library of C++17 components designed with practicality and efficiency
in mind. **Folly contains a variety of core library components used extensively
at Facebook**. In particular, it's often a dependency of Facebook's other
open source C++ efforts and place where those projects can share code.

It complements (as opposed to competing against) offerings
such as Boost and of course `std`. In fact, we embark on defining our
own component only when something we need is either not available, or
does not meet the needed performance profile. We endeavor to remove
things from folly if or when `std` or Boost obsoletes them.

Performance concerns permeate much of Folly, sometimes leading to
designs that are more idiosyncratic than they would otherwise be (see
e.g. `PackedSyncPtr.h`, `SmallLocks.h`). Good performance at large
scale is a unifying theme in all of Folly.

## Check it out in the intro video
[](https://www.youtube.com/watch?v=Wr_IfOICYSs)

# Logical Design

Folly is a collection of relatively independent components, some as
simple as a few symbols. There is no restriction on internal
dependencies, meaning that a given folly module may use any other
folly components.

All symbols are defined in the top-level namespace `folly`, except of
course macros. Macro names are ALL_UPPERCASE and should be prefixed
with `FOLLY_`. Namespace `folly` defines other internal namespaces
such as `internal` or `detail`. User code should not depend on symbols
in those namespaces.

Folly has an `experimental` directory as well. This designation connotes
primarily that we feel the API may change heavily over time. This code,
typically, is still in heavy use and is well tested.

# Physical Design

At the top level Folly uses the classic "stuttering" scheme
`folly/folly` used by Boost and others. The first directory serves as
an installation root of the library (with possible versioning a la
`folly-1.0/`), and the second is to distinguish the library when
including files, e.g. `#include <folly/FBString.h>`.

The directory structure is flat (mimicking the namespace structure),
i.e. we don't have an elaborate directory hierarchy (it is possible
this will change in future versions). The subdirectory `experimental`
contains files that are used inside folly and possibly at Facebook but
not considered stable enough for client use. Your code should not use
files in `folly/experimental` lest it may break when you update Folly.

The `folly/folly/test` subdirectory includes the unittests for all
components, usually named `ComponentXyzTest.cpp` for each
`ComponentXyz.*`. The `folly/folly/docs` directory contains
documentation.

# What's in it?

Because of folly's fairly flat structure, the best way to see what's in it
is to look at the headers in [top level `folly/` directory](https://github.com/facebook/folly/tree/main/folly). You can also
check the [`docs` folder](folly/docs) for documentation, starting with the
[overview](folly/docs/Overview.md).

Folly is published on GitHub at https://github.com/facebook/folly.

# Build Notes

Because folly does not provide any ABI compatibility guarantees from commit to
commit, we generally recommend building folly as a static library.

folly supports gcc (5.1+), clang, or MSVC. It should run on Linux (x86-32,
x86-64, and ARM), iOS, macOS, and Windows (x86-64). The CMake build is only
tested on some of these platforms; at a minimum, we aim to support macOS and
Linux (on the latest Ubuntu LTS release or newer.)

## `getdeps.py`

This script is used by many of Meta's OSS tools.  It will download and build all of the necessary dependencies first, and will then invoke cmake etc to build folly.  This will help ensure that you build with relevant versions of all of the dependent libraries, taking into account what versions are installed locally on your system.

It's written in python so you'll need python3.6 or later on your PATH.  It works on Linux, macOS and Windows.

The settings for folly's cmake build are held in its getdeps manifest `build/fbcode_builder/manifests/folly`, which you can edit locally if desired.

### Dependencies

If on Linux or MacOS (with homebrew installed) you can install system dependencies to save building them:

    # Clone the repo
    git clone https://github.com/facebook/folly
    # Install dependencies
    cd folly
    sudo ./build/fbcode_builder/getdeps.py install-system-deps --recursive

If you'd like to see the packages before installing them:

    ./build/fbcode_builder/getdeps.py install-system-deps --dry-run --recursive

On other platforms or if on Linux and without system dependencies `getdeps.py` will mostly download and build them for you during the build step.

Some of the dependencies `getdeps.py` uses and installs are:

  * a version of boost compiled with C++14 support.
  * googletest is required to build and run folly's tests.

### Build

This script will download and build all of the necessary dependencies first,
and will then invoke cmake etc to build folly.  This will help ensure that you build with relevant versions of all of the dependent libraries, taking into account what versions are installed locally on your system.

`getdeps.py` currently requires python 3.6+ to be on your path.

`getdeps.py` will invoke cmake etc.

    # Clone the repo
    git clone https://github.com/facebook/folly
    cd folly
    # Build, using system dependencies if available
    python3 ./build/fbcode_builder/getdeps.py --allow-system-packages build

It puts output in its scratch area:

  * `installed/folly/lib/libfolly.a`: Library

You can also specify a `--scratch-path` argument to control
the location of the scratch directory used for the build. You can find the default scratch install location from logs or with `python3 ./build/fbcode_builder/getdeps.py show-inst-dir`.

There are also
`--install-dir` and `--install-prefix` arguments to provide some more
fine-grained control of the installation directories. However, given that
folly provides no compatibility guarantees between commits we generally
recommend building and installing the libraries to a temporary location, and
then pointing your project's build at this temporary location, rather than
installing folly in the traditional system installation directories. e.g., if you are building with CMake you can use the `CMAKE_PREFIX_PATH` variable to allow CMake to find folly in this temporary installation directory when
building your project.

If you want to invoke `cmake` again to iterate, there is a helpful `run_cmake.py` script output in the scratch build directory.  You can find the scratch build directory from logs or with `python3 ./build/fbcode_builder/getdeps.py show-build-dir`.

### Run tests

By default `getdeps.py` will build the tests for folly. To run them:

    cd folly
    python3 ./build/fbcode_builder/getdeps.py --allow-system-packages test

### `build.sh`/`build.bat` wrapper

`build.sh` can be used on Linux and MacOS, on Windows use
the `build.bat` script instead. Its a wrapper around `getdeps.py`.

## Build with cmake directly

If you don't want to let getdeps invoke cmake for you then by default, building the tests is disabled as part of the CMake `all` target.
To build the tests, specify `-DBUILD_TESTS=ON` to CMake at configure time.

NB if you want to invoke `cmake` again to iterate on a `getdeps.py` build, there is a helpful `run_cmake.py` script output in the scratch-path build directory. You can find the scratch build directory from logs or with `python3 ./build/fbcode_builder/getdeps.py show-build-dir`.

Running tests with ctests also works if you cd to the build dir, e.g.
`(cd $(python3 ./build/fbcode_builder/getdeps.py show-build-dir) && ctest)`

### Finding dependencies in non-default locations

If you have boost, gtest, or other dependencies installed in a non-default
location, you can use the `CMAKE_INCLUDE_PATH` and `CMAKE_LIBRARY_PATH`
variables to make CMAKE look also look for header files and libraries in
non-standard locations.  For example, to also search the directories
`/alt/include/path1` and `/alt/include/path2` for header files and the
directories `/alt/lib/path1` and `/alt/lib/path2` for libraries, you can invoke
`cmake` as follows:

```
cmake \
  -DCMAKE_INCLUDE_PATH=/alt/include/path1:/alt/include/path2 \
  -DCMAKE_LIBRARY_PATH=/alt/lib/path1:/alt/lib/path2 ...
```

## Ubuntu LTS, CentOS Stream, Fedora

Use the `getdeps.py` approach above. We test in CI on Ubuntu LTS, and occasionally on other distros.

If you find the set of system packages is not quite right for your chosen distro, you can specify distro version specific overrides in the dependency manifests (e.g. https://github.com/facebook/folly/blob/main/build/fbcode_builder/manifests/boost ). You could probably make it work on most recent Ubuntu/Debian or Fedora/Redhat derived distributions.

At time of writing (Dec 2021) there is a build break on GCC 11.x based systems in lang_badge_test.  If you don't need badge functionality you can work around by commenting it out from CMakeLists.txt (unfortunately fbthrift does need it)

## Windows (Vcpkg)

Note that many tests are disabled for folly Windows builds, you can see them in the log from the cmake configure step, or by looking for WINDOWS_DISABLED in `CMakeLists.txt`

That said, `getdeps.py` builds work on Windows and are tested in CI.

If you prefer, you can try Vcpkg. folly is available in [Vcpkg](https://github.com/Microsoft/vcpkg#vcpkg) and releases may be built via `vcpkg install folly:x64-windows`.

You may also use `vcpkg install folly:x64-windows --head` to build against `main`.

## macOS

`getdeps.py` builds work on macOS and are tested in CI, however if you prefer, you can try one of the macOS package managers

### Homebrew

folly is available as a Formula and releases may be built via `brew install folly`.

You may also use `folly/build/bootstrap-osx-homebrew.sh` to build against `main`:

```
  ./folly/build/bootstrap-osx-homebrew.sh
```

This will create a build directory `_build` in the top-level.

### MacPorts

Install the required packages from MacPorts:

```
  sudo port install \
    boost \
    cmake \
    gflags \
    git \
    google-glog \
    libevent \
    libtool \
    lz4 \
    lzma \
    openssl \
    snappy \
    xz \
    zlib
```

Download and install double-conversion:

```
  git clone https://github.com/google/double-conversion.git
  cd double-conversion
  cmake -DBUILD_SHARED_LIBS=ON .
  make
  sudo make install
```

Download and install folly with the parameters listed below:

```
  git clone https://github.com/facebook/folly.git
  cd folly
  mkdir _build
  cd _build
  cmake ..
  make
  sudo make install
```

---

### Overview (`vnext/proposals/active/readme.md`)

This folder contains proposal documents for `react-native-windows @vnext` features that are under active development.

Please create a new folder for each new feature and use relative links for any included images or other assets. Please refer to the [instructions](../readme.md) to submit your proposal.

Once a feature is complete and shipped, the corresponding proposals should be moved to the [archive](../archive/readme.md) folder.

---

### Overview (`vnext/proposals/archive/readme.md`)

This folder contains archived proposal documents for `react-native-windows @vnext` features that have been completed and shipped.

Proposals from [active](../active/readme.md) folder should be moved to this folder once the feature has been implemented and shipped. Please update the header of the proposal file to include the `react-native-windows @vnext` version that corresponds to when the feature was first shipped.

---

### Overview (`vnext/external/folly/folly/portability/README.md`)

Warning
=======

These portability headers are **internal implementation details**.

They are intended to ensure that Folly can build on a variety of platforms.

They are not intended to help you build your programs on these platforms.

They are, and will remain, undocumented. They are, and will remain, subject to
rapid, immediate, and drastic changes - including full rewrites and merciless
deletions - without notice.

Note that before adding a new file to this directory you should determine
whether the API you are adding is a portability header or just a platform
dependent implementation detail. Only portability headers belong in this
directory. A portability header is defined as a header that provides the exact
API of some platform or configuration that is not available on all platforms.
If the API being added does not already exist on at least one of the platforms
Folly supports, then it is an implementation detail, and does not belong in
this directory.

---

### Overview (`packages/react-native-platform-override/src/e2etest/collateral/sampleOverrideRepo/README.md`)

### React Native Deforking Patches

This directory contains source copies of React Native code derived from microsoft/react-native.
This is a staging measure to let us move off of the fork. Files should not be added here or edited
apart from the purpose of removing differences from upstream react-native.

---

### Overview (`vnext/external/folly/folly/detail/base64_detail/README.md`)

*This file contains explanation of how SIMD implementation of Base64 functions*

Our solution is based on 0x80 blog: [encoding](http://0x80.pl/notesen/2016-01-12-sse-base64-encoding.html), [decoding](http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html).

This is a different version of the same explanation + we have some differences.

*NOTE: We are using 1 digit for two bits when writing data*

# Understanding Base64 encoding.

*If you find it easier, [Wikipedia](https://en.wikipedia.org/wiki/Base64).*

The goal of base64 is to encode arbitrary byte data as text that can be passed around.
It works as follows:
* we select a 64 character alphabet.
* we insert two 0 bits after each 6 bits. 2^6 is 64.
* because we now only need to encode 64 values, our alphabet is sufficient.

# Encoding

So, we have 2 steps needed to do the conversion: 1. get indexes 0-64, 2. lookup the corresponding char.
There is also a little bit of tail handling, see the apropriate section.

If one letter represents two bits, it looks smth like this (remember - our machines are little endian):

```
`cddd`bbcc`aaab => 0ddd`0ccc`0bbb`0aaa
```

After this we just have to convert the bytes into the selected alphabet.

This means we have two steps to the algorithm: encodeToIndexes and lookupByIndex.

## encodeToIndexes

*NOTE: assume 16 byte registers.*

We will only be converting 12 bytes to output 16 bytes.
The last 4 loaded bytes are ignored.

1. We need to shuffle bytes in a way that each dword contains all the bits to construct output for that dword. Specifically:

```
PONM,LKJI,HGFE,DCBA => KLJK,GIGH,EFDE,BCAB
```

> STEP BY STEP:
> * We had bytes in memory ABCD.
> * Loaded on a LE machine they become DCBA.
> * The first output dword will only fit ABC,
    D goes into the second dword.
> * We will also reshuffle CBA as BCAB becuase this will make
    futher operations simpler.

After this we will mutate each dword (letter+digit indicate 2 bits):

```
shuffled b2b3c1c2'c3d1d2d3'a1a2a3b1'b2b3c1c2
exepcted 00d1d2d3'00c1c2c3'00b1b2b3'00a1a2a3
```

At the moment of writing this we only have an SSE4.2 version. We can do it fairly straightforwardly with shifts and blends. However the 0x80 blogs suggests that using a tricky mutliplication scheme is superior, and that's what we do.

For neon there are by element shift instructions which would help.
On avx2 there are `srlv` family of instructions that can come in handy as well.
The 0x80 blog also talks about a BMI implementation (pdep/pext instructions). They had issues on AMD but apparently not on the AMDs in Meta's fleet, so in the future we can consider it as a possibility as well.

## lookupByIndex

The idea is to use table lookup/shuffle instructions (`pshuvb` on sse4.2). They allow you to shuffle a register by index (`0..16`).

We have values `0..64`. However, we can utilize that the output values are not random. The are split into a few contigious groups. We don't have to lookup the complete encoding, we just need to lookup the offset to add.


| Index | Maps to | Add to encode |
| ----- | --------| ------------- |
| 0-25  | 'A'-'Z' | 'A' - 0       |
| 26-51 | 'a'-'z' | 'a' - 26      |
| 52-61 | '0'-'9' | '0' - 52      |
| 62    | '+'     | '+' - 62      |
| 63    | '/'     | '/' - 63      |


*NOTE: the URL version of Base64 encoding uses -_ instead of +/*.

Since we have 16 values to map to, we are not going to bother with consolidating 52-61 to a single base and instead will them up individually.

This is our final lookup table:

```
0: 'A' - 0
1: 'a' - 26
2: '0' - 52,
3: '1' - 53
...
11: '9' - 61
12: '+' - 62
13: '/' - 63
14: -
15: -
```

We even have two extra indexes `14` and `15` that are unused.

## Tail handling

What if we have less than register size to load?
What if we have less than 3 elements to encode?

Base64 for incomplete 3 bytes works as if there were
extra 0s at the end, except the garbage elements are replaced
with either a padding character or just removed.

Example:

|input bytes (be) | Basic  | Url  |
|-----------------|--------|------|
| (1)             |  AQ==  | AQ   |
| (1, 0)          |  AQA=  | AQA  |
| (1, 0, 0)       |  AQAA  | AQAA |

After measuring different options, using scalar loop peeling
proved to be the fastest.

# Decoding

Overall the decoding process is similar to inverse of the encoding: 1. from chars get numbers `0..63` 2. pack them
into bytes.

However, unlike encoding, not all the sequences of bytes are valid.
We have to decide which ones to accept and how to handle errors.

*NOTE: error detection is fairly expensive, if in the
future there is a need for a decode that can sometimes
swallow invalid values, it can be done faster*.

Decisions:
`base64Decode` requires `=` padding and accepts only [`+`, `/`] as 62/63 character.
If there are extra bits on the end, those are not allowed: iZ== is not a valid input
because no input sequence will produce it.
`base64URLDecode`: allows everything encoded with plain base64 and base64URL.
It will succesfully decode some combinations that are not either. The extra bits on
the end are currently allowed: iZ== will decode successfully (this decision is not
motivated by anything).

*NOTE:* details on `baseURLDecode` rules:
* Padding bytes follow regual base64: if they are present they are allowed to be only in positions that
  regular base64 allows them to be in: 4th or 3rd and 4th in the 4 byte chunk. "aa==", "aaa=" - OK, "aa=", "==" - not OK. This decision follows the previous most common implementation of base64 in the codebase.
* Both ['+', '/'] and ['-', '_'] are allowed in any combinations. "+-" is legal for example.


*NOTE: this follows the previous design and not necessarily how other places define
base64URLDecode. The difference comes to decoding invalid sequence of padding characters.
Example: "ba=" we consider invalid while some other implmenetations might just strip '='. We
suspect it won't be an issue*.

This behaviour matches what the previous implementation did.

We only have a SIMD version of this algorithm for `base64Decode` because the URL decode has
very little use (so far at least).

The SIMD algorithm has 2 steps:
- `decodeCharToIndex`: convert to numbers from `0..63`
- `packIndexesToBytes`: packs `0..63` into the originally encoded bytes.

If we encounter an error, we are not going to stop processing data. We are just going to mark it and then check at the end.

## decodeCharToIndex

Convertions we want

| Char      | Char's Hex code | Res     | Res Hex     |
|-----------|-----------------|---------|-------------|
| '+'       |   0x2B          | 62      | 0x3E        |
| '/'       |   0x2F          | 63      | 0x3F        |
| '0' - '9' |   0x30 - 0x39   | 52 - 61 | 0x34 - 0x3D |
| 'A' - 'Z' |   0x41 - 0x5A   | 0  - 25 | 0x00 - 0x19 |
| 'a' - 'z' |   0x61 - 0x7A   | 26 - 51 | 0x1A - 0x33 |

### Idea

We have unique higher 4 bits (nibble) per consecutive group,
except for '+' and '/'.
We can find a unique offset with pshuvb by it.

### Deal with '+' and '/' nibbles

We need to move '+' and '/' into their own nibbles.
It's important that all previously invalid chars stay invalid.

The best way I see to do it is to substact 0x0f from everything less than or equal to +.
The reason to use 0x0f is that it's a constant we will need anyways ot get 4 higher nibbles.

However on intel there is no unsigned comparison, so all the negative values will be considered as <= '+'. To deal with it, we can use a signed comparison but subtract with satuation.

 * <= '+' gives -1 where '+'
 * and 0x0f
 * subs

Everything bigger than '+' will stay the same.
Everything smaller than '+' is invalid and will become even smaller.
It will saturate to -127 which is still ivalid, so we are OK.

 *NOTE: I was also thinking if this is possible to do with just one subtruction and no mask. Unfortunatly we also need to keep a separate nibble for '0' and '/' and '0' == '/' + 1, so that subtraction will guarantee put '/' and '0' on the same higher nibble.*

 *NOTE: If we drop the requirement on invalid elements, again - this is much easier*.

New conversion table:

| Char      | New Hex code  | Res     | Res Hex     |
|-----------|---------------|---------|-------------|
| '+'       |   0x1C        | 62      | 0x3E        |
| '/'       |   0x2F        | 63      | 0x3F        |
| '0' - '9' |   0x30 - 0x39 | 52 - 61 | 0x34 - 0x3D |
| 'A' - 'Z' |   0x41 - 0x5A | 0  - 25 | 0x00 - 0x19 |
| 'a' - 'z' |   0x61 - 0x7A | 26 - 51 | 0x1A - 0x33 |

### Detect invalid values.

The idea is that we have valid higher nibbles in range from `1..7`.
We can convert higher nibbles into a bitmask `0000'0010 ... 1000'0000` (`1 << nibble`)
Due to a lack of proper shift instruction on x86, we will use a table lookup (`pshuvb`).
All other higher nibbles can become 0, indicating invalid input.

Now for all possible lower nibbles we have a set of valid higher nibbles.


| Lower Nibble | Valid higher nibble |
| ------------ | ------------------- |
| 0            | 3, 5, 7             |
| 1 - 9        | 3, 4, 5, 6, 7       |
| A            | 4, 5, 6, 7          |
| B            | 4, 6                |
| C            | 1, 4, 6             |
| D, E         | 4, 6                |
| F            | 2, 4, 6             |


So: by higher nibble lookup a bit that indicates that higher nibble
    by lower nible lookup a set of valid bits
    and

This will give us a non-zero when it's OK.
And 0 when it's not.

Between iterations we can accumulate error with unsigned min.
0 - is the smallest value - so we will get 0 if there was one.

### Offset to correct values.

Similar idea to encode - we just lookup the proper offset and add it.
We'll need to lookup by higher nibble.

| Char      | New Hex code  | Res     | Offset (- means minus) |
|-----------|---------------|---------|------------------------|
| '+'       |   0x1C        | 62      | 62 - 0x1C              |
| '/'       |   0x2F        | 63      | 63 - '/'               |
| '0' - '9' |   0x30 - 0x39 | 52 - 61 | 52 - '0'               |
| 'A' - 'O' |   0x41 - 0x4F | 0  - 14 | 0  - 'A'               |
| 'P' - 'Z' |   0x50 - 0x5A | 15 - 25 | 0  - 'A'               |
| 'a' - 'o' |   0x61 - 0x6F | 26 - 40 | 26 - 'a'               |
| 'p' - 'z' |   0x70 - 0x7A | 26 - 51 | 26 - 'a'               |

## packIndexesToBytes

*NOTE: assume 16 byte registers.*

From a register of 16 bytes we need to get 12 bytes.
I think the only way to do it is to convert each 4 bytes to
appropriate 3 bytes and then put them all together.
After we doing conversion 4 to 3 we'll remove the leftover byte
with one shuffle.

Goal (*One letter - 2 bits*):

- Input: `0ddd'0ccc'0bbb'0aaa`
- Needed bytes: `'cddd'bbcc'aaab`

We can obviously shift and or to get the desired result
(and maybe on ARM we should) but again, shifting story for x86 is poor.

The 0x80 blog suggests the following trick.

### Multiply add (MADD) solution

On SSE there are `madd` instrucitons for adjacent bytes (`_mm_maddubs_epi16`)  and words (`_mm_madd_epi16`). Multiply is a strictly more powerful operation than shift, so this will work.

*NOTE: all of our numbers are positive so the sign of the operations doesn't matter*

Here is the scalar equivalent of the code we'll do.
(*I omit indicating leading 0s and ignore casts*).

```
std::uint16_t aaabbb = aaa << 6 + bbb;
std::uint16_t cccddd = ccc << 6 + ddd;
std::uint32_t aaabbbcccddd = aaabbb << 12 + cccddd;
```

Multiplication equivalent of `<< 6` is `* 0x40` and of `<< 12` is `* 0x1000`.

Now that we have `0000'aaab'bbcc'cddd`.
The correct order `cddd'bccc'aaab` which we can mix
into the final shuffle.

## looping

We can convert only in registers. There is a question: when can we write the whole
register to the output?
For example, for 16 bytes of input (no padding) we only have 12 bytes of output space.

A simple way to answer if we have enough space is to compute how much output space we'll need overall.
However, this operation is somewhat expensive and is likely already done for the allocation. So computing output size ideally should be avoided.

We can prove that as long as the `Register` is bigger than 16 bytes, `1.5 Register` of input space is enough to guarantee at least one register of the output sopace.

Proof.

Out of `1.5 Register`, `1 Register` converts to `0.75 Register` in the output. So we are left with proving that `0.5 Register` will produce at least `0.25 Register` of the output.

If there is no padding - `0.5` converts to `3/8`, which is `> 0.25`.
If there is padding, the last dword of input might produce just `1` output byte.

So, we need to prove that:

`convertedSize(RegisterSize / 2 - 4) >= RegisterSize / 4 - 1`

For `16` bytes it works `convertedSize(4) == 3`.
For `Register > 16` bytes, we can split:

```
convertedSize(RegisterSize / 4) +
convertedSize(RegisterSize / 4 - 4) >=
RegisterSize / 8 +
RegisterSize / 8 - 1
```

Since `convertedSize(RegisterSize / 4) > RegisterSize / 8` we just reduced the problem to 16 bytes.

Proven.

## Decoding SWAR

SWAR stands for SIMD Within A Register i.e. using bit tricks to
process multiple bytes in a bigger integer register.
Previous version of Base64Decode was using some bit tricks and, as a result,
was beating our performance for tails.

On top of that, if the platform lacks the necessary SIMD capabilities, SWAR is
benefitial, so we decided to implement it.

How does it work?

The simple version of the decoding alogirhtm matches from the input char to
the index: let's say char `a` is matched to the number `26`. So we would first match
chars to the corresponding indexes and then blend those indexes toghether.

Let's say (one letter still 2 bits):

```
0AAA'0BBB'0CCC'0DDD  // input chars
0aaa'0bbb'0ccc'0ddd  // corresponding bytes
cddd'bbcc'aaab'____  // after a bunch of bit manipulations
                     // (last byte is w/e)
```

However, what if we incorporated both position and character in the lookup table?

```
char:                 0AAA
corresponds to index: 0aaa

[0][0AAA] = 0000'0000'aaa0'0000
[1][0AAA] = 0000'aa00'000a'0000
[2][0AAA] = a000'00aa'0000'0000
[4][0AAA] = 0aaa'0000'0000'0000
```

This way we can just `or` results for all input chars.
Since we have one byte, which is always `0000`, we can use that byte for marking errors.
So for a busted input we can just store `0xffffffff`. We will `or` everything we output - and then check for `0xffffffff` in the end.

This is the formula for each position (d - decoded index for char):

```
d << 2;                                   // 0: 0000'0000'0000'aaa0
d >> 4 | (d << 12 & 0xff00);              // 1: 0000'0000'bb00'000b
(d << 6 & 0xff00) | (d << 22 & 0xff0000); // 2: 0000'c000'00cc'0000
d << 16;                                  // 3: 0000'0ddd'0000'0000
```

This is a memory/speed trade off. For a simple table lookup decoding we store 256 bytes. For this decoding we store 256 * 4 * 4 = 4kb. On big enough data this is a win of about a third over naive code. As far as SIMD clean up code is concerned, this is more questionable but for now we decided to go with it given that it shows an
improvement in microbenchmarks.

---

### Overview (`packages/@react-native/tester/js/examples/Experimental/PlatformTest/README.md`)

# RNTester PlatformTest

A barebones manual testing framework designed to work as a mechanism for recreating [Web Platform Tests](https://github.com/web-platform-tests/wpt) in React Native in order to verify their compliance with W3C specifications.

## Usage

Any new test case will start as a new React component which at the very least accepts a `harness` prop which will contain all of the framework's testing APIs. This component you write will be passed into the `component` prop of a `RNTesterPlatformTest` element whose other props are used for documenting your test. Rendering this `RNTesterPlatformTest` will look similar to something like this:

```js
function ExampleTestCase ({ harness }) { /* ... */ }

<RNTesterPlatformTest
  title="Example Test"
  description="Imagine there's a detailed description of this example test here"
  instructions={[
    "This is the example test's first step",
    "A second step",
    "A third step",
  ]}
  component={ExampleTestCase}
/>
```


As of writing this README there are 2 different types of tests that the `harness` prop provides:

### `test(testcase: (TestContext) => void, testName: string, options?: TestOptions)`

This is a method to create "regular" test reminiscent of other frameworks such as Jest. These are meant to be run imperatively, and while that means that they technically could work in a `useEffect` hook as a way to run the test "on mount" — it is instead recommended to try and keep these tests in callbacks instead. A good alternative to running the test on mount would be to instead put the test in a callback and render a "Start Test" button which executes the callback.

The first argument is the closure in which you will run your test and make assertions. The assertions are contained in the `TestContext` object which is provided in the test closure's first argument and contains the following assertions:

* `assert_true(a: boolean, description: string): void`
* `assert_equals(a: any, b: any, description: string): void`
* `assert_greater_than_equal(a: number, b: number, description: string): void`
* `assert_less_than_equal(a: number, b: number, description: string): void`

An optional third argument can be used for specifying additional options to the test — that object currently has the following properties (all of which are optional themselves):

* `skip: boolean`: In cases where we want the test to be registered but we don't want it to contribute to the pass/fail count.

Here's what a basic/contrived example which verifies the layout of a basic view:

```js
const EXPECTED_WIDTH = 100;
const EXPECTED_HEIGHT = 200;

function BasicLayoutTestCase({harness}) {
  const viewRef = useRef(null);

  const runTest = useCallback(() => {
    const view = viewRef.current;
    if (view != null) {
      view.measureInWindow(({width, height}) => {
        harness.test(({assert_equals}) => {
          assert_equals(
            width,
            EXPECTED_WIDTH,
            `view's computed width should be ${EXPECTED_WIDTH}`,
          );
          assert_equals(
            height,
            EXPECTED_HEIGHT,
            `view's computed width should be ${EXPECTED_HEIGHT}`,
          );
        }, "view's width and height are correct");
      });
    }
  }, [harness]);

  return (
    <>
      <View
        ref={viewRef}
        style={{width: EXPECTED_WIDTH, height: EXPECTED_HEIGHT}}
      />
      <Button title="Start Test" onPress={runTest} />
    </>
  );
}
```

### `useAsyncTest(description: string, timeoutMs?: number): AsyncPlatformTest`

This is a hook which can be used to represent tests that expect something to happen *some time* in the future. If the test isn't marked as "done" within a certain amount of time (10 seconds by default but can be optionally specified in the hook's second argument). This hook returns an object containing a `done` function which is used for marking the completion of the async test.

Here's what a basic example would look like for verifying that `pointermove` events are emitted:

```js
function BasicPointerMoveTestCase({harness}) {
  const testPointerMove = harness.useAsyncTest('pointermove event received');

  return (
    <View
      style={{width: 100, height: 100, backgroundColor: 'black'}}
      onPointerMove={() => testPointerMove.done()}
    />
  );
}
```

---

### Vnext External Fmt Doc Index (`vnext/external/fmt/doc/index.md`)

---
hide:
  - navigation
  - toc
---

# A modern formatting library

<div class="features-container">

<div class="feature">
<h2>Safety</h2>
<p>
  Inspired by Python's formatting facility, {fmt} provides a safe replacement
  for the <code>printf</code> family of functions. Errors in format strings,
  which are a common source of vulnerabilities in C, are <b>reported at
  compile time</b>. For example:

  <pre><code class="language-cpp"
  >fmt::format("{:d}", "I am not a number");</code></pre>

  will give a compile-time error because <code>d</code> is not a valid
  format specifier for strings. APIs like <a href="api/#format">
  <code>fmt::format</code></a> <b>prevent buffer overflow errors</b> via
  automatic memory management.
</p>
<a href="api#compile-time-checks">→ Learn more</a>
</div>

<div class="feature">
<h2>Extensibility</h2>
<p>
  Formatting of most <b>standard types</b>, including all containers, dates,
  and times is <b>supported out-of-the-box</b>. For example:
  
  <pre><code class="language-cpp"
  >fmt::print("{}", std::vector{1, 2, 3});</code></pre>

  prints the vector in a JSON-like format:

  <pre><code>[1, 2, 3]</code></pre>

  You can <b>make your own types formattable</b> and even make compile-time
  checks work for them.
</p>
<a href="api#udt">→ Learn more</a>
</div>

<div class="feature">
<h2>Performance</h2>
<p>
  {fmt} can be anywhere from <b>tens of percent to 20-30 times faster</b> than
  iostreams and <code>sprintf</code>, especially for numeric formatting.

<a href="https://github.com/fmtlib/fmt?tab=readme-ov-file#benchmarks">
<img src="perf.svg">
</a>

  The library <b>minimizes dynamic memory allocations</b> and can optionally
  <a href="api#compile-api">compile format strings</a> to optimal code.
</p>
</div>

<div class="feature">
<h2>Unicode support</h2>
<p>
  {fmt} provides <b>portable Unicode support</b> on major operating systems
  with UTF-8 and <code>char</code> strings. For example:

  <pre><code class="language-cpp"
  >fmt::print("Слава Україні!");</code></pre>

  will be printed correctly on Linux, macOS, and even Windows console,
  irrespective of the codepages.
</p>
<p>
  The default is <b>locale-independent</b>, but you can opt into localized
  formatting and {fmt} makes it work with Unicode, addressing issues in the
  standard libary.
</p>
</div>

<div class="feature">
<h2>Fast compilation</h2>
<p>
  The library makes extensive use of <b>type erasure</b> to achieve fast
  compilation. <code>fmt/base.h</code> provides a subset of the API with
  <b>minimal include dependencies</b> and enough functionality to replace
  all uses of <code>*printf</code>.
</p>
<p>
  Code using {fmt} is usually several times faster to compile than the
  equivalent iostreams code, and while <code>printf</code> compiles faster
  still, the gap is narrowing.
</p>
<a href=
"https://github.com/fmtlib/fmt?tab=readme-ov-file#compile-time-and-code-bloat">
→ Learn more</a>
</div>

<div class="feature">
<h2>Small binary footprint</h2>
<p>
  Type erasure is also used to prevent template bloat, resulting in <b>compact
  per-call binary code</b>. For example, a call to <code>fmt::print</code> with
  a single argument is just <a href="https://godbolt.org/g/TZU4KF">a few
  instructions</a>, comparable to <code>printf</code> despite adding
  runtime safety, and much smaller than the equivalent iostreams code.
</p>
<p>
  The library itself has small binary footprint and some components such as
  floating-point formatting can be disabled to make it even smaller for
  resource-constrained devices.
</p>
</div>

<div class="feature">
<h2>Portability</h2>
<p>
  {fmt} has a <b>small self-contained codebase</b> with the core consisting of
  just three headers and no external dependencies.
</p>
<p>
  The library is highly portable and requires only a minimal <b>subset of
  C++11</b> features which are available in GCC 4.8, Clang 3.4, MSVC 19.0
  (2015) and later. Newer compiler and standard library features are used
  if available, and enable additional functionality.
</p>
<p>
  Where possible, the output of formatting functions is <b>consistent across
  platforms</b>.
</p>
</p>
</div>

<div class="feature">
<h2>Open source</h2>
<p>
  {fmt} is in the top hundred open-source C++ libraries on GitHub and has
  <a href="https://github.com/fmtlib/fmt/graphs/contributors">hundreds of
  all-time contributors</a>.
</p>
<p>
  The library is distributed under a permissive MIT
  <a href="https://github.com/fmtlib/fmt#license">license</a> and is
  <b>relied upon by many open-source projects</b>, including Blender, PyTorch,
  Apple's FoundationDB, Windows Terminal, MongoDB, and others.
</p>
</div>

</div>

---

### Vnext External Folly Folly Docs Overview (`vnext/external/folly/folly/docs/Overview.md`)

### `folly/`

### Components

Below is a list of (some) Folly components in alphabetical order, along with
a brief description of each.

#### `Arena.h`, `ThreadCachedArena.h`

Simple arena for memory allocation: multiple allocations get freed all
at once. With threaded version.

#### [`AtomicHashMap.h`](AtomicHashMap.md), `AtomicHashArray.h`, `AtomicLinkedList.h`, ...

High-performance atomic data-structures. Many of these are built with very specific
tradeoffs and constraints in mind that make them faster than their more general
counterparts. Each header should contain information about what these tradeoffs are.

#### `Baton.h`

A Baton allows a thread to block once and be awoken: it captures a single handoff. It is
essentially a (very small, very fast) semaphore that supports only a single call to `sem_call`
and `sem_wait`.

#### [`Benchmark.h`](Benchmark.md)

A small framework for benchmarking code. Client code registers
benchmarks, optionally with an argument that dictates the scale of the
benchmark (iterations, working set size etc). The framework runs
benchmarks (subject to a command-line flag) and produces formatted
output with timing information.

#### `Bits.h`

Various bit manipulation utilities optimized for speed; includes functions
that wrap the
[ffsl(l)](http://linux.die.net/man/3/ffsll) primitives in a uniform
interface.

#### `ConcurrentSkipList.h`

An implementation of the structure described in [A Provably Correct
Scalable Concurrent Skip
List](http://people.csail.mit.edu/shanir/publications/OPODIS2006-BA.pdf)
by Herlihy et al.

#### [`Conv.h`](Conv.md)

A variety of data conversion routines (notably to and from string),
optimized for speed and safety.

#### `Demangle.h`

Pretty-printing C++ types.

#### `DiscriminatedPtr.h`

Similar to `std::variant`, but restricted to pointers only. Uses the
highest-order unused 16 bits in a pointer as discriminator. So
`sizeof(DiscriminatedPtr<int, string, Widget>) == sizeof(void*)`.

#### [`dynamic.h`](Dynamic.md)

Dynamically-typed object, created with JSON objects in mind. `DynamicConverter.h` is
a utility for efficiently converting from a `dynamic` to a more concrete structure when
the scheme is known (e.g. json -> `map<int,int>`).

#### `EvictingCacheMap.h`

A simple LRU hash map.

#### [`FBString.h`](FBString.md)

A drop-in implementation of `std::string` with a variety of optimizations.

#### [`FBVector.h`](FBVector.md)

A mostly drop-in implementation of `std::vector` with a variety of
optimizations.

#### `File.h`

A C++ abstraction around files.

#### `Fingerprint.h`

Rabin fingerprinting.

#### [`Function.h`](Function.md)

A polymorphic wrapper for callables similar to `std::function` but not copyable and therefore able to wrap non-copyable callables, such as lambdas that capture move-only types like `std::unique_ptr` or `folly::Promise`.

#### [`futures/`](Futures.md)

Futures is a framework for expressing asynchronous code in C++ using the Promise/Future pattern.

#### [`Format.h`](Format.md)

Python-style formatting utilities.

#### `gen/`

This library makes it possible to write declarative comprehensions for
processing sequences of values efficiently in C++ akin to C#'s LINQ.

#### [`GroupVarint.h`](GroupVarint.md)

[Group Varint
encoding](http://www.ir.uwaterloo.ca/book/addenda-06-index-compression.html)
for 32-bit values.

#### `IPAddress.h`

A collection of utilities to deal with IPAddresses, including ipv4 and ipv6.

#### `io/`

A collection of useful of abstractions for high-performance io. This is heavily relied upon
in Facebook's internally networking code.

#### `Hash.h`

Various popular hash function implementations.

#### [`Histogram.h`](Histogram.md)

A simple class for collecting histogram data.

#### `IntrusiveList.h`

Convenience type definitions for using `boost::intrusive_list`.

#### `json.h`

JSON serializer and deserializer. Uses `dynamic.h`.

#### `Likely.h`

Wrappers around [`__builtin_expect`](http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html).

#### `Malloc.h`, `Memory.h`

Memory allocation helpers, particularly when using jemalloc.

#### `MicroSpinLock.h`

A really, *really* small spinlock for fine-grained locking of lots of teeny-tiny data.

#### `MPMCQueue.h`

MPMCQueue<typename> is a high-performance bounded concurrent queue that
supports multiple producers, multiple consumers, and optional blocking.
The queue has a fixed capacity, for which all memory will be allocated
 up front.

The additional utility `MPMCPipeline.h` is an extension that lets you
chain several queues together with processing steps in between.

#### [`PackedSyncPtr.h`](PackedSyncPtr.md)

A highly specialized data structure consisting of a pointer, a 1-bit
spin lock, and a 15-bit integer, all inside one 64-bit word.

#### [`Poly.h`](Poly.md)

A class template that makes it relatively easy to define a type-erasing
polymorphic object wrapper.

#### `Preprocessor.h`

Necessarily evil stuff.

#### [`ProducerConsumerQueue.h`](ProducerConsumerQueue.md)

Lock free single-reader, single-writer queue.

#### `Random.h`

Defines only one function---`randomNumberSeed()`.

#### `Range.h`

Boost-style range facility and the `StringPiece` specialization.

#### `RWSpinLock.h`

Fast and compact reader-writer spin lock.

#### `ScopeGuard.h`

C++11 incarnation of the old [ScopeGuard](http://drdobbs.com/184403758) idiom.

#### `Singleton.h`

A singleton to rule the singletons. This is an attempt to insert a layer between
C++ statics and the fiasco that ensues, so that things can be created, and destroyed,
correctly upon program creation, program end and sometimes `dlopen` and `fork`.

Singletons are bad for you, but this may help.

#### [`SmallLocks.h`](SmallLocks.md)

Very small spin locks (1 byte and 1 bit).

#### `small_vector.h`

Vector with the small buffer optimization and an optional embedded
`PicoSpinLock`.

#### `sorted_vector_types.h`

Collections similar to `std::map` but implemented as sorted vectors.

#### `stats/`

A collection of efficient utilities for collecting statistics:
* time series counters, gauges, histograms, and quantiles;
* single-pass mean and variance.

#### `StlAllocator.h`

STL allocator wrapping a simple allocate/deallocate interface.

#### `String.h`

String utilities that connect `folly::fbstring` with `std::string`.

#### `Subprocess.h`

Subprocess library, modeled after Python's subprocess module.

#### [`Synchronized.h`](Synchronized.md)

High-level synchronization library.

#### `System.h`

Demangling and errno utilities.

#### [`ThreadCachedInt.h`](ThreadCachedInt.md)

High-performance atomic increment using thread caching.

#### [`ThreadLocal.h`](ThreadLocal.md)

Improved thread local storage for non-trivial types.

#### `TimeoutQueue.h`

Queue with per-item timeout.

#### `Traits.h`

Type traits that complement those defined in the standard C++11 header
`<traits>`.

#### `Unicode.h`

Defines the `codePointToUtf8` function.

#### `Uri.h`

A collection of utilities to deal with URIs.

---

### Branch Lifecycle Policy (`docs/branch-lifecycle-policy.md`)

# Branch Lifecycle Policy

This repository enforces a branch lifecycle policy to keep the branch list clean and manageable. Stale branches are identified automatically and removed after a period of inactivity.

## How It Works

A scheduled GitHub Action ([cleanup-stale-branches.yml](../.github/workflows/cleanup-stale-branches.yml)) runs **every Monday at 08:00 UTC** and scans all remote branches for inactivity.

### Staleness Thresholds

| Branch type | Stale after | Examples |
|-------------|-------------|----------|
| `copilot/*` | **90 days** | `copilot/fix-xyz`, `copilot/workspace` |
| All other branches | **180 days** | `user/feature`, `abhi/experiment` |

Scheduled runs are always **dry run** (report only). Deletions require a manual trigger.

## Protected Branches

The following branch patterns are **always excluded** from cleanup, regardless of age:

- `main` / `master`
- `develop`
- `release/*`
- `hotfix/*`
- `archive/*`
- `*-stable` (e.g., `0.72-stable`, `0.80-stable`)
- `preview-*` (e.g., `preview-0.80-test`)

## Additional Safeguards

- **Open PRs** — Branches with any open pull request (including drafts) are automatically skipped.

## How to Keep a Branch

If your branch must be retained beyond the staleness threshold, use **any** of these methods:

### 1. Use a protected prefix
Rename your branch under `archive/`:
```
git branch -m my-old-branch archive/my-old-branch
git push origin archive/my-old-branch
git push origin --delete my-old-branch
```

### 2. Keep an open PR
Create or keep a pull request (even a draft) from your branch. The workflow skips any branch with an open PR.

### 3. Add the pattern to the workflow
Add your branch prefix to the `PROTECTED` regex in the workflow file and submit a PR.

## Manual Cleanup

Maintainers can trigger the workflow manually from the **Actions** tab:

1. Go to **Actions → Cleanup Stale Branches**
2. Click **Run workflow**
3. Set `dry_run = false` to actually delete stale branches

## FAQ

**Q: What happens if my branch is deleted by mistake?**
A: Git branch deletions on GitHub are reversible for a short period. You can also restore from a local clone. 

**Q: Will this delete branches with open pull requests?**
A: No. The workflow checks for open PRs (including drafts) and skips those branches.

**Q: What about stable and preview branches?**
A: All `*-stable` and `preview-*` branches are protected by default and will never be deleted.

---

### Branch Setup (`docs/branch-setup.md`)

# Git branch setup

This document describes how to set up your development environment and contribute changes to the **microsoft/react-native-windows** project. This document assumes basic working knowledge with Git and related tools. We are providing instructions specific to this project.

## Creating your own fork

If you wish to contribute changes back to the **microsoft/react-native-windows** repository, start by creating your own fork of the repository. This is essential. This will keep the number of branches on the main repository to a small count. There are lots of developers in this project and creating lots of branches on the main repository does not scale. In your own fork, you can create as many branches as you like.

- Navigate to **[GitHub](https://www.github.com)** with a browser and log in to your GitHub account. For the sake of this document, let's assume your username is **johndoe**.
- Navigate to the **[microsoft/react-native-windows](https://github.com/microsoft/react-native-windows)** repository in the same browser session.
- Click on the **Fork** button at the top right corner of the page.
- Create the fork under your account. Your GitHub profile should now show **react-native-windows** as one of your repositories.
- Create a folder on your device and clone your fork of the **Microsoft** repository. e.g. `https://github.com/johndoe/react-native-windows.git`. Notice how your GitHub username is in the repository location.

```
> git clone https://github.com/johndoe/react-native-windows.git
```

## Setting up the upstream repository

Before starting to contribute changes, please setup your upstream repository to the primary **microsoft/react-native-windows** repository.

- When you run `git remote -v`, you should see only your fork in the output list

```
> git remote -v

     origin  https://github.com/johndoe/react-native-windows.git (fetch)

     origin  https://github.com/johndoe/react-native-windows.git (push)
```

- Map the primary **react-native-windows** repository as the upstream remote

```
> git remote add upstream https://github.com/microsoft/react-native-windows.git
```

- Now running `git remote -v` should show the upstream repository also

```
> git remote -v

     origin  https://github.com/johndoe/react-native-windows.git (fetch)
     origin  https://github.com/johndoe/react-native-windows.git (push)
     upstream        https://github.com/microsoft/react-native-windows.git (fetch)
     upstream        https://github.com/microsoft/react-native-windows.git (push)
```

- At this point you are ready to start branching and contributing back changes.

## Making code changes and creating a pull request

Create a branch from your fork and start making the code changes.  We recommend using [**SourceTree**](https://www.sourcetreeapp.com/) for working in your repo. Once you are happy with the changes, and want to merge them to the main **microsoft/react-native-windows** project, create a pull request from your branch directly to "microsoft/react-native-windows main".

Members on the **microsoft/react-native-windows** core team will help merge your changes.

## Merging upstream main branch into your fork's main branch

From time to time, your fork will get out of sync with the upstream remote. Use the following commands to get the main branch of your fork up to date.

```
> git fetch upstream
> git checkout main
> git pull upstream main
> git push
```

### Merging upstream main into your current branch

Use these commands instead if you would like to update your *current* branch in your fork from the upstream remote.

```
> git fetch upstream
> git pull upstream main
> git push
```

---

### Build Pipelines (`docs/build-pipelines.md`)

# Build Pipelines

React Native Windows uses three Azure DevOps pipelines built on the Office and general 1ES Pipeline Templates.

## Pipeline Overview

| Pipeline | File | Template | Trigger |
|----------|------|----------|---------|
| **CI** | `.ado/ci-pipeline.yml` | Office Official | Push to `main`, `*-stable` |
| **PR** | `.ado/pr-pipeline.yml` | 1ES Unofficial | PRs to `main`, `*-stable` |
| **Release** | `.ado/release-pipeline.yml` | Office Official | Triggered by successful CI run |

CI and PR share a single `build-template.yml` that contains all build, test, and packaging logic. The `buildEnvironment` parameter (`Continuous` or `PullRequest`) controls what runs:

- **Both**: build, test, lint, NuGet pack, CLI init verification
- **CI only**: ESRP code signing, release tagging
- **PR only**: beachball change file check

## Stages

```
Setup ──┬── Build ──── CLI
        │
        └── Tests
```

### Setup

Detects whether this is a **release build** (commit message starts with `RELEASE:`) or a **developer build**. For developer builds, runs beachball to bump versions. Publishes version variables for all downstream stages.

### Build

Runs in parallel for each platform/configuration in the build matrix:

- **Desktop** (x64/x86/ARM64EC, Debug/Release) — builds, runs unit and integration tests, signs shipping binaries (CI)
- **Universal** (x64/x86/ARM64, Debug/Release) — builds, runs unit tests, signs shipping binaries (CI)
- **Linting** — JS/TS lint, format check, override validation
- **NPM Pack** — creates npm tarballs
- **NuGet Pack** — downloads all build artifacts, packs NuGet packages, ESRP signs them (CI)

Each build job uses `*-single.yml` step templates that build the full `.sln`, run tests, and stage shipping artifacts — we test what we ship.

### Tests

Runs in parallel with Build (both depend only on Setup):

- **Node Tests** — Jest-based JavaScript tests
- **Playground** — builds playground apps across configs
- **E2E Tests** — Fabric end-to-end tests

### CLI

Depends on Build (needs the NuGet packages). Runs `react-native init` + `react-native-windows init` against the just-built packages to verify the developer experience works.

## Agent Pools

| Pool | Used By |
|------|---------|
| `fabric-internal-pool-large` | CI: all jobs |
| `rnw-pool-4` | PR: most jobs (default) |
| `rnw-pool-8` | PR: native builds |

PR uses public pools (no `-microsoft` suffix). The PR entry point overrides the pool defaults.

## SDL & Compliance

The Office Official template (CI) handles SDL automatically:

- **CredScan** — credential scanning
- **BinSkim** — binary security analysis (per-job targets via `templateContext.sdl`)
- **Component Governance** — open-source license compliance
- **CodeQL** — static analysis
- **ESLint** — JS/TS analysis (with exclusions)

PREfast, SpotBugs, and Bandit are disabled (no actionable findings for this repo).

## Release Flow

1. Developer merges a PR to `main`
2. **CI pipeline** runs: build, test, sign, pack
3. On success, a separate **prepare-release-bot** pipeline creates/updates a release PR (e.g., `prepare-release/main`)
4. When the release PR is merged (commit message: `RELEASE: ...`), CI runs again as a **release build**:
   - Skips beachball bump (versions already committed)
   - Builds, tests, signs, packs
   - Tags the source commit (`react-native-windows_v<version>`)
5. **Release pipeline** triggers on successful CI, publishing packages to npm and NuGet feeds

## Key Files

| File | Purpose |
|------|---------|
| `.ado/ci-pipeline.yml` | CI entry point |
| `.ado/pr-pipeline.yml` | PR entry point |
| `.ado/build-template.yml` | Shared build/test/pack logic |
| `.ado/release-pipeline.yml` | Release pipeline (publishes to feeds) |
| `.ado/jobs/desktop-single.yml` | Desktop build + test steps |
| `.ado/jobs/universal-single.yml` | Universal build + test steps |
| `.ado/jobs/cli-init-windows.yml` | CLI init verification |
| `.ado/jobs/e2e-test.yml` | E2E test job |
| `.ado/jobs/playground.yml` | Playground build job |
| `.ado/jobs/linting.yml` | Linting job |
| `.ado/jobs/node-tests.yml` | Node/Jest test job |
| `.ado/templates/prep-and-pack-nuget.yml` | NuGet packing steps |
| `.ado/templates/esrp-codesign-*.yml` | ESRP signing steps |

---

### Building Rnw (`docs/building-rnw.md`)

# Building React-Native-Windows

- Make sure you have installed [dependencies](https://microsoft.github.io/react-native-windows/docs/next/rnw-dependencies). Just run `vnext\scripts\rnw-dependencies.ps1` in an elevated PowerShell session.
- Install [Git](https://git-scm.com/download/win) if you don't have it installed in your development machine

## Build Steps
* Clone the repo
    ```cmd
    git clone https://github.com/microsoft/react-native-windows.git
    cd react-native-windows
    ```

* Install dependencies, and run JS build steps
    ```cmd
    yarn
    ```
Note that react-native-windows is a monorepo and relies on monorepo tools like yarn and lage.  See [this page](monorepo.md) for more details.

# Running the Playground app
  There are two ways to run the app.  In a fully managed easy way, or by manually running all the required steps:

## Automatic
The playground app can be run in a completely automatic way by doing:

```cmd
cd packages\playground
yarn windows --sln windows\playground.sln
```

## Manual

### Run the bundle server:
```cmd
cd packages\playground
yarn start
```

### Build solution

  * Using MSBuild
    ```cmd
    MSBuild.exe [/p:Platform=$(TargetPlatform)] [/p:Configuration=$(TargetConfiguration)]
    ```

  * Using Visual Studio IDE
    1. Open `Playground.sln`.
    2. Set your `Platform` to `x86` or `x64` and `Configuration ` to `Debug`.
    3. Select `Project / Build Solution (Ctrl+Shift+B)`

### Ensure debugger is running
Open Chrome and navigate to `http://localhost:8081/debugger-ui/` in a new tab. Press `F12` or `Ctrl+Shift+I` in Chrome to open its Developer Tools.

### Run the app
* In Visual Studio, set Playground as the StartUp Project.

* Run project (`F5` or `Debug / Start Debugging`).

You now see your new app and Chrome should have loaded `http://localhost:8081/debugger-ui/` in a new tab. Press `F12` or `Ctrl+Shift+I` in Chrome to open its Developer Tools.

### Load a sample bundle
* Press the "Load" button on the left side of the Windows 10 application window that appears.

 The selected React Native component (defaulted to `Bootstrap`) should get loaded in the bottom of the application window

 Try out the various samples by selecting from the comboboxes at the top of the application window and pressing "Load".

---

### Contributing (`docs/contributing.md`)

# Contributing to microsoft/react-native-windows

If this is your first time, below are some more detailed steps for getting your branch set up and submitting a PR. You can either do this with the command prompt or with a combination of the command prompt and SourceTree.

### Setting up your branch for changes 
 
For each bug or task you complete, it is recommended that you start with a fresh branch. If you have any lingering changes in your current branch that you want to save, go ahead and commit them. If you are just beginning, then you are good to go. On github, navigate to your repository which should be forked from microsoft/react-native-windows. If you haven't already created a fork, follow the steps in **[Git branch Setup](branch-setup.md)**. Above the list of files is a dropdown that should say 'main'. Use the dropdown to create a new branch and name is according to what you will be working on. (I.e. DropdownHighlight, CleanUpExamples, etc). Now you have created a new branch. 

**SourceTree:**
If you are using SourceTree you will want your branch to show up in SourceTree so you can commit changes to your branch. It takes time for it to show up automatically, so you can make it show by running `git remote update origin –prune` in your command prompt from the root. Once you see your new branch in SourceTree under Remotes on the left navigation pane, double click on your branch to check it out locally. A dialog will come up and the default settings should be fine, click Ok.  

**Git Command Line**
If you are using the command line, you will want to make sure you have your branch locally. It takes time for it to show up automatically, so you can make it show by running `git remote update origin –prune` in your command prompt from the root. Run `git branch -a` to see if your new branch shows up. Now you will want to check out your branch locally. You can do this with `git checkout -b branch-name`. Confirm you are now working out of the branch with `git branch`.

 
### Make the fix
Now that your branch is set up and ready for commits, go ahead and fix the bug you are working on or make some small change that you want to check in. 
 
### Verify your changes
Manually test your fix, and ensure that all tests are in a good state

### Commit your changes

**SourceTree:**
In SourceTree, click on commit in the top left. This won't actually do anything to your files, it will just change to show the commit UI. In the bottom container, stage all of the files you want to submit by selecting them and clicking "Stage". Add a short message in the textbox at the bottom on what is included in your change. This will not show as your entire submission text, just for this commit. 
 
**Git Command Line**
To stage files using the command line, you need to run `git add MyFileOne.tsx` for each file. You can also look up how to add all files with changes under a directory. Next you will want to commit changes with `git commit –m "This change updates the padding in the dropdown"`

You can commit multiple times until you are ready to make a pull request. You should keep the message short since it will not be used in the bug notes and is just for keeping track of the multiple commits in one pull request. 

### Run auto-format
Run `yarn format` in the repository's root directory if you're making C++ changes.

Run `yarn lint:fix` if making JS/TS changes.

### Provide changelog information
Run `yarn change --branch upstream/main` in the root of the repo.

### Creating a Pull Request

**SourceTree:**
In SourceTree click Push.

**Git Command Line**
Run `git push`. 

This will push any staged files you have in your branch.
 
Now go back to your fork on github. You should see a yellow bar at the top with your change and a button that says "Compare & Pull Request". Click that button. 

Click "Create Pull Request".

A bunch of tests will automatically kick off to verify your PR.  The tests marked as `required` must pass before a PR can be merged.  Currently the Azure Dev Ops tests will not kick off automatically.  -- These have to be kicked off by a team member.

Someone will also have to review your change before the change is allowed to be merged in. They may ask questions for more information or ask you to change things. Be sure to respond to their comments and push additional changes to the branch if they ask you to modify things before they sign off.
 
Now you are done! Celebrate!

---

### E2e Testing (`docs/e2e-testing.md`)

# End-to-End Testing

## e2e-test-app project structure

A test app, test library and test cases are in [`/packages/e2e-test-app-fabric/`](../packages/e2e-test-app-fabric), and are organized as below.

 - `test` – includes Jest tests using webdriverio
 - `windows` – the UWP native app
 - `jest.config.js` – configuration for Jest and WebDriverIO

## Running Tests

**Install [WinAppDriver v1.2.1](https://github.com/microsoft/WinAppDriver/releases/download/v1.2.1/WindowsApplicationDriver_1.2.1.msi)**

This will be automatically done for you if you use the [RNW dependency script](https://microsoft.github.io/react-native-windows/docs/rnw-dependencies) with `rnwDev` as an argument.

The E2E tests assume it is installed in the default location under `C:\Program Files (x86)\Windows Application Driver\WinAppDriver.exe`. If you choose a different path, you will need to specify it in [`/packages/e2e-test-app-fabric/jest.config.js`](../packages/e2e-test-app-fabric/jest.config.js).
```js
module.exports = {
...
  testEnvironmentOptions: {
    ...
    winAppDriverBin: 'D:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe',
  },
};
```

**Build the native test app**

> C:\repo\react-native-windows> `cd packages\e2e-test-app-fabric`
>
> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn windows --no-launch`

**Running all tests**

> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn start`
> 
> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn e2etest`


**Running a specific test**

> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn start`
> 
⚠ Only the test filename (without the rest of the path) should be included.
> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn e2etest visitAllPages.test.ts`

**Break on app start**

> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn start`
> 
> C:\repo\react-native-windows\packages\e2e-test-app-fabric> `yarn e2etest:debug visitAllPages.test.ts`

## Debugging E2E Tests in CI
### Increasing verbosity
By default the only messages printed during tests are related to errors returned by WinAppDriver or assertion failures. It is possible to increase verbosity to show individual WebDriver wire commands by editing [`/packages/e2e-test-app-fabric/jest.config.js`](../packages/e2e-test-app-fabric/jest.config.js).

```js
module.exports = {
...
  testEnvironmentOptions: {
    ...
    webdriverOptions: {
      // Level of logging verbosity: trace | debug | info | warn | error
      logLevel: 'error',
      ...
    },
  },
};
```

### Test Artifacts

If you have access to the AzureDevOps pipeline you'll be able to see test failures and debug crashes.
Here are the artifacts that are produced during the build:
- error screenshots of the app when a test failed
- test run XML - this contains some information like the name of the wdio test that failed and the JS stack
- tree dump outputs - you can compare these to the output of the main branch to see if there is a the difference responsible for the test failing. 
- crash dumps of the e2e test app (RNTesterApp)

You can access these by going to the AzureDevOps run for your PR and clicking on the artifacts link:



## Architecture

### WinAppDriver

WinAppDriver uses [UIA](https://docs.microsoft.com/en-us/windows/uwp/design/accessibility/accessibility-testing) to
inspect and manipulate a test application, allowing clients to connect to it using the w3c WebDriver protocol.

### WebDriverIO

WebDriverIO is a JavaScript library which connects to WinAppDriver using the WebDriver protocol. It provides [global
APIs](https://webdriver.io/docs/api) for querying the application UI tree such as selectors (see below) and a global `browser` object to manipulate the
test application.

### Jest

Jest is the test runner used for end-to-end testing, including assertsion libraries, test selection, etc. WebDriverIO setup is
provided by a custom environment [`@react-native-windows/automation`](../packages/@react-native-windows/automation).

## Authoring Tests

Tests are written using Jest and WebDriverIO (see more below) against a test app running `RNTester`. `RNTester` example
pages are used as Test UI, which is examined via Jest tests. Tests should attempt to target an existing `RNTester` page, but "Legacy" tests exist as custom pages only used by e2e-test-app-fabric

### Writing a test against an RNTester example page

```ts
// LegacyControlStyleTestPage.test.ts

describe('FancyWidget', () => {

  beforeAll(async () => {
    await goToComponentExample('FancyWidget');
  });

  test('FancyWidget is populated with placeholder', async () => {
    // Query for an element with accessibilityId of "foo" (see "locators" below)
    const field = await app.findElementByTestID('foo');
    expect(await field.getText()).toBe('placeholder');
  });

});
```

### Adding a custom RNTester page

Before adding a custom page, consider whether the change can be made to an existing RNTester page and upstreamed. If needed, new examples may be integrated into the Windows fork of RNTester, [`@react-native-windows/tester`](../packages/@react-native-windows/tester).

Hooks are recommended to author the test page. (see [https://reactjs.org/docs/hooks-intro.html](https://reactjs.org/docs/hooks-intro.html) and this [Pluralsight course](https://www.pluralsight.com/courses/using-react-hooks) to learn more about Hooks)

```js
// ControlStyleTestPage.tsx
export const title = 'LegacyControlStyleTest';
export const description = 'Legacy e2e test for Control Styles';
export const examples = [
  {
    render: function(): JSX.Element {
      return <ControlStyleTestPage />;
    },
  },
];
```

```js
  // RNTesterList.windows.js
  ...
  {
    key: 'LegacyControlStyleTest',
    module: require('../examples-win/LegacyTests/ControlStyleTestPage'),
  },
  ...
```

## Snapshot tests

E2ETests uses [snapshot tests](https://jestjs.io/docs/en/snapshot-testing) to detect unintended visual changes. Instead
of testing against the react tree, e2e-test-app-fabric compares the fully rendered composition tree. This allows testing the
correctness of ViewComponents.

```ts
import {dumpVisualTree} from '@react-native-windows/automation-commands';

test('Example test', async () => {
  const dump = await dumpVisualTree('test-id-here');
  expect(dump).toMatchSnapshot();
});
```

Snapshots can be updated by either:
1. Locally running `jest --updateSnapshot`.
2. Copying from the "shapshots" artifact uploaded from a failing PR

---

### Inspector (`docs/inspector.md`)

# Hermes Inspector

*React Native for Windows* with *Hermes engine* now supports direct JavaScript runtime inspection using tools such as Chrome or Edge devtools, VSCode debugger, Flipper etc. by implementing an in-process Chrome Debug Protocol server. 
Please note that it is fundamentally different from "Remote JS Debugging", which loads the JavaScript bundle into a remote Chrome browser session with duplex communication over IPC channels.

We share the implementation (code and design) with other platforms wherever possible. All the external endpoints, APIs and protocols should be identical to *React Native* environments on other platforms. 
Hence, we expect most tooling available on other platforms to just work on Windows. But, as of now, we have tested only with Chrome and Edge devtools.

## Steps to enable direct debugging

1. Initialize React Native Host,
   - Turn on `DeveloperSupport` 
   - Turn on `FastRefresh`
   - Turn on `Direct Debugging`
2. Ensure Dev-Server is running
3. Start the application

After the app has booted,

4. Navigate to `edge://inspect` in Edge browser or `chrome://inspect` in Chrome browser
5. Enable **Discover network targets** and **configure** the target discovery settings to include `localhost:8081` (or wherever the metro server is running)
6. Within a few seconds "Hermes React Native" should appear on the page as a remote target
7. Click on the **inspect** link to launch the devtools page
8. Click `Ctrl+P` to open source files and set break points
9. Alternatively, you can insert `debugger` statements in source code to break on specific locations

In order to break on locations during boot, you can either

- `debugger` statements during boot sequence will pause the runtime waiting for debugger to connect
- Set break point and refresh the bundle through the Dev Server. The runtime will wait for debugger to attach.

## Steps to enable heap profiling

Follow steps 1-7 from above, and then
1. Click on the "Memory" tab in the inspector
2. Heap snapshots and instrumented allocations with callstacks should be working.

## Enable debugging/profiling on release builds

We keep the inspector turned off on release builds by default. If you want to debug or profile release builds, set the MSBuild property `EnableHermesInspectorInReleaseFlavor` to `'true'` when building the platform.

---

### Modern Inspector Details (`docs/modern-inspector-details.md`)

# Modern Inspector Support in React Native for Windows

## Overview
The modern inspector is the Chrome DevTools–based debugging experience that ships with the latest
versions of React Native. This experience now works end-to-end for React Native for Windows (RNW)
applications, enabling parity with Android and iOS. The integration provides a unified way to inspect
JavaScript execution, evaluate console expressions, profile CPU and memory usage, and visualize the
component hierarchy for both the Paper and Composition UI stacks.

## Modern Inspector Building Blocks
- **Host Target** – One per `ReactHost`; surfaces metadata, reload requests, pause overlays, and
  implements the CDP-facing delegate (`ReactInspectorHostTargetDelegate`).
- **Instance Target** – Created for each React instance; registers runtime targets, tracks instance
  lifecycle, and unregisters cleanly on reload.
- **Runtime Target & Agent** – Runtime targets map to JavaScript VMs; agents are per-session objects
  that translate Chrome DevTools Protocol (CDP) messages into engine calls. RNW mirrors upstream
  lifetimes so reloads tear everything down deterministically.
- **Frontend Channel** – Delivers JSON CDP payloads between the RNW host and DevTools.
- **Inspector Thread** – A single `ReactInspectorThread` ensures CDP work is serialized away from
  the UI and JS queues. (iOS and Andrtoid use UI thread.)
- **Debugger Notifications** – `DebuggerNotifications.h` broadcasts pause/resume events so view
  hosts can react (e.g., showing overlays or resuming when the debugger continues).

## Windows Integration Points
- **ReactHost & ReactOptions** – `ReactHost` creates the `HostTarget`, exposes it through
  `ReactOptions::InspectorHostTarget`, and implements reload/pause hooks. This is the jump-off point
  for all inspector traffic. The inspector supported only if the `UseDirectDebugger` is true.
- **ReactInstanceWin / OInstance** – Register and unregister instance/runtime targets around runtime
  creation, keeping the inspector aligned with bridgeless and legacy bridge lifecycles.
- **DevSupportManager & Packager** – `DevSupportManager` now spins up
  `ReactInspectorPackagerConnectionDelegate`, allowing Metro to broker modern inspector connections
  and reuse the existing websocket infrastructure.
- **Dev Console Shortcut** – Metro’s `J` shortcut launches the inspector for Windows apps, matching
  upstream behavior.

## UI Overlays
- **Composition** – `DebuggerUIIsland` renders pause overlays, focus chrome, and selection adorners
  whenever the runtime is paused.
- **Paper** – `ReactRootView` updates provide the same pause/selection affordances.

## Hermes Runtime Integration
- `HermesRuntimeTargetDelegate` and `HermesRuntimeAgentDelegate` wrap the hermes-windows C debug API
  so we can re-use upstream modern inspector code.
- `RuntimeHolder`/`HermesRuntimeHolder` surface a `createRuntimeTargetDelegate` hook that instantiates
  delegates only when the inspector is enabled, and safely tears them down during reloads.

## Packager & Console Integration
- `ReactInspectorPackagerConnectionDelegate` maps the Metro websocket APIs to the modern inspector
  handshake.
- Console output, CPU sampling, and memory profiling are forwarded through the Hermes inspector
  plumbing automatically once a session is active.

## Using the Modern Inspector with RNW
1. Start your Metro bundler (`npx react-native start` or `yarn start`).
2. Launch your RNW app (Paper or Composition).
3. In the Metro console, press `J` to open the modern inspector URL in a browser.
4. Chrome DevTools will connect to the Hermes runtime. Pause execution, explore the component tree,
  and capture profiles as needed.
5. When execution is paused, the corresponding overlay is rendered in the app window; resume to clear
  the overlay.

## Known Limitations & Follow-Up Work
- **Network profiling** – The `NetworkIOAgent` is not wired up yet for Windows. The integration point
  is the `ReactInspectorHostTargetDelegate` in
  `vnext/Microsoft.ReactNative/ReactHost/ReactHost.cpp`; override `loadNetworkResource` there to
  forward requests through a Windows HTTP helper (similar to `GetJavaScriptFromServerAsync`) and
  stream results back via the provided `NetworkRequestListener`. Until this happens, the Network tab
  in DevTools stays empty.

---

### Monorepo (`docs/monorepo.md`)

# Monorepo details for react-native-windows
react-native-windows is a monorepo with several [packages](https://github.com/microsoft/react-native-windows/tree/main/packages) and uses monorepo management tools to install, build, and publish.  This page is all about what tools we use to manage this monorepo and some technical details, aimed at folks who are contributing to react-native-windows.

# Installation of npm dependencies
react-native-windows uses [yarn workspaces](https://classic.yarnpkg.com/en/docs/workspaces/) to install all react-native-windows npm dependencies.  See "workspaces" prop inside [package.json](https://github.com/microsoft/react-native-windows/blob/main/package.json).

# Lage Build
react-native-windows uses [lage](https://microsoft.github.io/lage/) to build all the "non-native" parts of react-native-windows.  See "scripts" prop inside  [package.json](https://github.com/microsoft/react-native-windows/blob/main/package.json).  Also see [laga.config.js](https://github.com/microsoft/react-native-windows/blob/main/lage.config.js).

# Beachball publishing
TODO - add details

---

### Project Structure (`docs/project-structure.md`)

# MSBuild Project Structure

This is a description of each of the core projects, their purpose and output artifacts.<br/>
Sample applications are not covered.

## Alphabetical Index
- [Common\Common.vcxproj](#Common)
- [Desktop\React.Windows.Desktop.vcxproj](#React.Windows.Desktop)
- **[Desktop.DLL\React.Windows.Desktop.DLL.vcxproj](#React.Windows.Desktop.DLL)**
- [Desktop.IntegrationTests\React.Windows.Desktop.IntegrationTests.vcxproj](#React.Windows.Desktop.IntegrationTests)
- [Desktop.UnitTests\React.Windows.Desktop.UnitTests.vcxproj](#React.Windows.Desktop.UnitTests)
- [Folly\Folly.vcxproj](#Folly)
- [FollyWin32\FollyWin32.vcxproj](#FollyWin32)
- [IntegrationTests\React.Windows.IntegrationTests.vcxproj](#React.Windows.IntegrationTests)
- **[Microsoft.ReactNative\Microsoft.ReactNative.vcxproj](#Microsoft.ReactNative)**
- [Microsoft.ReactNative.Cxx\Microsoft.ReactNative.Cxx.vcxitems](#Microsoft.ReactNative.Cxx)
- [Microsoft.ReactNative.Managed\Microsoft.ReactNative.Managed.csproj](#Microsoft.ReactNative.Managed)
- [Microsoft.ReactNative.SharedManaged\Microsoft.ReactNative.SharedManaged.projitems](#Microsoft.ReactNative.SharedManaged)
- [ReactCommon\ReactCommon.vcxproj](#ReactCommon)
- [ReactCommon.UnitTests\ReactCommon.UnitTests.vcxproj](#ReactCommon.UnitTests)
- [Shared\Shared.vcxitems](#Microsoft.ReactNative.Shared)

## Common Projects

### Common
*Static Library*\
Functionality shared between React and JSI projects.

### Microsoft.ReactNative.Shared
*Shared Items (no build artifact)*\
Holds sources common to both Windows variants, that require different build configuration
(i.e. compiler flags, language standard).

### ReactCommon
*Static Library*\
React Native core, cross-platform C++ types and interfaces.\
Sources provided as part of the `react-native` Node dependency. Not part of this repository.\
See https://github.com/facebook/react-native/tree/v0.62.0/ReactCommon.

### Folly
*Static Library*\
Folly variant type system for JavaScript/C++ interoperability.\
Sources provided as part of the `react-native` Node dependency. Not part of this repository.

### Microsoft.ReactNative.Cxx
*Shared Items (no build artifact)*\
Contains helpers to simplify authoring C++/WinRT native modules on top of [Microsoft.ReactNative](#Microsoft.ReactNative).

### Microsoft.ReactNative.Managed
*Managed Library*\
Contains helpers to simplify authoring C# native modules on top of [Microsoft.ReactNative](#Microsoft.ReactNative).

### Microsoft.ReactNative.SharedManaged
Deprecated: This is still here so that customers get a specific error message on how to upgrade their project.

### React.Windows.IntegrationTests
*Static Library*\
Common framework for running out of process and/or full React instance testing.

### IntegrationTests (Node Project)
*MSBuild Node project. For reading/editing purposes only (no build artifact)*\
Set of JavaScript component tests for [RNTester](https://github.com/facebook/react-native/tree/v0.62.0/RNTester).
Sources provided as part of the `react-native` Node dependency. Not part of this repository.\
See https://github.com/facebook/react-native/tree/v0.62.0/IntegrationTests.

## Windows Desktop Projects

### React.Windows.Desktop
*Static Library*\
Set of Native Modules, View Managers and Executors for Windows Desktop.

### React.Windows.Desktop.DLL
*Dynamic Library*\
Shared library that exports the intended public API surface for [React.Windows.Desktop](#React.Windows.Desktop).\
**Main artifact to use in Windows Desktop applications.**

### React.Windows.Desktop.UnitTests
*VSTest Dynamic Library*\
Set of isolated (mocked) tests for types defined in [React.Windows.Desktop](#React.Windows.Desktop).

### React.Windows.Desktop.IntegrationTests
*VSTest Dynamic Library*\
Set of component tests that validate functionality against external runtime components
(i.e. networking servers, file system, React Native applications, external processes).\
Validates [React.Windows.Desktop.DLL](#React.Windows.Desktop.DLL).

### ReactCommon.UnitTests
*Google Test Application*\
Gathers tests within `react-native\ReactCommon`.\
Its main purpose is to validate JSI with any given engine (V8, etc).

### FollyWin32
*Static Library*\
Superset of Folly APIs only available and required by [React.Windows.Desktop](#React.Windows.Desktop).\
Sources provided as part of the `react-native` Node dependency. Not part of this repository.

## Windows Universal Projects

### Microsoft.ReactNative
*Windows Runtime Component*</br>
The primary Windows Universal entry point and public API surface for React Native Windows.\
**Main artifact to use in Windows Universal applications.**

---

### React Native Windows Init (`docs/react-native-windows-init.md`)

# React Native Windows initialization

This document describes how the template initialization works for `react-native-windows init`.

## Where is the code:
The main logic that determines the template values and which files to apply is function [`copyProjectTemplateAndReplace` in `packages/@react-native-windows/cli/src/generator-windows/index.ts`](../packages/@react-native-windows/cli/src/generator-windows/index.ts#L48).
The parameters for `init` is located in variable [`argv` in `packages/react-native-windows-init/src/Cli.ts`](../packages/react-native-windows-init/src/Cli.ts#L27)

The template files can be found in [`vnext/template`](../vnext/template)

## Debugging:
To debug the template, see [Contributing to the CLI](https://github.com/microsoft/react-native-windows/wiki/Contributing-to-the-CLI) on our wiki.

## Templating tech (Mustache)
PR [#5126](https://github.com/microsoft/react-native-windows/pull/5126) updated the template generation for react-native-windows from regex replace to use the mustache template library. 

### Benefits
This has the following benefits:
* We can use conditionals and `foreach` in the template allowing for better expressivity
* This expressivity shows that we don't have to construct XML fragments in JavaScript anymore to be inserted by `regex.replace`
* We don't need to have have a copy and edit for large differences like we had for experimental NuGet, it is now a single template for each language.
* We can now generate a cpp template that use both NuGet AND WinUI3.

### Research before setteling on Mustache
There are several templating schemes we could have chosen. We had a quick discussion and chose [mustache](https://www.npmjs.com/package/mustache) as it is a well-adopted, lightweight library dedicated for templating.
Alternatives considered:
 * js template expression: This would have required all files to become js programs that needed to be imported and evaluated. Since a lot of files contain data format or code, we would have likely had quite a few ugly escaping cases.
 * T4:  This would have required visual studio to be installed on the users machine and therefore only work on Windows. There were also some perf concerns and we would have to write and ship a standalone executable for the MSBuild tasks so we can call it from JavaScript.

### Quick mustache tutorial:
For proper docs see the [manual](https://mustache.github.io/mustache.5.html) of [mustache](https://mustache.github.io/)
But in short:
You run `mustache` via `const text = mustache.render(inputText, obj);` where obj is a regular JavaScript object. 
For example:
```js
{
   name: 'you',
   condition1: true,
   condition2: false,
   myIds: [
    { id: 'abc' },
    { id: 'xyz' }
   ]
}
```

We only use 4 mustache elements replacement patterns:
 * The template `Hello {{ name }}!` will result in `Hello you!`.
 * The template `Hello {{#condition1}}you!{{/condition1}}` will result in `Hello you!`
 * The template `Hello {{^condition2}}you!{{/condition2}}` will result in `Hello you!`
 * The template:
   ```
   MyIds:
   {{#myIds}}
   Id: {{ id }}
   {{/myIds}}
   ```
   will result in:
   ```
   MyIds
   Id: abc
   Id: xyz
   ```

## Future
In the future we hope this to be integrated with the react-native CLI templating scheme. At the moment there is only a very basic replacement scheme for a set of well-defined variables, so at the moment it is not suitable. When we get to that point we'll see if we can leverage that or contribute some improvements in the templating for `react-native-init`.

---

### Sdl Gs Crash Monitoring (`docs/sdl-gs-crash-monitoring.md`)

# SDL Policy: /GS Stack Buffer Overrun Crash Monitoring

## Overview

This document describes the process for monitoring, analyzing, and fixing /GS (stack buffer overrun) crashes in React Native Windows, in accordance with Microsoft's Security Development Lifecycle (SDL) policy requirements.

## What is a /GS Crash?

A /GS crash occurs when the `/GS` compiler flag detects stack buffer corruption. The `/GS` flag adds security checks (stack cookies) to detect buffer overruns. When a mismatch is detected, the application is terminated with exception code **0xc0000409** (`STATUS_STACK_BUFFER_OVERRUN`).

## SDL Policy Requirements

Per Microsoft SDL policy:

1. **All high-confidence /GS crashes must be analyzed and fixed when appropriate**
2. **A monitoring plan must be in place to analyze future /GS failures within 60 days** of being reported to Watson
3. **Teams must investigate all crashes that are not false-positives** (`GS_FALSE_POSITIVE_*`)
4. **Fix identified stack buffer overruns** to prevent potential security vulnerabilities

## /GS Crash Classifications

Watson automatically classifies /GS crashes using the `!gs` debugger extension:

- **GS_POSITIVE**: High-confidence stack buffer overrun. **MUST be fixed immediately.**
- **GS_SUSPECT**: Suspected stack buffer overrun. Should be investigated.
- **GS_FALSE_POSITIVE**: False positive due to process corruption. Can be safely ignored.

## Monitoring Process

### 1. Finding /GS Crashes in Watson

1. Go to [Watson](https://aka.ms/watson)
2. Select "Buffer Overruns" under "Enter ANY of the following to see matching BUCKET(s)"
3. Enter the application name (szAppName) or DLL name (szModName)
4. Click "Show Crash/Hang Buckets"
5. Filter for crashes with exception code `0xc0000409`

### 2. Analyzing /GS Crashes

Use the provided `Analyze-Crash.ps1` script to analyze crash dumps:

```powershell
# Analyze a specific dump file
.\vnext\Scripts\Analyze-Crash.ps1 -DumpFilePath "path\to\crash.dmp"

# Or configure automatic dump collection for an exe
.\vnext\Scripts\Analyze-Crash.ps1 -ExeName "YourApp"
```

The script will:
- Detect if the crash is a /GS crash (0xc0000409)
- Run the `!gs` debugger extension for detailed analysis
- Classify the crash (GS_POSITIVE, GS_SUSPECT, or GS_FALSE_POSITIVE)
- Provide actionable guidance based on the classification

### 3. Triage and Response Timeline

| Classification | Priority | Action Required | Timeline |
|---------------|----------|----------------|----------|
| GS_POSITIVE | Critical | Analyze, fix, and test | Within 60 days of Watson report |
| GS_SUSPECT | High | Investigate and determine if real | Within 90 days |
| GS_FALSE_POSITIVE | Low | No action required | N/A |

### 4. Fixing /GS Crashes

When a real stack buffer overrun is identified:

1. **Review the crash analysis**
   - Check the `!gs` output in the analysis log
   - Identify the function with the buffer overrun
   - Locate the source of the overrun (strcpy, sprintf, etc.)

2. **Implement the fix**
   - Replace unsafe functions with safe alternatives:
     - `strcpy` → `strcpy_s`
     - `strcat` → `strcat_s`
     - `sprintf` → `sprintf_s` or `snprintf`
     - `gets` → `fgets` or `gets_s`
   - Add bounds checking to array operations
   - Validate input sizes before copying

3. **Test the fix**
   - Reproduce the original crash scenario
   - Verify the crash no longer occurs
   - Run existing tests to ensure no regressions

4. **Document the fix**
   - Include CVE information if applicable
   - Document the root cause and fix in commit message
   - Update security documentation if needed

## Common Vulnerable Patterns

Watch out for these common patterns that can lead to stack buffer overruns:

```cpp
// UNSAFE: No bounds checking
char buffer[100];
strcpy(buffer, userInput);  // ❌

// SAFE: Use safe alternative with size
char buffer[100];
strcpy_s(buffer, sizeof(buffer), userInput);  // ✅

// UNSAFE: sprintf without size limit
char buffer[50];
sprintf(buffer, "Value: %s", userInput);  // ❌

// SAFE: Use snprintf with size limit
char buffer[50];
snprintf(buffer, sizeof(buffer), "Value: %s", userInput);  // ✅

// UNSAFE: Array access without bounds check
void ProcessArray(int* data, int count) {
  int localArray[10];
  for (int i = 0; i < count; i++) {  // ❌ count could be > 10
    localArray[i] = data[i];
  }
}

// SAFE: Add bounds checking
void ProcessArray(int* data, int count) {
  int localArray[10];
  int safeCount = std::min(count, 10);
  for (int i = 0; i < safeCount; i++) {  // ✅
    localArray[i] = data[i];
  }
}
```

## Reporting Security Issues

If a /GS crash is determined to be a security vulnerability:

1. **Do NOT create a public GitHub issue**
2. Report to Microsoft Security Response Center (MSRC):
   - Online: https://msrc.microsoft.com/create-report
   - Email: secure@microsoft.com
3. Include:
   - Type of issue (stack buffer overrun)
   - Full paths of affected source files
   - Steps to reproduce
   - Crash dump and analysis (if safe to share)
   - Potential security impact

See [.github/security.md](../.github/security.md) for full security reporting guidelines.

## Tools and Resources

- **Analyze-Crash.ps1**: Automated crash analysis script with /GS detection
- **Watson**: https://aka.ms/watson - Microsoft crash reporting system
- **!gs debugger extension**: Built into Windows debuggers, analyzes /GS crashes
- **!analyze -v**: Verbose crash analysis including !gs output

## Regular Monitoring Schedule

To comply with SDL requirements:

1. **Weekly**: Check Watson for new /GS crashes
2. **Monthly**: Review and triage all open /GS issues
3. **Quarterly**: Audit codebase for unsafe string/buffer operations
4. **Before Release**: Ensure no open GS_POSITIVE crashes remain

## Questions?

For questions about /GS crashes or SDL policy:
- Internal: Contact your team's security champion
- External: File an issue in the repository (for non-security questions)
- Security issues: Follow the reporting process in [.github/security.md](../.github/security.md)

---

### Testing Nuget Packages (`docs/testing-nuget-packages.md`)

## Testing NuGet package for new @react-native-community/cli init templates.
Today's default is to use the C++ and C# code from the `react-native-windows` npm package as source. We have been working on moving to a binary distribution model for this code via NuGet. 

Today we support the following projects as a NuGet package:
 * Microsoft.ReactNative
 * Microsoft.ReactNative.Managed

 Testing NuGet packages is frequently a painful process as msbuild and NuGet lack referential transparency. The steps in this document hope to alleviate some of the challenges.

## Complicating factors
* NuGet packages can only be loaded from a feed
  > These scripts help maintain a test feed on your local disk
* Each change requires a version bump.
  NuGet caches by directory and simply checks if a directory with that version exists, regardless of whether the package has changed. It has implicit assumptions all up its stack that versions are immutable. Therefore each time you create a new package, you are forced to bump the versionpackage, you are forced to bupm the version
* UWP NuGet packages contain multiple slices specific for each platform.
  > These scripts allow you to filter to specific slices so you don't have to build all flavors


## Steps
1. Decide which slices you want. The default is a single slice `'Debug,X64'` but more are supported. 
1. Decide on the version scheme. Recommended is: `0.0.1-MyTest001` and keeping bumping the last 3 digigs
1. Build the bits in your repo for slice you selected
   1. open terminal for your enlistment (in vs dev prompt if you haven't setup your box otherwise)
   1. yarn
   1. yarn build
   1. pushd vnext
   1. NuGet restore Microsoft.ReactNative.sln
   1. msbuild Microsoft.ReactNative.sln /bl /m /p:Configuration=Debug /p:Platform=x64
   1. Repeat the preivous msbuild step for any other slices you might want to include
1. Publish the NuGet packages
   1. open terminal for your enlistment
   1. `vnext\Scripts\PublishNuGetPackagesLocally.cmd 0.0.1-MyTest001`
   > See below for a breakdown of the arguments
1. Link your repo for fast CLI testing
   1. open terminal for your enlsitment
   1. push vnext
   1. yarn link
      > if it fails with already being registered for another enlistment you can run `yarn unlink`
1. Generate a test project
   1. open terminal in a test folder
   1. `npx @react-native-community/cli init MyProj`
   1. cd `MyProj`
   1. Apply the react-native-windows template:
      1. `node z:\src\r3\packages\react-native-windows-init\bin.js --useDevMode --overwrite  --language cs --experimentalNuGetDependency --nuGetTestFeed c:\temp\RnWNuGetTesting\feed --nuGetTestVersion 0.0.1-MyTest001 `
         > See below for a breakdown of the arguments:
1. Deal with npm / nuget version mismatch
   1. The nuget package checks to see if there is a version match between the nuget package and the npm package.
      In testing these likely don't line up. You'll get the following error:
      ```
      error : Mismatch detected between npm package versions and nuget package version.
      error :     Npm:   '0.0.0-canary.148' - Z:\Temp\tst2\node_modules\react-native-windows\package.json
      error :     NuGet: '0.0.1-MyTest010' - Z:\Temp\tst2\windows\tst2\tsts2.csproj
      error : To update the nuget version, please see https://microsoft.github.io/react-native-windows/docs/nuget-update for instructions
      ```
      
      You can disable the check by setting the environment variable:

      `set ReactNativeWindowsAllowNugetNpmMismatch=true`
1. Do your testing

## Changes:
* Changes to the binaries in the NuGet package
  1. Rerun the builds for the slices you use
  1. Rerun publish NuGet script bumping the version number by one
  1. Reapply the windows template with the new version number
  1. Do your tests
* Change to the template generation
  1. yarn build
  1. Reapply the windows template
  1. Do your tests

## Scripts
### PublishNugetPackagesLocally
This script takes more options for more customization: `<version> [<targetDir>] [<slices>] [<baseConfiguration>] [<basePlatform>]`.
      
Let's break down all arguments:
* `targetDir`: Where the packages and feed should be placed. Default is `c:\temp\RnWNugetTesting`
* `slices`: This is the set of slices to produce in powershell array syntax. The default is: `@('x64.Debug')`. An example of more slices would be: `@('x64.Debug', 'X86.Release', 'ARM64.Release')`
* `baseConfiguration`: The slice that is used for the non configuration specific build outputs. Default is: `Debug`
* `basePlatform`: The slice that is used for the non platform specific build outputs. Default is `x64`

### react-native-windows-init ... cli.js
This script has many options, but let's break down the ones from the sample:
* `--version 0.0.0 --useDevMode`: The version doesn't matter when using dev mode, which means that the npm package is used that is registred as the dev package using `yarn link` per instructions above. This saves copying all the output files to your package directory, to your yarn cache. It is also a lot faster and since it is a link, you can make changes to your enlistment i.e. to `vnext\StyleSheets` and you don't have to reinstall between testing
* `--overwrite`: This just overwites files that already exist instead of prompting. This is very usefull when running the script multiple times to test the templates or to code that emits the template.
* `--language cs`: this is one of the public flags to generate a cs project instead of a cpp project. 
* `--experimentalNuGetDependency`: This is the critical one to let the template emit referneces to NuGet package rather than source packages. When we make it the default this will likely be renamed back to source for those that need a tight loop between test projects from template and the product code for developers working 'on' react-native-windows. If it proves that the sample and test apps we have in the repo satisfy this need, it can be removed and the tempaltes can be cleaned up by removing a lot of the conditionals bewteen the two.
* `--nuGetTestFeed c:\temp\RnWNugetTesting\feed`: This flag adds an extra feed to the nuget.config so that for local testing you can use a different feed. This is the default location that is pushed to by the `PublishNugetPackagesLocally.cmd` script.
* `--nuGetTestVersion 0.0.1-MyTest001`: By default the NuGet version matches the react-native version. For testing this can be cumbersome. Therefore this flag allows you to specify the version number for the NuGet packages.

---

### Testing (`docs/testing.md`)

# Testing ReactNative for Windows

When contributing to this project, unit and integration tests should be run to help prevent new bugs and regressions.

## Windows Desktop
Tests should be run with a VSTest-compatible client
(i.e. [VSTest.Console.exe](https://docs.microsoft.com/en-us/visualstudio/test/vstest-console-options?view=vs-2022),
[Visual Studio Test task](https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/test/vstest?view=azure-devops)).
This project includes convenience scripts to set up and run the test artifacts.

### Unit Tests
*Implemented in the React.Windows.Desktop.UnitTests project.*
Isolated, self-contained tests covering concrete implementations against mock dependencies and data.
```powershell
& Scripts\UnitTests.ps1
```

### Integration Tests
*Implemented in the React.Windows.Desktop.IntegrationTests project.*
Higher-level workflows interacting with real external dependencies (i.e. file system, networking servers).
These tests can run on the local development host.
```powershell
# Starts test services and runs tests.
& Scripts\IntegrationTests.ps1
```

### E2E Tests
*Implemented in packages/e2e-test-app*
<BR/>Please follow [Author and Run E2E Test for React Native Windows](e2e-testing.md) for E2E Tests

---

### Tracing (`docs/tracing.md`)

# Event Tracing in ReactNative for Windows

React native for Windows implements an event provider using [Event Tracing for Windows (ETW)](https://docs.microsoft.com/en-us/windows/win32/etw/event-tracing-portal) framework, to enable instrumenting and analyzing performance critical source code. Events generated by an ETW provider can be observed and analyzed using tools available through [Windows Performance Toolkit (WPT)](https://docs.microsoft.com/en-us/windows-hardware/test/wpt/).

Currently, we have implemented the [Systrace APIs](https://stuff.mit.edu/afs/sipb/project/android/docs/tools/help/systrace.html) on Windows to generate ETW events. Systrace APIs are used to instrument the core React Native source code. In future, we will instrument more of the React Native Windows source code with ETW events.

Tracing sessions can be managed as described below,

## Start a tracing session

1. Trace only events generated by React Native For Windows providers,

```powershell
& .\vnext\Scripts\Tracing\Start-Tracing.ps1
```

2. Trace events generated by React Native For Windows as well as the general system providers,

```powershell
& .\vnext\Scripts\Tracing\Start-Tracing.ps1 -IncludeGeneralTrace=$True
```

## Stop a tracing session and anayze the traces

1. Stop the session and start anaylizing the traces,

```powershell
& .\vnext\Scripts\Tracing\Stop-Tracing.ps1
```

2. Stop the session only,

```powershell
& .\vnext\Scripts\Tracing\Stop-Tracing.ps1 -NoAnalysis=$True
```

---

### Vnext External Fmt Doc ChangeLog Old (`vnext/external/fmt/doc/ChangeLog-old.md`)

# 7.1.3 - 2020-11-24

- Fixed handling of buffer boundaries in `format_to_n`
  (https://github.com/fmtlib/fmt/issues/1996,
  https://github.com/fmtlib/fmt/issues/2029).
- Fixed linkage errors when linking with a shared library
  (https://github.com/fmtlib/fmt/issues/2011).
- Reintroduced ostream support to range formatters
  (https://github.com/fmtlib/fmt/issues/2014).
- Worked around an issue with mixing std versions in gcc
  (https://github.com/fmtlib/fmt/issues/2017).

# 7.1.2 - 2020-11-04

- Fixed floating point formatting with large precision
  (https://github.com/fmtlib/fmt/issues/1976).

# 7.1.1 - 2020-11-01

- Fixed ABI compatibility with 7.0.x
  (https://github.com/fmtlib/fmt/issues/1961).
- Added the `FMT_ARM_ABI_COMPATIBILITY` macro to work around ABI
  incompatibility between GCC and Clang on ARM
  (https://github.com/fmtlib/fmt/issues/1919).
- Worked around a SFINAE bug in GCC 8
  (https://github.com/fmtlib/fmt/issues/1957).
- Fixed linkage errors when building with GCC\'s LTO
  (https://github.com/fmtlib/fmt/issues/1955).
- Fixed a compilation error when building without `__builtin_clz` or
  equivalent (https://github.com/fmtlib/fmt/pull/1968).
  Thanks @tohammer.
- Fixed a sign conversion warning
  (https://github.com/fmtlib/fmt/pull/1964). Thanks @OptoCloud.

# 7.1.0 - 2020-10-25

- Switched from
  [Grisu3](https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf)
  to [Dragonbox](https://github.com/jk-jeon/dragonbox) for the default
  floating-point formatting which gives the shortest decimal
  representation with round-trip guarantee and correct rounding
  (https://github.com/fmtlib/fmt/pull/1882,
  https://github.com/fmtlib/fmt/pull/1887,
  https://github.com/fmtlib/fmt/pull/1894). This makes {fmt}
  up to 20-30x faster than common implementations of
  `std::ostringstream` and `sprintf` on
  [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) and
  faster than double-conversion and Ryū:

  

  It is possible to get even better performance at the cost of larger
  binary size by compiling with the `FMT_USE_FULL_CACHE_DRAGONBOX`
  macro set to 1.

  Thanks @jk-jeon.

- Added an experimental unsynchronized file output API which, together
  with [format string
  compilation](https://fmt.dev/latest/api.html#compile-api), can give
  [5-9 times speed up compared to
  fprintf](https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html)
  on common platforms ([godbolt](https://godbolt.org/z/nsTcG8)):

  ```c++
  #include <fmt/os.h>

  int main() {
    auto f = fmt::output_file("guide");
    f.print("The answer is {}.", 42);
  }
  ```

- Added a formatter for `std::chrono::time_point<system_clock>`
  (https://github.com/fmtlib/fmt/issues/1819,
  https://github.com/fmtlib/fmt/pull/1837). For example
  ([godbolt](https://godbolt.org/z/c4M6fh)):

  ```c++
  #include <fmt/chrono.h>

  int main() {
    auto now = std::chrono::system_clock::now();
    fmt::print("The time is {:%H:%M:%S}.\n", now);
  }
  ```

  Thanks @adamburgess.

- Added support for ranges with non-const `begin`/`end` to `fmt::join`
  (https://github.com/fmtlib/fmt/issues/1784,
  https://github.com/fmtlib/fmt/pull/1786). For example
  ([godbolt](https://godbolt.org/z/jP63Tv)):

  ```c++
  #include <fmt/ranges.h>
  #include <range/v3/view/filter.hpp>

  int main() {
    using std::literals::string_literals::operator""s;
    auto strs = std::array{"a"s, "bb"s, "ccc"s};
    auto range = strs | ranges::views::filter(
      [] (const std::string &x) { return x.size() != 2; }
    );
    fmt::print("{}\n", fmt::join(range, ""));
  }
  ```

  prints \"accc\".

  Thanks @tonyelewis.

- Added a `memory_buffer::append` overload that takes a range
  (https://github.com/fmtlib/fmt/pull/1806). Thanks @BRevzin.

- Improved handling of single code units in `FMT_COMPILE`. For
  example:

  ```c++
  #include <fmt/compile.h>

  char* f(char* buf) {
    return fmt::format_to(buf, FMT_COMPILE("x{}"), 42);
  }
  ```

  compiles to just ([godbolt](https://godbolt.org/z/5vncz3)):

  ```asm
  _Z1fPc:
    movb $120, (%rdi)
    xorl %edx, %edx
    cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip)
    movl $3, %eax
    seta %dl
    subl %edx, %eax
    movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx
    cltq
    addq %rdi, %rax
    movw %dx, -2(%rax)
    ret
  ```

  Here a single `mov` instruction writes `'x'` (`$120`) to the output
  buffer.

- Added dynamic width support to format string compilation
  (https://github.com/fmtlib/fmt/issues/1809).

- Improved error reporting for unformattable types: now you\'ll get
  the type name directly in the error message instead of the note:

  ```c++
  #include <fmt/core.h>

  struct how_about_no {};

  int main() {
    fmt::print("{}", how_about_no());
  }
  ```

  Error ([godbolt](https://godbolt.org/z/GoxM4e)):

  `fmt/core.h:1438:3: error: static_assert failed due to requirement 'fmt::v7::formattable<how_about_no>()' "Cannot format an argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#udt" ...`

- Added the
  [make_args_checked](https://fmt.dev/7.1.0/api.html#argument-lists)
  function template that allows you to write formatting functions with
  compile-time format string checks and avoid binary code bloat
  ([godbolt](https://godbolt.org/z/PEf9qr)):

  ```c++
  void vlog(const char* file, int line, fmt::string_view format,
            fmt::format_args args) {
    fmt::print("{}: {}: ", file, line);
    fmt::vprint(format, args);
  }

  template <typename S, typename... Args>
  void log(const char* file, int line, const S& format, Args&&... args) {
    vlog(file, line, format,
        fmt::make_args_checked<Args...>(format, args...));
  }

  #define MY_LOG(format, ...) \
    log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__)

  MY_LOG("invalid squishiness: {}", 42);
  ```

- Replaced `snprintf` fallback with a faster internal IEEE 754 `float`
  and `double` formatter for arbitrary precision. For example
  ([godbolt](https://godbolt.org/z/dPhWvj)):

  ```c++
  #include <fmt/core.h>

  int main() {
    fmt::print("{:.500}\n", 4.9406564584124654E-324);
  }
  ```

  prints

  `4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324`.

- Made `format_to_n` and `formatted_size` part of the [core
  API](https://fmt.dev/latest/api.html#core-api)
  ([godbolt](https://godbolt.org/z/sPjY1K)):

  ```c++
  #include <fmt/core.h>

  int main() {
    char buffer[10];
    auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42);
  }
  ```

- Added `fmt::format_to_n` overload with format string compilation
  (https://github.com/fmtlib/fmt/issues/1764,
  https://github.com/fmtlib/fmt/pull/1767,
  https://github.com/fmtlib/fmt/pull/1869). For example
  ([godbolt](https://godbolt.org/z/93h86q)):

  ```c++
  #include <fmt/compile.h>

  int main() {
    char buffer[8];
    fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42);
  }
  ```

  Thanks @Kurkin and @alexezeder.

- Added `fmt::format_to` overload that take `text_style`
  (https://github.com/fmtlib/fmt/issues/1593,
  https://github.com/fmtlib/fmt/issues/1842,
  https://github.com/fmtlib/fmt/pull/1843). For example
  ([godbolt](https://godbolt.org/z/91153r)):

  ```c++
  #include <fmt/color.h>

  int main() {
    std::string out;
    fmt::format_to(std::back_inserter(out),
                   fmt::emphasis::bold | fg(fmt::color::red),
                   "The answer is {}.", 42);
  }
  ```

  Thanks @Naios.

- Made the `'#'` specifier emit trailing zeros in addition to the
  decimal point (https://github.com/fmtlib/fmt/issues/1797).
  For example ([godbolt](https://godbolt.org/z/bhdcW9)):

  ```c++
  #include <fmt/core.h>

  int main() {
    fmt::print("{:#.2g}", 0.5);
  }
  ```

  prints `0.50`.

- Changed the default floating point format to not include `.0` for
  consistency with `std::format` and `std::to_chars`
  (https://github.com/fmtlib/fmt/issues/1893,
  https://github.com/fmtlib/fmt/issues/1943). It is possible
  to get the decimal point and trailing zero with the `#` specifier.

- Fixed an issue with floating-point formatting that could result in
  addition of a non-significant trailing zero in rare cases e.g.
  `1.00e-34` instead of `1.0e-34`
  (https://github.com/fmtlib/fmt/issues/1873,
  https://github.com/fmtlib/fmt/issues/1917).

- Made `fmt::to_string` fallback on `ostream` insertion operator if
  the `formatter` specialization is not provided
  (https://github.com/fmtlib/fmt/issues/1815,
  https://github.com/fmtlib/fmt/pull/1829). Thanks @alexezeder.

- Added support for the append mode to the experimental file API and
  improved `fcntl.h` detection.
  (https://github.com/fmtlib/fmt/pull/1847,
  https://github.com/fmtlib/fmt/pull/1848). Thanks @t-wiser.

- Fixed handling of types that have both an implicit conversion
  operator and an overloaded `ostream` insertion operator
  (https://github.com/fmtlib/fmt/issues/1766).

- Fixed a slicing issue in an internal iterator type
  (https://github.com/fmtlib/fmt/pull/1822). Thanks @BRevzin.

- Fixed an issue in locale-specific integer formatting
  (https://github.com/fmtlib/fmt/issues/1927).

- Fixed handling of exotic code unit types
  (https://github.com/fmtlib/fmt/issues/1870,
  https://github.com/fmtlib/fmt/issues/1932).

- Improved `FMT_ALWAYS_INLINE`
  (https://github.com/fmtlib/fmt/pull/1878). Thanks @jk-jeon.

- Removed dependency on `windows.h`
  (https://github.com/fmtlib/fmt/pull/1900). Thanks @bernd5.

- Optimized counting of decimal digits on MSVC
  (https://github.com/fmtlib/fmt/pull/1890). Thanks @mwinterb.

- Improved documentation
  (https://github.com/fmtlib/fmt/issues/1772,
  https://github.com/fmtlib/fmt/pull/1775,
  https://github.com/fmtlib/fmt/pull/1792,
  https://github.com/fmtlib/fmt/pull/1838,
  https://github.com/fmtlib/fmt/pull/1888,
  https://github.com/fmtlib/fmt/pull/1918,
  https://github.com/fmtlib/fmt/pull/1939).
  Thanks @leolchat, @pepsiman, @Klaim, @ravijanjam, @francesco-st and @udnaan.

- Added the `FMT_REDUCE_INT_INSTANTIATIONS` CMake option that reduces
  the binary code size at the cost of some integer formatting
  performance. This can be useful for extremely memory-constrained
  embedded systems
  (https://github.com/fmtlib/fmt/issues/1778,
  https://github.com/fmtlib/fmt/pull/1781). Thanks @kammce.

- Added the `FMT_USE_INLINE_NAMESPACES` macro to control usage of
  inline namespaces
  (https://github.com/fmtlib/fmt/pull/1945). Thanks @darklukee.

- Improved build configuration
  (https://github.com/fmtlib/fmt/pull/1760,
  https://github.com/fmtlib/fmt/pull/1770,
  https://github.com/fmtlib/fmt/issues/1779,
  https://github.com/fmtlib/fmt/pull/1783,
  https://github.com/fmtlib/fmt/pull/1823).
  Thanks @dvetutnev, @xvitaly, @tambry, @medithe and @martinwuehrer.

- Fixed various warnings and compilation issues
  (https://github.com/fmtlib/fmt/pull/1790,
  https://github.com/fmtlib/fmt/pull/1802,
  https://github.com/fmtlib/fmt/pull/1808,
  https://github.com/fmtlib/fmt/issues/1810,
  https://github.com/fmtlib/fmt/issues/1811,
  https://github.com/fmtlib/fmt/pull/1812,
  https://github.com/fmtlib/fmt/pull/1814,
  https://github.com/fmtlib/fmt/pull/1816,
  https://github.com/fmtlib/fmt/pull/1817,
  https://github.com/fmtlib/fmt/pull/1818,
  https://github.com/fmtlib/fmt/issues/1825,
  https://github.com/fmtlib/fmt/pull/1836,
  https://github.com/fmtlib/fmt/pull/1855,
  https://github.com/fmtlib/fmt/pull/1856,
  https://github.com/fmtlib/fmt/pull/1860,
  https://github.com/fmtlib/fmt/pull/1877,
  https://github.com/fmtlib/fmt/pull/1879,
  https://github.com/fmtlib/fmt/pull/1880,
  https://github.com/fmtlib/fmt/issues/1896,
  https://github.com/fmtlib/fmt/pull/1897,
  https://github.com/fmtlib/fmt/pull/1898,
  https://github.com/fmtlib/fmt/issues/1904,
  https://github.com/fmtlib/fmt/pull/1908,
  https://github.com/fmtlib/fmt/issues/1911,
  https://github.com/fmtlib/fmt/issues/1912,
  https://github.com/fmtlib/fmt/issues/1928,
  https://github.com/fmtlib/fmt/pull/1929,
  https://github.com/fmtlib/fmt/issues/1935,
  https://github.com/fmtlib/fmt/pull/1937,
  https://github.com/fmtlib/fmt/pull/1942,
  https://github.com/fmtlib/fmt/issues/1949).
  Thanks @TheQwertiest, @medithe, @martinwuehrer, @n16h7hunt3r, @Othereum,
  @gsjaardema, @AlexanderLanin, @gcerretani, @chronoxor, @noizefloor,
  @akohlmey, @jk-jeon, @rimathia, @rglarix, @moiwi, @heckad, @MarcDirven.
  @BartSiwek and @darklukee.

# 7.0.3 - 2020-08-06

- Worked around broken `numeric_limits` for 128-bit integers
  (https://github.com/fmtlib/fmt/issues/1787).
- Added error reporting on missing named arguments
  (https://github.com/fmtlib/fmt/issues/1796).
- Stopped using 128-bit integers with clang-cl
  (https://github.com/fmtlib/fmt/pull/1800). Thanks @Kingcom.
- Fixed issues in locale-specific integer formatting
  (https://github.com/fmtlib/fmt/issues/1782,
  https://github.com/fmtlib/fmt/issues/1801).

# 7.0.2 - 2020-07-29

- Worked around broken `numeric_limits` for 128-bit integers
  (https://github.com/fmtlib/fmt/issues/1725).
- Fixed compatibility with CMake 3.4
  (https://github.com/fmtlib/fmt/issues/1779).
- Fixed handling of digit separators in locale-specific formatting
  (https://github.com/fmtlib/fmt/issues/1782).

# 7.0.1 - 2020-07-07

- Updated the inline version namespace name.
- Worked around a gcc bug in mangling of alias templates
  (https://github.com/fmtlib/fmt/issues/1753).
- Fixed a linkage error on Windows
  (https://github.com/fmtlib/fmt/issues/1757). Thanks @Kurkin.
- Fixed minor issues with the documentation.

# 7.0.0 - 2020-07-05

- Reduced the library size. For example, on macOS a stripped test
  binary statically linked with {fmt} [shrank from \~368k to less than
  100k](http://www.zverovich.net/2020/05/21/reducing-library-size.html).

- Added a simpler and more efficient [format string compilation
  API](https://fmt.dev/7.0.0/api.html#compile-api):

  ```c++
  #include <fmt/compile.h>

  // Converts 42 into std::string using the most efficient method and no
  // runtime format string processing.
  std::string s = fmt::format(FMT_COMPILE("{}"), 42);
  ```

  The old `fmt::compile` API is now deprecated.

- Optimized integer formatting: `format_to` with format string
  compilation and a stack-allocated buffer is now [faster than
  to_chars on both libc++ and
  libstdc++](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html).

- Optimized handling of small format strings. For example,

  ```c++
  fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5)
  ```

  is now \~40% faster
  (https://github.com/fmtlib/fmt/issues/1685).

- Applied extern templates to improve compile times when using the
  core API and `fmt/format.h`
  (https://github.com/fmtlib/fmt/issues/1452). For example,
  on macOS with clang the compile time of a test translation unit
  dropped from 2.3s to 0.3s with `-O2` and from 0.6s to 0.3s with the
  default settings (`-O0`).

  Before (`-O2`):

      % time c++ -c test.cc -I include -std=c++17 -O2
      c++ -c test.cc -I include -std=c++17 -O2  2.22s user 0.08s system 99% cpu 2.311 total

  After (`-O2`):

      % time c++ -c test.cc -I include -std=c++17 -O2
      c++ -c test.cc -I include -std=c++17 -O2  0.26s user 0.04s system 98% cpu 0.303 total

  Before (default):

      % time c++ -c test.cc -I include -std=c++17
      c++ -c test.cc -I include -std=c++17  0.53s user 0.06s system 98% cpu 0.601 total

  After (default):

      % time c++ -c test.cc -I include -std=c++17
      c++ -c test.cc -I include -std=c++17  0.24s user 0.06s system 98% cpu 0.301 total

  It is still recommended to use `fmt/core.h` instead of
  `fmt/format.h` but the compile time difference is now smaller.
  Thanks @alex3d for the suggestion.

- Named arguments are now stored on stack (no dynamic memory
  allocations) and the compiled code is more compact and efficient.
  For example

  ```c++
  #include <fmt/core.h>

  int main() {
    fmt::print("The answer is {answer}\n", fmt::arg("answer", 42));
  }
  ```

  compiles to just ([godbolt](https://godbolt.org/z/NcfEp_))

  ```asm
  .LC0:
          .string "answer"
  .LC1:
          .string "The answer is {answer}\n"
  main:
          sub     rsp, 56
          mov     edi, OFFSET FLAT:.LC1
          mov     esi, 23
          movabs  rdx, 4611686018427387905
          lea     rax, [rsp+32]
          lea     rcx, [rsp+16]
          mov     QWORD PTR [rsp+8], 1
          mov     QWORD PTR [rsp], rax
          mov     DWORD PTR [rsp+16], 42
          mov     QWORD PTR [rsp+32], OFFSET FLAT:.LC0
          mov     DWORD PTR [rsp+40], 0
          call    fmt::v6::vprint(fmt::v6::basic_string_view<char>,
                                  fmt::v6::format_args)
          xor     eax, eax
          add     rsp, 56
          ret

      .L.str.1:
              .asciz  "answer"
  ```

- Implemented compile-time checks for dynamic width and precision
  (https://github.com/fmtlib/fmt/issues/1614):

  ```c++
  #include <fmt/format.h>

  int main() {
    fmt::print(FMT_STRING("{0:{1}}"), 42);
  }
  ```

  now gives a compilation error because argument 1 doesn\'t exist:

      In file included from test.cc:1:
      include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be
      initialized by a constant expression
        FMT_CONSTEXPR_DECL bool invalid_format =
                                ^
      ...
      include/fmt/core.h:569:26: note: in call to
      '&checker(s, {}).context_->on_error(&"argument not found"[0])'
          if (id >= num_args_) on_error("argument not found");
                              ^

- Added sentinel support to `fmt::join`
  (https://github.com/fmtlib/fmt/pull/1689)

  ```c++
  struct zstring_sentinel {};
  bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; }
  bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; }

  struct zstring {
    const char* p;
    const char* begin() const { return p; }
    zstring_sentinel end() const { return {}; }
  };

  auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_"));
  // s == "h_e_l_l_o"
  ```

  Thanks @BRevzin.

- Added support for named arguments, `clear` and `reserve` to
  `dynamic_format_arg_store`
  (https://github.com/fmtlib/fmt/issues/1655,
  https://github.com/fmtlib/fmt/pull/1663,
  https://github.com/fmtlib/fmt/pull/1674,
  https://github.com/fmtlib/fmt/pull/1677). Thanks @vsolontsov-ll.

- Added support for the `'c'` format specifier to integral types for
  compatibility with `std::format`
  (https://github.com/fmtlib/fmt/issues/1652).

- Replaced the `'n'` format specifier with `'L'` for compatibility
  with `std::format`
  (https://github.com/fmtlib/fmt/issues/1624). The `'n'`
  specifier can be enabled via the `FMT_DEPRECATED_N_SPECIFIER` macro.

- The `'='` format specifier is now disabled by default for
  compatibility with `std::format`. It can be enabled via the
  `FMT_DEPRECATED_NUMERIC_ALIGN` macro.

- Removed the following deprecated APIs:

  -   `FMT_STRING_ALIAS` and `fmt` macros - replaced by `FMT_STRING`
  -   `fmt::basic_string_view::char_type` - replaced by
      `fmt::basic_string_view::value_type`
  -   `convert_to_int`
  -   `format_arg_store::types`
  -   `*parse_context` - replaced by `*format_parse_context`
  -   `FMT_DEPRECATED_INCLUDE_OS`
  -   `FMT_DEPRECATED_PERCENT` - incompatible with `std::format`
  -   `*writer` - replaced by compiled format API

- Renamed the `internal` namespace to `detail`
  (https://github.com/fmtlib/fmt/issues/1538). The former is
  still provided as an alias if the `FMT_USE_INTERNAL` macro is
  defined.

- Improved compatibility between `fmt::printf` with the standard specs
  (https://github.com/fmtlib/fmt/issues/1595,
  https://github.com/fmtlib/fmt/pull/1682,
  https://github.com/fmtlib/fmt/pull/1683,
  https://github.com/fmtlib/fmt/pull/1687,
  https://github.com/fmtlib/fmt/pull/1699). Thanks @rimathia.

- Fixed handling of `operator<<` overloads that use `copyfmt`
  (https://github.com/fmtlib/fmt/issues/1666).

- Added the `FMT_OS` CMake option to control inclusion of OS-specific
  APIs in the fmt target. This can be useful for embedded platforms
  (https://github.com/fmtlib/fmt/issues/1654,
  https://github.com/fmtlib/fmt/pull/1656). Thanks @kwesolowski.

- Replaced `FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION` with the
  `FMT_FUZZ` macro to prevent interfering with fuzzing of projects
  using {fmt} (https://github.com/fmtlib/fmt/pull/1650).
  Thanks @asraa.

- Fixed compatibility with emscripten
  (https://github.com/fmtlib/fmt/issues/1636,
  https://github.com/fmtlib/fmt/pull/1637). Thanks @ArthurSonzogni.

- Improved documentation
  (https://github.com/fmtlib/fmt/issues/704,
  https://github.com/fmtlib/fmt/pull/1643,
  https://github.com/fmtlib/fmt/pull/1660,
  https://github.com/fmtlib/fmt/pull/1681,
  https://github.com/fmtlib/fmt/pull/1691,
  https://github.com/fmtlib/fmt/pull/1706,
  https://github.com/fmtlib/fmt/pull/1714,
  https://github.com/fmtlib/fmt/pull/1721,
  https://github.com/fmtlib/fmt/pull/1739,
  https://github.com/fmtlib/fmt/pull/1740,
  https://github.com/fmtlib/fmt/pull/1741,
  https://github.com/fmtlib/fmt/pull/1751).
  Thanks @senior7515, @lsr0, @puetzk, @fpelliccioni, Alexey Kuzmenko, @jelly,
  @claremacrae, @jiapengwen, @gsjaardema and @alexey-milovidov.

- Implemented various build configuration fixes and improvements
  (https://github.com/fmtlib/fmt/pull/1603,
  https://github.com/fmtlib/fmt/pull/1657,
  https://github.com/fmtlib/fmt/pull/1702,
  https://github.com/fmtlib/fmt/pull/1728).
  Thanks @scramsby, @jtojnar, @orivej and @flagarde.

- Fixed various warnings and compilation issues
  (https://github.com/fmtlib/fmt/pull/1616,
  https://github.com/fmtlib/fmt/issues/1620,
  https://github.com/fmtlib/fmt/issues/1622,
  https://github.com/fmtlib/fmt/issues/1625,
  https://github.com/fmtlib/fmt/pull/1627,
  https://github.com/fmtlib/fmt/issues/1628,
  https://github.com/fmtlib/fmt/pull/1629,
  https://github.com/fmtlib/fmt/issues/1631,
  https://github.com/fmtlib/fmt/pull/1633,
  https://github.com/fmtlib/fmt/pull/1649,
  https://github.com/fmtlib/fmt/issues/1658,
  https://github.com/fmtlib/fmt/pull/1661,
  https://github.com/fmtlib/fmt/pull/1667,
  https://github.com/fmtlib/fmt/issues/1668,
  https://github.com/fmtlib/fmt/pull/1669,
  https://github.com/fmtlib/fmt/issues/1692,
  https://github.com/fmtlib/fmt/pull/1696,
  https://github.com/fmtlib/fmt/pull/1697,
  https://github.com/fmtlib/fmt/issues/1707,
  https://github.com/fmtlib/fmt/pull/1712,
  https://github.com/fmtlib/fmt/pull/1716,
  https://github.com/fmtlib/fmt/pull/1722,
  https://github.com/fmtlib/fmt/issues/1724,
  https://github.com/fmtlib/fmt/pull/1729,
  https://github.com/fmtlib/fmt/pull/1738,
  https://github.com/fmtlib/fmt/issues/1742,
  https://github.com/fmtlib/fmt/issues/1743,
  https://github.com/fmtlib/fmt/pull/1744,
  https://github.com/fmtlib/fmt/issues/1747,
  https://github.com/fmtlib/fmt/pull/1750).
  Thanks @gsjaardema, @gabime, @johnor, @Kurkin, @invexed, @peterbell10,
  @daixtrose, @petrutlucian94, @Neargye, @ambitslix, @gabime, @erthink,
  @tohammer and @0x8000-0000.

# 6.2.1 - 2020-05-09

- Fixed ostream support in `sprintf`
  (https://github.com/fmtlib/fmt/issues/1631).
- Fixed type detection when using implicit conversion to `string_view`
  and ostream `operator<<` inconsistently
  (https://github.com/fmtlib/fmt/issues/1662).

# 6.2.0 - 2020-04-05

- Improved error reporting when trying to format an object of a
  non-formattable type:

  ```c++
  fmt::format("{}", S());
  ```

  now gives:

      include/fmt/core.h:1015:5: error: static_assert failed due to requirement
      'formattable' "Cannot format argument. To make type T formattable provide a
      formatter<T> specialization:
      https://fmt.dev/latest/api.html#formatting-user-defined-types"
          static_assert(
          ^
      ...
      note: in instantiation of function template specialization
      'fmt::v6::format<char [3], S, char>' requested here
        fmt::format("{}", S());
             ^

  if `S` is not formattable.

- Reduced the library size by \~10%.

- Always print decimal point if `#` is specified
  (https://github.com/fmtlib/fmt/issues/1476,
  https://github.com/fmtlib/fmt/issues/1498):

  ```c++
  fmt::print("{:#.0f}", 42.0);
  ```

  now prints `42.`

- Implemented the `'L'` specifier for locale-specific numeric
  formatting to improve compatibility with `std::format`. The `'n'`
  specifier is now deprecated and will be removed in the next major
  release.

- Moved OS-specific APIs such as `windows_error` from `fmt/format.h`
  to `fmt/os.h`. You can define `FMT_DEPRECATED_INCLUDE_OS` to
  automatically include `fmt/os.h` from `fmt/format.h` for
  compatibility but this will be disabled in the next major release.

- Added precision overflow detection in floating-point formatting.

- Implemented detection of invalid use of `fmt::arg`.

- Used `type_identity` to block unnecessary template argument
  deduction. Thanks Tim Song.

- Improved UTF-8 handling
  (https://github.com/fmtlib/fmt/issues/1109):

  ```c++
  fmt::print("┌{0:─^{2}}┐\n"
             "│{1: ^{2}}│\n"
             "└{0:─^{2}}┘\n", "", "Прывітанне, свет!", 21);
  ```

  now prints:

      ┌─────────────────────┐
      │  Прывітанне, свет!  │
      └─────────────────────┘

  on systems that support Unicode.

- Added experimental dynamic argument storage
  (https://github.com/fmtlib/fmt/issues/1170,
  https://github.com/fmtlib/fmt/pull/1584):

  ```c++
  fmt::dynamic_format_arg_store<fmt::format_context> store;
  store.push_back("answer");
  store.push_back(42);
  fmt::vprint("The {} is {}.\n", store);
  ```

  prints:

      The answer is 42.

  Thanks @vsolontsov-ll.

- Made `fmt::join` accept `initializer_list`
  (https://github.com/fmtlib/fmt/pull/1591). Thanks @Rapotkinnik.

- Fixed handling of empty tuples
  (https://github.com/fmtlib/fmt/issues/1588).

- Fixed handling of output iterators in `format_to_n`
  (https://github.com/fmtlib/fmt/issues/1506).

- Fixed formatting of `std::chrono::duration` types to wide output
  (https://github.com/fmtlib/fmt/pull/1533). Thanks @zeffy.

- Added const `begin` and `end` overload to buffers
  (https://github.com/fmtlib/fmt/pull/1553). Thanks @dominicpoeschko.

- Added the ability to disable floating-point formatting via
  `FMT_USE_FLOAT`, `FMT_USE_DOUBLE` and `FMT_USE_LONG_DOUBLE` macros
  for extremely memory-constrained embedded system
  (https://github.com/fmtlib/fmt/pull/1590). Thanks @albaguirre.

- Made `FMT_STRING` work with `constexpr` `string_view`
  (https://github.com/fmtlib/fmt/pull/1589). Thanks @scramsby.

- Implemented a minor optimization in the format string parser
  (https://github.com/fmtlib/fmt/pull/1560). Thanks @IkarusDeveloper.

- Improved attribute detection
  (https://github.com/fmtlib/fmt/pull/1469,
  https://github.com/fmtlib/fmt/pull/1475,
  https://github.com/fmtlib/fmt/pull/1576).
  Thanks @federico-busato, @chronoxor and @refnum.

- Improved documentation
  (https://github.com/fmtlib/fmt/pull/1481,
  https://github.com/fmtlib/fmt/pull/1523).
  Thanks @JackBoosY and @imba-tjd.

- Fixed symbol visibility on Linux when compiling with
  `-fvisibility=hidden`
  (https://github.com/fmtlib/fmt/pull/1535). Thanks @milianw.

- Implemented various build configuration fixes and improvements
  (https://github.com/fmtlib/fmt/issues/1264,
  https://github.com/fmtlib/fmt/issues/1460,
  https://github.com/fmtlib/fmt/pull/1534,
  https://github.com/fmtlib/fmt/issues/1536,
  https://github.com/fmtlib/fmt/issues/1545,
  https://github.com/fmtlib/fmt/pull/1546,
  https://github.com/fmtlib/fmt/issues/1566,
  https://github.com/fmtlib/fmt/pull/1582,
  https://github.com/fmtlib/fmt/issues/1597,
  https://github.com/fmtlib/fmt/pull/1598).
  Thanks @ambitslix, @jwillikers and @stac47.

- Fixed various warnings and compilation issues
  (https://github.com/fmtlib/fmt/pull/1433,
  https://github.com/fmtlib/fmt/issues/1461,
  https://github.com/fmtlib/fmt/pull/1470,
  https://github.com/fmtlib/fmt/pull/1480,
  https://github.com/fmtlib/fmt/pull/1485,
  https://github.com/fmtlib/fmt/pull/1492,
  https://github.com/fmtlib/fmt/issues/1493,
  https://github.com/fmtlib/fmt/issues/1504,
  https://github.com/fmtlib/fmt/pull/1505,
  https://github.com/fmtlib/fmt/pull/1512,
  https://github.com/fmtlib/fmt/issues/1515,
  https://github.com/fmtlib/fmt/pull/1516,
  https://github.com/fmtlib/fmt/pull/1518,
  https://github.com/fmtlib/fmt/pull/1519,
  https://github.com/fmtlib/fmt/pull/1520,
  https://github.com/fmtlib/fmt/pull/1521,
  https://github.com/fmtlib/fmt/pull/1522,
  https://github.com/fmtlib/fmt/issues/1524,
  https://github.com/fmtlib/fmt/pull/1530,
  https://github.com/fmtlib/fmt/issues/1531,
  https://github.com/fmtlib/fmt/pull/1532,
  https://github.com/fmtlib/fmt/issues/1539,
  https://github.com/fmtlib/fmt/issues/1547,
  https://github.com/fmtlib/fmt/issues/1548,
  https://github.com/fmtlib/fmt/pull/1554,
  https://github.com/fmtlib/fmt/issues/1567,
  https://github.com/fmtlib/fmt/pull/1568,
  https://github.com/fmtlib/fmt/pull/1569,
  https://github.com/fmtlib/fmt/pull/1571,
  https://github.com/fmtlib/fmt/pull/1573,
  https://github.com/fmtlib/fmt/pull/1575,
  https://github.com/fmtlib/fmt/pull/1581,
  https://github.com/fmtlib/fmt/issues/1583,
  https://github.com/fmtlib/fmt/issues/1586,
  https://github.com/fmtlib/fmt/issues/1587,
  https://github.com/fmtlib/fmt/issues/1594,
  https://github.com/fmtlib/fmt/pull/1596,
  https://github.com/fmtlib/fmt/issues/1604,
  https://github.com/fmtlib/fmt/pull/1606,
  https://github.com/fmtlib/fmt/issues/1607,
  https://github.com/fmtlib/fmt/issues/1609).
  Thanks @marti4d, @iPherian, @parkertomatoes, @gsjaardema, @chronoxor,
  @DanielaE, @torsten48, @tohammer, @lefticus, @ryusakki, @adnsv, @fghzxm,
  @refnum, @pramodk, @Spirrwell and @scramsby.

# 6.1.2 - 2019-12-11

- Fixed ABI compatibility with `libfmt.so.6.0.0`
  (https://github.com/fmtlib/fmt/issues/1471).
- Fixed handling types convertible to `std::string_view`
  (https://github.com/fmtlib/fmt/pull/1451). Thanks @denizevrenci.
- Made CUDA test an opt-in enabled via the `FMT_CUDA_TEST` CMake
  option.
- Fixed sign conversion warnings
  (https://github.com/fmtlib/fmt/pull/1440). Thanks @0x8000-0000.

# 6.1.1 - 2019-12-04

- Fixed shared library build on Windows
  (https://github.com/fmtlib/fmt/pull/1443,
  https://github.com/fmtlib/fmt/issues/1445,
  https://github.com/fmtlib/fmt/pull/1446,
  https://github.com/fmtlib/fmt/issues/1450).
  Thanks @egorpugin and @bbolli.
- Added a missing decimal point in exponent notation with trailing
  zeros.
- Removed deprecated `format_arg_store::TYPES`.

# 6.1.0 - 2019-12-01

- {fmt} now formats IEEE 754 `float` and `double` using the shortest
  decimal representation with correct rounding by default:

  ```c++
  #include <cmath>
  #include <fmt/core.h>

  int main() {
    fmt::print("{}", M_PI);
  }
  ```

  prints `3.141592653589793`.

- Made the fast binary to decimal floating-point formatter the
  default, simplified it and improved performance. {fmt} is now 15
  times faster than libc++\'s `std::ostringstream`, 11 times faster
  than `printf` and 10% faster than double-conversion on
  [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark):

  | Function      | Time (ns) | Speedup |
  | ------------- | --------: | ------: |
  | ostringstream | 1,346.30  | 1.00x   |
  | ostrstream    | 1,195.74  | 1.13x   |
  | sprintf       | 995.08    | 1.35x   |
  | doubleconv    | 99.10     | 13.59x  |
  | fmt           | 88.34     | 15.24x  |

  

- {fmt} no longer converts `float` arguments to `double`. In
  particular this improves the default (shortest) representation of
  floats and makes `fmt::format` consistent with `std::format` specs
  (https://github.com/fmtlib/fmt/issues/1336,
  https://github.com/fmtlib/fmt/issues/1353,
  https://github.com/fmtlib/fmt/pull/1360,
  https://github.com/fmtlib/fmt/pull/1361):

  ```c++
  fmt::print("{}", 0.1f);
  ```

  prints `0.1` instead of `0.10000000149011612`.

  Thanks @orivej.

- Made floating-point formatting output consistent with
  `printf`/iostreams
  (https://github.com/fmtlib/fmt/issues/1376,
  https://github.com/fmtlib/fmt/issues/1417).

- Added support for 128-bit integers
  (https://github.com/fmtlib/fmt/pull/1287):

  ```c++
  fmt::print("{}", std::numeric_limits<__int128_t>::max());
  ```

  prints `170141183460469231731687303715884105727`.

  Thanks @denizevrenci.

- The overload of `print` that takes `text_style` is now atomic, i.e.
  the output from different threads doesn\'t interleave
  (https://github.com/fmtlib/fmt/pull/1351). Thanks @tankiJong.

- Made compile time in the header-only mode \~20% faster by reducing
  the number of template instantiations. `wchar_t` overload of
  `vprint` was moved from `fmt/core.h` to `fmt/format.h`.

- Added an overload of `fmt::join` that works with tuples
  (https://github.com/fmtlib/fmt/issues/1322,
  https://github.com/fmtlib/fmt/pull/1330):

  ```c++
  #include <tuple>
  #include <fmt/ranges.h>

  int main() {
    std::tuple<char, int, float> t{'a', 1, 2.0f};
    fmt::print("{}", t);
  }
  ```

  prints `('a', 1, 2.0)`.

  Thanks @jeremyong.

- Changed formatting of octal zero with prefix from \"00\" to \"0\":

  ```c++
  fmt::print("{:#o}", 0);
  ```

  prints `0`.

- The locale is now passed to ostream insertion (`<<`) operators
  (https://github.com/fmtlib/fmt/pull/1406):

  ```c++
  #include <fmt/locale.h>
  #include <fmt/ostream.h>

  struct S {
    double value;
  };

  std::ostream& operator<<(std::ostream& os, S s) {
    return os << s.value;
  }

  int main() {
    auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42});
    // s == "0,42"
  }
  ```

  Thanks @dlaugt.

- Locale-specific number formatting now uses grouping
  (https://github.com/fmtlib/fmt/issues/1393,
  https://github.com/fmtlib/fmt/pull/1394). Thanks @skrdaniel.

- Fixed handling of types with deleted implicit rvalue conversion to
  `const char**` (https://github.com/fmtlib/fmt/issues/1421):

  ```c++
  struct mystring {
    operator const char*() const&;
    operator const char*() &;
    operator const char*() const&& = delete;
    operator const char*() && = delete;
  };
  mystring str;
  fmt::print("{}", str); // now compiles
  ```

- Enums are now mapped to correct underlying types instead of `int`
  (https://github.com/fmtlib/fmt/pull/1286). Thanks @agmt.

- Enum classes are no longer implicitly converted to `int`
  (https://github.com/fmtlib/fmt/issues/1424).

- Added `basic_format_parse_context` for consistency with C++20
  `std::format` and deprecated `basic_parse_context`.

- Fixed handling of UTF-8 in precision
  (https://github.com/fmtlib/fmt/issues/1389,
  https://github.com/fmtlib/fmt/pull/1390). Thanks @tajtiattila.

- {fmt} can now be installed on Linux, macOS and Windows with
  [Conda](https://docs.conda.io/en/latest/) using its
  [conda-forge](https://conda-forge.org)
  [package](https://github.com/conda-forge/fmt-feedstock)
  (https://github.com/fmtlib/fmt/pull/1410):

      conda install -c conda-forge fmt

  Thanks @tdegeus.

- Added a CUDA test (https://github.com/fmtlib/fmt/pull/1285,
  https://github.com/fmtlib/fmt/pull/1317).
  Thanks @luncliff and @risa2000.

- Improved documentation
  (https://github.com/fmtlib/fmt/pull/1276,
  https://github.com/fmtlib/fmt/issues/1291,
  https://github.com/fmtlib/fmt/issues/1296,
  https://github.com/fmtlib/fmt/pull/1315,
  https://github.com/fmtlib/fmt/pull/1332,
  https://github.com/fmtlib/fmt/pull/1337,
  https://github.com/fmtlib/fmt/issues/1395
  https://github.com/fmtlib/fmt/pull/1418).
  Thanks @waywardmonkeys, @pauldreik and @jackoalan.

- Various code improvements
  (https://github.com/fmtlib/fmt/pull/1358,
  https://github.com/fmtlib/fmt/pull/1407).
  Thanks @orivej and @dpacbach.

- Fixed compile-time format string checks for user-defined types
  (https://github.com/fmtlib/fmt/issues/1292).

- Worked around a false positive in `unsigned-integer-overflow` sanitizer
  (https://github.com/fmtlib/fmt/issues/1377).

- Fixed various warnings and compilation issues
  (https://github.com/fmtlib/fmt/issues/1273,
  https://github.com/fmtlib/fmt/pull/1278,
  https://github.com/fmtlib/fmt/pull/1280,
  https://github.com/fmtlib/fmt/issues/1281,
  https://github.com/fmtlib/fmt/issues/1288,
  https://github.com/fmtlib/fmt/pull/1290,
  https://github.com/fmtlib/fmt/pull/1301,
  https://github.com/fmtlib/fmt/issues/1305,
  https://github.com/fmtlib/fmt/issues/1306,
  https://github.com/fmtlib/fmt/issues/1309,
  https://github.com/fmtlib/fmt/pull/1312,
  https://github.com/fmtlib/fmt/issues/1313,
  https://github.com/fmtlib/fmt/issues/1316,
  https://github.com/fmtlib/fmt/issues/1319,
  https://github.com/fmtlib/fmt/pull/1320,
  https://github.com/fmtlib/fmt/pull/1326,
  https://github.com/fmtlib/fmt/pull/1328,
  https://github.com/fmtlib/fmt/issues/1344,
  https://github.com/fmtlib/fmt/pull/1345,
  https://github.com/fmtlib/fmt/pull/1347,
  https://github.com/fmtlib/fmt/pull/1349,
  https://github.com/fmtlib/fmt/issues/1354,
  https://github.com/fmtlib/fmt/issues/1362,
  https://github.com/fmtlib/fmt/issues/1366,
  https://github.com/fmtlib/fmt/pull/1364,
  https://github.com/fmtlib/fmt/pull/1370,
  https://github.com/fmtlib/fmt/pull/1371,
  https://github.com/fmtlib/fmt/issues/1385,
  https://github.com/fmtlib/fmt/issues/1388,
  https://github.com/fmtlib/fmt/pull/1397,
  https://github.com/fmtlib/fmt/pull/1414,
  https://github.com/fmtlib/fmt/pull/1416,
  https://github.com/fmtlib/fmt/issues/1422
  https://github.com/fmtlib/fmt/pull/1427,
  https://github.com/fmtlib/fmt/issues/1431,
  https://github.com/fmtlib/fmt/pull/1433).
  Thanks @hhb, @gsjaardema, @gabime, @neheb, @vedranmiletic, @dkavolis,
  @mwinterb, @orivej, @denizevrenci, @leonklingele, @chronoxor, @kent-tri,
  @0x8000-0000 and @marti4d.

# 6.0.0 - 2019-08-26

- Switched to the [MIT license](
  https://github.com/fmtlib/fmt/blob/5a4b24613ba16cc689977c3b5bd8274a3ba1dd1f/LICENSE.rst)
  with an optional exception that allows distributing binary code
  without attribution.

- Floating-point formatting is now locale-independent by default:

  ```c++
  #include <locale>
  #include <fmt/core.h>

  int main() {
    std::locale::global(std::locale("ru_RU.UTF-8"));
    fmt::print("value = {}", 4.2);
  }
  ```

  prints \"value = 4.2\" regardless of the locale.

  For locale-specific formatting use the `n` specifier:

  ```c++
  std::locale::global(std::locale("ru_RU.UTF-8"));
  fmt::print("value = {:n}", 4.2);
  ```

  prints \"value = 4,2\".

- Added an experimental Grisu floating-point formatting algorithm
  implementation (disabled by default). To enable it compile with the
  `FMT_USE_GRISU` macro defined to 1:

  ```c++
  #define FMT_USE_GRISU 1
  #include <fmt/format.h>

  auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu
  ```

  With Grisu enabled, {fmt} is 13x faster than `std::ostringstream`
  (libc++) and 10x faster than `sprintf` on
  [dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark) ([full
  results](https://fmt.dev/unknown_mac64_clang10.0.html)):

  

- Separated formatting and parsing contexts for consistency with
  [C++20 std::format](http://eel.is/c++draft/format), removing the
  undocumented `basic_format_context::parse_context()` function.

- Added [oss-fuzz](https://github.com/google/oss-fuzz) support
  (https://github.com/fmtlib/fmt/pull/1199). Thanks @pauldreik.

- `formatter` specializations now always take precedence over
  `operator<<` (https://github.com/fmtlib/fmt/issues/952):

  ```c++
  #include <iostream>
  #include <fmt/ostream.h>

  struct S {};

  std::ostream& operator<<(std::ostream& os, S) {
    return os << 1;
  }

  template <>
  struct fmt::formatter<S> : fmt::formatter<int> {
    auto format(S, format_context& ctx) {
      return formatter<int>::format(2, ctx);
    }
  };

  int main() {
    std::cout << S() << "\n"; // prints 1 using operator<<
    fmt::print("{}\n", S());  // prints 2 using formatter
  }
  ```

- Introduced the experimental `fmt::compile` function that does format
  string compilation
  (https://github.com/fmtlib/fmt/issues/618,
  https://github.com/fmtlib/fmt/issues/1169,
  https://github.com/fmtlib/fmt/pull/1171):

  ```c++
  #include <fmt/compile.h>

  auto f = fmt::compile<int>("{}");
  std::string s = fmt::format(f, 42); // can be called multiple times to
                                      // format different values
  // s == "42"
  ```

  It moves the cost of parsing a format string outside of the format
  function which can be beneficial when identically formatting many
  objects of the same types. Thanks @stryku.

- Added experimental `%` format specifier that formats floating-point
  values as percentages
  (https://github.com/fmtlib/fmt/pull/1060,
  https://github.com/fmtlib/fmt/pull/1069,
  https://github.com/fmtlib/fmt/pull/1071):

  ```c++
  auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%"
  ```

  Thanks @gawain-bolton.

- Implemented precision for floating-point durations
  (https://github.com/fmtlib/fmt/issues/1004,
  https://github.com/fmtlib/fmt/pull/1012):

  ```c++
  auto s = fmt::format("{:.1}", std::chrono::duration<double>(1.234));
  // s == 1.2s
  ```

  Thanks @DanielaE.

- Implemented `chrono` format specifiers `%Q` and `%q` that give the
  value and the unit respectively
  (https://github.com/fmtlib/fmt/pull/1019):

  ```c++
  auto value = fmt::format("{:%Q}", 42s); // value == "42"
  auto unit  = fmt::format("{:%q}", 42s); // unit == "s"
  ```

  Thanks @DanielaE.

- Fixed handling of dynamic width in chrono formatter:

  ```c++
  auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12);
  //                        ^ width argument index                     ^ width
  // s == "03:25:45    "
  ```

  Thanks Howard Hinnant.

- Removed deprecated `fmt/time.h`. Use `fmt/chrono.h` instead.

- Added `fmt::format` and `fmt::vformat` overloads that take
  `text_style` (https://github.com/fmtlib/fmt/issues/993,
  https://github.com/fmtlib/fmt/pull/994):

  ```c++
  #include <fmt/color.h>

  std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
                                    "The answer is {}.", 42);
  ```

  Thanks @Naios.

- Removed the deprecated color API (`print_colored`). Use the new API,
  namely `print` overloads that take `text_style` instead.

- Made `std::unique_ptr` and `std::shared_ptr` formattable as pointers
  via `fmt::ptr` (https://github.com/fmtlib/fmt/pull/1121):

  ```c++
  std::unique_ptr<int> p = ...;
  fmt::print("{}", fmt::ptr(p)); // prints p as a pointer
  ```

  Thanks @sighingnow.

- Made `print` and `vprint` report I/O errors
  (https://github.com/fmtlib/fmt/issues/1098,
  https://github.com/fmtlib/fmt/pull/1099). Thanks @BillyDonahue.

- Marked deprecated APIs with the `[[deprecated]]` attribute and
  removed internal uses of deprecated APIs
  (https://github.com/fmtlib/fmt/pull/1022). Thanks @eliaskosunen.

- Modernized the codebase using more C++11 features and removing
  workarounds. Most importantly, `buffer_context` is now an alias
  template, so use `buffer_context<T>` instead of
  `buffer_context<T>::type`. These features require GCC 4.8 or later.

- `formatter` specializations now always take precedence over implicit
  conversions to `int` and the undocumented `convert_to_int` trait is
  now deprecated.

- Moved the undocumented `basic_writer`, `writer`, and `wwriter` types
  to the `internal` namespace.

- Removed deprecated `basic_format_context::begin()`. Use `out()`
  instead.

- Disallowed passing the result of `join` as an lvalue to prevent
  misuse.

- Refactored the undocumented structs that represent parsed format
  specifiers to simplify the API and allow multibyte fill.

- Moved SFINAE to template parameters to reduce symbol sizes.

- Switched to `fputws` for writing wide strings so that it\'s no
  longer required to call `_setmode` on Windows
  (https://github.com/fmtlib/fmt/issues/1229,
  https://github.com/fmtlib/fmt/pull/1243). Thanks @jackoalan.

- Improved literal-based API
  (https://github.com/fmtlib/fmt/pull/1254). Thanks @sylveon.

- Added support for exotic platforms without `uintptr_t` such as IBM i
  (AS/400) which has 128-bit pointers and only 64-bit integers
  (https://github.com/fmtlib/fmt/issues/1059).

- Added [Sublime Text syntax highlighting config](
  https://github.com/fmtlib/fmt/blob/master/support/C%2B%2B.sublime-syntax)
  (https://github.com/fmtlib/fmt/issues/1037). Thanks @Kronuz.

- Added the `FMT_ENFORCE_COMPILE_STRING` macro to enforce the use of
  compile-time format strings
  (https://github.com/fmtlib/fmt/pull/1231). Thanks @jackoalan.

- Stopped setting `CMAKE_BUILD_TYPE` if {fmt} is a subproject
  (https://github.com/fmtlib/fmt/issues/1081).

- Various build improvements
  (https://github.com/fmtlib/fmt/pull/1039,
  https://github.com/fmtlib/fmt/pull/1078,
  https://github.com/fmtlib/fmt/pull/1091,
  https://github.com/fmtlib/fmt/pull/1103,
  https://github.com/fmtlib/fmt/pull/1177).
  Thanks @luncliff, @jasonszang, @olafhering, @Lecetem and @pauldreik.

- Improved documentation
  (https://github.com/fmtlib/fmt/issues/1049,
  https://github.com/fmtlib/fmt/pull/1051,
  https://github.com/fmtlib/fmt/pull/1083,
  https://github.com/fmtlib/fmt/pull/1113,
  https://github.com/fmtlib/fmt/pull/1114,
  https://github.com/fmtlib/fmt/issues/1146,
  https://github.com/fmtlib/fmt/issues/1180,
  https://github.com/fmtlib/fmt/pull/1250,
  https://github.com/fmtlib/fmt/pull/1252,
  https://github.com/fmtlib/fmt/pull/1265).
  Thanks @mikelui, @foonathan, @BillyDonahue, @jwakely, @kaisbe and
  @sdebionne.

- Fixed ambiguous formatter specialization in `fmt/ranges.h`
  (https://github.com/fmtlib/fmt/issues/1123).

- Fixed formatting of a non-empty `std::filesystem::path` which is an
  infinitely deep range of its components
  (https://github.com/fmtlib/fmt/issues/1268).

- Fixed handling of general output iterators when formatting
  characters (https://github.com/fmtlib/fmt/issues/1056,
  https://github.com/fmtlib/fmt/pull/1058). Thanks @abolz.

- Fixed handling of output iterators in `formatter` specialization for
  ranges (https://github.com/fmtlib/fmt/issues/1064).

- Fixed handling of exotic character types
  (https://github.com/fmtlib/fmt/issues/1188).

- Made chrono formatting work with exceptions disabled
  (https://github.com/fmtlib/fmt/issues/1062).

- Fixed DLL visibility issues
  (https://github.com/fmtlib/fmt/pull/1134,
  https://github.com/fmtlib/fmt/pull/1147). Thanks @denchat.

- Disabled the use of UDL template extension on GCC 9
  (https://github.com/fmtlib/fmt/issues/1148).

- Removed misplaced `format` compile-time checks from `printf`
  (https://github.com/fmtlib/fmt/issues/1173).

- Fixed issues in the experimental floating-point formatter
  (https://github.com/fmtlib/fmt/issues/1072,
  https://github.com/fmtlib/fmt/issues/1129,
  https://github.com/fmtlib/fmt/issues/1153,
  https://github.com/fmtlib/fmt/pull/1155,
  https://github.com/fmtlib/fmt/issues/1210,
  https://github.com/fmtlib/fmt/issues/1222). Thanks @alabuzhev.

- Fixed bugs discovered by fuzzing or during fuzzing integration
  (https://github.com/fmtlib/fmt/issues/1124,
  https://github.com/fmtlib/fmt/issues/1127,
  https://github.com/fmtlib/fmt/issues/1132,
  https://github.com/fmtlib/fmt/pull/1135,
  https://github.com/fmtlib/fmt/issues/1136,
  https://github.com/fmtlib/fmt/issues/1141,
  https://github.com/fmtlib/fmt/issues/1142,
  https://github.com/fmtlib/fmt/issues/1178,
  https://github.com/fmtlib/fmt/issues/1179,
  https://github.com/fmtlib/fmt/issues/1194). Thanks @pauldreik.

- Fixed building tests on FreeBSD and Hurd
  (https://github.com/fmtlib/fmt/issues/1043). Thanks @jackyf.

- Fixed various warnings and compilation issues
  (https://github.com/fmtlib/fmt/pull/998,
  https://github.com/fmtlib/fmt/pull/1006,
  https://github.com/fmtlib/fmt/issues/1008,
  https://github.com/fmtlib/fmt/issues/1011,
  https://github.com/fmtlib/fmt/issues/1025,
  https://github.com/fmtlib/fmt/pull/1027,
  https://github.com/fmtlib/fmt/pull/1028,
  https://github.com/fmtlib/fmt/pull/1029,
  https://github.com/fmtlib/fmt/pull/1030,
  https://github.com/fmtlib/fmt/pull/1031,
  https://github.com/fmtlib/fmt/pull/1054,
  https://github.com/fmtlib/fmt/issues/1063,
  https://github.com/fmtlib/fmt/pull/1068,
  https://github.com/fmtlib/fmt/pull/1074,
  https://github.com/fmtlib/fmt/pull/1075,
  https://github.com/fmtlib/fmt/pull/1079,
  https://github.com/fmtlib/fmt/pull/1086,
  https://github.com/fmtlib/fmt/issues/1088,
  https://github.com/fmtlib/fmt/pull/1089,
  https://github.com/fmtlib/fmt/pull/1094,
  https://github.com/fmtlib/fmt/issues/1101,
  https://github.com/fmtlib/fmt/pull/1102,
  https://github.com/fmtlib/fmt/issues/1105,
  https://github.com/fmtlib/fmt/pull/1107,
  https://github.com/fmtlib/fmt/issues/1115,
  https://github.com/fmtlib/fmt/issues/1117,
  https://github.com/fmtlib/fmt/issues/1118,
  https://github.com/fmtlib/fmt/issues/1120,
  https://github.com/fmtlib/fmt/issues/1123,
  https://github.com/fmtlib/fmt/pull/1139,
  https://github.com/fmtlib/fmt/issues/1140,
  https://github.com/fmtlib/fmt/issues/1143,
  https://github.com/fmtlib/fmt/pull/1144,
  https://github.com/fmtlib/fmt/pull/1150,
  https://github.com/fmtlib/fmt/pull/1151,
  https://github.com/fmtlib/fmt/issues/1152,
  https://github.com/fmtlib/fmt/issues/1154,
  https://github.com/fmtlib/fmt/issues/1156,
  https://github.com/fmtlib/fmt/pull/1159,
  https://github.com/fmtlib/fmt/issues/1175,
  https://github.com/fmtlib/fmt/issues/1181,
  https://github.com/fmtlib/fmt/issues/1186,
  https://github.com/fmtlib/fmt/pull/1187,
  https://github.com/fmtlib/fmt/pull/1191,
  https://github.com/fmtlib/fmt/issues/1197,
  https://github.com/fmtlib/fmt/issues/1200,
  https://github.com/fmtlib/fmt/issues/1203,
  https://github.com/fmtlib/fmt/issues/1205,
  https://github.com/fmtlib/fmt/pull/1206,
  https://github.com/fmtlib/fmt/issues/1213,
  https://github.com/fmtlib/fmt/issues/1214,
  https://github.com/fmtlib/fmt/pull/1217,
  https://github.com/fmtlib/fmt/issues/1228,
  https://github.com/fmtlib/fmt/pull/1230,
  https://github.com/fmtlib/fmt/issues/1232,
  https://github.com/fmtlib/fmt/pull/1235,
  https://github.com/fmtlib/fmt/pull/1236,
  https://github.com/fmtlib/fmt/issues/1240).
  Thanks @DanielaE, @mwinterb, @eliaskosunen, @morinmorin, @ricco19,
  @waywardmonkeys, @chronoxor, @remyabel, @pauldreik, @gsjaardema, @rcane,
  @mocabe, @denchat, @cjdb, @HazardyKnusperkeks, @vedranmiletic, @jackoalan,
  @DaanDeMeyer and @starkmapper.

# 5.3.0 - 2018-12-28

- Introduced experimental chrono formatting support:

  ```c++
  #include <fmt/chrono.h>

  int main() {
    using namespace std::literals::chrono_literals;
    fmt::print("Default format: {} {}\n", 42s, 100ms);
    fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
  }
  ```

  prints:

      Default format: 42s 100ms
      strftime-like format: 03:15:30

- Added experimental support for emphasis (bold, italic, underline,
  strikethrough), colored output to a file stream, and improved
  colored formatting API
  (https://github.com/fmtlib/fmt/pull/961,
  https://github.com/fmtlib/fmt/pull/967,
  https://github.com/fmtlib/fmt/pull/973):

  ```c++
  #include <fmt/color.h>

  int main() {
    fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
               "Hello, {}!\n", "world");
    fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) |
               fmt::emphasis::underline, "Olá, {}!\n", "Mundo");
    fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic,
               "你好{}！\n", "世界");
  }
  ```

  prints the following on modern terminals with RGB color support:

  

  Thanks @Rakete1111.

- Added support for 4-bit terminal colors
  (https://github.com/fmtlib/fmt/issues/968,
  https://github.com/fmtlib/fmt/pull/974)

  ```c++
  #include <fmt/color.h>

  int main() {
    print(fg(fmt::terminal_color::red), "stop\n");
  }
  ```

  Note that these colors vary by terminal:

  

  Thanks @Rakete1111.

- Parameterized formatting functions on the type of the format string
  (https://github.com/fmtlib/fmt/issues/880,
  https://github.com/fmtlib/fmt/pull/881,
  https://github.com/fmtlib/fmt/pull/883,
  https://github.com/fmtlib/fmt/pull/885,
  https://github.com/fmtlib/fmt/pull/897,
  https://github.com/fmtlib/fmt/issues/920). Any object of
  type `S` that has an overloaded `to_string_view(const S&)` returning
  `fmt::string_view` can be used as a format string:

  ```c++
  namespace my_ns {
  inline string_view to_string_view(const my_string& s) {
    return {s.data(), s.length()};
  }
  }

  std::string message = fmt::format(my_string("The answer is {}."), 42);
  ```

  Thanks @DanielaE.

- Made `std::string_view` work as a format string
  (https://github.com/fmtlib/fmt/pull/898):

  ```c++
  auto message = fmt::format(std::string_view("The answer is {}."), 42);
  ```

  Thanks @DanielaE.

- Added wide string support to compile-time format string checks
  (https://github.com/fmtlib/fmt/pull/924):

  ```c++
  print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier
  ```

  Thanks @XZiar.

- Made colored print functions work with wide strings
  (https://github.com/fmtlib/fmt/pull/867):

  ```c++
  #include <fmt/color.h>

  int main() {
    print(fg(fmt::color::red), L"{}\n", 42);
  }
  ```

  Thanks @DanielaE.

- Introduced experimental Unicode support
  (https://github.com/fmtlib/fmt/issues/628,
  https://github.com/fmtlib/fmt/pull/891):

  ```c++
  using namespace fmt::literals;
  auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u
  ```

- Improved locale support:

  ```c++
  #include <fmt/locale.h>

  struct numpunct : std::numpunct<char> {
   protected:
    char do_thousands_sep() const override { return '~'; }
  };

  std::locale loc;
  auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567);
  // s == "1~234~567"
  ```

- Constrained formatting functions on proper iterator types
  (https://github.com/fmtlib/fmt/pull/921). Thanks @DanielaE.

- Added `make_printf_args` and `make_wprintf_args` functions
  (https://github.com/fmtlib/fmt/pull/934). Thanks @tnovotny.

- Deprecated `fmt::visit`, `parse_context`, and `wparse_context`. Use
  `fmt::visit_format_arg`, `format_parse_context`, and
  `wformat_parse_context` instead.

- Removed undocumented `basic_fixed_buffer` which has been superseded
  by the iterator-based API
  (https://github.com/fmtlib/fmt/issues/873,
  https://github.com/fmtlib/fmt/pull/902). Thanks @superfunc.

- Disallowed repeated leading zeros in an argument ID:

  ```c++
  fmt::print("{000}", 42); // error
  ```

- Reintroduced support for gcc 4.4.

- Fixed compilation on platforms with exotic `double`
  (https://github.com/fmtlib/fmt/issues/878).

- Improved documentation
  (https://github.com/fmtlib/fmt/issues/164,
  https://github.com/fmtlib/fmt/issues/877,
  https://github.com/fmtlib/fmt/pull/901,
  https://github.com/fmtlib/fmt/pull/906,
  https://github.com/fmtlib/fmt/pull/979).
  Thanks @kookjr, @DarkDimius and @HecticSerenity.

- Added pkgconfig support which makes it easier to consume the library
  from meson and other build systems
  (https://github.com/fmtlib/fmt/pull/916). Thanks @colemickens.

- Various build improvements
  (https://github.com/fmtlib/fmt/pull/909,
  https://github.com/fmtlib/fmt/pull/926,
  https://github.com/fmtlib/fmt/pull/937,
  https://github.com/fmtlib/fmt/pull/953,
  https://github.com/fmtlib/fmt/pull/959).
  Thanks @tchaikov, @luncliff, @AndreasSchoenle, @hotwatermorning and @Zefz.

- Improved `string_view` construction performance
  (https://github.com/fmtlib/fmt/pull/914). Thanks @gabime.

- Fixed non-matching char types
  (https://github.com/fmtlib/fmt/pull/895). Thanks @DanielaE.

- Fixed `format_to_n` with `std::back_insert_iterator`
  (https://github.com/fmtlib/fmt/pull/913). Thanks @DanielaE.

- Fixed locale-dependent formatting
  (https://github.com/fmtlib/fmt/issues/905).

- Fixed various compiler warnings and errors
  (https://github.com/fmtlib/fmt/pull/882,
  https://github.com/fmtlib/fmt/pull/886,
  https://github.com/fmtlib/fmt/pull/933,
  https://github.com/fmtlib/fmt/pull/941,
  https://github.com/fmtlib/fmt/issues/931,
  https://github.com/fmtlib/fmt/pull/943,
  https://github.com/fmtlib/fmt/pull/954,
  https://github.com/fmtlib/fmt/pull/956,
  https://github.com/fmtlib/fmt/pull/962,
  https://github.com/fmtlib/fmt/issues/965,
  https://github.com/fmtlib/fmt/issues/977,
  https://github.com/fmtlib/fmt/pull/983,
  https://github.com/fmtlib/fmt/pull/989).
  Thanks @Luthaf, @stevenhoving, @christinaa, @lgritz, @DanielaE,
  @0x8000-0000 and @liuping1997.

# 5.2.1 - 2018-09-21

- Fixed `visit` lookup issues on gcc 7 & 8
  (https://github.com/fmtlib/fmt/pull/870). Thanks @medithe.
- Fixed linkage errors on older gcc.
- Prevented `fmt/range.h` from specializing `fmt::basic_string_view`
  (https://github.com/fmtlib/fmt/issues/865,
  https://github.com/fmtlib/fmt/pull/868). Thanks @hhggit.
- Improved error message when formatting unknown types
  (https://github.com/fmtlib/fmt/pull/872). Thanks @foonathan.
- Disabled templated user-defined literals when compiled under nvcc
  (https://github.com/fmtlib/fmt/pull/875). Thanks @CandyGumdrop.
- Fixed `format_to` formatting to `wmemory_buffer`
  (https://github.com/fmtlib/fmt/issues/874).

# 5.2.0 - 2018-09-13

- Optimized format string parsing and argument processing which
  resulted in up to 5x speed up on long format strings and significant
  performance boost on various benchmarks. For example, version 5.2 is
  2.22x faster than 5.1 on decimal integer formatting with `format_to`
  (macOS, clang-902.0.39.2):

  | Method                     | Time, s         | Speedup |
  | -------------------------- | --------------: | ------: |
  | fmt::format 5.1            | 0.58            |         |
  | fmt::format 5.2            | 0.35            |   1.66x |
  | fmt::format_to 5.1         | 0.51            |         |
  | fmt::format_to 5.2         | 0.23            |   2.22x |
  | sprintf                    | 0.71            |         |
  | std::to_string             | 1.01            |         |
  | std::stringstream          | 1.73            |         |

- Changed the `fmt` macro from opt-out to opt-in to prevent name
  collisions. To enable it define the `FMT_STRING_ALIAS` macro to 1
  before including `fmt/format.h`:

  ```c++
  #define FMT_STRING_ALIAS 1
  #include <fmt/format.h>
  std::string answer = format(fmt("{}"), 42);
  ```

- Added compile-time format string checks to `format_to` overload that
  takes `fmt::memory_buffer`
  (https://github.com/fmtlib/fmt/issues/783):

  ```c++
  fmt::memory_buffer buf;
  // Compile-time error: invalid type specifier.
  fmt::format_to(buf, fmt("{:d}"), "foo");
  ```

- Moved experimental color support to `fmt/color.h` and enabled the
  new API by default. The old API can be enabled by defining the
  `FMT_DEPRECATED_COLORS` macro.

- Added formatting support for types explicitly convertible to
  `fmt::string_view`:

  ```c++
  struct foo {
    explicit operator fmt::string_view() const { return "foo"; }
  };
  auto s = format("{}", foo());
  ```

  In particular, this makes formatting function work with
  `folly::StringPiece`.

- Implemented preliminary support for `char*_t` by replacing the
  `format` function overloads with a single function template
  parameterized on the string type.

- Added support for dynamic argument lists
  (https://github.com/fmtlib/fmt/issues/814,
  https://github.com/fmtlib/fmt/pull/819). Thanks @MikePopoloski.

- Reduced executable size overhead for embedded targets using newlib
  nano by making locale dependency optional
  (https://github.com/fmtlib/fmt/pull/839). Thanks @teajay-fr.

- Keep `noexcept` specifier when exceptions are disabled
  (https://github.com/fmtlib/fmt/issues/801,
  https://github.com/fmtlib/fmt/pull/810). Thanks @qis.

- Fixed formatting of user-defined types providing `operator<<` with
  `format_to_n` (https://github.com/fmtlib/fmt/pull/806).
  Thanks @mkurdej.

- Fixed dynamic linkage of new symbols
  (https://github.com/fmtlib/fmt/issues/808).

- Fixed global initialization issue
  (https://github.com/fmtlib/fmt/issues/807):

  ```c++
  // This works on compilers with constexpr support.
  static const std::string answer = fmt::format("{}", 42);
  ```

- Fixed various compiler warnings and errors
  (https://github.com/fmtlib/fmt/pull/804,
  https://github.com/fmtlib/fmt/issues/809,
  https://github.com/fmtlib/fmt/pull/811,
  https://github.com/fmtlib/fmt/issues/822,
  https://github.com/fmtlib/fmt/pull/827,
  https://github.com/fmtlib/fmt/issues/830,
  https://github.com/fmtlib/fmt/pull/838,
  https://github.com/fmtlib/fmt/issues/843,
  https://github.com/fmtlib/fmt/pull/844,
  https://github.com/fmtlib/fmt/issues/851,
  https://github.com/fmtlib/fmt/pull/852,
  https://github.com/fmtlib/fmt/pull/854).
  Thanks @henryiii, @medithe, and @eliasdaler.

# 5.1.0 - 2018-07-05

- Added experimental support for RGB color output enabled with the
  `FMT_EXTENDED_COLORS` macro:

  ```c++
  #define FMT_EXTENDED_COLORS
  #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined
  #include <fmt/format.h>

  fmt::print(fmt::color::steel_blue, "Some beautiful text");
  ```

  The old API (the `print_colored` and `vprint_colored` functions and
  the `color` enum) is now deprecated.
  (https://github.com/fmtlib/fmt/issues/762
  https://github.com/fmtlib/fmt/pull/767). thanks @Remotion.

- Added quotes to strings in ranges and tuples
  (https://github.com/fmtlib/fmt/pull/766). Thanks @Remotion.

- Made `format_to` work with `basic_memory_buffer`
  (https://github.com/fmtlib/fmt/issues/776).

- Added `vformat_to_n` and `wchar_t` overload of `format_to_n`
  (https://github.com/fmtlib/fmt/issues/764,
  https://github.com/fmtlib/fmt/issues/769).

- Made `is_range` and `is_tuple_like` part of public (experimental)
  API to allow specialization for user-defined types
  (https://github.com/fmtlib/fmt/issues/751,
  https://github.com/fmtlib/fmt/pull/759). Thanks @drrlvn.

- Added more compilers to continuous integration and increased
  `FMT_PEDANTIC` warning levels
  (https://github.com/fmtlib/fmt/pull/736). Thanks @eliaskosunen.

- Fixed compilation with MSVC 2013.

- Fixed handling of user-defined types in `format_to`
  (https://github.com/fmtlib/fmt/issues/793).

- Forced linking of inline `vformat` functions into the library
  (https://github.com/fmtlib/fmt/issues/795).

- Fixed incorrect call to on_align in `'{:}='`
  (https://github.com/fmtlib/fmt/issues/750).

- Fixed floating-point formatting to a non-back_insert_iterator with
  sign & numeric alignment specified
  (https://github.com/fmtlib/fmt/issues/756).

- Fixed formatting to an array with `format_to_n`
  (https://github.com/fmtlib/fmt/issues/778).

- Fixed formatting of more than 15 named arguments
  (https://github.com/fmtlib/fmt/issues/754).

- Fixed handling of compile-time strings when including
  `fmt/ostream.h`. (https://github.com/fmtlib/fmt/issues/768).

- Fixed various compiler warnings and errors
  (https://github.com/fmtlib/fmt/issues/742,
  https://github.com/fmtlib/fmt/issues/748,
  https://github.com/fmtlib/fmt/issues/752,
  https://github.com/fmtlib/fmt/issues/770,
  https://github.com/fmtlib/fmt/pull/775,
  https://github.com/fmtlib/fmt/issues/779,
  https://github.com/fmtlib/fmt/pull/780,
  https://github.com/fmtlib/fmt/pull/790,
  https://github.com/fmtlib/fmt/pull/792,
  https://github.com/fmtlib/fmt/pull/800).
  Thanks @Remotion, @gabime, @foonathan, @Dark-Passenger and @0x8000-0000.

# 5.0.0 - 2018-05-21

- Added a requirement for partial C++11 support, most importantly
  variadic templates and type traits, and dropped `FMT_VARIADIC_*`
  emulation macros. Variadic templates are available since GCC 4.4,
  Clang 2.9 and MSVC 18.0 (2013). For older compilers use {fmt}
  [version 4.x](https://github.com/fmtlib/fmt/releases/tag/4.1.0)
  which continues to be maintained and works with C++98 compilers.

- Renamed symbols to follow standard C++ naming conventions and
  proposed a subset of the library for standardization in [P0645R2
  Text Formatting](https://wg21.link/P0645).

- Implemented `constexpr` parsing of format strings and [compile-time
  format string
  checks](https://fmt.dev/latest/api.html#compile-time-format-string-checks).
  For example

  ```c++
  #include <fmt/format.h>

  std::string s = format(fmt("{:d}"), "foo");
  ```

  gives a compile-time error because `d` is an invalid specifier for
  strings ([godbolt](https://godbolt.org/g/rnCy9Q)):

      ...
      <source>:4:19: note: in instantiation of function template specialization 'fmt::v5::format<S, char [4]>' requested here
        std::string s = format(fmt("{:d}"), "foo");
                        ^
      format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression
          handler.on_error("invalid type specifier");

  Compile-time checks require relaxed `constexpr` (C++14 feature)
  support. If the latter is not available, checks will be performed at
  runtime.

- Separated format string parsing and formatting in the extension API
  to enable compile-time format string processing. For example

  ```c++
  struct Answer {};

  namespace fmt {
  template <>
  struct formatter<Answer> {
    constexpr auto parse(parse_context& ctx) {
      auto it = ctx.begin();
      spec = *it;
      if (spec != 'd' && spec != 's')
        throw format_error("invalid specifier");
      return ++it;
    }

    template <typename FormatContext>
    auto format(Answer, FormatContext& ctx) {
      return spec == 's' ?
        format_to(ctx.begin(), "{}", "fourty-two") :
        format_to(ctx.begin(), "{}", 42);
    }

    char spec = 0;
  };
  }

  std::string s = format(fmt("{:x}"), Answer());
  ```

  gives a compile-time error due to invalid format specifier
  ([godbolt](https://godbolt.org/g/2jQ1Dv)):

      ...
      <source>:12:45: error: expression '<throw-expression>' is not a constant expression
             throw format_error("invalid specifier");

- Added [iterator
  support](https://fmt.dev/latest/api.html#output-iterator-support):

  ```c++
  #include <vector>
  #include <fmt/format.h>

  std::vector<char> out;
  fmt::format_to(std::back_inserter(out), "{}", 42);
  ```

- Added the
  [format_to_n](https://fmt.dev/latest/api.html#_CPPv2N3fmt11format_to_nE8OutputItNSt6size_tE11string_viewDpRK4Args)
  function that restricts the output to the specified number of
  characters (https://github.com/fmtlib/fmt/issues/298):

  ```c++
  char out[4];
  fmt::format_to_n(out, sizeof(out), "{}", 12345);
  // out == "1234" (without terminating '\0')
  ```

- Added the [formatted_size](
  https://fmt.dev/latest/api.html#_CPPv2N3fmt14formatted_sizeE11string_viewDpRK4Args)
  function for computing the output size:

  ```c++
  #include <fmt/format.h>

  auto size = fmt::formatted_size("{}", 12345); // size == 5
  ```

- Improved compile times by reducing dependencies on standard headers
  and providing a lightweight [core
  API](https://fmt.dev/latest/api.html#core-api):

  ```c++
  #include <fmt/core.h>

  fmt::print("The answer is {}.", 42);
  ```

  See [Compile time and code
  bloat](https://github.com/fmtlib/fmt#compile-time-and-code-bloat).

- Added the [make_format_args](
  https://fmt.dev/latest/api.html#_CPPv2N3fmt16make_format_argsEDpRK4Args)
  function for capturing formatting arguments:

  ```c++
  // Prints formatted error message.
  void vreport_error(const char *format, fmt::format_args args) {
    fmt::print("Error: ");
    fmt::vprint(format, args);
  }
  template <typename... Args>
  void report_error(const char *format, const Args & ... args) {
    vreport_error(format, fmt::make_format_args(args...));
  }
  ```

- Added the `make_printf_args` function for capturing `printf`
  arguments (https://github.com/fmtlib/fmt/issues/687,
  https://github.com/fmtlib/fmt/pull/694). Thanks @Kronuz.

- Added prefix `v` to non-variadic functions taking `format_args` to
  distinguish them from variadic ones:

  ```c++
  std::string vformat(string_view format_str, format_args args);

  template <typename... Args>
  std::string format(string_view format_str, const Args & ... args);
  ```

- Added experimental support for formatting ranges, containers and
  tuple-like types in `fmt/ranges.h`
  (https://github.com/fmtlib/fmt/pull/735):

  ```c++
  #include <fmt/ranges.h>

  std::vector<int> v = {1, 2, 3};
  fmt::print("{}", v); // prints {1, 2, 3}
  ```

  Thanks @Remotion.

- Implemented `wchar_t` date and time formatting
  (https://github.com/fmtlib/fmt/pull/712):

  ```c++
  #include <fmt/time.h>

  std::time_t t = std::time(nullptr);
  auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t));
  ```

  Thanks @DanielaE.

- Provided more wide string overloads
  (https://github.com/fmtlib/fmt/pull/724). Thanks @DanielaE.

- Switched from a custom null-terminated string view class to
  `string_view` in the format API and provided `fmt::string_view`
  which implements a subset of `std::string_view` API for pre-C++17
  systems.

- Added support for `std::experimental::string_view`
  (https://github.com/fmtlib/fmt/pull/607):

  ```c++
  #include <fmt/core.h>
  #include <experimental/string_view>

  fmt::print("{}", std::experimental::string_view("foo"));
  ```

  Thanks @virgiliofornazin.

- Allowed mixing named and automatic arguments:

  ```c++
  fmt::format("{} {two}", 1, fmt::arg("two", 2));
  ```

- Removed the write API in favor of the [format
  API](https://fmt.dev/latest/api.html#format-api) with compile-time
  handling of format strings.

- Disallowed formatting of multibyte strings into a wide character
  target (https://github.com/fmtlib/fmt/pull/606).

- Improved documentation
  (https://github.com/fmtlib/fmt/pull/515,
  https://github.com/fmtlib/fmt/issues/614,
  https://github.com/fmtlib/fmt/pull/617,
  https://github.com/fmtlib/fmt/pull/661,
  https://github.com/fmtlib/fmt/pull/680).
  Thanks @ibell, @mihaitodor and @johnthagen.

- Implemented more efficient handling of large number of format
  arguments.

- Introduced an inline namespace for symbol versioning.

- Added debug postfix `d` to the `fmt` library name
  (https://github.com/fmtlib/fmt/issues/636).

- Removed unnecessary `fmt/` prefix in includes
  (https://github.com/fmtlib/fmt/pull/397). Thanks @chronoxor.

- Moved `fmt/*.h` to `include/fmt/*.h` to prevent irrelevant files and
  directories appearing on the include search paths when fmt is used
  as a subproject and moved source files to the `src` directory.

- Added qmake project file `support/fmt.pro`
  (https://github.com/fmtlib/fmt/pull/641). Thanks @cowo78.

- Added Gradle build file `support/build.gradle`
  (https://github.com/fmtlib/fmt/pull/649). Thanks @luncliff.

- Removed `FMT_CPPFORMAT` CMake option.

- Fixed a name conflict with the macro `CHAR_WIDTH` in glibc
  (https://github.com/fmtlib/fmt/pull/616). Thanks @aroig.

- Fixed handling of nested braces in `fmt::join`
  (https://github.com/fmtlib/fmt/issues/638).

- Added `SOURCELINK_SUFFIX` for compatibility with Sphinx 1.5
  (https://github.com/fmtlib/fmt/pull/497). Thanks @ginggs.

- Added a missing `inline` in the header-only mode
  (https://github.com/fmtlib/fmt/pull/626). Thanks @aroig.

- Fixed various compiler warnings
  (https://github.com/fmtlib/fmt/pull/640,
  https://github.com/fmtlib/fmt/pull/656,
  https://github.com/fmtlib/fmt/pull/679,
  https://github.com/fmtlib/fmt/pull/681,
  https://github.com/fmtlib/fmt/pull/705,
  https://github.com/fmtlib/fmt/issues/715,
  https://github.com/fmtlib/fmt/pull/717,
  https://github.com/fmtlib/fmt/pull/720,
  https://github.com/fmtlib/fmt/pull/723,
  https://github.com/fmtlib/fmt/pull/726,
  https://github.com/fmtlib/fmt/pull/730,
  https://github.com/fmtlib/fmt/pull/739).
  Thanks @peterbell10, @LarsGullik, @foonathan, @eliaskosunen,
  @christianparpart, @DanielaE and @mwinterb.

- Worked around an MSVC bug and fixed several warnings
  (https://github.com/fmtlib/fmt/pull/653). Thanks @alabuzhev.

- Worked around GCC bug 67371
  (https://github.com/fmtlib/fmt/issues/682).

- Fixed compilation with `-fno-exceptions`
  (https://github.com/fmtlib/fmt/pull/655). Thanks @chenxiaolong.

- Made `constexpr remove_prefix` gcc version check tighter
  (https://github.com/fmtlib/fmt/issues/648).

- Renamed internal type enum constants to prevent collision with
  poorly written C libraries
  (https://github.com/fmtlib/fmt/issues/644).

- Added detection of `wostream operator<<`
  (https://github.com/fmtlib/fmt/issues/650).

- Fixed compilation on OpenBSD
  (https://github.com/fmtlib/fmt/pull/660). Thanks @hubslave.

- Fixed compilation on FreeBSD 12
  (https://github.com/fmtlib/fmt/pull/732). Thanks @dankm.

- Fixed compilation when there is a mismatch between `-std` options
  between the library and user code
  (https://github.com/fmtlib/fmt/issues/664).

- Fixed compilation with GCC 7 and `-std=c++11`
  (https://github.com/fmtlib/fmt/issues/734).

- Improved generated binary code on GCC 7 and older
  (https://github.com/fmtlib/fmt/issues/668).

- Fixed handling of numeric alignment with no width
  (https://github.com/fmtlib/fmt/issues/675).

- Fixed handling of empty strings in UTF8/16 converters
  (https://github.com/fmtlib/fmt/pull/676). Thanks @vgalka-sl.

- Fixed formatting of an empty `string_view`
  (https://github.com/fmtlib/fmt/issues/689).

- Fixed detection of `string_view` on libc++
  (https://github.com/fmtlib/fmt/issues/686).

- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/696).
  Thanks @sebkoenig.

- Fixed compile checks for mixing narrow and wide strings
  (https://github.com/fmtlib/fmt/issues/690).

- Disabled unsafe implicit conversion to `std::string`
  (https://github.com/fmtlib/fmt/issues/729).

- Fixed handling of reused format specs (as in `fmt::join`) for
  pointers (https://github.com/fmtlib/fmt/pull/725). Thanks @mwinterb.

- Fixed installation of `fmt/ranges.h`
  (https://github.com/fmtlib/fmt/pull/738). Thanks @sv1990.

# 4.1.0 - 2017-12-20

- Added `fmt::to_wstring()` in addition to `fmt::to_string()`
  (https://github.com/fmtlib/fmt/pull/559). Thanks @alabuzhev.
- Added support for C++17 `std::string_view`
  (https://github.com/fmtlib/fmt/pull/571 and
  https://github.com/fmtlib/fmt/pull/578).
  Thanks @thelostt and @mwinterb.
- Enabled stream exceptions to catch errors
  (https://github.com/fmtlib/fmt/issues/581). Thanks @crusader-mike.
- Allowed formatting of class hierarchies with `fmt::format_arg()`
  (https://github.com/fmtlib/fmt/pull/547). Thanks @rollbear.
- Removed limitations on character types
  (https://github.com/fmtlib/fmt/pull/563). Thanks @Yelnats321.
- Conditionally enabled use of `std::allocator_traits`
  (https://github.com/fmtlib/fmt/pull/583). Thanks @mwinterb.
- Added support for `const` variadic member function emulation with
  `FMT_VARIADIC_CONST`
  (https://github.com/fmtlib/fmt/pull/591). Thanks @ludekvodicka.
- Various bugfixes: bad overflow check, unsupported implicit type
  conversion when determining formatting function, test segfaults
  (https://github.com/fmtlib/fmt/issues/551), ill-formed
  macros (https://github.com/fmtlib/fmt/pull/542) and
  ambiguous overloads
  (https://github.com/fmtlib/fmt/issues/580). Thanks @xylosper.
- Prevented warnings on MSVC
  (https://github.com/fmtlib/fmt/pull/605,
  https://github.com/fmtlib/fmt/pull/602, and
  https://github.com/fmtlib/fmt/pull/545), clang
  (https://github.com/fmtlib/fmt/pull/582), GCC
  (https://github.com/fmtlib/fmt/issues/573), various
  conversion warnings (https://github.com/fmtlib/fmt/pull/609,
  https://github.com/fmtlib/fmt/pull/567,
  https://github.com/fmtlib/fmt/pull/553 and
  https://github.com/fmtlib/fmt/pull/553), and added
  `override` and `[[noreturn]]`
  (https://github.com/fmtlib/fmt/pull/549 and
  https://github.com/fmtlib/fmt/issues/555).
  Thanks @alabuzhev, @virgiliofornazin, @alexanderbock, @yumetodo, @VaderY,
  @jpcima, @thelostt and @Manu343726.
- Improved CMake: Used `GNUInstallDirs` to set installation location
  (https://github.com/fmtlib/fmt/pull/610) and fixed warnings
  (https://github.com/fmtlib/fmt/pull/536 and
  https://github.com/fmtlib/fmt/pull/556).
  Thanks @mikecrowe, @evgen231 and @henryiii.

# 4.0.0 - 2017-06-27

- Removed old compatibility headers `cppformat/*.h` and CMake options
  (https://github.com/fmtlib/fmt/pull/527). Thanks @maddinat0r.

- Added `string.h` containing `fmt::to_string()` as alternative to
  `std::to_string()` as well as other string writer functionality
  (https://github.com/fmtlib/fmt/issues/326 and
  https://github.com/fmtlib/fmt/pull/441):

  ```c++
  #include "fmt/string.h"

  std::string answer = fmt::to_string(42);
  ```

  Thanks @glebov-andrey.

- Moved `fmt::printf()` to new `printf.h` header and allowed `%s` as
  generic specifier (https://github.com/fmtlib/fmt/pull/453),
  made `%.f` more conformant to regular `printf()`
  (https://github.com/fmtlib/fmt/pull/490), added custom
  writer support (https://github.com/fmtlib/fmt/issues/476)
  and implemented missing custom argument formatting
  (https://github.com/fmtlib/fmt/pull/339 and
  https://github.com/fmtlib/fmt/pull/340):

  ```c++
  #include "fmt/printf.h"

  // %s format specifier can be used with any argument type.
  fmt::printf("%s", 42);
  ```

  Thanks @mojoBrendan, @manylegged and @spacemoose.
  See also https://github.com/fmtlib/fmt/issues/360,
  https://github.com/fmtlib/fmt/issues/335 and
  https://github.com/fmtlib/fmt/issues/331.

- Added `container.h` containing a `BasicContainerWriter` to write to
  containers like `std::vector`
  (https://github.com/fmtlib/fmt/pull/450). Thanks @polyvertex.

- Added `fmt::join()` function that takes a range and formats its
  elements separated by a given string
  (https://github.com/fmtlib/fmt/pull/466):

  ```c++
  #include "fmt/format.h"

  std::vector<double> v = {1.2, 3.4, 5.6};
  // Prints "(+01.20, +03.40, +05.60)".
  fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", "));
  ```

  Thanks @olivier80.

- Added support for custom formatting specifications to simplify
  customization of built-in formatting
  (https://github.com/fmtlib/fmt/pull/444). Thanks @polyvertex.
  See also https://github.com/fmtlib/fmt/issues/439.

- Added `fmt::format_system_error()` for error code formatting
  (https://github.com/fmtlib/fmt/issues/323 and
  https://github.com/fmtlib/fmt/pull/526). Thanks @maddinat0r.

- Added thread-safe `fmt::localtime()` and `fmt::gmtime()` as
  replacement for the standard version to `time.h`
  (https://github.com/fmtlib/fmt/pull/396). Thanks @codicodi.

- Internal improvements to `NamedArg` and `ArgLists`
  (https://github.com/fmtlib/fmt/pull/389 and
  https://github.com/fmtlib/fmt/pull/390). Thanks @chronoxor.

- Fixed crash due to bug in `FormatBuf`
  (https://github.com/fmtlib/fmt/pull/493). Thanks @effzeh. See also
  https://github.com/fmtlib/fmt/issues/480 and
  https://github.com/fmtlib/fmt/issues/491.

- Fixed handling of wide strings in `fmt::StringWriter`.

- Improved compiler error messages
  (https://github.com/fmtlib/fmt/issues/357).

- Fixed various warnings and issues with various compilers
  (https://github.com/fmtlib/fmt/pull/494,
  https://github.com/fmtlib/fmt/pull/499,
  https://github.com/fmtlib/fmt/pull/483,
  https://github.com/fmtlib/fmt/pull/485,
  https://github.com/fmtlib/fmt/pull/482,
  https://github.com/fmtlib/fmt/pull/475,
  https://github.com/fmtlib/fmt/pull/473 and
  https://github.com/fmtlib/fmt/pull/414).
  Thanks @chronoxor, @zhaohuaxishi, @pkestene, @dschmidt and @0x414c.

- Improved CMake: targets are now namespaced
  (https://github.com/fmtlib/fmt/pull/511 and
  https://github.com/fmtlib/fmt/pull/513), supported
  header-only `printf.h`
  (https://github.com/fmtlib/fmt/pull/354), fixed issue with
  minimal supported library subset
  (https://github.com/fmtlib/fmt/issues/418,
  https://github.com/fmtlib/fmt/pull/419 and
  https://github.com/fmtlib/fmt/pull/420).
  Thanks @bjoernthiel, @niosHD, @LogicalKnight and @alabuzhev.

- Improved documentation (https://github.com/fmtlib/fmt/pull/393).
  Thanks @pwm1234.

# 3.0.2 - 2017-06-14

- Added `FMT_VERSION` macro
  (https://github.com/fmtlib/fmt/issues/411).
- Used `FMT_NULL` instead of literal `0`
  (https://github.com/fmtlib/fmt/pull/409). Thanks @alabuzhev.
- Added extern templates for `format_float`
  (https://github.com/fmtlib/fmt/issues/413).
- Fixed implicit conversion issue
  (https://github.com/fmtlib/fmt/issues/507).
- Fixed signbit detection
  (https://github.com/fmtlib/fmt/issues/423).
- Fixed naming collision
  (https://github.com/fmtlib/fmt/issues/425).
- Fixed missing intrinsic for C++/CLI
  (https://github.com/fmtlib/fmt/pull/457). Thanks @calumr.
- Fixed Android detection
  (https://github.com/fmtlib/fmt/pull/458). Thanks @Gachapen.
- Use lean `windows.h` if not in header-only mode
  (https://github.com/fmtlib/fmt/pull/503). Thanks @Quentin01.
- Fixed issue with CMake exporting C++11 flag
  (https://github.com/fmtlib/fmt/pull/455). Thanks @EricWF.
- Fixed issue with nvcc and MSVC compiler bug and MinGW
  (https://github.com/fmtlib/fmt/issues/505).
- Fixed DLL issues (https://github.com/fmtlib/fmt/pull/469 and
  https://github.com/fmtlib/fmt/pull/502).
  Thanks @richardeakin and @AndreasSchoenle.
- Fixed test compilation under FreeBSD
  (https://github.com/fmtlib/fmt/issues/433).
- Fixed various warnings
  (https://github.com/fmtlib/fmt/pull/403,
  https://github.com/fmtlib/fmt/pull/410 and
  https://github.com/fmtlib/fmt/pull/510).
  Thanks @Lecetem, @chenhayat and @trozen.
- Worked around a broken `__builtin_clz` in clang with MS codegen
  (https://github.com/fmtlib/fmt/issues/519).
- Removed redundant include
  (https://github.com/fmtlib/fmt/issues/479).
- Fixed documentation issues.

# 3.0.1 - 2016-11-01

- Fixed handling of thousands separator
  (https://github.com/fmtlib/fmt/issues/353).
- Fixed handling of `unsigned char` strings
  (https://github.com/fmtlib/fmt/issues/373).
- Corrected buffer growth when formatting time
  (https://github.com/fmtlib/fmt/issues/367).
- Removed warnings under MSVC and clang
  (https://github.com/fmtlib/fmt/issues/318,
  https://github.com/fmtlib/fmt/issues/250, also merged
  https://github.com/fmtlib/fmt/pull/385 and
  https://github.com/fmtlib/fmt/pull/361).
  Thanks @jcelerier and @nmoehrle.
- Fixed compilation issues under Android
  (https://github.com/fmtlib/fmt/pull/327,
  https://github.com/fmtlib/fmt/issues/345 and
  https://github.com/fmtlib/fmt/pull/381), FreeBSD
  (https://github.com/fmtlib/fmt/pull/358), Cygwin
  (https://github.com/fmtlib/fmt/issues/388), MinGW
  (https://github.com/fmtlib/fmt/issues/355) as well as other
  issues (https://github.com/fmtlib/fmt/issues/350,
  https://github.com/fmtlib/fmt/issues/355,
  https://github.com/fmtlib/fmt/pull/348,
  https://github.com/fmtlib/fmt/pull/402,
  https://github.com/fmtlib/fmt/pull/405).
  Thanks @dpantele, @hghwng, @arvedarved, @LogicalKnight and @JanHellwig.
- Fixed some documentation issues and extended specification
  (https://github.com/fmtlib/fmt/issues/320,
  https://github.com/fmtlib/fmt/pull/333,
  https://github.com/fmtlib/fmt/issues/347,
  https://github.com/fmtlib/fmt/pull/362). Thanks @smellman.

# 3.0.0 - 2016-05-07

- The project has been renamed from C++ Format (cppformat) to fmt for
  consistency with the used namespace and macro prefix
  (https://github.com/fmtlib/fmt/issues/307). Library headers
  are now located in the `fmt` directory:

  ```c++
  #include "fmt/format.h"
  ```

  Including `format.h` from the `cppformat` directory is deprecated
  but works via a proxy header which will be removed in the next major
  version.

  The documentation is now available at <https://fmt.dev>.

- Added support for
  [strftime](http://en.cppreference.com/w/cpp/chrono/c/strftime)-like
  [date and time
  formatting](https://fmt.dev/3.0.0/api.html#date-and-time-formatting)
  (https://github.com/fmtlib/fmt/issues/283):

  ```c++
  #include "fmt/time.h"

  std::time_t t = std::time(nullptr);
  // Prints "The date is 2016-04-29." (with the current date)
  fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t));
  ```

- `std::ostream` support including formatting of user-defined types
  that provide overloaded `operator<<` has been moved to
  `fmt/ostream.h`:

  ```c++
  #include "fmt/ostream.h"

  class Date {
    int year_, month_, day_;
  public:
    Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}

    friend std::ostream &operator<<(std::ostream &os, const Date &d) {
      return os << d.year_ << '-' << d.month_ << '-' << d.day_;
    }
  };

  std::string s = fmt::format("The date is {}", Date(2012, 12, 9));
  // s == "The date is 2012-12-9"
  ```

- Added support for [custom argument
  formatters](https://fmt.dev/3.0.0/api.html#argument-formatters)
  (https://github.com/fmtlib/fmt/issues/235).

- Added support for locale-specific integer formatting with the `n`
  specifier (https://github.com/fmtlib/fmt/issues/305):

  ```c++
  std::setlocale(LC_ALL, "en_US.utf8");
  fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567
  ```

- Sign is now preserved when formatting an integer with an incorrect
  `printf` format specifier
  (https://github.com/fmtlib/fmt/issues/265):

  ```c++
  fmt::printf("%lld", -42); // prints -42
  ```

  Note that it would be an undefined behavior in `std::printf`.

- Length modifiers such as `ll` are now optional in printf formatting
  functions and the correct type is determined automatically
  (https://github.com/fmtlib/fmt/issues/255):

  ```c++
  fmt::printf("%d", std::numeric_limits<long long>::max());
  ```

  Note that it would be an undefined behavior in `std::printf`.

- Added initial support for custom formatters
  (https://github.com/fmtlib/fmt/issues/231).

- Fixed detection of user-defined literal support on Intel C++
  compiler (https://github.com/fmtlib/fmt/issues/311,
  https://github.com/fmtlib/fmt/pull/312).
  Thanks @dean0x7d and @speth.

- Reduced compile time
  (https://github.com/fmtlib/fmt/pull/243,
  https://github.com/fmtlib/fmt/pull/249,
  https://github.com/fmtlib/fmt/issues/317):

  

  

  Thanks @dean0x7d.

- Compile test fixes (https://github.com/fmtlib/fmt/pull/313).
  Thanks @dean0x7d.

- Documentation fixes (https://github.com/fmtlib/fmt/pull/239,
  https://github.com/fmtlib/fmt/issues/248,
  https://github.com/fmtlib/fmt/issues/252,
  https://github.com/fmtlib/fmt/pull/258,
  https://github.com/fmtlib/fmt/issues/260,
  https://github.com/fmtlib/fmt/issues/301,
  https://github.com/fmtlib/fmt/pull/309).
  Thanks @ReadmeCritic @Gachapen and @jwilk.

- Fixed compiler and sanitizer warnings
  (https://github.com/fmtlib/fmt/issues/244,
  https://github.com/fmtlib/fmt/pull/256,
  https://github.com/fmtlib/fmt/pull/259,
  https://github.com/fmtlib/fmt/issues/263,
  https://github.com/fmtlib/fmt/issues/274,
  https://github.com/fmtlib/fmt/pull/277,
  https://github.com/fmtlib/fmt/pull/286,
  https://github.com/fmtlib/fmt/issues/291,
  https://github.com/fmtlib/fmt/issues/296,
  https://github.com/fmtlib/fmt/issues/308).
  Thanks @mwinterb, @pweiskircher and @Naios.

- Improved compatibility with Windows Store apps
  (https://github.com/fmtlib/fmt/issues/280,
  https://github.com/fmtlib/fmt/pull/285) Thanks @mwinterb.

- Added tests of compatibility with older C++ standards
  (https://github.com/fmtlib/fmt/pull/273). Thanks @niosHD.

- Fixed Android build
  (https://github.com/fmtlib/fmt/pull/271). Thanks @newnon.

- Changed `ArgMap` to be backed by a vector instead of a map.
  (https://github.com/fmtlib/fmt/issues/261,
  https://github.com/fmtlib/fmt/pull/262). Thanks @mwinterb.

- Added `fprintf` overload that writes to a `std::ostream`
  (https://github.com/fmtlib/fmt/pull/251).
  Thanks @nickhutchinson.

- Export symbols when building a Windows DLL
  (https://github.com/fmtlib/fmt/pull/245).
  Thanks @macdems.

- Fixed compilation on Cygwin
  (https://github.com/fmtlib/fmt/issues/304).

- Implemented a workaround for a bug in Apple LLVM version 4.2 of
  clang (https://github.com/fmtlib/fmt/issues/276).

- Implemented a workaround for Google Test bug
  https://github.com/google/googletest/issues/705 on gcc 6
  (https://github.com/fmtlib/fmt/issues/268). Thanks @octoploid.

- Removed Biicode support because the latter has been discontinued.

# 2.1.1 - 2016-04-11

- The install location for generated CMake files is now configurable
  via the `FMT_CMAKE_DIR` CMake variable
  (https://github.com/fmtlib/fmt/pull/299). Thanks @niosHD.
- Documentation fixes
  (https://github.com/fmtlib/fmt/issues/252).

# 2.1.0 - 2016-03-21

- Project layout and build system improvements
  (https://github.com/fmtlib/fmt/pull/267):

  -   The code have been moved to the `cppformat` directory. Including
      `format.h` from the top-level directory is deprecated but works
      via a proxy header which will be removed in the next major
      version.
  -   C++ Format CMake targets now have proper interface definitions.
  -   Installed version of the library now supports the header-only
      configuration.
  -   Targets `doc`, `install`, and `test` are now disabled if C++
      Format is included as a CMake subproject. They can be enabled by
      setting `FMT_DOC`, `FMT_INSTALL`, and `FMT_TEST` in the parent
      project.

  Thanks @niosHD.

# 2.0.1 - 2016-03-13

- Improved CMake find and package support
  (https://github.com/fmtlib/fmt/issues/264). Thanks @niosHD.
- Fix compile error with Android NDK and mingw32
  (https://github.com/fmtlib/fmt/issues/241). Thanks @Gachapen.
- Documentation fixes
  (https://github.com/fmtlib/fmt/issues/248,
  https://github.com/fmtlib/fmt/issues/260).

# 2.0.0 - 2015-12-01

## General

- \[Breaking\] Named arguments
  (https://github.com/fmtlib/fmt/pull/169,
  https://github.com/fmtlib/fmt/pull/173,
  https://github.com/fmtlib/fmt/pull/174):

  ```c++
  fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
  ```

  Thanks @jamboree.

- \[Experimental\] User-defined literals for format and named
  arguments (https://github.com/fmtlib/fmt/pull/204,
  https://github.com/fmtlib/fmt/pull/206,
  https://github.com/fmtlib/fmt/pull/207):

  ```c++
  using namespace fmt::literals;
  fmt::print("The answer is {answer}.", "answer"_a=42);
  ```

  Thanks @dean0x7d.

- \[Breaking\] Formatting of more than 16 arguments is now supported
  when using variadic templates
  (https://github.com/fmtlib/fmt/issues/141). Thanks @Shauren.

- Runtime width specification
  (https://github.com/fmtlib/fmt/pull/168):

  ```c++
  fmt::format("{0:{1}}", 42, 5); // gives "   42"
  ```

  Thanks @jamboree.

- \[Breaking\] Enums are now formatted with an overloaded
  `std::ostream` insertion operator (`operator<<`) if available
  (https://github.com/fmtlib/fmt/issues/232).

- \[Breaking\] Changed default `bool` format to textual, \"true\" or
  \"false\" (https://github.com/fmtlib/fmt/issues/170):

  ```c++
  fmt::print("{}", true); // prints "true"
  ```

  To print `bool` as a number use numeric format specifier such as
  `d`:

  ```c++
  fmt::print("{:d}", true); // prints "1"
  ```

- `fmt::printf` and `fmt::sprintf` now support formatting of `bool`
  with the `%s` specifier giving textual output, \"true\" or \"false\"
  (https://github.com/fmtlib/fmt/pull/223):

  ```c++
  fmt::printf("%s", true); // prints "true"
  ```

  Thanks @LarsGullik.

- \[Breaking\] `signed char` and `unsigned char` are now formatted as
  integers by default
  (https://github.com/fmtlib/fmt/pull/217).

- \[Breaking\] Pointers to C strings can now be formatted with the `p`
  specifier (https://github.com/fmtlib/fmt/pull/223):

  ```c++
  fmt::print("{:p}", "test"); // prints pointer value
  ```

  Thanks @LarsGullik.

- \[Breaking\] `fmt::printf` and `fmt::sprintf` now print null
  pointers as `(nil)` and null strings as `(null)` for consistency
  with glibc (https://github.com/fmtlib/fmt/pull/226).
  Thanks @LarsGullik.

- \[Breaking\] `fmt::(s)printf` now supports formatting of objects of
  user-defined types that provide an overloaded `std::ostream`
  insertion operator (`operator<<`)
  (https://github.com/fmtlib/fmt/issues/201):

  ```c++
  fmt::printf("The date is %s", Date(2012, 12, 9));
  ```

- \[Breaking\] The `Buffer` template is now part of the public API and
  can be used to implement custom memory buffers
  (https://github.com/fmtlib/fmt/issues/140). Thanks @polyvertex.

- \[Breaking\] Improved compatibility between `BasicStringRef` and
  [std::experimental::basic_string_view](
  http://en.cppreference.com/w/cpp/experimental/basic_string_view)
  (https://github.com/fmtlib/fmt/issues/100,
  https://github.com/fmtlib/fmt/issues/159,
  https://github.com/fmtlib/fmt/issues/183):

  -   Comparison operators now compare string content, not pointers
  -   `BasicStringRef::c_str` replaced by `BasicStringRef::data`
  -   `BasicStringRef` is no longer assumed to be null-terminated

  References to null-terminated strings are now represented by a new
  class, `BasicCStringRef`.

- Dependency on pthreads introduced by Google Test is now optional
  (https://github.com/fmtlib/fmt/issues/185).

- New CMake options `FMT_DOC`, `FMT_INSTALL` and `FMT_TEST` to control
  generation of `doc`, `install` and `test` targets respectively, on
  by default (https://github.com/fmtlib/fmt/issues/197,
  https://github.com/fmtlib/fmt/issues/198,
  https://github.com/fmtlib/fmt/issues/200). Thanks @maddinat0r.

- `noexcept` is now used when compiling with MSVC2015
  (https://github.com/fmtlib/fmt/pull/215). Thanks @dmkrepo.

- Added an option to disable use of `windows.h` when
  `FMT_USE_WINDOWS_H` is defined as 0 before including `format.h`
  (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps.

- \[Breaking\] `windows.h` is now included with `NOMINMAX` unless
  `FMT_WIN_MINMAX` is defined. This is done to prevent breaking code
  using `std::min` and `std::max` and only affects the header-only
  configuration (https://github.com/fmtlib/fmt/issues/152,
  https://github.com/fmtlib/fmt/pull/153,
  https://github.com/fmtlib/fmt/pull/154). Thanks @DevO2012.

- Improved support for custom character types
  (https://github.com/fmtlib/fmt/issues/171). Thanks @alfps.

- Added an option to disable use of IOStreams when `FMT_USE_IOSTREAMS`
  is defined as 0 before including `format.h`
  (https://github.com/fmtlib/fmt/issues/205,
  https://github.com/fmtlib/fmt/pull/208). Thanks @JodiTheTigger.

- Improved detection of `isnan`, `isinf` and `signbit`.

## Optimization

- Made formatting of user-defined types more efficient with a custom
  stream buffer (https://github.com/fmtlib/fmt/issues/92,
  https://github.com/fmtlib/fmt/pull/230). Thanks @NotImplemented.
- Further improved performance of `fmt::Writer` on integer formatting
  and fixed a minor regression. Now it is \~7% faster than
  `karma::generate` on Karma\'s benchmark
  (https://github.com/fmtlib/fmt/issues/186).
- \[Breaking\] Reduced [compiled code
  size](https://github.com/fmtlib/fmt#compile-time-and-code-bloat)
  (https://github.com/fmtlib/fmt/issues/143,
  https://github.com/fmtlib/fmt/pull/149).

## Distribution

- \[Breaking\] Headers are now installed in
  `${CMAKE_INSTALL_PREFIX}/include/cppformat`
  (https://github.com/fmtlib/fmt/issues/178). Thanks @jackyf.

- \[Breaking\] Changed the library name from `format` to `cppformat`
  for consistency with the project name and to avoid potential
  conflicts (https://github.com/fmtlib/fmt/issues/178).
  Thanks @jackyf.

- C++ Format is now available in [Debian](https://www.debian.org/)
  GNU/Linux
  ([stretch](https://packages.debian.org/source/stretch/cppformat),
  [sid](https://packages.debian.org/source/sid/cppformat)) and derived
  distributions such as
  [Ubuntu](https://launchpad.net/ubuntu/+source/cppformat) 15.10 and
  later (https://github.com/fmtlib/fmt/issues/155):

      $ sudo apt-get install libcppformat1-dev

  Thanks @jackyf.

- [Packages for Fedora and
  RHEL](https://admin.fedoraproject.org/pkgdb/package/cppformat/) are
  now available. Thanks Dave Johansen.

- C++ Format can now be installed via [Homebrew](http://brew.sh/) on
  OS X (https://github.com/fmtlib/fmt/issues/157):

      $ brew install cppformat

  Thanks @ortho and Anatoliy Bulukin.

## Documentation

- Migrated from ReadTheDocs to GitHub Pages for better responsiveness
  and reliability (https://github.com/fmtlib/fmt/issues/128).
  New documentation address is <http://cppformat.github.io/>.
- Added [Building thedocumentation](
  https://fmt.dev/2.0.0/usage.html#building-the-documentation)
  section to the documentation.
- Documentation build script is now compatible with Python 3 and newer
  pip versions. (https://github.com/fmtlib/fmt/pull/189,
  https://github.com/fmtlib/fmt/issues/209).
  Thanks @JodiTheTigger and @xentec.
- Documentation fixes and improvements
  (https://github.com/fmtlib/fmt/issues/36,
  https://github.com/fmtlib/fmt/issues/75,
  https://github.com/fmtlib/fmt/issues/125,
  https://github.com/fmtlib/fmt/pull/160,
  https://github.com/fmtlib/fmt/pull/161,
  https://github.com/fmtlib/fmt/issues/162,
  https://github.com/fmtlib/fmt/issues/165,
  https://github.com/fmtlib/fmt/issues/210). 
  Thanks @syohex.
- Fixed out-of-tree documentation build
  (https://github.com/fmtlib/fmt/issues/177). Thanks @jackyf.

## Fixes

- Fixed `initializer_list` detection
  (https://github.com/fmtlib/fmt/issues/136). Thanks @Gachapen.

- \[Breaking\] Fixed formatting of enums with numeric format
  specifiers in `fmt::(s)printf`
  (https://github.com/fmtlib/fmt/issues/131,
  https://github.com/fmtlib/fmt/issues/139):

  ```c++
  enum { ANSWER = 42 };
  fmt::printf("%d", ANSWER);
  ```

  Thanks @Naios.

- Improved compatibility with old versions of MinGW
  (https://github.com/fmtlib/fmt/issues/129,
  https://github.com/fmtlib/fmt/pull/130,
  https://github.com/fmtlib/fmt/issues/132). Thanks @cstamford.

- Fixed a compile error on MSVC with disabled exceptions
  (https://github.com/fmtlib/fmt/issues/144).

- Added a workaround for broken implementation of variadic templates
  in MSVC2012 (https://github.com/fmtlib/fmt/issues/148).

- Placed the anonymous namespace within `fmt` namespace for the
  header-only configuration (https://github.com/fmtlib/fmt/issues/171).
  Thanks @alfps.

- Fixed issues reported by Coverity Scan
  (https://github.com/fmtlib/fmt/issues/187,
  https://github.com/fmtlib/fmt/issues/192).

- Implemented a workaround for a name lookup bug in MSVC2010
  (https://github.com/fmtlib/fmt/issues/188).

- Fixed compiler warnings
  (https://github.com/fmtlib/fmt/issues/95,
  https://github.com/fmtlib/fmt/issues/96,
  https://github.com/fmtlib/fmt/pull/114,
  https://github.com/fmtlib/fmt/issues/135,
  https://github.com/fmtlib/fmt/issues/142,
  https://github.com/fmtlib/fmt/issues/145,
  https://github.com/fmtlib/fmt/issues/146,
  https://github.com/fmtlib/fmt/issues/158,
  https://github.com/fmtlib/fmt/issues/163,
  https://github.com/fmtlib/fmt/issues/175,
  https://github.com/fmtlib/fmt/issues/190,
  https://github.com/fmtlib/fmt/pull/191,
  https://github.com/fmtlib/fmt/issues/194,
  https://github.com/fmtlib/fmt/pull/196,
  https://github.com/fmtlib/fmt/issues/216,
  https://github.com/fmtlib/fmt/pull/218,
  https://github.com/fmtlib/fmt/pull/220,
  https://github.com/fmtlib/fmt/pull/229,
  https://github.com/fmtlib/fmt/issues/233,
  https://github.com/fmtlib/fmt/issues/234,
  https://github.com/fmtlib/fmt/pull/236,
  https://github.com/fmtlib/fmt/issues/281,
  https://github.com/fmtlib/fmt/issues/289).
  Thanks @seanmiddleditch, @dixlorenz, @CarterLi, @Naios, @fmatthew5876,
  @LevskiWeng, @rpopescu, @gabime, @cubicool, @jkflying, @LogicalKnight,
  @inguin and @Jopie64.

- Fixed portability issues (mostly causing test failures) on ARM,
  ppc64, ppc64le, s390x and SunOS 5.11 i386
  (https://github.com/fmtlib/fmt/issues/138,
  https://github.com/fmtlib/fmt/issues/179,
  https://github.com/fmtlib/fmt/issues/180,
  https://github.com/fmtlib/fmt/issues/202,
  https://github.com/fmtlib/fmt/issues/225, [Red Hat Bugzilla
  Bug 1260297](https://bugzilla.redhat.com/show_bug.cgi?id=1260297)).
  Thanks @Naios, @jackyf and Dave Johansen.

- Fixed a name conflict with macro `free` defined in `crtdbg.h` when
  `_CRTDBG_MAP_ALLOC` is set (https://github.com/fmtlib/fmt/issues/211).

- Fixed shared library build on OS X
  (https://github.com/fmtlib/fmt/pull/212). Thanks @dean0x7d.

- Fixed an overload conflict on MSVC when `/Zc:wchar_t-` option is
  specified (https://github.com/fmtlib/fmt/pull/214).
  Thanks @slavanap.

- Improved compatibility with MSVC 2008
  (https://github.com/fmtlib/fmt/pull/236). Thanks @Jopie64.

- Improved compatibility with bcc32
  (https://github.com/fmtlib/fmt/issues/227).

- Fixed `static_assert` detection on Clang
  (https://github.com/fmtlib/fmt/pull/228). Thanks @dean0x7d.

# 1.1.0 - 2015-03-06

- Added `BasicArrayWriter`, a class template that provides operations
  for formatting and writing data into a fixed-size array
  (https://github.com/fmtlib/fmt/issues/105 and
  https://github.com/fmtlib/fmt/issues/122):

  ```c++
  char buffer[100];
  fmt::ArrayWriter w(buffer);
  w.write("The answer is {}", 42);
  ```

- Added [0 A.D.](http://play0ad.com/) and [PenUltima Online
  (POL)](http://www.polserver.com/) to the list of notable projects
  using C++ Format.

- C++ Format now uses MSVC intrinsics for better formatting performance
  (https://github.com/fmtlib/fmt/pull/115,
  https://github.com/fmtlib/fmt/pull/116,
  https://github.com/fmtlib/fmt/pull/118 and
  https://github.com/fmtlib/fmt/pull/121). Previously these
  optimizations where only used on GCC and Clang.
  Thanks @CarterLi and @objectx.

- CMake install target
  (https://github.com/fmtlib/fmt/pull/119). Thanks @TrentHouliston.

  You can now install C++ Format with `make install` command.

- Improved [Biicode](http://www.biicode.com/) support
  (https://github.com/fmtlib/fmt/pull/98 and
  https://github.com/fmtlib/fmt/pull/104).
  Thanks @MariadeAnton and @franramirez688.

- Improved support for building with [Android NDK](
  https://developer.android.com/tools/sdk/ndk/index.html)
  (https://github.com/fmtlib/fmt/pull/107). Thanks @newnon.

  The [android-ndk-example](https://github.com/fmtlib/android-ndk-example)
  repository provides and example of using C++ Format with Android NDK:

  

- Improved documentation of `SystemError` and `WindowsError`
  (https://github.com/fmtlib/fmt/issues/54).

- Various code improvements
  (https://github.com/fmtlib/fmt/pull/110,
  https://github.com/fmtlib/fmt/pull/111
  https://github.com/fmtlib/fmt/pull/112). Thanks @CarterLi.

- Improved compile-time errors when formatting wide into narrow
  strings (https://github.com/fmtlib/fmt/issues/117).

- Fixed `BasicWriter::write` without formatting arguments when C++11
  support is disabled
  (https://github.com/fmtlib/fmt/issues/109).

- Fixed header-only build on OS X with GCC 4.9
  (https://github.com/fmtlib/fmt/issues/124).

- Fixed packaging issues (https://github.com/fmtlib/fmt/issues/94).

- Added [changelog](https://github.com/fmtlib/fmt/blob/master/ChangeLog.md)
  (https://github.com/fmtlib/fmt/issues/103).

# 1.0.0 - 2015-02-05

- Add support for a header-only configuration when `FMT_HEADER_ONLY`
  is defined before including `format.h`:

  ```c++
  #define FMT_HEADER_ONLY
  #include "format.h"
  ```

- Compute string length in the constructor of `BasicStringRef` instead
  of the `size` method
  (https://github.com/fmtlib/fmt/issues/79). This eliminates
  size computation for string literals on reasonable optimizing
  compilers.

- Fix formatting of types with overloaded `operator <<` for
  `std::wostream` (https://github.com/fmtlib/fmt/issues/86):

  ```c++
  fmt::format(L"The date is {0}", Date(2012, 12, 9));
  ```

- Fix linkage of tests on Arch Linux
  (https://github.com/fmtlib/fmt/issues/89).

- Allow precision specifier for non-float arguments
  (https://github.com/fmtlib/fmt/issues/90):

  ```c++
  fmt::print("{:.3}\n", "Carpet"); // prints "Car"
  ```

- Fix build on Android NDK (https://github.com/fmtlib/fmt/issues/93).

- Improvements to documentation build procedure.

- Remove `FMT_SHARED` CMake variable in favor of standard [BUILD_SHARED_LIBS](
  http://www.cmake.org/cmake/help/v3.0/variable/BUILD_SHARED_LIBS.html).

- Fix error handling in `fmt::fprintf`.

- Fix a number of warnings.

# 0.12.0 - 2014-10-25

- \[Breaking\] Improved separation between formatting and buffer
  management. `Writer` is now a base class that cannot be instantiated
  directly. The new `MemoryWriter` class implements the default buffer
  management with small allocations done on stack. So `fmt::Writer`
  should be replaced with `fmt::MemoryWriter` in variable
  declarations.

  Old code:

  ```c++
  fmt::Writer w;
  ```

  New code:

  ```c++
  fmt::MemoryWriter w;
  ```

  If you pass `fmt::Writer` by reference, you can continue to do so:

  ```c++
  void f(fmt::Writer &w);
  ```

  This doesn\'t affect the formatting API.

- Support for custom memory allocators
  (https://github.com/fmtlib/fmt/issues/69)

- Formatting functions now accept [signed char]{.title-ref} and
  [unsigned char]{.title-ref} strings as arguments
  (https://github.com/fmtlib/fmt/issues/73):

  ```c++
  auto s = format("GLSL version: {}", glGetString(GL_VERSION));
  ```

- Reduced code bloat. According to the new [benchmark
  results](https://github.com/fmtlib/fmt#compile-time-and-code-bloat),
  cppformat is close to `printf` and by the order of magnitude better
  than Boost Format in terms of compiled code size.

- Improved appearance of the documentation on mobile by using the
  [Sphinx Bootstrap
  theme](http://ryan-roemer.github.io/sphinx-bootstrap-theme/):

  | Old | New |
  | --- | --- |
  |  |  |

# 0.11.0 - 2014-08-21

- Safe printf implementation with a POSIX extension for positional
  arguments:

  ```c++
  fmt::printf("Elapsed time: %.2f seconds", 1.23);
  fmt::printf("%1$s, %3$d %2$s", weekday, month, day);
  ```

- Arguments of `char` type can now be formatted as integers (Issue
  https://github.com/fmtlib/fmt/issues/55):

  ```c++
  fmt::format("0x{0:02X}", 'a');
  ```

- Deprecated parts of the API removed.

- The library is now built and tested on MinGW with Appveyor in
  addition to existing test platforms Linux/GCC, OS X/Clang,
  Windows/MSVC.

# 0.10.0 - 2014-07-01

**Improved API**

- All formatting methods are now implemented as variadic functions
  instead of using `operator<<` for feeding arbitrary arguments into a
  temporary formatter object. This works both with C++11 where
  variadic templates are used and with older standards where variadic
  functions are emulated by providing lightweight wrapper functions
  defined with the `FMT_VARIADIC` macro. You can use this macro for
  defining your own portable variadic functions:

  ```c++
  void report_error(const char *format, const fmt::ArgList &args) {
    fmt::print("Error: {}");
    fmt::print(format, args);
  }
  FMT_VARIADIC(void, report_error, const char *)

  report_error("file not found: {}", path);
  ```

  Apart from a more natural syntax, this also improves performance as
  there is no need to construct temporary formatter objects and
  control arguments\' lifetimes. Because the wrapper functions are
  very lightweight, this doesn\'t cause code bloat even in pre-C++11
  mode.

- Simplified common case of formatting an `std::string`. Now it
  requires a single function call:

  ```c++
  std::string s = format("The answer is {}.", 42);
  ```

  Previously it required 2 function calls:

  ```c++
  std::string s = str(Format("The answer is {}.") << 42);
  ```

  Instead of unsafe `c_str` function, `fmt::Writer` should be used
  directly to bypass creation of `std::string`:

  ```c++
  fmt::Writer w;
  w.write("The answer is {}.", 42);
  w.c_str();  // returns a C string
  ```

  This doesn\'t do dynamic memory allocation for small strings and is
  less error prone as the lifetime of the string is the same as for
  `std::string::c_str` which is well understood (hopefully).

- Improved consistency in naming functions that are a part of the
  public API. Now all public functions are lowercase following the
  standard library conventions. Previously it was a combination of
  lowercase and CapitalizedWords. Issue
  https://github.com/fmtlib/fmt/issues/50.

- Old functions are marked as deprecated and will be removed in the
  next release.

**Other Changes**

- Experimental support for printf format specifications (work in
  progress):

  ```c++
  fmt::printf("The answer is %d.", 42);
  std::string s = fmt::sprintf("Look, a %s!", "string");
  ```

- Support for hexadecimal floating point format specifiers `a` and
  `A`:

  ```c++
  print("{:a}", -42.0); // Prints -0x1.5p+5
  print("{:A}", -42.0); // Prints -0X1.5P+5
  ```

- CMake option `FMT_SHARED` that specifies whether to build format as
  a shared library (off by default).

# 0.9.0 - 2014-05-13

- More efficient implementation of variadic formatting functions.

- `Writer::Format` now has a variadic overload:

  ```c++
  Writer out;
  out.Format("Look, I'm {}!", "variadic");
  ```

- For efficiency and consistency with other overloads, variadic
  overload of the `Format` function now returns `Writer` instead of
  `std::string`. Use the `str` function to convert it to
  `std::string`:

  ```c++
  std::string s = str(Format("Look, I'm {}!", "variadic"));
  ```

- Replaced formatter actions with output sinks: `NoAction` -\>
  `NullSink`, `Write` -\> `FileSink`, `ColorWriter` -\>
  `ANSITerminalSink`. This improves naming consistency and shouldn\'t
  affect client code unless these classes are used directly which
  should be rarely needed.

- Added `ThrowSystemError` function that formats a message and throws
  `SystemError` containing the formatted message and system-specific
  error description. For example, the following code

  ```c++
  FILE *f = fopen(filename, "r");
  if (!f)
    ThrowSystemError(errno, "Failed to open file '{}'") << filename;
  ```

  will throw `SystemError` exception with description \"Failed to open
  file \'\<filename\>\': No such file or directory\" if file doesn\'t
  exist.

- Support for AppVeyor continuous integration platform.

- `Format` now throws `SystemError` in case of I/O errors.

- Improve test infrastructure. Print functions are now tested by
  redirecting the output to a pipe.

# 0.8.0 - 2014-04-14

- Initial release

---

### Vnext External Fmt Doc Api (`vnext/external/fmt/doc/api.md`)

# API Reference

The {fmt} library API consists of the following components:

- [`fmt/base.h`](#base-api): the base API providing main formatting functions
  for `char`/UTF-8 with C++20 compile-time checks and minimal dependencies
- [`fmt/format.h`](#format-api): `fmt::format` and other formatting functions
  as well as locale support
- [`fmt/ranges.h`](#ranges-api): formatting of ranges and tuples
- [`fmt/chrono.h`](#chrono-api): date and time formatting
- [`fmt/std.h`](#std-api): formatters for standard library types
- [`fmt/compile.h`](#compile-api): format string compilation
- [`fmt/color.h`](#color-api): terminal colors and text styles
- [`fmt/os.h`](#os-api): system APIs
- [`fmt/ostream.h`](#ostream-api): `std::ostream` support
- [`fmt/args.h`](#args-api): dynamic argument lists
- [`fmt/printf.h`](#printf-api): safe `printf`
- [`fmt/xchar.h`](#xchar-api): optional `wchar_t` support

All functions and types provided by the library reside in namespace `fmt`
and macros have prefix `FMT_`.

## Base API

`fmt/base.h` defines the base API which provides main formatting functions
for `char`/UTF-8 with C++20 compile-time checks. It has minimal include
dependencies for better compile times. This header is only beneficial when
using {fmt} as a library (the default) and not in the header-only mode.
It also provides `formatter` specializations for the following types:

- `int`, `long long`,
- `unsigned`, `unsigned long long`
- `float`, `double`, `long double`
- `bool`
- `char`
- `const char*`, [`fmt::string_view`](#basic_string_view)
- `const void*`

The following functions use [format string syntax](syntax.md) similar to that
of [str.format](https://docs.python.org/3/library/stdtypes.html#str.format)
in Python. They take *fmt* and *args* as arguments.

*fmt* is a format string that contains literal text and replacement fields
surrounded by braces `{}`. The fields are replaced with formatted arguments
in the resulting string. [`fmt::format_string`](#format_string) is a format
string which can be implicitly constructed from a string literal or a
`constexpr` string and is checked at compile time in C++20. To pass a runtime
format string wrap it in [`fmt::runtime`](#runtime).

*args* is an argument list representing objects to be formatted.

I/O errors are reported as [`std::system_error`](
https://en.cppreference.com/w/cpp/error/system_error) exceptions unless
specified otherwise.

::: print(format_string<T...>, T&&...)

::: print(FILE*, format_string<T...>, T&&...)

::: println(format_string<T...>, T&&...)

::: println(FILE*, format_string<T...>, T&&...)

::: format_to(OutputIt&&, format_string<T...>, T&&...)

::: format_to_n(OutputIt, size_t, format_string<T...>, T&&...)

::: format_to_n_result

::: formatted_size(format_string<T...>, T&&...)

<a id="udt"></a>
### Formatting User-Defined Types

The {fmt} library provides formatters for many standard C++ types.
See [`fmt/ranges.h`](#ranges-api) for ranges and tuples including standard
containers such as `std::vector`, [`fmt/chrono.h`](#chrono-api) for date and
time formatting and [`fmt/std.h`](#std-api) for other standard library types.

There are two ways to make a user-defined type formattable: providing a
`format_as` function or specializing the `formatter` struct template.

Use `format_as` if you want to make your type formattable as some other
type with the same format specifiers. The `format_as` function should
take an object of your type and return an object of a formattable type.
It should be defined in the same namespace as your type.

Example ([run](https://godbolt.org/z/nvME4arz8)):

    #include <fmt/format.h>

    namespace kevin_namespacy {

    enum class film {
      house_of_cards, american_beauty, se7en = 7
    };

    auto format_as(film f) { return fmt::underlying(f); }

    }

    int main() {
      fmt::print("{}\n", kevin_namespacy::film::se7en); // Output: 7
    }

Using specialization is more complex but gives you full control over
parsing and formatting. To use this method specialize the `formatter`
struct template for your type and implement `parse` and `format`
methods.

The recommended way of defining a formatter is by reusing an existing
one via inheritance or composition. This way you can support standard
format specifiers without implementing them yourself. For example:

```c++
// color.h:
#include <fmt/base.h>

enum class color {red, green, blue};

template <> struct fmt::formatter<color>: formatter<string_view> {
  // parse is inherited from formatter<string_view>.

  auto format(color c, format_context& ctx) const
    -> format_context::iterator;
};
```

```c++
// color.cc:
#include "color.h"
#include <fmt/format.h>

auto fmt::formatter<color>::format(color c, format_context& ctx) const
    -> format_context::iterator {
  string_view name = "unknown";
  switch (c) {
  case color::red:   name = "red"; break;
  case color::green: name = "green"; break;
  case color::blue:  name = "blue"; break;
  }
  return formatter<string_view>::format(name, ctx);
}
```

Note that `formatter<string_view>::format` is defined in `fmt/format.h`
so it has to be included in the source file. Since `parse` is inherited
from `formatter<string_view>` it will recognize all string format
specifications, for example

```c++
fmt::format("{:>10}", color::blue)
```

will return `"      blue"`.



In general the formatter has the following form:

    template <> struct fmt::formatter<T> {
      // Parses format specifiers and stores them in the formatter.
      //
      // [ctx.begin(), ctx.end()) is a, possibly empty, character range that
      // contains a part of the format string starting from the format
      // specifications to be parsed, e.g. in
      //
      //   fmt::format("{:f} continued", ...);
      //
      // the range will contain "f} continued". The formatter should parse
      // specifiers until '}' or the end of the range. In this example the
      // formatter should parse the 'f' specifier and return an iterator
      // pointing to '}'.
      constexpr auto parse(format_parse_context& ctx)
        -> format_parse_context::iterator;

      // Formats value using the parsed format specification stored in this
      // formatter and writes the output to ctx.out().
      auto format(const T& value, format_context& ctx) const
        -> format_context::iterator;
    };

It is recommended to at least support fill, align and width that apply
to the whole object and have the same semantics as in standard
formatters.

You can also write a formatter for a hierarchy of classes:

```c++
// demo.h:
#include <type_traits>
#include <fmt/core.h>

struct A {
  virtual ~A() {}
  virtual std::string name() const { return "A"; }
};

struct B : A {
  virtual std::string name() const { return "B"; }
};

template <typename T>
struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<A, T>, char>> :
    fmt::formatter<std::string> {
  auto format(const A& a, format_context& ctx) const {
    return formatter<std::string>::format(a.name(), ctx);
  }
};
```

```c++
// demo.cc:
#include "demo.h"
#include <fmt/format.h>

int main() {
  B b;
  A& a = b;
  fmt::print("{}", a); // Output: B
}
```

Providing both a `formatter` specialization and a `format_as` overload is
disallowed.

::: basic_format_parse_context

::: context

::: format_context

### Compile-Time Checks

Compile-time format string checks are enabled by default on compilers
that support C++20 `consteval`. On older compilers you can use the
[FMT_STRING](#legacy-checks) macro defined in `fmt/format.h` instead.

Unused arguments are allowed as in Python's `str.format` and ordinary functions.

::: basic_format_string

::: format_string

::: runtime(string_view)

### Named Arguments

::: arg(const Char*, const T&)

Named arguments are not supported in compile-time checks at the moment.

### Type Erasure

You can create your own formatting function with compile-time checks and
small binary footprint, for example ([run](https://godbolt.org/z/b9Pbasvzc)):

```c++
#include <fmt/format.h>

void vlog(const char* file, int line,
          fmt::string_view fmt, fmt::format_args args) {
  fmt::print("{}: {}: {}", file, line, fmt::vformat(fmt, args));
}

template <typename... T>
void log(const char* file, int line,
         fmt::format_string<T...> fmt, T&&... args) {
  vlog(file, line, fmt, fmt::make_format_args(args...));
}

#define MY_LOG(fmt, ...) log(__FILE__, __LINE__, fmt, __VA_ARGS__)

MY_LOG("invalid squishiness: {}", 42);
```

Note that `vlog` is not parameterized on argument types which improves
compile times and reduces binary code size compared to a fully
parameterized version.

::: make_format_args(T&...)

::: basic_format_args

::: format_args

::: basic_format_arg

### Compatibility

::: basic_string_view

::: string_view

## Format API

`fmt/format.h` defines the full format API providing additional
formatting functions and locale support.

<a id="format"></a>
::: format(format_string<T...>, T&&...)

::: vformat(string_view, format_args)

::: operator""_a()

### Utilities

::: ptr(T)

::: underlying(Enum)

::: to_string(const T&)

::: group_digits(T)

::: detail::buffer

::: basic_memory_buffer

### System Errors

{fmt} does not use `errno` to communicate errors to the user, but it may
call system functions which set `errno`. Users should not make any
assumptions about the value of `errno` being preserved by library
functions.

::: system_error

::: format_system_error

### Custom Allocators

The {fmt} library supports custom dynamic memory allocators. A custom
allocator class can be specified as a template argument to
[`fmt::basic_memory_buffer`](#basic_memory_buffer):

    using custom_memory_buffer = 
      fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;

It is also possible to write a formatting function that uses a custom
allocator:

    using custom_string =
      std::basic_string<char, std::char_traits<char>, custom_allocator>;

    custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
                          fmt::format_args args) {
      auto buf = custom_memory_buffer(alloc);
      fmt::vformat_to(std::back_inserter(buf), format_str, args);
      return custom_string(buf.data(), buf.size(), alloc);
    }

    template <typename ...Args>
    inline custom_string format(custom_allocator alloc,
                                fmt::string_view format_str,
                                const Args& ... args) {
      return vformat(alloc, format_str, fmt::make_format_args(args...));
    }

The allocator will be used for the output container only. Formatting
functions normally don't do any allocations for built-in and string
types except for non-default floating-point formatting that occasionally
falls back on `sprintf`.

### Locale

All formatting is locale-independent by default. Use the `'L'` format
specifier to insert the appropriate number separator characters from the
locale:

    #include <fmt/core.h>
    #include <locale>

    std::locale::global(std::locale("en_US.UTF-8"));
    auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"

`fmt/format.h` provides the following overloads of formatting functions
that take `std::locale` as a parameter. The locale type is a template
parameter to avoid the expensive `<locale>` include.

::: format(const Locale&, format_string<T...>, T&&...)

::: format_to(OutputIt, const Locale&, format_string<T...>, T&&...)

::: formatted_size(const Locale&, format_string<T...>, T&&...)

<a id="legacy-checks"></a>
### Legacy Compile-Time Checks

`FMT_STRING` enables compile-time checks on older compilers. It requires
C++14 or later and is a no-op in C++11.

::: FMT_STRING

To force the use of legacy compile-time checks, define the preprocessor
variable `FMT_ENFORCE_COMPILE_STRING`. When set, functions accepting
`FMT_STRING` will fail to compile with regular strings.

<a id="ranges-api"></a>
## Range and Tuple Formatting

`fmt/ranges.h` provides formatting support for ranges and tuples:

    #include <fmt/ranges.h>

    fmt::print("{}", std::tuple<char, int>{'a', 42});
    // Output: ('a', 42)

Using `fmt::join`, you can separate tuple elements with a custom separator:

    #include <fmt/ranges.h>

    auto t = std::tuple<int, char>{1, 'a'};
    fmt::print("{}", fmt::join(t, ", "));
    // Output: 1, a

::: join(Range&&, string_view)

::: join(It, Sentinel, string_view)

::: join(std::initializer_list<T>, string_view)

<a id="chrono-api"></a>
## Date and Time Formatting

`fmt/chrono.h` provides formatters for

- [`std::chrono::duration`](https://en.cppreference.com/w/cpp/chrono/duration)
- [`std::chrono::time_point`](
  https://en.cppreference.com/w/cpp/chrono/time_point)
- [`std::tm`](https://en.cppreference.com/w/cpp/chrono/c/tm)

The format syntax is described in [Chrono Format Specifications](syntax.md#
chrono-format-specifications).

**Example**:

    #include <fmt/chrono.h>

    int main() {
      std::time_t t = std::time(nullptr);

      fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
      // Output: The date is 2020-11-07.
      // (with 2020-11-07 replaced by the current date)

      using namespace std::literals::chrono_literals;

      fmt::print("Default format: {} {}\n", 42s, 100ms);
      // Output: Default format: 42s 100ms

      fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
      // Output: strftime-like format: 03:15:30
    }

::: localtime(std::time_t)

::: gmtime(std::time_t)

<a id="std-api"></a>
## Standard Library Types Formatting

`fmt/std.h` provides formatters for:

- [`std::atomic`](https://en.cppreference.com/w/cpp/atomic/atomic)
- [`std::atomic_flag`](https://en.cppreference.com/w/cpp/atomic/atomic_flag)
- [`std::bitset`](https://en.cppreference.com/w/cpp/utility/bitset)
- [`std::error_code`](https://en.cppreference.com/w/cpp/error/error_code)
- [`std::filesystem::path`](https://en.cppreference.com/w/cpp/filesystem/path)
- [`std::monostate`](https://en.cppreference.com/w/cpp/utility/variant/monostate)
- [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional)
- [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location)
- [`std::thread::id`](https://en.cppreference.com/w/cpp/thread/thread/id)
- [`std::variant`](https://en.cppreference.com/w/cpp/utility/variant/variant)

::: ptr(const std::unique_ptr<T, Deleter>&)

::: ptr(const std::shared_ptr<T>&)

### Formatting Variants

A `std::variant` is only formattable if every variant alternative is
formattable, and requires the `__cpp_lib_variant` [library
feature](https://en.cppreference.com/w/cpp/feature_test).

**Example**:

    #include <fmt/std.h>

    fmt::print("{}", std::variant<char, float>('x'));
    // Output: variant('x')

    fmt::print("{}", std::variant<std::monostate, char>());
    // Output: variant(monostate)

<a id="compile-api"></a>
## Format String Compilation

`fmt/compile.h` provides format string compilation enabled via the
`FMT_COMPILE` macro or the `_cf` user-defined literal defined in
namespace `fmt::literals`. Format strings marked with `FMT_COMPILE`
or `_cf` are parsed, checked and converted into efficient formatting
code at compile-time. This supports arguments of built-in and string
types as well as user-defined types with `format` functions taking
the format context type as a template parameter in their `formatter`
specializations. For example:

    template <> struct fmt::formatter<point> {
      constexpr auto parse(format_parse_context& ctx);

      template <typename FormatContext>
      auto format(const point& p, FormatContext& ctx) const;
    };

Format string compilation can generate more binary code compared to the
default API and is only recommended in places where formatting is a
performance bottleneck.

::: FMT_COMPILE

::: operator""_cf

<a id="color-api"></a>
## Terminal Colors and Text Styles

`fmt/color.h` provides support for terminal color and text style output.

::: print(const text_style&, format_string<T...>, T&&...)

::: fg(detail::color_type)

::: bg(detail::color_type)

::: styled(const T&, text_style)

<a id="os-api"></a>
## System APIs

::: ostream

::: windows_error

<a id="ostream-api"></a>
## `std::ostream` Support

`fmt/ostream.h` provides `std::ostream` support including formatting of
user-defined types that have an overloaded insertion operator
(`operator<<`). In order to make a type formattable via `std::ostream`
you should provide a `formatter` specialization inherited from
`ostream_formatter`:

    #include <fmt/ostream.h>

    struct date {
      int year, month, day;

      friend std::ostream& operator<<(std::ostream& os, const date& d) {
        return os << d.year << '-' << d.month << '-' << d.day;
      }
    };

    template <> struct fmt::formatter<date> : ostream_formatter {};

    std::string s = fmt::format("The date is {}", date{2012, 12, 9});
    // s == "The date is 2012-12-9"

::: streamed(const T&)

::: print(std::ostream&, format_string<T...>, T&&...)

<a id="args-api"></a>
## Dynamic Argument Lists

The header `fmt/args.h` provides `dynamic_format_arg_store`, a builder-like API
that can be used to construct format argument lists dynamically.

::: dynamic_format_arg_store

<a id="printf-api"></a>
## Safe `printf`

The header `fmt/printf.h` provides `printf`-like formatting
functionality. The following functions use [printf format string
syntax](https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html)
with the POSIX extension for positional arguments. Unlike their standard
counterparts, the `fmt` functions are type-safe and throw an exception
if an argument type doesn't match its format specification.

::: printf(string_view, const T&...)

::: fprintf(std::FILE*, const S&, const T&...)

::: sprintf(const S&, const T&...)

<a id="xchar-api"></a>
## Wide Strings

The optional header `fmt/xchar.h` provides support for `wchar_t` and
exotic character types.

::: is_char

::: wstring_view

::: wformat_context

::: to_wstring(const T&)

## Compatibility with C++20 `std::format`

{fmt} implements nearly all of the [C++20 formatting
library](https://en.cppreference.com/w/cpp/utility/format) with the
following differences:

- Names are defined in the `fmt` namespace instead of `std` to avoid
  collisions with standard library implementations.
- Width calculation doesn't use grapheme clusterization. The latter has
  been implemented in a separate branch but hasn't been integrated yet.

---

### Vnext External Fmt Doc Get Started (`vnext/external/fmt/doc/get-started.md`)

# Get Started

Compile and run {fmt} examples online with [Compiler Explorer](
https://godbolt.org/z/P7h6cd6o3).

{fmt} is compatible with any build system. The next section describes its usage
with CMake, while the [Build Systems](#build-systems) section covers the rest.

## CMake

{fmt} provides two CMake targets: `fmt::fmt` for the compiled library and
`fmt::fmt-header-only` for the header-only library. It is recommended to use
the compiled library for improved build times.

There are three primary ways to use {fmt} with CMake:

* **FetchContent**: Starting from CMake 3.11, you can use [`FetchContent`](
  https://cmake.org/cmake/help/v3.30/module/FetchContent.html) to automatically
  download {fmt} as a dependency at configure time:

        include(FetchContent)

        FetchContent_Declare(
          fmt
          GIT_REPOSITORY https://github.com/fmtlib/fmt
          GIT_TAG        e69e5f977d458f2650bb346dadf2ad30c5320281) # 10.2.1
        FetchContent_MakeAvailable(fmt)

        target_link_libraries(<your-target> fmt::fmt)

* **Installed**: You can find and use an [installed](#installation) version of
  {fmt} in your `CMakeLists.txt` file as follows:

        find_package(fmt)
        target_link_libraries(<your-target> fmt::fmt)

* **Embedded**: You can add the {fmt} source tree to your project and include it
  in your `CMakeLists.txt` file:

        add_subdirectory(fmt)
        target_link_libraries(<your-target> fmt::fmt)

## Installation

### Debian/Ubuntu

To install {fmt} on Debian, Ubuntu, or any other Debian-based Linux
distribution, use the following command:

    apt install libfmt-dev

### Homebrew

Install {fmt} on macOS using [Homebrew](https://brew.sh/):

    brew install fmt

### Conda

Install {fmt} on Linux, macOS, and Windows with [Conda](
https://docs.conda.io/en/latest/), using its [conda-forge package](
https://github.com/conda-forge/fmt-feedstock):

    conda install -c conda-forge fmt

### vcpkg

Download and install {fmt} using the vcpkg package manager:

    git clone https://github.com/Microsoft/vcpkg.git
    cd vcpkg
    ./bootstrap-vcpkg.sh
    ./vcpkg integrate install
    ./vcpkg install fmt



## Building from Source

CMake works by generating native makefiles or project files that can be
used in the compiler environment of your choice. The typical workflow
starts with:

    mkdir build  # Create a directory to hold the build output.
    cd build
    cmake ..     # Generate native build scripts.

run in the `fmt` repository.

If you are on a Unix-like system, you should now see a Makefile in the
current directory. Now you can build the library by running `make`.

Once the library has been built you can invoke `make test` to run the tests.

You can control generation of the make `test` target with the `FMT_TEST`
CMake option. This can be useful if you include fmt as a subdirectory in
your project but don't want to add fmt's tests to your `test` target.

To build a shared library set the `BUILD_SHARED_LIBS` CMake variable to `TRUE`:

    cmake -DBUILD_SHARED_LIBS=TRUE ..

To build a static library with position-independent code (e.g. for
linking it into another shared library such as a Python extension), set the
`CMAKE_POSITION_INDEPENDENT_CODE` CMake variable to `TRUE`:

    cmake -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE ..

After building the library you can install it on a Unix-like system by
running `sudo make install`.

### Building the Docs

To build the documentation you need the following software installed on
your system:

- [Python](https://www.python.org/)
- [Doxygen](http://www.stack.nl/~dimitri/doxygen/)
- [MkDocs](https://www.mkdocs.org/) with `mkdocs-material`, `mkdocstrings`,
  `pymdown-extensions` and `mike`

First generate makefiles or project files using CMake as described in
the previous section. Then compile the `doc` target/project, for example:

    make doc

This will generate the HTML documentation in `doc/html`.

## Build Systems

### build2

You can use [build2](https://build2.org), a dependency manager and a build
system, to use {fmt}.

Currently this package is available in these package repositories:

- <https://cppget.org/fmt/> for released and published versions.
- <https://github.com/build2-packaging/fmt> for unreleased or custom versions.

**Usage:**

- `build2` package name: `fmt`
- Library target name: `lib{fmt}`

To make your `build2` project depend on `fmt`:

- Add one of the repositories to your configurations, or in your
  `repositories.manifest`, if not already there:

        :
        role: prerequisite
        location: https://pkg.cppget.org/1/stable

- Add this package as a dependency to your `manifest` file (example
  for version 10):

        depends: fmt ~10.0.0

- Import the target and use it as a prerequisite to your own target
  using `fmt` in the appropriate `buildfile`:

        import fmt = fmt%lib{fmt}
        lib{mylib} : cxx{**} ... $fmt

Then build your project as usual with `b` or `bdep update`.

### Meson

[Meson WrapDB](https://mesonbuild.com/Wrapdb-projects.html) includes an `fmt`
package.

**Usage:**

- Install the `fmt` subproject from the WrapDB by running:

        meson wrap install fmt

  from the root of your project.

- In your project's `meson.build` file, add an entry for the new subproject:

        fmt = subproject('fmt')
        fmt_dep = fmt.get_variable('fmt_dep')

- Include the new dependency object to link with fmt:

        my_build_target = executable(
          'name', 'src/main.cc', dependencies: [fmt_dep])

**Options:**

If desired, {fmt} can be built as a static library, or as a header-only library.

For a static build, use the following subproject definition:

    fmt = subproject('fmt', default_options: 'default_library=static')
    fmt_dep = fmt.get_variable('fmt_dep')

For the header-only version, use:

    fmt = subproject('fmt')
    fmt_dep = fmt.get_variable('fmt_header_only_dep')

### Android NDK

{fmt} provides [Android.mk file](
https://github.com/fmtlib/fmt/blob/master/support/Android.mk) that can be used
to build the library with [Android NDK](
https://developer.android.com/tools/sdk/ndk/index.html).

### Other

To use the {fmt} library with any other build system, add
`include/fmt/base.h`, `include/fmt/format.h`, `include/fmt/format-inl.h`,
`src/format.cc` and optionally other headers from a [release archive](
https://github.com/fmtlib/fmt/releases) or the [git repository](
https://github.com/fmtlib/fmt) to your project, add `include` to include
directories and make sure `src/format.cc` is compiled and linked with your code.

---

### Vnext External Fmt Doc Python License (`vnext/external/fmt/doc/python-license.txt`)

A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.

In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
year, the PythonLabs team moved to Digital Creations (now Zope
Corporation, see http://www.zope.com).  In 2001, the Python Software
Foundation (PSF, see http://www.python.org/psf/) was formed, a
non-profit organization created specifically to own Python-related
Intellectual Property.  Zope Corporation is a sponsoring member of
the PSF.

All Python releases are Open Source (see http://www.opensource.org for
the Open Source Definition).  Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.

    Release         Derived     Year        Owner       GPL-
                    from                                compatible? (1)

    0.9.0 thru 1.2              1991-1995   CWI         yes
    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
    1.6             1.5.2       2000        CNRI        no
    2.0             1.6         2000        BeOpen.com  no
    1.6.1           1.6         2001        CNRI        yes (2)
    2.1             2.0+1.6.1   2001        PSF         no
    2.0.1           2.0+1.6.1   2001        PSF         yes
    2.1.1           2.1+2.0.1   2001        PSF         yes
    2.2             2.1.1       2001        PSF         yes
    2.1.2           2.1.1       2002        PSF         yes
    2.1.3           2.1.2       2002        PSF         yes
    2.2.1           2.2         2002        PSF         yes
    2.2.2           2.2.1       2002        PSF         yes
    2.2.3           2.2.2       2003        PSF         yes
    2.3             2.2.2       2002-2003   PSF         yes
    2.3.1           2.3         2002-2003   PSF         yes
    2.3.2           2.3.1       2002-2003   PSF         yes
    2.3.3           2.3.2       2002-2003   PSF         yes
    2.3.4           2.3.3       2004        PSF         yes
    2.3.5           2.3.4       2005        PSF         yes
    2.4             2.3         2004        PSF         yes
    2.4.1           2.4         2005        PSF         yes
    2.4.2           2.4.1       2005        PSF         yes
    2.4.3           2.4.2       2006        PSF         yes
    2.4.4           2.4.3       2006        PSF         yes
    2.5             2.4         2006        PSF         yes
    2.5.1           2.5         2007        PSF         yes
    2.5.2           2.5.1       2008        PSF         yes
    2.5.3           2.5.2       2008        PSF         yes
    2.6             2.5         2008        PSF         yes
    2.6.1           2.6         2008        PSF         yes
    2.6.2           2.6.1       2009        PSF         yes
    2.6.3           2.6.2       2009        PSF         yes
    2.6.4           2.6.3       2009        PSF         yes
    2.6.5           2.6.4       2010        PSF         yes
    3.0             2.6         2008        PSF         yes
    3.0.1           3.0         2009        PSF         yes
    3.1             3.0.1       2009        PSF         yes
    3.1.1           3.1         2009        PSF         yes
    3.1.2           3.1.1       2010        PSF         yes
    3.1.3           3.1.2       2010        PSF         yes
    3.1.4           3.1.3       2011        PSF         yes
    3.2             3.1         2011        PSF         yes
    3.2.1           3.2         2011        PSF         yes
    3.2.2           3.2.1       2011        PSF         yes
    3.2.3           3.2.2       2012        PSF         yes
    3.3.0           3.2         2012        PSF         yes

Footnotes:

(1) GPL-compatible doesn't mean that we're distributing Python under
    the GPL.  All Python licenses, unlike the GPL, let you distribute
    a modified version without making your changes open source.  The
    GPL-compatible licenses make it possible to combine Python with
    other software that is released under the GPL; the others don't.

(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
    because its license has a choice of law clause.  According to
    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
    is "not incompatible" with the GPL.

Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.


B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================

PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------

1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012 Python Software Foundation; All Rights Reserved" are retained in Python
alone or in any derivative version prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS"
basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee.  This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.

8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.


BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------

BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS"
basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions.  Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee.  This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party.  As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.

7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.


CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------

1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee.  Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement.  This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013.  This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".

3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee.  This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.

8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.

        ACCEPT


CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------

Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

---

### Vnext External Fmt Doc Syntax (`vnext/external/fmt/doc/syntax.md`)

# Format String Syntax

Formatting functions such as [`fmt::format`](api.md#format) and [`fmt::print`](
api.md#print) use the same format string syntax described in this section.

Format strings contain "replacement fields" surrounded by curly braces `{}`.
Anything that is not contained in braces is considered literal text, which is
copied unchanged to the output. If you need to include a brace character in
the literal text, it can be escaped by doubling: `{{` and `}}`.

The grammar for a replacement field is as follows:

<a id="replacement-field"></a>
<pre><code class="language-json"
>replacement_field ::= "{" [arg_id] [":" (<a href="#format-spec"
  >format_spec</a> | <a href="#chrono-format-spec">chrono_format_spec</a>)] "}"
arg_id            ::= integer | identifier
integer           ::= digit+
digit             ::= "0"..."9"
identifier        ::= id_start id_continue*
id_start          ::= "a"..."z" | "A"..."Z" | "_"
id_continue       ::= id_start | digit</code>
</pre>

In less formal terms, the replacement field can start with an *arg_id* that
specifies the argument whose value is to be formatted and inserted into the
output instead of the replacement field. The *arg_id* is optionally followed
by a *format_spec*, which is preceded by a colon `':'`. These specify a
non-default format for the replacement value.

See also the [Format Specification
Mini-Language](#format-specification-mini-language) section.

If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence,
they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be
automatically inserted in that order.

Named arguments can be referred to by their names or indices.

Some simple format string examples:

```c++
"First, thou shalt count to {0}" // References the first argument
"Bring me a {}"                  // Implicitly references the first argument
"From {} to {}"                  // Same as "From {0} to {1}"
```

The *format_spec* field contains a specification of how the value should
be presented, including such details as field width, alignment, padding,
decimal precision and so on. Each value type can define its own
"formatting mini-language" or interpretation of the *format_spec*.

Most built-in types support a common formatting mini-language, which is
described in the next section.

A *format_spec* field can also include nested replacement fields in
certain positions within it. These nested replacement fields can contain
only an argument id; format specifications are not allowed. This allows
the formatting of a value to be dynamically specified.

See the [Format Examples](#format-examples) section for some examples.

## Format Specification Mini-Language

"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented. Each formattable
type may define how the format specification is to be interpreted.

Most built-in types implement the following options for format
specifications, although some of the formatting options are only
supported by the numeric types.

The general form of a *standard format specifier* is:

<a id="format-spec"></a>
<pre><code class="language-json"
>format_spec ::= [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type]
fill        ::= &lt;a character other than '{' or '}'>
align       ::= "<" | ">" | "^"
sign        ::= "+" | "-" | " "
width       ::= <a href="#replacement-field">integer</a> | "{" [<a
  href="#replacement-field">arg_id</a>] "}"
precision   ::= <a href="#replacement-field">integer</a> | "{" [<a
  href="#replacement-field">arg_id</a>] "}"
type        ::= "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" |
                "g" | "G" | "o" | "p" | "s" | "x" | "X" | "?"</code>
</pre>

The *fill* character can be any Unicode code point other than `'{'` or `'}'`.
The presence of a fill character is signaled by the character following it,
which must be one of the alignment options. If the second character of
*format_spec* is not a valid alignment option, then it is assumed that both
the fill character and the alignment option are absent.

The meaning of the various alignment options is as follows:

<table>
<tr>
  <th>Option</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'<'</code></td>
  <td>
    Forces the field to be left-aligned within the available space (this is the
    default for most objects).
  </td>
</tr>
<tr>
  <td><code>'>'</code></td>
  <td>
    Forces the field to be right-aligned within the available space (this is
    the default for numbers).
  </td>
</tr>
<tr>
  <td><code>'^'</code></td>
  <td>Forces the field to be centered within the available space.</td>
</tr>
</table>

Note that unless a minimum field width is defined, the field width will
always be the same size as the data to fill it, so that the alignment
option has no meaning in this case.

The *sign* option is only valid for floating point and signed integer types,
and can be one of the following:

<table>
<tr>
  <th>Option</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'+'</code></td>
  <td>
    Indicates that a sign should be used for both nonnegative as well as
    negative numbers.
  </td>
</tr>
<tr>
  <td><code>'-'</code></td>
  <td>
    Indicates that a sign should be used only for negative numbers (this is the
    default behavior).
  </td>
</tr>
<tr>
  <td>space</td>
  <td>
    Indicates that a leading space should be used on nonnegative numbers, and a
    minus sign on negative numbers.
  </td>
</tr>
</table>

The `'#'` option causes the "alternate form" to be used for the
conversion. The alternate form is defined differently for different
types. This option is only valid for integer and floating-point types.
For integers, when binary, octal, or hexadecimal output is used, this
option adds the prefix respective `"0b"` (`"0B"`), `"0"`, or `"0x"`
(`"0X"`) to the output value. Whether the prefix is lower-case or
upper-case is determined by the case of the type specifier, for example,
the prefix `"0x"` is used for the type `'x'` and `"0X"` is used for
`'X'`. For floating-point numbers the alternate form causes the result
of the conversion to always contain a decimal-point character, even if
no digits follow it. Normally, a decimal-point character appears in the
result of these conversions only if a digit follows it. In addition, for
`'g'` and `'G'` conversions, trailing zeros are not removed from the
result.

*width* is a decimal integer defining the minimum field width. If not
specified, then the field width will be determined by the content.

Preceding the *width* field by a zero (`'0'`) character enables
sign-aware zero-padding for numeric types. It forces the padding to be
placed after the sign or base (if any) but before the digits. This is
used for printing fields in the form "+000000120". This option is only
valid for numeric types and it has no effect on formatting of infinity
and NaN. This option is ignored when any alignment specifier is present.

The *precision* is a decimal number indicating how many digits should be
displayed after the decimal point for a floating-point value formatted
with `'f'` and `'F'`, or before and after the decimal point for a
floating-point value formatted with `'g'` or `'G'`. For non-number types
the field indicates the maximum field size - in other words, how many
characters will be used from the field content. The *precision* is not
allowed for integer, character, Boolean, and pointer values. Note that a
C string must be null-terminated even if precision is specified.

The `'L'` option uses the current locale setting to insert the appropriate
number separator characters. This option is only valid for numeric types.

Finally, the *type* determines how the data should be presented.

The available string presentation types are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'s'</code></td>
  <td>
    String format. This is the default type for strings and may be omitted.
  </td>
</tr>
<tr>
  <td><code>'?'</code></td>
  <td>Debug format. The string is quoted and special characters escaped.</td>
</tr>
<tr>
  <td>none</td>
  <td>The same as <code>'s'</code>.</td>
</tr>
</table>

The available character presentation types are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'c'</code></td>
  <td>
    Character format. This is the default type for characters and may be
    omitted.
  </td>
</tr>
<tr>
  <td><code>'?'</code></td>
  <td>Debug format. The character is quoted and special characters escaped.</td>
</tr>
<tr>
  <td>none</td>
  <td>The same as <code>'c'</code>.</td>
</tr>
</table>

The available integer presentation types are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'b'</code></td>
  <td>
    Binary format. Outputs the number in base 2. Using the <code>'#'</code>
    option with this type adds the prefix <code>"0b"</code> to the output value.    
  </td>
</tr>
<tr>
  <td><code>'B'</code></td>
  <td>
    Binary format. Outputs the number in base 2. Using the <code>'#'</code>
    option with this type adds the prefix <code>"0B"</code> to the output value.
  </td>
</tr>
<tr>
  <td><code>'c'</code></td>
  <td>Character format. Outputs the number as a character.</td>
</tr>
<tr>
  <td><code>'d'</code></td>
  <td>Decimal integer. Outputs the number in base 10.</td>
</tr>
<tr>
  <td><code>'o'</code></td>
  <td>Octal format. Outputs the number in base 8.</td>
</tr>
<tr>
  <td><code>'x'</code></td>
  <td>
    Hex format. Outputs the number in base 16, using lower-case letters for the
    digits above 9. Using the <code>'#'</code> option with this type adds the
    prefix <code>"0x"</code> to the output value.
  </td>
</tr>
<tr>
  <td><code>'X'</code></td>
  <td>
    Hex format. Outputs the number in base 16, using upper-case letters for the
    digits above 9. Using the <code>'#'</code> option with this type adds the
    prefix <code>"0X"</code> to the output value.
  </td>
</tr>
<tr>
  <td>none</td>
  <td>The same as <code>'d'</code>.</td>
</tr>
</table>

Integer presentation types can also be used with character and Boolean values
with the only exception that `'c'` cannot be used with `bool`. Boolean values
are formatted using textual representation, either `true` or `false`, if the
presentation type is not specified.

The available presentation types for floating-point values are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'a'</code></td>
  <td>
    Hexadecimal floating point format. Prints the number in base 16 with
    prefix <code>"0x"</code> and lower-case letters for digits above 9.
    Uses <code>'p'</code> to indicate the exponent.
  </td>
</tr>
<tr>
  <td><code>'A'</code></td>
  <td>
    Same as <code>'a'</code> except it uses upper-case letters for the
    prefix, digits above 9 and to indicate the exponent.
  </td>
</tr>
<tr>
  <td><code>'e'</code></td>
  <td>
    Exponent notation. Prints the number in scientific notation using
    the letter 'e' to indicate the exponent.
  </td>
</tr>
<tr>
  <td><code>'E'</code></td>
  <td>
    Exponent notation. Same as <code>'e'</code> except it uses an
    upper-case <code>'E'</code> as the separator character.
  </td>
</tr>
<tr>
  <td><code>'f'</code></td>
  <td>Fixed point. Displays the number as a fixed-point number.</td>
</tr>
<tr>
  <td><code>'F'</code></td>
  <td>
    Fixed point. Same as <code>'f'</code>, but converts <code>nan</code>
    to <code>NAN</code> and <code>inf</code> to <code>INF</code>.
  </td>
</tr>
<tr>
  <td><code>'g'</code></td>
  <td>
    <p>General format. For a given precision <code>p &gt;= 1</code>,
    this rounds the number to <code>p</code> significant digits and then
    formats the result in either fixed-point format or in scientific
    notation, depending on its magnitude.</p>
    <p>A precision of <code>0</code> is treated as equivalent to a precision
    of <code>1</code>.</p>
  </td>
</tr>
<tr>
  <td><code>'G'</code></td>
  <td>
    General format. Same as <code>'g'</code> except switches to
    <code>'E'</code> if the number gets too large. The representations of
    infinity and NaN are uppercased, too.
  </td>
</tr>
<tr>
  <td>none</td>
  <td>
    Similar to <code>'g'</code>, except that the default precision is as
    high as needed to represent the particular value.
  </td>
</tr>
</table>

The available presentation types for pointers are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'p'</code></td>
  <td>
    Pointer format. This is the default type for pointers and may be omitted.
  </td>
</tr>
<tr>
  <td>none</td>
  <td>The same as <code>'p'</code>.</td>
</tr>
</table>

## Chrono Format Specifications

Format specifications for chrono duration and time point types as well as
`std::tm` have the following syntax:

<a id="chrono-format-spec"></a>
<pre><code class="language-json"
>chrono_format_spec ::= [[<a href="#format-spec">fill</a>]<a href="#format-spec"
  >align</a>][<a href="#format-spec">width</a>]["." <a href="#format-spec"
  >precision</a>][chrono_specs]
chrono_specs       ::= conversion_spec |
                       chrono_specs (conversion_spec | literal_char)
conversion_spec    ::= "%" [padding_modifier] [locale_modifier] chrono_type
literal_char       ::= &lt;a character other than '{', '}' or '%'>
padding_modifier   ::= "-" | "_"  | "0"
locale_modifier    ::= "E" | "O"
chrono_type        ::= "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" |
                       "F" | "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" |
                       "n" | "p" | "q" | "Q" | "r" | "R" | "S" | "t" | "T" |
                       "u" | "U" | "V" | "w" | "W" | "x" | "X" | "y" | "Y" |
                       "z" | "Z" | "%"</code>
</pre>

Literal chars are copied unchanged to the output. Precision is valid only
for `std::chrono::duration` types with a floating-point representation type.

The available presentation types (*chrono_type*) are:

<table>
<tr>
  <th>Type</th>
  <th>Meaning</th>
</tr>
<tr>
  <td><code>'a'</code></td>
  <td>
    The abbreviated weekday name, e.g. "Sat". If the value does not contain a
    valid weekday, an exception of type <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'A'</code></td>
  <td>
    The full weekday name, e.g. "Saturday". If the value does not contain a
    valid weekday, an exception of type <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'b'</code></td>
  <td>
    The abbreviated month name, e.g. "Nov". If the value does not contain a
    valid month, an exception of type <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'B'</code></td>
  <td>
    The full month name, e.g. "November". If the value does not contain a valid
    month, an exception of type <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'c'</code></td>
  <td>
    The date and time representation, e.g. "Sat Nov 12 22:04:00 1955". The
    modified command <code>%Ec</code> produces the locale's alternate date and
    time representation.
  </td>
</tr>
<tr>
  <td><code>'C'</code></td>
  <td>
    The year divided by 100 using floored division, e.g. "19". If the result
    is a single decimal digit, it is prefixed with 0. The modified command
    <code>%EC</code> produces the locale's alternative representation of the
    century.
  </td>
</tr>
<tr>
  <td><code>'d'</code></td>
  <td>
    The day of month as a decimal number. If the result is a single decimal
    digit, it is prefixed with 0. The modified command <code>%Od</code>
    produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'D'</code></td>
  <td>Equivalent to <code>%m/%d/%y</code>, e.g. "11/12/55".</td>
</tr>
<tr>
  <td><code>'e'</code></td>
  <td>
    The day of month as a decimal number. If the result is a single decimal
    digit, it is prefixed with a space. The modified command <code>%Oe</code>
    produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'F'</code></td>
  <td>Equivalent to <code>%Y-%m-%d</code>, e.g. "1955-11-12".</td>
</tr>
<tr>
  <td><code>'g'</code></td>
  <td>
    The last two decimal digits of the ISO week-based year. If the result is a
    single digit it is prefixed by 0.
  </td>
</tr>
<tr>
  <td><code>'G'</code></td>
  <td>
    The ISO week-based year as a decimal number. If the result is less than
    four digits it is left-padded with 0 to four digits.
  </td>
</tr>
<tr>
  <td><code>'h'</code></td>
  <td>Equivalent to <code>%b</code>, e.g. "Nov".</td>
</tr>
<tr>
  <td><code>'H'</code></td>
  <td>
    The hour (24-hour clock) as a decimal number. If the result is a single
    digit, it is prefixed with 0. The modified command <code>%OH</code>
    produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'I'</code></td>
  <td>
    The hour (12-hour clock) as a decimal number. If the result is a single
    digit, it is prefixed with 0. The modified command <code>%OI</code>
    produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'j'</code></td>
  <td>
    If the type being formatted is a specialization of duration, the decimal
    number of days without padding. Otherwise, the day of the year as a decimal
    number. Jan 1 is 001. If the result is less than three digits, it is
    left-padded with 0 to three digits.
  </td>
</tr>
<tr>
  <td><code>'m'</code></td>
  <td>
    The month as a decimal number. Jan is 01. If the result is a single digit,
    it is prefixed with 0. The modified command <code>%Om</code> produces the
    locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'M'</code></td>
  <td>
    The minute as a decimal number. If the result is a single digit, it
    is prefixed with 0. The modified command <code>%OM</code> produces the
    locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'n'</code></td>
  <td>A new-line character.</td>
</tr>
<tr>
  <td><code>'p'</code></td>
  <td>The AM/PM designations associated with a 12-hour clock.</td>
</tr>
<tr>
  <td><code>'q'</code></td>
  <td>The duration's unit suffix.</td>
</tr>
<tr>
  <td><code>'Q'</code></td>
  <td>
    The duration's numeric value (as if extracted via <code>.count()</code>).
  </td>
</tr>
<tr>
  <td><code>'r'</code></td>
  <td>The 12-hour clock time, e.g. "10:04:00 PM".</td>
</tr>
<tr>
  <td><code>'R'</code></td>
  <td>Equivalent to <code>%H:%M</code>, e.g. "22:04".</td>
</tr>
<tr>
  <td><code>'S'</code></td>
  <td>
    Seconds as a decimal number. If the number of seconds is less than 10, the
    result is prefixed with 0. If the precision of the input cannot be exactly
    represented with seconds, then the format is a decimal floating-point number
    with a fixed format and a precision matching that of the precision of the
    input (or to a microseconds precision if the conversion to floating-point
    decimal seconds cannot be made within 18 fractional digits). The character
    for the decimal point is localized according to the locale. The modified
    command <code>%OS</code> produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'t'</code></td>
  <td>A horizontal-tab character.</td>
</tr>
<tr>
  <td><code>'T'</code></td>
  <td>Equivalent to <code>%H:%M:%S</code>.</td>
</tr>
<tr>
  <td><code>'u'</code></td>
  <td>
    The ISO weekday as a decimal number (1-7), where Monday is 1. The modified
    command <code>%Ou</code> produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'U'</code></td>
  <td>
    The week number of the year as a decimal number. The first Sunday of the
    year is the first day of week 01. Days of the same year prior to that are
    in week 00. If the result is a single digit, it is prefixed with 0.
    The modified command <code>%OU</code> produces the locale's alternative
    representation.
  </td>
</tr>
<tr>
  <td><code>'V'</code></td>
  <td>
    The ISO week-based week number as a decimal number. If the result is a
    single digit, it is prefixed with 0. The modified command <code>%OV</code>
    produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'w'</code></td>
  <td>
    The weekday as a decimal number (0-6), where Sunday is 0. The modified
    command <code>%Ow</code> produces the locale's alternative representation.
  </td>
</tr>
<tr>
  <td><code>'W'</code></td>
  <td>
    The week number of the year as a decimal number. The first Monday of the
    year is the first day of week 01. Days of the same year prior to that are
    in week 00. If the result is a single digit, it is prefixed with 0.
    The modified command <code>%OW</code> produces the locale's alternative
    representation.
  </td>
</tr>
<tr>
  <td><code>'x'</code></td>
  <td>
    The date representation, e.g. "11/12/55". The modified command
    <code>%Ex</code> produces the locale's alternate date representation.
  </td>
</tr>
<tr>
  <td><code>'X'</code></td>
  <td>
    The time representation, e.g. "10:04:00". The modified command
    <code>%EX</code> produces the locale's alternate time representation.
  </td>
</tr>
<tr>
  <td><code>'y'</code></td>
  <td>
    The last two decimal digits of the year. If the result is a single digit
    it is prefixed by 0. The modified command <code>%Oy</code> produces the
    locale's alternative representation. The modified command <code>%Ey</code>
    produces the locale's alternative representation of offset from
    <code>%EC</code> (year only).
  </td>
</tr>
<tr>
  <td><code>'Y'</code></td>
  <td>
    The year as a decimal number. If the result is less than four digits it is
    left-padded with 0 to four digits. The modified command <code>%EY</code>
    produces the locale's alternative full year representation.
  </td>
</tr>
<tr>
  <td><code>'z'</code></td>
  <td>
    The offset from UTC in the ISO 8601:2004 format. For example -0430 refers
    to 4 hours 30 minutes behind UTC. If the offset is zero, +0000 is used.
    The modified commands <code>%Ez</code> and <code>%Oz</code> insert a
    <code>:</code> between the hours and minutes: -04:30. If the offset
    information is not available, an exception of type
    <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'Z'</code></td>
  <td>
    The time zone abbreviation. If the time zone abbreviation is not available,
    an exception of type <code>format_error</code> is thrown.
  </td>
</tr>
<tr>
  <td><code>'%'</code></td>
  <td>A % character.</td>
</tr>
</table>

Specifiers that have a calendaric component such as `'d'` (the day of month)
are valid only for `std::tm` and time points but not durations.

The available padding modifiers (*padding_modifier*) are:

| Type  | Meaning                                 |
|-------|-----------------------------------------|
| `'-'` | Pad a numeric result with spaces.       |
| `'_'` | Do not pad a numeric result string.     |
| `'0'` | Pad a numeric result string with zeros. |

These modifiers are only supported for the `'H'`, `'I'`, `'M'`, `'S'`, `'U'`,
`'V'` and `'W'` presentation types.

## Range Format Specifications

Format specifications for range types have the following syntax:

<pre><code class="language-json"
>range_format_spec ::= ["n"][range_type][range_underlying_spec]</code>
</pre>

The `'n'` option formats the range without the opening and closing brackets.

The available presentation types for `range_type` are:

| Type   | Meaning                                                    |
|--------|------------------------------------------------------------|
| none   | Default format.                                            |
| `'s'`  | String format. The range is formatted as a string.         |
| `'?⁠s'` | Debug format. The range is formatted as an escaped string. |

If `range_type` is `'s'` or `'?s'`, the range element type must be a character
type. The `'n'` option and `range_underlying_spec` are mutually exclusive with
`'s'` and `'?s'`.

The `range_underlying_spec` is parsed based on the formatter of the range's
element type.

By default, a range of characters or strings is printed escaped and quoted.
But if any `range_underlying_spec` is provided (even if it is empty), then the
characters or strings are printed according to the provided specification.

Examples:

```c++
fmt::print("{}", std::vector{10, 20, 30});
// Output: [10, 20, 30]
fmt::print("{::#x}", std::vector{10, 20, 30});
// Output: [0xa, 0x14, 0x1e]
fmt::print("{}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: ['h', 'e', 'l', 'l', 'o']
fmt::print("{:n}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: 'h', 'e', 'l', 'l', 'o'
fmt::print("{:s}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: "hello"
fmt::print("{:?s}", std::vector{'h', 'e', 'l', 'l', 'o', '\n'});
// Output: "hello\n"
fmt::print("{::}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: [h, e, l, l, o]
fmt::print("{::d}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: [104, 101, 108, 108, 111]
```

## Format Examples

This section contains examples of the format syntax and comparison with
the printf formatting.

In most of the cases the syntax is similar to the printf formatting,
with the addition of the `{}` and with `:` used instead of `%`. For
example, `"%03.2f"` can be translated to `"{:03.2f}"`.

The new format syntax also supports new and different options, shown in
the following examples.

Accessing arguments by position:

```c++
fmt::format("{0}, {1}, {2}", 'a', 'b', 'c');
// Result: "a, b, c"
fmt::format("{}, {}, {}", 'a', 'b', 'c');
// Result: "a, b, c"
fmt::format("{2}, {1}, {0}", 'a', 'b', 'c');
// Result: "c, b, a"
fmt::format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
// Result: "abracadabra"
```

Aligning the text and specifying a width:

```c++
fmt::format("{:<30}", "left aligned");
// Result: "left aligned                  "
fmt::format("{:>30}", "right aligned");
// Result: "                 right aligned"
fmt::format("{:^30}", "centered");
// Result: "           centered           "
fmt::format("{:*^30}", "centered");  // use '*' as a fill char
// Result: "***********centered***********"
```

Dynamic width:

```c++
fmt::format("{:<{}}", "left aligned", 30);
// Result: "left aligned                  "
```

Dynamic precision:

```c++
fmt::format("{:.{}f}", 3.14, 1);
// Result: "3.1"
```

Replacing `%+f`, `%-f`, and `% f` and specifying a sign:

```c++
fmt::format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
// Result: "+3.140000; -3.140000"
fmt::format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
// Result: " 3.140000; -3.140000"
fmt::format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"
```

Replacing `%x` and `%o` and converting the value to different bases:

```c++
fmt::format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
// Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
// with 0x or 0 or 0b as prefix:
fmt::format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
// Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"
```

Padded hex byte with prefix and always prints both hex characters:

```c++
fmt::format("{:#04x}", 0);
// Result: "0x00"
```

Box drawing using Unicode fill:

```c++
fmt::print(
    "┌{0:─^{2}}┐\n"
    "│{1: ^{2}}│\n"
    "└{0:─^{2}}┘\n", "", "Hello, world!", 20);
```

prints:

```
┌────────────────────┐
│   Hello, world!    │
└────────────────────┘
```

Using type-specific formatting:

```c++
#include <fmt/chrono.h>

auto t = tm();
t.tm_year = 2010 - 1900;
t.tm_mon = 7;
t.tm_mday = 4;
t.tm_hour = 12;
t.tm_min = 15;
t.tm_sec = 58;
fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
// Prints: 2010-08-04 12:15:58
```

Using the comma as a thousands separator:

```c++
#include <fmt/format.h>

auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890);
// s == "1,234,567,890"
```

---

### Vnext External Folly Folly Docs AtomicHashMap (`vnext/external/folly/folly/docs/AtomicHashMap.md`)

`folly/AtomicHashmap.h`
----------------------

`folly/AtomicHashmap.h` introduces a synchronized UnorderedAssociativeContainer
implementation designed for extreme performance in heavily multithreaded
environments (about 2-5x faster than tbb::concurrent_hash_map) and good memory
usage properties.  Find and iteration are wait-free, insert has key-level lock
granularity, there is minimal memory overhead, and permanent 32-bit ids can be
used to reference each element.


### Limitations
***

Although it can provide extreme performance, AtomicHashmap has some unique
limitations as well.

* The space for erased elements cannot be reclaimed (they are tombstoned
forever) so it's generally not a good idea to use this if you're erasing things
a lot.

* Only supports 32 or 64 bit keys - this is because they must be atomically
compare-and-swap'ed.

* Growth beyond initialization reduces performance - if you don't know
the approximate number of elements you'll be inserting into the map, you
probably shouldn't use this class.

* Must manage synchronization externally in order to modify values in the map
after insertion.  Lock pools are a common way to do this, or you may
consider using `folly::PackedSyncPtr<T>` as your `ValueT`.

* Must define special reserved key values for empty, erased, and locked
elements.

For a complete list of limitations and departures from the
UnorderedAssociativeContainer concept, see `folly/AtomicHashMap.h`


### Unique Features
***

* `value_type` references remain valid as long as the map itself.  Note this is
not true for most other probing hash maps which will move elements when
rehashing, which is necessary for them to grow.  AtomicHashMap grows by chaining
additional slabs, so elements never need to be moved.

* Unique 32-bit ids can be used to reference elements in the map via
`iterator::getIndex()`.  This can be helpful to save memory in the rest of the
application by replacing 64-bit pointers or keys.

* Iterators are never invalidated.  This means you can iterate through the map
while simultaneously inserting and erasing.  This is particularly useful for
non-blocking map serialization.


### Usage
***

Usage is similar to most maps, although note the conspicuous lack of operator[]
which encourages non thread-safe access patterns.

Below is a synchronized key counter implementation that allows the counter
values to be incremented in parallel with serializing all the values to a
string.

```Cpp
   class Counters {
    private:
     AtomicHashMap<int64_t,int64_t> ahm;

    public:
     explicit Counters(size_t numCounters) : ahm(numCounters) {}

     void increment(int64_t obj_id) {
       auto ret = ahm.insert(make_pair(obj_id, 1));
       if (!ret.second) {
         // obj_id already exists, increment
         NoBarrier_AtomicIncrement(&ret.first->second, 1);
       }
     }

     int64_t getValue(int64_t obj_id) {
       auto ret = ahm.find(obj_id);
       return ret != ahm.end() ? ret->second : 0;
     }

     // Serialize the counters without blocking increments
     string toString() {
       string ret = "{\n";
       ret.reserve(ahm.size() * 32);
       for (const auto& e : ahm) {
         ret += folly::to<string>(
           "  [", e.first, ":", NoBarrier_Load(&e.second), "]\n");
       }
       ret += "}\n";
       return ret;
     }
   };
```

### Implementation
***

AtomicHashMap is a composition of AtomicHashArray submaps, which implement the
meat of the functionality.  Only one AHA is created on initialization, and
additional submaps are appended if the first one gets full.  If the AHM grows,
there will be multiple submaps that must be probed in series to find a given
key.  The more growth, the more submaps will be chained, and the slower it will
get.  If the initial size estimate is good, only one submap will ever be created
and performance will be optimal.

AtomicHashArray is a fixed-size probing hash map (also referred to as an open
addressed hash map) where hash collisions are resolved by checking subsequent
elements.  This means that they can be allocated in slabs as arrays of
value_type elements, have excellent cache performance, and have no memory
overhead from storing pointers.

The algorithm is simple - when inserting, the key is hash-mod'ed to an offset,
and that element-key is atomically compare-and-swap'ed with the locked key
value.  If successful, the value is written and the element-key is unlocked by
setting it to the input key value.  If the compare fails, the next element is
tried until success or the map is full.

Finds are even simpler.  The key is hash-mod'ed to an offset, and the
element-key is examined.  If it is the same as the input key, the reference is
returned, if it's the empty key, failure is returned, otherwise the next key is
tried.  This can be done wait-free without any atomic instructions because the
elements are always in a valid state.

Erase is done by finding the key, then compare-and-swap'ing the element-key with
the reserved erased key value.  If the swap succeeds, return success, otherwise
return failure (the element was erased by a competing thread).  If the key does
not exist, return failure.

---

### Vnext External Folly Folly Docs Benchmark (`vnext/external/folly/folly/docs/Benchmark.md`)

`folly/Benchmark.h`
-----------------

`folly/Benchmark.h` provides a simple framework for writing and
executing benchmarks. Currently the framework targets only
single-threaded testing (though you can internally use fork-join
parallelism and measure total run time).

### Overview
***

Using `folly/Benchmark.h` is very simple. Here's an example:

``` Cpp
    #include <folly/Benchmark.h>
    #include <vector>
    using namespace std;
    using namespace folly;
    BENCHMARK(insertFrontVector) {
      // Let's insert 100 elements at the front of a vector
      vector<int> v;
      for (unsigned int i = 0; i < 100; ++i) {
        v.insert(v.begin(), i);
      }
    }
    BENCHMARK(insertBackVector) {
      // Let's insert 100 elements at the back of a vector
      vector<int> v;
      for (unsigned int i = 0; i < 100; ++i) {
        v.insert(v.end(), i);
      }
    }
    int main() {
      runBenchmarks();
    }
```

Compiling and running this code produces to the standard output:

```
    ===============================================================================
    test.cpp                                              relative ns/iter  iters/s
    ===============================================================================
    insertFrontVector                                                3.84K  260.38K
    insertBackVector                                                 1.61K  622.75K
    ===============================================================================
```

Let's worry about the empty column "relative" later. The table
contains, for each benchmark, the time spent per call and the converse
number of calls per second. Numbers are represented in metric notation
(K for thousands, M for millions etc). As expected, in this example
the second function is much faster (fewer ns/iter and more iters/s).

The macro `BENCHMARK` introduces a function and also adds it to an
internal array containing all benchmarks in the system. The defined
function takes no arguments and returns `void`.

The framework calls the function many times to collect statistics
about it. Sometimes the function itself would want to do that
iteration---for example how about inserting `n` elements instead of
100 elements? To do the iteration internally, use `BENCHMARK` with two
parameters. The second parameter is the number of iterations and is
passed by the framework down to the function. The type of the count is
implicitly `unsigned`. Consider a slightly reworked example:

``` Cpp
    #include <folly/Benchmark.h>
    #include <folly/container/Foreach.h>
    #include <vector>
    using namespace std;
    using namespace folly;
    BENCHMARK(insertFrontVector, n) {
      vector<int> v;
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.begin(), i);
      }
    }
    BENCHMARK(insertBackVector, n) {
      vector<int> v;
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.end(), i);
      }
    }
    int main() {
      runBenchmarks();
    }
```

The produced numbers are substantially different:

```
    ===============================================================================
    Benchmark                                             relative ns/iter  iters/s
    ===============================================================================
    insertFrontVector                                               39.92    25.05M
    insertBackVector                                                 3.46   288.89M
    ===============================================================================
```

Now the numbers indicate the speed of one single insertion because the
framework assumed the user-defined function used internal iteration
(which it does). So inserting at the back of a vector is more than 10
times faster than inserting at the front! Speaking of comparisons...

### Baselines
***

Choosing one or more good baselines is a crucial activity in any
measurement. Without a baseline there is little information to derive
from the sheer numbers. If, for example, you do experimentation with
algorithms, a good baseline is often an established approach (e.g. the
built-in `std::sort` for sorting). Essentially all experimental
numbers should be compared against some baseline.

To support baseline-driven measurements, `folly/Benchmark.h` defines
`BENCHMARK_RELATIVE`, which works much like `BENCHMARK`, except it
considers the most recent lexically-occurring `BENCHMARK` a baseline,
and fills the "relative" column. Say, for example, we want to use
front insertion for a vector as a baseline and see how back insertion
compares with it:

``` Cpp
    #include <folly/Benchmark.h>
    #include <folly/container/Foreach.h>
    #include <vector>
    using namespace std;
    using namespace folly;
    BENCHMARK(insertFrontVector, n) {
      vector<int> v;
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.begin(), i);
      }
    }
    BENCHMARK_RELATIVE(insertBackVector, n) {
      vector<int> v;
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.end(), i);
      }
    }
    int main() {
      runBenchmarks();
    }
```

This program prints something like:

```
    ===============================================================================
    Benchmark                                             relative ns/iter  iters/s
    ===============================================================================
    insertFrontVector                                               42.65    23.45M
    insertBackVector                                     1208.24%    3.53   283.30M
    ===============================================================================
```

showing the 1208.24% relative speed advantage of inserting at the back
compared to front. The scale is chosen in such a way that 100% means
identical speed, numbers smaller than 100% indicate the benchmark is
slower than the baseline, and numbers greater than 100% indicate the
benchmark is faster. For example, if you see 42% that means the speed
of the benchmark is 0.42 of the baseline speed. If you see 123%, it
means the benchmark is 23% or 1.23 times faster.

To close the current benchmark group and start another, simply use
`BENCHMARK` again.

### Ars Gratia Artis
***

If you want to draw a horizontal line of dashes (e.g. at the end of a
group or for whatever reason), use `BENCHMARK_DRAW_LINE()`. The line
fulfills a purely aesthetic role; it doesn't interact with
measurements in any way.

``` Cpp
    BENCHMARK(foo) {
      Foo foo;
      foo.doSomething();
    }

    BENCHMARK_DRAW_LINE();

    BENCHMARK(bar) {
      Bar bar;
      bar.doSomething();
    }
```

If you want to print arbitrary text (e.g. a comment or for whatever
reason), use `BENCHMARK_DRAW_TEXT("your text here")`. The output will
be the literal value so escape codes like `\n` or `\t` will not work.
To add multiple lines of output use multiple `BENCHMARK_DRAW_TEXT`
calls.

``` Cpp
    BENCHMARK(foo) {
      Foo foo;
      foo.doSomething();
    }

    BENCHMARK_DRAW_TEXT("Note: bar is expected to be 2x more expensive.");

    BENCHMARK(bar) {
      Bar bar;
      bar.doSomething();
    }
```

### Suspending a benchmark
***

Sometimes benchmarking code must do some preparation work that is
physically inside the benchmark function, but should not take part to
its time budget. To temporarily suspend the benchmark, use the
pseudo-statement `BENCHMARK_SUSPEND` as follows:

``` Cpp
    BENCHMARK(insertBackVector, n) {
      vector<int> v;
      BENCHMARK_SUSPEND {
        v.reserve(n);
      }
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.end(), i);
      }
    }
```

The preallocation effected with `v.reserve(n)` will not count toward
the total run time of the benchmark.

Only the main thread should call `BENCHMARK_SUSPEND` (and of course it
should not call it while other threads are doing actual work). This is
because the timer is application-global.

If the scope introduced by `BENCHMARK_SUSPEND` is not desired, you may
want to "manually" use the `BenchmarkSuspender` type. Constructing
such an object suspends time measurement, and destroying it resumes
the measurement. If you want to resume time measurement before the
destructor, call `dismiss` against the `BenchmarkSuspender`
object. The previous example could have been written like this:

``` Cpp
    BENCHMARK(insertBackVector, n) {
      BenchmarkSuspender braces;
      vector<int> v;
      v.reserve(n);
      braces.dismiss();
      for (unsigned int i = 0; i < n; ++i) {
        v.insert(v.end(), i);
      }
    }
```

### `doNotOptimizeAway`
***

Finally, the small utility function `doNotOptimizeAway` prevents
compiler optimizations that may interfere with benchmarking . Call
doNotOptimizeAway(var) against variables that you use for
benchmarking but otherwise are useless. The compiler tends to do a
good job at eliminating unused variables, and this function fools it
into thinking a variable is in fact needed. Example:

``` Cpp
    BENCHMARK(fpOps, n) {
      double d = 1;
      FOR_EACH_RANGE (i, 1, n) {
        d += i;
        d -= i;
        d *= i;
        d /= i;
      }
      doNotOptimizeAway(d);
    }
```

### A look under the hood
***

`folly/Benchmark.h` has a simple, systematic approach to collecting
timings.

First, it organizes measurements in several large epochs, and takes
the minimum over all epochs. Taking the minimum gives the closest
result to the real runtime. Benchmark timings are not a regular random
variable that fluctuates around an average. Instead, the real time
we're looking for is one to which there's a variety of additive noise
(i.e. there is no noise that could actually shorten the benchmark time
below its real value). In theory, taking an infinite amount of samples
and keeping the minimum is the actual time that needs
measuring. That's why the accuracy of benchmarking increases with the
number of epochs.

Clearly, in real functioning there will also be noise and a variety of
effects caused by the running context. But the noise during the
benchmark (straight setup, simple looping) is a poor model for the
noise in the real application. So taking the minimum across several
epochs is the most informative result.

Inside each epoch, the function measured is iterated an increasing
number of times until the total runtime is large enough to make noise
negligible. At that point the time is collected, and the time per
iteration is computed. As mentioned, the minimum time per iteration
over all epochs is the final result.

The timer function used is `clock_gettime` with the `CLOCK_REALTIME`
clock id. Note that you must use a recent Linux kernel (2.6.38 or
newer), otherwise the resolution of `CLOCK_REALTIME` is inadequate.

---

### Vnext External Folly Folly Docs Conv (`vnext/external/folly/folly/docs/Conv.md`)

`folly/Conv.h`
-------------

`folly/Conv.h` is a one-stop-shop for converting values across
types. Its main features are simplicity of the API (only the
names `to` and `toAppend` must be memorized), speed
(folly is significantly faster, sometimes by an order of magnitude,
than comparable APIs), and correctness.

### Synopsis
***

All examples below are assume to have included `folly/Conv.h`
and issued `using namespace folly;` You will need:

``` Cpp
    // To format as text and append to a string, use toAppend.
    fbstring str;
    toAppend(2.5, &str);
    CHECK_EQ(str, "2.5");

    // Multiple arguments are okay, too. Just put the pointer to string at the end.
    toAppend(" is ", 2, " point ", 5, &str);
    CHECK_EQ(str, "2.5 is 2 point 5");

    // You don't need to use fbstring (although it's much faster for conversions and in general).
    std::string stdStr;
    toAppend("Pi is about ", 22.0 / 7, &stdStr);
    // In general, just use to<TargetType>(sourceValue). It returns its result by value.
    stdStr = to<std::string>("Variadic ", "arguments also accepted.");

    // to<fbstring> is 2.5x faster than to<std::string> for typical workloads.
    str = to<fbstring>("Variadic ", "arguments also accepted.");
```

### Integral-to-integral conversion
***

Using `to<Target>(value)` to convert one integral type to another
will behave as follows:

* If the target type can accommodate all possible values of the
  source value, the value is implicitly converted. No further
  action is taken. Example:

``` Cpp
        short x;
        unsigned short y;
        ...
        auto a = to<int>(x); // zero overhead conversion
        auto b = to<int>(y); // zero overhead conversion
```

* Otherwise, `to` inserts bounds checks and throws
  `std::range_error` if the target type cannot accommodate the
  source value. Example:

``` Cpp
    short x;
    unsigned short y;
    long z;
    ...
    x = 123;
    auto a = to<unsigned short>(x); // fine
    x = -1;
    a = to<unsigned short>(x); // THROWS
    z = 2000000000;
    auto b = to<int>(z); // fine
    z += 1000000000;
    b = to<int>(z); // THROWS
    auto b = to<unsigned int>(z); // fine
```

### Anything-to-string conversion
***

As mentioned, there are two primitives for converting anything to
string: `to` and `toAppend`. They support the same set of source
types, literally by definition (`to` is implemented in terms of
`toAppend` for all types). The call `toAppend(value, &str)`
formats and appends `value` to `str` whereas
`to<StringType>(value)` formats `value` as a `StringType` and
returns the result by value. Currently, the supported
`StringType`s are `std::string` and `fbstring`

Both `toAppend` and `to` with a string type as a target support
variadic arguments. Each argument is converted in turn. For
`toAppend` the last argument in a variadic list must be the
address of a supported string type (no need to specify the string
type as a template argument).

#### Integral-to-string conversion

Nothing special here - integrals are converted to strings in
decimal format, with a '-' prefix for negative values. Example:

``` Cpp
    auto a = to<fbstring>(123);
    assert(a == "123");
    a = to<fbstring>(-456);
    assert(a == "-456");
```

The conversion implementation is aggressively optimized. It
converts two digits at a time assisted by fixed-size tables.
Converting a `long` to an `fbstring` is 3.6x faster than using
`boost::lexical_cast` and 2.5x faster than using `sprintf` even
though the latter is used in conjunction with a stack-allocated
constant-size buffer.

Note that converting integral types to `fbstring` has a
particular advantage compared to converting to `std::string`
No integral type (<= 64 bits) has more than 20 decimal digits
including sign. Since `fbstring` employs the small string
optimization for up to 23 characters, converting an integral
to `fbstring` is guaranteed to not allocate memory, resulting
in significant speed and memory locality gains. Benchmarks
reveal a 2x gain on a typical workload.

#### `char` to string conversion

Although `char` is technically an integral type, most of the time
you want the string representation of `'a'` to be `"a"`, not `96`
That's why `folly/Conv.h` handles `char` as a special case that
does the expected thing. Note that `signed char` and `unsigned
char` are still considered integral types.


#### Floating point to string conversion

`folly/Conv.h` uses [V8's double conversion](http://code.google.com/p/double-conversion/)
routines. They are accurate and fast; on typical workloads,
`to<fbstring>(doubleValue)` is 1.9x faster than `sprintf` and
5.5x faster than `boost::lexical_cast` (It is also 1.3x faster
than `to<std::string>(doubleValue)`

#### `const char*` to string conversion

For completeness, `folly/Conv.h` supports `const char*` including
i.e. string literals. The "conversion" consists, of course, of
the string itself. Example:

``` Cpp
    auto s = to<fbstring>("Hello, world");
    assert(s == "Hello, world");
```

#### Anything from string conversion (i.e. parsing)
***

`folly/Conv.h` includes three kinds of parsing routines:

* `to<Type>(const char* begin, const char* end)` rigidly
  converts the range [begin, end) to `Type` These routines have
  drastic restrictions (e.g. allow no leading or trailing
  whitespace) and are intended as an efficient back-end for more
  tolerant routines.
* `to<Type>(stringy)` converts `stringy` to `Type` Value
  `stringy` may be of type `const char*`, `StringPiece`,
  `std::string`, or `fbstring` (Technically, the requirement is
  that `stringy` implicitly converts to a `StringPiece`
* `to<Type>(&stringPiece)` parses with progress information:
  given `stringPiece` of type `StringPiece` it parses as much
  as possible from it as type `Type` and alters `stringPiece`
  to remove the munched characters. This is easiest clarified
  by an example:

``` Cpp
    fbstring s = " 1234 angels on a pin";
    StringPiece pc(s);
    auto x = to<int>(&pc);
    assert(x == 1234);
    assert(pc == " angels on a pin";
```

Note how the routine ate the leading space but not the trailing one.

#### Parsing integral types

Parsing integral types is unremarkable - decimal format is
expected, optional `'+'` or `'-'` sign for signed types, but no
optional `'+'` is allowed for unsigned types. The one remarkable
element is speed - parsing typical `long` values is 6x faster than
`sscanf`. `folly/Conv.h` uses aggressive loop unrolling and
table-assisted SIMD-style code arrangement that avoids integral
division (slow) and data dependencies across operations
(ILP-unfriendly). Example:

``` Cpp
    fbstring str = "  12345  ";
    assert(to<int>(str) == 12345);
    str = "  12345six seven eight";
    StringPiece pc(str);
    assert(to<int>(&pc) == 12345);
    assert(str == "six seven eight");
```

#### Parsing floating-point types

`folly/Conv.h` uses, again, [V8's double-conversion](http://code.google.com/p/double-conversion/)
routines as back-end. The speed is 3x faster than `sscanf` and
1.7x faster than in-home routines such as `parse<double>` But
the more important detail is accuracy - even if you do code a
routine that works faster than `to<double>` chances are it is
incorrect and will fail in a variety of corner cases. Using
`to<double>` is strongly recommended.

Note that if the string "NaN" (with any capitalization) is passed to
`to<double>` then `NaN` is returned, which can be tested for as follows:

``` Cpp
    fbstring str = "nan"; // "NaN", "NAN", etc.
    double d = to<double>(str);
    if (std::isnan(d)) {
      // string was a valid representation of the double value NaN
    }
```

Note that passing "-NaN" (with any capitalization) to `to<double>` also returns
`NaN`.

Note that if the strings "inf" or "infinity" (with any capitalization) are
passed to `to<double>` then `infinity` is returned, which can be tested for
as follows:

``` Cpp
    fbstring str = "inf"; // "Inf", "INF", "infinity", "Infinity", etc.
    double d = to<double>(str);
    if (std::isinf(d)) {
      // string was a valid representation of one of the double values +Infinity
      // or -Infinity
    }
```

Note that passing "-inf" or "-infinity" (with any capitalization) to
`to<double>` returns `-infinity` rather than `+infinity`. The sign of the
`infinity` can be tested for as follows:

``` Cpp
    fbstring str = "-inf"; // or "inf", "-Infinity", "+Infinity", etc.
    double d = to<double>(str);
    if (d == std::numeric_limits<double>::infinity()) {
      // string was a valid representation of the double value +Infinity
    } else if (d == -std::numeric_limits<double>::infinity()) {
      // string was a valid representation of the double value -Infinity
    }
```

Note that if an unparseable string is passed to `to<double>` then an exception
is thrown, rather than `NaN` being returned.  This can be tested for as follows:

``` Cpp
    fbstring str = "not-a-double"; // Or "1.1.1", "", "$500.00", etc.
    double d;
    try {
      d = to<double>(str);
    } catch (const std::range_error &) {
      // string could not be parsed
    }
```

Note that the empty string (`""`) is an unparseable value, and will cause
`to<double>` to throw an exception.

#### Non-throwing interfaces

`tryTo<T>` is the non-throwing variant of `to<T>`. It returns
an `Expected<T, ConversionCode>`. You can think of `Expected`
as like an `Optional<T>`, but if the conversion failed, `Expected`
stores an error code instead of a `T`.

`tryTo<T>` has similar performance as `to<T>` when the
conversion is successful. On the error path, you can expect
`tryTo<T>` to be roughly three orders of magnitude faster than
the throwing `to<T>` and to completely avoid any lock contention
arising from stack unwinding.

Here is how to use non-throwing conversions:

``` Cpp
    auto t1 = tryTo<int>(str);
    if (t1.hasValue()) {
      use(t1.value());
    }
```

`Expected` has a composability feature to make the above pattern simpler.

``` Cpp
    tryTo<int>(str).then([](int i) { use(i); });
```

---

### Vnext External Folly Folly Docs Dynamic (`vnext/external/folly/folly/docs/Dynamic.md`)

`folly/dynamic.h`
-----------------

`folly/dynamic.h` provides a runtime dynamically typed value for
C++, similar to the way languages with runtime type systems work
(e.g. Python). It can hold types from a predetermined set of types
(ints, bools, arrays of other dynamics, etc), similar to something like
`std::variant`, but the syntax is intended to be a little more like
using the native type directly.

### Overview
***

Here are some code samples to get started (assumes a `using
folly::dynamic;` was used):

``` Cpp
    dynamic twelve = 12; // creates a dynamic that holds an integer
    dynamic str = "string"; // yep, this one is an fbstring

    // A few other types.
    dynamic nul = nullptr;
    dynamic boolean = false;

    // Arrays can be initialized with dynamic::array.
    dynamic array = dynamic::array("array ", "of ", 4, " elements");
    assert(array.size() == 4);
    dynamic emptyArray = dynamic::array;
    assert(emptyArray.empty());

    // Maps from dynamics to dynamics are called objects.  The
    // dynamic::object constant is how you make an empty map from dynamics
    // to dynamics.
    dynamic map = dynamic::object;
    map["something"] = 12;
    map["another_something"] = map["something"] * 2;

    // Dynamic objects may be initialized this way
    dynamic map2 = dynamic::object("something", 12)("another_something", 24);
```

### Runtime Type Checking and Conversions
***

Any operation on a dynamic requires checking at runtime that the
type is compatible with the operation. If it isn't, you'll get a
`folly::TypeError`. Other exceptions can also be thrown if
you try to do something impossible (e.g. if you put a very large
64-bit integer in and try to read it out as a double).

More examples should hopefully clarify this:

``` Cpp
    dynamic dint = 42;

    dynamic str = "foo";
    dynamic anotherStr = str + "something"; // fine
    dynamic thisThrows = str + dint; // TypeError is raised
```

Explicit type conversions can be requested for some of the basic types:

``` Cpp
    dynamic dint = 12345678;
    dynamic doub = dint.asDouble(); // doub will hold 12345678.0
    dynamic str = dint.asString(); // str == "12345678"

    dynamic hugeInt = std::numeric_limits<int64_t>::max();
    dynamic hugeDoub = hugeInt.asDouble();  // throws a folly/Conv.h error,
                                            // since it can't fit in a double
```

For more complicated conversions, see [DynamicConverter](DynamicConverter.md).

### Comparison Operators and Hashing
#### Equality Operators
Equality operators (`==`, `!=`) are supported for all types.

For dynamics of the same type, the underlying equality operator shall apply.

For comparisons between different numeric types (double and int64), numeric
equality will apply - thus `2.0 == 2`.

Values of any other different types will be deemed to not be equal.

#### Ordering operators
Ordering operators (`<`, `<=`, `>`, `>=`) are supported for all types, except
`dynamic::object` which will throw if it is involved in an ordering operator.

For dynamics of the same type, the underlying ordering operator shall apply.

For comparisons between different numeric types (double and int64), numeric
ordering will apply - thus `1.5 < 2`.

Ordering of values between other different types will maintain total ordering
properties and be consistent within a given binary run, and thus safe for use in
e.g. `std::set`. The actual ordering is undefined and could change across
versions, thus a dependency should not be taken outside of the total ordering
property within a given binary.

#### Hashing
Hashing is supported by all types, and the hashes of two values will match if
they are equal per `dynamic::operator==`.

As a result, numerical types have the same numerical hashing regardless of int64
vs double - so e.g. `std::hash<dynamic>()(2)` will give the same value as
`std::hash<dynamic>()(2.0)`.

### Iteration and Lookup
***

You can iterate over dynamic arrays as you would over any C++ sequence container.

``` Cpp
    dynamic array = dynamic::array(2, 3, "foo");

    for (auto& val : array) {
      doSomethingWith(val);
    }
```

You can iterate over dynamic maps by calling `items()`, `keys()`,
`values()`, which behave similarly to the homonymous methods of Python
dictionaries.

``` Cpp
    dynamic obj = dynamic::object(2, 3)("hello", "world")("x", 4);

    for (auto& pair : obj.items()) {
      // Key is pair.first, value is pair.second
      processKey(pair.first);
      processValue(pair.second);
    }

    for (auto& key : obj.keys()) {
      processKey(key);
    }

    for (auto& value : obj.values()) {
      processValue(value);
    }
```

You can find an element by key in a dynamic map using the `find()` method,
which returns an iterator compatible with `items()`:

``` Cpp
    dynamic obj = dynamic::object(2, 3)("hello", "world")("x", 4);

    auto pos = obj.find("hello");
    // pos->first is "hello"
    // pos->second is "world"

    auto pos = obj.find("no_such_key");
    // pos == obj.items().end()
```


### Use for JSON
***

The original motivation for implementing this type was to try to
make dealing with json documents in C++ almost as easy as it is
in languages with dynamic type systems (php or javascript, etc).
The reader can judge whether we're anywhere near that goal, but
here's what it looks like:

``` Cpp
    // Parsing JSON strings and using them.
    std::string jsonDocument = R"({"key":12,"key2":[false, null, true, "yay"]})";
    dynamic parsed = folly::parseJson(jsonDocument);
    assert(parsed["key"] == 12);
    assert(parsed["key2"][0] == false);
    assert(parsed["key2"][1] == nullptr);

    // Building the same document programmatically.
    dynamic sonOfAJ = dynamic::object
      ("key", 12)
      ("key2", dynamic::array(false, nullptr, true, "yay"));

    // Printing.  (See also folly::toPrettyJson)
    auto str = folly::toJson(sonOfAJ);
    assert(jsonDocument.compare(str) == 0);
```

### Performance
***

Dynamic typing is more expensive than static typing, even when
you do it in C++. ;)

However, some effort has been made to keep `folly::dynamic` and
the json (de)serialization at least reasonably performant for
common cases. The heap is only used for arrays and objects, and
move construction is fully supported. String formatting
internally also uses the highly performant `folly::to<>` (see
`folly/Conv.h`).

A trade off to keep in mind though, is that
`sizeof(folly::dynamic)` is 64 bytes. You probably don't want to
use it if you need to allocate large numbers of them (prefer
static types, etc).

### Some Design Rationale
***

**Q. Why doesn't a dynamic string support begin(), end(), and operator[]?**

The value_type of a dynamic iterator is `dynamic`, and `operator[]`
(or the `at()` function) has to return a reference to a dynamic.  If
we wanted this to work for strings, this would mean we'd have to
support dynamics with a character type, and moreover that the internal
representation of strings would be such that we can hand out
references to dynamic as accessors on individual characters.  There
are a lot of potential efficiency drawbacks with this, and it seems
like a feature that is not needed too often in practice.

**Q. Isn't this just a poor imitation of the C# language feature?**

Pretty much.

---

### Vnext External Folly Folly Docs DynamicConverter (`vnext/external/folly/folly/docs/DynamicConverter.md`)

`folly/DynamicConverter.h`
--------------------------

When dynamic objects contain data of a known type, it is sometimes
useful to have its well-typed representation. A broad set of
type-conversions are contained in `DynamicConverter.h`, and
facilitate the transformation of dynamic objects into their well-typed
format.

### Usage
***

Simply pass a dynamic into a templated convertTo:

```cpp
    dynamic d = { { 1, 2, 3 }, { 4, 5 } }; // a vector of vector of int
    auto vvi = convertTo<fbvector<fbvector<int>>>(d);
```

### Supported Types
***

convertTo naturally supports conversions to

1. arithmetic types (such as int64_t, unsigned short, bool, and double)
2. fbstring, std::string
3. containers and map-containers

NOTE:

convertTo<Type> will assume that Type is a container if
* it has a Type::value_type, and
* it has a Type::iterator, and
* it has a constructor that accepts two InputIterators

Additionally, convertTo<Type> will assume that Type is a map if
* it has a Type::key_type, and
* it has a Type::mapped_type, and
* value_type is a pair of const key_type and mapped_type

If Type meets the container criteria, then it will be constructed
by calling its InputIterator constructor.

### Customization
***

If you want to use convertTo to convert dynamics into your own custom
class, then all you have to do is provide a template specialization
of DynamicConverter with the static method convert. Make sure you put it
in namespace folly.

Example:

``` Cpp
    struct Token {
      int kind_;
      fbstring lexeme_;
      
      explicit Token(int kind, const fbstring& lexeme)
        : kind_(kind), lexeme_(lexeme) {}
    };
    namespace folly {
    template <> struct DynamicConverter<Token> {
      static Token convert(const dynamic& d) {
        int k = convertTo<int>(d["KIND"]);
        fbstring lex = convertTo<fbstring>(d["LEXEME"]);
        return Token(k, lex);
      }
    };
    }
```

---

### Vnext External Folly Folly Docs Executors (`vnext/external/folly/folly/docs/Executors.md`)

<section class="dex_document"><h1>Thread pools &amp; Executors</h1><p class="dex_introduction">Run your concurrent code in a performant way</p><h2 id="all-about-thread-pools">All about thread pools <a href="#all-about-thread-pools" class="headerLink">#</a></h2>

<h3 id="how-do-i-use-the-thread">How do I use the thread pools? <a href="#how-do-i-use-the-thread" class="headerLink">#</a></h3>

<p>Wangle provides two concrete thread pools (IOThreadPoolExecutor, CPUThreadPoolExecutor) as well as building them in as part of a complete async framework.  Generally you might want to grab the global executor, and use it with a future, like this:</p>

<div class="remarkup-code-block" data-code-lang="php"><pre class="remarkup-code"><span class="no">auto</span> <span class="no">f</span> <span class="o">=</span> <span class="nf" data-symbol-name="someFutureFunction">someFutureFunction</span><span class="o">().</span><span class="nf" data-symbol-name="via">via</span><span class="o">(</span><span class="nf" data-symbol-name="getCPUExecutor">getCPUExecutor</span><span class="o">()).</span><span class="nf" data-symbol-name="then">then</span><span class="o">(...)</span></pre></div>

<p>Or maybe you need to construct a thrift/memcache client, and need an event base:</p>

<div class="remarkup-code-block" data-code-lang="php"><pre class="remarkup-code"><span class="no">auto</span> <span class="no">f</span> <span class="o">=</span> <span class="nf" data-symbol-name="getClient">getClient</span><span class="o">(</span><span class="nf" data-symbol-name="getIOExecutor">getIOExecutor</span><span class="o">()-&gt;</span><span class="na" data-symbol-name="getEventBase">getEventBase</span><span class="o">())-&gt;</span><span class="na" data-symbol-name="callSomeFunction">callSomeFunction</span><span class="o">(</span><span class="no">args</span><span class="o">...)</span>
         <span class="o">.</span><span class="nf" data-symbol-name="via">via</span><span class="o">(</span><span class="nf" data-symbol-name="getCPUExecutor">getCPUExecutor</span><span class="o">())</span>
         <span class="o">.</span><span class="nf" data-symbol-name="then">then</span><span class="o">([](</span><span class="no">Result</span> <span class="no">r</span><span class="o">)&#123;</span> <span class="o">....</span> <span class="k">do</span> <span class="no">something</span> <span class="no">with</span> <span class="no">result</span><span class="o">&#125;);</span></pre></div>

<h3 id="vs-c-11-s-std-launch">vs. C++11&#039;s std::launch <a href="#vs-c-11-s-std-launch" class="headerLink">#</a></h3>

<p>The current C++11 std::launch only has two modes: async or deferred.  In a production system, neither is what you want:  async will launch a new thread for every launch without limit, while deferred will defer the work until it is needed lazily, but then do the work <strong>in the current thread synchronously</strong> when it is needed.</p>

<p>Wangle&#039;s thread pools always launch work as soon as possible, have limits to the maximum number of tasks / threads allowed, so we will never use more threads than absolutely needed.  See implementation details below about each type of executor.</p>

<h3 id="why-do-we-need-yet-anoth">Why do we need yet another set of thread pools? <a href="#why-do-we-need-yet-anoth" class="headerLink">#</a></h3>

<p>Unfortunately none of the existing thread pools had every feature needed - things based on pipes are too slow.   Several older ones didn&#039;t support std::function.</p>

<h3 id="why-do-we-need-several-d">Why do we need several different types of thread pools? <a href="#why-do-we-need-several-d" class="headerLink">#</a></h3>

<p>If you want epoll support, you need an fd - event_fd is the latest notification hotness.   Unfortunately, an active fd triggers all the epoll loops it is in, leading to thundering herd - so if you want a fair queue (one queue total vs. one queue per worker thread), you need to use some kind of semaphore.  Unfortunately semaphores can&#039;t be put in epoll loops, so they are incompatible with IO.   Fortunately, you usually want to separate the IO and CPU bound work anyway to give stronger tail latency guarantees on IO.</p>

<h3 id="iothreadpoolexecutor">IOThreadPoolExecutor <a href="#iothreadpoolexecutor" class="headerLink">#</a></h3>

<ul>
<li>Uses event_fd for notification, and waking an epoll loop.</li>
<li>There is one queue (NotificationQueue specifically) per thread/epoll.</li>
<li>If the thread is already running and not waiting on epoll, we don&#039;t make any additional syscalls to wake up the loop, just put the new task in the queue.</li>
<li>If any thread has been waiting for more than a few seconds, its stack is madvised away.   Currently however tasks are scheduled round robin on the queues, so unless there is <strong>no</strong> work going on, this isn&#039;t very effective.</li>
<li>::getEventBase() will return an EventBase you can schedule IO work on directly, chosen round-robin.</li>
<li>Since there is one queue per thread, there is hardly any contention on the queues - so a simple spinlock around an std::deque is used for the tasks.  There is no max queue size.</li>
<li>By default, there is one thread per core - it usually doesn&#039;t make sense to have more IO threads than this, assuming they don&#039;t block.</li>
</ul>

<h3 id="cputhreadpoolexecutor">CPUThreadPoolExecutor <a href="#cputhreadpoolexecutor" class="headerLink">#</a></h3>

<ul>
<li>A single queue backed by folly/LifoSem and folly/MPMC queue.  Since there is only a single queue, contention can be quite high, since all the worker threads and all the producer threads hit the same queue.  MPMC queue excels in this situation.  MPMC queue dictates a max queue size.</li>
<li>LifoSem wakes up threads in Lifo order - i.e. there are only few threads as necessary running, and we always try to reuse the same few threads for better cache locality.</li>
<li>Inactive threads have their stack madvised away.  This works quite well in combination with Lifosem - it almost doesn&#039;t matter if more threads than are necessary are specified at startup.</li>
<li>stop() will finish all outstanding tasks at exit</li>
<li>Supports priorities - priorities are implemented as multiple queues - each worker thread checks the highest priority queue first.  Threads themselves don&#039;t have priorities set, so a series of long running low priority tasks could still hog all the threads.  (at last check pthreads thread priorities didn&#039;t work very well)</li>
</ul>

<h3 id="threadpoolexecutor">ThreadPoolExecutor <a href="#threadpoolexecutor" class="headerLink">#</a></h3>

<p>Base class that contains the thread startup/shutdown/stats logic, since this is pretty disjoint from how tasks are actually run</p>

<h3 id="observers">Observers <a href="#observers" class="headerLink">#</a></h3>

<p>An observer interface is provided to listen for thread start/stop events.  This is useful to create objects that should be one-per-thread, but also have them work correctly if threads are added/removed from the thread pool.</p>

<h3 id="stats">Stats <a href="#stats" class="headerLink">#</a></h3>

<p>PoolStats are provided to get task count, running time, waiting time, etc.</p>
</section>

---

### Vnext External Folly Folly Docs FBString (`vnext/external/folly/folly/docs/FBString.md`)

`folly/FBString.h`
------------------

`fbstring` is a drop-in replacement for `std::string`. The main
benefit of `fbstring` is significantly increased performance on
virtually all important primitives. This is achieved by using a
three-tiered storage strategy and by cooperating with the memory
allocator. In particular, `fbstring` is designed to detect use of
jemalloc and cooperate with it to achieve significant improvements in
speed and memory usage.

`fbstring` supports 32- and 64-bit and little- and big-endian
architectures.

### Storage strategies
***

* Small strings (<= 23 chars) are stored in-situ without memory
  allocation.

* Medium strings (24 - 255 chars) are stored in malloc-allocated
  memory and copied eagerly.

* Large strings (> 255 chars) are stored in malloc-allocated memory and
  copied lazily.

### Implementation highlights
***

* 100% compatible with `std::string`.

* Thread-safe reference counted copy-on-write for "large"
  strings (> 255 chars).

* Uses `malloc` instead of allocators.

* Jemalloc-friendly. `fbstring` automatically detects if application
  uses jemalloc and if so, significantly improves allocation
  strategy by using non-standard jemalloc extensions.

* `find()` is implemented using simplified Boyer-Moore
  algorithm. Casual tests indicate a 30x speed improvement over
  `string::find()` for successful searches and a 1.5x speed
  improvement for failed searches.

* Offers conversions to and from `std::string`.

---

### Vnext External Folly Folly Docs FBVector (`vnext/external/folly/folly/docs/FBVector.md`)

`folly/FBVector.h`
------------------

Simply replacing `std::vector` with `folly::fbvector` (after
having included the `folly/FBVector.h` header file) will
improve the performance of your C++ code using vectors with
common coding patterns. The improvements are always non-negative,
almost always measurable, frequently significant, sometimes
dramatic, and occasionally spectacular.

### Sample
***
```cpp
    folly::fbvector<int> numbers({0, 1, 2, 3});
    numbers.reserve(10);
    for (int i = 4; i < 10; i++) {
      numbers.push_back(i * 2);
    }
    assert(numbers[6] == 12);
```
### Motivation
***

`std::vector` is the stalwart abstraction many use for
dynamically-allocated arrays in C++. It is also the best known
and most used of all containers. It may therefore seem a
surprise that `std::vector` leaves important - and sometimes
vital - efficiency opportunities on the table. This document
explains how our own drop-in abstraction `fbvector` improves key
performance aspects of `std::vector`. Refer to
folly/test/FBVectorTest.cpp for a few benchmarks.

### Memory Handling
***

It is well known that `std::vector` grows exponentially (at a
constant factor) in order to avoid quadratic growth performance.
The trick is choosing a good factor. Any factor greater than 1
ensures O(1) amortized append complexity towards infinity. But a
factor that's too small (say, 1.1) causes frequent vector reallocation, and
one that's too large (say, 3 or 4) forces the vector to consume much more
memory than needed.

The initial HP implementation by Stepanov used a
growth factor of 2; i.e., whenever you'd `push_back` into a vector
without there being room, it would double the current capacity. This
was not a good choice: it can be mathematically proven that a growth factor of
2 is rigorously the <i>worst</i> possible because it never allows the vector 
to reuse any of its previously-allocated memory. Despite other compilers
reducing the growth factor to 1.5, gcc has staunchly maintained its factor of
2. This makes `std::vector` cache- unfriendly and memory manager unfriendly.

To see why that's the case, consider a large vector of capacity C.
When there's a request to grow the vector, the vector
(assuming no in-place resizing, see the appropriate section in
this document) will allocate a chunk of memory next to its current chunk,
copy its existing data to the new chunk, and then deallocate the old chunk.
So now we have a chunk of size C followed by a chunk of size k * C. Continuing
this process we'll then have a chunk of size k * k * C to the right and so on.
That leads to a series of the form (using ^^ for power):

    C, C*k,  C*k^^2, C*k^^3, ...

If we choose k = 2 we know that every element in the series will
be strictly larger than the sum of all previous ones because of
the remarkable equality:

    1 + 2^^1 + 2^^2 + 2^^3... + 2^^n = 2^^(n+1) - 1

This means that any new chunk requested will be larger
than all previously used chunks combined, so the vector must
crawl forward in memory; it can't move back to its deallocated chunks.
But any number smaller than 2 guarantees that you'll at some point be 
able to reuse the previous chunks. For instance, choosing 1.5 as the factor
allows memory reuse after 4 reallocations; 1.45 allows memory reuse after 3
reallocations; and 1.3 allows reuse after only 2 reallocations.

Of course, the above makes a number of simplifying assumptions
about how the memory allocator works, but definitely you don't
want to choose the theoretically absolute worst growth factor.
`fbvector` uses a growth factor of 1.5. That does not impede good
performance at small sizes because of the way `fbvector`
cooperates with jemalloc (below).

### The jemalloc Connection
***

Virtually all modern allocators allocate memory in fixed-size
quanta that are chosen to minimize management overhead while at
the same time offering good coverage at low slack. For example, an
allocator may choose blocks of doubling size (32, 64, 128,
<t_co>, ...) up to 4096, and then blocks of size multiples of a
page up until 1MB, and then 512KB increments and so on.

As discussed above, `std::vector` also needs to (re)allocate in
quanta. The next quantum is usually defined in terms of the
current size times the infamous growth constant. Because of this
setup, `std::vector` has some slack memory at the end much like
an allocated block has some slack memory at the end.

It doesn't take a rocket surgeon to figure out that an allocator-
aware `std::vector` would be a marriage made in heaven: the
vector could directly request blocks of "perfect" size from the
allocator so there would be virtually no slack in the allocator.
Also, the entire growth strategy could be adjusted to work
perfectly with allocator's own block growth strategy. That's
exactly what `fbvector` does - it automatically detects the use
of jemalloc and adjusts its reallocation strategy accordingly.

But wait, there's more. Many memory allocators do not support in-
place reallocation, although most of them could. This comes from
the now notorious design of `realloc()` to opaquely perform
either in-place reallocation or an allocate-memcpy-deallocate
cycle. Such lack of control subsequently forced all clib-based
allocator designs to avoid in-place reallocation, and that
includes C++'s `new` and `std::allocator`. This is a major loss of
efficiency because an in-place reallocation, being very cheap,
may mean a much less aggressive growth strategy. In turn that
means less slack memory and faster reallocations.

### Object Relocation
***

One particularly sensitive topic about handling C++ values is
that they are all conservatively considered <i>non-
relocatable</i>. In contrast, a relocatable value would preserve
its invariant even if its bits were moved arbitrarily in memory.
For example, an `int32_t` is relocatable because moving its 4 bytes
would preserve its actual value, so the address of that value
does not "matter" to its integrity.

C++'s assumption of non-relocatable values hurts everybody for
the benefit of a few questionable designs. The issue is that
moving a C++ object "by the book" entails (a) creating a new copy
from the existing value; (b) destroying the old value. This is
quite vexing and violates common sense; consider this
hypothetical conversation between Captain Picard and an
incredulous alien:

Incredulous Alien: "So, this teleporter, how does it work?"<br>
Picard: "It beams people and arbitrary matter from one place to
another."<br> Incredulous Alien: "Hmmm... is it safe?"<br>
Picard: "Yes, but earlier models were a hassle. They'd clone the
person to another location. Then the teleporting chief would have
to shoot the original. Ask O'Brien, he was an intern during those
times. A bloody mess, that's what it was."

Only a tiny minority of objects are genuinely non-relocatable:

* Objects that use internal pointers, e.g.:
```cpp
    class Ew {
      char buffer[1024];
      char * pointerInsideBuffer;
    public:
      Ew() : pointerInsideBuffer(buffer) {}
      ...
    }
```
* Objects that need to update "observers" that store pointers to them.

The first class of designs can always be redone at small or no
cost in efficiency. The second class of objects should not be
values in the first place - they should be allocated with `new`
and manipulated using (smart) pointers. It is highly unusual for
a value to have observers that alias pointers to it.

Relocatable objects are of high interest to `std::vector` because
such knowledge makes insertion into the vector and vector
reallocation considerably faster: instead of going to Picard's
copy-destroy cycle, relocatable objects can be moved around
simply by using `memcpy` or `memmove`. This optimization can
yield arbitrarily high wins in efficiency; for example, it
transforms `vector< vector<double> >` or `vector< hash_map<int,
string> >` from risky liabilities into highly workable
compositions.

In order to allow fast relocation without risk, `fbvector` uses a
trait `folly::IsRelocatable` defined in `"folly/Traits.h"`. By default,
`folly::IsRelocatable::value` conservatively yields false. If
you know that your type `Widget` is in fact relocatable, go right
after `Widget`'s definition and write this:
```cpp
    // at global namespace level
    namespace folly {
      struct IsRelocatable<Widget> : boost::true_type {};
    }
```
If you don't do this, `fbvector<Widget>` will fail to compile
with a `static_assert`.

### Miscellaneous
***

`fbvector` uses a careful implementation all around to make
sure it doesn't lose efficiency through the cracks. Some future
directions may be in improving raw memory copying (`memcpy` is
not an intrinsic in gcc and does not work terribly well for
large chunks) and in furthering the collaboration with
jemalloc. Have fun!

---

### Vnext External Folly Folly Docs Format (`vnext/external/folly/folly/docs/Format.md`)

`folly/Format.h`
----------------

`folly/Format.h` provides a fast, powerful, type-safe, flexible facility
for formatting text, using a specification language similar to Python's
[str.format](http://docs.python.org/library/string.html#formatstrings).
By default, it can format strings, numbers (integral and floating point),
and dynamically-typed `folly::dynamic` objects, and can extract values from
random-access containers and string-keyed maps.  In many cases, `format` is
faster than `sprintf` as well as being fully type-safe.

### Overview
***

Here are some code samples to get started:

```
/* Detailed source-code truncated for AI context efficiency. */
```


### Format string syntax
***

Format string (`format`):
`"{" [arg_index] ["[" key "]"] [":" format_spec] "}"`

- `arg_index`: index of argument to format; default = next argument.  Note
  that a format string may have either default argument indexes or
  non-default argument indexes, but not both (to avoid confusion).
- `key`: if the argument is a container (C-style array or pointer,
  `std::array`, vector, deque, map), you may use this
  to select the element to format; works with random-access sequences and
  integer- and string-keyed maps.  Multiple level keys work as well, with
  components separated with "."; for example, given
  `map<string, map<string, string>> m`, `{[foo.bar]}` selects
  `m["foo"]["bar"]`.
- `format_spec`: format specification, see below

Format specification:
`[[fill] align] [sign] ["#"] ["0"] [width] [","] ["." precision] ["."] [type]`

- `fill` (may only be specified if `align` is also specified): pad with this
  character ('` `' (space) or '`0`' (zero) might be useful; space is default)
- `align`: one of '`<`', '`>`', '`=`', '`^`':
    - '`<`': left-align (default for most objects)
    - '`>`': right-align (default for numbers)
    - '`=`': pad after sign, but before significant digits; used to print
            `-0000120`; only valid for numbers
    - '`^`': center
- `sign`: one of '`+`', '`-`', ' ' (space) (only valid for numbers)
    - '`+`': output '`+`' if positive or zero, '`-`' if negative
    - '`-`': output '`-`' if negative, nothing otherwise (default)
    - '` `' (space): output '` `' (space) if positive or zero, '`-`' if negative
- '`#`': output base prefix (`0` for octal, `0b` or `0B` for binary, `0x` or
  `0X` for hexadecimal; only valid for integers)
- '`0`': 0-pad after sign, same as specifying "`0=`" as the `fill` and
  `align` parameters (only valid for numbers)
- `width`: minimum field width. May be '`*`' to indicate that the field width
  is given by an argument. Defaults to the next argument (preceding the value
  to be formatted) but an explicit argument index may be given following the
  '`*`'.
- '`,`' (comma): output comma as thousands' separator (only valid for integers,
  and only for decimal output)
- `precision` (not allowed for integers):
    - for floating point values, number of digits after decimal point ('`f`' or
      '`F`' presentation) or number of significant digits ('`g`' or '`G`')
    - for others, maximum field size (truncate subsequent characters)
- '`.`' (when used after precision or in lieu of precison): Forces a trailing
  decimal point to make it clear this is a floating point value.
- `type`: presentation format, see below

Presentation formats:

- Strings (`folly::StringPiece`, `std::string`, `folly::fbstring`,
  `const char*`):
    - '`s`' (default)
- Integers:
    - '`b`': output in binary (base 2) ("`0b`" prefix if '`#`' specified)
    - '`B`': output in binary (base 2) ("`0B`" prefix if '`#`' specified)
    - '`c`': output as a character (cast to `char`)
    - '`d`': output in decimal (base 10) (default)
    - '`o`': output in octal (base 8)
    - '`O`': output in octal (base 8) (same as '`o`')
    - '`x`': output in hexadecimal (base 16) (lower-case digits above 9)
    - '`X`': output in hexadecimal (base 16) (upper-case digits above 9)
    - '`n`': locale-aware output (currently same as '`d`')
- `bool`:
    - default: output "`true`" or "`false`" as strings
    - integer presentations allowed as well
- `char`:
    - same as other integers, but default is '`c`' instead of '`d`'
- Floating point (`float`, `double`; `long double` is not implemented):
    - '`e`': scientific notation using '`e`' as exponent character
    - '`E`': scientific notation using '`E`' as exponent character
    - '`f`': fixed point
    - '`F`': fixed point (same as '`f`')
    - '`g`': general; use either '`f`' or '`e`' depending on magnitude (default)
    - '`G`': general; use either '`f`' or '`E`' depending on magnitude
    - '`n`': locale-aware version of '`g`' (currently same as '`g`')
    - '`%`': percentage: multiply by 100 then display as '`f`'


### Extension
***

You can extend `format` for your own class by providing a specialization for
`folly::FormatValue`.  See `folly/Format.h` and `folly/FormatArg.h` for
details, and the existing specialization for `folly::dynamic` in
`folly/dynamic-inl.h` for an implementation example.

---

### Vnext External Folly Folly Docs Function (`vnext/external/folly/folly/docs/Function.md`)

`folly/Function.h`
------------------

`folly::Function` is a polymorphic function wrapper that is not copyable and does not require the wrapped function to be copy constructible. It is similar to `std::function`, but different with respect to some interesting features.

There are some limitations in `std::function` that `folly::Function` tries to avoid. `std::function` is copy-constructible and requires that the callable that it wraps is copy-constructible as well, which is a constraint that is often inconvenient. In most cases when using a `std::function` you don't make use of its copy-constructibility, so you might sometimes feel like you get back very little in return for a noticeable restriction.

This restriction becomes apparent when trying to use a lambda capturing a `unique_ptr` (or any non-copyable type) as a callback for a folly::Future.
``` Cpp
std::unique_ptr<Foo> foo_ptr = new Foo;

some_future.then(
    [foo_ptr = std::move(foo_ptr)] mutable
    (int x)
    { foo_ptr->setX(x); }
);
```
This piece of code did not compile before `folly::Future` started using `folly::Function` instead of `std::function` to store the callback. Because the lambda captures something non-copyable (the `unique_ptr`), it is not copyable itself. And `std::function` can only store copyable callables.

The implementation of folly::Future did not make use of the copy-constructibility of `std::function` at any point. There was no benefit from the fact that the `std::function` is copy-constructible, but the fact that it can only wrap copy-constructible callables posed a restriction.

A workaround was available: `folly::MoveWrapper`, which wraps an object that may be non-copyable and implements copy operations by moving the embedded object. Using a `folly::MoveWrapper`, you can capture non-copyable objects in a lambda, and the lambda itself is still copyable and may be wrapped in a `std::function`. It is a pragmatic solution for the above problem, but you have to be a little careful. The problem is that you can’t use a `MoveWrapper` anywhere where copy operations are assumed to behave like actual copy operations. Also, a `folly::MoveWrapper<std::unique_ptr<T>>` essentially behaves like `auto_ptr<T>`. Ask yourself whether you’d want to use lots of `auto_ptr`s in your codebase. And the original question still persists: we very often don’t benefit from copy-constructibility of `std::function`, so why do we have to live with this restriction? I.e. why do we have to use `MoveWrapper`?

`folly::Function` is an actual solution to this problem, as it can wrap non-copyable callables, at the cost of not being copy-constructible, which more often than not is not a relevant restriction. `folly::Future` now uses `folly::Function` to store callbacks, so the good news is: the code example from the top of this note is becoming a perfectly valid way to use future callbacks. The code compiles and behaves as you would expect.

Here are more details about `folly::Function`: much like `std::function`, it wraps an arbitrary object that can be invoked like a given function type. E.g. a `folly::Function<int(std::string, double)>` can wrap any callable object that returns an `int` (or something that is convertible to an `int`) when invoked with a `std::string` and a `double` argument. The function type is a template parameter of `folly::Function`, but the specific type of the callable is not.

Other than copyability, there is one more significant difference between `std::function` and `folly::Function`, and it concerns const-correctness. `std::function` does not enforce const-correctness: it allows you to store mutable callables (i.e. callables that may change their inner state when executed, such as a mutable lambda) and call them in a const context (i.e. when you only have access to a const reference to the `std::function` object). For example:
``` Cpp
class FooBar {
 public:
  void call_func() const {
    func_();
  }
 private:
  std::function<void()> func_;
};
```
The `call_func` member function is declared const. However, when it calls `func_()`, it may change the inner state of `func_`, and thereby the inner state of the `FooBar` object. Inside the `FooBar` class, `func_` is like a non-const method that is callable from const methods.

Some people consider `std::function` in the standard broken with respect to this. (Paper N4348 explains this problem in more detail.) It also lists possible ways to fix the problem. `folly::Function`, however, goes a different way: you have to declare whether you want to store a const function, in which case you can invoke any reference (const or non-const) of the `folly::Function`, or a non-const (mutable) function, in which case you need a non-const reference to the `folly::Function` to be able to invoke it. In the above example, let’s say that `func_` stores a const function, which makes it okay that it gets invoked from `call_func` (a const method). Instead of `std::function`, you could use `folly::Function<void() const>` for the `func_` member.

Const-ness is part of a function type. To illustrate:
``` Cpp
class Foo {
 public:
  int operator()() { return 1; }
  int operator()(char const*) { return 2; }
  int operator()(int) { return 3; }
  int operator()(int) const { return 4; }
  int operator()(int, int) const { return 5; }
};
```
You can overload methods multiple times using different argument signatures. Const-ness is part of that signature, so even for the same set of argument types you can overload a const and a non-const version. It’s not even particularly unusual to do that. Take for instance the `begin()` method of STL container types: `begin()` returns an `iterator`, `begin() const` returns a `const_iterator`. `folly::Function` allows you to select a specific overload easily:
``` Cpp
folly::Function<int()> uf1 = Foo();
// uf1() returns 1
folly::Function<int(char const*)> uf2 = Foo();
// uf2() returns 2
folly::Function<int(int)> uf3 = Foo();
// uf3() returns 3
folly::Function<int(int) const> uf4 = Foo();
// uf4() returns 4
folly::Function<int(int, int) const> uf5 = Foo();
// uf5() returns 5
```
If `cfoo` is a const-reference to a `Foo` object, `cfoo(int)` returns 4. If `foo` is a non-const reference to a `Foo` object, `foo(int)` returns 3. Normal const-to-non-const conversion behavior applies: if you call `foo(int, int)` it will return 5: a non-const reference will invoke the const method if no non-const method is defined. Which leads to the following behavior:
``` Cpp
folly::Function<int(int, int)> uf5nc = Foo();
// uf5nc() returns 5
```
If you are wondering if the introduction of const function types means that you have to change lots of normal function types to const function types if you want to use `folly::Function`: not really, or at least not as much as you might think. There are only two reasons to use a `folly::Function` with a const function type:
* a callable object defines both const and non-const `operator()` and you explicitly want to select the const one
* you need to invoke a `folly::Function` from a const context (i.e. you only have a const reference to the `folly::Function`)

In practice, you will not need the const variant very often. Adding const to a function type adds a restriction for the callable: it must not change its inner state when invoked. If you don’t care whether it does or not, don’t worry about const!

A `folly::Function<R(Args...) const>` can be converted into a `folly::Function<R(Args...)>`: either way the stored callable will not change its inner state when invoked. The former type expresses and guarantees that, the latter does not. When you get rid of the const, the selected function stays the same:
``` Cpp
folly::Function<int(int)> uf4nc = std::move(uf4);
// uf4nc() returns 4, not 3!
```
If you want to go the other way, you are talking about a (potentially dangerous) const cast: a callable that may or may not change its inner state is declared as one that guarantees not to do that. Proceed at your own risk! This conversion does not happen implicitly, though:
``` Cpp
folly::Function<int() const> uf1c = folly::constCastFunction(std::move(uf1));
// uf1c() returns 1
```
Admittedly, seeing const function types as template parameters is unfamiliar. As far as I am aware it happens nowhere in the standard library. But it is the most consistent way to deal with the issue of const-correctness here. Const qualifiers are part of a function type, as a matter of fact. If you require a const-qualified function to be wrapped in a `folly::Function`, just declare it as that! More often than not you will find that you do not need the const qualifier. While writing the `folly::Function` implementation, a good set of unit tests had existed before the const function types got introduced. Not a single one of those unit tests had to be changed: they all compiled and passed after the introduction of const function types. Obviously new ones were added to test the const-correctness. But in your day-to-day use of `folly::Function` you won’t have to worry about const very often.

Memory usage
============
Like most implementations of `std::function`, `folly::Function` stores small callable objects in-line and larger callable objects will be stored on the heap. `folly::Function` returns the size of the allocation it has made from its `heapAllocatedMemory()` member function; naturally it will return `0` when the callable is stored in-line.

---

### Vnext External Folly Folly Docs Futures (`vnext/external/folly/folly/docs/Futures.md`)

# Futures

### Futures is a framework for expressing asynchronous code in C++ using the Promise/Future pattern.

# Overview

Folly Futures is an async C++ framework inspired by [Twitter's Futures](https://twitter.github.io/finagle/guide/Futures.html) implementation in Scala (see also [Future.scala](https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/Future.scala), [Promise.scala](https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/Promise.scala), and friends), and loosely builds upon the existing but anemic Futures code found in the C++11 standard ([std::future](https://en.cppreference.com/w/cpp/thread/future)) and [boost::future](https://www.boost.org/doc/libs/1_53_0/doc/html/thread/synchronization.html#thread.synchronization.futures) (especially >= 1.53.0). Although inspired by the C++11 std::future interface, it is not a drop-in replacement because some ideas don't translate well enough to maintain API compatibility.

The primary difference from std::future is that you can attach callbacks to Futures (with `thenValue` or `thenTry`), under the control of an executor to manage where work runs, which enables sequential and parallel composition of Futures for cleaner asynchronous code.

# Brief Synopsis

```cpp
#include <folly/futures/Future.h>
#include <folly/executors/ThreadedExecutor.h>
using namespace folly;
using namespace std;

void foo(int x) {
  // do something with x
  cout << "foo(" << x << ")" << endl;
}

// ...
  folly::ThreadedExecutor executor;
  cout << "making Promise" << endl;
  Promise<int> p;
  Future<int> f = p.getSemiFuture().via(&executor);
  auto f2 = move(f).thenValue(foo);
  cout << "Future chain made" << endl;

// ... now perhaps in another event callback

  cout << "fulfilling Promise" << endl;
  p.setValue(42);
  move(f2).get();
  cout << "Promise fulfilled" << endl;
```

This would print:

```
making Promise
Future chain made
fulfilling Promise
foo(42)
Promise fulfilled
```

## Blog Post

In addition to this document, there is [a blog post on code.facebook.com (June
2015)](https://code.facebook.com/posts/1661982097368498/futures-for-c-11-at-facebook/).

# Brief guide
This brief guide covers the basics. For a more in-depth coverage skip to the appropriate section.

Let's begin with an example using an imaginary simplified Memcache client interface:

```cpp
using std::string;
class MemcacheClient {
 public:
  struct GetReply {
    enum class Result {
      FOUND,
      NOT_FOUND,
      SERVER_ERROR,
    };

    Result result;
    // The value when result is FOUND,
    // The error message when result is SERVER_ERROR or CLIENT_ERROR
    // undefined otherwise
    string value;
  };

  GetReply get(string key);
};
```

This API is synchronous, i.e. when you call `get()` you have to wait for the result. This is very simple, but unfortunately it is also very easy to write very slow code using synchronous APIs.

Now, consider this traditional asynchronous signature for the same operation:

```cpp
int async_get(string key, std::function<void(GetReply)> callback);
```

When you call `async_get()`, your asynchronous operation begins and when it finishes your callback will be called with the result. Very performant code can be written with an API like this, but for nontrivial applications the code devolves into a special kind of spaghetti code affectionately referred to as "callback hell".

The Future-based API looks like this:

```cpp
SemiFuture<GetReply> future_get(string key);
```

A `SemiFuture<GetReply>` or `Future<GetReply>` is a placeholder for the `GetReply` that we will eventually get. For most of the descriptive text below, Future can refer to either `folly::SemiFuture` or `folly::Future` as the former is a safe subset of the latter. A Future usually starts life out "unfulfilled", or incomplete, i.e.:

```cpp
fut.isReady() == false
fut.value()  // will throw an exception because the Future is not ready
```

At some point in the future, the `Future` will have been fulfilled, and we can access its value.

```cpp
fut.isReady() == true
GetReply& reply = fut.value();
```

Futures support exceptions. If the asynchronous producer fails with an exception, your Future may represent an exception instead of a value. In that case:

```cpp
fut.isReady() == true
fut.value() // will rethrow the exception
```

Just what is exceptional depends on the API. In our example we have chosen not to raise exceptions for `SERVER_ERROR`, but represent this explicitly in the `GetReply` object. On the other hand, an astute Memcache veteran would notice that we left `CLIENT_ERROR` out of `GetReply::Result`, and perhaps a `CLIENT_ERROR` would have been raised as an exception, because `CLIENT_ERROR` means there's a bug in the library and this would be truly exceptional. These decisions are judgement calls by the API designer. The important thing is that exceptional conditions (including and especially spurious exceptions that nobody expects) get captured and can be handled higher up the "stack".

So far we have described a way to initiate an asynchronous operation via an API that returns a Future, and then sometime later after it is fulfilled, we get its value. This is slightly more useful than a synchronous API, but it's not yet ideal. There are two more very important pieces to the puzzle.

First, we can aggregate Futures, to define a new Future that completes after some or all of the aggregated Futures complete. Consider two examples: fetching a batch of requests and waiting for all of them, and fetching a group of requests and waiting for only one of them.

```cpp
MemcacheClient mc;

vector<SemiFuture<GetReply>> futs;
for (auto& key : keys) {
  futs.push_back(mc.future_get(key));
}
auto all = collectAll(futs.begin(), futs.end());

vector<SemiFuture<GetReply>> futs;
for (auto& key : keys) {
  futs.push_back(mc.future_get(key));
}
auto any = collectAny(futs.begin(), futs.end());

vector<SemiFuture<GetReply>> futs;
for (auto& key : keys) {
  futs.push_back(mc.future_get(key));
}
auto anyv = collectAnyWithoutException(futs.begin(), futs.end());
```

`all` and `any` are Futures (for the exact type and usage see the header files). They will be complete when all/one of futs are complete, respectively. (There is also `collectN()` for when you need some, and `collectAnyWithoutException` when you need one value if some value would be available.)

Second, we can associate a Future with an executor. An executor specifies where work will run, and we detail this more later. In summary, given an executor we can convert a `SemiFuture` to a `Future` with an executor, or a `Future` on one executor to a `Future` on another executor.

For example:

```cpp
folly::ThreadedExecutor executor;
SemiFuture<GetReply> semiFut = mc.future_get("foo");
Future<GetReply> fut1 = std::move(semiFut).via(&executor);
```

Once an executor is attached, a `Future` allows continuations to be attached and chained together monadically. An example will clarify:

```cpp
SemiFuture<GetReply> semiFut = mc.future_get("foo");
Future<GetReply> fut1 = std::move(semiFut).via(&executor);

Future<string> fut2 = std::move(fut1).thenValue(
  [](GetReply reply) {
    if (reply.result == MemcacheClient::GetReply::Result::FOUND)
      return reply.value;
    throw SomeException("No value");
  });

Future<Unit> fut3 = std::move(fut2)
  .thenValue([](string str) {
    cout << str << endl;
  })
  .thenTry([](folly::Try<string> strTry) {
    cout << strTry.value() << endl;
  })
  .thenError(folly::tag_t<std::exception>{}, [](std::exception const& e) {
    cerr << e.what() << endl;
  });
```

That example is a little contrived but the idea is that you can transform a result from one type to another, potentially in a chain, and unhandled errors propagate. Of course, the intermediate variables are optional.

Using `.thenValue` or `.thenTry` to add callbacks is idiomatic. It brings all the code into one place, which avoids callback hell. `.thenValue` appends a continuation that takes `T&&` for some `Future<T>` and an error bypasses the callback and is passed to the next, `thenTry` takes a callback taking `folly::Try<T>` which encapsulates both value and exception. `thenError(tag_t<ExceptionType>{},...` will bypass a value and only run if there is an exception, the `ExceptionType` template parameter to the tag type allows filtering by exception type; `tag_t<ExceptionType>{}` is optional and if no tag is passed passed the function will be parameterized with a `folly::exception_wrapper`. For C++17 there is a global inline variable and `folly::tag<ExceptionType>` may be passed directly without explicit construction.



Up to this point we have skirted around the matter of waiting for Futures. You may never need to wait for a Future, because your code is event-driven and all follow-up action happens in a then-block. But if want to have a batch workflow, where you initiate a batch of asynchronous operations and then wait for them all to finish at a synchronization point, then you will want to wait for a Future. Futures have a blocking method called `wait()` that does exactly that and optionally takes a timeout.

Futures are partially threadsafe. A Promise or Future can migrate between threads as long as there's a full memory barrier of some sort. `Future::thenValue` and `Promise::setValue` (and all variants that boil down to those two calls) can be called from different threads. **But**, be warned that you might be surprised about which thread your callback executes on. Let's consider an example, where we take a future straight from a promise, without going via the safer SemiFuture, and where we therefore have a `Future` that does not carry an executor. This is in general something to avoid.

```cpp
// Thread A
Promise<Unit> p;
auto f = p.getFuture();

// Thread B
std::move(f).thenValue(x).thenValue(y).thenTry(z);

// Thread A
p.setValue();
```

This is legal and technically threadsafe. However, it is important to realize that you do not know in which thread `x`, `y`, and/or `z` will execute. Maybe they will execute in Thread A when `p.setValue()` is called. Or, maybe they will execute in Thread B when `f.thenValue` is called. Or, maybe `x` will execute in Thread A, but `y` and/or `z` will execute in Thread B. There's a race between `setValue` and `then`—whichever runs last will execute the callback. The only guarantee is that one of them will run the callback.

For safety, `.via` should be preferred. We can chain `.via` operations to give very strong control over where callbacks run:

```cpp
std::move(aFuture)
  .thenValue(x)
  .via(e1).thenValue(y1).thenValue(y2)
  .via(e2).thenValue(z);
```

`x` will execute in the context of the executor associated with `aFuture`. `y1` and `y2` will execute in the context of `e1`, and `z` will execute in the context of `e2`. If after `z` you want to get back to the original context, you need to get there with a call to `via` passing the original executor.

# You make me Promises, Promises

If you are wrapping an asynchronous operation, or providing an asynchronous API to users, then you will want to make `Promise`s. Every Future has a corresponding Promise (except Futures that spring into existence already completed, with `makeFuture()`). Promises are simple: you make one, you extract the Future, and you fulfill it with a value or an exception. Example:

```cpp
Promise<int> p;
SemiFuture<int> f = p.getSemiFuture();

f.isReady() == false

p.setValue(42);

f.isReady() == true
f.value() == 42
```

and an exception example:

```cpp
Promise<int> p;
SemiFuture<int> f = p.getSemiFuture();

f.isReady() == false

p.setException(std::runtime_error("Fail"));

f.isReady() == true
f.value() // throws the exception
```

It's good practice to use setWith which takes a function and automatically captures exceptions, e.g.

```cpp
Promise<int> p;
p.setWith([]{
  try {
    // do stuff that may throw
    return 42;
  } catch (MySpecialException const& e) {
    // handle it
    return 7;
  }
  // Any exceptions that we didn't catch, will be caught for us
});
```

---

### Vnext External Folly Folly Docs GroupVarint (`vnext/external/folly/folly/docs/GroupVarint.md`)

`folly/GroupVarint.h`
---------------------

`folly/GroupVarint.h` is an implementation of variable-length encoding for 32-
and 64-bit integers using the Group Varint encoding scheme as described in
Jeff Dean's [WSDM 2009 talk][wsdm] and in [Information Retrieval: Implementing
and Evaluating Search Engines][irbook].

[wsdm]: http://research.google.com/people/jeff/WSDM09-keynote.pdf
[irbook]: http://www.ir.uwaterloo.ca/book/addenda-06-index-compression.html

Briefly, a group of four 32-bit integers is encoded as a sequence of variable
length, between 5 and 17 bytes; the first byte encodes the length (in bytes)
of each integer in the group.  A group of five 64-bit integers is encoded as a
sequence of variable length, between 7 and 42 bytes; the first two bytes
encode the length (in bytes) of each integer in the group.

`GroupVarint.h` defines a few classes:

* `GroupVarint<T>`, where `T` is `uint32_t` or `uint64_t`:

    Basic encoding / decoding interface, mainly aimed at encoding / decoding
    one group at a time.

* `GroupVarintEncoder<T, Output>`, where `T` is `uint32_t` or `uint64_t`,
  and `Output` is a functor that accepts `StringPiece` objects as arguments:

    Streaming encoder: add values one at a time, and they will be
    flushed to the output one group at a time.  Handles the case where
    the last group is incomplete (the number of integers to encode isn't
    a multiple of the group size)

* `GroupVarintDecoder<T>`, where `T` is `uint32_t` or `uint64_t`:

    Streaming decoder: extract values one at a time.  Handles the case where
    the last group is incomplete.

The 32-bit implementation is significantly faster than the 64-bit
implementation; on platforms supporting the SSSE3 instruction set, we
use the PSHUFB instruction to speed up lookup, as described in [SIMD-Based
Decoding of Posting Lists][cikmpaper] (CIKM 2011).

[cikmpaper]: http://www.stepanovpapers.com/CIKM_2011.pdf

For more details, see the header file `folly/GroupVarint.h` and the
associated test file `folly/test/GroupVarintTest.cpp`.

---

### Vnext External Folly Folly Docs Histogram (`vnext/external/folly/folly/docs/Histogram.md`)

`folly/stats/Histogram.h`
-------------------

### Classes
***

#### `Histogram`

`Histogram.h` defines a simple histogram class, templated on the type of data
you want to store.  This class is useful for tracking a large stream of data
points, where you want to remember the overall distribution of the data, but do
not need to remember each data point individually.

Each histogram bucket stores the number of data points that fell in the bucket,
as well as the overall sum of the data points in the bucket.  Note that no
overflow checking is performed, so if you have a bucket with a large number of
very large values, it may overflow and cause inaccurate data for this bucket.
As such, the histogram class is not well suited to storing data points with
very large values.  However, it works very well for smaller data points such as
request latencies, request or response sizes, etc.

In addition to providing access to the raw bucket data, the `Histogram` class
also provides methods for estimating percentile values.  This allows you to
estimate the median value (the 50th percentile) and other values such as the
95th or 99th percentiles.

All of the buckets have the same width.  The number of buckets and bucket width
is fixed for the lifetime of the histogram.  As such, you do need to know your
expected data range ahead of time in order to have accurate statistics.  The
histogram does keep one bucket to store all data points that fall below the
histogram minimum, and one bucket for the data points above the maximum.
However, because these buckets don't have a good lower/upper bound, percentile
estimates in these buckets may be inaccurate.

#### `HistogramBuckets`

The `Histogram` class is built on top of `HistogramBuckets`.
`HistogramBuckets` provides an API very similar to `Histogram`, but allows a
user-defined bucket class.  This allows users to implement more complex
histogram types that store more than just the count and sum in each bucket.

When computing percentile estimates `HistogramBuckets` allows user-defined
functions for computing the average value and data count in each bucket.  This
allows you to define more complex buckets which may have multiple different
ways of computing the average value and the count.

For example, one use case could be tracking timeseries data in each bucket.
Each set of timeseries data can have independent data in the bucket, which can
show how the data distribution is changing over time.

### Example Usage
***

Say we have code that sends many requests to remote services, and want to
generate a histogram showing how long the requests take.  The following code
will initialize histogram with 50 buckets, tracking values between 0 and 5000.
(There are 50 buckets since the bucket width is specified as 100.  If the
bucket width is not an even multiple of the histogram range, the last bucket
will simply be shorter than the others.)

``` Cpp
    folly::Histogram<int64_t> latencies(100, 0, 5000);
```

The addValue() method is used to add values to the histogram.  Each time a
request finishes we can add its latency to the histogram:

``` Cpp
    latencies.addValue(now - startTime);
```

You can access each of the histogram buckets to display the overall
distribution.  Note that bucket 0 tracks all data points that were below the
specified histogram minimum, and the last bucket tracks the data points that
were above the maximum.

``` Cpp
    auto numBuckets = latencies.getNumBuckets();
    cout << "Below min: " << latencies.getBucketByIndex(0).count << "\n";
    for (unsigned int n = 1; n < numBuckets - 1; ++n) {
      cout << latencies.getBucketMin(n) << "-" << latencies.getBucketMax(n)
           << ": " << latencies.getBucketByIndex(n).count << "\n";
    }
    cout << "Above max: "
         << latencies.getBucketByIndex(numBuckets - 1).count << "\n";
```

You can also use the `getPercentileEstimate()` method to estimate the value at
the Nth percentile in the distribution.  For example, to estimate the median,
as well as the 95th and 99th percentile values:

``` Cpp
    int64_t median = latencies.getPercentileEstimate(0.5);
    int64_t p95 = latencies.getPercentileEstimate(0.95);
    int64_t p99 = latencies.getPercentileEstimate(0.99);
```

### Thread Safety
***

Note that `Histogram` and `HistogramBuckets` objects are not thread-safe.  If
you wish to access a single `Histogram` from multiple threads, you must perform
your own locking to ensure that multiple threads do not access it at the same
time.

---

--- METRICS ---
- Files Extracted: 77
- Estimated Token Budget: ~125982 tokens
- Canonical Reference: https://codewiki.google/github.com/microsoft/react-native-windows
