Skip to content

Commit e975a91

Browse files
authored
Translate exception-safety.md (#47)
1 parent 34ac244 commit e975a91

File tree

1 file changed

+136
-8
lines changed

1 file changed

+136
-8
lines changed

src/exception-safety.md

Lines changed: 136 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,101 @@
1+
<!--
12
# Exception Safety
3+
-->
24

5+
# 例外安全性
6+
7+
<!--
38
Although programs should use unwinding sparingly, there's a lot of code that
49
*can* panic. If you unwrap a None, index out of bounds, or divide by 0, your
510
program will panic. On debug builds, every arithmetic operation can panic
611
if it overflows. Unless you are very careful and tightly control what code runs,
712
pretty much everything can unwind, and you need to be ready for it.
13+
-->
14+
15+
プログラム内では巻き戻しを注意深く使用するべきですが、パニック*し得る*コードが
16+
たくさんあります。もし None をアンラップしたり、境界外のインデックスを指定したり、
17+
0 で除算したりしたら、プログラムはパニックするでしょう。デバッグビルドでは、
18+
全ての算術演算は、オーバーフロー時にパニックします。非常に注意深く、
19+
そしてどのコードを実行するかを厳しくコントロールしない限り、ほとんどすべての
20+
コードが巻き戻しをする可能性があり、これに対して準備をする必要があります。
821

22+
<!--
923
Being ready for unwinding is often referred to as *exception safety*
1024
in the broader programming world. In Rust, there are two levels of exception
1125
safety that one may concern themselves with:
26+
-->
27+
28+
巻き戻しに対して準備が出来ていることは、もっと広いプログラミングの世界において、
29+
しばしば*例外安全*と呼ばれています。 Rust では、プログラムが関わる可能性のある、
30+
2 つの例外安全のレベルがあります。
1231

32+
<!--
1333
* In unsafe code, we *must* be exception safe to the point of not violating
1434
memory safety. We'll call this *minimal* exception safety.
1535

1636
* In safe code, it is *good* to be exception safe to the point of your program
1737
doing the right thing. We'll call this *maximal* exception safety.
38+
-->
39+
40+
* アンセーフなコードでは、メモリ安全性を侵害しないという点において、
41+
例外安全で*なければなりません*。これを、*最小限*の例外安全と呼びます。
42+
43+
* 安全なコードでは、プログラムが正しいことを行なうという点において、
44+
例外安全であると*良い*です。これを*最大限*の例外安全と呼びます。
1845

46+
<!--
1947
As is the case in many places in Rust, Unsafe code must be ready to deal with
2048
bad Safe code when it comes to unwinding. Code that transiently creates
2149
unsound states must be careful that a panic does not cause that state to be
2250
used. Generally this means ensuring that only non-panicking code is run while
2351
these states exist, or making a guard that cleans up the state in the case of
2452
a panic. This does not necessarily mean that the state a panic witnesses is a
2553
fully coherent state. We need only guarantee that it's a *safe* state.
26-
54+
-->
55+
56+
Rust の多くの場において事実なのですが、巻き戻しとなると、アンセーフなコードは、
57+
悪い安全なコードに対処する準備をしなければなりません。一時的に健全ではない
58+
状態を生むコードは、パニックによってその状態が使用されないよう、注意深く
59+
扱わなければなりません。通常これは、このような健全でない状態が存在する間、
60+
パニックを起こさないコードのみを確実に実行させることを意味するか、あるいは
61+
パニックの際、その状態を片付けるガードを生成することを意味します。
62+
これは必ずしも、パニックが起きているときの状態が、完全に一貫した状態であるということを
63+
意味しません。*安全な*状態であると保証されていることだけが必要なのです。
64+
65+
<!--
2766
Most Unsafe code is leaf-like, and therefore fairly easy to make exception-safe.
2867
It controls all the code that runs, and most of that code can't panic. However
2968
it is not uncommon for Unsafe code to work with arrays of temporarily
3069
uninitialized data while repeatedly invoking caller-provided code. Such code
3170
needs to be careful and consider exception safety.
71+
-->
72+
73+
ほとんどのアンセーフなコードは葉のようなもの (訳注: それ以上別の関数を呼ぶことが
74+
ない) で、それ故に割と簡単に例外安全に出来ます。実行するコードは完全に制御されていて、
75+
そしてほとんどのコードはパニックしません。しかし、アンセーフなコードが
76+
繰り返し呼び出し側のコードを実行している間に、部分的に初期化されていない配列を
77+
扱うことはよくあります。このようなコードは注意深く扱い、例外安全を考える必要があるのです。
3278

3379

3480

3581

3682

3783
## Vec::push_all
3884

85+
<!--
3986
`Vec::push_all` is a temporary hack to get extending a Vec by a slice reliably
4087
efficient without specialization. Here's a simple implementation:
88+
-->
89+
90+
`Vec::push_all` は、特殊化なしに、スライスが確実に効率的であることを利用した、
91+
Vec を伸ばす一時的なハックです。これは単純な実装です。
4192

4293
```rust,ignore
4394
impl<T: Clone> Vec<T> {
4495
fn push_all(&mut self, to_push: &[T]) {
4596
self.reserve(to_push.len());
4697
unsafe {
47-
// can't overflow because we just reserved this
98+
// 今さっき reserve をしたので、オーバーフローするはずがありません
4899
self.set_len(self.len() + to_push.len());
49100

50101
for (i, x) in to_push.iter().enumerate() {
@@ -55,28 +106,52 @@ impl<T: Clone> Vec<T> {
55106
}
56107
```
57108

109+
<!--
58110
We bypass `push` in order to avoid redundant capacity and `len` checks on the
59111
Vec that we definitely know has capacity. The logic is totally correct, except
60112
there's a subtle problem with our code: it's not exception-safe! `set_len`,
61113
`offset`, and `write` are all fine; `clone` is the panic bomb we over-looked.
114+
-->
62115

116+
絶対にキャパシティがあると分かっている Vec の capacity と `len` の余分なチェックを
117+
回避するため、 `push` を使用していません。論理は完全に正しいです。但し、
118+
このコードに微妙な問題が含まれていることを除く。すなわち、このコードは例外安全
119+
ではないのです! `set_len` と `offset` と `write` は全部問題ありません。 `clone` は、
120+
我々が見落としていたパニックの起爆装置です。
121+
122+
<!--
63123
Clone is completely out of our control, and is totally free to panic. If it
64124
does, our function will exit early with the length of the Vec set too large. If
65125
the Vec is looked at or dropped, uninitialized memory will be read!
126+
-->
127+
128+
Clone は全く制御不能で、全く自由にパニックしてしまいます。もしパニックしてしまえば、
129+
この関数は、 Vec の長さが大きすぎる値に設定されたまま、早期に終了してしまいます。
130+
もし Vec が読み出されたりドロップされたりすると、未初期化のメモリが読み出されて
131+
しまいます!
66132

133+
<!--
67134
The fix in this case is fairly simple. If we want to guarantee that the values
68135
we *did* clone are dropped, we can set the `len` every loop iteration. If we
69136
just want to guarantee that uninitialized memory can't be observed, we can set
70137
the `len` after the loop.
138+
-->
71139

72-
140+
この場合、修正は割と簡単です。もし*本当に*、クローンした値がドロップされたと
141+
いうことを保証したいのなら、全てのループのイテレーションにおいて、 `len` を
142+
設定することが出来ます。もし単に、未初期化のメモリが読まれないようにしたいのなら、
143+
ループの後に `len` を設定することが出来ます。
73144

74145

75146

76147
## BinaryHeap::sift_up
77148

149+
<!--
78150
Bubbling an element up a heap is a bit more complicated than extending a Vec.
79151
The pseudocode is as follows:
152+
-->
153+
154+
ヒープにおけるアップヒープは Vec を伸ばすことよりちょっと複雑です。擬似コードはこんな感じです。
80155

81156
```text
82157
bubble_up(heap, index):
@@ -86,28 +161,48 @@ bubble_up(heap, index):
86161

87162
```
88163

164+
<!--
89165
A literal transcription of this code to Rust is totally fine, but has an annoying
90166
performance characteristic: the `self` element is swapped over and over again
91167
uselessly. We would rather have the following:
168+
-->
169+
170+
このコードを Rust に直訳するのは全く問題ありません。ですが、嫌になるようなパフォーマンス
171+
です。すなわち、 `self` の要素が無駄に交換され続けます。それならむしろ、以下のコードの方が
172+
良いでしょう。
92173

93174
```text
94175
bubble_up(heap, index):
95176
let elem = heap[index]
96-
while index != 0 && element < heap[parent(index)]:
177+
while index != 0 && elem < heap[parent(index)]:
97178
heap[index] = heap[parent(index)]
98179
index = parent(index)
99180
heap[index] = elem
100181
```
101182

183+
<!--
102184
This code ensures that each element is copied as little as possible (it is in
103185
fact necessary that elem be copied twice in general). However it now exposes
104186
some exception safety trouble! At all times, there exists two copies of one
105187
value. If we panic in this function something will be double-dropped.
106188
Unfortunately, we also don't have full control of the code: that comparison is
107189
user-defined!
190+
-->
108191

192+
このコードでは確実に、それぞれの要素ができるだけ少ない回数でコピーされます
193+
(実は一般的に、要素を 2 回コピーすることが必要なのです) 。しかし、これによって、
194+
いくつか例外安全性の問題が露見しました! 毎回、ある値に対する 2 つのコピーが
195+
存在します。もしこの関数内でパニックしたら、何かが 2 回ドロップされてしまいます。
196+
残念ながら、このコードに関しても、完全にコントロールすることは出来ません。
197+
比較がユーザ定義されているのです!
198+
199+
<!--
109200
Unlike Vec, the fix isn't as easy here. One option is to break the user-defined
110201
code and the unsafe code into two separate phases:
202+
-->
203+
204+
Vec とは違い、これを直すのは簡単ではありません。一つの選択肢として、ユーザ定義の
205+
コードとアンセーフなコードを、 2 つの段階に分割することです。
111206

112207
```text
113208
bubble_up(heap, index):
@@ -122,16 +217,34 @@ bubble_up(heap, index):
122217
heap[index] = elem
123218
```
124219

220+
<!--
125221
If the user-defined code blows up, that's no problem anymore, because we haven't
126222
actually touched the state of the heap yet. Once we do start messing with the
127223
heap, we're working with only data and functions that we trust, so there's no
128224
concern of panics.
225+
-->
129226

227+
もしユーザ定義のコードでトラブっても、もう問題ありません。なぜなら、
228+
ヒープの状態にはまだ触れていないからです。ヒープを実際に弄るとき、
229+
信用しているデータや関数のみを扱っています。ですからもうパニックの心配は
230+
ありません。
231+
232+
<!--
130233
Perhaps you're not happy with this design. Surely it's cheating! And we have
131234
to do the complex heap traversal *twice*! Alright, let's bite the bullet. Let's
132235
intermix untrusted and unsafe code *for reals*.
236+
-->
237+
238+
多分、この設計を嬉しく思わないでしょう。明らかに騙している! そして複雑な
239+
ヒープのトラバーサルを *2 回* 行わなければならない! 分かった、我慢しよう。
240+
信用していないコードやアンセーフなコードを*本気で*混ぜてみよう。
133241

242+
<!--
134243
If Rust had `try` and `finally` like in Java, we could do the following:
244+
-->
245+
246+
もし Rust に Java のような `try` と `finally` があったら、コードは
247+
こんな感じだったでしょう。
135248

136249
```text
137250
bubble_up(heap, index):
@@ -144,21 +257,36 @@ bubble_up(heap, index):
144257
heap[index] = elem
145258
```
146259

260+
<!--
147261
The basic idea is simple: if the comparison panics, we just toss the loose
148262
element in the logically uninitialized index and bail out. Anyone who observes
149263
the heap will see a potentially *inconsistent* heap, but at least it won't
150264
cause any double-drops! If the algorithm terminates normally, then this
151265
operation happens to coincide precisely with the how we finish up regardless.
266+
-->
152267

268+
基本的な考えは単純です。すなわち、もし比較においてパニックしたのなら、単に要素を
269+
論理的に未初期化のインデックスの位置に保存し、脱出します。このヒープを観察する誰もが、
270+
潜在的には*一貫性のない*ヒープを目にするでしょうが、少なくともこのコードは二重ドロップを
271+
起こしません! もしアルゴリズムが通常通り終了すれば、この操作はコードがどのように終了するかに
272+
関わらず、結果を正確に一致させるために実行されます。
273+
274+
<!--
153275
Sadly, Rust has no such construct, so we're going to need to roll our own! The
154276
way to do this is to store the algorithm's state in a separate struct with a
155277
destructor for the "finally" logic. Whether we panic or not, that destructor
156278
will run and clean up after us.
279+
-->
280+
281+
悲しいことに、 Rust にはそのような構造が存在しません。ですので、自分たちで退避させなければ
282+
ならないようです! これを行なうには、 "finally" の論理を構成するため、デストラクタと共に
283+
アルゴリズムの状態を、別の構造体に保存します。パニックしようがしまいが、デストラクタは
284+
実行され、状態を綺麗にします。
157285

158286
```rust,ignore
159287
struct Hole<'a, T: 'a> {
160288
data: &'a mut [T],
161-
/// `elt` is always `Some` from new until drop.
289+
/// `elt` new で生成されたときからドロップまで、常に Some です
162290
elt: Option<T>,
163291
pos: usize,
164292
}
@@ -191,7 +319,7 @@ impl<'a, T> Hole<'a, T> {
191319

192320
impl<'a, T> Drop for Hole<'a, T> {
193321
fn drop(&mut self) {
194-
// fill the hole again
322+
// 穴を再び埋めます
195323
unsafe {
196324
let pos = self.pos;
197325
ptr::write(&mut self.data[pos], self.elt.take().unwrap());
@@ -202,15 +330,15 @@ impl<'a, T> Drop for Hole<'a, T> {
202330
impl<T: Ord> BinaryHeap<T> {
203331
fn sift_up(&mut self, pos: usize) {
204332
unsafe {
205-
// Take out the value at `pos` and create a hole.
333+
// `pos` にある値を受け取り、穴を作ります。
206334
let mut hole = Hole::new(&mut self.data, pos);
207335

208336
while hole.pos() != 0 {
209337
let parent = parent(hole.pos());
210338
if hole.removed() <= hole.get(parent) { break }
211339
hole.move_to(parent);
212340
}
213-
// Hole will be unconditionally filled here; panic or not!
341+
// 状況に関わらず、穴はここで埋まります。パニックしてもしなくても!
214342
}
215343
}
216344
}

0 commit comments

Comments
 (0)