Skip to content

Commit 9878eea

Browse files
committed
Implement indexing for slices
1 parent fa4a377 commit 9878eea

File tree

3 files changed

+28
-13
lines changed

3 files changed

+28
-13
lines changed

examples/example.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,3 +180,7 @@ fn make_array() -> [u8; 3] {
180180
fn some_promoted_tuple() -> &'static (&'static str, &'static str) {
181181
&("abc", "some")
182182
}
183+
184+
fn index_slice(s: &[u8]) -> u8 {
185+
s[2]
186+
}

examples/mini_core.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,11 @@ impl<T> Index<usize> for [T; 3] {
207207
&self[index]
208208
}
209209
}
210+
211+
impl<T> Index<usize> for [T] {
212+
type Output = T;
213+
214+
fn index(&self, index: usize) -> &Self::Output {
215+
&self[index]
216+
}
217+
}

src/common.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -433,21 +433,24 @@ impl<'a, 'tcx: 'a> CPlace<'tcx> {
433433
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
434434
index: Value,
435435
) -> CPlace<'tcx> {
436-
match self.layout().ty.sty {
437-
ty::Array(elem_ty, _) => {
438-
let elem_layout = fx.layout_of(elem_ty);
436+
let (elem_layout, addr) = match self.layout().ty.sty {
437+
ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.expect_addr()),
438+
ty::Slice(elem_ty) => (
439+
fx.layout_of(elem_ty),
440+
match self {
441+
CPlace::Addr(addr, _, _) => addr,
442+
CPlace::Var(_, _) => bug!("Expected CPlace::Addr found CPlace::Var"),
443+
},
444+
),
445+
_ => bug!("place_index({:?})", self.layout().ty),
446+
};
439447

440-
let offset = fx
441-
.bcx
442-
.ins()
443-
.imul_imm(index, elem_layout.size.bytes() as i64);
448+
let offset = fx
449+
.bcx
450+
.ins()
451+
.imul_imm(index, elem_layout.size.bytes() as i64);
444452

445-
let addr = self.expect_addr();
446-
CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
447-
}
448-
ty::Slice(_elem_ty) => unimpl!("place_index(TySlice)"),
449-
_ => bug!("place_index({:?})", self.layout().ty),
450-
}
453+
CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
451454
}
452455

453456
pub fn place_deref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CPlace<'tcx> {

0 commit comments

Comments
 (0)