こんにちは、R&Dチームの齋藤(@aznhe21)です。 今日はオプティムの創立記念パーティーがオンラインで行われます。 オプティムは2000/6/8に設立され、去年は20周年の節目であったにも関わらず生憎の時制で大きく祝えませんでしたが、 今年は準備も万全、盛大にお祝いしたいと思います。
さて、本日、日本時間6/18(金)、Rust 1.53がリリースされました。 この記事ではRust 1.53での変更点を詳しく紹介します。
- ピックアップ
- 安定化されたAPIのドキュメント
- AtomicBool::fetch_update
- AtomicPtr::fetch_update
- BTreeMap::retain
- BTreeSet::retain
- BufReader::seek_relative
- DebugStruct::non_exhaustive
- Duration::MAX
- Duration::ZERO
- Duration::is_zero
- Duration::saturating_add
- Duration::saturating_mul
- Duration::saturating_sub
- ErrorKind::Unsupported
- Option::insert
- Ordering::is_eq
- Ordering::is_ge
- Ordering::is_gt
- Ordering::is_le
- Ordering::is_lt
- Ordering::is_ne
- OsStr::is_ascii
- OsStr::make_ascii_lowercase
- OsStr::make_ascii_uppercase
- OsStr::to_ascii_lowercase
- OsStr::to_ascii_uppercase
- Peekable::peek_mut
- Rc::decrement_strong_count
- Rc::increment_strong_count
- Vec::extend_from_within
- array::from_mut
- array::from_ref
- cmp::max_by_key
- cmp::max_by
- cmp::min_by_key
- cmp::min_by
- f32::is_subnormal
- f64::is_subnormal
- 変更点リスト
- 関連リンク
- さいごに
- ライセンス表記
ピックアップ
個人的に注目する変更点を「ピックアップ」としてまとめました。 全ての変更点を網羅したリストは変更点リストをご覧ください。
識別子にASCII以外の文字も使えるようになった
変数名や構造体名など、様々なところで非ASCII文字が使えるようになりました。
fn main() { let 日本語の変数だよ = "ほげ"; println!("{}", 日本語の変数だよ); // 絵文字は使えない // let 💩 = "💩"; }
識別子はNFCによって正規化し直されるため、macOSのファイル名(NFDで正規化される)をコピペしても一応は安心です。
fn main() { // この「プ」はどちらもNFCでの正規化 let mut オプティム = "オプティム"; println!("{:?}", オプティム.chars()); // Chars(['オ', 'プ', 'テ', 'ィ', 'ム']) // この「プ」はどちらもNFDでの正規化 オプティム = "オプティム"; // バイト列で見ると異なる変数名に代入したが、正規化により正しく代入されている println!("{:?}", オプティム.chars()); // Chars(['オ', 'フ', '\u{309a}', 'テ', 'ィ', 'ム']) }
どんな文字が使えるかはUAX 31に従います。 Rustの記事ではないものの、UAX 31や他の言語での状況についてはこちらが詳しいです。
導入の動機はRFC 2457が詳しいんですが、このRFCのPRへのリアクションを見ると結構賛否両論です。 そこで、動機を訳しつつ引用します。
ドメイン固有の用語を使ってコードを書くと、プロジェクト要件から単語を翻訳するのとは対象的に、実装や議論が簡素化されます。 また、コードが社内プロジェクトや教育現場など限られた人だけを対象にしている場合にそのグループの言語でコードを書くことは、 コミュニケーションが促進される、あるいは英語が苦手な人でもRustのコードを書くことが出来る、と言った点で有益でしょう。
PEP 3131(※訳注:Python言語の機能拡張の際に議論した結果などのまとめ資料で、RustのRFCに相当する) の理論的根拠がそれを上手く説明しています。
PythonRustのコードは、英語はもちろんラテン語の表記体系にも精通していない世界中の多くの人々によって書かれています。 そのような開発者は、クラスや関数の名前を付ける時にその概念の(間違いがちな)英訳を考えるのではなく、 母国語のままで宣言したいと良く思います。 母国語の識別子を使用することで、その言語を話す人たちの間ではコードの明確さや保守性が向上します。一部の言語(特にラテン系の表記体系)には、一般的に翻字の仕組みが存在します(※訳注:日本語ではヘボン式ローマ字などがある)。 しかし、それ以外の言語ではラテン語を使用して母国語を書くのが非常に困難です。
加えて、数学指向のプロジェクトでは数学での記述に近い識別子を使えるでしょう。
ORパターンが使えるようになった
これまで、パターンマッチにおいては複数のパターンを|で繋げることしか出来ませんでした。
fn main() { let x = "496".parse::<u32>(); match x { Ok(6) | Ok(28) | Ok(496) | Ok(8128) | Ok(33550336) => println!("x is a perfect number"), Ok(_) => println!("x is not a perfect number"), Err(_) => println!("failed to parse"), } }
ORパターンにより、Ok()の中でも|で繋げることが出来るようになりました。
fn main() { let x = "496".parse::<u32>(); match x { Ok(6 | 28 | 496 | 8128 | 33550336) => println!("a perfect number"), Ok(_) => println!("not a perfect number"), Err(_) => println!("failed to parse"), } }
配列にIntoIteratorが実装された
Rust 1.50で配列要素の所有権を奪いつつイテレート出来るようになったわけですが、
std::array::IntoIter::newを使わなければならず少し面倒でした。
use std::array::IntoIter; fn main() { let array = ["hoge".to_string(), "fuga".to_string()]; for mut s in IntoIter::new(array) { s.push_str("-piyo"); println!("{}", s); } }
Rust 1.53からは配列型に対して直接IntoIteratorトレイトが実装されるようになり、配列をそのままループに使うことが出来るようになりました。
これは互換性上も問題はないと判断されています。
fn main() { let array = ["hoge".to_string(), "fuga".to_string()]; for mut s in array { s.push_str("-piyo"); println!("{}", s); } // IntoIteratorを要求する引数にも使える let mut vec: Vec<u32> = Vec::new(); vec.extend([0, 1, 2]); }
しかし、.into_iter()メソッドを呼び出す形式では後方互換性への配慮から制限があります。
この制限はRust 2021 Editionでは取り払われる予定です。
fn main() { let arr = [1, 2, 3]; for x in arr { let _: u32 = x; // xは借用されていない } // .into_iter()では今のところ借用となってしまう // 2021 Editionでは借用無しでイテレーターが使えるようになる予定 arr.into_iter().for_each(|_: &u32| {}); // IntoIteratorを直接使えば使えないこともない IntoIterator::into_iter(arr).for_each(|_: u32| {}); }
安定化されたAPIのドキュメント
安定化されたAPIのドキュメントを独自に訳して紹介します。リストだけ見たい方は安定化されたAPIをご覧ください。
AtomicBool::fetch_update
#[cfg(target_has_atomic_load_store = "8")] impl AtomicBool { #[inline] #[stable(feature = "atomic_fetch_update", since = "1.53.0")] #[cfg(target_has_atomic = "8")] pub fn fetch_update<F>( &self, set_order: Ordering, fetch_order: Ordering, mut f: F, ) -> Result<bool, bool> where F: FnMut(bool) -> Option<bool>, { /* 実装は省略 */ } }
値を取得し、任意な新規の値を返す関数を適用する。
関数がSome(_)を返した場合はResultのOk(直前の値)を返し、さもなくばErr(直前の値)を返す。
注意:関数呼び出し中に他のスレッドで値が変更された場合、関数は複数回呼び出されるかもしれない。
ただし、これは関数がSome(_)を返す間だけであり、それ以外では格納された値に対して一度だけ関数が適用される。
※訳注:実装を見たほうが分かりやすいかもしれない。
fetch_updateはこの操作のメモリオーダーを示すために2つのOrderingを引数に取る。
1つ目は操作が最終的に成功した時に要求されるオーダーを、2つ目は読み込み時に要求されるオーダーを示す。
これらはそれぞれ、AtomicBool::compare_exchangeの成功時と失敗時のオーダーに対応する。
成功時のオーダーとしてAcquireを指定すると格納時にはRelaxedが使われ、
Releaseを指定すると最終的な成功時の読み込みにはRelaxedが使われる。
(失敗した)読み込みのオーダーにはSeqCstかAcquire、またはRelaxedのみが使え、かつ成功時以下のオーダーでなければならない。
注意:このメソッドはu8での不可分操作をサポートしたプラットフォームでのみ使用可能
サンプル
use std::sync::atomic::{AtomicBool, Ordering}; let x = AtomicBool::new(false); assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false)); assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false)); assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true)); assert_eq!(x.load(Ordering::SeqCst), false);
AtomicPtr::fetch_update
#[cfg(target_has_atomic_load_store = "ptr")] impl<T> AtomicPtr<T> { #[inline] #[stable(feature = "atomic_fetch_update", since = "1.53.0")] #[cfg(target_has_atomic = "ptr")] pub fn fetch_update<F>( &self, set_order: Ordering, fetch_order: Ordering, mut f: F, ) -> Result<*mut T, *mut T> where F: FnMut(*mut T) -> Option<*mut T>, { /* 実装は省略 */ } }
値を取得し、任意な新規の値を返す関数を適用する。
関数がSome(_)を返した場合はResultのOk(直前の値)を返し、さもなくばErr(直前の値)を返す。
注意:関数呼び出し中に他のスレッドで値が変更された場合、関数は複数回呼び出されるかもしれない。
ただし、これは関数がSome(_)を返す間だけであり、それ以外では格納された値に対して一度だけ関数が適用される。
※訳注:実装を見たほうが分かりやすいかもしれない。
fetch_updateはこの操作のメモリオーダーを示すために2つのOrderingを引数に取る。
1つ目は操作が最終的に成功した時に要求されるオーダーを、2つ目は読み込み時に要求されるオーダーを示す。
これらはそれぞれ、AtomicPtr::compare_exchangeの成功時と失敗時のオーダーに対応する。
成功時のオーダーとしてAcquireを指定すると格納時にはRelaxedが使われ、
Releaseを指定すると最終的な成功時の読み込みにはRelaxedが使われる。
(失敗した)読み込みのオーダーにはSeqCstかAcquire、またはRelaxedのみが使え、かつ成功時以下のオーダーでなければならない。
注意:このメソッドはポインタでの不可分操作をサポートしたプラットフォームでのみ使用可能
サンプル
use std::sync::atomic::{AtomicPtr, Ordering}; let ptr: *mut _ = &mut 5; let some_ptr = AtomicPtr::new(ptr); let new: *mut _ = &mut 10; assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr)); let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| { if x == ptr { Some(new) } else { None } }); assert_eq!(result, Ok(ptr)); assert_eq!(some_ptr.load(Ordering::SeqCst), new);
BTreeMap::retain
impl<K, V> BTreeMap<K, V> { #[inline] #[stable(feature = "btree_retain", since = "1.53.0")] pub fn retain<F>(&mut self, mut f: F) where K: Ord, F: FnMut(&K, &mut V) -> bool, { /* 実装は省略 */ } }
述語関数で指定された要素のみ維持する。
言い換えれば、f(&k, &mut v)がfalseを返すような全ての(k, v)ペアを削除する。
サンプル
use std::collections::BTreeMap; let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect(); // キーが偶数の要素のみを残す map.retain(|&k, _| k % 2 == 0); assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
BTreeSet::retain
impl<T> BTreeSet<T> { #[stable(feature = "btree_retain", since = "1.53.0")] pub fn retain<F>(&mut self, mut f: F) where T: Ord, F: FnMut(&T) -> bool, { /* 実装は省略 */ } }
述語関数で指定された要素のみ維持する。
言い換えれば、f(&e)がfalseを返すような全てのe要素を削除する。
サンプル
use std::collections::BTreeSet; let xs = [1, 2, 3, 4, 5, 6]; let mut set: BTreeSet<i32> = xs.iter().cloned().collect(); // 偶数のみを残す set.retain(|&k| k % 2 == 0); assert!(set.iter().eq([2, 4, 6].iter()));
BufReader::seek_relative
impl<R: Seek> BufReader<R> { #[stable(feature = "bufreader_seek_relative", since = "1.53.0")] pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> { /* 実装は省略 */ } }
現在の位置に基づいてシークする。 新しい場所がバッファ内に位置する場合、より効率的なシークのためにバッファはフラッシュされない。 このメソッドは内包するリーダーの位置を返さないため、必要な場合は呼び出し側で追従しなければならない。
DebugStruct::non_exhaustive
impl<'a, 'b: 'a> DebugStruct<'a, 'b> { #[stable(feature = "debug_non_exhaustive", since = "1.53.0")] pub fn finish_non_exhaustive(&mut self) -> fmt::Result { /* 実装は省略 */ } }
構造体を非網羅的であると記録し、デバッグ表現内で他に表示されていないフィールドがあることを読み手に示す。
サンプル
use std::fmt; struct Bar { bar: i32, hidden: f32, } impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Bar") .field("bar", &self.bar) .finish_non_exhaustive() // 他にもフィールドがあることを表示 } } assert_eq!( format!("{:?}", Bar { bar: 10, hidden: 1.0 }), "Bar { bar: 10, .. }", );
Duration::MAX
impl Duration { #[stable(feature = "duration_saturating_ops", since = "1.53.0")] pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1); }
最大のDuration。
プラットフォームによって異なる場合があるかもしれない。
実際のところ、2つのInstantインスタンス間、あるいは2つのSystemTimeインスタンス間の差を保持出来なければならないという制約により、
現在は全プラットフォームで約5849億4241万7355年という値が与えられている。
サンプル
use std::time::Duration; assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
Duration::ZERO
impl Duration { #[stable(feature = "duration_zero", since = "1.53.0")] pub const ZERO: Duration = Duration::from_nanos(0); }
経過がゼロであるDuration。
サンプル
use std::time::Duration; let duration = Duration::ZERO; assert!(duration.is_zero()); assert_eq!(duration.as_nanos(), 0);
Duration::is_zero
#[stable(feature = "duration_zero", since = "1.53.0")] #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")] #[inline] pub const fn is_zero(&self) -> bool { /* 実装は省略 */ } }
このDurationが表す期間がゼロである場合、真を返す。
サンプル
use std::time::Duration; assert!(Duration::ZERO.is_zero()); assert!(Duration::new(0, 0).is_zero()); assert!(Duration::from_nanos(0).is_zero()); assert!(Duration::from_secs(0).is_zero()); assert!(!Duration::new(1, 1).is_zero()); assert!(!Duration::from_nanos(1).is_zero()); assert!(!Duration::from_secs(1).is_zero());
Duration::saturating_add
impl Duration { #[stable(feature = "duration_saturating_ops", since = "1.53.0")] #[inline] #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")] pub const fn saturating_add(self, rhs: Duration) -> Duration { /* 実装は省略 */ } }
Durationを飽和させつつ加える。
self + rhsを計算するが、オーバーフローした場合はDuration::MAXを返す。
サンプル
use std::time::Duration; assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1)); assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
Duration::saturating_mul
impl Duration { #[stable(feature = "duration_saturating_ops", since = "1.53.0")] #[inline] #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")] pub const fn saturating_mul(self, rhs: u32) -> Duration { /* 実装は省略 */ } }
Durationを飽和させつつ乗じる。
self * rhsを計算するが、オーバーフローした場合はDuration::MAXを返す。
サンプル
use std::time::Duration; assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2)); assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
Duration::saturating_sub
impl Duration { #[stable(feature = "duration_saturating_ops", since = "1.53.0")] #[inline] #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")] pub const fn saturating_sub(self, rhs: Duration) -> Duration { /* 実装は省略 */ } }
Durationを飽和させつつ減らす。
self - rhsを計算するが、結果が負になった、あるいはオーバーフローした場合はDuration::ZEROを返す。
サンプル
use std::time::Duration; assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1)); assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
ErrorKind::Unsupported
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] #[non_exhaustive] pub enum ErrorKind { // ... #[stable(feature = "unsupported_error", since = "1.53.0")] Unsupported, }
この操作はこのプラットフォームではサポートされていない。
実行した操作が成功することは無いことを意味する。
Option::insert
impl<T> Option<T> { #[inline] #[stable(feature = "option_insert", since = "1.53.0")] pub fn insert(&mut self, value: T) -> &mut T { /* 実装は省略 */ } }
valueをこのOptionに挿入し、値への可変参照を返す。
もしこのOptionが値を保持している場合、古い値は破棄される。
Optionが既にSomeを保持している場合には値を更新しないOption::get_or_insertも参照されたい。
サンプル
let mut opt = None; let val = opt.insert(1); assert_eq!(*val, 1); assert_eq!(opt.unwrap(), 1); let val = opt.insert(2); assert_eq!(*val, 2); *val = 3; assert_eq!(opt.unwrap(), 3);
Ordering::is_eq
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_eq(self) -> bool { /* 実装は省略 */ } }
このOrderingがEqualバリアントである場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_eq(), false); assert_eq!(Ordering::Equal.is_eq(), true); assert_eq!(Ordering::Greater.is_eq(), false);
Ordering::is_ge
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_ge(self) -> bool { /* 実装は省略 */ } }
このOrderingがGreaterバリアント、あるいはEqualバリアントである場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_ge(), false); assert_eq!(Ordering::Equal.is_ge(), true); assert_eq!(Ordering::Greater.is_ge(), true);
Ordering::is_gt
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_gt(self) -> bool { /* 実装は省略 */ } }
このOrderingがGreaterバリアントである場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_gt(), false); assert_eq!(Ordering::Equal.is_gt(), false); assert_eq!(Ordering::Greater.is_gt(), true);
Ordering::is_le
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_le(self) -> bool { /* 実装は省略 */ } }
このOrderingがLessバリアント、あるいはEqualバリアントである場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_le(), true); assert_eq!(Ordering::Equal.is_le(), true); assert_eq!(Ordering::Greater.is_le(), false);
Ordering::is_lt
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_lt(self) -> bool { /* 実装は省略 */ } }
このOrderingがLessバリアントである場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_lt(), true); assert_eq!(Ordering::Equal.is_lt(), false); assert_eq!(Ordering::Greater.is_lt(), false);
Ordering::is_ne
impl Ordering { #[inline] #[must_use] #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")] #[stable(feature = "ordering_helpers", since = "1.53.0")] pub const fn is_ne(self) -> bool { /* 実装は省略 */ } }
このOrderingがEqualバリアントでない場合にtrueを返す。
サンプル
use std::cmp::Ordering; assert_eq!(Ordering::Less.is_ne(), true); assert_eq!(Ordering::Equal.is_ne(), false); assert_eq!(Ordering::Greater.is_ne(), true);
OsStr::is_ascii
impl OsStr { #[stable(feature = "osstring_ascii", since = "1.53.0")] #[inline] pub fn is_ascii(&self) -> bool { /* 実装は省略 */ } }
この文字列に含まれる全ての文字がASCIIの範囲内であるかを返す。
サンプル
use std::ffi::OsString; let ascii = OsString::from("hello!\n"); let non_ascii = OsString::from("Grüße, Jürgen ❤"); assert!(ascii.is_ascii()); assert!(!non_ascii.is_ascii());
OsStr::make_ascii_lowercase
impl OsStr { #[stable(feature = "osstring_ascii", since = "1.53.0")] #[inline] pub fn make_ascii_lowercase(&mut self) { /* 実装は省略 */ } }
破壊的にこの文字列をASCIIの小文字に変換する。
ASCIIの'A'から'Z'までの文字は'a'から'z'に変換されるが、非ASCII文字はそのままとなる。
非破壊的に新しい小文字の値を返すには、OsStr::to_ascii_lowercaseを使うこと。
サンプル
use std::ffi::OsString; let mut s = OsString::from("GRÜßE, JÜRGEN ❤"); s.make_ascii_lowercase(); assert_eq!("grÜße, jÜrgen ❤", s);
OsStr::make_ascii_uppercase
impl OsStr { #[stable(feature = "osstring_ascii", since = "1.53.0")] #[inline] pub fn make_ascii_uppercase(&mut self) { /* 実装は省略 */ } }
破壊的にこの文字列をASCIIの大文字に変換する。
ASCIIの'a'から'z'までの文字は'A'から'Z'に変換されるが、非ASCII文字はそのままとなる。
非破壊的に既存の値を変更せずに新しい小文字の値を返すには、OsStr::to_ascii_uppercaseを使うこと。
サンプル
use std::ffi::OsString; let mut s = OsString::from("Grüße, Jürgen ❤"); s.make_ascii_uppercase(); assert_eq!("GRüßE, JüRGEN ❤", s);
OsStr::to_ascii_lowercase
impl OsStr { #[stable(feature = "osstring_ascii", since = "1.53.0")] pub fn to_ascii_lowercase(&self) -> OsString { /* 実装は省略 */ } }
それぞれの文字がASCIIの小文字に変換された、この文字列のコピーを返す。
ASCIIの'A'から'Z'までの文字は'a'から'z'に変換されるが、非ASCII文字はそのままとなる。
破壊的に小文字に変換するには、OsStr::make_ascii_lowercaseを使うこと。
サンプル
use std::ffi::OsString; let s = OsString::from("Grüße, Jürgen ❤"); assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
OsStr::to_ascii_uppercase
impl OsStr { #[stable(feature = "osstring_ascii", since = "1.53.0")] pub fn to_ascii_uppercase(&self) -> OsString { /* 実装は省略 */ } }
それぞれの文字がASCIIの大文字に変換された、この文字列のコピーを返す。
ASCIIの'a'から'z'までの文字は'A'から'Z'に変換されるが、非ASCII文字はそのままとなる。
破壊的に大文字に変換するには、OsStr::make_ascii_uppercaseを使うこと。
Peekable::peek_mut
impl<I: Iterator> Peekable<I> { #[inline] #[stable(feature = "peekable_peek_mut", since = "1.53.0")] pub fn peek_mut(&mut self) -> Option<&mut I::Item> { /* 実装は省略 */ } }
イテレータを進めること無く、次の値への可変参照を返す。
nextのように、値があればそれをSome(T)に包む。
しかしイテレーションが終わればNoneを返す。
peek_mut()は参照を返す上、多くのイテレーターは参照を返す形でイテレートするため、
戻り値が二重参照となるような混乱する状況が発生し得る。
この影響を下記例にて窺うことが出来る。
サンプル
let mut iter = [1, 2, 3].iter().peekable(); // `peek()`のようにイテレーターを進めること無く先を見ることが出来る assert_eq!(iter.peek_mut(), Some(&mut &1)); assert_eq!(iter.peek_mut(), Some(&mut &1)); assert_eq!(iter.next(), Some(&1)); // イテレーターを覗き見、可変参照を通して値を設定する if let Some(p) = iter.peek_mut() { assert_eq!(*p, &2); *p = &5; } // イテレータを継続すると、設定した値が再登場する assert_eq!(iter.collect::<Vec<_>>(), vec![&5, &3]);
Rc::decrement_strong_count
impl<T: ?Sized> Rc<T> { #[inline] #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")] pub unsafe fn decrement_strong_count(ptr: *const T) { /* 実装は省略 */ } }
指定されたポインタと紐付くRc<T>の強参照カウントを1つ減算する。
安全性
ポインタはRc::into_rawを通じて得たものでなければならず、かつ紐付いたRcのインスタンスが、
このメソッドの呼び出し時に正常(強参照カウントが1以上であるなど)でなければならない。
このメソッドは最後のRc及びその内部領域を解放するのに使えるが、最後のRcが解放されたあとには呼び出してはならない。
サンプル
use std::rc::Rc; let five = Rc::new(5); unsafe { let ptr = Rc::into_raw(five); Rc::increment_strong_count(ptr); let five = Rc::from_raw(ptr); assert_eq!(2, Rc::strong_count(&five)); Rc::decrement_strong_count(ptr); assert_eq!(1, Rc::strong_count(&five)); }
Rc::increment_strong_count
impl<T: ?Sized> Rc<T> { #[inline] #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")] pub unsafe fn increment_strong_count(ptr: *const T) { /* 実装は省略 */ } }
指定されたポインタと紐付くRc<T>の強参照カウントを1つ加算する。
安全性
ポインタはRc::into_rawを通じて得たものでなければならず、かつ紐付いたRcのインスタンスが、
このメソッドの呼び出し中に正常(強参照カウントが1以上であるなど)でなければならない。
サンプル
use std::rc::Rc; let five = Rc::new(5); unsafe { let ptr = Rc::into_raw(five); Rc::increment_strong_count(ptr); let five = Rc::from_raw(ptr); assert_eq!(2, Rc::strong_count(&five)); }
Vec::extend_from_within
impl<T: Clone, A: Allocator> Vec<T, A> { #[stable(feature = "vec_extend_from_within", since = "1.53.0")] pub fn extend_from_within<R>(&mut self, src: R) where R: RangeBounds<usize>, { /* 実装は省略 */ } }
srcの範囲を元に、このベクタの最後に要素をコピーする。
サンプル
let mut vec = vec![0, 1, 2, 3, 4]; vec.extend_from_within(2..); assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]); vec.extend_from_within(..2); assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]); vec.extend_from_within(4..8); assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
array::from_mut
#[stable(feature = "array_from_ref", since = "1.53.0")] pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] { /* 実装は省略 */ }
(コピー無しに)Tへの可変参照を長さ1の配列への可変参照に変換する。
array::from_ref
#[stable(feature = "array_from_ref", since = "1.53.0")] pub fn from_ref<T>(s: &T) -> &[T; 1] { /* 実装は省略 */ }
(コピー無しに)Tへの参照を長さ1の配列への参照に変換する。
cmp::max_by_key
#[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T { /* 実装は省略 */ }
指定された関数を通して最大値をもたらした方の要素を返す。
比較によって等値であると判断された場合、2番目の実引数が返る。
サンプル
use std::cmp; assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2); assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
cmp::max_by
#[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T { /* 実装は省略 */ }
指定された比較関数を基に、2つの値のうち大きい方を返す。
比較によって等値であると判断された場合、2番目の実引数が返る。
サンプル
use std::cmp; assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
cmp::min_by_key
#[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T { /* 実装は省略 */ }
指定された関数を通して最小値をもたらした方の要素を返す。
比較によって等値であると判断された場合、1番目の実引数が返る。
サンプル
use std::cmp; assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1); assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
cmp::min_by
#[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T { /* 実装は省略 */ }
指定された比較関数を基に、2つの値のうち小さい方を返す。
比較によって等値であると判断された場合、1番目の実引数が返る。
f32::is_subnormal
#[lang = "f32"] #[cfg(not(test))] impl f32 #[stable(feature = "is_subnormal", since = "1.53.0")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] #[inline] pub const fn is_subnormal(self) -> bool { /* 実装は省略 */ } }
数値が非正規化数である場合、trueを返す。
let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 let max = f32::MAX; let lower_than_min = 1.0e-40_f32; let zero = 0.0_f32; assert!(!min.is_subnormal()); assert!(!max.is_subnormal()); assert!(!zero.is_subnormal()); assert!(!f32::NAN.is_subnormal()); assert!(!f32::INFINITY.is_subnormal()); // `0`と`min`の間の値は非正規化数である assert!(lower_than_min.is_subnormal());
f64::is_subnormal
#[lang = "f64"] #[cfg(not(test))] impl f64 { #[stable(feature = "is_subnormal", since = "1.53.0")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] #[inline] pub const fn is_subnormal(self) -> bool { /* 実装は省略 */ } }
数値が非正規化数である場合、trueを返す。
let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64 let max = f64::MAX; let lower_than_min = 1.0e-308_f64; let zero = 0.0_f64; assert!(!min.is_subnormal()); assert!(!max.is_subnormal()); assert!(!zero.is_subnormal()); assert!(!f64::NAN.is_subnormal()); assert!(!f64::INFINITY.is_subnormal()); // `0`と`min`の間の値は非正規化数である assert!(lower_than_min.is_subnormal());
変更点リスト
公式リリースノートをベースに意訳・編集・追記をした変更点リストです。
言語
- Unicodeを識別子として使えるようになった。これにより複数言語の識別子が使えるようになるが、
◆や🦀などの文字と見做されないグリフは依然として使うことは出来ない。 具体的にはUAX #31 "Unicode Identifier and Pattern Syntax"に適合する識別子が使える。 これはPythonなどの言語と同じ基準だが、RustはNFCによる正規化を使用するため他の言語とは異なる可能性がある。
→ピックアップ - パターンマッチ内で「ORパターン」が指定出来るようになった。
以前は下記のように完全なパターンでのみ
|(OR)を使うことが出来た。
→ピックアップ
let x = Some(2u8); // 以前 matches!(x, Some(1) | Some(2)); // 現在 matches!(x, Some(1 | 2));
macro_rules!の照合子(matcher)に:pat_paramを追加した。これは:patと同じ意味論を持つ。 これにより将来のエディションで:patの意味論をパターンの断片(pattern fragment)に変えることが出来るようになる
コンパイラ
- 最小の外部LLVMバージョンを10に引き上げた
wasm64-unknown-unknownターゲットがティア3※でサポートされるようになった- WindowsのMSVC上で、クロージャと非同期関数のデバッグ情報を改善した
※Rustのティアで管理されるプラットフォームの詳細はPlatform Supportのページ(英語)を参照
ライブラリ
- Androidプラットフォームにおいて、アボート時の文言が
android_set_abort_messageに転送されるようになった(ただしそれが使える場合のみ) slice::IterMut<'_, T>がAsRef<[T]>を実装するようになった- あらゆる長さの配列が
IntoIteratorを実装するようになった。 現状、配列での.into_iter()メソッドの呼び出しはimpl Iterator<Item=&T>を返すが、将来のエディションでItemがTに変更される。 なお、IntoIterator::into_iterの呼び出しに直接配列を指定すれば期待通りにimpl Iterator<Item=T>を提供する
→ピックアップ leading_zeros及びtrailing_zerosが全ての整数のNonZero型で使えるようになった- IEEE RFC 754に従い、
{f32, f64}::from_strが特殊な値(NaNと-0)をパース・表示するようになった - スライスのインデックスとして
(Bound<usize>, Bound<usize>)を使えるようになった - 全ての数値型に関連定数
BITSが追加された
安定化されたAPI
※各APIのドキュメントを独自に訳した安定化されたAPIのドキュメントもご参照ください。
AtomicBool::fetch_updateAtomicPtr::fetch_updateBTreeMap::retainBTreeSet::retainBufReader::seek_relativeDebugStruct::non_exhaustiveDuration::MAXDuration::ZERODuration::is_zeroDuration::saturating_addDuration::saturating_mulDuration::saturating_subErrorKind::UnsupportedOption::insertOrdering::is_eqOrdering::is_geOrdering::is_gtOrdering::is_leOrdering::is_ltOrdering::is_neOsStr::is_asciiOsStr::make_ascii_lowercaseOsStr::make_ascii_uppercaseOsStr::to_ascii_lowercaseOsStr::to_ascii_uppercasePeekable::peek_mutRc::decrement_strong_countRc::increment_strong_countVec::extend_from_withinarray::from_mutarray::from_refcmp::max_by_keycmp::max_bycmp::min_by_keycmp::min_byf32::is_subnormalf64::is_subnormal
Cargo
- デフォルトの
HEADブランチが「master」でないgitレポジトリをサポートした。 これにはCargo.lockのバージョン3(デフォルトブランチが正しく処理出来るようになる変更)への切り替えが含まれる - macOSターゲットにおいて、デバッグ情報は
unpackedな分割形式がデフォルトになった - 新規のプロジェクトにおいて、
Cargo.tomlにauthorsフィールドが含まれないようになった
Rustdoc
互換性メモ
- 属性を展開する際のトークン基準での処理が実装された
Ipv4::from_strがIPアドレスの16進数表記に加えて8進数表記も弾くようになった。 IPアドレスの8進数表記は混乱の元になるだけでなく脆弱性の温床になる可能性があり、現在は推奨されていない
※訳注:IPv4アドレスの表記については下記が詳しい。
- 追加された
BITS定数は外部の宣言と競合する可能性がある。 特にlexical-coreクレートで問題が発生することが判明しているが、0.4から0.7までのバージョンで修正が公開済みである。 この依存関係のみをアップデートする場合、cargo update -p lexical-coreを実行すること
内部のみ
これらの変更がユーザーに直接利益をもたらすわけではないものの、コンパイラ及び周辺ツール内部での重要なパフォーマンス改善をもたらす。
std::sys::windows::allocの実装を手直しした- rustdoc:get_blanket_implsにおいて、包括的実装(blanket impls)でない実装に対してはinfer_ctxtに突入しない
- rustdoc:
get_blanket_implsにおいては包括的実装のみ参照 - rustdocの定数型を手直し
関連リンク
さいごに
次のRust 1.54は2021/7/30(金)に予定されています。 属性内でマクロを含む式が使えるようになるようです。
オプティムでは京大卒エンジニアも募集しています。
ライセンス表記
- この記事はApache 2/MITのデュアルライセンスで公開されている公式リリースノートを翻訳・追記をしています
- 冒頭の画像中にはRust公式サイトで配布されているロゴを使用しており、 このロゴは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.