Skip to content

Commit

Permalink
language changes: fixed most warnings, switches to new slicing syntax.
Browse files Browse the repository at this point in the history
  • Loading branch information
lifthrasiir committed Oct 13, 2014
1 parent 6af93e8 commit 2942038
Show file tree
Hide file tree
Showing 39 changed files with 389 additions and 390 deletions.
44 changes: 22 additions & 22 deletions src/engine/cache.rs
Expand Up @@ -4,7 +4,7 @@

//! Caches backed by the external database.

use std::{io, result, path};
use std::{io, path};
use std::io::{IoError, OtherIoError, IoResult, FileStat, SeekSet};
use std::io::fs::{PathExtensions, File, readdir};
use util::md5::{MD5, MD5Hash};
Expand All @@ -30,33 +30,33 @@ fn test_encode_path() {
if cs.len() == 1 {
Path::new(cs[0])
} else {
Path::new(cs[0]).join_many(cs.slice_from(1))
Path::new(cs[0]).join_many(cs[1..])
}
}

let root = path([".", "a", "b"]);
assert_eq!(encode_path(&root, &path([".", "c", "d"])).as_slice(), b".\0..\0..\0c\0d");
assert_eq!(encode_path(&root, &path([".", "c", "d", ""])).as_slice(), b".\0..\0..\0c\0d");
assert_eq!(encode_path(&root, &path([".", "a", "e"])).as_slice(), b".\0..\0e");
assert_eq!(encode_path(&root, &path([".", "a", "b", "f"])).as_slice(), b".\0f");
assert_eq!(encode_path(&root, &path([".", "c", "d"]))[], b".\0..\0..\0c\0d");
assert_eq!(encode_path(&root, &path([".", "c", "d", ""]))[], b".\0..\0..\0c\0d");
assert_eq!(encode_path(&root, &path([".", "a", "e"]))[], b".\0..\0e");
assert_eq!(encode_path(&root, &path([".", "a", "b", "f"]))[], b".\0f");

if cfg!(target_os = "windows") {
assert_eq!(encode_path(&root, &path(["\\", "x", "y", "z"])).as_slice(), b"\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["C:\\", "x", "y", "z"])).as_slice(), b"C:\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["c:\\", "x", "y", "z"])).as_slice(), b"C:\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["C:.", "x", "y", "z"])).as_slice(), b"C:\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["c:.", "x", "y", "z"])).as_slice(), b"C:\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["\\", "x", "y", "z"]))[], b"\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["C:\\", "x", "y", "z"]))[], b"C:\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["c:\\", "x", "y", "z"]))[], b"C:\\\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["C:.", "x", "y", "z"]))[], b"C:\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["c:.", "x", "y", "z"]))[], b"C:\0x\0y\0z");

let absroot = path(["C:\\", "a", "b"]);
assert_eq!(encode_path(&absroot, &path(["C:\\", "c", "d"])).as_slice(), b".\0..\0..\0c\0d");
assert_eq!(encode_path(&absroot, &path(["D:\\", "c", "d"])).as_slice(), b"D:\\\0c\0d");
assert_eq!(encode_path(&absroot, &path(["C:\\", "c", "d"]))[], b".\0..\0..\0c\0d");
assert_eq!(encode_path(&absroot, &path(["D:\\", "c", "d"]))[], b"D:\\\0c\0d");
} else {
assert_eq!(encode_path(&root, &path(["/", "x", "y", "z"])).as_slice(), b"/\0x\0y\0z");
assert_eq!(encode_path(&root, &path(["/", "x", "y", "z"]))[], b"/\0x\0y\0z");

let absroot = path(["/", "a", "b"]);
assert_eq!(encode_path(&absroot, &path(["/", "c", "d"])).as_slice(), b".\0..\0..\0c\0d");
assert_eq!(encode_path(&absroot, &path(["/", "c", "d"]))[], b".\0..\0..\0c\0d");
// this is why the caller should use the absolute path if possible
assert_eq!(encode_path(&absroot, &path([".", "c", "d"])).as_slice(), b".\0c\0d");
assert_eq!(encode_path(&absroot, &path([".", "c", "d"]))[], b".\0c\0d");
}
}

Expand Down Expand Up @@ -282,7 +282,7 @@ impl MetadataCache {

let tr = try!(Transaction::new(&self.db));

let (res, dirstat) = try!(self.check_cached_entries(path, encoded.as_slice()));
let (res, dirstat) = try!(self.check_cached_entries(path, encoded[]));
debug!("get_entries: cache result = {}", res);

match res {
Expand Down Expand Up @@ -330,8 +330,8 @@ impl MetadataCache {
debug!("get_entries: entries = {}",
entries.iter().map(|p| p.display().to_string())
.collect::<Vec<String>>());
let entrystats: Vec<FileStat> =
try!(result::collect(entries.iter().map(|p| p.stat())));
let entrystats = try!(entries.iter().map(|p| p.stat())
.collect::<Result<Vec<FileStat>,_>>());
debug!("get_entries: entrystats.modified = {}",
entrystats.iter().map(|p| p.modified).collect::<Vec<u64>>());

Expand All @@ -350,8 +350,8 @@ impl MetadataCache {
INSERT INTO files(dir, name, size, mtime) VALUES(?, ?, ?, ?);
"));
c.bind_param(1, &sqlite3::Integer64(dirid));
for (path, st) in entries.move_iter().zip(entrystats.iter()) {
let filename = Vec::from_slice(path.filename().unwrap());
for (path, st) in entries.into_iter().zip(entrystats.iter()) {
let filename = path.filename().unwrap().to_vec();
c.reset();
c.bind_param(2, &sqlite3::Blob(filename));
c.bind_param(3, &sqlite3::Integer64(size_from_filestat(st)));
Expand Down Expand Up @@ -437,7 +437,7 @@ impl MetadataCache {

let tr = try!(Transaction::new(&self.db));

let (res, filestat) = try!(self.check_cached_hash(path, encoded.as_slice(), filename));
let (res, filestat) = try!(self.check_cached_hash(path, encoded[], filename));
debug!("get_hash: cache result = {}", res);

match res {
Expand Down
12 changes: 6 additions & 6 deletions src/engine/input.rs
Expand Up @@ -100,7 +100,7 @@ impl VirtualInput {
/// Returns true if the virtual input has a specified key kind in the key specification.
pub fn active_in_key_spec(&self, kind: KeyKind, keyspec: &KeySpec) -> bool {
match *self {
LaneInput(Lane(lane)) => keyspec.kinds.as_slice()[lane] == Some(kind),
LaneInput(Lane(lane)) => keyspec.kinds[lane] == Some(kind),
SpeedDownInput | SpeedUpInput => true
}
}
Expand Down Expand Up @@ -209,10 +209,10 @@ pub fn read_keymap(keyspec: &KeySpec, getenv: |&str| -> Option<String>) -> Resul
let spec = spec.unwrap_or(keyset.default.to_string());

let mut i = 0;
for part in spec.as_slice().split('|') {
for part in spec[].split('|') {
let (kind, vinputs) = keyset.mapping[i];
for s in part.split('%') {
match parse_input(s.as_slice()) {
match parse_input(s[]) {
Some(input) => {
for &vinput in vinputs.iter() {
add_mapping(&mut map, kind, input, vinput);
Expand All @@ -232,11 +232,11 @@ pub fn read_keymap(keyspec: &KeySpec, getenv: |&str| -> Option<String>) -> Resul

for &lane in keyspec.order.iter() {
let key = Key(36 + *lane as int);
let kind = keyspec.kinds.as_slice()[*lane].unwrap();
let kind = keyspec.kinds[*lane].unwrap();
let envvar = format!("SNRS_{}{}_KEY", key, kind.to_char());
let envvar2 = format!("ANGOLMOIS_{}{}_KEY", key, kind.to_char());
for s in getenv(envvar.as_slice()).or(getenv(envvar2.as_slice())).iter() {
match parse_input(s.as_slice()) {
for s in getenv(envvar[]).or(getenv(envvar2[])).iter() {
match parse_input(s[]) {
Some(input) => { add_mapping(&mut map, Some(kind), input, LaneInput(lane)); }
None => { return Err(format!("Unknown key name in the environment variable {}: {}",
envvar, *s)); }
Expand Down
18 changes: 9 additions & 9 deletions src/engine/keyspec.rs
Expand Up @@ -61,7 +61,7 @@ impl KeyKind {
pub fn all() -> &'static [KeyKind] {
static ALL: [KeyKind, ..10] = [WhiteKey, WhiteKeyAlt, BlackKey, Scratch, FootPedal,
Button1, Button2, Button3, Button4, Button5];
ALL.as_slice()
ALL[]
}

/// Converts a mnemonic character to an appropriate key kind. Used for parsing a key
Expand Down Expand Up @@ -139,18 +139,18 @@ impl KeySpec {
/// Returns a list of lanes on the left side, from left to right.
pub fn left_lanes<'r>(&'r self) -> &'r [Lane] {
assert!(self.split <= self.order.len());
self.order.slice(0, self.split)
self.order[..self.split]
}

/// Returns a list of lanes on the right side if any, from left to right.
pub fn right_lanes<'r>(&'r self) -> &'r [Lane] {
assert!(self.split <= self.order.len());
self.order.slice(self.split, self.order.len())
self.order[self.split..]
}

/// Removes insignificant lanes.
pub fn filter_timeline<S:Clone,I:Clone>(&self, timeline: &mut Timeline<S,I>) {
filter_lanes(timeline, self.order.as_slice());
filter_lanes(timeline, self.order[]);
}
}

Expand Down Expand Up @@ -235,7 +235,7 @@ pub fn preset_to_key_spec(bms: &Bms, preset: Option<String>) -> Option<(String,
};

for &(name, leftkeys, rightkeys) in PRESETS.iter() {
if name == preset.as_slice() {
if name == preset[] {
return Some((leftkeys.to_string(), rightkeys.to_string()));
}
}
Expand Down Expand Up @@ -279,25 +279,25 @@ pub fn key_spec(bms: &Bms, preset: Option<String>,
Some(left) => {
let mut err = false;
for &(lane,kind) in left.iter() {
if keyspec.kinds.as_slice()[*lane].is_some() { err = true; break; }
if keyspec.kinds[*lane].is_some() { err = true; break; }
keyspec.order.push(lane);
keyspec.kinds.as_mut_slice()[*lane] = Some(kind);
keyspec.kinds[mut][*lane] = Some(kind);
}
if err {None} else {Some(left.len())}
}
}
};

if !leftkeys.is_empty() {
match parse_and_add(&mut keyspec, leftkeys.as_slice()) {
match parse_and_add(&mut keyspec, leftkeys[]) {
None => { return Err(format!("Invalid key spec for left hand side: {}", leftkeys)); }
Some(nkeys) => { keyspec.split += nkeys; }
}
} else {
return Err(format!("No key model is specified using -k or -K"));
}
if !rightkeys.is_empty() {
match parse_and_add(&mut keyspec, rightkeys.as_slice()) {
match parse_and_add(&mut keyspec, rightkeys[]) {
None => { return Err(format!("Invalid key spec for right hand side: {}", rightkeys)); }
Some(nkeys) => { // no split panes except for Couple Play
if bms.meta.mode != CouplePlay { keyspec.split += nkeys; }
Expand Down
50 changes: 24 additions & 26 deletions src/engine/player.rs
Expand Up @@ -36,18 +36,18 @@ pub fn apply_modf_to_lanes<R:Rng>(timeline: &mut BmsTimeline, modf: Modf, r: &mu

let mut lanes = Vec::new();
for i in range(begin, end) {
let lane = keyspec.order.as_slice()[i];
let kind = keyspec.kinds.as_slice()[*lane];
let lane = keyspec.order[i];
let kind = keyspec.kinds[*lane];
if modf == ShuffleExModf || modf == RandomExModf ||
kind.map_or(false, |kind| kind.counts_as_key()) {
lanes.push(lane);
}
}

match modf {
MirrorModf => timeline_modf::mirror(timeline, lanes.as_slice()),
ShuffleModf | ShuffleExModf => timeline_modf::shuffle(timeline, r, lanes.as_slice()),
RandomModf | RandomExModf => timeline_modf::randomize(timeline, r, lanes.as_slice())
MirrorModf => timeline_modf::mirror(timeline, lanes[]),
ShuffleModf | ShuffleExModf => timeline_modf::shuffle(timeline, r, lanes[]),
RandomModf | RandomExModf => timeline_modf::randomize(timeline, r, lanes[])
};
}

Expand Down Expand Up @@ -260,7 +260,7 @@ fn create_beep() -> sdl_mixer::Chunk {
|i| { let i = i as i32; (i%28-14) * cmp::min(2000, (12000-i)*(12000-i)/50000) });
unsafe {
slice::raw::buf_as_slice(samples.as_ptr() as *const u8, samples.len() * 4, |samples| {
sdl_mixer::Chunk::new(Vec::from_slice(samples), 128)
sdl_mixer::Chunk::new(samples.to_vec(), 128)
})
}
}
Expand All @@ -286,8 +286,7 @@ impl Player {

// set all pointers to the origin and let the `tick` do the initial calculation
let origin = timeline.pointer(VirtualPos, originoffset);
let duration = timeline.duration(originoffset,
|sref| sndres.as_slice()[**sref as uint].duration());
let duration = timeline.duration(originoffset, |sref| sndres[**sref as uint].duration());
let mut player = Player {
opts: opts, meta: meta, timeline: timeline, infos: infos, duration: duration,
keyspec: keyspec, keymap: keymap,
Expand Down Expand Up @@ -405,16 +404,16 @@ impl Player {
/// key sounds.
pub fn play_sound(&mut self, sref: SoundRef, bgm: bool) {
let sref = **sref as uint;
if self.sndres.as_slice()[sref].chunk().is_none() {
if self.sndres[sref].chunk().is_none() {
return;
}
let lastch = self.sndlastch.as_slice()[sref].map(|ch| ch as libc::c_int);
let lastch = self.sndlastch[sref].map(|ch| ch as libc::c_int);

// try to play on the last channel if it is not occupied by other sounds (in this case
// the last channel info is removed)
let mut ch;
loop {
ch = self.sndres.as_mut_slice()[sref].mut_chunk().unwrap().play(lastch, 0);
ch = self.sndres[mut][sref].chunk_mut().unwrap().play(lastch, 0);
if ch >= 0 { break; }
self.allocate_more_channels(32);
}
Expand All @@ -424,11 +423,11 @@ impl Player {
sdl_mixer::group_channel(Some(ch), Some(group));

let ch = ch as uint;
for &idx in self.lastchsnd.as_slice()[ch].iter() {
self.sndlastch.as_mut_slice()[idx] = None;
for &idx in self.lastchsnd[ch].iter() {
self.sndlastch[mut][idx] = None;
}
self.sndlastch.as_mut_slice()[sref] = Some(ch);
self.lastchsnd.as_mut_slice()[ch] = Some(sref);
self.sndlastch[mut][sref] = Some(ch);
self.lastchsnd[mut][ch] = Some(sref);
}

/// Plays a given sound if `sref` is not zero. This reflects the fact that an alphanumeric
Expand Down Expand Up @@ -485,7 +484,7 @@ impl Player {
// if LN grading is in progress and it is not within the threshold then
// MISS grade is issued
let nextlndone =
self.thru.as_slice()[*lane].as_ref().and_then(|thru| {
self.thru[*lane].as_ref().and_then(|thru| {
thru.find_next_of_type(|obj| {
obj.object_lane() == Some(lane) &&
obj.is_lndone()
Expand All @@ -494,12 +493,12 @@ impl Player {
for p in nextlndone.iter() {
let delta = (p.loc.vtime - self.cur.loc.vtime) * self.gradefactor;
if num::abs(delta) < BAD_CUTOFF {
self.nograding.as_mut_slice()[p.index] = true;
self.nograding[mut][p.index] = true;
} else {
self.update_grade_to_miss();
}
}
self.thru.as_mut_slice()[*lane] = None;
self.thru[mut][*lane] = None;
}

/// Processes the press event at given lane:
Expand All @@ -522,12 +521,11 @@ impl Player {
obj.object_lane() == Some(lane) && obj.is_gradable()
});
for p in gradable.iter() {
if p.index >= self.checked.index && !self.nograding.as_slice()[p.index] &&
!p.is_lndone() {
if p.index >= self.checked.index && !self.nograding[p.index] && !p.is_lndone() {
let dist = (p.loc.vtime - self.cur.loc.vtime) * self.gradefactor;
if num::abs(dist) < BAD_CUTOFF {
if p.is_lnstart() { self.thru.as_mut_slice()[*lane] = Some(p.clone()); }
self.nograding.as_mut_slice()[p.index] = true;
if p.is_lnstart() { self.thru[mut][*lane] = Some(p.clone()); }
self.nograding[mut][p.index] = true;
self.update_grade_from_distance(dist);
}
}
Expand Down Expand Up @@ -602,17 +600,17 @@ impl Player {
let dist = (self.cur.loc.vtime - p.loc.vtime) * self.gradefactor;
if dist < BAD_CUTOFF { break; }

if !self.nograding.as_slice()[p.index] {
if !self.nograding[p.index] {
for &Lane(lane) in p.object_lane().iter() {
let missable =
match p.data() {
Visible(..) | LNStart(..) => true,
LNDone(..) => self.thru.as_slice()[lane].is_some(),
LNDone(..) => self.thru[lane].is_some(),
_ => false,
};
if missable {
self.update_grade_to_miss();
self.thru.as_mut_slice()[lane] = None;
self.thru[mut][lane] = None;
}
}
}
Expand Down Expand Up @@ -680,7 +678,7 @@ impl Player {
match p.data() {
Bomb(lane,sref,damage) if self.key_pressed(lane) => {
// ongoing long note is not graded twice
self.thru.as_mut_slice()[*lane] = None;
self.thru[mut][*lane] = None;
for &sref in sref.iter() {
self.play_sound(sref, false);
}
Expand Down
4 changes: 2 additions & 2 deletions src/engine/resource.rs
Expand Up @@ -58,7 +58,7 @@ impl SearchContextAdditions for SearchContext {
basedir: &Path) -> Result<Path,String> {
use std::ascii::StrAsciiExt;
// preserve extensions for the movie files
if path.to_ascii_lower().as_slice().ends_with(".mpg") {
if path.to_ascii_lower()[].ends_with(".mpg") {
resolve_relative_path_result(self, basedir, path, [])
} else {
resolve_relative_path_result(self, basedir, path, IMAGE_EXTS)
Expand All @@ -85,7 +85,7 @@ impl SoundResource {
}

/// Returns the associated chunk if any.
pub fn mut_chunk<'r>(&'r mut self) -> Option<&'r mut Chunk> {
pub fn chunk_mut<'r>(&'r mut self) -> Option<&'r mut Chunk> {
match *self {
NoSound => None,
Sound(ref mut chunk) => Some(chunk)
Expand Down
6 changes: 3 additions & 3 deletions src/ext/smpeg.rs
Expand Up @@ -9,7 +9,7 @@
//! The minimal but functional binding for SMPEG.

use libc::{c_int, c_float};
use std::ptr::mut_null;
use std::ptr::null_mut;
use std::mem::transmute;
use std::string::raw::from_buf;
use sdl::video::Surface;
Expand Down Expand Up @@ -105,7 +105,7 @@ impl MPEG {
pub fn from_path(path: &Path) -> Result<MPEG, String> {
let raw = unsafe {
let path = path.to_c_str();
ll::SMPEG_new(path.as_ptr(), mut_null(), 0)
ll::SMPEG_new(path.as_ptr(), null_mut(), 0)
};

if raw.is_null() { Err(::sdl::get_error()) }
Expand All @@ -122,7 +122,7 @@ impl MPEG {

pub fn set_display(&self, surface: &Surface) {
unsafe {
ll::SMPEG_setdisplay(self.raw, surface.raw, mut_null(), mut_null());
ll::SMPEG_setdisplay(self.raw, surface.raw, null_mut(), null_mut());
}
}

Expand Down

0 comments on commit 2942038

Please sign in to comment.