Rust 1.55を早めに深掘り

こんにちは、R&Dチームの齋藤(@aznhe21)です。 最近はい・らすとのネタが浮かばず苦労しています。センスと丁度良いリリース日をください。

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

9/10は黒澤映画「羅生門」がヴェネチア国際映画祭で日本発の金獅子賞を受賞した日 R生門

ピックアップ

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

パターンとして「以上」のレンジが使えるようになった

パターンとして1..のような形のレンジが使えるようになりました。 パターンとして使えることで複雑な構造での分岐がやりやすくなります。

use chrono::NaiveDate;

// 日付とその時点の年齢から、2人が結婚が可能かかどうかを返す
fn marriageable(date: NaiveDate, man: u32, woman: u32) -> bool {
    match (date >= NaiveDate::from_ymd(2022, 4, 1), man, woman) {
        // 2022年4月1日以降は男女ともに18歳以上で結婚可能
        (true, 18.., 18..) => true,
        // それまでは男性が18歳以上、女性が16歳以上で結婚可能
        (false, 18.., 16..) => true,
        // それ以外は結婚出来ない
        _ => false,
    }
}

ただし、他のスタイルのレンジは実装や演算子の優先順位等で問題があるようで、まだ使うことは出来ません。

match x {
    ..1 => println!("0"),
//  ^^^   half-open range patterns are unstable
    1..3 => println!("1〜2"),
//  ^^^^  exclusive range pattern syntax is experimental
    3..=4 => println!("3〜4"),
//  ^^^^^ exclusive range pattern syntax is experimental
    5.. => println!("5〜"),
//  ↑はOK
}

配列をそのまま写像出来るようになった

固定長配列において、配列の所有権を奪い、同じ長さの配列として値を写像出来るようになりました。

let arr: [u32; 3] = [0, 1, 2];
let arr: [u32; 3] = arr.map(|x| x * 2);
println!("{:?}", arr); // [0, 2, 4]

ただしrust-lang/rust#75243の中でも指摘されている通り、生成されたコードが必ずしも最適化されているとは限らず、 また配列の大きさによってはスタックを使い尽くしてしまうこともあるようなので使用方法には注意が必要です。

詳細はarray::mapのドキュメントも参照してください。

I/O関数から返されるエラーの値が一部変更された

これまで、標準ライブラリのI/O系の関数(std::fs::writeなど)から返されるエラーで、 ErrorKindに定義されていないタイプのエラーではErrorKind::Otherが返されていました。

Rust 1.56では仕様が変更され、ErrorKind::Otherは標準ライブラリでは使われず、ユーザーコード(クレート含む)でのみ使用されることになりました。 そして、これまでErrorKind::Otherで返っていたエラーはmatchではワイルドカード(_)でのみ受け取れるようになりました。

これは将来的にバリアントが追加されることを想定したもので、 例えばENOSPCは(安定化されておらず使えないものの)ErrorKind::Otherの代わりにErrorKind::StorageFullを返すようになるようです。

もしこういったエラーを受け取るためにErrorKind::Otherを使っているのであればコードを修正する必要があります。

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

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

core::ops::Bound::cloned

原典

impl<T: Clone> Bound<&T> {
    #[stable(feature = "bound_cloned", since = "1.55.0")]
    pub fn cloned(self) -> Bound<T>
    { /* 実装は省略 */ }
}

境界の中身を複製し、Bound<&T>からBound<T>に変換する。

サンプル
use std::ops::Bound::*;
use std::ops::RangeBounds;

assert_eq!((1..12).start_bound(), Included(&1));
assert_eq!((1..12).start_bound().cloned(), Included(1));

std::string::Drain::as_str

原典

impl<'a> Drain<'a> {
    #[stable(feature = "string_drain_as_str", since = "1.55.0")]
    pub fn as_str(&self) -> &str
    { /* 実装は省略 */ }
}

このイテレーターの残りの(部分)文字列をスライスとして返す。

サンプル
let mut s = String::from("abc");
let mut drain = s.drain(..);
assert_eq!(drain.as_str(), "abc");
let _ = drain.next().unwrap();
assert_eq!(drain.as_str(), "bc");

std::io::IntoInnerError::into_error

原典

impl<W> IntoInnerError<W> {
    #[stable(feature = "io_into_inner_error_parts", since = "1.55.0")]
    pub fn into_error(self) -> Error
    { /* 実装は省略 */ }
}

IntoInnerErrorを消費し、BufWriter::into_inner()の呼び出し時に発生したエラーを返す。 errorメソッドとは異なり、内包するエラーの所有権を得ることが出来る。

サンプル
use std::io::{BufWriter, ErrorKind, Write};

let mut not_enough_space = [0u8; 12];
let mut stream = BufWriter::new(not_enough_space.as_mut());
write!(stream, "実際には書き込めない").unwrap();
let into_inner_err = stream.into_inner().expect_err("ここで小さすぎることが分かる");
let err = into_inner_err.into_error();
assert_eq!(err.kind(), ErrorKind::WriteZero);

std::io::IntoInnerError::into_parts

原典

impl<W> IntoInnerError<W> {
    #[stable(feature = "io_into_inner_error_parts", since = "1.55.0")]
    pub fn into_parts(self) -> (Error, W)
    { /* 実装は省略 */ }
}

IntoInnerErrorを消費し、BufWriter::into_inner()の呼び出し時に発生したエラー及び内包するwriterを返す。

単純に内包するエラーの所有権を得るためにも使えるが、より発展的なエラーからの復帰に使うことも出来る。

サンプル
use std::io::{BufWriter, ErrorKind, Write};

let mut not_enough_space = [0u8; 12];
let mut stream = BufWriter::new(not_enough_space.as_mut());
write!(stream, "実際には書き込めない").unwrap();
let into_inner_err = stream.into_inner().expect_err("ここで小さすぎることが分かる");
let (err, recovered_writer) = into_inner_err.into_parts();
assert_eq!(err.kind(), ErrorKind::WriteZero);
assert_eq!(recovered_writer.buffer(), "書き込めない".as_bytes());

core::mem::MaybeUninit::assume_init_mut

原典

impl<T> MaybeUninit<T> {
    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
    #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
    #[inline(always)]
    pub const unsafe fn assume_init_mut(&mut self) -> &mut T
    { /* 実装は省略 */ }
}

内包する値への(唯一の)可変参照を返す。

初期化済みだが所有権を持たないMaybeUninitに(.assume_init()を使わないまま)アクセスするために使える。

安全性

中身を完全に初期化しないままこのメソッドを使うのは未定義動作である。 つまりMaybeUninit<T>が初期化された状態であることを保証するのは呼び出し側の責任である。 例えばMaybeUninitを初期化するのに.assume_init_mut()は使えない。

サンプル
このメソッドの正しい使い方
use std::mem::MaybeUninit;

extern "C" {
    /// 入力バッファのバイト列**全て**を初期化する。
    fn initialize_buffer(buf: *mut [u8; 1024]);
}

let mut buf = MaybeUninit::<[u8; 1024]>::uninit();

// `buf`を初期化
unsafe { initialize_buffer(buf.as_mut_ptr()); }
// ここでは`buf`は初期化されているので`.assume_init()`を使える。
// しかし`.assume_init()`は1024バイトの`memcpy`を引き起こすことがある。
// バッファをコピーなく初期化することを確実にするため、
// `&mut MaybeUninit<[u8; 1024]>`を`&mut [u8; 1024]`に昇格させる。
let buf: &mut [u8; 1024] = unsafe {
    // SAFETY: `buf`は初期化済み
    buf.assume_init_mut()
};

// `buf`は通常のスライス同様に使える
buf.sort_unstable();
assert!(
    buf.windows(2).all(|pair| pair[0] <= pair[1]),
    "バッファはソート済み",
);
このメソッドの間違った使い方

.assume_init_mut()を使って値を初期化することは出来ない。

use std::mem::MaybeUninit;

let mut b = MaybeUninit::<bool>::uninit();
unsafe {
    *b.assume_init_mut() = true;
    // 未初期化の`bool`に対して(可変の)参照を作った。
    // これは未定義の動作である。⚠️
}

例えば未初期化のバッファに対してReadすることは出来ない。

use std::{io, mem::MaybeUninit};

fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
{
    let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
    reader.read_exact(unsafe { buffer.assume_init_mut() })?;
                            // ^^^^^^^^^^^^^^^^^^^^^^^^
                            // 未初期化のメモリへの(可変)参照。
                            // これは未定義の動作である。
    Ok(unsafe { buffer.assume_init() })
}

core::mem::MaybeUninit::assume_init_ref

原典

impl<T> MaybeUninit<T> {
    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
    #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
    #[inline(always)]
    pub const unsafe fn assume_init_ref(&self) -> &T
    { /* 実装は省略 */ }
}

内部の値に対する共有の参照を取得する。

初期化済みだが所有権を持たないMaybeUninitに(.assume_init()を使わないまま)アクセスするために使える。

安全性

中身を完全に初期化しないままこのメソッドを使うのは未定義動作である。 つまりMaybeUninit<T>が初期化された状態であることを保証するのは呼び出し側の責任である。

サンプル
このメソッドの正しい使い方
use std::mem::MaybeUninit;

let mut x = MaybeUninit::<Vec<u32>>::uninit();
// `x`を初期化
x.write(vec![1, 2, 3]);
// ここでは`MaybeUninit<_>`は初期化されており、共有の参照を作っても良い
let x: &Vec<u32> = unsafe {
    // SAFETY: `x`は初期化済み
    x.assume_init_ref()
};
assert_eq!(x, &vec![1, 2, 3]);
このメソッドの間違った使い方
use std::mem::MaybeUninit;

let x = MaybeUninit::<Vec<u32>>::uninit();
let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
// 未初期化のベクタに対する参照を作った。これは未定義の動作である。⚠️
use std::{cell::Cell, mem::MaybeUninit};

let b = MaybeUninit::<Cell<bool>>::uninit();
// `MaybeUninit`を`Cell::set`を使って初期化する
unsafe {
    b.assume_init_ref().set(true);
   // ^^^^^^^^^^^^^^^
   // 未初期化の`Cell<bool>`への参照:UB!
}

core::mem::MaybeUninit::write

原典

impl<T> MaybeUninit<T> {
    #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
    #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")]
    #[inline(always)]
    pub const fn write(&mut self, val: T) -> &mut T
    { /* 実装は省略 */ }
}

MaybeUninit<T>の値を設定する。

これまでの値をドロップせずに上書きするため、デストラクタの実行を省きたい場合を除き、 このメソッドを2度呼び出すことが無いよう注意が必要である。 また、便宜のために(安全に初期化済みである)selfの中身への可変参照を返す。

assume_initassume_init_dropなどを呼び出さずにスコープを抜けた場合、 値はMaybeUninit内に格納済であるため、内部データのデストラクタは実行されない。この関数から可変参照を受け取るコードはこのことに注意が必要である。 Rustの安全性モデルではリーク自体は安全と見做されるが、通常そういったものは望ましくない。 とは言えこの可変参照は他の可変参照と同様の挙動をするため、参照を通して新しい値を代入すれば古い中身はドロップする。

サンプル

このメソッドの正しい使い方

use std::mem::MaybeUninit;

let mut x = MaybeUninit::<Vec<u8>>::uninit();

{
    let hello = x.write((&b"Hello, world!").to_vec());
    // helloに設定する時、以前のメモリ割り当てはリークせずドロップする
    *hello = (&b"Hello").to_vec();
    hello[0] = 'h' as u8;
}
// xは初期化済み
let s = unsafe { x.assume_init() };
assert_eq!(b"hello", s.as_slice());

リークを伴うこのメソッドの使用例

use std::mem::MaybeUninit;

let mut x = MaybeUninit::<String>::uninit();

x.write("Hello".to_string());
// 内部の文字列はリークする
x.write("hello".to_string());
// xは初期化済み
let s = unsafe { x.assume_init() };

このメソッドはいくつかのケースでunsafeを避けるために使用出来る。 下記の例ではピン留めされた参照を貸し出す、固定サイズのアリーナの一部実装である。 writeにより生ポインタを通した書き込みを避けることが出来る。

#![feature(maybe_uninit_extra)]
use core::pin::Pin;
use core::mem::MaybeUninit;

struct PinArena<T> {
    memory: Box<[MaybeUninit<T>]>,
    len: usize,
}

impl <T> PinArena<T> {
    pub fn capacity(&self) -> usize {
        self.memory.len()
    }
    pub fn push(&mut self, val: T) -> Pin<&mut T> {
        if self.len >= self.capacity() {
            panic!("満杯のPinArenaへのpushを試みた");
        }
        let ref_ = self.memory[self.len].write(val);
        self.len += 1;
        unsafe { Pin::new_unchecked(ref_) }
    }
}

array::map

原典

#[lang = "array"]
impl<T, const N: usize> [T; N] {
    #[stable(feature = "array_map", since = "1.55.0")]
    pub fn map<F, U>(self, f: F) -> [U; N]
    where
        F: FnMut(T) -> U,
    { /* 実装は省略 */ }
}

selfと同じサイズの配列を、それぞれの要素に順に関数fを適用して返す。

固定長配列である必要がない場合はIterator::mapの使用も検討されたい。

パフォーマンスとスタック使用量について

残念ながら、このメソッドは必ずしも最適化されているとは言えない。 これは主には巨大な配列に対してであり、小さい配列を写像する場合は十分最適化されるようである。 また、デバッグモード(例えば何も最適化しない場合)では大量のスタックが消費される場合がある(配列の数倍以上のサイズ)。

そのため、パフォーマンスが重要なコードでは巨大な配列でのこのメソッドの利用は避けるか、生成されたコードを確認すること。 また連続した写像も避けるべきである(arr.map(...).map(...)など)。

ほとんどのケースでは配列で.iter().into_iter()を呼び出すことで、代わりにIterator::mapを使用出来る (訳注:配列への.into_iter()にはRust 2021 Editionが必要)。 [T; N]::mapが必要なのは、値として同じ大きさの配列が必須のときだけである。 Rustの遅延イテレーターは非常に良く最適化される傾向にあるのだ。

サンプル
let x = [1, 2, 3];
let y = x.map(|v| v + 1);
assert_eq!(y, [2, 3, 4]);

let x = [1, 2, 3];
let mut temp = 0;
let y = x.map(|v| { temp += 1; v * temp });
assert_eq!(y, [1, 4, 9]);

let x = ["Ferris", "Bueller's", "Day", "Off"];
let y = x.map(|v| v.len());
assert_eq!(y, [6, 9, 3, 3]);

core::ops::ControlFlow

原典

#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ControlFlow<B, C = ()> {
    #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
    #[lang = "Continue"]
    Continue(C),
    #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
    #[lang = "Break"]
    Break(B),
}

操作が早期に終了すべきか、それとも通常通りに進むべきかを伝えるために使われる。

早期に終了するかどうかをユーザーに選択させたいもの(グラフの走査やVisitorなど)を公開する時に使う。 列挙型にすることで意味が――「falseって何の意味だっけ・・・?」と悩むことも無く――明確になり、また値を含ませることも出来る。

サンプル

Iterator::try_for_eachを早期に終了する。

use std::ops::ControlFlow;

let r = (2..100).try_for_each(|x| {
    if 403 % x == 0 {
        return ControlFlow::Break(x)
    }

    ControlFlow::Continue(())
});
assert_eq!(r, ControlFlow::Break(13));

最小限のツリー走査

use std::ops::ControlFlow;

pub struct TreeNode<T> {
    value: T,
    left: Option<Box<TreeNode<T>>>,
    right: Option<Box<TreeNode<T>>>,
}

impl<T> TreeNode<T> {
    pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
        if let Some(left) = &self.left {
            left.traverse_inorder(&mut f)?;
        }
        f(&self.value)?;
        if let Some(right) = &self.right {
            right.traverse_inorder(&mut f)?;
        }
        ControlFlow::Continue(())
    }
}
バリアント
Continue(C)
通常通りこの操作の次の過程に進む
Break(B)
残りの過程を実行せずにこの操作を終了する

core::arch::x86::_bittest

原典

#[inline]
#[cfg_attr(test, assert_instr(bt))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittest(p: *const i32, b: i32) -> u8
{ /* 実装は省略 */ }

x86のみでサポートされる。

pで示さるメモリの位置bにあるビットを返す。

core::arch::x86::_bittestandcomplement

原典

#[inline]
#[cfg_attr(test, assert_instr(btc))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandcomplement(p: *mut i32, b: i32) -> u8
{ /* 実装は省略 */ }

x86のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを反転する。

core::arch::x86::_bittestandreset

原典

#[inline]
#[cfg_attr(test, assert_instr(btr))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandreset(p: *mut i32, b: i32) -> u8
{ /* 実装は省略 */ }

x86のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを0にリセットする。

core::arch::x86::_bittestandset

原典

#[inline]
#[cfg_attr(test, assert_instr(bts))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandset(p: *mut i32, b: i32) -> u8
{ /* 実装は省略 */ }

x86のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを1にセットする。

core::arch::x86_64::_bittest64

原典

#[inline]
#[cfg_attr(test, assert_instr(bt))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittest64(p: *const i64, b: i64) -> u8
{ /* 実装は省略 */ }

x86-64のみでサポートされる。

pで示さるメモリの位置bにあるビットを返す。

core::arch::x86_64::_bittestandcomplement64

原典

#[inline]
#[cfg_attr(test, assert_instr(btc))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandcomplement64(p: *mut i64, b: i64) -> u8
{ /* 実装は省略 */ }

x86-64のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを反転する。

core::arch::x86_64::_bittestandreset64

原典

#[inline]
#[cfg_attr(test, assert_instr(btr))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandreset64(p: *mut i64, b: i64) -> u8
{ /* 実装は省略 */ }

x86-64のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを0にリセットする。

core::arch::x86_64::_bittestandset64

原典

#[inline]
#[cfg_attr(test, assert_instr(bts))]
#[stable(feature = "simd_x86_bittest", since = "1.55.0")]
pub unsafe fn _bittestandset64(p: *mut i64, b: i64) -> u8
{ /* 実装は省略 */ }

x86-64のみでサポートされる。

pで示さるメモリの位置bにあるビットを返し、そのビットを1にセットする。

変更点リスト

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

言語

コンパイラ

※Rustのティアで管理されるプラットフォームの詳細はPlatform Supportのページ(英語)を参照

ライブラリ

安定化されたAPI

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

また、以前から安定化されていたAPIのうち以下のものが定数化された。

Cargo

Rustdoc

互換性メモ

関連リンク

さいごに

次のRust 1.56は2021/10/22(金)に予定されています。 配列からHashMapを構築出来るようになったり、定数関数内でtransmute出来るようになったりするようです。

オプティムでは名作エンジニアを募集しています。

ライセンス表記

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

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.