Skip to content

Commit b48bc9e

Browse files
committed
auto merge of rust-lang#12445 : huonw/rust/less-unsafe, r=alexcrichton
Commits for details. Highlights: - `flate` returns `CVec<u8>` to save reallocating a whole new `&[u8]` - a lot of `transmute`s removed outright or replaced with `as` (etc.)
2 parents 68a4f7d + 9e8d5aa commit b48bc9e

File tree

19 files changed

+68
-78
lines changed

19 files changed

+68
-78
lines changed

mk/crates.mk

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ DEPS_rustc := syntax native:rustllvm flate arena serialize sync getopts \
6565
collections time extra
6666
DEPS_rustdoc := rustc native:sundown serialize sync getopts collections \
6767
test time
68-
DEPS_flate := std native:miniz
68+
DEPS_flate := std extra native:miniz
6969
DEPS_arena := std collections
7070
DEPS_glob := std
7171
DEPS_serialize := std

src/libarena/lib.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,12 @@ unsafe fn destroy_chunk(chunk: &Chunk) {
167167
// is necessary in order to properly do cleanup if a failure occurs
168168
// during an initializer.
169169
#[inline]
170-
unsafe fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
171-
let p_bits: uint = transmute(p);
172-
p_bits | (is_done as uint)
170+
fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
171+
p as uint | (is_done as uint)
173172
}
174173
#[inline]
175-
unsafe fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
176-
(transmute(p & !1), p & 1 == 1)
174+
fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
175+
((p & !1) as *TyDesc, p & 1 == 1)
177176
}
178177

179178
impl Arena {

src/libextra/c_vec.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@
3535
* if necessary.
3636
*/
3737

38+
use std::cast;
3839
use std::ptr;
40+
use std::raw;
3941

4042
/**
4143
* The type representing a foreign chunk of memory
@@ -111,6 +113,20 @@ impl <T> CVec<T> {
111113
}
112114
}
113115

116+
/// View the stored data as a slice.
117+
pub fn as_slice<'a>(&'a self) -> &'a [T] {
118+
unsafe {
119+
cast::transmute(raw::Slice { data: self.base as *T, len: self.len })
120+
}
121+
}
122+
123+
/// View the stored data as a mutable slice.
124+
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
125+
unsafe {
126+
cast::transmute(raw::Slice { data: self.base as *T, len: self.len })
127+
}
128+
}
129+
114130
/**
115131
* Retrieves an element at a given index
116132
*

src/libflate/lib.rs

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ Simple compression
2020
#[license = "MIT/ASL2"];
2121
#[allow(missing_doc)];
2222

23+
extern crate extra;
2324
use std::libc::{c_void, size_t, c_int};
2425
use std::libc;
25-
use std::vec;
26+
use extra::c_vec::CVec;
2627

2728
pub mod rustrt {
2829
use std::libc::{c_int, c_void, size_t};
@@ -33,63 +34,57 @@ pub mod rustrt {
3334
src_buf_len: size_t,
3435
pout_len: *mut size_t,
3536
flags: c_int)
36-
-> *c_void;
37+
-> *mut c_void;
3738

3839
pub fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
3940
src_buf_len: size_t,
4041
pout_len: *mut size_t,
4142
flags: c_int)
42-
-> *c_void;
43+
-> *mut c_void;
4344
}
4445
}
4546

4647
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
4748
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
4849
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
4950

50-
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
51+
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> CVec<u8> {
5152
unsafe {
5253
let mut outsz : size_t = 0;
5354
let res = rustrt::tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
5455
bytes.len() as size_t,
5556
&mut outsz,
5657
flags);
57-
assert!(res as int != 0);
58-
let out = vec::raw::from_buf_raw(res as *u8,
59-
outsz as uint);
60-
libc::free(res as *mut c_void);
61-
out
58+
assert!(!res.is_null());
59+
CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))
6260
}
6361
}
6462

65-
pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
63+
pub fn deflate_bytes(bytes: &[u8]) -> CVec<u8> {
6664
deflate_bytes_internal(bytes, LZ_NORM)
6765
}
6866

69-
pub fn deflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
67+
pub fn deflate_bytes_zlib(bytes: &[u8]) -> CVec<u8> {
7068
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
7169
}
7270

73-
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
71+
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> CVec<u8> {
7472
unsafe {
7573
let mut outsz : size_t = 0;
7674
let res = rustrt::tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
7775
bytes.len() as size_t,
7876
&mut outsz,
7977
flags);
80-
assert!(res as int != 0);
81-
let out = vec::raw::from_buf_raw(res as *u8,
82-
outsz as uint);
83-
libc::free(res as *mut c_void);
84-
out
78+
assert!(!res.is_null());
79+
CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))
8580
}
8681
}
8782

88-
pub fn inflate_bytes(bytes: &[u8]) -> ~[u8] {
83+
pub fn inflate_bytes(bytes: &[u8]) -> CVec<u8> {
8984
inflate_bytes_internal(bytes, 0)
9085
}
9186

92-
pub fn inflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
87+
pub fn inflate_bytes_zlib(bytes: &[u8]) -> CVec<u8> {
9388
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
9489
}
9590

@@ -115,19 +110,19 @@ mod tests {
115110
debug!("de/inflate of {} bytes of random word-sequences",
116111
input.len());
117112
let cmp = deflate_bytes(input);
118-
let out = inflate_bytes(cmp);
113+
let out = inflate_bytes(cmp.as_slice());
119114
debug!("{} bytes deflated to {} ({:.1f}% size)",
120115
input.len(), cmp.len(),
121116
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
122-
assert_eq!(input, out);
117+
assert_eq!(input.as_slice(), out.as_slice());
123118
}
124119
}
125120

126121
#[test]
127122
fn test_zlib_flate() {
128123
let bytes = ~[1, 2, 3, 4, 5];
129124
let deflated = deflate_bytes(bytes);
130-
let inflated = inflate_bytes(deflated);
131-
assert_eq!(inflated, bytes);
125+
let inflated = inflate_bytes(deflated.as_slice());
126+
assert_eq!(inflated.as_slice(), bytes.as_slice());
132127
}
133128
}

src/libgreen/context.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
// except according to those terms.
1010

1111
use std::uint;
12-
use std::cast::{transmute, transmute_mut_unsafe,
13-
transmute_region, transmute_mut_region};
12+
use std::cast::{transmute, transmute_mut_unsafe};
1413
use stack::Stack;
1514
use std::rt::stack;
1615
use std::raw;
@@ -55,10 +54,6 @@ impl Context {
5554
// Save and then immediately load the current context,
5655
// which we will then modify to call the given function when restored
5756
let mut regs = new_regs();
58-
unsafe {
59-
rust_swap_registers(transmute_mut_region(&mut *regs),
60-
transmute_region(&*regs));
61-
};
6257

6358
initialize_call_frame(&mut *regs,
6459
init,
@@ -294,11 +289,8 @@ fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint,
294289
}
295290

296291
fn align_down(sp: *mut uint) -> *mut uint {
297-
unsafe {
298-
let sp: uint = transmute(sp);
299-
let sp = sp & !(16 - 1);
300-
transmute::<uint, *mut uint>(sp)
301-
}
292+
let sp = (sp as uint) & !(16 - 1);
293+
sp as *mut uint
302294
}
303295

304296
// ptr::mut_offset is positive ints only

src/libgreen/sched.rs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -612,9 +612,7 @@ impl Scheduler {
612612
f: |&mut Scheduler, ~GreenTask|) -> ~GreenTask {
613613
let f_opaque = ClosureConverter::from_fn(f);
614614

615-
let current_task_dupe = unsafe {
616-
*cast::transmute::<&~GreenTask, &uint>(&current_task)
617-
};
615+
let current_task_dupe = &*current_task as *GreenTask;
618616

619617
// The current task is placed inside an enum with the cleanup
620618
// function. This enum is then placed inside the scheduler.
@@ -633,13 +631,8 @@ impl Scheduler {
633631
cast::transmute_mut_region(*next_task.sched.get_mut_ref());
634632

635633
let current_task: &mut GreenTask = match sched.cleanup_job {
636-
Some(CleanupJob { task: ref task, .. }) => {
637-
let task_ptr: *~GreenTask = task;
638-
cast::transmute_mut_region(*cast::transmute_mut_unsafe(task_ptr))
639-
}
640-
None => {
641-
rtabort!("no cleanup job");
642-
}
634+
Some(CleanupJob { task: ref mut task, .. }) => &mut **task,
635+
None => rtabort!("no cleanup job")
643636
};
644637

645638
let (current_task_context, next_task_context) =
@@ -852,7 +845,7 @@ impl Scheduler {
852845

853846
// * Utility Functions
854847

855-
pub fn sched_id(&self) -> uint { unsafe { cast::transmute(self) } }
848+
pub fn sched_id(&self) -> uint { self as *Scheduler as uint }
856849

857850
pub fn run_cleanup_job(&mut self) {
858851
let cleanup_job = self.cleanup_job.take_unwrap();

src/libgreen/task.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ impl GreenTask {
266266
// context switches
267267

268268
pub fn as_uint(&self) -> uint {
269-
unsafe { cast::transmute(self) }
269+
self as *GreenTask as uint
270270
}
271271

272272
pub unsafe fn from_uint(val: uint) -> ~GreenTask { cast::transmute(val) }

src/libnative/io/addrinfo.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use std::cast;
1414
use std::io::IoError;
1515
use std::libc;
1616
use std::libc::{c_char, c_int};
17-
use std::ptr::null;
17+
use std::ptr::{null, mut_null};
1818

1919
use super::net::sockaddr_to_addr;
2020

@@ -42,13 +42,13 @@ impl GetAddrInfoRequest {
4242
});
4343

4444
let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo);
45-
let res = null();
45+
let mut res = mut_null();
4646

4747
// Make the call
4848
let s = unsafe {
4949
let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) };
5050
let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) };
51-
getaddrinfo(ch, cs, hint_ptr, &res)
51+
getaddrinfo(ch, cs, hint_ptr, &mut res)
5252
};
5353

5454
// Error?
@@ -74,7 +74,7 @@ impl GetAddrInfoRequest {
7474
flags: (*rp).ai_flags as uint
7575
});
7676

77-
rp = (*rp).ai_next;
77+
rp = (*rp).ai_next as *mut libc::addrinfo;
7878
}
7979
}
8080

@@ -86,8 +86,8 @@ impl GetAddrInfoRequest {
8686

8787
extern "system" {
8888
fn getaddrinfo(node: *c_char, service: *c_char,
89-
hints: *libc::addrinfo, res: **libc::addrinfo) -> c_int;
90-
fn freeaddrinfo(res: *libc::addrinfo);
89+
hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int;
90+
fn freeaddrinfo(res: *mut libc::addrinfo);
9191
#[cfg(not(windows))]
9292
fn gai_strerror(errcode: c_int) -> *c_char;
9393
#[cfg(windows)]

src/libnative/io/file.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ impl FileDesc {
9191
#[cfg(not(windows))] type rlen = libc::size_t;
9292
let ret = retry(|| unsafe {
9393
libc::read(self.fd(),
94-
buf.as_ptr() as *mut libc::c_void,
94+
buf.as_mut_ptr() as *mut libc::c_void,
9595
buf.len() as rlen) as libc::c_int
9696
});
9797
if ret == 0 {

src/libnative/io/net.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ impl rtio::RtioTcpStream for TcpStream {
309309
let ret = retry(|| {
310310
unsafe {
311311
libc::recv(self.fd(),
312-
buf.as_ptr() as *mut libc::c_void,
312+
buf.as_mut_ptr() as *mut libc::c_void,
313313
buf.len() as wrlen,
314314
0) as libc::c_int
315315
}

src/libnative/task.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ impl rt::Runtime for Ops {
186186
cur_task.put_runtime(self as ~rt::Runtime);
187187

188188
unsafe {
189-
let cur_task_dupe = *cast::transmute::<&~Task, &uint>(&cur_task);
189+
let cur_task_dupe = &*cur_task as *Task;
190190
let task = BlockedTask::block(cur_task);
191191

192192
if times == 1 {
@@ -218,7 +218,7 @@ impl rt::Runtime for Ops {
218218
}
219219
}
220220
// re-acquire ownership of the task
221-
cur_task = cast::transmute::<uint, ~Task>(cur_task_dupe);
221+
cur_task = cast::transmute(cur_task_dupe);
222222
}
223223

224224
// put the task back in TLS, and everything is as it once was.

src/librustc/back/link.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -944,7 +944,7 @@ fn link_rlib(sess: Session,
944944
// into the archive.
945945
let bc = obj_filename.with_extension("bc");
946946
match fs::File::open(&bc).read_to_end().and_then(|data| {
947-
fs::File::create(&bc).write(flate::deflate_bytes(data))
947+
fs::File::create(&bc).write(flate::deflate_bytes(data).as_slice())
948948
}) {
949949
Ok(()) => {}
950950
Err(e) => {

src/librustc/back/lto.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub fn run(sess: session::Session, llmod: ModuleRef,
5858
let bc = bc.expect("missing bytecode in archive!");
5959
let bc = time(sess.time_passes(), format!("inflate {}.bc", name), (), |_|
6060
flate::inflate_bytes(bc));
61-
let ptr = bc.as_ptr();
61+
let ptr = bc.as_slice().as_ptr();
6262
debug!("linking {}", name);
6363
time(sess.time_passes(), format!("ll link {}", name), (), |()| unsafe {
6464
if !llvm::LLVMRustLinkInExternalBitcode(llmod,

src/librustc/metadata/cstore.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use metadata::loader;
1818

1919
use std::cell::RefCell;
2020
use collections::HashMap;
21+
use extra::c_vec::CVec;
2122
use syntax::ast;
2223
use syntax::parse::token::IdentInterner;
2324

@@ -28,7 +29,7 @@ use syntax::parse::token::IdentInterner;
2829
pub type cnum_map = @RefCell<HashMap<ast::CrateNum, ast::CrateNum>>;
2930

3031
pub enum MetadataBlob {
31-
MetadataVec(~[u8]),
32+
MetadataVec(CVec<u8>),
3233
MetadataArchive(loader::ArchiveMetadata),
3334
}
3435

src/librustc/middle/trans/base.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2569,7 +2569,7 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
25692569
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
25702570
let metadata = encoder::encode_metadata(encode_parms, krate);
25712571
let compressed = encoder::metadata_encoding_version +
2572-
flate::deflate_bytes(metadata);
2572+
flate::deflate_bytes(metadata).as_slice();
25732573
let llmeta = C_bytes(compressed);
25742574
let llconst = C_struct([llmeta], false);
25752575
let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,

src/librustuv/queue.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ impl QueuePool {
123123
unsafe {
124124
assert_eq!(uvll::uv_async_init(loop_.handle, handle, async_cb), 0);
125125
uvll::uv_unref(handle);
126-
let data: *c_void = *cast::transmute::<&~QueuePool, &*c_void>(&q);
126+
let data = &*q as *QueuePool as *c_void;
127127
uvll::set_data_for_uv_handle(handle, data);
128128
}
129129

src/libserialize/ebml.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,7 @@ pub mod reader {
161161
];
162162

163163
unsafe {
164-
let (ptr, _): (*u8, uint) = transmute(data);
165-
let ptr = ptr.offset(start as int);
166-
let ptr: *i32 = transmute(ptr);
164+
let ptr = data.as_ptr().offset(start as int) as *i32;
167165
let val = from_be32(*ptr) as u32;
168166

169167
let i = (val >> 28u) as uint;

0 commit comments

Comments
 (0)