1
+ <!--
1
2
# Insert and Remove
3
+ -->
2
4
5
+ # 挿入と削除
6
+
7
+ <!--
3
8
Something *not* provided by slice is `insert` and `remove`, so let's do those
4
9
next.
10
+ -->
11
+
12
+ スライスから提供* されない* ものに、 ` insert ` と ` remove ` があります。
13
+ 今度はこれらを実装していきましょう。
5
14
15
+ <!--
6
16
Insert needs to shift all the elements at the target index to the right by one.
7
17
To do this we need to use `ptr::copy`, which is our version of C's `memmove`.
8
18
This copies some chunk of memory from one location to another, correctly
9
19
handling the case where the source and destination overlap (which will
10
20
definitely happen here).
21
+ -->
11
22
23
+ 挿入では、挿入位置から最後の要素まで、 1 ずつずらす必要があります。
24
+ これを行なうために、 ` ptr::copy ` を使う必要があります。 C の ` memmove ` の、
25
+ Rust 版のようなものです。これは、ある場所のメモリを別の場所にコピーします。
26
+ そして、2つの場所が重なっていても、正しくコピーされます (今回の場合、
27
+ 明らかに重なります) 。
28
+
29
+ <!--
12
30
If we insert at index `i`, we want to shift the `[i .. len]` to `[i+1 .. len+1]`
13
31
using the old len.
32
+ -->
33
+
34
+ インデックス ` i ` の位置に挿入する場合、古い ` len ` の値を用いて、
35
+ ` [i .. len] ` を ` [i+1 .. len+1] ` にシフトします。
14
36
15
37
``` rust,ignore
16
38
pub fn insert(&mut self, index: usize, elem: T) {
17
- // Note: `<=` because it's valid to insert after everything
18
- // which would be equivalent to push.
39
+ // 注意: 全要素の後に挿入しても問題ないため、
40
+ // `<=` としています。これは、プッシュと同等です。
41
+
42
+ // 境界外インデックスです
19
43
assert!(index <= self.len, "index out of bounds");
20
44
if self.cap == self.len { self.grow(); }
21
45
22
46
unsafe {
23
47
if index < self.len {
24
- // ptr::copy(src, dest, len): "copy from source to dest len elems "
48
+ // ptr::copy(src, dest, len): "src から dest まで len 個の要素をコピー "
25
49
ptr::copy(self.ptr.offset(index as isize),
26
50
self.ptr.offset(index as isize + 1),
27
51
self.len - index);
@@ -32,12 +56,19 @@ pub fn insert(&mut self, index: usize, elem: T) {
32
56
}
33
57
```
34
58
59
+ <!--
35
60
Remove behaves in the opposite manner. We need to shift all the elements from
36
61
`[i+1 .. len + 1]` to `[i .. len]` using the *new* len.
62
+ -->
63
+
64
+ 削除では真逆の事を行ないます。* 新しい* len を使用して、
65
+ ` [i+1 .. len+1] ` を ` [i .. len] ` にシフトします。
37
66
38
67
``` rust,ignore
39
68
pub fn remove(&mut self, index: usize) -> T {
40
- // Note: `<` because it's *not* valid to remove after everything
69
+ // 注意: 全要素のあとの物を削除することは*有効ではない*ため、 '<' を使用します
70
+
71
+ // 境界外インデックスです
41
72
assert!(index < self.len, "index out of bounds");
42
73
unsafe {
43
74
self.len -= 1;
0 commit comments