Rust 1.57を早めに深掘り

こんにちは、R&Dチームの齋藤(@aznhe21)です。 今回の記事で自分がPlayStationと同い年ということを知りました。

さて、本日12/3(金)にRust 1.57がリリースされました。 この記事ではRust 1.57での変更点を詳しく紹介します。

12/3は初代PlayStationの発売日 全てのゲンゴは、ここに集まる。

ピックアップ

個人的に注目する変更点を「ピックアップ」としてまとめました。 全ての変更点を網羅したリストは変更点リストをご覧ください。

定数文脈でもパニック出来るようになった

const式の中でもpanic!が引き起こせるようになりました。static_assertionsクレートを使っている大部分を置換えられそうです。

struct Hoge(u8, usize);

// static_assertionsクレートを使う場合
extern crate static_assertions as sa;
sa::assert_eq_size!(Hoge, [usize; 2]);

// Rust 1.57から:単体で書く場合
// assert_eq!はDebugトレイトがconstでない関係で使えない(今のところ)
const _: () = assert!(std::mem::size_of::<Hoge>() == std::mem::size_of::<usize>() * 2);

コレクション型でメモリの確保エラーを捉えられるようになった

主なコレクション型(StringVecVecDequeHashMapHashSet)でメモリを確保出来ない場合のエラーを捉えられるようになりました。 領域予約時にエラーを捉えられる形で実装されています (挿入時にエラーを捉える形だとtry_pushやらtry_extendやらtry_insertやらと、APIがネズミ算式に増えてしまうためのようです)。

fn main() {
    let mut v: Vec<u8> = Vec::new();
    v.try_reserve(4 * 1024 * 1024 * 1024)
        .expect("4GiBを確保出来なかった");
    // OOMは発生し得ない
    v.extend(std::iter::repeat(1).take(4 * 1024 * 1024 * 1024));
}

Cargoのプロファイルを自作出来るようになった

これまでのCargoでのビルド設定はデバッグビルドとリリースビルドのみでしたが、 ビルド設定(プロファイル)を自作出来るようになりました。

これまでも下記のようにデバッグ用やリリース用にビルド設定をカスタマイズ出来ました。

[profile.dev.package.image]
# デバッグ時でもimageクレートは最適化する
opt-level = 2

[profile.release]
# バイナリサイズが小さくなるように最適化する
opt-level = s

これに加え、自作プロファイルを用意することで用途ごとにビルド設定をカスタマイズ出来るようになりました。 自作プロファイルはinheritsに継承元のプロファイルを指定します。定義済みのプロファイルとしてはdevreleasetestbenchdocがあります。

[profile.ci-test]
# CI向けの設定
inherits = "dev" # デバッグ用プロファイルを継承
incremental = false # 保存するデータが減るのでコンパイルが速くなる(かもしれない)

[profile.prod]
# 配布用バイナリ向けの設定
inherits = "release" # リリース用プロファイルを継承
lto = true

cargo test --profile=ci-testcargo build --profile=prodのように実行することでプロファイルを指定したビルドが出来ます。

安定化されたAPIのドキュメント

安定化されたAPIのドキュメントを独自に訳して紹介します。リストだけ見たい方は安定化されたAPIをご覧ください。

[T; N]::as_mut_slice

原典

#[lang = "array"]
impl<T, const N: usize> [T; N] {
    #[stable(feature = "array_as_slice", since = "1.57.0")]
    pub fn as_mut_slice(&mut self) -> &mut [T]
    { /* 実装は省略 */ }
}

配列全体を含む可変スライスを返す。&mut s[..]と同等である。

[T; N]::as_slice

原典

#[lang = "array"]
impl<T, const N: usize> [T; N] {
    #[stable(feature = "array_as_slice", since = "1.57.0")]
    pub const fn as_slice(&self) -> &[T]
    { /* 実装は省略 */ }
}

配列全体を含むスライスを返す。&s[..]と同等である。

alloc::collections::TryReserveError

原典

#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "try_reserve", since = "1.57.0")]
pub struct TryReserveError
{ /* フィールドは省略 */ }

try_reserveメソッドのためのエラー型。

alloc::collections::HashMap::try_reserve

原典

impl<K, V, S> HashMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    #[inline]
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたHashMap<K, V>に対し、最低でもadditional分の要素を挿入出来るよう領域の予約を試みる。 再三のメモリ確保を避けるため、より大きな領域が予約される場合がある。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::HashMap;

let mut map: HashMap<&str, isize> = HashMap::new();
map.try_reserve(10).expect("テストハーネスが10バイトでOOMするのはなぜ?");

alloc::collections::HashSet::try_reserve

原典

impl<T, S> HashSet<T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    #[inline]
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたHashSet<K, V>に対し、最低でもadditional分の要素を挿入出来るよう領域の予約を試みる。 再三のメモリ確保を避けるため、より大きな領域が予約される場合がある。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::HashSet;
let mut set: HashSet<i32> = HashSet::new();
set.try_reserve(10).expect("テストハーネスが10バイトでOOMするのはなぜ?");

alloc::string::String::try_reserve

原典

impl String {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたStringに対し、最低でもadditional分の要素を挿入出来るよう領域の予約を試みる。 再三のメモリ確保を避けるため、より大きな領域が予約される場合がある。 try_reserveを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.push_str(data);

    Ok(output)
}

alloc::string::String::try_reserve_exact

原典

impl String {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたStringに対し、ちょうどadditional分の要素を挿入出来るよう領域の予約を試みる。 try_reserve_exactを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

アロケーターは要求したよりも大きな空間を返すことがあるため、正確にちょうどの領域が確保されるとは限らない。 今後も挿入が予想される場合、try_reserveの使用が推奨される。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.push_str(data);

    Ok(output)
}

alloc::vec::Vec::try_reserve

原典

impl<T, A: Allocator> Vec<T, A> {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたVec<T>に対し、最低でもadditional分の要素を挿入出来るよう領域の予約を試みる。 再三のメモリ確保を避けるため、より大きな領域が予約される場合がある。 try_reserveを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // とても複雑な処理
    }));

    Ok(output)
}

alloc::vec::Vec::try_reserve_exact

原典

impl<T, A: Allocator> Vec<T, A> {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたVec<T>に対し、ちょうどadditional分の要素を挿入出来るよう領域の予約を試みる。 try_reserve_exactを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

アロケーターは要求したよりも大きな空間を返すことがあるため、正確にちょうどの領域が確保されるとは限らない。 今後も挿入が予想される場合、try_reserveの使用が推奨される。

エラー

領域がオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve_exact(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // とても複雑な処理
    }));

    Ok(output)
}

alloc::collections::VecDeque::try_reserve

原典

impl<T, A: Allocator> VecDeque<T, A> {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたVecDeque<T>に対し、最低でもadditional分の要素を挿入出来るよう領域の予約を試みる。 再三のメモリ確保を避けるため、より大きな領域が予約される場合がある。 try_reserveを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

エラー

領域がusizeでオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;
use std::collections::VecDeque;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
    let mut output = VecDeque::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // とても複雑な処理
    }));

    Ok(output)
}

alloc::collections::VecDeque::try_reserve_exact

原典

impl<T, A: Allocator> VecDeque<T, A> {
    #[stable(feature = "try_reserve", since = "1.57.0")]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError>
    { /* 実装は省略 */ }
}

渡されたVecDeque<T>に対し、ちょうどadditional分の要素を挿入出来るよう領域の予約を試みる。 try_reserve_exactを呼び出したあと、領域はself.len() + additional以上の大きさとなる。 領域が十分確保されている場合は何もしない。

アロケーターは要求したよりも大きな空間を返すことがあるため、正確にちょうどの領域が確保されるとは限らない。 今後も挿入が予想される場合、try_reserveの使用が推奨される。

エラー

領域がusizeでオーバーフローした、もしくはアロケーターが失敗を報告した場合、エラーが返る。

サンプル
use std::collections::TryReserveError;
use std::collections::VecDeque;

fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
    let mut output = VecDeque::new();

    // メモリを事前確保する。出来なければ終了
    output.try_reserve_exact(data.len())?;

    // 複雑な作業の合間でもOOMが発生することはない
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // とても複雑な処理
    }));

    Ok(output)
}

core::iter::Iterator::map_while

原典

#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub trait Iterator {
    #[inline]
    #[stable(feature = "iter_map_while", since = "1.57.0")]
    fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
    where
        Self: Sized,
        P: FnMut(Self::Item) -> Option<B>,
    { /* 実装は省略 */ }
}

述語と写像の両方に基づき要素を列挙するイテレーターを生成する。

map_while()は引数にクロージャーを取る。このクロージャーはイテレーターの要素ごとに呼ばれ、その戻り値がSome(_)の間要素を列挙する。

サンプル

基本的な使い方:

let a = [-1i32, 4, 0, 1];

let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);

take_whilemapを使った同義のサンプル:

let a = [-1i32, 4, 0, 1];

let mut iter = a.iter()
                .map(|x| 16i32.checked_div(*x))
                .take_while(|x| x.is_some())
                .map(|x| x.unwrap());

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);

最初のNoneのあとに止まっている。

use std::convert::TryFrom;

let a = [0, 1, 2, -3, 4, 5, -6];

let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
let vec = iter.collect::<Vec<_>>();

// u32に適した要素はまだある(4と5)が、`map_while`が`-3`の時に`None`を返し(`predicate`が`None`を返す)、
// `collect`は最初に出くわす`None`で停止する
assert_eq!(vec, vec![0, 1, 2]);

map_while()は値が含まれるべきかどうかを判断するために値を調べるため、イテレーターを消費してもその値は無い。

use std::convert::TryFrom;

let a = [1, 2, -3, 4];
let mut iter = a.iter();

let result: Vec<u32> = iter.by_ref()
                           .map_while(|n| u32::try_from(*n).ok())
                           .collect();

assert_eq!(result, &[1, 2]);

let result: Vec<i32> = iter.cloned().collect();

assert_eq!(result, &[4]);

-3は繰り返し処理を終了すべきかを判断するために消費され、イテレーターに戻されることもないため存在しない。

このイテレーターはtake_whileと異なり保護(fuse)されていないことに注意されたい。 また、最初のNoneが返されたあとにこのイテレーターが何を返すかも規定されていない。 保護されたイテレーターが必要な場合はfuseメソッドを使用されたい。

core::iter::MapWhile

原典

[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "iter_map_while", since = "1.57.0")]
#[derive(Clone)]
pub struct MapWhile<I, P>
{ /* フィールドは省略 */ }

predicateSome(_)を返す要素のみ受け入れるイテレーター。

この構造体はIteratormap_whileメソッドによって生成される。 詳細はそちらのドキュメントを参照されたい。

proc_macro::is_available

原典

#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
pub fn is_available() -> bool
{ /* 実装は省略 */ }

現在実行中のプログラムからproc_macroにアクセス可能かどうかを判断する。

proc_macroクレートは手続きマクロの実装内で使われることのみを目的としたクレート。 このクレート内の全ての関数は、ビルドスクリプトや単体テスト、通常のRustバイナリのような手続きマクロ外から呼び出された場合はパニックする。

マクロ・非マクロの両用法をサポートするよう設計されたRustライブラリを考慮し、 proc_macro::is_availableは、proc_macroのAPIを利用するために必要な基盤が現在利用可能かどうかを検出するためのパニックしない方法を提供する。 手続きマクロ内から呼び出された場合はtrueを、その他のバイナリから呼び出された場合はfalseを返す。

Command::get_program

原典

impl Command {
    #[stable(feature = "command_access", since = "1.57.0")]
    pub fn get_program(&self) -> &OsStr
    { /* 実装は省略 */ }
}

Command::newに渡されたプログラムへのパスを返す。

サンプル
use std::process::Command;

let cmd = Command::new("echo");
assert_eq!(cmd.get_program(), "echo");

Command::get_args

原典

impl Command {
    #[stable(feature = "command_access", since = "1.57.0")]
    pub fn get_args(&self) -> CommandArgs<'_>
    { /* 実装は省略 */ }
}

プログラムに渡される引数のイテレーターを返す。

最初の引数としてのプログラムへのパスは含まれず、Command::argCommand::argsで指定された引数のみが含まれる。

サンプル
use std::ffi::OsStr;
use std::process::Command;

let mut cmd = Command::new("echo");
cmd.arg("1番目").arg("2番目");
let args: Vec<&OsStr> = cmd.get_args().collect();
assert_eq!(args, &["1番目", "2番目"]);

Command::get_envs

原典

impl Command {
    #[stable(feature = "command_access", since = "1.57.0")]
    pub fn get_envs(&self) -> CommandEnvs<'_>
    { /* 実装は省略 */ }
}

プロセス起動時に設定される環境変数のイテレーターを返す。

各要素はタプル((&OsStr, Option<&OsStr>))で、1番目はキー、2番目は値であり、明示的に削除される環境変数はNoneである。

Command::envCommand::envs及びCommand::env_removeで明示的に設定された環境変数のみが含まれる。 子プロセスに引き継がれる環境変数は含まれない。

サンプル
use std::ffi::OsStr;
use std::process::Command;

let mut cmd = Command::new("ls");
cmd.env("TERM", "dumb").env_remove("TZ");
let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
assert_eq!(envs, &[
    (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
    (OsStr::new("TZ"), None)
]);

Command::get_current_dir

原典

impl Command {
    #[stable(feature = "command_access", since = "1.57.0")]
    pub fn get_current_dir(&self) -> Option<&Path>
    { /* 実装は省略 */ }
}

子プロセス向けの作業ディレクトリを返す。

作業ディレクトリが変更されない場合、Noneを返す。

サンプル
use std::path::Path;
use std::process::Command;

let mut cmd = Command::new("ls");
assert_eq!(cmd.get_current_dir(), None);
cmd.current_dir("/bin");
assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));

CommandArgs

原典

#[stable(feature = "command_access", since = "1.57.0")]
#[derive(Debug)]
pub struct CommandArgs<'a>
{ /* フィールドは省略 */ }

コマンドの引数を巡るイテレーター。

この構造体はCommand::get_argsで生成される。 詳細はそちらのドキュメントを参照されたい。

CommandEnvs

原典

#[stable(feature = "command_access", since = "1.57.0")]
#[derive(Debug)]
pub struct CommandEnvs<'a>
{ /* フィールドは省略 */ }

コマンドの環境変数を巡るイテレーター。

この構造体はCommand::get_envsで生成される。 詳細はそちらのドキュメントを参照されたい。

変更点リスト

公式リリースノートをベースに意訳・編集・追記をした変更点リストです。

言語

コンパイラ

※Rustのティア付けされたプラットフォームサポートの詳細はPlatform Supportのページ(英語)を参照

ライブラリ

安定化されたAPI

※各APIのドキュメントを独自に訳した安定化されたAPIのドキュメントもご参照ください。

以下のAPIが定数文脈でも使えるようになった。

Cargo

互換性メモ

内部の変更

これらの変更は直接ユーザーの利益に繋がるものではないが、rustc及び関連ツールにおける内部の改善や全体的なパフォーマンスの改善をもたらす。

関連リンク

さいごに

次のRust 1.58は2022/1/14(金)に予定されています。 format!などで引数への指定なしに変数を使用出来るようになったり、cargo buildから直接strip出来るようになったりするようです。

オプティムでは100ポリゴンのエンジニアを募集しています。

ライセンス表記

  • この記事はApache 2/MITのデュアルライセンスで公開されている公式リリースノート及びドキュメントから翻訳・追記をしています
  • 冒頭の画像中にはRust公式サイトで配布されているロゴを使用しており、 このロゴはMozillaまたはRust財団によってCC-BYの下で配布されています
  • 冒頭の画像中にはRustacean.netで配布されているロゴを使用しており、 このロゴはCC0の下で配布されています
  • 冒頭の画像はいらすとやさんの画像を使っています。いつもありがとうございます

MIT License

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

Apache License

                              Apache License
                        Version 2.0, January 2004
                     http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

   To apply the Apache License to your work, attach the following
   boilerplate notice, with the fields enclosed by brackets "[]"
   replaced with your own identifying information. (Don't include
   the brackets!)  The text should be enclosed in the appropriate
   comment syntax for the file format. We also recommend that a
   file or class name and description of purpose be included on the
   same "printed page" as the copyright notice for easier
   identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.