Merge remote-tracking branch 'original/incoming' into incoming

Conflicts:
	src/libstd/json.rs
	src/libstd/sort.rs
This commit is contained in:
Simon BD 2012-10-03 21:47:09 -05:00
commit efcd2385ea
378 changed files with 11486 additions and 8500 deletions

View file

@ -1,6 +1,5 @@
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
/**
* Concurrency-enabled mechanisms for sharing mutable and/or immutable state
* between tasks.
@ -12,14 +11,9 @@ use private::{SharedMutableState, shared_mutable_state,
use sync::{Mutex, mutex_with_condvars,
RWlock, rwlock_with_condvars};
export ARC, clone, get;
export Condvar;
export MutexARC, mutex_arc_with_condvars, unwrap_mutex_arc;
export RWARC, rw_arc_with_condvars, RWWriteMode, RWReadMode;
export unwrap_rw_arc;
/// As sync::condvar, a mechanism for unlock-and-descheduling and signalling.
struct Condvar { is_mutex: bool, failed: &mut bool, cond: &sync::Condvar }
pub struct Condvar { is_mutex: bool, failed: &mut bool, cond: &sync::Condvar }
impl &Condvar {
/// Atomically exit the associated ARC and block until a signal is sent.
@ -72,7 +66,7 @@ impl &Condvar {
struct ARC<T: Const Send> { x: SharedMutableState<T> }
/// Create an atomically reference counted wrapper.
fn ARC<T: Const Send>(+data: T) -> ARC<T> {
pub fn ARC<T: Const Send>(data: T) -> ARC<T> {
ARC { x: unsafe { shared_mutable_state(move data) } }
}
@ -80,7 +74,7 @@ fn ARC<T: Const Send>(+data: T) -> ARC<T> {
* Access the underlying data in an atomically reference counted
* wrapper.
*/
fn get<T: Const Send>(rc: &a/ARC<T>) -> &a/T {
pub fn get<T: Const Send>(rc: &a/ARC<T>) -> &a/T {
unsafe { get_shared_immutable_state(&rc.x) }
}
@ -91,7 +85,7 @@ fn get<T: Const Send>(rc: &a/ARC<T>) -> &a/T {
* object. However, one of the `arc` objects can be sent to another task,
* allowing them to share the underlying data.
*/
fn clone<T: Const Send>(rc: &ARC<T>) -> ARC<T> {
pub fn clone<T: Const Send>(rc: &ARC<T>) -> ARC<T> {
ARC { x: unsafe { clone_shared_mutable_state(&rc.x) } }
}
@ -104,7 +98,7 @@ fn clone<T: Const Send>(rc: &ARC<T>) -> ARC<T> {
* unwrap from a task that holds another reference to the same ARC; it is
* guaranteed to deadlock.
*/
fn unwrap<T: Const Send>(+rc: ARC<T>) -> T {
fn unwrap<T: Const Send>(rc: ARC<T>) -> T {
let ARC { x: x } <- rc;
unsafe { unwrap_shared_mutable_state(move x) }
}
@ -119,14 +113,14 @@ struct MutexARCInner<T: Send> { lock: Mutex, failed: bool, data: T }
struct MutexARC<T: Send> { x: SharedMutableState<MutexARCInner<T>> }
/// Create a mutex-protected ARC with the supplied data.
fn MutexARC<T: Send>(+user_data: T) -> MutexARC<T> {
pub fn MutexARC<T: Send>(user_data: T) -> MutexARC<T> {
mutex_arc_with_condvars(move user_data, 1)
}
/**
* Create a mutex-protected ARC with the supplied data and a specified number
* of condvars (as sync::mutex_with_condvars).
*/
fn mutex_arc_with_condvars<T: Send>(+user_data: T,
pub fn mutex_arc_with_condvars<T: Send>(user_data: T,
num_condvars: uint) -> MutexARC<T> {
let data =
MutexARCInner { lock: mutex_with_condvars(num_condvars),
@ -197,7 +191,7 @@ impl<T: Send> &MutexARC<T> {
* Will additionally fail if another task has failed while accessing the arc.
*/
// FIXME(#2585) make this a by-move method on the arc
fn unwrap_mutex_arc<T: Send>(+arc: MutexARC<T>) -> T {
pub fn unwrap_mutex_arc<T: Send>(arc: MutexARC<T>) -> T {
let MutexARC { x: x } <- arc;
let inner = unsafe { unwrap_shared_mutable_state(move x) };
let MutexARCInner { failed: failed, data: data, _ } <- inner;
@ -253,14 +247,14 @@ struct RWARC<T: Const Send> {
}
/// Create a reader/writer ARC with the supplied data.
fn RWARC<T: Const Send>(+user_data: T) -> RWARC<T> {
pub fn RWARC<T: Const Send>(user_data: T) -> RWARC<T> {
rw_arc_with_condvars(move user_data, 1)
}
/**
* Create a reader/writer ARC with the supplied data and a specified number
* of condvars (as sync::rwlock_with_condvars).
*/
fn rw_arc_with_condvars<T: Const Send>(+user_data: T,
pub fn rw_arc_with_condvars<T: Const Send>(user_data: T,
num_condvars: uint) -> RWARC<T> {
let data =
RWARCInner { lock: rwlock_with_condvars(num_condvars),
@ -340,7 +334,7 @@ impl<T: Const Send> &RWARC<T> {
* }
* ~~~
*/
fn write_downgrade<U>(blk: fn(+v: RWWriteMode<T>) -> U) -> U {
fn write_downgrade<U>(blk: fn(v: RWWriteMode<T>) -> U) -> U {
let state = unsafe { get_shared_mutable_state(&self.x) };
do borrow_rwlock(state).write_downgrade |write_mode| {
check_poison(false, state.failed);
@ -350,7 +344,7 @@ impl<T: Const Send> &RWARC<T> {
}
/// To be called inside of the write_downgrade block.
fn downgrade(+token: RWWriteMode/&a<T>) -> RWReadMode/&a<T> {
fn downgrade(token: RWWriteMode/&a<T>) -> RWReadMode/&a<T> {
// The rwlock should assert that the token belongs to us for us.
let state = unsafe { get_shared_immutable_state(&self.x) };
let RWWriteMode((data, t, _poison)) <- token;
@ -375,7 +369,7 @@ impl<T: Const Send> &RWARC<T> {
* in write mode.
*/
// FIXME(#2585) make this a by-move method on the arc
fn unwrap_rw_arc<T: Const Send>(+arc: RWARC<T>) -> T {
pub fn unwrap_rw_arc<T: Const Send>(arc: RWARC<T>) -> T {
let RWARC { x: x, _ } <- arc;
let inner = unsafe { unwrap_shared_mutable_state(move x) };
let RWARCInner { failed: failed, data: data, _ } <- inner;
@ -396,10 +390,10 @@ fn borrow_rwlock<T: Const Send>(state: &r/mut RWARCInner<T>) -> &r/RWlock {
// FIXME (#3154) ice with struct/&<T> prevents these from being structs.
/// The "write permission" token used for RWARC.write_downgrade().
enum RWWriteMode<T: Const Send> =
pub enum RWWriteMode<T: Const Send> =
(&mut T, sync::RWlockWriteMode, PoisonOnFail);
/// The "read permission" token used for RWARC.write_downgrade().
enum RWReadMode<T:Const Send> = (&T, sync::RWlockReadMode);
pub enum RWReadMode<T:Const Send> = (&T, sync::RWlockReadMode);
impl<T: Const Send> &RWWriteMode<T> {
/// Access the pre-downgrade RWARC in write mode.
@ -648,7 +642,7 @@ mod tests {
let mut children = ~[];
for 5.times {
let arc3 = ~arc.clone();
do task::task().future_result(|+r| vec::push(children, r)).spawn {
do task::task().future_result(|+r| children.push(r)).spawn {
do arc3.read |num| {
assert *num >= 0;
}
@ -676,7 +670,7 @@ mod tests {
let mut reader_convos = ~[];
for 10.times {
let ((rc1,rp1),(rc2,rp2)) = (pipes::stream(),pipes::stream());
vec::push(reader_convos, (rc1,rp2));
reader_convos.push((rc1,rp2));
let arcn = ~arc.clone();
do task::spawn {
rp1.recv(); // wait for downgrader to give go-ahead
@ -719,7 +713,7 @@ mod tests {
// send to other readers
for vec::each(reader_convos) |x| {
match *x {
(rc, _) => rc.send(()),
(ref rc, _) => rc.send(()),
}
}
}
@ -728,7 +722,7 @@ mod tests {
// complete handshake with other readers
for vec::each(reader_convos) |x| {
match *x {
(_, rp) => rp.recv(),
(_, ref rp) => rp.recv(),
}
}
wc1.send(()); // tell writer to try again

View file

@ -23,9 +23,6 @@
// to waste time running the destructors of POD.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
export Arena, arena_with_size;
use list::{List, Cons, Nil};
use cast::reinterpret_cast;
@ -34,12 +31,10 @@ use libc::size_t;
#[abi = "rust-intrinsic"]
extern mod rusti {
#[legacy_exports];
fn move_val_init<T>(&dst: T, -src: T);
fn needs_drop<T>() -> bool;
}
extern mod rustrt {
#[legacy_exports];
#[rust_stack]
fn rust_call_tydesc_glue(root: *u8, tydesc: *TypeDesc, field: size_t);
}
@ -52,7 +47,7 @@ const tydesc_drop_glue_index: size_t = 3 as size_t;
// will always stay at 0.
type Chunk = {data: @[u8], mut fill: uint, is_pod: bool};
struct Arena {
pub struct Arena {
// The head is seperated out from the list as a unbenchmarked
// microoptimization, to avoid needing to case on the list to
// access the head.
@ -63,25 +58,25 @@ struct Arena {
unsafe {
destroy_chunk(&self.head);
for list::each(self.chunks) |chunk| {
if !chunk.is_pod { destroy_chunk(&chunk); }
if !chunk.is_pod { destroy_chunk(chunk); }
}
}
}
}
fn chunk(size: uint, is_pod: bool) -> Chunk {
let mut v = @[];
unsafe { at_vec::raw::reserve(v, size); }
{ data: v, mut fill: 0u, is_pod: is_pod }
let mut v: @[const u8] = @[];
unsafe { at_vec::raw::reserve(&mut v, size); }
{ data: unsafe { cast::transmute(v) }, mut fill: 0u, is_pod: is_pod }
}
fn arena_with_size(initial_size: uint) -> Arena {
pub fn arena_with_size(initial_size: uint) -> Arena {
return Arena {mut head: chunk(initial_size, false),
mut pod_head: chunk(initial_size, true),
mut chunks: @Nil};
}
fn Arena() -> Arena {
pub fn Arena() -> Arena {
arena_with_size(32u)
}

View file

@ -1,8 +1,7 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use io::Reader;
trait ToBase64 {
pub trait ToBase64 {
fn to_base64() -> ~str;
}
@ -63,7 +62,7 @@ impl &str: ToBase64 {
}
}
trait FromBase64 {
pub trait FromBase64 {
fn from_base64() -> ~[u8];
}
@ -102,12 +101,12 @@ impl ~[u8]: FromBase64 {
} else if ch == '=' {
match len - i {
1u => {
vec::push(r, ((n >> 16u) & 0xFFu) as u8);
vec::push(r, ((n >> 8u ) & 0xFFu) as u8);
r.push(((n >> 16u) & 0xFFu) as u8);
r.push(((n >> 8u ) & 0xFFu) as u8);
return copy r;
}
2u => {
vec::push(r, ((n >> 10u) & 0xFFu) as u8);
r.push(((n >> 10u) & 0xFFu) as u8);
return copy r;
}
_ => fail ~"invalid base64 padding"
@ -119,9 +118,9 @@ impl ~[u8]: FromBase64 {
i += 1u;
};
vec::push(r, ((n >> 16u) & 0xFFu) as u8);
vec::push(r, ((n >> 8u ) & 0xFFu) as u8);
vec::push(r, ((n ) & 0xFFu) as u8);
r.push(((n >> 16u) & 0xFFu) as u8);
r.push(((n >> 8u ) & 0xFFu) as u8);
r.push(((n ) & 0xFFu) as u8);
}
r

View file

@ -1,10 +1,7 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use vec::{to_mut, from_elem};
export Bitv, from_bytes, from_bools, from_fn;
struct SmallBitv {
/// only the lowest nbits of this value are used. the rest is undefined.
mut bits: u32
@ -98,7 +95,7 @@ struct BigBitv {
mut storage: ~[mut uint]
}
fn BigBitv(+storage: ~[mut uint]) -> BigBitv {
fn BigBitv(storage: ~[mut uint]) -> BigBitv {
BigBitv {storage: storage}
}
@ -140,17 +137,17 @@ impl BigBitv {
}
#[inline(always)]
fn each_storage(op: fn(&v: uint) -> bool) {
fn each_storage(op: fn(v: &mut uint) -> bool) {
for uint::range(0, self.storage.len()) |i| {
let mut w = self.storage[i];
let b = !op(w);
let b = !op(&mut w);
self.storage[i] = w;
if !b { break; }
}
}
#[inline(always)]
fn invert() { for self.each_storage() |w| { w = !w } }
fn invert() { for self.each_storage() |w| { *w = !*w } }
#[inline(always)]
fn union(b: &BigBitv, nbits: uint) -> bool {
@ -210,12 +207,12 @@ enum BitvVariant { Big(~BigBitv), Small(~SmallBitv) }
enum Op {Union, Intersect, Assign, Difference}
// The bitvector type
struct Bitv {
pub struct Bitv {
rep: BitvVariant,
nbits: uint
}
fn Bitv (nbits: uint, init: bool) -> Bitv {
pub fn Bitv (nbits: uint, init: bool) -> Bitv {
let rep = if nbits <= 32 {
Small(~SmallBitv(if init {!0} else {0}))
}
@ -241,22 +238,22 @@ priv impl Bitv {
self.die();
}
match self.rep {
Small(s) => match other.rep {
Small(s1) => match op {
Union => s.union(s1, self.nbits),
Intersect => s.intersect(s1, self.nbits),
Assign => s.become(s1, self.nbits),
Difference => s.difference(s1, self.nbits)
Small(ref s) => match other.rep {
Small(ref s1) => match op {
Union => s.union(*s1, self.nbits),
Intersect => s.intersect(*s1, self.nbits),
Assign => s.become(*s1, self.nbits),
Difference => s.difference(*s1, self.nbits)
},
Big(_) => self.die()
},
Big(s) => match other.rep {
Big(ref s) => match other.rep {
Small(_) => self.die(),
Big(s1) => match op {
Union => s.union(s1, self.nbits),
Intersect => s.intersect(s1, self.nbits),
Assign => s.become(s1, self.nbits),
Difference => s.difference(s1, self.nbits)
Big(ref s1) => match op {
Union => s.union(*s1, self.nbits),
Intersect => s.intersect(*s1, self.nbits),
Assign => s.become(*s1, self.nbits),
Difference => s.difference(*s1, self.nbits)
}
}
}
@ -297,10 +294,10 @@ impl Bitv {
#[inline(always)]
fn clone() -> ~Bitv {
~match self.rep {
Small(b) => {
Small(ref b) => {
Bitv{nbits: self.nbits, rep: Small(~SmallBitv{bits: b.bits})}
}
Big(b) => {
Big(ref b) => {
let st = to_mut(from_elem(self.nbits / uint_bits + 1, 0));
let len = st.len();
for uint::range(0, len) |i| { st[i] = b.storage[i]; };
@ -314,8 +311,8 @@ impl Bitv {
pure fn get(i: uint) -> bool {
assert (i < self.nbits);
match self.rep {
Big(b) => b.get(i),
Small(s) => s.get(i)
Big(ref b) => b.get(i),
Small(ref s) => s.get(i)
}
}
@ -328,8 +325,8 @@ impl Bitv {
fn set(i: uint, x: bool) {
assert (i < self.nbits);
match self.rep {
Big(b) => b.set(i, x),
Small(s) => s.set(i, x)
Big(ref b) => b.set(i, x),
Small(ref s) => s.set(i, x)
}
}
@ -340,15 +337,15 @@ impl Bitv {
* bitvectors contain identical elements.
*/
#[inline(always)]
fn equal(v1: Bitv) -> bool {
fn equal(v1: &Bitv) -> bool {
if self.nbits != v1.nbits { return false; }
match self.rep {
Small(b) => match v1.rep {
Small(b1) => b.equals(b1, self.nbits),
Small(ref b) => match v1.rep {
Small(ref b1) => b.equals(*b1, self.nbits),
_ => false
},
Big(s) => match v1.rep {
Big(s1) => s.equals(s1, self.nbits),
Big(ref s) => match v1.rep {
Big(ref s1) => s.equals(*s1, self.nbits),
Small(_) => return false
}
}
@ -358,8 +355,8 @@ impl Bitv {
#[inline(always)]
fn clear() {
match self.rep {
Small(b) => b.clear(),
Big(s) => for s.each_storage() |w| { w = 0u }
Small(ref b) => b.clear(),
Big(ref s) => for s.each_storage() |w| { *w = 0u }
}
}
@ -367,16 +364,16 @@ impl Bitv {
#[inline(always)]
fn set_all() {
match self.rep {
Small(b) => b.set_all(),
Big(s) => for s.each_storage() |w| { w = !0u } }
Small(ref b) => b.set_all(),
Big(ref s) => for s.each_storage() |w| { *w = !0u } }
}
/// Invert all bits
#[inline(always)]
fn invert() {
match self.rep {
Small(b) => b.invert(),
Big(s) => for s.each_storage() |w| { w = !w } }
Small(ref b) => b.invert(),
Big(ref s) => for s.each_storage() |w| { *w = !*w } }
}
/**
@ -389,13 +386,13 @@ impl Bitv {
* Returns `true` if `v0` was changed.
*/
#[inline(always)]
fn difference(v: ~Bitv) -> bool { self.do_op(Difference, v) }
fn difference(v: &Bitv) -> bool { self.do_op(Difference, v) }
/// Returns true if all bits are 1
#[inline(always)]
fn is_true() -> bool {
match self.rep {
Small(b) => b.is_true(self.nbits),
Small(ref b) => b.is_true(self.nbits),
_ => {
for self.each() |i| { if !i { return false; } }
true
@ -415,7 +412,7 @@ impl Bitv {
/// Returns true if all bits are 0
fn is_false() -> bool {
match self.rep {
Small(b) => b.is_false(self.nbits),
Small(ref b) => b.is_false(self.nbits),
Big(_) => {
for self.each() |i| { if i { return false; } }
true
@ -520,7 +517,7 @@ impl Bitv {
* with the most significant bits of each byte coming first. Each
* bit becomes true if equal to 1 or false if equal to 0.
*/
fn from_bytes(bytes: &[u8]) -> Bitv {
pub fn from_bytes(bytes: &[u8]) -> Bitv {
from_fn(bytes.len() * 8, |i| {
let b = bytes[i / 8] as uint;
let offset = i % 8;
@ -531,7 +528,7 @@ fn from_bytes(bytes: &[u8]) -> Bitv {
/**
* Transform a [bool] into a bitv by converting each bool into a bit.
*/
fn from_bools(bools: &[bool]) -> Bitv {
pub fn from_bools(bools: &[bool]) -> Bitv {
from_fn(bools.len(), |i| bools[i])
}
@ -539,7 +536,7 @@ fn from_bools(bools: &[bool]) -> Bitv {
* Create a bitv of the specified length where the value at each
* index is f(index).
*/
fn from_fn(len: uint, f: fn(index: uint) -> bool) -> Bitv {
pub fn from_fn(len: uint, f: fn(index: uint) -> bool) -> Bitv {
let bitv = Bitv(len, false);
for uint::range(0, len) |i| {
bitv.set(i, f(i));
@ -556,7 +553,7 @@ pure fn land(w0: uint, w1: uint) -> uint { return w0 & w1; }
pure fn right(_w0: uint, w1: uint) -> uint { return w1; }
impl Bitv: ops::Index<uint,bool> {
pure fn index(&&i: uint) -> bool {
pure fn index(+i: uint) -> bool {
self.get(i)
}
}
@ -866,14 +863,14 @@ mod tests {
fn test_equal_differing_sizes() {
let v0 = Bitv(10u, false);
let v1 = Bitv(11u, false);
assert !v0.equal(v1);
assert !v0.equal(&v1);
}
#[test]
fn test_equal_greatly_differing_sizes() {
let v0 = Bitv(10u, false);
let v1 = Bitv(110u, false);
assert !v0.equal(v1);
assert !v0.equal(&v1);
}
#[test]
@ -884,7 +881,7 @@ mod tests {
let b = bitv::Bitv(1, true);
b.set(0, true);
assert a.equal(b);
assert a.equal(&b);
}
#[test]
@ -899,7 +896,7 @@ mod tests {
b.set(i, true);
}
assert a.equal(b);
assert a.equal(&b);
}
#[test]

View file

@ -26,19 +26,13 @@
* still held if needed.
*/
export CVec;
export CVec, c_vec_with_dtor;
export get, set;
export len;
export ptr;
/**
* The type representing a foreign chunk of memory
*
* Wrapped in a enum for opacity; FIXME #818 when it is possible to have
* truly opaque types, this should be revisited.
*/
enum CVec<T> {
pub enum CVec<T> {
CVecCtor({ base: *mut T, len: uint, rsrc: @DtorRes})
}
@ -70,7 +64,7 @@ fn DtorRes(dtor: Option<fn@()>) -> DtorRes {
* * base - A foreign pointer to a buffer
* * len - The number of elements in the buffer
*/
unsafe fn CVec<T>(base: *mut T, len: uint) -> CVec<T> {
pub unsafe fn CVec<T>(base: *mut T, len: uint) -> CVec<T> {
return CVecCtor({
base: base,
len: len,
@ -89,7 +83,7 @@ unsafe fn CVec<T>(base: *mut T, len: uint) -> CVec<T> {
* * dtor - A function to run when the value is destructed, useful
* for freeing the buffer, etc.
*/
unsafe fn c_vec_with_dtor<T>(base: *mut T, len: uint, dtor: fn@())
pub unsafe fn c_vec_with_dtor<T>(base: *mut T, len: uint, dtor: fn@())
-> CVec<T> {
return CVecCtor({
base: base,
@ -107,7 +101,7 @@ unsafe fn c_vec_with_dtor<T>(base: *mut T, len: uint, dtor: fn@())
*
* Fails if `ofs` is greater or equal to the length of the vector
*/
fn get<T: Copy>(t: CVec<T>, ofs: uint) -> T {
pub fn get<T: Copy>(t: CVec<T>, ofs: uint) -> T {
assert ofs < len(t);
return unsafe { *ptr::mut_offset((*t).base, ofs) };
}
@ -117,7 +111,7 @@ fn get<T: Copy>(t: CVec<T>, ofs: uint) -> T {
*
* Fails if `ofs` is greater or equal to the length of the vector
*/
fn set<T: Copy>(t: CVec<T>, ofs: uint, v: T) {
pub fn set<T: Copy>(t: CVec<T>, ofs: uint, +v: T) {
assert ofs < len(t);
unsafe { *ptr::mut_offset((*t).base, ofs) = v };
}
@ -127,18 +121,17 @@ fn set<T: Copy>(t: CVec<T>, ofs: uint, v: T) {
*/
/// Returns the length of the vector
fn len<T>(t: CVec<T>) -> uint {
pub fn len<T>(t: CVec<T>) -> uint {
return (*t).len;
}
/// Returns a pointer to the first element of the vector
unsafe fn ptr<T>(t: CVec<T>) -> *mut T {
pub unsafe fn ptr<T>(t: CVec<T>) -> *mut T {
return (*t).base;
}
#[cfg(test)]
mod tests {
#[legacy_exports];
use libc::*;
fn malloc(n: size_t) -> CVec<u8> {

View file

@ -1,19 +1,18 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
/// A dynamic, mutable location.
///
/// Similar to a mutable option type, but friendlier.
struct Cell<T> {
pub struct Cell<T> {
mut value: Option<T>
}
/// Creates a new full cell with the given value.
fn Cell<T>(+value: T) -> Cell<T> {
pub fn Cell<T>(value: T) -> Cell<T> {
Cell { value: Some(move value) }
}
fn empty_cell<T>() -> Cell<T> {
pub fn empty_cell<T>() -> Cell<T> {
Cell { value: None }
}
@ -30,7 +29,7 @@ impl<T> Cell<T> {
}
/// Returns the value, failing if the cell is full.
fn put_back(+value: T) {
fn put_back(value: T) {
if !self.is_empty() {
fail ~"attempt to put a value back into a full cell";
}

View file

@ -1,10 +1,9 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
/// Additional general-purpose comparison functionality.
const fuzzy_epsilon: float = 1.0e-6;
trait FuzzyEq {
pub trait FuzzyEq {
pure fn fuzzy_eq(other: &self) -> bool;
}

View file

@ -6,14 +6,11 @@ Higher level communication abstractions.
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use pipes::{Channel, Recv, Chan, Port, Selectable};
export DuplexStream;
/// An extension of `pipes::stream` that allows both sending and receiving.
struct DuplexStream<T: Send, U: Send> {
pub struct DuplexStream<T: Send, U: Send> {
priv chan: Chan<T>,
priv port: Port <U>,
}
@ -49,7 +46,7 @@ impl<T: Send, U: Send> DuplexStream<T, U> : Selectable {
}
/// Creates a bidirectional stream.
fn DuplexStream<T: Send, U: Send>()
pub fn DuplexStream<T: Send, U: Send>()
-> (DuplexStream<T, U>, DuplexStream<U, T>)
{
let (c2, p1) = pipes::stream();

View file

@ -1,16 +1,8 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
//! Unsafe debugging functions for inspecting values.
use cast::reinterpret_cast;
export debug_tydesc;
export debug_opaque;
export debug_box;
export debug_tag;
export debug_fn;
export ptr_cast;
export breakpoint;
#[abi = "cdecl"]
extern mod rustrt {
@ -24,34 +16,34 @@ extern mod rustrt {
fn rust_dbg_breakpoint();
}
fn debug_tydesc<T>() {
pub fn debug_tydesc<T>() {
rustrt::debug_tydesc(sys::get_type_desc::<T>());
}
fn debug_opaque<T>(+x: T) {
rustrt::debug_opaque(sys::get_type_desc::<T>(), ptr::addr_of(x) as *());
pub fn debug_opaque<T>(x: T) {
rustrt::debug_opaque(sys::get_type_desc::<T>(), ptr::addr_of(&x) as *());
}
fn debug_box<T>(x: @T) {
rustrt::debug_box(sys::get_type_desc::<T>(), ptr::addr_of(x) as *());
pub fn debug_box<T>(x: @T) {
rustrt::debug_box(sys::get_type_desc::<T>(), ptr::addr_of(&x) as *());
}
fn debug_tag<T>(+x: T) {
rustrt::debug_tag(sys::get_type_desc::<T>(), ptr::addr_of(x) as *());
pub fn debug_tag<T>(x: T) {
rustrt::debug_tag(sys::get_type_desc::<T>(), ptr::addr_of(&x) as *());
}
fn debug_fn<T>(+x: T) {
rustrt::debug_fn(sys::get_type_desc::<T>(), ptr::addr_of(x) as *());
pub fn debug_fn<T>(x: T) {
rustrt::debug_fn(sys::get_type_desc::<T>(), ptr::addr_of(&x) as *());
}
unsafe fn ptr_cast<T, U>(x: @T) -> @U {
pub unsafe fn ptr_cast<T, U>(x: @T) -> @U {
reinterpret_cast(
&rustrt::debug_ptrcast(sys::get_type_desc::<T>(),
reinterpret_cast(&x)))
}
/// Triggers a debugger breakpoint
fn breakpoint() {
pub fn breakpoint() {
rustrt::rust_dbg_breakpoint();
}

View file

@ -1,16 +1,15 @@
//! A deque. Untested as of yet. Likely buggy
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
#[forbid(non_camel_case_types)];
use option::{Some, None};
use dvec::DVec;
use core::cmp::{Eq};
trait Deque<T> {
pub trait Deque<T> {
fn size() -> uint;
fn add_front(T);
fn add_back(T);
fn add_front(v: T);
fn add_back(v: T);
fn pop_front() -> T;
fn pop_back() -> T;
fn peek_front() -> T;
@ -20,7 +19,7 @@ trait Deque<T> {
// FIXME (#2343) eventually, a proper datatype plus an exported impl would
// be preferrable.
fn create<T: Copy>() -> Deque<T> {
pub fn create<T: Copy>() -> Deque<T> {
type Cell<T> = Option<T>;
let initial_capacity: uint = 32u; // 2^5
@ -28,7 +27,7 @@ fn create<T: Copy>() -> Deque<T> {
* Grow is only called on full elts, so nelts is also len(elts), unlike
* elsewhere.
*/
fn grow<T: Copy>(nelts: uint, lo: uint, +elts: ~[Cell<T>])
fn grow<T: Copy>(nelts: uint, lo: uint, elts: ~[Cell<T>])
-> ~[Cell<T>] {
let mut elts = move elts;
assert (nelts == vec::len(elts));
@ -38,15 +37,15 @@ fn create<T: Copy>() -> Deque<T> {
let nalloc = uint::next_power_of_two(nelts + 1u);
while i < nalloc {
if i < nelts {
vec::push(rv, elts[(lo + i) % nelts]);
} else { vec::push(rv, None); }
rv.push(elts[(lo + i) % nelts]);
} else { rv.push(None); }
i += 1u;
}
move rv
}
fn get<T: Copy>(elts: &DVec<Cell<T>>, i: uint) -> T {
match (*elts).get_elt(i) { Some(t) => t, _ => fail }
match (*elts).get_elt(i) { Some(move t) => t, _ => fail }
}
type Repr<T> = {mut nelts: uint,
@ -120,7 +119,6 @@ fn create<T: Copy>() -> Deque<T> {
#[cfg(test)]
mod tests {
#[legacy_exports];
#[test]
fn test_simple() {
let d: deque::Deque<int> = deque::create::<int>();
@ -202,7 +200,7 @@ mod tests {
assert (deq.get(3) == d);
}
fn test_parameterized<T: Copy Eq Owned>(+a: T, +b: T, +c: T, +d: T) {
fn test_parameterized<T: Copy Eq Owned>(a: T, +b: T, +c: T, +d: T) {
let deq: deque::Deque<T> = deque::create::<T>();
assert (deq.size() == 0u);
deq.add_front(a);

View file

@ -4,31 +4,6 @@
use core::Option;
use option::{Some, None};
export Doc;
export doc_at;
export maybe_get_doc;
export get_doc;
export docs;
export tagged_docs;
export doc_data;
export doc_as_str;
export doc_as_u8;
export doc_as_u16;
export doc_as_u32;
export doc_as_u64;
export doc_as_i8;
export doc_as_i16;
export doc_as_i32;
export doc_as_i64;
export Writer;
export serializer;
export ebml_deserializer;
export EbmlDeserializer;
export deserializer;
export with_doc_data;
export get_doc;
export extensions;
type EbmlTag = {id: uint, size: uint};
type EbmlState = {ebml_tag: EbmlTag, tag_pos: uint, data_pos: uint};
@ -37,12 +12,12 @@ type EbmlState = {ebml_tag: EbmlTag, tag_pos: uint, data_pos: uint};
// separate modules within this file.
// ebml reading
type Doc = {data: @~[u8], start: uint, end: uint};
pub type Doc = {data: @~[u8], start: uint, end: uint};
type TaggedDoc = {tag: uint, doc: Doc};
impl Doc: ops::Index<uint,Doc> {
pure fn index(&&tag: uint) -> Doc {
pure fn index(+tag: uint) -> Doc {
unsafe {
get_doc(self, tag)
}
@ -72,11 +47,11 @@ fn vuint_at(data: &[u8], start: uint) -> {val: uint, next: uint} {
} else { error!("vint too big"); fail; }
}
fn Doc(data: @~[u8]) -> Doc {
pub fn Doc(data: @~[u8]) -> Doc {
return {data: data, start: 0u, end: vec::len::<u8>(*data)};
}
fn doc_at(data: @~[u8], start: uint) -> TaggedDoc {
pub fn doc_at(data: @~[u8], start: uint) -> TaggedDoc {
let elt_tag = vuint_at(*data, start);
let elt_size = vuint_at(*data, elt_tag.next);
let end = elt_size.next + elt_size.val;
@ -84,7 +59,7 @@ fn doc_at(data: @~[u8], start: uint) -> TaggedDoc {
doc: {data: data, start: elt_size.next, end: end}};
}
fn maybe_get_doc(d: Doc, tg: uint) -> Option<Doc> {
pub fn maybe_get_doc(d: Doc, tg: uint) -> Option<Doc> {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
@ -101,7 +76,7 @@ fn maybe_get_doc(d: Doc, tg: uint) -> Option<Doc> {
return None::<Doc>;
}
fn get_doc(d: Doc, tg: uint) -> Doc {
pub fn get_doc(d: Doc, tg: uint) -> Doc {
match maybe_get_doc(d, tg) {
Some(d) => return d,
None => {
@ -111,7 +86,7 @@ fn get_doc(d: Doc, tg: uint) -> Doc {
}
}
fn docs(d: Doc, it: fn(uint, Doc) -> bool) {
pub fn docs(d: Doc, it: fn(uint, Doc) -> bool) {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
@ -123,7 +98,7 @@ fn docs(d: Doc, it: fn(uint, Doc) -> bool) {
}
}
fn tagged_docs(d: Doc, tg: uint, it: fn(Doc) -> bool) {
pub fn tagged_docs(d: Doc, tg: uint, it: fn(Doc) -> bool) {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
@ -137,43 +112,43 @@ fn tagged_docs(d: Doc, tg: uint, it: fn(Doc) -> bool) {
}
}
fn doc_data(d: Doc) -> ~[u8] { vec::slice::<u8>(*d.data, d.start, d.end) }
pub fn doc_data(d: Doc) -> ~[u8] { vec::slice::<u8>(*d.data, d.start, d.end) }
fn with_doc_data<T>(d: Doc, f: fn(x: &[u8]) -> T) -> T {
pub fn with_doc_data<T>(d: Doc, f: fn(x: &[u8]) -> T) -> T {
return f(vec::view(*d.data, d.start, d.end));
}
fn doc_as_str(d: Doc) -> ~str { return str::from_bytes(doc_data(d)); }
pub fn doc_as_str(d: Doc) -> ~str { return str::from_bytes(doc_data(d)); }
fn doc_as_u8(d: Doc) -> u8 {
pub fn doc_as_u8(d: Doc) -> u8 {
assert d.end == d.start + 1u;
return (*d.data)[d.start];
}
fn doc_as_u16(d: Doc) -> u16 {
pub fn doc_as_u16(d: Doc) -> u16 {
assert d.end == d.start + 2u;
return io::u64_from_be_bytes(*d.data, d.start, 2u) as u16;
}
fn doc_as_u32(d: Doc) -> u32 {
pub fn doc_as_u32(d: Doc) -> u32 {
assert d.end == d.start + 4u;
return io::u64_from_be_bytes(*d.data, d.start, 4u) as u32;
}
fn doc_as_u64(d: Doc) -> u64 {
pub fn doc_as_u64(d: Doc) -> u64 {
assert d.end == d.start + 8u;
return io::u64_from_be_bytes(*d.data, d.start, 8u);
}
fn doc_as_i8(d: Doc) -> i8 { doc_as_u8(d) as i8 }
fn doc_as_i16(d: Doc) -> i16 { doc_as_u16(d) as i16 }
fn doc_as_i32(d: Doc) -> i32 { doc_as_u32(d) as i32 }
fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 }
pub fn doc_as_i8(d: Doc) -> i8 { doc_as_u8(d) as i8 }
pub fn doc_as_i16(d: Doc) -> i16 { doc_as_u16(d) as i16 }
pub fn doc_as_i32(d: Doc) -> i32 { doc_as_u32(d) as i32 }
pub fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 }
// ebml writing
type Writer_ = {writer: io::Writer, mut size_positions: ~[uint]};
enum Writer {
pub enum Writer {
Writer_(Writer_)
}
@ -197,7 +172,7 @@ fn write_vuint(w: io::Writer, n: uint) {
fail fmt!("vint to write too big: %?", n);
}
fn Writer(w: io::Writer) -> Writer {
pub fn Writer(w: io::Writer) -> Writer {
let size_positions: ~[uint] = ~[];
return Writer_({writer: w, mut size_positions: size_positions});
}
@ -211,13 +186,13 @@ impl Writer {
write_vuint(self.writer, tag_id);
// Write a placeholder four-byte size.
vec::push(self.size_positions, self.writer.tell());
self.size_positions.push(self.writer.tell());
let zeroes: &[u8] = &[0u8, 0u8, 0u8, 0u8];
self.writer.write(zeroes);
}
fn end_tag() {
let last_size_pos = vec::pop::<uint>(self.size_positions);
let last_size_pos = self.size_positions.pop();
let cur_pos = self.writer.tell();
self.writer.seek(last_size_pos as int, io::SeekSet);
let size = (cur_pos - last_size_pos - 4u);
@ -292,7 +267,7 @@ impl Writer {
self.writer.write(b);
}
fn wr_str(s: ~str) {
fn wr_str(s: &str) {
debug!("Write str: %?", s);
self.writer.write(str::to_bytes(s));
}
@ -409,16 +384,16 @@ impl ebml::Writer: serialization::Serializer {
type EbmlDeserializer_ = {mut parent: ebml::Doc,
mut pos: uint};
enum EbmlDeserializer {
pub enum EbmlDeserializer {
EbmlDeserializer_(EbmlDeserializer_)
}
fn ebml_deserializer(d: ebml::Doc) -> EbmlDeserializer {
pub fn ebml_deserializer(d: ebml::Doc) -> EbmlDeserializer {
EbmlDeserializer_({mut parent: d, mut pos: d.start})
}
priv impl EbmlDeserializer {
fn _check_label(lbl: ~str) {
fn _check_label(lbl: &str) {
if self.pos < self.parent.end {
let {tag: r_tag, doc: r_doc} =
ebml::doc_at(self.parent.data, self.pos);
@ -516,7 +491,7 @@ impl EbmlDeserializer: serialization::Deserializer {
fn read_str() -> ~str { ebml::doc_as_str(self.next_doc(EsStr)) }
// Compound types:
fn read_enum<T>(name: ~str, f: fn() -> T) -> T {
fn read_enum<T>(name: &str, f: fn() -> T) -> T {
debug!("read_enum(%s)", name);
self._check_label(name);
self.push_doc(self.next_doc(EsEnum), f)
@ -565,7 +540,7 @@ impl EbmlDeserializer: serialization::Deserializer {
f()
}
fn read_rec_field<T>(f_name: ~str, f_idx: uint, f: fn() -> T) -> T {
fn read_rec_field<T>(f_name: &str, f_idx: uint, f: fn() -> T) -> T {
debug!("read_rec_field(%s, idx=%u)", f_name, f_idx);
self._check_label(f_name);
f()
@ -588,11 +563,11 @@ impl EbmlDeserializer: serialization::Deserializer {
#[test]
fn test_option_int() {
fn serialize_1<S: serialization::Serializer>(s: S, v: int) {
fn serialize_1<S: serialization::Serializer>(&&s: S, v: int) {
s.emit_i64(v as i64);
}
fn serialize_0<S: serialization::Serializer>(s: S, v: Option<int>) {
fn serialize_0<S: serialization::Serializer>(&&s: S, v: Option<int>) {
do s.emit_enum(~"core::option::t") {
match v {
None => s.emit_enum_variant(
@ -606,11 +581,11 @@ fn test_option_int() {
}
}
fn deserialize_1<S: serialization::Deserializer>(s: S) -> int {
fn deserialize_1<S: serialization::Deserializer>(&&s: S) -> int {
s.read_i64() as int
}
fn deserialize_0<S: serialization::Deserializer>(s: S) -> Option<int> {
fn deserialize_0<S: serialization::Deserializer>(&&s: S) -> Option<int> {
do s.read_enum(~"core::option::t") {
do s.read_enum_variant |i| {
match i {

643
src/libstd/ebml2.rs Normal file
View file

@ -0,0 +1,643 @@
use serialization2;
// Simple Extensible Binary Markup Language (ebml) reader and writer on a
// cursor model. See the specification here:
// http://www.matroska.org/technical/specs/rfc/index.html
struct EbmlTag {
id: uint,
size: uint,
}
struct EbmlState {
ebml_tag: EbmlTag,
tag_pos: uint,
data_pos: uint,
}
// FIXME (#2739): When we have module renaming, make "reader" and "writer"
// separate modules within this file.
// ebml reading
struct Doc {
data: @~[u8],
start: uint,
end: uint,
}
struct TaggedDoc {
tag: uint,
doc: Doc,
}
impl Doc: ops::Index<uint,Doc> {
pure fn index(+tag: uint) -> Doc {
unsafe {
get_doc(self, tag)
}
}
}
fn vuint_at(data: &[u8], start: uint) -> {val: uint, next: uint} {
let a = data[start];
if a & 0x80u8 != 0u8 {
return {val: (a & 0x7fu8) as uint, next: start + 1u};
}
if a & 0x40u8 != 0u8 {
return {val: ((a & 0x3fu8) as uint) << 8u |
(data[start + 1u] as uint),
next: start + 2u};
} else if a & 0x20u8 != 0u8 {
return {val: ((a & 0x1fu8) as uint) << 16u |
(data[start + 1u] as uint) << 8u |
(data[start + 2u] as uint),
next: start + 3u};
} else if a & 0x10u8 != 0u8 {
return {val: ((a & 0x0fu8) as uint) << 24u |
(data[start + 1u] as uint) << 16u |
(data[start + 2u] as uint) << 8u |
(data[start + 3u] as uint),
next: start + 4u};
} else { error!("vint too big"); fail; }
}
pub fn Doc(data: @~[u8]) -> Doc {
Doc { data: data, start: 0u, end: vec::len::<u8>(*data) }
}
pub fn doc_at(data: @~[u8], start: uint) -> TaggedDoc {
let elt_tag = vuint_at(*data, start);
let elt_size = vuint_at(*data, elt_tag.next);
let end = elt_size.next + elt_size.val;
TaggedDoc {
tag: elt_tag.val,
doc: Doc { data: data, start: elt_size.next, end: end }
}
}
pub fn maybe_get_doc(d: Doc, tg: uint) -> Option<Doc> {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
let elt_size = vuint_at(*d.data, elt_tag.next);
pos = elt_size.next + elt_size.val;
if elt_tag.val == tg {
return Some(Doc { data: d.data, start: elt_size.next, end: pos });
}
}
None
}
pub fn get_doc(d: Doc, tg: uint) -> Doc {
match maybe_get_doc(d, tg) {
Some(d) => d,
None => {
error!("failed to find block with tag %u", tg);
fail;
}
}
}
pub fn docs(d: Doc, it: fn(uint, Doc) -> bool) {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
let elt_size = vuint_at(*d.data, elt_tag.next);
pos = elt_size.next + elt_size.val;
let doc = Doc { data: d.data, start: elt_size.next, end: pos };
if !it(elt_tag.val, doc) {
break;
}
}
}
pub fn tagged_docs(d: Doc, tg: uint, it: fn(Doc) -> bool) {
let mut pos = d.start;
while pos < d.end {
let elt_tag = vuint_at(*d.data, pos);
let elt_size = vuint_at(*d.data, elt_tag.next);
pos = elt_size.next + elt_size.val;
if elt_tag.val == tg {
let doc = Doc { data: d.data, start: elt_size.next, end: pos };
if !it(doc) {
break;
}
}
}
}
pub fn doc_data(d: Doc) -> ~[u8] { vec::slice::<u8>(*d.data, d.start, d.end) }
pub fn with_doc_data<T>(d: Doc, f: fn(x: &[u8]) -> T) -> T {
f(vec::view(*d.data, d.start, d.end))
}
pub fn doc_as_str(d: Doc) -> ~str { str::from_bytes(doc_data(d)) }
pub fn doc_as_u8(d: Doc) -> u8 {
assert d.end == d.start + 1u;
(*d.data)[d.start]
}
pub fn doc_as_u16(d: Doc) -> u16 {
assert d.end == d.start + 2u;
io::u64_from_be_bytes(*d.data, d.start, 2u) as u16
}
pub fn doc_as_u32(d: Doc) -> u32 {
assert d.end == d.start + 4u;
io::u64_from_be_bytes(*d.data, d.start, 4u) as u32
}
pub fn doc_as_u64(d: Doc) -> u64 {
assert d.end == d.start + 8u;
io::u64_from_be_bytes(*d.data, d.start, 8u)
}
pub fn doc_as_i8(d: Doc) -> i8 { doc_as_u8(d) as i8 }
pub fn doc_as_i16(d: Doc) -> i16 { doc_as_u16(d) as i16 }
pub fn doc_as_i32(d: Doc) -> i32 { doc_as_u32(d) as i32 }
pub fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 }
// ebml writing
struct Serializer {
writer: io::Writer,
priv mut size_positions: ~[uint],
}
fn write_sized_vuint(w: io::Writer, n: uint, size: uint) {
match size {
1u => w.write(&[0x80u8 | (n as u8)]),
2u => w.write(&[0x40u8 | ((n >> 8_u) as u8), n as u8]),
3u => w.write(&[0x20u8 | ((n >> 16_u) as u8), (n >> 8_u) as u8,
n as u8]),
4u => w.write(&[0x10u8 | ((n >> 24_u) as u8), (n >> 16_u) as u8,
(n >> 8_u) as u8, n as u8]),
_ => fail fmt!("vint to write too big: %?", n)
};
}
fn write_vuint(w: io::Writer, n: uint) {
if n < 0x7f_u { write_sized_vuint(w, n, 1u); return; }
if n < 0x4000_u { write_sized_vuint(w, n, 2u); return; }
if n < 0x200000_u { write_sized_vuint(w, n, 3u); return; }
if n < 0x10000000_u { write_sized_vuint(w, n, 4u); return; }
fail fmt!("vint to write too big: %?", n);
}
pub fn Serializer(w: io::Writer) -> Serializer {
let size_positions: ~[uint] = ~[];
Serializer { writer: w, mut size_positions: size_positions }
}
// FIXME (#2741): Provide a function to write the standard ebml header.
impl Serializer {
fn start_tag(tag_id: uint) {
debug!("Start tag %u", tag_id);
// Write the enum ID:
write_vuint(self.writer, tag_id);
// Write a placeholder four-byte size.
self.size_positions.push(self.writer.tell());
let zeroes: &[u8] = &[0u8, 0u8, 0u8, 0u8];
self.writer.write(zeroes);
}
fn end_tag() {
let last_size_pos = self.size_positions.pop();
let cur_pos = self.writer.tell();
self.writer.seek(last_size_pos as int, io::SeekSet);
let size = (cur_pos - last_size_pos - 4u);
write_sized_vuint(self.writer, size, 4u);
self.writer.seek(cur_pos as int, io::SeekSet);
debug!("End tag (size = %u)", size);
}
fn wr_tag(tag_id: uint, blk: fn()) {
self.start_tag(tag_id);
blk();
self.end_tag();
}
fn wr_tagged_bytes(tag_id: uint, b: &[u8]) {
write_vuint(self.writer, tag_id);
write_vuint(self.writer, vec::len(b));
self.writer.write(b);
}
fn wr_tagged_u64(tag_id: uint, v: u64) {
do io::u64_to_be_bytes(v, 8u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_u32(tag_id: uint, v: u32) {
do io::u64_to_be_bytes(v as u64, 4u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_u16(tag_id: uint, v: u16) {
do io::u64_to_be_bytes(v as u64, 2u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_u8(tag_id: uint, v: u8) {
self.wr_tagged_bytes(tag_id, &[v]);
}
fn wr_tagged_i64(tag_id: uint, v: i64) {
do io::u64_to_be_bytes(v as u64, 8u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_i32(tag_id: uint, v: i32) {
do io::u64_to_be_bytes(v as u64, 4u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_i16(tag_id: uint, v: i16) {
do io::u64_to_be_bytes(v as u64, 2u) |v| {
self.wr_tagged_bytes(tag_id, v);
}
}
fn wr_tagged_i8(tag_id: uint, v: i8) {
self.wr_tagged_bytes(tag_id, &[v as u8]);
}
fn wr_tagged_str(tag_id: uint, v: &str) {
str::byte_slice(v, |b| self.wr_tagged_bytes(tag_id, b));
}
fn wr_bytes(b: &[u8]) {
debug!("Write %u bytes", vec::len(b));
self.writer.write(b);
}
fn wr_str(s: &str) {
debug!("Write str: %?", s);
self.writer.write(str::to_bytes(s));
}
}
// FIXME (#2743): optionally perform "relaxations" on end_tag to more
// efficiently encode sizes; this is a fixed point iteration
// Set to true to generate more debugging in EBML serialization.
// Totally lame approach.
const debug: bool = false;
enum EbmlSerializerTag {
EsUint, EsU64, EsU32, EsU16, EsU8,
EsInt, EsI64, EsI32, EsI16, EsI8,
EsBool,
EsStr,
EsF64, EsF32, EsFloat,
EsEnum, EsEnumVid, EsEnumBody,
EsVec, EsVecLen, EsVecElt,
EsOpaque,
EsLabel // Used only when debugging
}
priv impl Serializer {
// used internally to emit things like the vector length and so on
fn _emit_tagged_uint(t: EbmlSerializerTag, v: uint) {
assert v <= 0xFFFF_FFFF_u;
self.wr_tagged_u32(t as uint, v as u32);
}
fn _emit_label(label: &str) {
// There are various strings that we have access to, such as
// the name of a record field, which do not actually appear in
// the serialized EBML (normally). This is just for
// efficiency. When debugging, though, we can emit such
// labels and then they will be checked by deserializer to
// try and check failures more quickly.
if debug { self.wr_tagged_str(EsLabel as uint, label) }
}
}
impl Serializer {
fn emit_opaque(&self, f: fn()) {
do self.wr_tag(EsOpaque as uint) {
f()
}
}
}
impl Serializer: serialization2::Serializer {
fn emit_nil(&self) {}
fn emit_uint(&self, v: uint) {
self.wr_tagged_u64(EsUint as uint, v as u64);
}
fn emit_u64(&self, v: u64) { self.wr_tagged_u64(EsU64 as uint, v); }
fn emit_u32(&self, v: u32) { self.wr_tagged_u32(EsU32 as uint, v); }
fn emit_u16(&self, v: u16) { self.wr_tagged_u16(EsU16 as uint, v); }
fn emit_u8(&self, v: u8) { self.wr_tagged_u8 (EsU8 as uint, v); }
fn emit_int(&self, v: int) {
self.wr_tagged_i64(EsInt as uint, v as i64);
}
fn emit_i64(&self, v: i64) { self.wr_tagged_i64(EsI64 as uint, v); }
fn emit_i32(&self, v: i32) { self.wr_tagged_i32(EsI32 as uint, v); }
fn emit_i16(&self, v: i16) { self.wr_tagged_i16(EsI16 as uint, v); }
fn emit_i8(&self, v: i8) { self.wr_tagged_i8 (EsI8 as uint, v); }
fn emit_bool(&self, v: bool) {
self.wr_tagged_u8(EsBool as uint, v as u8)
}
// FIXME (#2742): implement these
fn emit_f64(&self, _v: f64) { fail ~"Unimplemented: serializing an f64"; }
fn emit_f32(&self, _v: f32) { fail ~"Unimplemented: serializing an f32"; }
fn emit_float(&self, _v: float) {
fail ~"Unimplemented: serializing a float";
}
fn emit_char(&self, _v: char) {
fail ~"Unimplemented: serializing a char";
}
fn emit_borrowed_str(&self, v: &str) {
self.wr_tagged_str(EsStr as uint, v)
}
fn emit_owned_str(&self, v: &str) {
self.emit_borrowed_str(v)
}
fn emit_managed_str(&self, v: &str) {
self.emit_borrowed_str(v)
}
fn emit_borrowed(&self, f: fn()) { f() }
fn emit_owned(&self, f: fn()) { f() }
fn emit_managed(&self, f: fn()) { f() }
fn emit_enum(&self, name: &str, f: fn()) {
self._emit_label(name);
self.wr_tag(EsEnum as uint, f)
}
fn emit_enum_variant(&self, _v_name: &str, v_id: uint, _cnt: uint,
f: fn()) {
self._emit_tagged_uint(EsEnumVid, v_id);
self.wr_tag(EsEnumBody as uint, f)
}
fn emit_enum_variant_arg(&self, _idx: uint, f: fn()) { f() }
fn emit_borrowed_vec(&self, len: uint, f: fn()) {
do self.wr_tag(EsVec as uint) {
self._emit_tagged_uint(EsVecLen, len);
f()
}
}
fn emit_owned_vec(&self, len: uint, f: fn()) {
self.emit_borrowed_vec(len, f)
}
fn emit_managed_vec(&self, len: uint, f: fn()) {
self.emit_borrowed_vec(len, f)
}
fn emit_vec_elt(&self, _idx: uint, f: fn()) {
self.wr_tag(EsVecElt as uint, f)
}
fn emit_rec(&self, f: fn()) { f() }
fn emit_struct(&self, _name: &str, f: fn()) { f() }
fn emit_field(&self, name: &str, _idx: uint, f: fn()) {
self._emit_label(name);
f()
}
fn emit_tup(&self, _len: uint, f: fn()) { f() }
fn emit_tup_elt(&self, _idx: uint, f: fn()) { f() }
}
struct Deserializer {
priv mut parent: Doc,
priv mut pos: uint,
}
pub fn Deserializer(d: Doc) -> Deserializer {
Deserializer { mut parent: d, mut pos: d.start }
}
priv impl Deserializer {
fn _check_label(lbl: &str) {
if self.pos < self.parent.end {
let TaggedDoc { tag: r_tag, doc: r_doc } =
doc_at(self.parent.data, self.pos);
if r_tag == (EsLabel as uint) {
self.pos = r_doc.end;
let str = doc_as_str(r_doc);
if lbl != str {
fail fmt!("Expected label %s but found %s", lbl, str);
}
}
}
}
fn next_doc(exp_tag: EbmlSerializerTag) -> Doc {
debug!(". next_doc(exp_tag=%?)", exp_tag);
if self.pos >= self.parent.end {
fail ~"no more documents in current node!";
}
let TaggedDoc { tag: r_tag, doc: r_doc } =
doc_at(self.parent.data, self.pos);
debug!("self.parent=%?-%? self.pos=%? r_tag=%? r_doc=%?-%?",
copy self.parent.start, copy self.parent.end,
copy self.pos, r_tag, r_doc.start, r_doc.end);
if r_tag != (exp_tag as uint) {
fail fmt!("expected EMBL doc with tag %? but found tag %?",
exp_tag, r_tag);
}
if r_doc.end > self.parent.end {
fail fmt!("invalid EBML, child extends to 0x%x, parent to 0x%x",
r_doc.end, self.parent.end);
}
self.pos = r_doc.end;
r_doc
}
fn push_doc<T>(d: Doc, f: fn() -> T) -> T{
let old_parent = self.parent;
let old_pos = self.pos;
self.parent = d;
self.pos = d.start;
let r = f();
self.parent = old_parent;
self.pos = old_pos;
move r
}
fn _next_uint(exp_tag: EbmlSerializerTag) -> uint {
let r = doc_as_u32(self.next_doc(exp_tag));
debug!("_next_uint exp_tag=%? result=%?", exp_tag, r);
r as uint
}
}
impl Deserializer {
fn read_opaque<R>(&self, op: fn(Doc) -> R) -> R {
do self.push_doc(self.next_doc(EsOpaque)) {
op(copy self.parent)
}
}
}
impl Deserializer: serialization2::Deserializer {
fn read_nil(&self) -> () { () }
fn read_u64(&self) -> u64 { doc_as_u64(self.next_doc(EsU64)) }
fn read_u32(&self) -> u32 { doc_as_u32(self.next_doc(EsU32)) }
fn read_u16(&self) -> u16 { doc_as_u16(self.next_doc(EsU16)) }
fn read_u8 (&self) -> u8 { doc_as_u8 (self.next_doc(EsU8 )) }
fn read_uint(&self) -> uint {
let v = doc_as_u64(self.next_doc(EsUint));
if v > (core::uint::max_value as u64) {
fail fmt!("uint %? too large for this architecture", v);
}
v as uint
}
fn read_i64(&self) -> i64 { doc_as_u64(self.next_doc(EsI64)) as i64 }
fn read_i32(&self) -> i32 { doc_as_u32(self.next_doc(EsI32)) as i32 }
fn read_i16(&self) -> i16 { doc_as_u16(self.next_doc(EsI16)) as i16 }
fn read_i8 (&self) -> i8 { doc_as_u8 (self.next_doc(EsI8 )) as i8 }
fn read_int(&self) -> int {
let v = doc_as_u64(self.next_doc(EsInt)) as i64;
if v > (int::max_value as i64) || v < (int::min_value as i64) {
fail fmt!("int %? out of range for this architecture", v);
}
v as int
}
fn read_bool(&self) -> bool { doc_as_u8(self.next_doc(EsBool)) as bool }
fn read_f64(&self) -> f64 { fail ~"read_f64()"; }
fn read_f32(&self) -> f32 { fail ~"read_f32()"; }
fn read_float(&self) -> float { fail ~"read_float()"; }
fn read_char(&self) -> char { fail ~"read_char()"; }
fn read_owned_str(&self) -> ~str { doc_as_str(self.next_doc(EsStr)) }
fn read_managed_str(&self) -> @str { fail ~"read_managed_str()"; }
// Compound types:
fn read_owned<T>(&self, f: fn() -> T) -> T {
debug!("read_owned()");
f()
}
fn read_managed<T>(&self, f: fn() -> T) -> T {
debug!("read_managed()");
f()
}
fn read_enum<T>(&self, name: &str, f: fn() -> T) -> T {
debug!("read_enum(%s)", name);
self._check_label(name);
self.push_doc(self.next_doc(EsEnum), f)
}
fn read_enum_variant<T>(&self, f: fn(uint) -> T) -> T {
debug!("read_enum_variant()");
let idx = self._next_uint(EsEnumVid);
debug!(" idx=%u", idx);
do self.push_doc(self.next_doc(EsEnumBody)) {
f(idx)
}
}
fn read_enum_variant_arg<T>(&self, idx: uint, f: fn() -> T) -> T {
debug!("read_enum_variant_arg(idx=%u)", idx);
f()
}
fn read_owned_vec<T>(&self, f: fn(uint) -> T) -> T {
debug!("read_owned_vec()");
do self.push_doc(self.next_doc(EsVec)) {
let len = self._next_uint(EsVecLen);
debug!(" len=%u", len);
f(len)
}
}
fn read_managed_vec<T>(&self, f: fn(uint) -> T) -> T {
debug!("read_managed_vec()");
do self.push_doc(self.next_doc(EsVec)) {
let len = self._next_uint(EsVecLen);
debug!(" len=%u", len);
f(len)
}
}
fn read_vec_elt<T>(&self, idx: uint, f: fn() -> T) -> T {
debug!("read_vec_elt(idx=%u)", idx);
self.push_doc(self.next_doc(EsVecElt), f)
}
fn read_rec<T>(&self, f: fn() -> T) -> T {
debug!("read_rec()");
f()
}
fn read_struct<T>(&self, name: &str, f: fn() -> T) -> T {
debug!("read_struct(name=%s)", name);
f()
}
fn read_field<T>(&self, name: &str, idx: uint, f: fn() -> T) -> T {
debug!("read_field(name=%s, idx=%u)", name, idx);
self._check_label(name);
f()
}
fn read_tup<T>(&self, len: uint, f: fn() -> T) -> T {
debug!("read_tup(len=%u)", len);
f()
}
fn read_tup_elt<T>(&self, idx: uint, f: fn() -> T) -> T {
debug!("read_tup_elt(idx=%u)", idx);
f()
}
}
// ___________________________________________________________________________
// Testing
#[cfg(test)]
mod tests {
#[test]
fn test_option_int() {
fn test_v(v: Option<int>) {
debug!("v == %?", v);
let bytes = do io::with_bytes_writer |wr| {
let ebml_w = Serializer(wr);
v.serialize(&ebml_w)
};
let ebml_doc = Doc(@bytes);
let deser = Deserializer(ebml_doc);
let v1 = serialization2::deserialize(&deser);
debug!("v1 == %?", v1);
assert v == v1;
}
test_v(Some(22));
test_v(None);
test_v(Some(3));
}
}

View file

@ -1,5 +1,4 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
#[warn(deprecated_mode)];
/*!
* A functional key,value store that works on anything.
@ -16,13 +15,7 @@ use core::cmp::{Eq, Ord};
use option::{Some, None};
use option = option;
export Treemap;
export init;
export insert;
export find;
export traverse;
type Treemap<K, V> = @TreeNode<K, V>;
pub type Treemap<K, V> = @TreeNode<K, V>;
enum TreeNode<K, V> {
Empty,
@ -30,14 +23,14 @@ enum TreeNode<K, V> {
}
/// Create a treemap
fn init<K, V>() -> Treemap<K, V> { @Empty }
pub fn init<K, V>() -> Treemap<K, V> { @Empty }
/// Insert a value into the map
fn insert<K: Copy Eq Ord, V: Copy>(m: Treemap<K, V>, +k: K, +v: V)
pub fn insert<K: Copy Eq Ord, V: Copy>(m: Treemap<K, V>, +k: K, +v: V)
-> Treemap<K, V> {
@match m {
@Empty => Node(@k, @v, @Empty, @Empty),
@Node(@kk, vv, left, right) => {
@Node(@copy kk, vv, left, right) => {
if k < kk {
Node(@kk, vv, insert(left, k, v), right)
} else if k == kk {
@ -48,19 +41,19 @@ fn insert<K: Copy Eq Ord, V: Copy>(m: Treemap<K, V>, +k: K, +v: V)
}
/// Find a value based on the key
fn find<K: Eq Ord, V: Copy>(m: Treemap<K, V>, +k: K) -> Option<V> {
pub fn find<K: Eq Ord, V: Copy>(m: Treemap<K, V>, +k: K) -> Option<V> {
match *m {
Empty => None,
Node(@kk, @v, left, right) => {
if k == kk {
Node(@ref kk, @copy v, left, right) => {
if k == *kk {
Some(v)
} else if k < kk { find(left, move k) } else { find(right, move k) }
} else if k < *kk { find(left, move k) } else { find(right, move k) }
}
}
}
/// Visit all pairs in the map in order.
fn traverse<K, V: Copy>(m: Treemap<K, V>, f: fn(K, V)) {
pub fn traverse<K, V: Copy>(m: Treemap<K, V>, f: fn((&K), (&V))) {
match *m {
Empty => (),
/*
@ -68,11 +61,9 @@ fn traverse<K, V: Copy>(m: Treemap<K, V>, f: fn(K, V)) {
matches to me, so I changed it. but that may be a
de-optimization -- tjc
*/
Node(@k, @v, left, right) => {
// copy v to make aliases work out
let v1 = v;
Node(@ref k, @ref v, left, right) => {
traverse(left, f);
f(k, v1);
f(k, v);
traverse(right, f);
}
}

View file

@ -62,31 +62,12 @@
* }
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use core::cmp::Eq;
use core::result::{Err, Ok};
use core::option;
use core::option::{Some, None};
export Opt;
export reqopt;
export optopt;
export optflag;
export optflagopt;
export optmulti;
export getopts;
export Matches;
export Fail_;
export fail_str;
export opt_present;
export opts_present;
export opt_str;
export opts_str;
export opt_strs;
export opt_maybe_str;
export opt_default;
export Result; //NDM
enum Name {
Long(~str),
@ -98,7 +79,7 @@ enum HasArg { Yes, No, Maybe, }
enum Occur { Req, Optional, Multi, }
/// A description of a possible option
type Opt = {name: Name, hasarg: HasArg, occur: Occur};
pub type Opt = {name: Name, hasarg: HasArg, occur: Occur};
fn mkname(nm: &str) -> Name {
let unm = str::from_slice(nm);
@ -110,9 +91,9 @@ fn mkname(nm: &str) -> Name {
impl Name : Eq {
pure fn eq(other: &Name) -> bool {
match self {
Long(e0a) => {
Long(ref e0a) => {
match (*other) {
Long(e0b) => e0a == e0b,
Long(ref e0b) => e0a == e0b,
_ => false
}
}
@ -135,22 +116,22 @@ impl Occur : Eq {
}
/// Create an option that is required and takes an argument
fn reqopt(name: &str) -> Opt {
pub fn reqopt(name: &str) -> Opt {
return {name: mkname(name), hasarg: Yes, occur: Req};
}
/// Create an option that is optional and takes an argument
fn optopt(name: &str) -> Opt {
pub fn optopt(name: &str) -> Opt {
return {name: mkname(name), hasarg: Yes, occur: Optional};
}
/// Create an option that is optional and does not take an argument
fn optflag(name: &str) -> Opt {
pub fn optflag(name: &str) -> Opt {
return {name: mkname(name), hasarg: No, occur: Optional};
}
/// Create an option that is optional and takes an optional argument
fn optflagopt(name: &str) -> Opt {
pub fn optflagopt(name: &str) -> Opt {
return {name: mkname(name), hasarg: Maybe, occur: Optional};
}
@ -158,7 +139,7 @@ fn optflagopt(name: &str) -> Opt {
* Create an option that is optional, takes an argument, and may occur
* multiple times
*/
fn optmulti(name: &str) -> Opt {
pub fn optmulti(name: &str) -> Opt {
return {name: mkname(name), hasarg: Yes, occur: Multi};
}
@ -168,7 +149,7 @@ enum Optval { Val(~str), Given, }
* The result of checking command line arguments. Contains a vector
* of matches and a vector of free strings.
*/
type Matches = {opts: ~[Opt], vals: ~[~[Optval]], free: ~[~str]};
pub type Matches = {opts: ~[Opt], vals: ~[~[Optval]], free: ~[~str]};
fn is_arg(arg: &str) -> bool {
return str::len(arg) > 1u && arg[0] == '-' as u8;
@ -177,7 +158,7 @@ fn is_arg(arg: &str) -> bool {
fn name_str(nm: &Name) -> ~str {
return match *nm {
Short(ch) => str::from_char(ch),
Long(s) => s
Long(copy s) => s
};
}
@ -189,7 +170,7 @@ fn find_opt(opts: &[Opt], +nm: Name) -> Option<uint> {
* The type returned when the command line does not conform to the
* expected format. Pass this value to <fail_str> to get an error message.
*/
enum Fail_ {
pub enum Fail_ {
ArgumentMissing(~str),
UnrecognizedOption(~str),
OptionMissing(~str),
@ -198,15 +179,23 @@ enum Fail_ {
}
/// Convert a `fail_` enum into an error string
fn fail_str(+f: Fail_) -> ~str {
pub fn fail_str(f: Fail_) -> ~str {
return match f {
ArgumentMissing(nm) => ~"Argument to option '" + nm + ~"' missing.",
UnrecognizedOption(nm) => ~"Unrecognized option: '" + nm + ~"'.",
OptionMissing(nm) => ~"Required option '" + nm + ~"' missing.",
OptionDuplicated(nm) => ~"Option '" + nm + ~"' given more than once.",
UnexpectedArgument(nm) => {
~"Option " + nm + ~" does not take an argument."
}
ArgumentMissing(ref nm) => {
~"Argument to option '" + *nm + ~"' missing."
}
UnrecognizedOption(ref nm) => {
~"Unrecognized option: '" + *nm + ~"'."
}
OptionMissing(ref nm) => {
~"Required option '" + *nm + ~"' missing."
}
OptionDuplicated(ref nm) => {
~"Option '" + *nm + ~"' given more than once."
}
UnexpectedArgument(ref nm) => {
~"Option " + *nm + ~" does not take an argument."
}
};
}
@ -214,7 +203,7 @@ fn fail_str(+f: Fail_) -> ~str {
* The result of parsing a command line with a set of options
* (result::t<Matches, Fail_>)
*/
type Result = result::Result<Matches, Fail_>;
pub type Result = result::Result<Matches, Fail_>;
/**
* Parse command line arguments according to the provided options
@ -223,9 +212,9 @@ type Result = result::Result<Matches, Fail_>;
* `opt_str`, etc. to interrogate results. Returns `err(Fail_)` on failure.
* Use <fail_str> to get an error message.
*/
fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
pub fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
let n_opts = vec::len::<Opt>(opts);
fn f(_x: uint) -> ~[Optval] { return ~[]; }
fn f(+_x: uint) -> ~[Optval] { return ~[]; }
let vals = vec::to_mut(vec::from_fn(n_opts, f));
let mut free: ~[~str] = ~[];
let l = vec::len(args);
@ -234,10 +223,10 @@ fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
let cur = args[i];
let curlen = str::len(cur);
if !is_arg(cur) {
vec::push(free, cur);
free.push(cur);
} else if cur == ~"--" {
let mut j = i + 1u;
while j < l { vec::push(free, args[j]); j += 1u; }
while j < l { free.push(args[j]); j += 1u; }
break;
} else {
let mut names;
@ -287,7 +276,7 @@ fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
}
}
}
vec::push(names, opt);
names.push(opt);
j = range.next;
}
}
@ -303,23 +292,22 @@ fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
if !i_arg.is_none() {
return Err(UnexpectedArgument(name_str(nm)));
}
vec::push(vals[optid], Given);
vals[optid].push(Given);
}
Maybe => {
if !i_arg.is_none() {
vec::push(vals[optid], Val(i_arg.get()));
vals[optid].push(Val(i_arg.get()));
} else if name_pos < vec::len::<Name>(names) ||
i + 1u == l || is_arg(args[i + 1u]) {
vec::push(vals[optid], Given);
} else { i += 1u; vec::push(vals[optid], Val(args[i])); }
vals[optid].push(Given);
} else { i += 1u; vals[optid].push(Val(args[i])); }
}
Yes => {
if !i_arg.is_none() {
vec::push(vals[optid],
Val(i_arg.get()));
vals[optid].push(Val(i_arg.get()));
} else if i + 1u == l {
return Err(ArgumentMissing(name_str(nm)));
} else { i += 1u; vec::push(vals[optid], Val(args[i])); }
} else { i += 1u; vals[optid].push(Val(args[i])); }
}
}
}
@ -347,7 +335,7 @@ fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
free: free});
}
fn opt_vals(+mm: Matches, nm: &str) -> ~[Optval] {
fn opt_vals(mm: Matches, nm: &str) -> ~[Optval] {
return match find_opt(mm.opts, mkname(nm)) {
Some(id) => mm.vals[id],
None => {
@ -357,15 +345,15 @@ fn opt_vals(+mm: Matches, nm: &str) -> ~[Optval] {
};
}
fn opt_val(+mm: Matches, nm: &str) -> Optval { return opt_vals(mm, nm)[0]; }
fn opt_val(mm: Matches, nm: &str) -> Optval { return opt_vals(mm, nm)[0]; }
/// Returns true if an option was matched
fn opt_present(+mm: Matches, nm: &str) -> bool {
pub fn opt_present(mm: Matches, nm: &str) -> bool {
return vec::len::<Optval>(opt_vals(mm, nm)) > 0u;
}
/// Returns true if any of several options were matched
fn opts_present(+mm: Matches, names: &[~str]) -> bool {
pub fn opts_present(mm: Matches, names: &[~str]) -> bool {
for vec::each(names) |nm| {
match find_opt(mm.opts, mkname(*nm)) {
Some(_) => return true,
@ -382,8 +370,8 @@ fn opts_present(+mm: Matches, names: &[~str]) -> bool {
* Fails if the option was not matched or if the match did not take an
* argument
*/
fn opt_str(+mm: Matches, nm: &str) -> ~str {
return match opt_val(mm, nm) { Val(s) => s, _ => fail };
pub fn opt_str(mm: Matches, nm: &str) -> ~str {
return match opt_val(mm, nm) { Val(copy s) => s, _ => fail };
}
/**
@ -392,10 +380,10 @@ fn opt_str(+mm: Matches, nm: &str) -> ~str {
* Fails if the no option was provided from the given list, or if the no such
* option took an argument
*/
fn opts_str(+mm: Matches, names: &[~str]) -> ~str {
pub fn opts_str(mm: Matches, names: &[~str]) -> ~str {
for vec::each(names) |nm| {
match opt_val(mm, *nm) {
Val(s) => return s,
Val(copy s) => return s,
_ => ()
}
}
@ -409,19 +397,22 @@ fn opts_str(+mm: Matches, names: &[~str]) -> ~str {
*
* Used when an option accepts multiple values.
*/
fn opt_strs(+mm: Matches, nm: &str) -> ~[~str] {
pub fn opt_strs(mm: Matches, nm: &str) -> ~[~str] {
let mut acc: ~[~str] = ~[];
for vec::each(opt_vals(mm, nm)) |v| {
match *v { Val(s) => vec::push(acc, s), _ => () }
match *v { Val(copy s) => acc.push(s), _ => () }
}
return acc;
}
/// Returns the string argument supplied to a matching option or none
fn opt_maybe_str(+mm: Matches, nm: &str) -> Option<~str> {
pub fn opt_maybe_str(mm: Matches, nm: &str) -> Option<~str> {
let vals = opt_vals(mm, nm);
if vec::len::<Optval>(vals) == 0u { return None::<~str>; }
return match vals[0] { Val(s) => Some::<~str>(s), _ => None::<~str> };
return match vals[0] {
Val(copy s) => Some(s),
_ => None
};
}
@ -432,10 +423,10 @@ fn opt_maybe_str(+mm: Matches, nm: &str) -> Option<~str> {
* present but no argument was provided, and the argument if the option was
* present and an argument was provided.
*/
fn opt_default(+mm: Matches, nm: &str, def: &str) -> Option<~str> {
pub fn opt_default(mm: Matches, nm: &str, def: &str) -> Option<~str> {
let vals = opt_vals(mm, nm);
if vec::len::<Optval>(vals) == 0u { return None::<~str>; }
return match vals[0] { Val(s) => Some::<~str>(s),
return match vals[0] { Val(copy s) => Some::<~str>(s),
_ => Some::<~str>(str::from_slice(def)) }
}
@ -460,7 +451,7 @@ mod tests {
use opt = getopts;
use result::{Err, Ok};
fn check_fail_type(+f: Fail_, ft: FailType) {
fn check_fail_type(f: Fail_, ft: FailType) {
match f {
ArgumentMissing(_) => assert ft == ArgumentMissing_,
UnrecognizedOption(_) => assert ft == UnrecognizedOption_,
@ -478,7 +469,7 @@ mod tests {
let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20");
}
@ -492,7 +483,7 @@ mod tests {
let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionMissing_),
Err(copy f) => check_fail_type(f, OptionMissing_),
_ => fail
}
}
@ -503,7 +494,7 @@ mod tests {
let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -514,7 +505,7 @@ mod tests {
let opts = ~[reqopt(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -525,7 +516,7 @@ mod tests {
let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20");
}
@ -539,7 +530,7 @@ mod tests {
let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionMissing_),
Err(copy f) => check_fail_type(f, OptionMissing_),
_ => fail
}
}
@ -550,7 +541,7 @@ mod tests {
let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -561,7 +552,7 @@ mod tests {
let opts = ~[reqopt(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -574,7 +565,7 @@ mod tests {
let opts = ~[optopt(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20");
}
@ -588,7 +579,7 @@ mod tests {
let opts = ~[optopt(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"test")),
Ok(copy m) => assert (!opt_present(m, ~"test")),
_ => fail
}
}
@ -599,7 +590,7 @@ mod tests {
let opts = ~[optopt(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -610,7 +601,7 @@ mod tests {
let opts = ~[optopt(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -621,7 +612,7 @@ mod tests {
let opts = ~[optopt(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20");
}
@ -635,7 +626,7 @@ mod tests {
let opts = ~[optopt(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"t")),
Ok(copy m) => assert (!opt_present(m, ~"t")),
_ => fail
}
}
@ -646,7 +637,7 @@ mod tests {
let opts = ~[optopt(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -657,7 +648,7 @@ mod tests {
let opts = ~[optopt(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -670,7 +661,7 @@ mod tests {
let opts = ~[optflag(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (opt_present(m, ~"test")),
Ok(copy m) => assert (opt_present(m, ~"test")),
_ => fail
}
}
@ -681,7 +672,7 @@ mod tests {
let opts = ~[optflag(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"test")),
Ok(copy m) => assert (!opt_present(m, ~"test")),
_ => fail
}
}
@ -692,7 +683,7 @@ mod tests {
let opts = ~[optflag(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => {
Err(copy f) => {
log(error, fail_str(f));
check_fail_type(f, UnexpectedArgument_);
}
@ -706,7 +697,7 @@ mod tests {
let opts = ~[optflag(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -717,7 +708,7 @@ mod tests {
let opts = ~[optflag(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (opt_present(m, ~"t")),
Ok(copy m) => assert (opt_present(m, ~"t")),
_ => fail
}
}
@ -728,7 +719,7 @@ mod tests {
let opts = ~[optflag(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"t")),
Ok(copy m) => assert (!opt_present(m, ~"t")),
_ => fail
}
}
@ -739,7 +730,7 @@ mod tests {
let opts = ~[optflag(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(ref m) => {
// The next variable after the flag is just a free argument
assert (m.free[0] == ~"20");
@ -754,7 +745,7 @@ mod tests {
let opts = ~[optflag(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
Err(copy f) => check_fail_type(f, OptionDuplicated_),
_ => fail
}
}
@ -767,7 +758,7 @@ mod tests {
let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20");
}
@ -781,7 +772,7 @@ mod tests {
let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"test")),
Ok(copy m) => assert (!opt_present(m, ~"test")),
_ => fail
}
}
@ -792,7 +783,7 @@ mod tests {
let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -803,7 +794,7 @@ mod tests {
let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"test"));
assert (opt_str(m, ~"test") == ~"20");
let pair = opt_strs(m, ~"test");
@ -820,7 +811,7 @@ mod tests {
let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20");
}
@ -834,7 +825,7 @@ mod tests {
let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => assert (!opt_present(m, ~"t")),
Ok(copy m) => assert (!opt_present(m, ~"t")),
_ => fail
}
}
@ -845,7 +836,7 @@ mod tests {
let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
Err(copy f) => check_fail_type(f, ArgumentMissing_),
_ => fail
}
}
@ -856,7 +847,7 @@ mod tests {
let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (opt_present(m, ~"t"));
assert (opt_str(m, ~"t") == ~"20");
let pair = opt_strs(m, ~"t");
@ -873,7 +864,7 @@ mod tests {
let opts = ~[optmulti(~"t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, UnrecognizedOption_),
Err(copy f) => check_fail_type(f, UnrecognizedOption_),
_ => fail
}
}
@ -884,7 +875,7 @@ mod tests {
let opts = ~[optmulti(~"test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, UnrecognizedOption_),
Err(copy f) => check_fail_type(f, UnrecognizedOption_),
_ => fail
}
}
@ -901,7 +892,7 @@ mod tests {
optopt(~"notpresent")];
let rs = getopts(args, opts);
match rs {
Ok(m) => {
Ok(copy m) => {
assert (m.free[0] == ~"prog");
assert (m.free[1] == ~"free1");
assert (opt_str(m, ~"s") == ~"20");
@ -926,8 +917,8 @@ mod tests {
let args = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"];
let opts = ~[optopt(~"e"), optopt(~"encrypt")];
let matches = match getopts(args, opts) {
result::Ok(m) => m,
result::Err(_f) => fail
result::Ok(move m) => m,
result::Err(_) => fail
};
assert opts_present(matches, ~[~"e"]);
assert opts_present(matches, ~[~"encrypt"]);
@ -947,8 +938,8 @@ mod tests {
let args = ~[~"-Lfoo"];
let opts = ~[optmulti(~"L")];
let matches = match getopts(args, opts) {
result::Ok(m) => m,
result::Err(_f) => fail
result::Ok(move m) => m,
result::Err(_) => fail
};
assert opts_present(matches, ~[~"L"]);
assert opts_str(matches, ~[~"L"]) == ~"foo";

File diff suppressed because it is too large Load diff

View file

@ -1,20 +1,19 @@
//! A standard linked list
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
#[warn(deprecated_mode)];
use core::cmp::Eq;
use core::option;
use option::*;
use option::{Some, None};
enum List<T> {
pub enum List<T> {
Cons(T, @List<T>),
Nil,
}
/// Cregate a list from a vector
fn from_vec<T: Copy>(v: &[T]) -> @List<T> {
vec::foldr(v, @Nil::<T>, |h, t| @Cons(h, t))
pub fn from_vec<T: Copy>(v: &[T]) -> @List<T> {
vec::foldr(v, @Nil::<T>, |h, t| @Cons(*h, t))
}
/**
@ -30,9 +29,9 @@ fn from_vec<T: Copy>(v: &[T]) -> @List<T> {
* * z - The initial value
* * f - The function to apply
*/
fn foldl<T: Copy, U>(+z: T, ls: @List<U>, f: fn((&T), (&U)) -> T) -> T {
pub fn foldl<T: Copy, U>(z: T, ls: @List<U>, f: fn((&T), (&U)) -> T) -> T {
let mut accum: T = z;
do iter(ls) |elt| { accum = f(&accum, &elt);}
do iter(ls) |elt| { accum = f(&accum, elt);}
accum
}
@ -43,12 +42,12 @@ fn foldl<T: Copy, U>(+z: T, ls: @List<U>, f: fn((&T), (&U)) -> T) -> T {
* When function `f` returns true then an option containing the element
* is returned. If `f` matches no elements then none is returned.
*/
fn find<T: Copy>(ls: @List<T>, f: fn((&T)) -> bool) -> Option<T> {
pub fn find<T: Copy>(ls: @List<T>, f: fn((&T)) -> bool) -> Option<T> {
let mut ls = ls;
loop {
ls = match *ls {
Cons(hd, tl) => {
if f(&hd) { return Some(hd); }
Cons(ref hd, tl) => {
if f(hd) { return Some(*hd); }
tl
}
Nil => return None
@ -57,15 +56,15 @@ fn find<T: Copy>(ls: @List<T>, f: fn((&T)) -> bool) -> Option<T> {
}
/// Returns true if a list contains an element with the given value
fn has<T: Copy Eq>(ls: @List<T>, +elt: T) -> bool {
pub fn has<T: Copy Eq>(ls: @List<T>, +elt: T) -> bool {
for each(ls) |e| {
if e == elt { return true; }
if *e == elt { return true; }
}
return false;
}
/// Returns true if the list is empty
pure fn is_empty<T: Copy>(ls: @List<T>) -> bool {
pub pure fn is_empty<T: Copy>(ls: @List<T>) -> bool {
match *ls {
Nil => true,
_ => false
@ -73,19 +72,19 @@ pure fn is_empty<T: Copy>(ls: @List<T>) -> bool {
}
/// Returns true if the list is not empty
pure fn is_not_empty<T: Copy>(ls: @List<T>) -> bool {
pub pure fn is_not_empty<T: Copy>(ls: @List<T>) -> bool {
return !is_empty(ls);
}
/// Returns the length of a list
fn len<T>(ls: @List<T>) -> uint {
pub fn len<T>(ls: @List<T>) -> uint {
let mut count = 0u;
iter(ls, |_e| count += 1u);
count
}
/// Returns all but the first element of a list
pure fn tail<T: Copy>(ls: @List<T>) -> @List<T> {
pub pure fn tail<T: Copy>(ls: @List<T>) -> @List<T> {
match *ls {
Cons(_, tl) => return tl,
Nil => fail ~"list empty"
@ -93,19 +92,19 @@ pure fn tail<T: Copy>(ls: @List<T>) -> @List<T> {
}
/// Returns the first element of a list
pure fn head<T: Copy>(ls: @List<T>) -> T {
pub pure fn head<T: Copy>(ls: @List<T>) -> T {
match *ls {
Cons(hd, _) => hd,
Cons(copy hd, _) => hd,
// makes me sad
_ => fail ~"head invoked on empty list"
}
}
/// Appends one list to another
pure fn append<T: Copy>(l: @List<T>, m: @List<T>) -> @List<T> {
pub pure fn append<T: Copy>(l: @List<T>, m: @List<T>) -> @List<T> {
match *l {
Nil => return m,
Cons(x, xs) => {
Cons(copy x, xs) => {
let rest = append(xs, m);
return @Cons(x, rest);
}
@ -121,11 +120,11 @@ pure fn push<T: Copy>(ll: &mut @list<T>, +vv: T) {
*/
/// Iterate over a list
fn iter<T>(l: @List<T>, f: fn(T)) {
pub fn iter<T>(l: @List<T>, f: fn((&T))) {
let mut cur = l;
loop {
cur = match *cur {
Cons(hd, tl) => {
Cons(ref hd, tl) => {
f(hd);
tl
}
@ -135,11 +134,11 @@ fn iter<T>(l: @List<T>, f: fn(T)) {
}
/// Iterate over a list
fn each<T>(l: @List<T>, f: fn(T) -> bool) {
pub fn each<T>(l: @List<T>, f: fn((&T)) -> bool) {
let mut cur = l;
loop {
cur = match *cur {
Cons(hd, tl) => {
Cons(ref hd, tl) => {
if !f(hd) { return; }
tl
}
@ -151,9 +150,9 @@ fn each<T>(l: @List<T>, f: fn(T) -> bool) {
impl<T:Eq> List<T> : Eq {
pure fn eq(other: &List<T>) -> bool {
match self {
Cons(e0a, e1a) => {
Cons(ref e0a, e1a) => {
match (*other) {
Cons(e0b, e1b) => e0a == e0b && e1a == e1b,
Cons(ref e0b, e1b) => e0a == e0b && e1a == e1b,
_ => false
}
}

View file

@ -1,7 +1,6 @@
//! A map type
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use io::WriterUtil;
use to_str::ToStr;
@ -12,16 +11,12 @@ use core::cmp::Eq;
use hash::Hash;
use to_bytes::IterBytes;
export HashMap, hashfn, eqfn, Set, Map, chained, set_add;
export hash_from_vec;
export vec_from_set;
/// A convenience type to treat a hashmap as a set
type Set<K:Eq IterBytes Hash> = HashMap<K, ()>;
pub type Set<K:Eq IterBytes Hash> = HashMap<K, ()>;
type HashMap<K:Eq IterBytes Hash, V> = chained::T<K, V>;
pub type HashMap<K:Eq IterBytes Hash, V> = chained::T<K, V>;
trait Map<K:Eq IterBytes Hash Copy, V: Copy> {
pub trait Map<K:Eq IterBytes Hash Copy, V: Copy> {
/// Return the number of elements in the map
pure fn size() -> uint;
@ -33,10 +28,10 @@ trait Map<K:Eq IterBytes Hash Copy, V: Copy> {
*
* Returns true if the key did not already exist in the map
*/
fn insert(+v: K, +v: V) -> bool;
fn insert(v: K, +v: V) -> bool;
/// Returns true if the map contains a value for the specified key
fn contains_key(+key: K) -> bool;
fn contains_key(key: K) -> bool;
/// Returns true if the map contains a value for the specified
/// key, taking the key by reference.
@ -46,31 +41,31 @@ trait Map<K:Eq IterBytes Hash Copy, V: Copy> {
* Get the value for the specified key. Fails if the key does not exist in
* the map.
*/
fn get(+key: K) -> V;
fn get(key: K) -> V;
/**
* Get the value for the specified key. If the key does not exist in
* the map then returns none.
*/
pure fn find(+key: K) -> Option<V>;
pure fn find(key: K) -> Option<V>;
/**
* Remove and return a value from the map. Returns true if the
* key was present in the map, otherwise false.
*/
fn remove(+key: K) -> bool;
fn remove(key: K) -> bool;
/// Clear the map, removing all key/value pairs.
fn clear();
/// Iterate over all the key/value pairs in the map by value
pure fn each(fn(+key: K, +value: V) -> bool);
pure fn each(fn(key: K, +value: V) -> bool);
/// Iterate over all the keys in the map by value
pure fn each_key(fn(+key: K) -> bool);
pure fn each_key(fn(key: K) -> bool);
/// Iterate over all the values in the map by value
pure fn each_value(fn(+value: V) -> bool);
pure fn each_value(fn(value: V) -> bool);
/// Iterate over all the key/value pairs in the map by reference
pure fn each_ref(fn(key: &K, value: &V) -> bool);
@ -83,10 +78,9 @@ trait Map<K:Eq IterBytes Hash Copy, V: Copy> {
}
mod util {
#[legacy_exports];
type Rational = {num: int, den: int}; // : int::positive(*.den);
pub type Rational = {num: int, den: int}; // : int::positive(*.den);
pure fn rational_leq(x: Rational, y: Rational) -> bool {
pub pure fn rational_leq(x: Rational, y: Rational) -> bool {
// NB: Uses the fact that rationals have positive denominators WLOG:
x.num * y.den <= y.num * x.den
@ -96,9 +90,7 @@ mod util {
// FIXME (#2344): package this up and export it as a datatype usable for
// external code that doesn't want to pay the cost of a box.
mod chained {
#[legacy_exports];
export T, mk, HashMap;
pub mod chained {
const initial_capacity: uint = 32u; // 2^5
@ -114,7 +106,7 @@ mod chained {
mut chains: ~[mut Option<@Entry<K,V>>]
}
type T<K:Eq IterBytes Hash, V> = @HashMap_<K, V>;
pub type T<K:Eq IterBytes Hash, V> = @HashMap_<K, V>;
enum SearchResult<K, V> {
NotFound,
@ -209,7 +201,7 @@ mod chained {
impl<K:Eq IterBytes Hash Copy, V: Copy> T<K, V>: Map<K, V> {
pure fn size() -> uint { self.count }
fn contains_key(+k: K) -> bool {
fn contains_key(k: K) -> bool {
self.contains_key_ref(&k)
}
@ -221,7 +213,7 @@ mod chained {
}
}
fn insert(+k: K, +v: V) -> bool {
fn insert(k: K, +v: V) -> bool {
let hash = k.hash_keyed(0,0) as uint;
match self.search_tbl(&k, hash) {
NotFound => {
@ -263,7 +255,7 @@ mod chained {
}
}
pure fn find(+k: K) -> Option<V> {
pure fn find(k: K) -> Option<V> {
unsafe {
match self.search_tbl(&k, k.hash_keyed(0,0) as uint) {
NotFound => None,
@ -273,7 +265,7 @@ mod chained {
}
}
fn get(+k: K) -> V {
fn get(k: K) -> V {
let opt_v = self.find(k);
if opt_v.is_none() {
fail fmt!("Key not found in table: %?", k);
@ -281,7 +273,7 @@ mod chained {
option::unwrap(move opt_v)
}
fn remove(+k: K) -> bool {
fn remove(k: K) -> bool {
match self.search_tbl(&k, k.hash_keyed(0,0) as uint) {
NotFound => false,
FoundFirst(idx, entry) => {
@ -302,15 +294,15 @@ mod chained {
self.chains = chains(initial_capacity);
}
pure fn each(blk: fn(+key: K, +value: V) -> bool) {
pure fn each(blk: fn(key: K, +value: V) -> bool) {
self.each_ref(|k, v| blk(*k, *v))
}
pure fn each_key(blk: fn(+key: K) -> bool) {
pure fn each_key(blk: fn(key: K) -> bool) {
self.each_key_ref(|p| blk(*p))
}
pure fn each_value(blk: fn(+value: V) -> bool) {
pure fn each_value(blk: fn(value: V) -> bool) {
self.each_value_ref(|p| blk(*p))
}
@ -356,7 +348,7 @@ mod chained {
}
impl<K:Eq IterBytes Hash Copy, V: Copy> T<K, V>: ops::Index<K, V> {
pure fn index(&&k: K) -> V {
pure fn index(+k: K) -> V {
unsafe {
self.get(k)
}
@ -367,7 +359,7 @@ mod chained {
vec::to_mut(vec::from_elem(nchains, None))
}
fn mk<K:Eq IterBytes Hash, V: Copy>() -> T<K,V> {
pub fn mk<K:Eq IterBytes Hash, V: Copy>() -> T<K,V> {
let slf: T<K, V> = @HashMap_ {count: 0u,
chains: chains(initial_capacity)};
slf
@ -379,18 +371,18 @@ Function: hashmap
Construct a hashmap.
*/
fn HashMap<K:Eq IterBytes Hash Const, V: Copy>()
pub fn HashMap<K:Eq IterBytes Hash Const, V: Copy>()
-> HashMap<K, V> {
chained::mk()
}
/// Convenience function for adding keys to a hashmap with nil type keys
fn set_add<K:Eq IterBytes Hash Const Copy>(set: Set<K>, +key: K) -> bool {
pub fn set_add<K:Eq IterBytes Hash Const Copy>(set: Set<K>, key: K) -> bool {
set.insert(key, ())
}
/// Convert a set into a vector.
fn vec_from_set<T:Eq IterBytes Hash Copy>(s: Set<T>) -> ~[T] {
pub fn vec_from_set<T:Eq IterBytes Hash Copy>(s: Set<T>) -> ~[T] {
do vec::build_sized(s.size()) |push| {
for s.each_key() |k| {
push(k);
@ -399,12 +391,12 @@ fn vec_from_set<T:Eq IterBytes Hash Copy>(s: Set<T>) -> ~[T] {
}
/// Construct a hashmap from a vector
fn hash_from_vec<K: Eq IterBytes Hash Const Copy, V: Copy>(
pub fn hash_from_vec<K: Eq IterBytes Hash Const Copy, V: Copy>(
items: &[(K, V)]) -> HashMap<K, V> {
let map = HashMap();
for vec::each(items) |item| {
match *item {
(key, value) => {
(copy key, copy value) => {
map.insert(key, value);
}
}
@ -423,13 +415,13 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
fn insert(+key: K, +value: V) -> bool {
fn insert(key: K, value: V) -> bool {
do self.borrow_mut |p| {
p.insert(key, value)
}
}
fn contains_key(+key: K) -> bool {
fn contains_key(key: K) -> bool {
do self.borrow_const |p| {
p.contains_key(&key)
}
@ -441,13 +433,13 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
fn get(+key: K) -> V {
fn get(key: K) -> V {
do self.borrow_const |p| {
p.get(&key)
}
}
pure fn find(+key: K) -> Option<V> {
pure fn find(key: K) -> Option<V> {
unsafe {
do self.borrow_const |p| {
p.find(&key)
@ -455,7 +447,7 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
fn remove(+key: K) -> bool {
fn remove(key: K) -> bool {
do self.borrow_mut |p| {
p.remove(&key)
}
@ -467,7 +459,7 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
pure fn each(op: fn(+key: K, +value: V) -> bool) {
pure fn each(op: fn(key: K, +value: V) -> bool) {
unsafe {
do self.borrow_imm |p| {
p.each(|k, v| op(*k, *v))
@ -475,7 +467,7 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
pure fn each_key(op: fn(+key: K) -> bool) {
pure fn each_key(op: fn(key: K) -> bool) {
unsafe {
do self.borrow_imm |p| {
p.each_key(|k| op(*k))
@ -483,7 +475,7 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
}
}
pure fn each_value(op: fn(+value: V) -> bool) {
pure fn each_value(op: fn(value: V) -> bool) {
unsafe {
do self.borrow_imm |p| {
p.each_value(|v| op(*v))
@ -518,7 +510,6 @@ impl<K: Eq IterBytes Hash Copy, V: Copy> @Mut<LinearMap<K, V>>:
#[cfg(test)]
mod tests {
#[legacy_exports];
#[test]
fn test_simple() {

View file

@ -1,7 +1,6 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
fn md4(msg: &[u8]) -> {a: u32, b: u32, c: u32, d: u32} {
pub fn md4(msg: &[u8]) -> {a: u32, b: u32, c: u32, d: u32} {
// subtle: if orig_len is merely uint, then the code below
// which performs shifts by 32 bits or more has undefined
// results.
@ -11,14 +10,14 @@ fn md4(msg: &[u8]) -> {a: u32, b: u32, c: u32, d: u32} {
let mut msg = vec::append(vec::from_slice(msg), ~[0x80u8]);
let mut bitlen = orig_len + 8u64;
while (bitlen + 64u64) % 512u64 > 0u64 {
vec::push(msg, 0u8);
msg.push(0u8);
bitlen += 8u64;
}
// append length
let mut i = 0u64;
while i < 8u64 {
vec::push(msg, (orig_len >> (i * 8u64)) as u8);
msg.push((orig_len >> (i * 8u64)) as u8);
i += 1u64;
}
@ -85,7 +84,7 @@ fn md4(msg: &[u8]) -> {a: u32, b: u32, c: u32, d: u32} {
return {a: a, b: b, c: c, d: d};
}
fn md4_str(msg: &[u8]) -> ~str {
pub fn md4_str(msg: &[u8]) -> ~str {
let {a, b, c, d} = md4(msg);
fn app(a: u32, b: u32, c: u32, d: u32, f: fn(u32)) {
f(a); f(b); f(c); f(d);
@ -103,7 +102,7 @@ fn md4_str(msg: &[u8]) -> ~str {
result
}
fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) }
pub fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) }
#[test]
fn test_md4() {

View file

@ -1,10 +1,5 @@
//! Top-level module for network-related functionality
use tcp = net_tcp;
export tcp;
use ip = net_ip;
export ip;
use url = net_url;
export url;
pub use tcp = net_tcp;
pub use ip = net_ip;
pub use url = net_url;

View file

@ -1,6 +1,5 @@
//! Types/fns concerning Internet Protocol (IP), versions 4 & 6
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use iotask = uv::iotask::IoTask;
use interact = uv::iotask::interact;
@ -21,14 +20,8 @@ use get_data_for_req = uv::ll::get_data_for_req;
use ll = uv::ll;
use comm = core::comm;
export IpAddr, parse_addr_err;
export format_addr;
export v4, v6;
export get_addr;
export Ipv4, Ipv6;
/// An IP address
enum IpAddr {
pub enum IpAddr {
/// An IPv4 address
Ipv4(sockaddr_in),
Ipv6(sockaddr_in6)
@ -46,17 +39,17 @@ type ParseAddrErr = {
*
* * ip - a `std::net::ip::ip_addr`
*/
fn format_addr(ip: &IpAddr) -> ~str {
pub fn format_addr(ip: &IpAddr) -> ~str {
match *ip {
Ipv4(addr) => unsafe {
let result = uv_ip4_name(&addr);
Ipv4(ref addr) => unsafe {
let result = uv_ip4_name(addr);
if result == ~"" {
fail ~"failed to convert inner sockaddr_in address to str"
}
result
},
Ipv6(addr) => unsafe {
let result = uv_ip6_name(&addr);
Ipv6(ref addr) => unsafe {
let result = uv_ip6_name(addr);
if result == ~"" {
fail ~"failed to convert inner sockaddr_in address to str"
}
@ -84,17 +77,17 @@ enum IpGetAddrErr {
* a vector of `ip_addr` results, in the case of success, or an error
* object in the case of failure
*/
fn get_addr(node: &str, iotask: iotask)
pub fn get_addr(node: &str, iotask: iotask)
-> result::Result<~[IpAddr], IpGetAddrErr> {
do core::comm::listen |output_ch| {
do str::as_buf(node) |node_ptr, len| unsafe {
log(debug, fmt!("slice len %?", len));
let handle = create_uv_getaddrinfo_t();
let handle_ptr = ptr::addr_of(handle);
let handle_ptr = ptr::addr_of(&handle);
let handle_data: GetAddrData = {
output_ch: output_ch
};
let handle_data_ptr = ptr::addr_of(handle_data);
let handle_data_ptr = ptr::addr_of(&handle_data);
do interact(iotask) |loop_ptr| unsafe {
let result = uv_getaddrinfo(
loop_ptr,
@ -117,8 +110,7 @@ fn get_addr(node: &str, iotask: iotask)
}
}
mod v4 {
#[legacy_exports];
pub mod v4 {
/**
* Convert a str to `ip_addr`
*
@ -134,37 +126,37 @@ mod v4 {
*
* * an `ip_addr` of the `ipv4` variant
*/
fn parse_addr(ip: &str) -> IpAddr {
pub fn parse_addr(ip: &str) -> IpAddr {
match try_parse_addr(ip) {
result::Ok(addr) => copy(addr),
result::Err(err_data) => fail err_data.err_msg
result::Ok(copy addr) => addr,
result::Err(ref err_data) => fail err_data.err_msg
}
}
// the simple, old style numberic representation of
// ipv4
type Ipv4Rep = { a: u8, b: u8, c: u8, d:u8 };
pub type Ipv4Rep = { a: u8, b: u8, c: u8, d:u8 };
trait AsUnsafeU32 {
pub trait AsUnsafeU32 {
unsafe fn as_u32() -> u32;
}
impl Ipv4Rep: AsUnsafeU32 {
// this is pretty dastardly, i know
unsafe fn as_u32() -> u32 {
*((ptr::addr_of(self)) as *u32)
*((ptr::addr_of(&self)) as *u32)
}
}
fn parse_to_ipv4_rep(ip: &str) -> result::Result<Ipv4Rep, ~str> {
pub fn parse_to_ipv4_rep(ip: &str) -> result::Result<Ipv4Rep, ~str> {
let parts = vec::map(str::split_char(ip, '.'), |s| {
match uint::from_str(*s) {
Some(n) if n <= 255u => n,
_ => 256u
Some(n) if n <= 255 => n,
_ => 256
}
});
if vec::len(parts) != 4u {
if parts.len() != 4 {
result::Err(fmt!("'%s' doesn't have 4 parts", ip))
}
else if vec::contains(parts, 256u) {
else if parts.contains(&256) {
result::Err(fmt!("invalid octal in addr '%s'", ip))
}
else {
@ -172,28 +164,28 @@ mod v4 {
c: parts[2] as u8, d: parts[3] as u8})
}
}
fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
pub fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
unsafe {
let INADDR_NONE = ll::get_INADDR_NONE();
let ip_rep_result = parse_to_ipv4_rep(ip);
if result::is_err(ip_rep_result) {
let err_str = result::get_err(ip_rep_result);
if result::is_err(&ip_rep_result) {
let err_str = result::get_err(&ip_rep_result);
return result::Err({err_msg: err_str})
}
// ipv4_rep.as_u32 is unsafe :/
let input_is_inaddr_none =
result::get(ip_rep_result).as_u32() == INADDR_NONE;
result::get(&ip_rep_result).as_u32() == INADDR_NONE;
let new_addr = uv_ip4_addr(str::from_slice(ip), 22);
let reformatted_name = uv_ip4_name(&new_addr);
log(debug, fmt!("try_parse_addr: input ip: %s reparsed ip: %s",
ip, reformatted_name));
let ref_ip_rep_result = parse_to_ipv4_rep(reformatted_name);
if result::is_err(ref_ip_rep_result) {
let err_str = result::get_err(ref_ip_rep_result);
if result::is_err(&ref_ip_rep_result) {
let err_str = result::get_err(&ref_ip_rep_result);
return result::Err({err_msg: err_str})
}
if result::get(ref_ip_rep_result).as_u32() == INADDR_NONE &&
if result::get(&ref_ip_rep_result).as_u32() == INADDR_NONE &&
!input_is_inaddr_none {
return result::Err(
{err_msg: ~"uv_ip4_name produced invalid result."})
@ -204,8 +196,7 @@ mod v4 {
}
}
}
mod v6 {
#[legacy_exports];
pub mod v6 {
/**
* Convert a str to `ip_addr`
*
@ -221,13 +212,13 @@ mod v6 {
*
* * an `ip_addr` of the `ipv6` variant
*/
fn parse_addr(ip: &str) -> IpAddr {
pub fn parse_addr(ip: &str) -> IpAddr {
match try_parse_addr(ip) {
result::Ok(addr) => copy(addr),
result::Err(err_data) => fail err_data.err_msg
result::Ok(copy addr) => addr,
result::Err(copy err_data) => fail err_data.err_msg
}
}
fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
pub fn try_parse_addr(ip: &str) -> result::Result<IpAddr,ParseAddrErr> {
unsafe {
// need to figure out how to establish a parse failure..
let new_addr = uv_ip6_addr(str::from_slice(ip), 22);
@ -252,7 +243,7 @@ type GetAddrData = {
};
extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
res: *addrinfo) unsafe {
res: *addrinfo) unsafe {
log(debug, ~"in get_addr_cb");
let handle_data = get_data_for_req(handle) as
*GetAddrData;
@ -277,7 +268,7 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
result::Err(GetAddrUnknownError));
break;
};
vec::push(out_vec, move new_ip_addr);
out_vec.push(move new_ip_addr);
let next_addr = ll::get_next_addrinfo(curr_addr);
if next_addr == ptr::null::<addrinfo>() as *addrinfo {
@ -312,7 +303,6 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
#[cfg(test)]
mod test {
#[legacy_exports];
#[test]
fn test_ip_ipv4_parse_and_format_ip() {
let localhost_str = ~"127.0.0.1";
@ -330,11 +320,11 @@ mod test {
#[test]
fn test_ip_ipv4_bad_parse() {
match v4::try_parse_addr(~"b4df00d") {
result::Err(err_info) => {
result::Err(ref err_info) => {
log(debug, fmt!("got error as expected %?", err_info));
assert true;
}
result::Ok(addr) => {
result::Ok(ref addr) => {
fail fmt!("Expected failure, but got addr %?", addr);
}
}
@ -343,11 +333,11 @@ mod test {
#[ignore(target_os="win32")]
fn test_ip_ipv6_bad_parse() {
match v6::try_parse_addr(~"::,~2234k;") {
result::Err(err_info) => {
result::Err(ref err_info) => {
log(debug, fmt!("got error as expected %?", err_info));
assert true;
}
result::Ok(addr) => {
result::Ok(ref addr) => {
fail fmt!("Expected failure, but got addr %?", addr);
}
}
@ -358,7 +348,7 @@ mod test {
let localhost_name = ~"localhost";
let iotask = uv::global_loop::get();
let ga_result = get_addr(localhost_name, iotask);
if result::is_err(ga_result) {
if result::is_err(&ga_result) {
fail ~"got err result from net::ip::get_addr();"
}
// note really sure how to realiably test/assert
@ -384,6 +374,6 @@ mod test {
let localhost_name = ~"sjkl234m,./sdf";
let iotask = uv::global_loop::get();
let ga_result = get_addr(localhost_name, iotask);
assert result::is_err(ga_result);
assert result::is_err(&ga_result);
}
}

View file

@ -11,22 +11,8 @@ use libc::size_t;
use io::{Reader, ReaderUtil, Writer};
use comm = core::comm;
// tcp interfaces
export TcpSocket;
// buffered socket
export TcpSocketBuf, socket_buf;
// errors
export TcpErrData, TcpConnectErrData;
// operations on a tcp_socket
export write, write_future, read_start, read_stop;
// tcp server stuff
export listen, accept;
// tcp client stuff
export connect;
#[nolink]
extern mod rustrt {
#[legacy_exports];
fn rust_uv_current_kernel_malloc(size: libc::c_uint) -> *libc::c_void;
fn rust_uv_current_kernel_free(mem: *libc::c_void);
fn rust_uv_helper_uv_tcp_t_size() -> libc::c_uint;
@ -48,7 +34,7 @@ struct TcpSocket {
}
}
fn TcpSocket(socket_data: @TcpSocketData) -> TcpSocket {
pub fn TcpSocket(socket_data: @TcpSocketData) -> TcpSocket {
TcpSocket {
socket_data: socket_data
}
@ -64,14 +50,14 @@ struct TcpSocketBuf {
data: @TcpBufferedSocketData,
}
fn TcpSocketBuf(data: @TcpBufferedSocketData) -> TcpSocketBuf {
pub fn TcpSocketBuf(data: @TcpBufferedSocketData) -> TcpSocketBuf {
TcpSocketBuf {
data: data
}
}
/// Contains raw, string-based, error information returned from libuv
type TcpErrData = {
pub type TcpErrData = {
err_name: ~str,
err_msg: ~str
};
@ -103,7 +89,7 @@ enum TcpListenErrData {
AccessDenied
}
/// Details returned as part of a `result::err` result from `tcp::connect`
enum TcpConnectErrData {
pub enum TcpConnectErrData {
/**
* Some unplanned-for error. The first and second fields correspond
* to libuv's `err_name` and `err_msg` fields, respectively.
@ -129,7 +115,7 @@ enum TcpConnectErrData {
* the remote host. In the event of failure, a
* `net::tcp::tcp_connect_err_data` instance will be returned
*/
fn connect(+input_ip: ip::IpAddr, port: uint,
pub fn connect(input_ip: ip::IpAddr, port: uint,
iotask: IoTask)
-> result::Result<TcpSocket, TcpConnectErrData> unsafe {
let result_po = core::comm::Port::<ConnAttempt>();
@ -138,7 +124,7 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
result_ch: core::comm::Chan(result_po),
closed_signal_ch: core::comm::Chan(closed_signal_po)
};
let conn_data_ptr = ptr::addr_of(conn_data);
let conn_data_ptr = ptr::addr_of(&conn_data);
let reader_po = core::comm::Port::<result::Result<~[u8], TcpErrData>>();
let stream_handle_ptr = malloc_uv_tcp_t();
*(stream_handle_ptr as *mut uv::ll::uv_tcp_t) = uv::ll::tcp_t();
@ -150,7 +136,7 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
write_req: uv::ll::write_t(),
iotask: iotask
};
let socket_data_ptr = ptr::addr_of(*socket_data);
let socket_data_ptr = ptr::addr_of(&(*socket_data));
log(debug, fmt!("tcp_connect result_ch %?", conn_data.result_ch));
// get an unsafe representation of our stream_handle_ptr that
// we can send into the interact cb to be handled in libuv..
@ -165,10 +151,10 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
log(debug, ~"tcp_init successful");
log(debug, ~"dealing w/ ipv4 connection..");
let connect_req_ptr =
ptr::addr_of((*socket_data_ptr).connect_req);
ptr::addr_of(&((*socket_data_ptr).connect_req));
let addr_str = ip::format_addr(&input_ip);
let connect_result = match input_ip {
ip::Ipv4(addr) => {
ip::Ipv4(ref addr) => {
// have to "recreate" the sockaddr_in/6
// since the ip_addr discards the port
// info.. should probably add an additional
@ -179,16 +165,16 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
uv::ll::tcp_connect(
connect_req_ptr,
stream_handle_ptr,
ptr::addr_of(in_addr),
ptr::addr_of(&in_addr),
tcp_connect_on_connect_cb)
}
ip::Ipv6(addr) => {
ip::Ipv6(ref addr) => {
log(debug, fmt!("addr: %?", addr));
let in_addr = uv::ll::ip6_addr(addr_str, port as int);
uv::ll::tcp_connect6(
connect_req_ptr,
stream_handle_ptr,
ptr::addr_of(in_addr),
ptr::addr_of(&in_addr),
tcp_connect_on_connect_cb)
}
};
@ -233,7 +219,7 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
log(debug, ~"tcp::connect - received success on result_po");
result::Ok(TcpSocket(socket_data))
}
ConnFailure(err_data) => {
ConnFailure(ref err_data) => {
core::comm::recv(closed_signal_po);
log(debug, ~"tcp::connect - received failure on result_po");
// still have to free the malloc'd stream handle..
@ -262,9 +248,9 @@ fn connect(+input_ip: ip::IpAddr, port: uint,
* A `result` object with a `nil` value as the `ok` variant, or a
* `tcp_err_data` value as the `err` variant
*/
fn write(sock: &TcpSocket, raw_write_data: ~[u8])
pub fn write(sock: &TcpSocket, raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> unsafe {
let socket_data_ptr = ptr::addr_of(*(sock.socket_data));
let socket_data_ptr = ptr::addr_of(&(*(sock.socket_data)));
write_common_impl(socket_data_ptr, raw_write_data)
}
@ -299,9 +285,9 @@ fn write(sock: &TcpSocket, raw_write_data: ~[u8])
* `result` object with a `nil` value as the `ok` variant, or a `tcp_err_data`
* value as the `err` variant
*/
fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
pub fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
-> future::Future<result::Result<(), TcpErrData>> unsafe {
let socket_data_ptr = ptr::addr_of(*(sock.socket_data));
let socket_data_ptr = ptr::addr_of(&(*(sock.socket_data)));
do future_spawn {
let data_copy = copy(raw_write_data);
write_common_impl(socket_data_ptr, data_copy)
@ -323,10 +309,10 @@ fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
* optionally, loop on) from until `read_stop` is called, or a
* `tcp_err_data` record
*/
fn read_start(sock: &TcpSocket)
pub fn read_start(sock: &TcpSocket)
-> result::Result<comm::Port<
result::Result<~[u8], TcpErrData>>, TcpErrData> unsafe {
let socket_data = ptr::addr_of(*(sock.socket_data));
let socket_data = ptr::addr_of(&(*(sock.socket_data)));
read_start_common_impl(socket_data)
}
@ -337,11 +323,11 @@ fn read_start(sock: &TcpSocket)
*
* * `sock` - a `net::tcp::tcp_socket` that you wish to stop reading on
*/
fn read_stop(sock: &TcpSocket,
pub fn read_stop(sock: &TcpSocket,
+read_port: comm::Port<result::Result<~[u8], TcpErrData>>) ->
result::Result<(), TcpErrData> unsafe {
log(debug, fmt!("taking the read_port out of commission %?", read_port));
let socket_data = ptr::addr_of(*sock.socket_data);
let socket_data = ptr::addr_of(&(*sock.socket_data));
read_stop_common_impl(socket_data)
}
@ -362,7 +348,7 @@ fn read_stop(sock: &TcpSocket,
*/
fn read(sock: &TcpSocket, timeout_msecs: uint)
-> result::Result<~[u8],TcpErrData> {
let socket_data = ptr::addr_of(*(sock.socket_data));
let socket_data = ptr::addr_of(&(*(sock.socket_data)));
read_common_impl(socket_data, timeout_msecs)
}
@ -397,7 +383,7 @@ fn read(sock: &TcpSocket, timeout_msecs: uint)
*/
fn read_future(sock: &TcpSocket, timeout_msecs: uint)
-> future::Future<result::Result<~[u8],TcpErrData>> {
let socket_data = ptr::addr_of(*(sock.socket_data));
let socket_data = ptr::addr_of(&(*(sock.socket_data)));
do future_spawn {
read_common_impl(socket_data, timeout_msecs)
}
@ -472,7 +458,7 @@ fn read_future(sock: &TcpSocket, timeout_msecs: uint)
* this function will return a `net::tcp::tcp_err_data` record
* as the `err` variant of a `result`.
*/
fn accept(new_conn: TcpNewConnection)
pub fn accept(new_conn: TcpNewConnection)
-> result::Result<TcpSocket, TcpErrData> unsafe {
match new_conn{
@ -491,7 +477,7 @@ fn accept(new_conn: TcpNewConnection)
write_req : uv::ll::write_t(),
iotask : iotask
};
let client_socket_data_ptr = ptr::addr_of(*client_socket_data);
let client_socket_data_ptr = ptr::addr_of(&(*client_socket_data));
let client_stream_handle_ptr =
(*client_socket_data_ptr).stream_handle_ptr;
@ -535,7 +521,7 @@ fn accept(new_conn: TcpNewConnection)
}
// UNSAFE LIBUV INTERACTION END
match core::comm::recv(result_po) {
Some(err_data) => result::Err(err_data),
Some(copy err_data) => result::Err(err_data),
None => result::Ok(TcpSocket(client_socket_data))
}
}
@ -570,7 +556,7 @@ fn accept(new_conn: TcpNewConnection)
* successful/normal shutdown, and a `tcp_listen_err_data` enum in the event
* of listen exiting because of an error
*/
fn listen(+host_ip: ip::IpAddr, port: uint, backlog: uint,
pub fn listen(host_ip: ip::IpAddr, port: uint, backlog: uint,
iotask: IoTask,
+on_establish_cb: fn~(comm::Chan<Option<TcpErrData>>),
+new_connect_cb: fn~(TcpNewConnection,
@ -587,7 +573,7 @@ fn listen(+host_ip: ip::IpAddr, port: uint, backlog: uint,
}
}
fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
iotask: IoTask,
+on_establish_cb: fn~(comm::Chan<Option<TcpErrData>>),
+on_connect_cb: fn~(*uv::ll::uv_tcp_t))
@ -596,7 +582,7 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
let kill_po = core::comm::Port::<Option<TcpErrData>>();
let kill_ch = core::comm::Chan(kill_po);
let server_stream = uv::ll::tcp_t();
let server_stream_ptr = ptr::addr_of(server_stream);
let server_stream_ptr = ptr::addr_of(&server_stream);
let server_data = {
server_stream_ptr: server_stream_ptr,
stream_closed_ch: core::comm::Chan(stream_closed_po),
@ -605,7 +591,7 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
iotask: iotask,
mut active: true
};
let server_data_ptr = ptr::addr_of(server_data);
let server_data_ptr = ptr::addr_of(&server_data);
let setup_result = do core::comm::listen |setup_ch| {
// this is to address a compiler warning about
@ -623,17 +609,17 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
server_data_ptr);
let addr_str = ip::format_addr(&loc_ip);
let bind_result = match loc_ip {
ip::Ipv4(addr) => {
ip::Ipv4(ref addr) => {
log(debug, fmt!("addr: %?", addr));
let in_addr = uv::ll::ip4_addr(addr_str, port as int);
uv::ll::tcp_bind(server_stream_ptr,
ptr::addr_of(in_addr))
ptr::addr_of(&in_addr))
}
ip::Ipv6(addr) => {
ip::Ipv6(ref addr) => {
log(debug, fmt!("addr: %?", addr));
let in_addr = uv::ll::ip6_addr(addr_str, port as int);
uv::ll::tcp_bind6(server_stream_ptr,
ptr::addr_of(in_addr))
ptr::addr_of(&in_addr))
}
};
match bind_result {
@ -666,7 +652,7 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
setup_ch.recv()
};
match setup_result {
Some(err_data) => {
Some(ref err_data) => {
do iotask::interact(iotask) |loop_ptr| unsafe {
log(debug, fmt!("tcp::listen post-kill recv hl interact %?",
loop_ptr));
@ -703,8 +689,9 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
stream_closed_po.recv();
match kill_result {
// some failure post bind/listen
Some(err_data) => result::Err(GenericListenErr(err_data.err_name,
err_data.err_msg)),
Some(ref err_data) => result::Err(GenericListenErr(
err_data.err_name,
err_data.err_msg)),
// clean exit
None => result::Ok(())
}
@ -727,17 +714,17 @@ fn listen_common(+host_ip: ip::IpAddr, port: uint, backlog: uint,
*
* A buffered wrapper that you can cast as an `io::reader` or `io::writer`
*/
fn socket_buf(+sock: TcpSocket) -> TcpSocketBuf {
pub fn socket_buf(sock: TcpSocket) -> TcpSocketBuf {
TcpSocketBuf(@{ sock: move sock, mut buf: ~[] })
}
/// Convenience methods extending `net::tcp::tcp_socket`
impl TcpSocket {
fn read_start() -> result::Result<comm::Port<
pub fn read_start() -> result::Result<comm::Port<
result::Result<~[u8], TcpErrData>>, TcpErrData> {
read_start(&self)
}
fn read_stop(-read_port:
pub fn read_stop(read_port:
comm::Port<result::Result<~[u8], TcpErrData>>) ->
result::Result<(), TcpErrData> {
read_stop(&self, move read_port)
@ -750,11 +737,11 @@ impl TcpSocket {
future::Future<result::Result<~[u8], TcpErrData>> {
read_future(&self, timeout_msecs)
}
fn write(raw_write_data: ~[u8])
pub fn write(raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> {
write(&self, raw_write_data)
}
fn write_future(raw_write_data: ~[u8])
pub fn write_future(raw_write_data: ~[u8])
-> future::Future<result::Result<(), TcpErrData>> {
write_future(&self, raw_write_data)
}
@ -762,7 +749,7 @@ impl TcpSocket {
/// Implementation of `io::reader` trait for a buffered `net::tcp::tcp_socket`
impl TcpSocketBuf: io::Reader {
fn read(buf: &[mut u8], len: uint) -> uint {
fn read(buf: &[mut u8], +len: uint) -> uint {
// Loop until our buffer has enough data in it for us to read from.
while self.data.buf.len() < len {
let read_result = read(&self.data.sock, 0u);
@ -779,7 +766,7 @@ impl TcpSocketBuf: io::Reader {
}
}
else {
vec::push_all(self.data.buf, result::unwrap(read_result));
self.data.buf.push_all(result::unwrap(read_result));
}
}
@ -790,7 +777,7 @@ impl TcpSocketBuf: io::Reader {
vec::bytes::memcpy(buf, vec::view(data, 0, data.len()), count);
vec::push_all(self.data.buf, vec::view(data, count, data.len()));
self.data.buf.push_all(vec::view(data, count, data.len()));
count
}
@ -798,13 +785,13 @@ impl TcpSocketBuf: io::Reader {
let mut bytes = ~[0];
if self.read(bytes, 1u) == 0 { fail } else { bytes[0] as int }
}
fn unread_byte(amt: int) {
vec::unshift((*(self.data)).buf, amt as u8);
fn unread_byte(+amt: int) {
self.data.buf.unshift(amt as u8);
}
fn eof() -> bool {
false // noop
}
fn seek(dist: int, seek: io::SeekStyle) {
fn seek(+dist: int, +seek: io::SeekStyle) {
log(debug, fmt!("tcp_socket_buf seek stub %? %?", dist, seek));
// noop
}
@ -815,9 +802,9 @@ impl TcpSocketBuf: io::Reader {
/// Implementation of `io::reader` trait for a buffered `net::tcp::tcp_socket`
impl TcpSocketBuf: io::Writer {
fn write(data: &[const u8]) unsafe {
pub fn write(data: &[const u8]) unsafe {
let socket_data_ptr =
ptr::addr_of(*((*(self.data)).sock).socket_data);
ptr::addr_of(&(*((*(self.data)).sock).socket_data));
let w_result = write_common_impl(socket_data_ptr,
vec::slice(data, 0, vec::len(data)));
if w_result.is_err() {
@ -826,7 +813,7 @@ impl TcpSocketBuf: io::Writer {
err_data.err_name, err_data.err_msg));
}
}
fn seek(dist: int, seek: io::SeekStyle) {
fn seek(+dist: int, +seek: io::SeekStyle) {
log(debug, fmt!("tcp_socket_buf seek stub %? %?", dist, seek));
// noop
}
@ -849,7 +836,7 @@ fn tear_down_socket_data(socket_data: @TcpSocketData) unsafe {
let close_data = {
closed_ch: closed_ch
};
let close_data_ptr = ptr::addr_of(close_data);
let close_data_ptr = ptr::addr_of(&close_data);
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
log(debug, fmt!("interact dtor for tcp_socket stream %? loop %?",
@ -871,20 +858,20 @@ fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint)
log(debug, ~"starting tcp::read");
let iotask = (*socket_data).iotask;
let rs_result = read_start_common_impl(socket_data);
if result::is_err(rs_result) {
let err_data = result::get_err(rs_result);
if result::is_err(&rs_result) {
let err_data = result::get_err(&rs_result);
result::Err(err_data)
}
else {
log(debug, ~"tcp::read before recv_timeout");
let read_result = if timeout_msecs > 0u {
timer::recv_timeout(
iotask, timeout_msecs, result::get(rs_result))
iotask, timeout_msecs, result::get(&rs_result))
} else {
Some(core::comm::recv(result::get(rs_result)))
Some(core::comm::recv(result::get(&rs_result)))
};
log(debug, ~"tcp::read after recv_timeout");
match read_result {
match move read_result {
None => {
log(debug, ~"tcp::read: timed out..");
let err_data = {
@ -894,7 +881,7 @@ fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint)
read_stop_common_impl(socket_data);
result::Err(err_data)
}
Some(data_result) => {
Some(move data_result) => {
log(debug, ~"tcp::read got data");
read_stop_common_impl(socket_data);
data_result
@ -924,7 +911,7 @@ fn read_stop_common_impl(socket_data: *TcpSocketData) ->
}
};
match core::comm::recv(stop_po) {
Some(err_data) => result::Err(err_data.to_tcp_err()),
Some(ref err_data) => result::Err(err_data.to_tcp_err()),
None => result::Ok(())
}
}
@ -954,7 +941,7 @@ fn read_start_common_impl(socket_data: *TcpSocketData)
}
};
match core::comm::recv(start_po) {
Some(err_data) => result::Err(err_data.to_tcp_err()),
Some(ref err_data) => result::Err(err_data.to_tcp_err()),
None => result::Ok((*socket_data).reader_po)
}
}
@ -965,18 +952,18 @@ fn read_start_common_impl(socket_data: *TcpSocketData)
fn write_common_impl(socket_data_ptr: *TcpSocketData,
raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> unsafe {
let write_req_ptr = ptr::addr_of((*socket_data_ptr).write_req);
let write_req_ptr = ptr::addr_of(&((*socket_data_ptr).write_req));
let stream_handle_ptr =
(*socket_data_ptr).stream_handle_ptr;
let write_buf_vec = ~[ uv::ll::buf_init(
vec::raw::to_ptr(raw_write_data),
vec::len(raw_write_data)) ];
let write_buf_vec_ptr = ptr::addr_of(write_buf_vec);
let write_buf_vec_ptr = ptr::addr_of(&write_buf_vec);
let result_po = core::comm::Port::<TcpWriteResult>();
let write_data = {
result_ch: core::comm::Chan(result_po)
};
let write_data_ptr = ptr::addr_of(write_data);
let write_data_ptr = ptr::addr_of(&write_data);
do iotask::interact((*socket_data_ptr).iotask) |loop_ptr| unsafe {
log(debug, fmt!("in interact cb for tcp::write %?", loop_ptr));
match uv::ll::write(write_req_ptr,
@ -1001,7 +988,7 @@ fn write_common_impl(socket_data_ptr: *TcpSocketData,
// aftermath, so we don't have to sit here blocking.
match core::comm::recv(result_po) {
TcpWriteSuccess => result::Ok(()),
TcpWriteError(err_data) => result::Err(err_data.to_tcp_err())
TcpWriteError(ref err_data) => result::Err(err_data.to_tcp_err())
}
}
@ -1223,16 +1210,13 @@ type TcpBufferedSocketData = {
//#[cfg(test)]
mod test {
#[legacy_exports];
// FIXME don't run on fbsd or linux 32 bit (#2064)
#[cfg(target_os="win32")]
#[cfg(target_os="darwin")]
#[cfg(target_os="linux")]
mod tcp_ipv4_server_and_client_test {
#[legacy_exports];
#[cfg(target_arch="x86_64")]
mod impl64 {
#[legacy_exports];
#[test]
fn test_gl_tcp_server_and_client_ipv4() unsafe {
impl_gl_tcp_ipv4_server_and_client();
@ -1257,7 +1241,6 @@ mod test {
}
#[cfg(target_arch="x86")]
mod impl32 {
#[legacy_exports];
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_server_and_client_ipv4() unsafe {
@ -1475,7 +1458,7 @@ mod test {
*/
}
fn buf_write<W:io::Writer>(+w: &W, val: &str) {
fn buf_write<W:io::Writer>(w: &W, val: &str) {
log(debug, fmt!("BUF_WRITE: val len %?", str::len(val)));
do str::byte_slice(val) |b_slice| {
log(debug, fmt!("BUF_WRITE: b_slice len %?",
@ -1484,7 +1467,7 @@ mod test {
}
}
fn buf_read<R:io::Reader>(+r: &R, len: uint) -> ~str {
fn buf_read<R:io::Reader>(r: &R, len: uint) -> ~str {
let new_bytes = (*r).read_bytes(len);
log(debug, fmt!("in buf_read.. new_bytes len: %?",
vec::len(new_bytes)));
@ -1514,9 +1497,9 @@ mod test {
let accept_result = accept(new_conn);
log(debug, ~"SERVER: after accept()");
if result::is_err(accept_result) {
if result::is_err(&accept_result) {
log(debug, ~"SERVER: error accept connection");
let err_data = result::get_err(accept_result);
let err_data = result::get_err(&accept_result);
core::comm::send(kill_ch, Some(err_data));
log(debug,
~"SERVER/WORKER: send on err cont ch");
@ -1530,8 +1513,8 @@ mod test {
log(debug, ~"SERVER: successfully accepted"+
~"connection!");
let received_req_bytes = read(&sock, 0u);
match received_req_bytes {
result::Ok(data) => {
match move received_req_bytes {
result::Ok(move data) => {
log(debug, ~"SERVER: got REQ str::from_bytes..");
log(debug, fmt!("SERVER: REQ data len: %?",
vec::len(data)));
@ -1542,7 +1525,7 @@ mod test {
log(debug, ~"SERVER: after write.. die");
core::comm::send(kill_ch, None);
}
result::Err(err_data) => {
result::Err(move err_data) => {
log(debug, fmt!("SERVER: error recvd: %s %s",
err_data.err_name, err_data.err_msg));
core::comm::send(kill_ch, Some(err_data));
@ -1558,11 +1541,11 @@ mod test {
log(debug, ~"SERVER: recv'd on cont_ch..leaving listen cb");
});
// err check on listen_result
if result::is_err(listen_result) {
match result::get_err(listen_result) {
GenericListenErr(name, msg) => {
if result::is_err(&listen_result) {
match result::get_err(&listen_result) {
GenericListenErr(ref name, ref msg) => {
fail fmt!("SERVER: exited abnormally name %s msg %s",
name, msg);
*name, *msg);
}
AccessDenied => {
fail ~"SERVER: exited abnormally, got access denied..";
@ -1592,8 +1575,8 @@ mod test {
new_conn, kill_ch);
});
// err check on listen_result
if result::is_err(listen_result) {
result::get_err(listen_result)
if result::is_err(&listen_result) {
result::get_err(&listen_result)
}
else {
fail ~"SERVER: did not fail as expected"
@ -1609,9 +1592,9 @@ mod test {
log(debug, ~"CLIENT: starting..");
let connect_result = connect(move server_ip_addr, server_port,
iotask);
if result::is_err(connect_result) {
if result::is_err(&connect_result) {
log(debug, ~"CLIENT: failed to connect");
let err_data = result::get_err(connect_result);
let err_data = result::get_err(&connect_result);
Err(err_data)
}
else {
@ -1636,9 +1619,9 @@ mod test {
fn tcp_write_single(sock: &TcpSocket, val: ~[u8]) {
let write_result_future = sock.write_future(val);
let write_result = write_result_future.get();
if result::is_err(write_result) {
if result::is_err(&write_result) {
log(debug, ~"tcp_write_single: write failed!");
let err_data = result::get_err(write_result);
let err_data = result::get_err(&write_result);
log(debug, fmt!("tcp_write_single err name: %s msg: %s",
err_data.err_name, err_data.err_msg));
// meh. torn on what to do here.

View file

@ -1,6 +1,5 @@
//! Types/fns concerning URLs (see RFC 3986)
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after a snapshot
use core::cmp::Eq;
use map::HashMap;
@ -11,15 +10,6 @@ use result::{Err, Ok};
use to_str::ToStr;
use to_bytes::IterBytes;
export Url, Query;
export from_str, to_str;
export get_scheme;
export query_to_str;
export encode, decode;
export encode_component, decode_component;
export encode_form_urlencoded, decode_form_urlencoded;
struct Url {
scheme: ~str,
user: Option<UserInfo>,
@ -35,9 +25,9 @@ type UserInfo = {
pass: Option<~str>
};
type Query = ~[(~str, ~str)];
pub type Query = ~[(~str, ~str)];
fn Url(+scheme: ~str, +user: Option<UserInfo>, +host: ~str,
pub fn Url(scheme: ~str, +user: Option<UserInfo>, +host: ~str,
+port: Option<~str>, +path: ~str, +query: Query,
+fragment: Option<~str>) -> Url {
Url { scheme: move scheme, user: move user, host: move host,
@ -45,7 +35,7 @@ fn Url(+scheme: ~str, +user: Option<UserInfo>, +host: ~str,
fragment: move fragment }
}
fn UserInfo(+user: ~str, +pass: Option<~str>) -> UserInfo {
fn UserInfo(user: ~str, +pass: Option<~str>) -> UserInfo {
{user: move user, pass: move pass}
}
@ -94,7 +84,7 @@ fn encode_inner(s: &str, full_url: bool) -> ~str {
*
* This function is compliant with RFC 3986.
*/
fn encode(s: &str) -> ~str {
pub fn encode(s: &str) -> ~str {
encode_inner(s, true)
}
@ -104,7 +94,7 @@ fn encode(s: &str) -> ~str {
*
* This function is compliant with RFC 3986.
*/
fn encode_component(s: &str) -> ~str {
pub fn encode_component(s: &str) -> ~str {
encode_inner(s, false)
}
@ -151,14 +141,14 @@ fn decode_inner(s: &str, full_url: bool) -> ~str {
*
* This will only decode escape sequences generated by encode_uri.
*/
fn decode(s: &str) -> ~str {
pub fn decode(s: &str) -> ~str {
decode_inner(s, true)
}
/**
* Decode a string encoded with percent encoding.
*/
fn decode_component(s: &str) -> ~str {
pub fn decode_component(s: &str) -> ~str {
decode_inner(s, false)
}
@ -184,7 +174,7 @@ fn encode_plus(s: &str) -> ~str {
/**
* Encode a hashmap to the 'application/x-www-form-urlencoded' media type.
*/
fn encode_form_urlencoded(m: HashMap<~str, @DVec<@~str>>) -> ~str {
pub fn encode_form_urlencoded(m: HashMap<~str, @DVec<@~str>>) -> ~str {
let mut out = ~"";
let mut first = true;
@ -210,7 +200,7 @@ fn encode_form_urlencoded(m: HashMap<~str, @DVec<@~str>>) -> ~str {
* Decode a string encoded with the 'application/x-www-form-urlencoded' media
* type into a hashmap.
*/
fn decode_form_urlencoded(s: ~[u8]) ->
pub fn decode_form_urlencoded(s: ~[u8]) ->
map::HashMap<~str, @dvec::DVec<@~str>> {
do io::with_bytes_reader(s) |rdr| {
let m = HashMap();
@ -307,7 +297,7 @@ fn userinfo_from_str(uinfo: &str) -> UserInfo {
return UserInfo(user, pass);
}
fn userinfo_to_str(+userinfo: UserInfo) -> ~str {
fn userinfo_to_str(userinfo: UserInfo) -> ~str {
if option::is_some(&userinfo.pass) {
return str::concat(~[copy userinfo.user, ~":",
option::unwrap(copy userinfo.pass),
@ -329,13 +319,13 @@ fn query_from_str(rawquery: &str) -> Query {
if str::len(rawquery) != 0 {
for str::split_char(rawquery, '&').each |p| {
let (k, v) = split_char_first(*p, '=');
vec::push(query, (decode_component(k), decode_component(v)));
query.push((decode_component(k), decode_component(v)));
};
}
return query;
}
fn query_to_str(+query: Query) -> ~str {
pub fn query_to_str(query: Query) -> ~str {
let mut strvec = ~[];
for query.each |kv| {
let (k, v) = copy *kv;
@ -345,7 +335,7 @@ fn query_to_str(+query: Query) -> ~str {
}
// returns the scheme and the rest of the url, or a parsing error
fn get_scheme(rawurl: &str) -> result::Result<(~str, ~str), @~str> {
pub fn get_scheme(rawurl: &str) -> result::Result<(~str, ~str), @~str> {
for str::each_chari(rawurl) |i,c| {
match c {
'A' .. 'Z' | 'a' .. 'z' => loop,
@ -524,7 +514,7 @@ fn get_authority(rawurl: &str) ->
let host_is_end_plus_one: &fn() -> bool = || {
end+1 == len
&& !['?', '#', '/'].contains(rawurl[end] as char)
&& !['?', '#', '/'].contains(&(rawurl[end] as char))
};
// finish up
@ -624,33 +614,33 @@ fn get_query_fragment(rawurl: &str) ->
*
*/
fn from_str(rawurl: &str) -> result::Result<Url, ~str> {
pub fn from_str(rawurl: &str) -> result::Result<Url, ~str> {
// scheme
let mut schm = get_scheme(rawurl);
if result::is_err(schm) {
return result::Err(copy *result::get_err(schm));
if result::is_err(&schm) {
return result::Err(copy *result::get_err(&schm));
}
let (scheme, rest) = result::unwrap(schm);
// authority
let mut auth = get_authority(rest);
if result::is_err(auth) {
return result::Err(copy *result::get_err(auth));
if result::is_err(&auth) {
return result::Err(copy *result::get_err(&auth));
}
let (userinfo, host, port, rest) = result::unwrap(auth);
// path
let has_authority = if host == ~"" { false } else { true };
let mut pth = get_path(rest, has_authority);
if result::is_err(pth) {
return result::Err(copy *result::get_err(pth));
if result::is_err(&pth) {
return result::Err(copy *result::get_err(&pth));
}
let (path, rest) = result::unwrap(pth);
// query and fragment
let mut qry = get_query_fragment(rest);
if result::is_err(qry) {
return result::Err(copy *result::get_err(qry));
if result::is_err(&qry) {
return result::Err(copy *result::get_err(&qry));
}
let (query, fragment) = result::unwrap(qry);
@ -661,7 +651,7 @@ fn from_str(rawurl: &str) -> result::Result<Url, ~str> {
impl Url : FromStr {
static fn from_str(s: &str) -> Option<Url> {
match from_str(s) {
Ok(url) => Some(url),
Ok(move url) => Some(url),
Err(_) => None
}
}
@ -682,7 +672,7 @@ impl Url : FromStr {
* result in just "http://somehost.com".
*
*/
fn to_str(+url: Url) -> ~str {
pub fn to_str(url: Url) -> ~str {
let user = if url.user.is_some() {
userinfo_to_str(option::unwrap(copy url.user))
} else {
@ -714,7 +704,7 @@ fn to_str(+url: Url) -> ~str {
}
impl Url: to_str::ToStr {
fn to_str() -> ~str {
pub fn to_str() -> ~str {
to_str(self)
}
}
@ -736,7 +726,7 @@ impl Url : Eq {
}
impl Url: IterBytes {
pure fn iter_bytes(lsb0: bool, f: to_bytes::Cb) {
pure fn iter_bytes(+lsb0: bool, f: to_bytes::Cb) {
unsafe { self.to_str() }.iter_bytes(lsb0, f)
}
}
@ -796,13 +786,13 @@ mod tests {
assert p == option::Some(~"8000");
// invalid authorities;
assert result::is_err(get_authority(
assert result::is_err(&get_authority(
~"//user:pass@rust-lang:something"));
assert result::is_err(get_authority(
assert result::is_err(&get_authority(
~"//user@rust-lang:something:/path"));
assert result::is_err(get_authority(
assert result::is_err(&get_authority(
~"//2001:0db8:85a3:0042:0000:8a2e:0370:7334:800a"));
assert result::is_err(get_authority(
assert result::is_err(&get_authority(
~"//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00"));
// these parse as empty, because they don't start with '//'
@ -830,7 +820,7 @@ mod tests {
assert r == ~"?q=v";
//failure cases
assert result::is_err(get_path(~"something?q", true));
assert result::is_err(&get_path(~"something?q", true));
}
@ -877,13 +867,13 @@ mod tests {
#[test]
fn test_no_scheme() {
assert result::is_err(get_scheme(~"noschemehere.html"));
assert result::is_err(&get_scheme(~"noschemehere.html"));
}
#[test]
fn test_invalid_scheme_errors() {
assert result::is_err(from_str(~"99://something"));
assert result::is_err(from_str(~"://something"));
assert result::is_err(&from_str(~"99://something"));
assert result::is_err(&from_str(~"://something"));
}
#[test]

View file

@ -1,6 +1,5 @@
use future_spawn = future::spawn;
export map, mapi, alli, any, mapi_factory;
/**
* The maximum number of tasks this module will spawn for a single
@ -55,7 +54,7 @@ fn map_slices<A: Copy Send, B: Copy Send>(
f(base, slice)
}
};
vec::push(futures, move f);
futures.push(move f);
};
base += items_per_task;
}
@ -73,21 +72,21 @@ fn map_slices<A: Copy Send, B: Copy Send>(
}
/// A parallel version of map.
fn map<A: Copy Send, B: Copy Send>(xs: ~[A], f: fn~(A) -> B) -> ~[B] {
pub fn map<A: Copy Send, B: Copy Send>(xs: &[A], +f: fn~((&A)) -> B) -> ~[B] {
vec::concat(map_slices(xs, || {
fn~(_base: uint, slice : &[A], copy f) -> ~[B] {
vec::map(slice, |x| f(*x))
vec::map(slice, |x| f(x))
}
}))
}
/// A parallel version of mapi.
fn mapi<A: Copy Send, B: Copy Send>(xs: ~[A],
f: fn~(uint, A) -> B) -> ~[B] {
pub fn mapi<A: Copy Send, B: Copy Send>(xs: &[A],
+f: fn~(uint, (&A)) -> B) -> ~[B] {
let slices = map_slices(xs, || {
fn~(base: uint, slice : &[A], copy f) -> ~[B] {
vec::mapi(slice, |i, x| {
f(i + base, *x)
f(i + base, x)
})
}
});
@ -103,7 +102,7 @@ fn mapi<A: Copy Send, B: Copy Send>(xs: ~[A],
* In this case, f is a function that creates functions to run over the
* inner elements. This is to skirt the need for copy constructors.
*/
fn mapi_factory<A: Copy Send, B: Copy Send>(
pub fn mapi_factory<A: Copy Send, B: Copy Send>(
xs: &[A], f: fn() -> fn~(uint, A) -> B) -> ~[B] {
let slices = map_slices(xs, || {
let f = f();
@ -120,21 +119,21 @@ fn mapi_factory<A: Copy Send, B: Copy Send>(
}
/// Returns true if the function holds for all elements in the vector.
fn alli<A: Copy Send>(xs: ~[A], f: fn~(uint, A) -> bool) -> bool {
pub fn alli<A: Copy Send>(xs: &[A], +f: fn~(uint, (&A)) -> bool) -> bool {
do vec::all(map_slices(xs, || {
fn~(base: uint, slice : &[A], copy f) -> bool {
vec::alli(slice, |i, x| {
f(i + base, x)
})
}
})) |x| { x }
})) |x| { *x }
}
/// Returns true if the function holds for any elements in the vector.
fn any<A: Copy Send>(xs: ~[A], f: fn~(A) -> bool) -> bool {
pub fn any<A: Copy Send>(xs: &[A], +f: fn~(&(A)) -> bool) -> bool {
do vec::any(map_slices(xs, || {
fn~(_base : uint, slice: &[A], copy f) -> bool {
vec::any(slice, |x| f(x))
}
})) |x| { x }
})) |x| { *x }
}

View file

@ -1,5 +1,4 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use io::Writer;
use io::WriterUtil;

176
src/libstd/prettyprint2.rs Normal file
View file

@ -0,0 +1,176 @@
#[forbid(deprecated_mode)];
use io::Writer;
use io::WriterUtil;
use serialization2;
pub struct Serializer {
wr: io::Writer,
}
pub fn Serializer(wr: io::Writer) -> Serializer {
Serializer { wr: wr }
}
pub impl Serializer: serialization2::Serializer {
fn emit_nil(&self) {
self.wr.write_str(~"()")
}
fn emit_uint(&self, v: uint) {
self.wr.write_str(fmt!("%?u", v));
}
fn emit_u64(&self, v: u64) {
self.wr.write_str(fmt!("%?_u64", v));
}
fn emit_u32(&self, v: u32) {
self.wr.write_str(fmt!("%?_u32", v));
}
fn emit_u16(&self, v: u16) {
self.wr.write_str(fmt!("%?_u16", v));
}
fn emit_u8(&self, v: u8) {
self.wr.write_str(fmt!("%?_u8", v));
}
fn emit_int(&self, v: int) {
self.wr.write_str(fmt!("%?", v));
}
fn emit_i64(&self, v: i64) {
self.wr.write_str(fmt!("%?_i64", v));
}
fn emit_i32(&self, v: i32) {
self.wr.write_str(fmt!("%?_i32", v));
}
fn emit_i16(&self, v: i16) {
self.wr.write_str(fmt!("%?_i16", v));
}
fn emit_i8(&self, v: i8) {
self.wr.write_str(fmt!("%?_i8", v));
}
fn emit_bool(&self, v: bool) {
self.wr.write_str(fmt!("%b", v));
}
fn emit_float(&self, v: float) {
self.wr.write_str(fmt!("%?_f", v));
}
fn emit_f64(&self, v: f64) {
self.wr.write_str(fmt!("%?_f64", v));
}
fn emit_f32(&self, v: f32) {
self.wr.write_str(fmt!("%?_f32", v));
}
fn emit_char(&self, v: char) {
self.wr.write_str(fmt!("%?", v));
}
fn emit_borrowed_str(&self, v: &str) {
self.wr.write_str(fmt!("&%?", v));
}
fn emit_owned_str(&self, v: &str) {
self.wr.write_str(fmt!("~%?", v));
}
fn emit_managed_str(&self, v: &str) {
self.wr.write_str(fmt!("@%?", v));
}
fn emit_borrowed(&self, f: fn()) {
self.wr.write_str(~"&");
f();
}
fn emit_owned(&self, f: fn()) {
self.wr.write_str(~"~");
f();
}
fn emit_managed(&self, f: fn()) {
self.wr.write_str(~"@");
f();
}
fn emit_enum(&self, _name: &str, f: fn()) {
f();
}
fn emit_enum_variant(&self, v_name: &str, _v_id: uint, sz: uint,
f: fn()) {
self.wr.write_str(v_name);
if sz > 0u { self.wr.write_str(~"("); }
f();
if sz > 0u { self.wr.write_str(~")"); }
}
fn emit_enum_variant_arg(&self, idx: uint, f: fn()) {
if idx > 0u { self.wr.write_str(~", "); }
f();
}
fn emit_borrowed_vec(&self, _len: uint, f: fn()) {
self.wr.write_str(~"&[");
f();
self.wr.write_str(~"]");
}
fn emit_owned_vec(&self, _len: uint, f: fn()) {
self.wr.write_str(~"~[");
f();
self.wr.write_str(~"]");
}
fn emit_managed_vec(&self, _len: uint, f: fn()) {
self.wr.write_str(~"@[");
f();
self.wr.write_str(~"]");
}
fn emit_vec_elt(&self, idx: uint, f: fn()) {
if idx > 0u { self.wr.write_str(~", "); }
f();
}
fn emit_rec(&self, f: fn()) {
self.wr.write_str(~"{");
f();
self.wr.write_str(~"}");
}
fn emit_struct(&self, name: &str, f: fn()) {
self.wr.write_str(fmt!("%s {", name));
f();
self.wr.write_str(~"}");
}
fn emit_field(&self, name: &str, idx: uint, f: fn()) {
if idx > 0u { self.wr.write_str(~", "); }
self.wr.write_str(name);
self.wr.write_str(~": ");
f();
}
fn emit_tup(&self, _len: uint, f: fn()) {
self.wr.write_str(~"(");
f();
self.wr.write_str(~")");
}
fn emit_tup_elt(&self, idx: uint, f: fn()) {
if idx > 0u { self.wr.write_str(~", "); }
f();
}
}

View file

@ -24,17 +24,16 @@
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
/// The type of ropes.
type Rope = node::Root;
pub type Rope = node::Root;
/*
Section: Creating a rope
*/
/// Create an empty rope
fn empty() -> Rope {
pub fn empty() -> Rope {
return node::Empty;
}
@ -55,7 +54,7 @@ fn empty() -> Rope {
* * this operation does not copy the string;
* * the function runs in linear time.
*/
fn of_str(str: @~str) -> Rope {
pub fn of_str(str: @~str) -> Rope {
return of_substr(str, 0u, str::len(*str));
}
@ -81,7 +80,7 @@ fn of_str(str: @~str) -> Rope {
* * this function does _not_ check the validity of the substring;
* * this function fails if `byte_offset` or `byte_len` do not match `str`.
*/
fn of_substr(str: @~str, byte_offset: uint, byte_len: uint) -> Rope {
pub fn of_substr(str: @~str, byte_offset: uint, byte_len: uint) -> Rope {
if byte_len == 0u { return node::Empty; }
if byte_offset + byte_len > str::len(*str) { fail; }
return node::Content(node::of_substr(str, byte_offset, byte_len));
@ -98,7 +97,7 @@ Section: Adding things to a rope
*
* * this function executes in near-constant time
*/
fn append_char(rope: Rope, char: char) -> Rope {
pub fn append_char(rope: Rope, char: char) -> Rope {
return append_str(rope, @str::from_chars(~[char]));
}
@ -109,7 +108,7 @@ fn append_char(rope: Rope, char: char) -> Rope {
*
* * this function executes in near-linear time
*/
fn append_str(rope: Rope, str: @~str) -> Rope {
pub fn append_str(rope: Rope, str: @~str) -> Rope {
return append_rope(rope, of_str(str))
}
@ -119,7 +118,7 @@ fn append_str(rope: Rope, str: @~str) -> Rope {
* # Performance note
* * this function executes in near-constant time
*/
fn prepend_char(rope: Rope, char: char) -> Rope {
pub fn prepend_char(rope: Rope, char: char) -> Rope {
return prepend_str(rope, @str::from_chars(~[char]));
}
@ -129,12 +128,12 @@ fn prepend_char(rope: Rope, char: char) -> Rope {
* # Performance note
* * this function executes in near-linear time
*/
fn prepend_str(rope: Rope, str: @~str) -> Rope {
pub fn prepend_str(rope: Rope, str: @~str) -> Rope {
return append_rope(of_str(str), rope)
}
/// Concatenate two ropes
fn append_rope(left: Rope, right: Rope) -> Rope {
pub fn append_rope(left: Rope, right: Rope) -> Rope {
match (left) {
node::Empty => return right,
node::Content(left_content) => {
@ -155,7 +154,7 @@ fn append_rope(left: Rope, right: Rope) -> Rope {
* rope remains balanced. However, this function does not take any further
* measure to ensure that the result is balanced.
*/
fn concat(v: ~[Rope]) -> Rope {
pub fn concat(v: ~[Rope]) -> Rope {
//Copy `v` into a mut vector
let mut len = vec::len(v);
if len == 0u { return node::Empty; }
@ -198,7 +197,7 @@ Section: Keeping ropes healthy
* If you perform numerous rope concatenations, it is generally a good idea
* to rebalance your rope at some point, before using it for other purposes.
*/
fn bal(rope:Rope) -> Rope {
pub fn bal(rope:Rope) -> Rope {
match (rope) {
node::Empty => return rope,
node::Content(x) => match (node::bal(x)) {
@ -226,7 +225,7 @@ Section: Transforming ropes
* * this function fails if char_offset/char_len do not represent
* valid positions in rope
*/
fn sub_chars(rope: Rope, char_offset: uint, char_len: uint) -> Rope {
pub fn sub_chars(rope: Rope, char_offset: uint, char_len: uint) -> Rope {
if char_len == 0u { return node::Empty; }
match (rope) {
node::Empty => fail,
@ -251,7 +250,7 @@ fn sub_chars(rope: Rope, char_offset: uint, char_len: uint) -> Rope {
* * this function fails if byte_offset/byte_len do not represent
* valid positions in rope
*/
fn sub_bytes(rope: Rope, byte_offset: uint, byte_len: uint) -> Rope {
pub fn sub_bytes(rope: Rope, byte_offset: uint, byte_len: uint) -> Rope {
if byte_len == 0u { return node::Empty; }
match (rope) {
node::Empty => fail,
@ -277,7 +276,7 @@ Section: Comparing ropes
* A negative value if `left < right`, 0 if eq(left, right) or a positive
* value if `left > right`
*/
fn cmp(left: Rope, right: Rope) -> int {
pub fn cmp(left: Rope, right: Rope) -> int {
match ((left, right)) {
(node::Empty, node::Empty) => return 0,
(node::Empty, _) => return -1,
@ -292,7 +291,7 @@ fn cmp(left: Rope, right: Rope) -> int {
* Returns `true` if both ropes have the same content (regardless of
* their structure), `false` otherwise
*/
fn eq(left: Rope, right: Rope) -> bool {
pub fn eq(left: Rope, right: Rope) -> bool {
return cmp(left, right) == 0;
}
@ -307,7 +306,7 @@ fn eq(left: Rope, right: Rope) -> bool {
* `true` if `left <= right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
fn le(left: Rope, right: Rope) -> bool {
pub fn le(left: Rope, right: Rope) -> bool {
return cmp(left, right) <= 0;
}
@ -322,7 +321,7 @@ fn le(left: Rope, right: Rope) -> bool {
* `true` if `left < right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
fn lt(left: Rope, right: Rope) -> bool {
pub fn lt(left: Rope, right: Rope) -> bool {
return cmp(left, right) < 0;
}
@ -337,7 +336,7 @@ fn lt(left: Rope, right: Rope) -> bool {
* `true` if `left >= right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
fn ge(left: Rope, right: Rope) -> bool {
pub fn ge(left: Rope, right: Rope) -> bool {
return cmp(left, right) >= 0;
}
@ -352,7 +351,7 @@ fn ge(left: Rope, right: Rope) -> bool {
* `true` if `left > right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
fn gt(left: Rope, right: Rope) -> bool {
pub fn gt(left: Rope, right: Rope) -> bool {
return cmp(left, right) > 0;
}
@ -380,7 +379,7 @@ Section: Iterating
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
fn loop_chars(rope: Rope, it: fn(char) -> bool) -> bool {
pub fn loop_chars(rope: Rope, it: fn(c: char) -> bool) -> bool {
match (rope) {
node::Empty => return true,
node::Content(x) => return node::loop_chars(x, it)
@ -394,7 +393,7 @@ fn loop_chars(rope: Rope, it: fn(char) -> bool) -> bool {
* * rope - A rope to traverse. It may be empty
* * it - A block to execute with each consecutive character of the rope.
*/
fn iter_chars(rope: Rope, it: fn(char)) {
pub fn iter_chars(rope: Rope, it: fn(char)) {
do loop_chars(rope) |x| {
it(x);
true
@ -423,36 +422,33 @@ fn iter_chars(rope: Rope, it: fn(char)) {
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
fn loop_leaves(rope: Rope, it: fn(node::Leaf) -> bool) -> bool{
pub fn loop_leaves(rope: Rope, it: fn(node::Leaf) -> bool) -> bool{
match (rope) {
node::Empty => return true,
node::Content(x) => return node::loop_leaves(x, it)
}
}
mod iterator {
#[legacy_exports];
mod leaf {
#[legacy_exports];
fn start(rope: Rope) -> node::leaf_iterator::T {
pub mod iterator {
pub mod leaf {
pub fn start(rope: Rope) -> node::leaf_iterator::T {
match (rope) {
node::Empty => return node::leaf_iterator::empty(),
node::Content(x) => return node::leaf_iterator::start(x)
}
}
fn next(it: &node::leaf_iterator::T) -> Option<node::Leaf> {
pub fn next(it: &node::leaf_iterator::T) -> Option<node::Leaf> {
return node::leaf_iterator::next(it);
}
}
mod char {
#[legacy_exports];
fn start(rope: Rope) -> node::char_iterator::T {
pub mod char {
pub fn start(rope: Rope) -> node::char_iterator::T {
match (rope) {
node::Empty => return node::char_iterator::empty(),
node::Content(x) => return node::char_iterator::start(x)
}
}
fn next(it: &node::char_iterator::T) -> Option<char> {
pub fn next(it: &node::char_iterator::T) -> Option<char> {
return node::char_iterator::next(it)
}
}
@ -473,7 +469,7 @@ mod iterator {
*
* Constant time.
*/
fn height(rope: Rope) -> uint {
pub fn height(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::height(x)
@ -489,7 +485,7 @@ fn height(rope: Rope) -> uint {
*
* Constant time.
*/
pure fn char_len(rope: Rope) -> uint {
pub pure fn char_len(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::char_len(x)
@ -503,7 +499,7 @@ pure fn char_len(rope: Rope) -> uint {
*
* Constant time.
*/
pure fn byte_len(rope: Rope) -> uint {
pub pure fn byte_len(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::byte_len(x)
@ -526,7 +522,7 @@ pure fn byte_len(rope: Rope) -> uint {
* This function executes in a time proportional to the height of the
* rope + the (bounded) length of the largest leaf.
*/
fn char_at(rope: Rope, pos: uint) -> char {
pub fn char_at(rope: Rope, pos: uint) -> char {
match (rope) {
node::Empty => fail,
node::Content(x) => return node::char_at(x, pos)
@ -538,10 +534,9 @@ fn char_at(rope: Rope, pos: uint) -> char {
Section: Implementation
*/
mod node {
#[legacy_exports];
/// Implementation of type `rope`
enum Root {
pub enum Root {
/// An empty rope
Empty,
/// A non-empty rope
@ -565,7 +560,7 @@ mod node {
* string can be shared between several ropes, e.g. for indexing
* purposes.
*/
type Leaf = {
pub type Leaf = {
byte_offset: uint,
byte_len: uint,
char_len: uint,
@ -589,7 +584,7 @@ mod node {
*
* Used for rebalancing and to allocate stacks for traversals.
*/
type Concat = {
pub type Concat = {
//FIXME (#2744): Perhaps a `vec` instead of `left`/`right`
left: @Node,
right: @Node,
@ -598,7 +593,7 @@ mod node {
height: uint
};
enum Node {
pub enum Node {
/// A leaf consisting in a `str`
Leaf(Leaf),
/// The concatenation of two ropes
@ -610,14 +605,14 @@ mod node {
*
* This is not a strict value
*/
const hint_max_leaf_char_len: uint = 256u;
pub const hint_max_leaf_char_len: uint = 256u;
/**
* The maximal height that _should_ be permitted in a tree.
*
* This is not a strict value
*/
const hint_max_node_height: uint = 16u;
pub const hint_max_node_height: uint = 16u;
/**
* Adopt a string as a node.
@ -629,7 +624,7 @@ mod node {
* Performance note: The complexity of this function is linear in
* the length of `str`.
*/
fn of_str(str: @~str) -> @Node {
pub fn of_str(str: @~str) -> @Node {
return of_substr(str, 0u, str::len(*str));
}
@ -650,7 +645,7 @@ mod node {
* Behavior is undefined if `byte_start` or `byte_len` do not represent
* valid positions in `str`
*/
fn of_substr(str: @~str, byte_start: uint, byte_len: uint) -> @Node {
pub fn of_substr(str: @~str, byte_start: uint, byte_len: uint) -> @Node {
return of_substr_unsafer(str, byte_start, byte_len,
str::count_chars(*str, byte_start, byte_len));
}
@ -676,8 +671,8 @@ mod node {
* * Behavior is undefined if `char_len` does not accurately represent the
* number of chars between byte_start and byte_start+byte_len
*/
fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint,
char_len: uint) -> @Node {
pub fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint,
char_len: uint) -> @Node {
assert(byte_start + byte_len <= str::len(*str));
let candidate = @Leaf({
byte_offset: byte_start,
@ -734,18 +729,18 @@ mod node {
}
}
pure fn byte_len(node: @Node) -> uint {
pub pure fn byte_len(node: @Node) -> uint {
//FIXME (#2744): Could we do this without the pattern-matching?
match (*node) {
Leaf(y) => return y.byte_len,
Concat(y) => return y.byte_len
Concat(ref y) => return y.byte_len
}
}
pure fn char_len(node: @Node) -> uint {
pub pure fn char_len(node: @Node) -> uint {
match (*node) {
Leaf(y) => return y.char_len,
Concat(y) => return y.char_len
Concat(ref y) => return y.char_len
}
}
@ -757,7 +752,7 @@ mod node {
* * forest - The forest. This vector is progressively rewritten during
* execution and should be discarded as meaningless afterwards.
*/
fn tree_from_forest_destructive(forest: &[mut @Node]) -> @Node {
pub fn tree_from_forest_destructive(forest: &[mut @Node]) -> @Node {
let mut i;
let mut len = vec::len(forest);
while len > 1u {
@ -801,7 +796,7 @@ mod node {
return forest[0];
}
fn serialize_node(node: @Node) -> ~str unsafe {
pub fn serialize_node(node: @Node) -> ~str unsafe {
let mut buf = vec::to_mut(vec::from_elem(byte_len(node), 0u8));
let mut offset = 0u;//Current position in the buffer
let it = leaf_iterator::start(node);
@ -832,10 +827,10 @@ mod node {
*
* This function executes in linear time.
*/
fn flatten(node: @Node) -> @Node unsafe {
pub fn flatten(node: @Node) -> @Node unsafe {
match (*node) {
Leaf(_) => return node,
Concat(x) => {
Concat(ref x) => {
return @Leaf({
byte_offset: 0u,
byte_len: x.byte_len,
@ -861,7 +856,7 @@ mod node {
* * `option::some(x)` otherwise, in which case `x` has the same contents
* as `node` bot lower height and/or fragmentation.
*/
fn bal(node: @Node) -> Option<@Node> {
pub fn bal(node: @Node) -> Option<@Node> {
if height(node) < hint_max_node_height { return option::None; }
//1. Gather all leaves as a forest
let mut forest = ~[];
@ -869,7 +864,7 @@ mod node {
loop {
match (leaf_iterator::next(&it)) {
option::None => break,
option::Some(x) => vec::push(forest, @Leaf(x))
option::Some(x) => forest.push(@Leaf(x))
}
}
//2. Rebuild tree from forest
@ -897,7 +892,8 @@ mod node {
* This function fails if `byte_offset` or `byte_len` do not represent
* valid positions in `node`.
*/
fn sub_bytes(node: @Node, byte_offset: uint, byte_len: uint) -> @Node {
pub fn sub_bytes(node: @Node, byte_offset: uint,
byte_len: uint) -> @Node {
let mut node = node;
let mut byte_offset = byte_offset;
loop {
@ -913,7 +909,7 @@ mod node {
char_len: char_len,
content: x.content});
}
node::Concat(x) => {
node::Concat(ref x) => {
let left_len: uint = node::byte_len(x.left);
if byte_offset <= left_len {
if byte_offset + byte_len <= left_len {
@ -958,7 +954,8 @@ mod node {
* This function fails if `char_offset` or `char_len` do not represent
* valid positions in `node`.
*/
fn sub_chars(node: @Node, char_offset: uint, char_len: uint) -> @Node {
pub fn sub_chars(node: @Node, char_offset: uint,
char_len: uint) -> @Node {
let mut node = node;
let mut char_offset = char_offset;
loop {
@ -976,7 +973,7 @@ mod node {
char_len: char_len,
content: x.content});
}
node::Concat(x) => {
node::Concat(ref x) => {
if char_offset == 0u && char_len == x.char_len {return node;}
let left_len : uint = node::char_len(x.left);
if char_offset <= left_len {
@ -1003,7 +1000,7 @@ mod node {
};
}
fn concat2(left: @Node, right: @Node) -> @Node {
pub fn concat2(left: @Node, right: @Node) -> @Node {
return @Concat({left : left,
right : right,
char_len: char_len(left) + char_len(right),
@ -1012,14 +1009,14 @@ mod node {
})
}
fn height(node: @Node) -> uint {
pub fn height(node: @Node) -> uint {
match (*node) {
Leaf(_) => return 0u,
Concat(x) => return x.height
Concat(ref x) => return x.height
}
}
fn cmp(a: @Node, b: @Node) -> int {
pub fn cmp(a: @Node, b: @Node) -> int {
let ita = char_iterator::start(a);
let itb = char_iterator::start(b);
let mut result = 0;
@ -1040,7 +1037,7 @@ mod node {
return result;
}
fn loop_chars(node: @Node, it: fn(char) -> bool) -> bool {
pub fn loop_chars(node: @Node, it: fn(c: char) -> bool) -> bool {
return loop_leaves(node,|leaf| {
str::all_between(*leaf.content,
leaf.byte_offset,
@ -1062,12 +1059,12 @@ mod node {
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
fn loop_leaves(node: @Node, it: fn(Leaf) -> bool) -> bool{
pub fn loop_leaves(node: @Node, it: fn(Leaf) -> bool) -> bool{
let mut current = node;
loop {
match (*current) {
Leaf(x) => return it(x),
Concat(x) => if loop_leaves(x.left, it) { //non tail call
Concat(ref x) => if loop_leaves(x.left, it) { //non tail call
current = x.right; //tail call
} else {
return false;
@ -1093,7 +1090,7 @@ mod node {
* proportional to the height of the rope + the (bounded)
* length of the largest leaf.
*/
fn char_at(node: @Node, pos: uint) -> char {
pub fn char_at(node: @Node, pos: uint) -> char {
let mut node = node;
let mut pos = pos;
loop {
@ -1108,19 +1105,18 @@ mod node {
};
}
mod leaf_iterator {
#[legacy_exports];
type T = {
pub mod leaf_iterator {
pub type T = {
stack: ~[mut @Node],
mut stackpos: int
};
fn empty() -> T {
pub fn empty() -> T {
let stack : ~[mut @Node] = ~[mut];
return {stack: move stack, mut stackpos: -1}
}
fn start(node: @Node) -> T {
pub fn start(node: @Node) -> T {
let stack = vec::to_mut(vec::from_elem(height(node)+1u, node));
return {
stack: move stack,
@ -1128,13 +1124,13 @@ mod node {
}
}
fn next(it: &T) -> Option<Leaf> {
pub fn next(it: &T) -> Option<Leaf> {
if it.stackpos < 0 { return option::None; }
loop {
let current = it.stack[it.stackpos];
it.stackpos -= 1;
match (*current) {
Concat(x) => {
Concat(ref x) => {
it.stackpos += 1;
it.stack[it.stackpos] = x.right;
it.stackpos += 1;
@ -1146,15 +1142,14 @@ mod node {
}
}
mod char_iterator {
#[legacy_exports];
type T = {
pub mod char_iterator {
pub type T = {
leaf_iterator: leaf_iterator::T,
mut leaf: Option<Leaf>,
mut leaf_byte_pos: uint
};
fn start(node: @Node) -> T {
pub fn start(node: @Node) -> T {
return {
leaf_iterator: leaf_iterator::start(node),
mut leaf: option::None,
@ -1162,7 +1157,7 @@ mod node {
}
}
fn empty() -> T {
pub fn empty() -> T {
return {
leaf_iterator: leaf_iterator::empty(),
mut leaf: option::None,
@ -1170,7 +1165,7 @@ mod node {
}
}
fn next(it: &T) -> Option<char> {
pub fn next(it: &T) -> Option<char> {
loop {
match (get_current_or_next_leaf(it)) {
option::None => return option::None,
@ -1185,7 +1180,7 @@ mod node {
};
}
fn get_current_or_next_leaf(it: &T) -> Option<Leaf> {
pub fn get_current_or_next_leaf(it: &T) -> Option<Leaf> {
match ((*it).leaf) {
option::Some(_) => return (*it).leaf,
option::None => {
@ -1202,7 +1197,7 @@ mod node {
}
}
fn get_next_char_in_leaf(it: &T) -> Option<char> {
pub fn get_next_char_in_leaf(it: &T) -> Option<char> {
match copy (*it).leaf {
option::None => return option::None,
option::Some(aleaf) => {
@ -1225,7 +1220,6 @@ mod node {
#[cfg(test)]
mod tests {
#[legacy_exports];
//Utility function, used for sanity check
fn rope_to_string(r: Rope) -> ~str {
@ -1240,7 +1234,7 @@ mod tests {
*x.content, x.byte_offset,
x.byte_offset + x.byte_len);
}
node::Concat(x) => {
node::Concat(ref x) => {
aux(str, x.left);
aux(str, x.right);
}

View file

@ -63,7 +63,7 @@ trait Deserializer {
fn read_float() -> float;
// Compound types:
fn read_enum<T>(name: ~str, f: fn() -> T) -> T;
fn read_enum<T>(name: &str, f: fn() -> T) -> T;
fn read_enum_variant<T>(f: fn(uint) -> T) -> T;
fn read_enum_variant_arg<T>(idx: uint, f: fn() -> T) -> T;
fn read_vec<T>(f: fn(uint) -> T) -> T;
@ -71,7 +71,7 @@ trait Deserializer {
fn read_box<T>(f: fn() -> T) -> T;
fn read_uniq<T>(f: fn() -> T) -> T;
fn read_rec<T>(f: fn() -> T) -> T;
fn read_rec_field<T>(f_name: ~str, f_idx: uint, f: fn() -> T) -> T;
fn read_rec_field<T>(f_name: &str, f_idx: uint, f: fn() -> T) -> T;
fn read_tup<T>(sz: uint, f: fn() -> T) -> T;
fn read_tup_elt<T>(idx: uint, f: fn() -> T) -> T;
}
@ -81,7 +81,7 @@ trait Deserializer {
//
// In some cases, these should eventually be coded as traits.
fn emit_from_vec<S: Serializer, T>(s: S, v: ~[T], f: fn(T)) {
fn emit_from_vec<S: Serializer, T>(&&s: S, &&v: ~[T], f: fn(&&x: T)) {
do s.emit_vec(vec::len(v)) {
for vec::eachi(v) |i,e| {
do s.emit_vec_elt(i) {
@ -91,7 +91,7 @@ fn emit_from_vec<S: Serializer, T>(s: S, v: ~[T], f: fn(T)) {
}
}
fn read_to_vec<D: Deserializer, T: Copy>(d: D, f: fn() -> T) -> ~[T] {
fn read_to_vec<D: Deserializer, T: Copy>(&&d: D, f: fn() -> T) -> ~[T] {
do d.read_vec |len| {
do vec::from_fn(len) |i| {
d.read_vec_elt(i, || f())
@ -100,11 +100,11 @@ fn read_to_vec<D: Deserializer, T: Copy>(d: D, f: fn() -> T) -> ~[T] {
}
trait SerializerHelpers {
fn emit_from_vec<T>(v: ~[T], f: fn(T));
fn emit_from_vec<T>(&&v: ~[T], f: fn(&&x: T));
}
impl<S: Serializer> S: SerializerHelpers {
fn emit_from_vec<T>(v: ~[T], f: fn(T)) {
fn emit_from_vec<T>(&&v: ~[T], f: fn(&&x: T)) {
emit_from_vec(self, v, f)
}
}
@ -119,142 +119,142 @@ impl<D: Deserializer> D: DeserializerHelpers {
}
}
fn serialize_uint<S: Serializer>(s: S, v: uint) {
fn serialize_uint<S: Serializer>(&&s: S, v: uint) {
s.emit_uint(v);
}
fn deserialize_uint<D: Deserializer>(d: D) -> uint {
fn deserialize_uint<D: Deserializer>(&&d: D) -> uint {
d.read_uint()
}
fn serialize_u8<S: Serializer>(s: S, v: u8) {
fn serialize_u8<S: Serializer>(&&s: S, v: u8) {
s.emit_u8(v);
}
fn deserialize_u8<D: Deserializer>(d: D) -> u8 {
fn deserialize_u8<D: Deserializer>(&&d: D) -> u8 {
d.read_u8()
}
fn serialize_u16<S: Serializer>(s: S, v: u16) {
fn serialize_u16<S: Serializer>(&&s: S, v: u16) {
s.emit_u16(v);
}
fn deserialize_u16<D: Deserializer>(d: D) -> u16 {
fn deserialize_u16<D: Deserializer>(&&d: D) -> u16 {
d.read_u16()
}
fn serialize_u32<S: Serializer>(s: S, v: u32) {
fn serialize_u32<S: Serializer>(&&s: S, v: u32) {
s.emit_u32(v);
}
fn deserialize_u32<D: Deserializer>(d: D) -> u32 {
fn deserialize_u32<D: Deserializer>(&&d: D) -> u32 {
d.read_u32()
}
fn serialize_u64<S: Serializer>(s: S, v: u64) {
fn serialize_u64<S: Serializer>(&&s: S, v: u64) {
s.emit_u64(v);
}
fn deserialize_u64<D: Deserializer>(d: D) -> u64 {
fn deserialize_u64<D: Deserializer>(&&d: D) -> u64 {
d.read_u64()
}
fn serialize_int<S: Serializer>(s: S, v: int) {
fn serialize_int<S: Serializer>(&&s: S, v: int) {
s.emit_int(v);
}
fn deserialize_int<D: Deserializer>(d: D) -> int {
fn deserialize_int<D: Deserializer>(&&d: D) -> int {
d.read_int()
}
fn serialize_i8<S: Serializer>(s: S, v: i8) {
fn serialize_i8<S: Serializer>(&&s: S, v: i8) {
s.emit_i8(v);
}
fn deserialize_i8<D: Deserializer>(d: D) -> i8 {
fn deserialize_i8<D: Deserializer>(&&d: D) -> i8 {
d.read_i8()
}
fn serialize_i16<S: Serializer>(s: S, v: i16) {
fn serialize_i16<S: Serializer>(&&s: S, v: i16) {
s.emit_i16(v);
}
fn deserialize_i16<D: Deserializer>(d: D) -> i16 {
fn deserialize_i16<D: Deserializer>(&&d: D) -> i16 {
d.read_i16()
}
fn serialize_i32<S: Serializer>(s: S, v: i32) {
fn serialize_i32<S: Serializer>(&&s: S, v: i32) {
s.emit_i32(v);
}
fn deserialize_i32<D: Deserializer>(d: D) -> i32 {
fn deserialize_i32<D: Deserializer>(&&d: D) -> i32 {
d.read_i32()
}
fn serialize_i64<S: Serializer>(s: S, v: i64) {
fn serialize_i64<S: Serializer>(&&s: S, v: i64) {
s.emit_i64(v);
}
fn deserialize_i64<D: Deserializer>(d: D) -> i64 {
fn deserialize_i64<D: Deserializer>(&&d: D) -> i64 {
d.read_i64()
}
fn serialize_str<S: Serializer>(s: S, v: &str) {
fn serialize_str<S: Serializer>(&&s: S, v: &str) {
s.emit_str(v);
}
fn deserialize_str<D: Deserializer>(d: D) -> ~str {
fn deserialize_str<D: Deserializer>(&&d: D) -> ~str {
d.read_str()
}
fn serialize_float<S: Serializer>(s: S, v: float) {
fn serialize_float<S: Serializer>(&&s: S, v: float) {
s.emit_float(v);
}
fn deserialize_float<D: Deserializer>(d: D) -> float {
fn deserialize_float<D: Deserializer>(&&d: D) -> float {
d.read_float()
}
fn serialize_f32<S: Serializer>(s: S, v: f32) {
fn serialize_f32<S: Serializer>(&&s: S, v: f32) {
s.emit_f32(v);
}
fn deserialize_f32<D: Deserializer>(d: D) -> f32 {
fn deserialize_f32<D: Deserializer>(&&d: D) -> f32 {
d.read_f32()
}
fn serialize_f64<S: Serializer>(s: S, v: f64) {
fn serialize_f64<S: Serializer>(&&s: S, v: f64) {
s.emit_f64(v);
}
fn deserialize_f64<D: Deserializer>(d: D) -> f64 {
fn deserialize_f64<D: Deserializer>(&&d: D) -> f64 {
d.read_f64()
}
fn serialize_bool<S: Serializer>(s: S, v: bool) {
fn serialize_bool<S: Serializer>(&&s: S, v: bool) {
s.emit_bool(v);
}
fn deserialize_bool<D: Deserializer>(d: D) -> bool {
fn deserialize_bool<D: Deserializer>(&&d: D) -> bool {
d.read_bool()
}
fn serialize_Option<S: Serializer,T>(s: S, v: Option<T>, st: fn(T)) {
fn serialize_Option<S: Serializer,T>(&&s: S, &&v: Option<T>, st: fn(&&x: T)) {
do s.emit_enum(~"option") {
match v {
None => do s.emit_enum_variant(~"none", 0u, 0u) {
},
Some(v) => do s.emit_enum_variant(~"some", 1u, 1u) {
Some(ref v) => do s.emit_enum_variant(~"some", 1u, 1u) {
do s.emit_enum_variant_arg(0u) {
st(v)
st(*v)
}
}
}
}
}
fn deserialize_Option<D: Deserializer,T: Copy>(d: D, st: fn() -> T)
fn deserialize_Option<D: Deserializer,T: Copy>(&&d: D, st: fn() -> T)
-> Option<T> {
do d.read_enum(~"option") {
do d.read_enum_variant |i| {

View file

@ -0,0 +1,563 @@
//! Support code for serialization.
/*
Core serialization interfaces.
*/
#[forbid(deprecated_mode)];
#[forbid(non_camel_case_types)];
pub trait Serializer {
// Primitive types:
fn emit_nil(&self);
fn emit_uint(&self, v: uint);
fn emit_u64(&self, v: u64);
fn emit_u32(&self, v: u32);
fn emit_u16(&self, v: u16);
fn emit_u8(&self, v: u8);
fn emit_int(&self, v: int);
fn emit_i64(&self, v: i64);
fn emit_i32(&self, v: i32);
fn emit_i16(&self, v: i16);
fn emit_i8(&self, v: i8);
fn emit_bool(&self, v: bool);
fn emit_float(&self, v: float);
fn emit_f64(&self, v: f64);
fn emit_f32(&self, v: f32);
fn emit_char(&self, v: char);
fn emit_borrowed_str(&self, v: &str);
fn emit_owned_str(&self, v: &str);
fn emit_managed_str(&self, v: &str);
// Compound types:
fn emit_borrowed(&self, f: fn());
fn emit_owned(&self, f: fn());
fn emit_managed(&self, f: fn());
fn emit_enum(&self, name: &str, f: fn());
fn emit_enum_variant(&self, v_name: &str, v_id: uint, sz: uint, f: fn());
fn emit_enum_variant_arg(&self, idx: uint, f: fn());
fn emit_borrowed_vec(&self, len: uint, f: fn());
fn emit_owned_vec(&self, len: uint, f: fn());
fn emit_managed_vec(&self, len: uint, f: fn());
fn emit_vec_elt(&self, idx: uint, f: fn());
fn emit_rec(&self, f: fn());
fn emit_struct(&self, name: &str, f: fn());
fn emit_field(&self, f_name: &str, f_idx: uint, f: fn());
fn emit_tup(&self, len: uint, f: fn());
fn emit_tup_elt(&self, idx: uint, f: fn());
}
pub trait Deserializer {
// Primitive types:
fn read_nil(&self) -> ();
fn read_uint(&self) -> uint;
fn read_u64(&self) -> u64;
fn read_u32(&self) -> u32;
fn read_u16(&self) -> u16;
fn read_u8(&self) -> u8;
fn read_int(&self) -> int;
fn read_i64(&self) -> i64;
fn read_i32(&self) -> i32;
fn read_i16(&self) -> i16;
fn read_i8(&self) -> i8;
fn read_bool(&self) -> bool;
fn read_f64(&self) -> f64;
fn read_f32(&self) -> f32;
fn read_float(&self) -> float;
fn read_char(&self) -> char;
fn read_owned_str(&self) -> ~str;
fn read_managed_str(&self) -> @str;
// Compound types:
fn read_enum<T>(&self, name: &str, f: fn() -> T) -> T;
fn read_enum_variant<T>(&self, f: fn(uint) -> T) -> T;
fn read_enum_variant_arg<T>(&self, idx: uint, f: fn() -> T) -> T;
fn read_owned<T>(&self, f: fn() -> T) -> T;
fn read_managed<T>(&self, f: fn() -> T) -> T;
fn read_owned_vec<T>(&self, f: fn(uint) -> T) -> T;
fn read_managed_vec<T>(&self, f: fn(uint) -> T) -> T;
fn read_vec_elt<T>(&self, idx: uint, f: fn() -> T) -> T;
fn read_rec<T>(&self, f: fn() -> T) -> T;
fn read_struct<T>(&self, name: &str, f: fn() -> T) -> T;
fn read_field<T>(&self, name: &str, idx: uint, f: fn() -> T) -> T;
fn read_tup<T>(&self, sz: uint, f: fn() -> T) -> T;
fn read_tup_elt<T>(&self, idx: uint, f: fn() -> T) -> T;
}
pub trait Serializable {
fn serialize<S: Serializer>(&self, s: &S);
}
pub trait Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> self;
}
pub impl uint: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_uint(*self) }
}
pub impl uint: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> uint {
d.read_uint()
}
}
pub impl u8: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_u8(*self) }
}
pub impl u8: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> u8 {
d.read_u8()
}
}
pub impl u16: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_u16(*self) }
}
pub impl u16: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> u16 {
d.read_u16()
}
}
pub impl u32: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_u32(*self) }
}
pub impl u32: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> u32 {
d.read_u32()
}
}
pub impl u64: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_u64(*self) }
}
pub impl u64: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> u64 {
d.read_u64()
}
}
pub impl int: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_int(*self) }
}
pub impl int: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> int {
d.read_int()
}
}
pub impl i8: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_i8(*self) }
}
pub impl i8: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> i8 {
d.read_i8()
}
}
pub impl i16: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_i16(*self) }
}
pub impl i16: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> i16 {
d.read_i16()
}
}
pub impl i32: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_i32(*self) }
}
pub impl i32: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> i32 {
d.read_i32()
}
}
pub impl i64: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_i64(*self) }
}
pub impl i64: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> i64 {
d.read_i64()
}
}
pub impl &str: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_borrowed_str(*self) }
}
pub impl ~str: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_owned_str(*self) }
}
pub impl ~str: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> ~str {
d.read_owned_str()
}
}
pub impl @str: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_managed_str(*self) }
}
pub impl @str: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> @str {
d.read_managed_str()
}
}
pub impl float: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_float(*self) }
}
pub impl float: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> float {
d.read_float()
}
}
pub impl f32: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_f32(*self) }
}
pub impl f32: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> f32 {
d.read_f32() }
}
pub impl f64: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_f64(*self) }
}
pub impl f64: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> f64 {
d.read_f64()
}
}
pub impl bool: Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_bool(*self) }
}
pub impl bool: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> bool {
d.read_bool()
}
}
pub impl (): Serializable {
fn serialize<S: Serializer>(&self, s: &S) { s.emit_nil() }
}
pub impl (): Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> () {
d.read_nil()
}
}
pub impl<T: Serializable> &T: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
s.emit_borrowed(|| (**self).serialize(s))
}
}
pub impl<T: Serializable> ~T: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
s.emit_owned(|| (**self).serialize(s))
}
}
pub impl<T: Deserializable> ~T: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> ~T {
d.read_owned(|| ~deserialize(d))
}
}
pub impl<T: Serializable> @T: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
s.emit_managed(|| (**self).serialize(s))
}
}
pub impl<T: Deserializable> @T: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> @T {
d.read_managed(|| @deserialize(d))
}
}
pub impl<T: Serializable> &[T]: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
do s.emit_borrowed_vec(self.len()) {
for self.eachi |i, e| {
s.emit_vec_elt(i, || e.serialize(s))
}
}
}
}
pub impl<T: Serializable> ~[T]: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
do s.emit_owned_vec(self.len()) {
for self.eachi |i, e| {
s.emit_vec_elt(i, || e.serialize(s))
}
}
}
}
pub impl<T: Deserializable> ~[T]: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> ~[T] {
do d.read_owned_vec |len| {
do vec::from_fn(len) |i| {
d.read_vec_elt(i, || deserialize(d))
}
}
}
}
pub impl<T: Serializable> @[T]: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
do s.emit_managed_vec(self.len()) {
for self.eachi |i, e| {
s.emit_vec_elt(i, || e.serialize(s))
}
}
}
}
pub impl<T: Deserializable> @[T]: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> @[T] {
do d.read_managed_vec |len| {
do at_vec::from_fn(len) |i| {
d.read_vec_elt(i, || deserialize(d))
}
}
}
}
pub impl<T: Serializable> Option<T>: Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
do s.emit_enum(~"option") {
match *self {
None => do s.emit_enum_variant(~"none", 0u, 0u) {
},
Some(ref v) => do s.emit_enum_variant(~"some", 1u, 1u) {
s.emit_enum_variant_arg(0u, || v.serialize(s))
}
}
}
}
}
pub impl<T: Deserializable> Option<T>: Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> Option<T> {
do d.read_enum(~"option") {
do d.read_enum_variant |i| {
match i {
0 => None,
1 => Some(d.read_enum_variant_arg(0u, || deserialize(d))),
_ => fail(#fmt("Bad variant for option: %u", i))
}
}
}
}
}
pub impl<
T0: Serializable,
T1: Serializable
> (T0, T1): Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
match *self {
(ref t0, ref t1) => {
do s.emit_tup(2) {
s.emit_tup_elt(0, || t0.serialize(s));
s.emit_tup_elt(1, || t1.serialize(s));
}
}
}
}
}
pub impl<
T0: Deserializable,
T1: Deserializable
> (T0, T1): Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> (T0, T1) {
do d.read_tup(2) {
(
d.read_tup_elt(0, || deserialize(d)),
d.read_tup_elt(1, || deserialize(d))
)
}
}
}
pub impl<
T0: Serializable,
T1: Serializable,
T2: Serializable
> (T0, T1, T2): Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
match *self {
(ref t0, ref t1, ref t2) => {
do s.emit_tup(3) {
s.emit_tup_elt(0, || t0.serialize(s));
s.emit_tup_elt(1, || t1.serialize(s));
s.emit_tup_elt(2, || t2.serialize(s));
}
}
}
}
}
pub impl<
T0: Deserializable,
T1: Deserializable,
T2: Deserializable
> (T0, T1, T2): Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> (T0, T1, T2) {
do d.read_tup(3) {
(
d.read_tup_elt(0, || deserialize(d)),
d.read_tup_elt(1, || deserialize(d)),
d.read_tup_elt(2, || deserialize(d))
)
}
}
}
pub impl<
T0: Serializable,
T1: Serializable,
T2: Serializable,
T3: Serializable
> (T0, T1, T2, T3): Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
match *self {
(ref t0, ref t1, ref t2, ref t3) => {
do s.emit_tup(4) {
s.emit_tup_elt(0, || t0.serialize(s));
s.emit_tup_elt(1, || t1.serialize(s));
s.emit_tup_elt(2, || t2.serialize(s));
s.emit_tup_elt(3, || t3.serialize(s));
}
}
}
}
}
pub impl<
T0: Deserializable,
T1: Deserializable,
T2: Deserializable,
T3: Deserializable
> (T0, T1, T2, T3): Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D) -> (T0, T1, T2, T3) {
do d.read_tup(4) {
(
d.read_tup_elt(0, || deserialize(d)),
d.read_tup_elt(1, || deserialize(d)),
d.read_tup_elt(2, || deserialize(d)),
d.read_tup_elt(3, || deserialize(d))
)
}
}
}
pub impl<
T0: Serializable,
T1: Serializable,
T2: Serializable,
T3: Serializable,
T4: Serializable
> (T0, T1, T2, T3, T4): Serializable {
fn serialize<S: Serializer>(&self, s: &S) {
match *self {
(ref t0, ref t1, ref t2, ref t3, ref t4) => {
do s.emit_tup(5) {
s.emit_tup_elt(0, || t0.serialize(s));
s.emit_tup_elt(1, || t1.serialize(s));
s.emit_tup_elt(2, || t2.serialize(s));
s.emit_tup_elt(3, || t3.serialize(s));
s.emit_tup_elt(4, || t4.serialize(s));
}
}
}
}
}
pub impl<
T0: Deserializable,
T1: Deserializable,
T2: Deserializable,
T3: Deserializable,
T4: Deserializable
> (T0, T1, T2, T3, T4): Deserializable {
static fn deserialize<D: Deserializer>(&self, d: &D)
-> (T0, T1, T2, T3, T4) {
do d.read_tup(5) {
(
d.read_tup_elt(0, || deserialize(d)),
d.read_tup_elt(1, || deserialize(d)),
d.read_tup_elt(2, || deserialize(d)),
d.read_tup_elt(3, || deserialize(d)),
d.read_tup_elt(4, || deserialize(d))
)
}
}
}
// ___________________________________________________________________________
// Helper routines
//
// In some cases, these should eventually be coded as traits.
pub trait SerializerHelpers {
fn emit_from_vec<T>(&self, v: &[T], f: fn(&T));
}
pub impl<S: Serializer> S: SerializerHelpers {
fn emit_from_vec<T>(&self, v: &[T], f: fn(&T)) {
do self.emit_owned_vec(v.len()) {
for v.eachi |i, e| {
do self.emit_vec_elt(i) {
f(e)
}
}
}
}
}
pub trait DeserializerHelpers {
fn read_to_vec<T>(&self, f: fn() -> T) -> ~[T];
}
pub impl<D: Deserializer> D: DeserializerHelpers {
fn read_to_vec<T>(&self, f: fn() -> T) -> ~[T] {
do self.read_owned_vec |len| {
do vec::from_fn(len) |i| {
self.read_vec_elt(i, || f())
}
}
}
}

View file

@ -13,14 +13,12 @@
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
/*
* A SHA-1 implementation derived from Paul E. Jones's reference
* implementation, which is written for clarity, not speed. At some
* point this will want to be rewritten.
*/
export sha1;
/// The SHA-1 interface
trait Sha1 {
@ -53,7 +51,7 @@ const k3: u32 = 0xCA62C1D6u32;
/// Construct a `sha` object
fn sha1() -> Sha1 {
pub fn sha1() -> Sha1 {
type Sha1State =
{h: ~[mut u32],
mut len_low: u32,

View file

@ -2,8 +2,7 @@
* A simple map based on a vector for small integer keys. Space requirements
* are O(highest integer key).
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use core::option;
use core::option::{Some, None};
@ -14,12 +13,12 @@ use map::Map;
// requires this to be.
type SmallIntMap_<T: Copy> = {v: DVec<Option<T>>};
enum SmallIntMap<T:Copy> {
pub enum SmallIntMap<T:Copy> {
SmallIntMap_(@SmallIntMap_<T>)
}
/// Create a smallintmap
fn mk<T: Copy>() -> SmallIntMap<T> {
pub fn mk<T: Copy>() -> SmallIntMap<T> {
let v = DVec();
return SmallIntMap_(@{v: move v});
}
@ -29,16 +28,16 @@ fn mk<T: Copy>() -> SmallIntMap<T> {
* the specified key then the original value is replaced.
*/
#[inline(always)]
fn insert<T: Copy>(self: SmallIntMap<T>, key: uint, +val: T) {
pub fn insert<T: Copy>(self: SmallIntMap<T>, key: uint, val: T) {
//io::println(fmt!("%?", key));
self.v.grow_set_elt(key, None, Some(val));
self.v.grow_set_elt(key, &None, Some(val));
}
/**
* Get the value for the specified key. If the key does not exist
* in the map then returns none
*/
pure fn find<T: Copy>(self: SmallIntMap<T>, key: uint) -> Option<T> {
pub pure fn find<T: Copy>(self: SmallIntMap<T>, key: uint) -> Option<T> {
if key < self.v.len() { return self.v.get_elt(key); }
return None::<T>;
}
@ -50,18 +49,18 @@ pure fn find<T: Copy>(self: SmallIntMap<T>, key: uint) -> Option<T> {
*
* If the key does not exist in the map
*/
pure fn get<T: Copy>(self: SmallIntMap<T>, key: uint) -> T {
pub pure fn get<T: Copy>(self: SmallIntMap<T>, key: uint) -> T {
match find(self, key) {
None => {
error!("smallintmap::get(): key not present");
fail;
}
Some(v) => return v
Some(move v) => return v
}
}
/// Returns true if the map contains a value for the specified key
fn contains_key<T: Copy>(self: SmallIntMap<T>, key: uint) -> bool {
pub fn contains_key<T: Copy>(self: SmallIntMap<T>, key: uint) -> bool {
return !find(self, key).is_none();
}
@ -78,12 +77,12 @@ impl<V: Copy> SmallIntMap<V>: map::Map<uint, V> {
sz
}
#[inline(always)]
fn insert(+key: uint, +value: V) -> bool {
fn insert(key: uint, value: V) -> bool {
let exists = contains_key(self, key);
insert(self, key, value);
return !exists;
}
fn remove(+key: uint) -> bool {
fn remove(key: uint) -> bool {
if key >= self.v.len() {
return false;
}
@ -94,30 +93,30 @@ impl<V: Copy> SmallIntMap<V>: map::Map<uint, V> {
fn clear() {
self.v.set(~[]);
}
fn contains_key(+key: uint) -> bool {
fn contains_key(key: uint) -> bool {
contains_key(self, key)
}
fn contains_key_ref(key: &uint) -> bool {
contains_key(self, *key)
}
fn get(+key: uint) -> V { get(self, key) }
pure fn find(+key: uint) -> Option<V> { find(self, key) }
fn get(key: uint) -> V { get(self, key) }
pure fn find(key: uint) -> Option<V> { find(self, key) }
fn rehash() { fail }
pure fn each(it: fn(+key: uint, +value: V) -> bool) {
pure fn each(it: fn(key: uint, +value: V) -> bool) {
self.each_ref(|k, v| it(*k, *v))
}
pure fn each_key(it: fn(+key: uint) -> bool) {
pure fn each_key(it: fn(key: uint) -> bool) {
self.each_ref(|k, _v| it(*k))
}
pure fn each_value(it: fn(+value: V) -> bool) {
pure fn each_value(it: fn(value: V) -> bool) {
self.each_ref(|_k, v| it(*v))
}
pure fn each_ref(it: fn(key: &uint, value: &V) -> bool) {
let mut idx = 0u, l = self.v.len();
while idx < l {
match self.v.get_elt(idx) {
Some(elt) => if !it(&idx, &elt) { break },
Some(ref elt) => if !it(&idx, elt) { break },
None => ()
}
idx += 1u;
@ -132,7 +131,7 @@ impl<V: Copy> SmallIntMap<V>: map::Map<uint, V> {
}
impl<V: Copy> SmallIntMap<V>: ops::Index<uint, V> {
pure fn index(&&key: uint) -> V {
pure fn index(+key: uint) -> V {
unsafe {
get(self, key)
}
@ -140,6 +139,6 @@ impl<V: Copy> SmallIntMap<V>: ops::Index<uint, V> {
}
/// Cast the given smallintmap to a map::map
fn as_map<V: Copy>(s: SmallIntMap<V>) -> map::Map<uint, V> {
pub fn as_map<V: Copy>(s: SmallIntMap<V>) -> map::Map<uint, V> {
s as map::Map::<uint, V>
}

View file

@ -1,18 +1,10 @@
//! Sorting methods
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use vec::{len, push};
use core::cmp::{Eq, Ord};
use dvec::DVec;
export le;
export merge_sort;
export quick_sort;
export quick_sort3;
export tim_sort;
export Sort;
type Le<T> = pure fn(v1: &T, v2: &T) -> bool;
/**
@ -21,7 +13,7 @@ type Le<T> = pure fn(v1: &T, v2: &T) -> bool;
* Has worst case O(n log n) performance, best case O(n), but
* is not space efficient. This is a stable sort.
*/
fn merge_sort<T: Copy>(v: &[const T], le: Le<T>) -> ~[T] {
pub fn merge_sort<T: Copy>(v: &[const T], le: Le<T>) -> ~[T] {
type Slice = (uint, uint);
return merge_sort_(v, (0u, len(v)), le);
@ -49,9 +41,9 @@ fn merge_sort<T: Copy>(v: &[const T], le: Le<T>) -> ~[T] {
let mut b_ix = 0u;
while a_ix < a_len && b_ix < b_len {
if le(&a[a_ix], &b[b_ix]) {
vec::push(rs, a[a_ix]);
rs.push(a[a_ix]);
a_ix += 1u;
} else { vec::push(rs, b[b_ix]); b_ix += 1u; }
} else { rs.push(b[b_ix]); b_ix += 1u; }
}
rs = vec::append(rs, vec::slice(a, a_ix, a_len));
rs = vec::append(rs, vec::slice(b, b_ix, b_len));
@ -95,7 +87,7 @@ fn qsort<T: Copy>(arr: &[mut T], left: uint,
* Has worst case O(n^2) performance, average case O(n log n).
* This is an unstable sort.
*/
fn quick_sort<T: Copy>(arr: &[mut T], compare_func: Le<T>) {
pub fn quick_sort<T: Copy>(arr: &[mut T], compare_func: Le<T>) {
if len::<T>(arr) == 0u { return; }
qsort::<T>(arr, 0u, len::<T>(arr) - 1u, compare_func);
}
@ -157,12 +149,12 @@ fn qsort3<T: Copy Ord Eq>(arr: &[mut T], left: int, right: int) {
*
* This is an unstable sort.
*/
fn quick_sort3<T: Copy Ord Eq>(arr: &[mut T]) {
pub fn quick_sort3<T: Copy Ord Eq>(arr: &[mut T]) {
if arr.len() <= 1 { return; }
qsort3(arr, 0, (arr.len() - 1) as int);
}
trait Sort {
pub trait Sort {
fn qsort(self);
}
@ -923,7 +915,7 @@ mod tests {
fn check_sort(v1: &[int], v2: &[int]) {
let len = vec::len::<int>(v1);
pure fn le(a: &int, b: &int) -> bool { *a <= *b }
pub pure fn le(a: &int, b: &int) -> bool { *a <= *b }
let f = le;
let v3 = merge_sort::<int>(v1, f);
let mut i = 0u;
@ -953,7 +945,7 @@ mod tests {
#[test]
fn test_merge_sort_mutable() {
pure fn le(a: &int, b: &int) -> bool { *a <= *b }
pub pure fn le(a: &int, b: &int) -> bool { *a <= *b }
let v1 = ~[mut 3, 2, 1];
let v2 = merge_sort(v1, le);
assert v2 == ~[1, 2, 3];

View file

@ -18,11 +18,11 @@ not required in or otherwise suitable for the core library.
#[no_core];
#[legacy_modes];
#[legacy_exports];
#[allow(vecs_implicitly_copyable)];
#[deny(non_camel_case_types)];
#[forbid(deprecated_pattern)];
extern mod core(vers = "0.4");
use core::*;
@ -34,116 +34,81 @@ export sync, arc, comm;
export bitv, deque, fun_treemap, list, map;
export smallintmap, sort, treemap;
export rope, arena, par;
export ebml, dbg, getopts, json, rand, sha1, term, time, prettyprint;
export test, tempfile, serialization;
export ebml, ebml2;
export dbg, getopts, json, rand, sha1, term, time;
export prettyprint, prettyprint2;
export test, tempfile, serialization, serialization2;
export cmp;
export base64;
export cell;
// General io and system-services modules
#[legacy_exports]
mod net;
#[legacy_exports]
mod net_ip;
#[legacy_exports]
mod net_tcp;
#[legacy_exports]
mod net_url;
// libuv modules
#[legacy_exports]
mod uv;
#[legacy_exports]
mod uv_ll;
#[legacy_exports]
mod uv_iotask;
#[legacy_exports]
mod uv_global_loop;
// Utility modules
#[legacy_exports]
mod c_vec;
#[legacy_exports]
mod timer;
#[legacy_exports]
mod cell;
// Concurrency
#[legacy_exports]
mod sync;
#[legacy_exports]
mod arc;
#[legacy_exports]
mod comm;
// Collections
#[legacy_exports]
mod bitv;
#[legacy_exports]
mod deque;
#[legacy_exports]
mod fun_treemap;
#[legacy_exports]
mod list;
#[legacy_exports]
mod map;
#[legacy_exports]
mod rope;
#[legacy_exports]
mod smallintmap;
#[legacy_exports]
mod sort;
#[legacy_exports]
mod treemap;
#[legacy_exports]
// And ... other stuff
#[legacy_exports]
mod ebml;
#[legacy_exports]
mod ebml2;
mod dbg;
#[legacy_exports]
mod getopts;
#[legacy_exports]
mod json;
#[legacy_exports]
mod sha1;
#[legacy_exports]
mod md4;
#[legacy_exports]
mod tempfile;
#[legacy_exports]
mod term;
#[legacy_exports]
mod time;
#[legacy_exports]
mod prettyprint;
#[legacy_exports]
mod prettyprint2;
mod arena;
#[legacy_exports]
mod par;
#[legacy_exports]
mod cmp;
#[legacy_exports]
mod base64;
#[cfg(unicode)]
#[legacy_exports]
mod unicode;
// Compiler support modules
#[legacy_exports]
mod test;
#[legacy_exports]
mod serialization;
mod serialization2;
// Local Variables:
// mode: rust;

View file

@ -1,6 +1,5 @@
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
/**
* The concurrency primitives you know and love.
*
@ -8,9 +7,6 @@
* in std.
*/
export Condvar, Semaphore, Mutex, mutex_with_condvars;
export RWlock, rwlock_with_condvars, RWlockReadMode, RWlockWriteMode;
use private::{Exclusive, exclusive};
/****************************************************************************
@ -73,7 +69,7 @@ struct SemInner<Q> {
enum Sem<Q: Send> = Exclusive<SemInner<Q>>;
#[doc(hidden)]
fn new_sem<Q: Send>(count: int, +q: Q) -> Sem<Q> {
fn new_sem<Q: Send>(count: int, q: Q) -> Sem<Q> {
Sem(exclusive(SemInner {
mut count: count, waiters: new_waitqueue(), blocked: q }))
}
@ -82,7 +78,7 @@ fn new_sem_and_signal(count: int, num_condvars: uint)
-> Sem<~[mut Waitqueue]> {
let mut queues = ~[];
for num_condvars.times {
vec::push(queues, new_waitqueue());
queues.push(new_waitqueue());
}
new_sem(count, vec::to_mut(move queues))
}
@ -177,7 +173,7 @@ fn SemAndSignalRelease(sem: &r/Sem<~[mut Waitqueue]>)
}
/// A mechanism for atomic-unlock-and-deschedule blocking and signalling.
struct Condvar { priv sem: &Sem<~[mut Waitqueue]>, drop { } }
pub struct Condvar { priv sem: &Sem<~[mut Waitqueue]>, drop { } }
impl &Condvar {
/**
@ -380,14 +376,14 @@ impl &Semaphore {
struct Mutex { priv sem: Sem<~[mut Waitqueue]> }
/// Create a new mutex, with one associated condvar.
fn Mutex() -> Mutex { mutex_with_condvars(1) }
pub fn Mutex() -> Mutex { mutex_with_condvars(1) }
/**
* Create a new mutex, with a specified number of associated condvars. This
* will allow calling wait_on/signal_on/broadcast_on with condvar IDs between
* 0 and num_condvars-1. (If num_condvars is 0, lock_cond will be allowed but
* any operations on the condvar will fail.)
*/
fn mutex_with_condvars(num_condvars: uint) -> Mutex {
pub fn mutex_with_condvars(num_condvars: uint) -> Mutex {
Mutex { sem: new_sem_and_signal(1, num_condvars) }
}
@ -430,13 +426,13 @@ struct RWlock {
}
/// Create a new rwlock, with one associated condvar.
fn RWlock() -> RWlock { rwlock_with_condvars(1) }
pub fn RWlock() -> RWlock { rwlock_with_condvars(1) }
/**
* Create a new rwlock, with a specified number of associated condvars.
* Similar to mutex_with_condvars.
*/
fn rwlock_with_condvars(num_condvars: uint) -> RWlock {
pub fn rwlock_with_condvars(num_condvars: uint) -> RWlock {
RWlock { order_lock: semaphore(1),
access_lock: new_sem_and_signal(1, num_condvars),
state: exclusive(RWlockInner { read_mode: false,
@ -539,7 +535,7 @@ impl &RWlock {
* }
* ~~~
*/
fn write_downgrade<U>(blk: fn(+v: RWlockWriteMode) -> U) -> U {
fn write_downgrade<U>(blk: fn(v: RWlockWriteMode) -> U) -> U {
// Implementation slightly different from the slicker 'write's above.
// The exit path is conditional on whether the caller downgrades.
let mut _release = None;
@ -555,7 +551,7 @@ impl &RWlock {
}
/// To be called inside of the write_downgrade block.
fn downgrade(+token: RWlockWriteMode/&a) -> RWlockReadMode/&a {
fn downgrade(token: RWlockWriteMode/&a) -> RWlockReadMode/&a {
if !ptr::ref_eq(self, token.lock) {
fail ~"Can't downgrade() with a different rwlock's write_mode!";
}
@ -647,9 +643,9 @@ fn RWlockReleaseDowngrade(lock: &r/RWlock) -> RWlockReleaseDowngrade/&r {
}
/// The "write permission" token used for rwlock.write_downgrade().
struct RWlockWriteMode { /* priv */ lock: &RWlock, drop { } }
pub struct RWlockWriteMode { /* priv */ lock: &RWlock, drop { } }
/// The "read permission" token used for rwlock.write_downgrade().
struct RWlockReadMode { priv lock: &RWlock, drop { } }
pub struct RWlockReadMode { priv lock: &RWlock, drop { } }
impl &RWlockWriteMode {
/// Access the pre-downgrade rwlock in write mode.
@ -777,7 +773,7 @@ mod tests {
let m = ~Mutex();
let m2 = ~m.clone();
let mut sharedstate = ~0;
let ptr = ptr::addr_of(*sharedstate);
let ptr = ptr::p2::addr_of(&(*sharedstate));
do task::spawn {
let sharedstate: &mut int =
unsafe { cast::reinterpret_cast(&ptr) };
@ -840,7 +836,7 @@ mod tests {
for num_waiters.times {
let mi = ~m.clone();
let (chan, port) = pipes::stream();
vec::push(ports, port);
ports.push(port);
do task::spawn {
do mi.lock_cond |cond| {
chan.send(());
@ -930,7 +926,7 @@ mod tests {
for 2.times {
let (c,p) = pipes::stream();
let c = ~mut Some(c);
vec::push(sibling_convos, p);
sibling_convos.push(p);
let mi = ~m2.clone();
// spawn sibling task
do task::spawn { // linked
@ -961,7 +957,7 @@ mod tests {
drop { self.c.send(()); }
}
fn SendOnFailure(+c: pipes::Chan<()>) -> SendOnFailure {
fn SendOnFailure(c: pipes::Chan<()>) -> SendOnFailure {
SendOnFailure {
c: c
}
@ -1042,14 +1038,14 @@ mod tests {
}
}
#[cfg(test)]
fn test_rwlock_exclusion(+x: ~RWlock, mode1: RWlockMode,
fn test_rwlock_exclusion(x: ~RWlock, mode1: RWlockMode,
mode2: RWlockMode) {
// Test mutual exclusion between readers and writers. Just like the
// mutex mutual exclusion test, a ways above.
let (c,p) = pipes::stream();
let x2 = ~x.clone();
let mut sharedstate = ~0;
let ptr = ptr::addr_of(*sharedstate);
let ptr = ptr::p2::addr_of(&(*sharedstate));
do task::spawn {
let sharedstate: &mut int =
unsafe { cast::reinterpret_cast(&ptr) };
@ -1087,7 +1083,7 @@ mod tests {
test_rwlock_exclusion(~RWlock(), Downgrade, Downgrade);
}
#[cfg(test)]
fn test_rwlock_handshake(+x: ~RWlock, mode1: RWlockMode,
fn test_rwlock_handshake(x: ~RWlock, mode1: RWlockMode,
mode2: RWlockMode, make_mode2_go_first: bool) {
// Much like sem_multi_resource.
let x2 = ~x.clone();
@ -1194,7 +1190,7 @@ mod tests {
for num_waiters.times {
let xi = ~x.clone();
let (chan, port) = pipes::stream();
vec::push(ports, port);
ports.push(port);
do task::spawn {
do lock_cond(xi, dg1) |cond| {
chan.send(());

View file

@ -1,12 +1,11 @@
//! Temporary files and directories
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use core::option;
use option::{None, Some};
fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option<Path> {
pub fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option<Path> {
let r = rand::Rng();
let mut i = 0u;
while (i < 1000u) {
@ -24,8 +23,8 @@ fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option<Path> {
fn test_mkdtemp() {
let r = mkdtemp(&Path("."), "foobar");
match r {
Some(p) => {
os::remove_dir(&p);
Some(ref p) => {
os::remove_dir(p);
assert(str::ends_with(p.to_str(), "foobar"));
}
_ => assert(false)

View file

@ -1,46 +1,45 @@
//! Simple ANSI color library
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use core::Option;
// FIXME (#2807): Windows support.
const color_black: u8 = 0u8;
const color_red: u8 = 1u8;
const color_green: u8 = 2u8;
const color_yellow: u8 = 3u8;
const color_blue: u8 = 4u8;
const color_magenta: u8 = 5u8;
const color_cyan: u8 = 6u8;
const color_light_gray: u8 = 7u8;
const color_light_grey: u8 = 7u8;
const color_dark_gray: u8 = 8u8;
const color_dark_grey: u8 = 8u8;
const color_bright_red: u8 = 9u8;
const color_bright_green: u8 = 10u8;
const color_bright_yellow: u8 = 11u8;
const color_bright_blue: u8 = 12u8;
const color_bright_magenta: u8 = 13u8;
const color_bright_cyan: u8 = 14u8;
const color_bright_white: u8 = 15u8;
pub const color_black: u8 = 0u8;
pub const color_red: u8 = 1u8;
pub const color_green: u8 = 2u8;
pub const color_yellow: u8 = 3u8;
pub const color_blue: u8 = 4u8;
pub const color_magenta: u8 = 5u8;
pub const color_cyan: u8 = 6u8;
pub const color_light_gray: u8 = 7u8;
pub const color_light_grey: u8 = 7u8;
pub const color_dark_gray: u8 = 8u8;
pub const color_dark_grey: u8 = 8u8;
pub const color_bright_red: u8 = 9u8;
pub const color_bright_green: u8 = 10u8;
pub const color_bright_yellow: u8 = 11u8;
pub const color_bright_blue: u8 = 12u8;
pub const color_bright_magenta: u8 = 13u8;
pub const color_bright_cyan: u8 = 14u8;
pub const color_bright_white: u8 = 15u8;
fn esc(writer: io::Writer) { writer.write(~[0x1bu8, '[' as u8]); }
pub fn esc(writer: io::Writer) { writer.write(~[0x1bu8, '[' as u8]); }
/// Reset the foreground and background colors to default
fn reset(writer: io::Writer) {
pub fn reset(writer: io::Writer) {
esc(writer);
writer.write(~['0' as u8, 'm' as u8]);
}
/// Returns true if the terminal supports color
fn color_supported() -> bool {
pub fn color_supported() -> bool {
let supported_terms = ~[~"xterm-color", ~"xterm",
~"screen-bce", ~"xterm-256color"];
return match os::getenv(~"TERM") {
option::Some(env) => {
option::Some(ref env) => {
for vec::each(supported_terms) |term| {
if *term == env { return true; }
if *term == *env { return true; }
}
false
}
@ -48,7 +47,7 @@ fn color_supported() -> bool {
};
}
fn set_color(writer: io::Writer, first_char: u8, color: u8) {
pub fn set_color(writer: io::Writer, first_char: u8, color: u8) {
assert (color < 16u8);
esc(writer);
let mut color = color;
@ -57,12 +56,12 @@ fn set_color(writer: io::Writer, first_char: u8, color: u8) {
}
/// Set the foreground color
fn fg(writer: io::Writer, color: u8) {
pub fn fg(writer: io::Writer, color: u8) {
return set_color(writer, '3' as u8, color);
}
/// Set the background color
fn bg(writer: io::Writer, color: u8) {
pub fn bg(writer: io::Writer, color: u8) {
return set_color(writer, '4' as u8, color);
}

View file

@ -5,8 +5,7 @@
// simplest interface possible for representing and running tests
// while providing a base that other test frameworks may build off of.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
#[warn(deprecated_mode)];
use core::cmp::Eq;
use either::Either;
@ -16,17 +15,6 @@ use libc::size_t;
use task::TaskBuilder;
use comm = core::comm;
export TestName;
export TestFn;
export TestDesc;
export test_main;
export TestResult;
export TestOpts;
export TrOk;
export TrFailed;
export TrIgnored;
export run_tests_console;
#[abi = "cdecl"]
extern mod rustrt {
#[legacy_exports];
@ -37,17 +25,17 @@ extern mod rustrt {
// paths; i.e. it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// hierarchically it may.
type TestName = ~str;
pub type TestName = ~str;
// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
type TestFn = fn~();
pub type TestFn = fn~();
// The definition of a single test. A test runner will run a list of
// these.
type TestDesc = {
pub type TestDesc = {
name: TestName,
testfn: TestFn,
ignore: bool,
@ -56,16 +44,16 @@ type TestDesc = {
// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
fn test_main(args: &[~str], tests: &[TestDesc]) {
pub fn test_main(args: &[~str], tests: &[TestDesc]) {
let opts =
match parse_opts(args) {
either::Left(o) => o,
either::Right(m) => fail m
either::Left(move o) => o,
either::Right(move m) => fail m
};
if !run_tests_console(&opts, tests) { fail ~"Some tests failed"; }
}
type TestOpts = {filter: Option<~str>, run_ignored: bool,
pub type TestOpts = {filter: Option<~str>, run_ignored: bool,
logfile: Option<~str>};
type OptRes = Either<TestOpts, ~str>;
@ -76,8 +64,8 @@ fn parse_opts(args: &[~str]) -> OptRes {
let opts = ~[getopts::optflag(~"ignored"), getopts::optopt(~"logfile")];
let matches =
match getopts::getopts(args_, opts) {
Ok(m) => m,
Err(f) => return either::Right(getopts::fail_str(f))
Ok(move m) => m,
Err(move f) => return either::Right(getopts::fail_str(f))
};
let filter =
@ -94,7 +82,7 @@ fn parse_opts(args: &[~str]) -> OptRes {
return either::Left(test_opts);
}
enum TestResult { TrOk, TrFailed, TrIgnored, }
pub enum TestResult { TrOk, TrFailed, TrIgnored, }
impl TestResult : Eq {
pure fn eq(other: &TestResult) -> bool {
@ -114,19 +102,20 @@ type ConsoleTestState =
mut failures: ~[TestDesc]};
// A simple console test runner
fn run_tests_console(opts: &TestOpts,
pub fn run_tests_console(opts: &TestOpts,
tests: &[TestDesc]) -> bool {
fn callback(event: &TestEvent, st: ConsoleTestState) {
debug!("callback(event=%?)", event);
match *event {
TeFiltered(filtered_tests) => {
st.total = vec::len(filtered_tests);
TeFiltered(ref filtered_tests) => {
st.total = filtered_tests.len();
let noun = if st.total != 1u { ~"tests" } else { ~"test" };
st.out.write_line(fmt!("\nrunning %u %s", st.total, noun));
}
TeWait(test) => st.out.write_str(fmt!("test %s ... ", test.name)),
TeResult(test, result) => {
TeWait(ref test) => st.out.write_str(
fmt!("test %s ... ", test.name)),
TeResult(copy test, result) => {
match st.log_out {
Some(f) => write_log(f, result, &test),
None => ()
@ -141,7 +130,7 @@ fn run_tests_console(opts: &TestOpts,
st.failed += 1u;
write_failed(st.out, st.use_color);
st.out.write_line(~"");
vec::push(st.failures, copy test);
st.failures.push(test);
}
TrIgnored => {
st.ignored += 1u;
@ -154,11 +143,11 @@ fn run_tests_console(opts: &TestOpts,
}
let log_out = match opts.logfile {
Some(path) => match io::file_writer(&Path(path),
Some(ref path) => match io::file_writer(&Path(*path),
~[io::Create, io::Truncate]) {
result::Ok(w) => Some(w),
result::Err(s) => {
fail(fmt!("can't open output file: %s", s))
result::Err(ref s) => {
fail(fmt!("can't open output file: %s", *s))
}
},
None => None
@ -281,7 +270,7 @@ enum TestEvent {
type MonitorMsg = (TestDesc, TestResult);
fn run_tests(opts: &TestOpts, tests: &[TestDesc],
callback: fn@(TestEvent)) {
callback: fn@(e: TestEvent)) {
let mut filtered_tests = filter_tests(opts, tests);
callback(TeFiltered(copy filtered_tests));
@ -347,7 +336,7 @@ fn filter_tests(opts: &TestOpts,
} else {
let filter_str =
match opts.filter {
option::Some(f) => f,
option::Some(copy f) => f,
option::None => ~""
};
@ -358,7 +347,7 @@ fn filter_tests(opts: &TestOpts,
} else { return option::None; }
}
vec::filter_map(filtered, |x| filter_fn(&x, filter_str))
vec::filter_map(filtered, |x| filter_fn(x, filter_str))
};
// Maybe pull out the ignored test and unignore them
@ -374,7 +363,7 @@ fn filter_tests(opts: &TestOpts,
} else { return option::None; }
};
vec::filter_map(filtered, |x| filter(&x))
vec::filter_map(filtered, |x| filter(x))
};
// Sort the tests alphabetically
@ -390,7 +379,7 @@ fn filter_tests(opts: &TestOpts,
type TestFuture = {test: TestDesc, wait: fn@() -> TestResult};
fn run_test(+test: TestDesc, monitor_ch: comm::Chan<MonitorMsg>) {
fn run_test(test: TestDesc, monitor_ch: comm::Chan<MonitorMsg>) {
if test.ignore {
core::comm::send(monitor_ch, (copy test, TrIgnored));
return;
@ -491,7 +480,7 @@ mod tests {
fn first_free_arg_should_be_a_filter() {
let args = ~[~"progname", ~"filter"];
let opts = match parse_opts(args) {
either::Left(o) => o,
either::Left(copy o) => o,
_ => fail ~"Malformed arg in first_free_arg_should_be_a_filter"
};
assert ~"filter" == opts.filter.get();
@ -501,7 +490,7 @@ mod tests {
fn parse_ignored_flag() {
let args = ~[~"progname", ~"filter", ~"--ignored"];
let opts = match parse_opts(args) {
either::Left(o) => o,
either::Left(copy o) => o,
_ => fail ~"Malformed arg in parse_ignored_flag"
};
assert (opts.run_ignored);
@ -545,7 +534,7 @@ mod tests {
for vec::each(names) |name| {
let test = {name: *name, testfn: copy testfn, ignore: false,
should_fail: false};
vec::push(tests, test);
tests.push(test);
}
tests
};
@ -564,7 +553,7 @@ mod tests {
for vec::each(pairs) |p| {
match *p {
(a, b) => { assert (a == b.name); }
(ref a, ref b) => { assert (*a == b.name); }
}
}
}

View file

@ -1,25 +1,10 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use core::cmp::Eq;
use libc::{c_char, c_int, c_long, size_t, time_t};
use io::Reader;
use io::{Reader, ReaderUtil};
use result::{Result, Ok, Err};
export
Timespec,
get_time,
precise_time_ns,
precise_time_s,
tzset,
Tm,
empty_tm,
now,
at,
now_utc,
at_utc,
strptime;
#[abi = "cdecl"]
extern mod rustrt {
#[legacy_exports];
@ -35,7 +20,7 @@ extern mod rustrt {
}
/// A record specifying a time value in seconds and nanoseconds.
type Timespec = {sec: i64, nsec: i32};
pub type Timespec = {sec: i64, nsec: i32};
impl Timespec : Eq {
pure fn eq(other: &Timespec) -> bool {
@ -48,7 +33,7 @@ impl Timespec : Eq {
* Returns the current time as a `timespec` containing the seconds and
* nanoseconds since 1970-01-01T00:00:00Z.
*/
fn get_time() -> Timespec {
pub fn get_time() -> Timespec {
let mut sec = 0i64;
let mut nsec = 0i32;
rustrt::get_time(sec, nsec);
@ -59,7 +44,7 @@ fn get_time() -> Timespec {
* Returns the current value of a high-resolution performance counter
* in nanoseconds since an unspecified epoch.
*/
fn precise_time_ns() -> u64 {
pub fn precise_time_ns() -> u64 {
let mut ns = 0u64;
rustrt::precise_time_ns(ns);
ns
@ -69,11 +54,11 @@ fn precise_time_ns() -> u64 {
* Returns the current value of a high-resolution performance counter
* in seconds since an unspecified epoch.
*/
fn precise_time_s() -> float {
pub fn precise_time_s() -> float {
return (precise_time_ns() as float) / 1000000000.;
}
fn tzset() {
pub fn tzset() {
rustrt::rust_tzset();
}
@ -110,7 +95,7 @@ impl Tm_ : Eq {
pure fn ne(other: &Tm_) -> bool { !self.eq(other) }
}
enum Tm {
pub enum Tm {
Tm_(Tm_)
}
@ -119,7 +104,7 @@ impl Tm : Eq {
pure fn ne(other: &Tm) -> bool { *self != *(*other) }
}
fn empty_tm() -> Tm {
pub fn empty_tm() -> Tm {
Tm_({
tm_sec: 0_i32,
tm_min: 0_i32,
@ -137,7 +122,7 @@ fn empty_tm() -> Tm {
}
/// Returns the specified time in UTC
fn at_utc(clock: Timespec) -> Tm {
pub fn at_utc(clock: Timespec) -> Tm {
let mut {sec, nsec} = clock;
let mut tm = empty_tm();
rustrt::rust_gmtime(sec, nsec, tm);
@ -145,12 +130,12 @@ fn at_utc(clock: Timespec) -> Tm {
}
/// Returns the current time in UTC
fn now_utc() -> Tm {
pub fn now_utc() -> Tm {
at_utc(get_time())
}
/// Returns the specified time in the local timezone
fn at(clock: Timespec) -> Tm {
pub fn at(clock: Timespec) -> Tm {
let mut {sec, nsec} = clock;
let mut tm = empty_tm();
rustrt::rust_localtime(sec, nsec, tm);
@ -158,12 +143,12 @@ fn at(clock: Timespec) -> Tm {
}
/// Returns the current time in the local timezone
fn now() -> Tm {
pub fn now() -> Tm {
at(get_time())
}
/// Parses the time from the string according to the format string.
fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
type TmMut = {
mut tm_sec: i32,
mut tm_min: i32,
@ -576,7 +561,7 @@ fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
match rdr.read_char() {
'%' => match parse_type(s, pos, rdr.read_char(), &tm) {
Ok(next) => pos = next,
Err(e) => { result = Err(e); break; }
Err(copy e) => { result = Err(e); break; }
},
c => {
if c != ch { break }
@ -604,7 +589,7 @@ fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
}
}
fn strftime(format: &str, +tm: Tm) -> ~str {
fn strftime(format: &str, tm: Tm) -> ~str {
fn parse_type(ch: char, tm: &Tm) -> ~str {
//FIXME (#2350): Implement missing types.
let die = || #fmt("strftime: can't understand this format %c ",
@ -979,7 +964,7 @@ mod tests {
tzset();
match strptime(~"", ~"") {
Ok(tm) => {
Ok(ref tm) => {
assert tm.tm_sec == 0_i32;
assert tm.tm_min == 0_i32;
assert tm.tm_hour == 0_i32;
@ -1001,8 +986,8 @@ mod tests {
== Err(~"Invalid time");
match strptime(~"Fri Feb 13 15:31:30 2009", format) {
Err(e) => fail e,
Ok(tm) => {
Err(copy e) => fail e,
Ok(ref tm) => {
assert tm.tm_sec == 30_i32;
assert tm.tm_min == 31_i32;
assert tm.tm_hour == 15_i32;
@ -1020,8 +1005,8 @@ mod tests {
fn test(s: &str, format: &str) -> bool {
match strptime(s, format) {
Ok(tm) => tm.strftime(format) == str::from_slice(s),
Err(e) => fail e
Ok(ref tm) => tm.strftime(format) == str::from_slice(s),
Err(copy e) => fail e
}
}

View file

@ -1,15 +1,12 @@
//! Utilities that leverage libuv's `uv_timer_*` API
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
// tjc: forbid deprecated modes again after snap
use uv = uv;
use uv::iotask;
use iotask::IoTask;
use comm = core::comm;
export delayed_send, sleep, recv_timeout;
/**
* Wait for timeout period then send provided value over a channel
*
@ -26,14 +23,14 @@ export delayed_send, sleep, recv_timeout;
* * ch - a channel of type T to send a `val` on
* * val - a value of type T to send over the provided `ch`
*/
fn delayed_send<T: Copy Send>(iotask: IoTask,
msecs: uint, ch: comm::Chan<T>, +val: T) {
pub fn delayed_send<T: Copy Send>(iotask: IoTask,
msecs: uint, ch: comm::Chan<T>, val: T) {
unsafe {
let timer_done_po = core::comm::Port::<()>();
let timer_done_ch = core::comm::Chan(timer_done_po);
let timer_done_ch_ptr = ptr::addr_of(timer_done_ch);
let timer_done_ch_ptr = ptr::addr_of(&timer_done_ch);
let timer = uv::ll::timer_t();
let timer_ptr = ptr::addr_of(timer);
let timer_ptr = ptr::addr_of(&timer);
do iotask::interact(iotask) |loop_ptr| unsafe {
let init_result = uv::ll::timer_init(loop_ptr, timer_ptr);
if (init_result == 0i32) {
@ -75,7 +72,7 @@ fn delayed_send<T: Copy Send>(iotask: IoTask,
* * `iotask` - a `uv::iotask` that the tcp request will run on
* * msecs - an amount of time, in milliseconds, for the current task to block
*/
fn sleep(iotask: IoTask, msecs: uint) {
pub fn sleep(iotask: IoTask, msecs: uint) {
let exit_po = core::comm::Port::<()>();
let exit_ch = core::comm::Chan(exit_po);
delayed_send(iotask, msecs, exit_ch, ());
@ -102,7 +99,7 @@ fn sleep(iotask: IoTask, msecs: uint) {
* on the provided port in the allotted timeout period, then the result will
* be a `some(T)`. If not, then `none` will be returned.
*/
fn recv_timeout<T: Copy Send>(iotask: IoTask,
pub fn recv_timeout<T: Copy Send>(iotask: IoTask,
msecs: uint,
wait_po: comm::Port<T>) -> Option<T> {
let timeout_po = comm::Port::<()>();

View file

@ -5,19 +5,13 @@
* very naive algorithm, but it will probably be updated to be a
* red-black tree or something else.
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
#[warn(deprecated_mode)];
use core::cmp::{Eq, Ord};
use core::option::{Some, None};
use Option = core::Option;
export TreeMap;
export insert;
export find;
export traverse;
type TreeMap<K, V> = @mut TreeEdge<K, V>;
pub type TreeMap<K, V> = @mut TreeEdge<K, V>;
type TreeEdge<K, V> = Option<@TreeNode<K, V>>;
@ -29,10 +23,10 @@ enum TreeNode<K, V> = {
};
/// Create a treemap
fn TreeMap<K, V>() -> TreeMap<K, V> { @mut None }
pub fn TreeMap<K, V>() -> TreeMap<K, V> { @mut None }
/// Insert a value into the map
fn insert<K: Copy Eq Ord, V: Copy>(m: &mut TreeEdge<K, V>, +k: K, +v: V) {
pub fn insert<K: Copy Eq Ord, V: Copy>(m: &mut TreeEdge<K, V>, +k: K, +v: V) {
match copy *m {
None => {
*m = Some(@TreeNode({key: k,
@ -54,7 +48,7 @@ fn insert<K: Copy Eq Ord, V: Copy>(m: &mut TreeEdge<K, V>, +k: K, +v: V) {
}
/// Find a value based on the key
fn find<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>, +k: K)
pub fn find<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>, +k: K)
-> Option<V> {
match copy *m {
None => None,
@ -73,13 +67,13 @@ fn find<K: Copy Eq Ord, V: Copy>(m: &const TreeEdge<K, V>, +k: K)
}
/// Visit all pairs in the map in order.
fn traverse<K, V: Copy>(m: &const TreeEdge<K, V>, f: fn(K, V)) {
pub fn traverse<K, V: Copy>(m: &const TreeEdge<K, V>, f: fn((&K), (&V))) {
match copy *m {
None => (),
Some(node) => {
traverse(&const node.left, f);
// copy of value is req'd as f() requires an immutable ptr
f(node.key, copy node.value);
f(&node.key, &copy node.value);
traverse(&const node.right, f);
}
}
@ -130,7 +124,7 @@ mod tests {
fn t(n: @mut int, +k: int, +_v: ()) {
assert (*n == k); *n += 1;
}
traverse(m, |x,y| t(n, x, y));
traverse(m, |x,y| t(n, *x, *y));
}
#[test]

View file

@ -1,158 +1,155 @@
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
mod icu {
#[legacy_exports];
type UBool = u8;
type UProperty = int;
type UChar32 = char;
pub mod icu {
pub type UBool = u8;
pub type UProperty = int;
pub type UChar32 = char;
const TRUE : u8 = 1u8;
const FALSE : u8 = 1u8;
pub const TRUE : u8 = 1u8;
pub const FALSE : u8 = 1u8;
const UCHAR_ALPHABETIC : UProperty = 0;
const UCHAR_BINARY_START : UProperty = 0; // = UCHAR_ALPHABETIC
const UCHAR_ASCII_HEX_DIGIT : UProperty = 1;
const UCHAR_BIDI_CONTROL : UProperty = 2;
pub const UCHAR_ALPHABETIC : UProperty = 0;
pub const UCHAR_BINARY_START : UProperty = 0; // = UCHAR_ALPHABETIC
pub const UCHAR_ASCII_HEX_DIGIT : UProperty = 1;
pub const UCHAR_BIDI_CONTROL : UProperty = 2;
const UCHAR_BIDI_MIRRORED : UProperty = 3;
const UCHAR_DASH : UProperty = 4;
const UCHAR_DEFAULT_IGNORABLE_CODE_POINT : UProperty = 5;
const UCHAR_DEPRECATED : UProperty = 6;
pub const UCHAR_BIDI_MIRRORED : UProperty = 3;
pub const UCHAR_DASH : UProperty = 4;
pub const UCHAR_DEFAULT_IGNORABLE_CODE_POINT : UProperty = 5;
pub const UCHAR_DEPRECATED : UProperty = 6;
const UCHAR_DIACRITIC : UProperty = 7;
const UCHAR_EXTENDER : UProperty = 8;
const UCHAR_FULL_COMPOSITION_EXCLUSION : UProperty = 9;
const UCHAR_GRAPHEME_BASE : UProperty = 10;
pub const UCHAR_DIACRITIC : UProperty = 7;
pub const UCHAR_EXTENDER : UProperty = 8;
pub const UCHAR_FULL_COMPOSITION_EXCLUSION : UProperty = 9;
pub const UCHAR_GRAPHEME_BASE : UProperty = 10;
const UCHAR_GRAPHEME_EXTEND : UProperty = 11;
const UCHAR_GRAPHEME_LINK : UProperty = 12;
const UCHAR_HEX_DIGIT : UProperty = 13;
const UCHAR_HYPHEN : UProperty = 14;
pub const UCHAR_GRAPHEME_EXTEND : UProperty = 11;
pub const UCHAR_GRAPHEME_LINK : UProperty = 12;
pub const UCHAR_HEX_DIGIT : UProperty = 13;
pub const UCHAR_HYPHEN : UProperty = 14;
const UCHAR_ID_CONTINUE : UProperty = 15;
const UCHAR_ID_START : UProperty = 16;
const UCHAR_IDEOGRAPHIC : UProperty = 17;
const UCHAR_IDS_BINARY_OPERATOR : UProperty = 18;
pub const UCHAR_ID_CONTINUE : UProperty = 15;
pub const UCHAR_ID_START : UProperty = 16;
pub const UCHAR_IDEOGRAPHIC : UProperty = 17;
pub const UCHAR_IDS_BINARY_OPERATOR : UProperty = 18;
const UCHAR_IDS_TRINARY_OPERATOR : UProperty = 19;
const UCHAR_JOIN_CONTROL : UProperty = 20;
const UCHAR_LOGICAL_ORDER_EXCEPTION : UProperty = 21;
const UCHAR_LOWERCASE : UProperty = 22;
pub const UCHAR_IDS_TRINARY_OPERATOR : UProperty = 19;
pub const UCHAR_JOIN_CONTROL : UProperty = 20;
pub const UCHAR_LOGICAL_ORDER_EXCEPTION : UProperty = 21;
pub const UCHAR_LOWERCASE : UProperty = 22;
const UCHAR_MATH : UProperty = 23;
const UCHAR_NONCHARACTER_CODE_POINT : UProperty = 24;
const UCHAR_QUOTATION_MARK : UProperty = 25;
const UCHAR_RADICAL : UProperty = 26;
pub const UCHAR_MATH : UProperty = 23;
pub const UCHAR_NONCHARACTER_CODE_POINT : UProperty = 24;
pub const UCHAR_QUOTATION_MARK : UProperty = 25;
pub const UCHAR_RADICAL : UProperty = 26;
const UCHAR_SOFT_DOTTED : UProperty = 27;
const UCHAR_TERMINAL_PUNCTUATION : UProperty = 28;
const UCHAR_UNIFIED_IDEOGRAPH : UProperty = 29;
const UCHAR_UPPERCASE : UProperty = 30;
pub const UCHAR_SOFT_DOTTED : UProperty = 27;
pub const UCHAR_TERMINAL_PUNCTUATION : UProperty = 28;
pub const UCHAR_UNIFIED_IDEOGRAPH : UProperty = 29;
pub const UCHAR_UPPERCASE : UProperty = 30;
const UCHAR_WHITE_SPACE : UProperty = 31;
const UCHAR_XID_CONTINUE : UProperty = 32;
const UCHAR_XID_START : UProperty = 33;
const UCHAR_CASE_SENSITIVE : UProperty = 34;
pub const UCHAR_WHITE_SPACE : UProperty = 31;
pub const UCHAR_XID_CONTINUE : UProperty = 32;
pub const UCHAR_XID_START : UProperty = 33;
pub const UCHAR_CASE_SENSITIVE : UProperty = 34;
const UCHAR_S_TERM : UProperty = 35;
const UCHAR_VARIATION_SELECTOR : UProperty = 36;
const UCHAR_NFD_INERT : UProperty = 37;
const UCHAR_NFKD_INERT : UProperty = 38;
pub const UCHAR_S_TERM : UProperty = 35;
pub const UCHAR_VARIATION_SELECTOR : UProperty = 36;
pub const UCHAR_NFD_INERT : UProperty = 37;
pub const UCHAR_NFKD_INERT : UProperty = 38;
const UCHAR_NFC_INERT : UProperty = 39;
const UCHAR_NFKC_INERT : UProperty = 40;
const UCHAR_SEGMENT_STARTER : UProperty = 41;
const UCHAR_PATTERN_SYNTAX : UProperty = 42;
pub const UCHAR_NFC_INERT : UProperty = 39;
pub const UCHAR_NFKC_INERT : UProperty = 40;
pub const UCHAR_SEGMENT_STARTER : UProperty = 41;
pub const UCHAR_PATTERN_SYNTAX : UProperty = 42;
const UCHAR_PATTERN_WHITE_SPACE : UProperty = 43;
const UCHAR_POSIX_ALNUM : UProperty = 44;
const UCHAR_POSIX_BLANK : UProperty = 45;
const UCHAR_POSIX_GRAPH : UProperty = 46;
pub const UCHAR_PATTERN_WHITE_SPACE : UProperty = 43;
pub const UCHAR_POSIX_ALNUM : UProperty = 44;
pub const UCHAR_POSIX_BLANK : UProperty = 45;
pub const UCHAR_POSIX_GRAPH : UProperty = 46;
const UCHAR_POSIX_PRINT : UProperty = 47;
const UCHAR_POSIX_XDIGIT : UProperty = 48;
const UCHAR_CASED : UProperty = 49;
const UCHAR_CASE_IGNORABLE : UProperty = 50;
pub const UCHAR_POSIX_PRINT : UProperty = 47;
pub const UCHAR_POSIX_XDIGIT : UProperty = 48;
pub const UCHAR_CASED : UProperty = 49;
pub const UCHAR_CASE_IGNORABLE : UProperty = 50;
const UCHAR_CHANGES_WHEN_LOWERCASED : UProperty = 51;
const UCHAR_CHANGES_WHEN_UPPERCASED : UProperty = 52;
const UCHAR_CHANGES_WHEN_TITLECASED : UProperty = 53;
const UCHAR_CHANGES_WHEN_CASEFOLDED : UProperty = 54;
pub const UCHAR_CHANGES_WHEN_LOWERCASED : UProperty = 51;
pub const UCHAR_CHANGES_WHEN_UPPERCASED : UProperty = 52;
pub const UCHAR_CHANGES_WHEN_TITLECASED : UProperty = 53;
pub const UCHAR_CHANGES_WHEN_CASEFOLDED : UProperty = 54;
const UCHAR_CHANGES_WHEN_CASEMAPPED : UProperty = 55;
const UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED : UProperty = 56;
const UCHAR_BINARY_LIMIT : UProperty = 57;
const UCHAR_BIDI_CLASS : UProperty = 0x1000;
pub const UCHAR_CHANGES_WHEN_CASEMAPPED : UProperty = 55;
pub const UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED : UProperty = 56;
pub const UCHAR_BINARY_LIMIT : UProperty = 57;
pub const UCHAR_BIDI_CLASS : UProperty = 0x1000;
const UCHAR_INT_START : UProperty = 0x1000; // UCHAR_BIDI_CLASS
const UCHAR_BLOCK : UProperty = 0x1001;
const UCHAR_CANONICAL_COMBINING_CLASS : UProperty = 0x1002;
const UCHAR_DECOMPOSITION_TYPE : UProperty = 0x1003;
pub const UCHAR_INT_START : UProperty = 0x1000; // UCHAR_BIDI_CLASS
pub const UCHAR_BLOCK : UProperty = 0x1001;
pub const UCHAR_CANONICAL_COMBINING_CLASS : UProperty = 0x1002;
pub const UCHAR_DECOMPOSITION_TYPE : UProperty = 0x1003;
const UCHAR_EAST_ASIAN_WIDTH : UProperty = 0x1004;
const UCHAR_GENERAL_CATEGORY : UProperty = 0x1005;
const UCHAR_JOINING_GROUP : UProperty = 0x1006;
const UCHAR_JOINING_TYPE : UProperty = 0x1007;
pub const UCHAR_EAST_ASIAN_WIDTH : UProperty = 0x1004;
pub const UCHAR_GENERAL_CATEGORY : UProperty = 0x1005;
pub const UCHAR_JOINING_GROUP : UProperty = 0x1006;
pub const UCHAR_JOINING_TYPE : UProperty = 0x1007;
const UCHAR_LINE_BREAK : UProperty = 0x1008;
const UCHAR_NUMERIC_TYPE : UProperty = 0x1009;
const UCHAR_SCRIPT : UProperty = 0x100A;
const UCHAR_HANGUL_SYLLABLE_TYPE : UProperty = 0x100B;
pub const UCHAR_LINE_BREAK : UProperty = 0x1008;
pub const UCHAR_NUMERIC_TYPE : UProperty = 0x1009;
pub const UCHAR_SCRIPT : UProperty = 0x100A;
pub const UCHAR_HANGUL_SYLLABLE_TYPE : UProperty = 0x100B;
const UCHAR_NFD_QUICK_CHECK : UProperty = 0x100C;
const UCHAR_NFKD_QUICK_CHECK : UProperty = 0x100D;
const UCHAR_NFC_QUICK_CHECK : UProperty = 0x100E;
const UCHAR_NFKC_QUICK_CHECK : UProperty = 0x100F;
pub const UCHAR_NFD_QUICK_CHECK : UProperty = 0x100C;
pub const UCHAR_NFKD_QUICK_CHECK : UProperty = 0x100D;
pub const UCHAR_NFC_QUICK_CHECK : UProperty = 0x100E;
pub const UCHAR_NFKC_QUICK_CHECK : UProperty = 0x100F;
const UCHAR_LEAD_CANONICAL_COMBINING_CLASS : UProperty = 0x1010;
const UCHAR_TRAIL_CANONICAL_COMBINING_CLASS : UProperty = 0x1011;
const UCHAR_GRAPHEME_CLUSTER_BREAK : UProperty = 0x1012;
const UCHAR_SENTENCE_BREAK : UProperty = 0x1013;
pub const UCHAR_LEAD_CANONICAL_COMBINING_CLASS : UProperty = 0x1010;
pub const UCHAR_TRAIL_CANONICAL_COMBINING_CLASS : UProperty = 0x1011;
pub const UCHAR_GRAPHEME_CLUSTER_BREAK : UProperty = 0x1012;
pub const UCHAR_SENTENCE_BREAK : UProperty = 0x1013;
const UCHAR_WORD_BREAK : UProperty = 0x1014;
const UCHAR_INT_LIMIT : UProperty = 0x1015;
pub const UCHAR_WORD_BREAK : UProperty = 0x1014;
pub const UCHAR_INT_LIMIT : UProperty = 0x1015;
const UCHAR_GENERAL_CATEGORY_MASK : UProperty = 0x2000;
const UCHAR_MASK_START : UProperty = 0x2000;
pub const UCHAR_GENERAL_CATEGORY_MASK : UProperty = 0x2000;
pub const UCHAR_MASK_START : UProperty = 0x2000;
// = UCHAR_GENERAL_CATEGORY_MASK
const UCHAR_MASK_LIMIT : UProperty = 0x2001;
pub const UCHAR_MASK_LIMIT : UProperty = 0x2001;
const UCHAR_NUMERIC_VALUE : UProperty = 0x3000;
const UCHAR_DOUBLE_START : UProperty = 0x3000;
pub const UCHAR_NUMERIC_VALUE : UProperty = 0x3000;
pub const UCHAR_DOUBLE_START : UProperty = 0x3000;
// = UCHAR_NUMERIC_VALUE
const UCHAR_DOUBLE_LIMIT : UProperty = 0x3001;
pub const UCHAR_DOUBLE_LIMIT : UProperty = 0x3001;
const UCHAR_AGE : UProperty = 0x4000;
const UCHAR_STRING_START : UProperty = 0x4000; // = UCHAR_AGE
const UCHAR_BIDI_MIRRORING_GLYPH : UProperty = 0x4001;
const UCHAR_CASE_FOLDING : UProperty = 0x4002;
pub const UCHAR_AGE : UProperty = 0x4000;
pub const UCHAR_STRING_START : UProperty = 0x4000; // = UCHAR_AGE
pub const UCHAR_BIDI_MIRRORING_GLYPH : UProperty = 0x4001;
pub const UCHAR_CASE_FOLDING : UProperty = 0x4002;
const UCHAR_ISO_COMMENT : UProperty = 0x4003;
const UCHAR_LOWERCASE_MAPPING : UProperty = 0x4004;
const UCHAR_NAME : UProperty = 0x4005;
const UCHAR_SIMPLE_CASE_FOLDING : UProperty = 0x4006;
pub const UCHAR_ISO_COMMENT : UProperty = 0x4003;
pub const UCHAR_LOWERCASE_MAPPING : UProperty = 0x4004;
pub const UCHAR_NAME : UProperty = 0x4005;
pub const UCHAR_SIMPLE_CASE_FOLDING : UProperty = 0x4006;
const UCHAR_SIMPLE_LOWERCASE_MAPPING : UProperty = 0x4007;
const UCHAR_SIMPLE_TITLECASE_MAPPING : UProperty = 0x4008;
const UCHAR_SIMPLE_UPPERCASE_MAPPING : UProperty = 0x4009;
const UCHAR_TITLECASE_MAPPING : UProperty = 0x400A;
pub const UCHAR_SIMPLE_LOWERCASE_MAPPING : UProperty = 0x4007;
pub const UCHAR_SIMPLE_TITLECASE_MAPPING : UProperty = 0x4008;
pub const UCHAR_SIMPLE_UPPERCASE_MAPPING : UProperty = 0x4009;
pub const UCHAR_TITLECASE_MAPPING : UProperty = 0x400A;
const UCHAR_UNICODE_1_NAME : UProperty = 0x400B;
const UCHAR_UPPERCASE_MAPPING : UProperty = 0x400C;
const UCHAR_STRING_LIMIT : UProperty = 0x400D;
pub const UCHAR_UNICODE_1_NAME : UProperty = 0x400B;
pub const UCHAR_UPPERCASE_MAPPING : UProperty = 0x400C;
pub const UCHAR_STRING_LIMIT : UProperty = 0x400D;
const UCHAR_SCRIPT_EXTENSIONS : UProperty = 0x7000;
const UCHAR_OTHER_PROPERTY_START : UProperty = 0x7000;
pub const UCHAR_SCRIPT_EXTENSIONS : UProperty = 0x7000;
pub const UCHAR_OTHER_PROPERTY_START : UProperty = 0x7000;
// = UCHAR_SCRIPT_EXTENSIONS;
const UCHAR_OTHER_PROPERTY_LIMIT : UProperty = 0x7001;
pub const UCHAR_OTHER_PROPERTY_LIMIT : UProperty = 0x7001;
const UCHAR_INVALID_CODE : UProperty = -1;
pub const UCHAR_INVALID_CODE : UProperty = -1;
#[link_name = "icuuc"]
#[abi = "cdecl"]
extern mod libicu {
#[legacy_exports];
pub extern mod libicu {
pure fn u_hasBinaryProperty(c: UChar32, which: UProperty) -> UBool;
pure fn u_isdigit(c: UChar32) -> UBool;
pure fn u_islower(c: UChar32) -> UBool;
@ -163,12 +160,12 @@ mod icu {
}
}
pure fn is_XID_start(c: char) -> bool {
pub pure fn is_XID_start(c: char) -> bool {
return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START)
== icu::TRUE;
}
pure fn is_XID_continue(c: char) -> bool {
pub pure fn is_XID_continue(c: char) -> bool {
return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START)
== icu::TRUE;
}
@ -178,7 +175,7 @@ Function: is_digit
Returns true if a character is a digit.
*/
pure fn is_digit(c: char) -> bool {
pub pure fn is_digit(c: char) -> bool {
return icu::libicu::u_isdigit(c) == icu::TRUE;
}
@ -187,7 +184,7 @@ Function: is_lower
Returns true if a character is a lowercase letter.
*/
pure fn is_lower(c: char) -> bool {
pub pure fn is_lower(c: char) -> bool {
return icu::libicu::u_islower(c) == icu::TRUE;
}
@ -196,7 +193,7 @@ Function: is_space
Returns true if a character is space.
*/
pure fn is_space(c: char) -> bool {
pub pure fn is_space(c: char) -> bool {
return icu::libicu::u_isspace(c) == icu::TRUE;
}
@ -205,13 +202,12 @@ Function: is_upper
Returns true if a character is an uppercase letter.
*/
pure fn is_upper(c: char) -> bool {
pub pure fn is_upper(c: char) -> bool {
return icu::libicu::u_isupper(c) == icu::TRUE;
}
#[cfg(test)]
mod tests {
#[legacy_exports];
#[test]
fn test_is_digit() {

View file

@ -23,11 +23,6 @@
* facilities.
*/
use ll = uv_ll;
export ll;
use iotask = uv_iotask;
export iotask;
use global_loop = uv_global_loop;
export global_loop;
pub use ll = uv_ll;
pub use iotask = uv_iotask;
pub use global_loop = uv_global_loop;

View file

@ -1,9 +1,6 @@
//! A process-wide libuv event loop for library use.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
export get;
use ll = uv_ll;
use iotask = uv_iotask;
@ -16,7 +13,6 @@ use task::TaskBuilder;
use either::{Left, Right};
extern mod rustrt {
#[legacy_exports];
fn rust_uv_get_kernel_global_chan_ptr() -> *libc::uintptr_t;
}
@ -32,7 +28,7 @@ extern mod rustrt {
* * A `hl::high_level_loop` that encapsulates communication with the global
* loop.
*/
fn get() -> IoTask {
pub fn get() -> IoTask {
return get_monitor_task_gl();
}
@ -113,7 +109,6 @@ fn spawn_loop() -> IoTask {
#[cfg(test)]
mod test {
#[legacy_exports];
extern fn simple_timer_close_cb(timer_ptr: *ll::uv_timer_t) unsafe {
let exit_ch_ptr = ll::get_data_for_uv_handle(
timer_ptr as *libc::c_void) as *comm::Chan<bool>;
@ -139,11 +134,11 @@ mod test {
fn impl_uv_hl_simple_timer(iotask: IoTask) unsafe {
let exit_po = core::comm::Port::<bool>();
let exit_ch = core::comm::Chan(exit_po);
let exit_ch_ptr = ptr::addr_of(exit_ch);
let exit_ch_ptr = ptr::p2::addr_of(&exit_ch);
log(debug, fmt!("EXIT_CH_PTR newly created exit_ch_ptr: %?",
exit_ch_ptr));
let timer_handle = ll::timer_t();
let timer_ptr = ptr::addr_of(timer_handle);
let timer_ptr = ptr::p2::addr_of(&timer_handle);
do iotask::interact(iotask) |loop_ptr| unsafe {
log(debug, ~"user code inside interact loop!!!");
let init_status = ll::timer_init(loop_ptr, timer_ptr);

View file

@ -5,30 +5,24 @@
* `interact` function you can execute code in a uv callback.
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
export IoTask;
export spawn_iotask;
export interact;
export exit;
// tjc: forbid deprecated modes again after a snapshot
use libc::c_void;
use ptr::addr_of;
use ptr::p2::addr_of;
use comm = core::comm;
use comm::{Port, Chan, listen};
use task::TaskBuilder;
use ll = uv_ll;
/// Used to abstract-away direct interaction with a libuv loop.
enum IoTask {
pub enum IoTask {
IoTask_({
async_handle: *ll::uv_async_t,
op_chan: Chan<IoTaskMsg>
})
}
fn spawn_iotask(+task: task::TaskBuilder) -> IoTask {
pub fn spawn_iotask(task: task::TaskBuilder) -> IoTask {
do listen |iotask_ch| {
@ -65,7 +59,7 @@ fn spawn_iotask(+task: task::TaskBuilder) -> IoTask {
* module. It is not safe to send the `loop_ptr` param to this callback out
* via ports/chans.
*/
unsafe fn interact(iotask: IoTask,
pub unsafe fn interact(iotask: IoTask,
+cb: fn~(*c_void)) {
send_msg(iotask, Interaction(move cb));
}
@ -77,7 +71,7 @@ unsafe fn interact(iotask: IoTask,
* async handle and do a sanity check to make sure that all other handles are
* closed, causing a failure otherwise.
*/
fn exit(iotask: IoTask) unsafe {
pub fn exit(iotask: IoTask) unsafe {
send_msg(iotask, TeardownLoop);
}
@ -97,7 +91,7 @@ fn run_loop(iotask_ch: Chan<IoTask>) unsafe {
// set up the special async handle we'll use to allow multi-task
// communication with this loop
let async = ll::async_t();
let async_handle = addr_of(async);
let async_handle = addr_of(&async);
// associate the async handle with the loop
ll::async_init(loop_ptr, async_handle, wake_up_cb);
@ -107,7 +101,7 @@ fn run_loop(iotask_ch: Chan<IoTask>) unsafe {
async_handle: async_handle,
msg_po: Port()
};
ll::set_data_for_uv_handle(async_handle, addr_of(data));
ll::set_data_for_uv_handle(async_handle, addr_of(&data));
// Send out a handle through which folks can talk to us
// while we dwell in the I/O loop
@ -149,7 +143,7 @@ extern fn wake_up_cb(async_handle: *ll::uv_async_t,
while msg_po.peek() {
match msg_po.recv() {
Interaction(cb) => cb(loop_ptr),
Interaction(ref cb) => (*cb)(loop_ptr),
TeardownLoop => begin_teardown(data)
}
}
@ -171,7 +165,6 @@ extern fn tear_down_close_cb(handle: *ll::uv_async_t) unsafe {
#[cfg(test)]
mod test {
#[legacy_exports];
extern fn async_close_cb(handle: *ll::uv_async_t) unsafe {
log(debug, fmt!("async_close_cb handle %?", handle));
let exit_ch = (*(ll::get_data_for_uv_handle(handle)
@ -189,14 +182,14 @@ mod test {
};
fn impl_uv_iotask_async(iotask: IoTask) unsafe {
let async_handle = ll::async_t();
let ah_ptr = ptr::addr_of(async_handle);
let ah_ptr = ptr::addr_of(&async_handle);
let exit_po = core::comm::Port::<()>();
let exit_ch = core::comm::Chan(exit_po);
let ah_data = {
iotask: iotask,
exit_ch: exit_ch
};
let ah_data_ptr = ptr::addr_of(ah_data);
let ah_data_ptr = ptr::addr_of(&ah_data);
do interact(iotask) |loop_ptr| unsafe {
ll::async_init(loop_ptr, ah_ptr, async_handle_cb);
ll::set_data_for_uv_handle(ah_ptr, ah_data_ptr as *libc::c_void);

View file

@ -27,13 +27,13 @@ use comm = core::comm;
use ptr::to_unsafe_ptr;
// libuv struct mappings
type uv_ip4_addr = {
pub type uv_ip4_addr = {
ip: ~[u8],
port: int
};
type uv_ip6_addr = uv_ip4_addr;
pub type uv_ip6_addr = uv_ip4_addr;
enum uv_handle_type {
pub enum uv_handle_type {
UNKNOWN_HANDLE = 0,
UV_TCP,
UV_UDP,
@ -51,9 +51,9 @@ enum uv_handle_type {
UV_FS_EVENT
}
type handle_type = libc::c_uint;
pub type handle_type = libc::c_uint;
type uv_handle_fields = {
pub type uv_handle_fields = {
loop_handle: *libc::c_void,
type_: handle_type,
close_cb: *u8,
@ -61,7 +61,7 @@ type uv_handle_fields = {
};
// unix size: 8
type uv_err_t = {
pub type uv_err_t = {
code: libc::c_int,
sys_errno_: libc::c_int
};
@ -71,13 +71,13 @@ type uv_err_t = {
// in other types as a pointer to be used in other
// operations (so mostly treat it as opaque, once you
// have it in this form..)
type uv_stream_t = {
pub type uv_stream_t = {
fields: uv_handle_fields
};
// 64bit unix size: 272
#[cfg(unix)]
type uv_tcp_t = {
pub type uv_tcp_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -91,11 +91,11 @@ type uv_tcp_t = {
};
// 32bit unix size: 328 (164)
#[cfg(target_arch="x86_64")]
type uv_tcp_t_32bit_unix_riders = {
pub type uv_tcp_t_32bit_unix_riders = {
a29: *u8
};
#[cfg(target_arch="x86")]
type uv_tcp_t_32bit_unix_riders = {
pub type uv_tcp_t_32bit_unix_riders = {
a29: *u8, a30: *u8, a31: *u8,
a32: *u8, a33: *u8, a34: *u8,
a35: *u8, a36: *u8
@ -103,7 +103,7 @@ type uv_tcp_t_32bit_unix_riders = {
// 32bit win32 size: 240 (120)
#[cfg(windows)]
type uv_tcp_t = {
pub type uv_tcp_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -116,20 +116,20 @@ type uv_tcp_t = {
// unix size: 48
#[cfg(unix)]
type uv_connect_t = {
pub type uv_connect_t = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8
};
// win32 size: 88 (44)
#[cfg(windows)]
type uv_connect_t = {
pub type uv_connect_t = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
a08: *u8, a09: *u8, a10: *u8
};
// unix size: 16
type uv_buf_t = {
pub type uv_buf_t = {
base: *u8,
len: libc::size_t
};
@ -138,7 +138,7 @@ type uv_buf_t = {
// unix size: 144
#[cfg(unix)]
type uv_write_t = {
pub type uv_write_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -147,16 +147,16 @@ type uv_write_t = {
a14: uv_write_t_32bit_unix_riders
};
#[cfg(target_arch="x86_64")]
type uv_write_t_32bit_unix_riders = {
pub type uv_write_t_32bit_unix_riders = {
a13: *u8
};
#[cfg(target_arch="x86")]
type uv_write_t_32bit_unix_riders = {
pub type uv_write_t_32bit_unix_riders = {
a13: *u8, a14: *u8
};
// win32 size: 136 (68)
#[cfg(windows)]
type uv_write_t = {
pub type uv_write_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -166,7 +166,7 @@ type uv_write_t = {
// 64bit unix size: 120
// 32bit unix size: 152 (76)
#[cfg(unix)]
type uv_async_t = {
pub type uv_async_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -174,16 +174,16 @@ type uv_async_t = {
a11: uv_async_t_32bit_unix_riders
};
#[cfg(target_arch="x86_64")]
type uv_async_t_32bit_unix_riders = {
pub type uv_async_t_32bit_unix_riders = {
a10: *u8
};
#[cfg(target_arch="x86")]
type uv_async_t_32bit_unix_riders = {
pub type uv_async_t_32bit_unix_riders = {
a10: *u8, a11: *u8, a12: *u8, a13: *u8
};
// win32 size 132 (68)
#[cfg(windows)]
type uv_async_t = {
pub type uv_async_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -194,7 +194,7 @@ type uv_async_t = {
// 64bit unix size: 128
// 32bit unix size: 84
#[cfg(unix)]
type uv_timer_t = {
pub type uv_timer_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -202,17 +202,17 @@ type uv_timer_t = {
a11: uv_timer_t_32bit_unix_riders
};
#[cfg(target_arch="x86_64")]
type uv_timer_t_32bit_unix_riders = {
pub type uv_timer_t_32bit_unix_riders = {
a10: *u8, a11: *u8
};
#[cfg(target_arch="x86")]
type uv_timer_t_32bit_unix_riders = {
pub type uv_timer_t_32bit_unix_riders = {
a10: *u8, a11: *u8, a12: *u8, a13: *u8,
a14: *u8, a15: *u8, a16: *u8
};
// win32 size: 64
#[cfg(windows)]
type uv_timer_t = {
pub type uv_timer_t = {
fields: uv_handle_fields,
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8,
@ -220,7 +220,7 @@ type uv_timer_t = {
};
// unix size: 16
type sockaddr_in = {
pub type sockaddr_in = {
mut sin_family: u16,
mut sin_port: u16,
mut sin_addr: u32, // in_addr: this is an opaque, per-platform struct
@ -230,12 +230,12 @@ type sockaddr_in = {
// unix size: 28 .. FIXME #1645
// stuck with 32 becuse of rust padding structs?
#[cfg(target_arch="x86_64")]
type sockaddr_in6 = {
pub type sockaddr_in6 = {
a0: *u8, a1: *u8,
a2: *u8, a3: *u8
};
#[cfg(target_arch="x86")]
type sockaddr_in6 = {
pub type sockaddr_in6 = {
a0: *u8, a1: *u8,
a2: *u8, a3: *u8,
a4: *u8, a5: *u8,
@ -244,17 +244,16 @@ type sockaddr_in6 = {
// unix size: 28 .. FIXME #1645
// stuck with 32 becuse of rust padding structs?
type addr_in = addr_in_impl::addr_in;
pub type addr_in = addr_in_impl::addr_in;
#[cfg(unix)]
mod addr_in_impl {
#[legacy_exports];
pub mod addr_in_impl {
#[cfg(target_arch="x86_64")]
type addr_in = {
pub type addr_in = {
a0: *u8, a1: *u8,
a2: *u8, a3: *u8
};
#[cfg(target_arch="x86")]
type addr_in = {
pub type addr_in = {
a0: *u8, a1: *u8,
a2: *u8, a3: *u8,
a4: *u8, a5: *u8,
@ -262,65 +261,60 @@ mod addr_in_impl {
};
}
#[cfg(windows)]
mod addr_in_impl {
#[legacy_exports];
type addr_in = {
pub mod addr_in_impl {
pub type addr_in = {
a0: *u8, a1: *u8,
a2: *u8, a3: *u8
};
}
// unix size: 48, 32bit: 32
type addrinfo = addrinfo_impl::addrinfo;
pub type addrinfo = addrinfo_impl::addrinfo;
#[cfg(target_os="linux")]
mod addrinfo_impl {
#[legacy_exports];
pub mod addrinfo_impl {
#[cfg(target_arch="x86_64")]
type addrinfo = {
pub type addrinfo = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8
};
#[cfg(target_arch="x86")]
type addrinfo = {
pub type addrinfo = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8, a06: *u8, a07: *u8
};
}
#[cfg(target_os="macos")]
#[cfg(target_os="freebsd")]
mod addrinfo_impl {
#[legacy_exports];
type addrinfo = {
pub mod addrinfo_impl {
pub type addrinfo = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8
};
}
#[cfg(windows)]
mod addrinfo_impl {
#[legacy_exports];
type addrinfo = {
pub mod addrinfo_impl {
pub type addrinfo = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8,
a04: *u8, a05: *u8
};
}
// unix size: 72
type uv_getaddrinfo_t = {
pub type uv_getaddrinfo_t = {
a00: *u8, a01: *u8, a02: *u8, a03: *u8, a04: *u8, a05: *u8,
a06: *u8, a07: *u8, a08: *u8
};
mod uv_ll_struct_stubgen {
#[legacy_exports];
fn gen_stub_uv_tcp_t() -> uv_tcp_t {
pub mod uv_ll_struct_stubgen {
pub fn gen_stub_uv_tcp_t() -> uv_tcp_t {
return gen_stub_os();
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn gen_stub_os() -> uv_tcp_t {
pub fn gen_stub_os() -> uv_tcp_t {
return gen_stub_arch();
#[cfg(target_arch="x86_64")]
fn gen_stub_arch() -> uv_tcp_t {
pub fn gen_stub_arch() -> uv_tcp_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -345,7 +339,7 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(target_arch="x86")]
fn gen_stub_arch() -> uv_tcp_t {
pub fn gen_stub_arch() -> uv_tcp_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -373,7 +367,7 @@ mod uv_ll_struct_stubgen {
}
}
#[cfg(windows)]
fn gen_stub_os() -> uv_tcp_t {
pub fn gen_stub_os() -> uv_tcp_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -394,7 +388,7 @@ mod uv_ll_struct_stubgen {
}
}
#[cfg(unix)]
fn gen_stub_uv_connect_t() -> uv_connect_t {
pub fn gen_stub_uv_connect_t() -> uv_connect_t {
return {
a00: 0 as *u8, a01: 0 as *u8, a02: 0 as *u8,
a03: 0 as *u8,
@ -402,7 +396,7 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(windows)]
fn gen_stub_uv_connect_t() -> uv_connect_t {
pub fn gen_stub_uv_connect_t() -> uv_connect_t {
return {
a00: 0 as *u8, a01: 0 as *u8, a02: 0 as *u8,
a03: 0 as *u8,
@ -412,10 +406,10 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(unix)]
fn gen_stub_uv_async_t() -> uv_async_t {
pub fn gen_stub_uv_async_t() -> uv_async_t {
return gen_stub_arch();
#[cfg(target_arch = "x86_64")]
fn gen_stub_arch() -> uv_async_t {
pub fn gen_stub_arch() -> uv_async_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -430,7 +424,7 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(target_arch = "x86")]
fn gen_stub_arch() -> uv_async_t {
pub fn gen_stub_arch() -> uv_async_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -447,7 +441,7 @@ mod uv_ll_struct_stubgen {
}
}
#[cfg(windows)]
fn gen_stub_uv_async_t() -> uv_async_t {
pub fn gen_stub_uv_async_t() -> uv_async_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -461,10 +455,10 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(unix)]
fn gen_stub_uv_timer_t() -> uv_timer_t {
pub fn gen_stub_uv_timer_t() -> uv_timer_t {
return gen_stub_arch();
#[cfg(target_arch = "x86_64")]
fn gen_stub_arch() -> uv_timer_t {
pub fn gen_stub_arch() -> uv_timer_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -479,7 +473,7 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(target_arch = "x86")]
fn gen_stub_arch() -> uv_timer_t {
pub fn gen_stub_arch() -> uv_timer_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -498,7 +492,7 @@ mod uv_ll_struct_stubgen {
}
}
#[cfg(windows)]
fn gen_stub_uv_timer_t() -> uv_timer_t {
pub fn gen_stub_uv_timer_t() -> uv_timer_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -511,10 +505,10 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(unix)]
fn gen_stub_uv_write_t() -> uv_write_t {
pub fn gen_stub_uv_write_t() -> uv_write_t {
return gen_stub_arch();
#[cfg(target_arch="x86_64")]
fn gen_stub_arch() -> uv_write_t {
pub fn gen_stub_arch() -> uv_write_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -528,7 +522,7 @@ mod uv_ll_struct_stubgen {
};
}
#[cfg(target_arch="x86")]
fn gen_stub_arch() -> uv_write_t {
pub fn gen_stub_arch() -> uv_write_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -543,7 +537,7 @@ mod uv_ll_struct_stubgen {
}
}
#[cfg(windows)]
fn gen_stub_uv_write_t() -> uv_write_t {
pub fn gen_stub_uv_write_t() -> uv_write_t {
return { fields: { loop_handle: ptr::null(), type_: 0u32,
close_cb: ptr::null(),
mut data: ptr::null() },
@ -556,7 +550,7 @@ mod uv_ll_struct_stubgen {
a12: 0 as *u8
};
}
fn gen_stub_uv_getaddrinfo_t() -> uv_getaddrinfo_t {
pub fn gen_stub_uv_getaddrinfo_t() -> uv_getaddrinfo_t {
{
a00: 0 as *u8, a01: 0 as *u8, a02: 0 as *u8, a03: 0 as *u8,
a04: 0 as *u8, a05: 0 as *u8, a06: 0 as *u8, a07: 0 as *u8,
@ -567,7 +561,6 @@ mod uv_ll_struct_stubgen {
#[nolink]
extern mod rustrt {
#[legacy_exports];
// libuv public API
fn rust_uv_loop_new() -> *libc::c_void;
fn rust_uv_loop_delete(lp: *libc::c_void);
@ -686,32 +679,32 @@ extern mod rustrt {
fn rust_uv_helper_addr_in_size() -> libc::c_uint;
}
unsafe fn loop_new() -> *libc::c_void {
pub unsafe fn loop_new() -> *libc::c_void {
return rustrt::rust_uv_loop_new();
}
unsafe fn loop_delete(loop_handle: *libc::c_void) {
pub unsafe fn loop_delete(loop_handle: *libc::c_void) {
rustrt::rust_uv_loop_delete(loop_handle);
}
unsafe fn loop_refcount(loop_ptr: *libc::c_void) -> libc::c_int {
pub unsafe fn loop_refcount(loop_ptr: *libc::c_void) -> libc::c_int {
return rustrt::rust_uv_loop_refcount(loop_ptr);
}
unsafe fn run(loop_handle: *libc::c_void) {
pub unsafe fn run(loop_handle: *libc::c_void) {
rustrt::rust_uv_run(loop_handle);
}
unsafe fn close<T>(handle: *T, cb: *u8) {
pub unsafe fn close<T>(handle: *T, cb: *u8) {
rustrt::rust_uv_close(handle as *libc::c_void, cb);
}
unsafe fn tcp_init(loop_handle: *libc::c_void, handle: *uv_tcp_t)
pub unsafe fn tcp_init(loop_handle: *libc::c_void, handle: *uv_tcp_t)
-> libc::c_int {
return rustrt::rust_uv_tcp_init(loop_handle, handle);
}
// FIXME ref #2064
unsafe fn tcp_connect(connect_ptr: *uv_connect_t,
pub unsafe fn tcp_connect(connect_ptr: *uv_connect_t,
tcp_handle_ptr: *uv_tcp_t,
addr_ptr: *sockaddr_in,
after_connect_cb: *u8)
@ -722,7 +715,7 @@ unsafe fn tcp_connect(connect_ptr: *uv_connect_t,
after_connect_cb, addr_ptr);
}
// FIXME ref #2064
unsafe fn tcp_connect6(connect_ptr: *uv_connect_t,
pub unsafe fn tcp_connect6(connect_ptr: *uv_connect_t,
tcp_handle_ptr: *uv_tcp_t,
addr_ptr: *sockaddr_in6,
after_connect_cb: *u8)
@ -731,30 +724,30 @@ unsafe fn tcp_connect6(connect_ptr: *uv_connect_t,
after_connect_cb, addr_ptr);
}
// FIXME ref #2064
unsafe fn tcp_bind(tcp_server_ptr: *uv_tcp_t,
pub unsafe fn tcp_bind(tcp_server_ptr: *uv_tcp_t,
addr_ptr: *sockaddr_in) -> libc::c_int {
return rustrt::rust_uv_tcp_bind(tcp_server_ptr,
addr_ptr);
}
// FIXME ref #2064
unsafe fn tcp_bind6(tcp_server_ptr: *uv_tcp_t,
pub unsafe fn tcp_bind6(tcp_server_ptr: *uv_tcp_t,
addr_ptr: *sockaddr_in6) -> libc::c_int {
return rustrt::rust_uv_tcp_bind6(tcp_server_ptr,
addr_ptr);
}
unsafe fn listen<T>(stream: *T, backlog: libc::c_int,
pub unsafe fn listen<T>(stream: *T, backlog: libc::c_int,
cb: *u8) -> libc::c_int {
return rustrt::rust_uv_listen(stream as *libc::c_void, backlog, cb);
}
unsafe fn accept(server: *libc::c_void, client: *libc::c_void)
pub unsafe fn accept(server: *libc::c_void, client: *libc::c_void)
-> libc::c_int {
return rustrt::rust_uv_accept(server as *libc::c_void,
client as *libc::c_void);
}
unsafe fn write<T>(req: *uv_write_t, stream: *T,
pub unsafe fn write<T>(req: *uv_write_t, stream: *T,
buf_in: *~[uv_buf_t], cb: *u8) -> libc::c_int {
let buf_ptr = vec::raw::to_ptr(*buf_in);
let buf_cnt = vec::len(*buf_in) as i32;
@ -762,28 +755,28 @@ unsafe fn write<T>(req: *uv_write_t, stream: *T,
stream as *libc::c_void,
buf_ptr, buf_cnt, cb);
}
unsafe fn read_start(stream: *uv_stream_t, on_alloc: *u8,
pub unsafe fn read_start(stream: *uv_stream_t, on_alloc: *u8,
on_read: *u8) -> libc::c_int {
return rustrt::rust_uv_read_start(stream as *libc::c_void,
on_alloc, on_read);
}
unsafe fn read_stop(stream: *uv_stream_t) -> libc::c_int {
pub unsafe fn read_stop(stream: *uv_stream_t) -> libc::c_int {
return rustrt::rust_uv_read_stop(stream as *libc::c_void);
}
unsafe fn last_error(loop_handle: *libc::c_void) -> uv_err_t {
pub unsafe fn last_error(loop_handle: *libc::c_void) -> uv_err_t {
return rustrt::rust_uv_last_error(loop_handle);
}
unsafe fn strerror(err: *uv_err_t) -> *libc::c_char {
pub unsafe fn strerror(err: *uv_err_t) -> *libc::c_char {
return rustrt::rust_uv_strerror(err);
}
unsafe fn err_name(err: *uv_err_t) -> *libc::c_char {
pub unsafe fn err_name(err: *uv_err_t) -> *libc::c_char {
return rustrt::rust_uv_err_name(err);
}
unsafe fn async_init(loop_handle: *libc::c_void,
pub unsafe fn async_init(loop_handle: *libc::c_void,
async_handle: *uv_async_t,
cb: *u8) -> libc::c_int {
return rustrt::rust_uv_async_init(loop_handle,
@ -791,12 +784,12 @@ unsafe fn async_init(loop_handle: *libc::c_void,
cb);
}
unsafe fn async_send(async_handle: *uv_async_t) {
pub unsafe fn async_send(async_handle: *uv_async_t) {
return rustrt::rust_uv_async_send(async_handle);
}
unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t {
pub unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t {
let out_buf = { base: ptr::null(), len: 0 as libc::size_t };
let out_buf_ptr = ptr::addr_of(out_buf);
let out_buf_ptr = ptr::addr_of(&out_buf);
log(debug, fmt!("buf_init - input %u len %u out_buf: %u",
input as uint,
len as uint,
@ -814,21 +807,21 @@ unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t {
return out_buf;
//return result;
}
unsafe fn ip4_addr(ip: &str, port: int)
pub unsafe fn ip4_addr(ip: &str, port: int)
-> sockaddr_in {
do str::as_c_str(ip) |ip_buf| {
rustrt::rust_uv_ip4_addr(ip_buf as *u8,
port as libc::c_int)
}
}
unsafe fn ip6_addr(ip: &str, port: int)
pub unsafe fn ip6_addr(ip: &str, port: int)
-> sockaddr_in6 {
do str::as_c_str(ip) |ip_buf| {
rustrt::rust_uv_ip6_addr(ip_buf as *u8,
port as libc::c_int)
}
}
unsafe fn ip4_name(src: &sockaddr_in) -> ~str {
pub unsafe fn ip4_name(src: &sockaddr_in) -> ~str {
// ipv4 addr max size: 15 + 1 trailing null byte
let dst: ~[u8] = ~[0u8,0u8,0u8,0u8,0u8,0u8,0u8,0u8,
0u8,0u8,0u8,0u8,0u8,0u8,0u8,0u8];
@ -844,7 +837,7 @@ unsafe fn ip4_name(src: &sockaddr_in) -> ~str {
str::raw::from_buf(dst_buf)
}
}
unsafe fn ip6_name(src: &sockaddr_in6) -> ~str {
pub unsafe fn ip6_name(src: &sockaddr_in6) -> ~str {
// ipv6 addr max size: 45 + 1 trailing null byte
let dst: ~[u8] = ~[0u8,0u8,0u8,0u8,0u8,0u8,0u8,0u8,
0u8,0u8,0u8,0u8,0u8,0u8,0u8,0u8,
@ -865,19 +858,19 @@ unsafe fn ip6_name(src: &sockaddr_in6) -> ~str {
}
}
unsafe fn timer_init(loop_ptr: *libc::c_void,
pub unsafe fn timer_init(loop_ptr: *libc::c_void,
timer_ptr: *uv_timer_t) -> libc::c_int {
return rustrt::rust_uv_timer_init(loop_ptr, timer_ptr);
}
unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: uint,
pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: uint,
repeat: uint) -> libc::c_int {
return rustrt::rust_uv_timer_start(timer_ptr, cb, timeout as libc::c_uint,
repeat as libc::c_uint);
}
unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> libc::c_int {
pub unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> libc::c_int {
return rustrt::rust_uv_timer_stop(timer_ptr);
}
unsafe fn getaddrinfo(loop_ptr: *libc::c_void,
pub unsafe fn getaddrinfo(loop_ptr: *libc::c_void,
handle: *uv_getaddrinfo_t,
cb: *u8,
node_name_ptr: *u8,
@ -890,126 +883,127 @@ unsafe fn getaddrinfo(loop_ptr: *libc::c_void,
service_name_ptr,
hints)
}
unsafe fn freeaddrinfo(res: *addrinfo) {
pub unsafe fn freeaddrinfo(res: *addrinfo) {
rustrt::rust_uv_freeaddrinfo(res);
}
// libuv struct initializers
unsafe fn tcp_t() -> uv_tcp_t {
pub unsafe fn tcp_t() -> uv_tcp_t {
return uv_ll_struct_stubgen::gen_stub_uv_tcp_t();
}
unsafe fn connect_t() -> uv_connect_t {
pub unsafe fn connect_t() -> uv_connect_t {
return uv_ll_struct_stubgen::gen_stub_uv_connect_t();
}
unsafe fn write_t() -> uv_write_t {
pub unsafe fn write_t() -> uv_write_t {
return uv_ll_struct_stubgen::gen_stub_uv_write_t();
}
unsafe fn async_t() -> uv_async_t {
pub unsafe fn async_t() -> uv_async_t {
return uv_ll_struct_stubgen::gen_stub_uv_async_t();
}
unsafe fn timer_t() -> uv_timer_t {
pub unsafe fn timer_t() -> uv_timer_t {
return uv_ll_struct_stubgen::gen_stub_uv_timer_t();
}
unsafe fn getaddrinfo_t() -> uv_getaddrinfo_t {
pub unsafe fn getaddrinfo_t() -> uv_getaddrinfo_t {
return uv_ll_struct_stubgen::gen_stub_uv_getaddrinfo_t();
}
// data access helpers
unsafe fn get_loop_for_uv_handle<T>(handle: *T)
pub unsafe fn get_loop_for_uv_handle<T>(handle: *T)
-> *libc::c_void {
return rustrt::rust_uv_get_loop_for_uv_handle(handle as *libc::c_void);
}
unsafe fn get_stream_handle_from_connect_req(connect: *uv_connect_t)
pub unsafe fn get_stream_handle_from_connect_req(connect: *uv_connect_t)
-> *uv_stream_t {
return rustrt::rust_uv_get_stream_handle_from_connect_req(
connect);
}
unsafe fn get_stream_handle_from_write_req(
pub unsafe fn get_stream_handle_from_write_req(
write_req: *uv_write_t)
-> *uv_stream_t {
return rustrt::rust_uv_get_stream_handle_from_write_req(
write_req);
}
unsafe fn get_data_for_uv_loop(loop_ptr: *libc::c_void) -> *libc::c_void {
pub unsafe fn get_data_for_uv_loop(loop_ptr: *libc::c_void) -> *libc::c_void {
rustrt::rust_uv_get_data_for_uv_loop(loop_ptr)
}
unsafe fn set_data_for_uv_loop(loop_ptr: *libc::c_void, data: *libc::c_void) {
pub unsafe fn set_data_for_uv_loop(loop_ptr: *libc::c_void,
data: *libc::c_void) {
rustrt::rust_uv_set_data_for_uv_loop(loop_ptr, data);
}
unsafe fn get_data_for_uv_handle<T>(handle: *T) -> *libc::c_void {
pub unsafe fn get_data_for_uv_handle<T>(handle: *T) -> *libc::c_void {
return rustrt::rust_uv_get_data_for_uv_handle(handle as *libc::c_void);
}
unsafe fn set_data_for_uv_handle<T, U>(handle: *T,
pub unsafe fn set_data_for_uv_handle<T, U>(handle: *T,
data: *U) {
rustrt::rust_uv_set_data_for_uv_handle(handle as *libc::c_void,
data as *libc::c_void);
}
unsafe fn get_data_for_req<T>(req: *T) -> *libc::c_void {
pub unsafe fn get_data_for_req<T>(req: *T) -> *libc::c_void {
return rustrt::rust_uv_get_data_for_req(req as *libc::c_void);
}
unsafe fn set_data_for_req<T, U>(req: *T,
pub unsafe fn set_data_for_req<T, U>(req: *T,
data: *U) {
rustrt::rust_uv_set_data_for_req(req as *libc::c_void,
data as *libc::c_void);
}
unsafe fn get_base_from_buf(buf: uv_buf_t) -> *u8 {
pub unsafe fn get_base_from_buf(buf: uv_buf_t) -> *u8 {
return rustrt::rust_uv_get_base_from_buf(buf);
}
unsafe fn get_len_from_buf(buf: uv_buf_t) -> libc::size_t {
pub unsafe fn get_len_from_buf(buf: uv_buf_t) -> libc::size_t {
return rustrt::rust_uv_get_len_from_buf(buf);
}
unsafe fn malloc_buf_base_of(suggested_size: libc::size_t)
pub unsafe fn malloc_buf_base_of(suggested_size: libc::size_t)
-> *u8 {
return rustrt::rust_uv_malloc_buf_base_of(suggested_size);
}
unsafe fn free_base_of_buf(buf: uv_buf_t) {
pub unsafe fn free_base_of_buf(buf: uv_buf_t) {
rustrt::rust_uv_free_base_of_buf(buf);
}
unsafe fn get_last_err_info(uv_loop: *libc::c_void) -> ~str {
pub unsafe fn get_last_err_info(uv_loop: *libc::c_void) -> ~str {
let err = last_error(uv_loop);
let err_ptr = ptr::addr_of(err);
let err_ptr = ptr::addr_of(&err);
let err_name = str::raw::from_c_str(err_name(err_ptr));
let err_msg = str::raw::from_c_str(strerror(err_ptr));
return fmt!("LIBUV ERROR: name: %s msg: %s",
err_name, err_msg);
}
unsafe fn get_last_err_data(uv_loop: *libc::c_void) -> uv_err_data {
pub unsafe fn get_last_err_data(uv_loop: *libc::c_void) -> uv_err_data {
let err = last_error(uv_loop);
let err_ptr = ptr::addr_of(err);
let err_ptr = ptr::addr_of(&err);
let err_name = str::raw::from_c_str(err_name(err_ptr));
let err_msg = str::raw::from_c_str(strerror(err_ptr));
{ err_name: err_name, err_msg: err_msg }
}
type uv_err_data = {
pub type uv_err_data = {
err_name: ~str,
err_msg: ~str
};
unsafe fn is_ipv4_addrinfo(input: *addrinfo) -> bool {
pub unsafe fn is_ipv4_addrinfo(input: *addrinfo) -> bool {
rustrt::rust_uv_is_ipv4_addrinfo(input)
}
unsafe fn is_ipv6_addrinfo(input: *addrinfo) -> bool {
pub unsafe fn is_ipv6_addrinfo(input: *addrinfo) -> bool {
rustrt::rust_uv_is_ipv6_addrinfo(input)
}
unsafe fn get_INADDR_NONE() -> u32 {
pub unsafe fn get_INADDR_NONE() -> u32 {
rustrt::rust_uv_helper_get_INADDR_NONE()
}
unsafe fn get_next_addrinfo(input: *addrinfo) -> *addrinfo {
pub unsafe fn get_next_addrinfo(input: *addrinfo) -> *addrinfo {
rustrt::rust_uv_get_next_addrinfo(input)
}
unsafe fn addrinfo_as_sockaddr_in(input: *addrinfo) -> *sockaddr_in {
pub unsafe fn addrinfo_as_sockaddr_in(input: *addrinfo) -> *sockaddr_in {
rustrt::rust_uv_addrinfo_as_sockaddr_in(input)
}
unsafe fn addrinfo_as_sockaddr_in6(input: *addrinfo) -> *sockaddr_in6 {
pub unsafe fn addrinfo_as_sockaddr_in6(input: *addrinfo) -> *sockaddr_in6 {
rustrt::rust_uv_addrinfo_as_sockaddr_in6(input)
}
#[cfg(test)]
mod test {
#[legacy_exports];
pub mod test {
enum tcp_read_data {
tcp_read_eof,
tcp_read_more(~[u8]),
@ -1120,9 +1114,9 @@ mod test {
client_chan: *comm::Chan<~str>) unsafe {
let test_loop = loop_new();
let tcp_handle = tcp_t();
let tcp_handle_ptr = ptr::addr_of(tcp_handle);
let tcp_handle_ptr = ptr::addr_of(&tcp_handle);
let connect_handle = connect_t();
let connect_req_ptr = ptr::addr_of(connect_handle);
let connect_req_ptr = ptr::addr_of(&connect_handle);
// this is the persistent payload of data that we
// need to pass around to get this example to work.
@ -1138,12 +1132,12 @@ mod test {
// this is the enclosing record, we'll pass a ptr to
// this to C..
let write_handle = write_t();
let write_handle_ptr = ptr::addr_of(write_handle);
let write_handle_ptr = ptr::addr_of(&write_handle);
log(debug, fmt!("tcp req: tcp stream: %d write_handle: %d",
tcp_handle_ptr as int,
write_handle_ptr as int));
let client_data = { writer_handle: write_handle_ptr,
req_buf: ptr::addr_of(req_msg),
req_buf: ptr::addr_of(&req_msg),
read_chan: client_chan };
let tcp_init_result = tcp_init(
@ -1154,7 +1148,7 @@ mod test {
log(debug, ~"building addr...");
let addr = ip4_addr(ip, port);
// FIXME ref #2064
let addr_ptr = ptr::addr_of(addr);
let addr_ptr = ptr::addr_of(&addr);
log(debug, fmt!("after build addr in rust. port: %u",
addr.sin_port as uint));
@ -1169,10 +1163,10 @@ mod test {
// until its initialized
set_data_for_req(
connect_req_ptr as *libc::c_void,
ptr::addr_of(client_data) as *libc::c_void);
ptr::addr_of(&client_data) as *libc::c_void);
set_data_for_uv_handle(
tcp_handle_ptr as *libc::c_void,
ptr::addr_of(client_data) as *libc::c_void);
ptr::addr_of(&client_data) as *libc::c_void);
log(debug, ~"before run tcp req loop");
run(test_loop);
log(debug, ~"after run tcp req loop");
@ -1369,13 +1363,13 @@ mod test {
continue_chan: *comm::Chan<bool>) unsafe {
let test_loop = loop_new();
let tcp_server = tcp_t();
let tcp_server_ptr = ptr::addr_of(tcp_server);
let tcp_server_ptr = ptr::addr_of(&tcp_server);
let tcp_client = tcp_t();
let tcp_client_ptr = ptr::addr_of(tcp_client);
let tcp_client_ptr = ptr::addr_of(&tcp_client);
let server_write_req = write_t();
let server_write_req_ptr = ptr::addr_of(server_write_req);
let server_write_req_ptr = ptr::addr_of(&server_write_req);
let resp_str_bytes = str::to_bytes(server_resp_msg);
let resp_msg_ptr: *u8 = vec::raw::to_ptr(resp_str_bytes);
@ -1386,20 +1380,20 @@ mod test {
let continue_async_handle = async_t();
let continue_async_handle_ptr =
ptr::addr_of(continue_async_handle);
ptr::addr_of(&continue_async_handle);
let async_data =
{ continue_chan: continue_chan };
let async_data_ptr = ptr::addr_of(async_data);
let async_data_ptr = ptr::addr_of(&async_data);
let server_data: tcp_server_data = {
client: tcp_client_ptr,
server: tcp_server_ptr,
server_kill_msg: kill_server_msg,
server_resp_buf: ptr::addr_of(resp_msg),
server_resp_buf: ptr::addr_of(&resp_msg),
server_chan: server_chan,
server_write_req: server_write_req_ptr
};
let server_data_ptr = ptr::addr_of(server_data);
let server_data_ptr = ptr::addr_of(&server_data);
set_data_for_uv_handle(tcp_server_ptr as *libc::c_void,
server_data_ptr as *libc::c_void);
@ -1409,7 +1403,7 @@ mod test {
if (tcp_init_result == 0i32) {
let server_addr = ip4_addr(server_ip, server_port);
// FIXME ref #2064
let server_addr_ptr = ptr::addr_of(server_addr);
let server_addr_ptr = ptr::addr_of(&server_addr);
// uv_tcp_bind()
let bind_result = tcp_bind(tcp_server_ptr,
@ -1478,13 +1472,13 @@ mod test {
let continue_port = core::comm::Port::<bool>();
let continue_chan = core::comm::Chan::<bool>(continue_port);
let continue_chan_ptr = ptr::addr_of(continue_chan);
let continue_chan_ptr = ptr::addr_of(&continue_chan);
do task::spawn_sched(task::ManualThreads(1u)) {
do task::spawn_sched(task::ManualThreads(1)) {
impl_uv_tcp_server(bind_ip, port,
kill_server_msg,
server_resp_msg,
ptr::addr_of(server_chan),
ptr::addr_of(&server_chan),
continue_chan_ptr);
};
@ -1496,7 +1490,7 @@ mod test {
do task::spawn_sched(task::ManualThreads(1u)) {
impl_uv_tcp_request(request_ip, port,
kill_server_msg,
ptr::addr_of(client_chan));
ptr::addr_of(&client_chan));
};
let msg_from_client = core::comm::recv(server_port);
@ -1510,22 +1504,19 @@ mod test {
#[cfg(target_os="win32")]
#[cfg(target_os="darwin")]
#[cfg(target_os="linux")]
mod tcp_and_server_client_test {
#[legacy_exports];
pub mod tcp_and_server_client_test {
#[cfg(target_arch="x86_64")]
mod impl64 {
#[legacy_exports];
pub mod impl64 {
#[test]
fn test_uv_ll_tcp_server_and_request() unsafe {
pub fn test_uv_ll_tcp_server_and_request() unsafe {
impl_uv_tcp_server_and_request();
}
}
#[cfg(target_arch="x86")]
mod impl32 {
#[legacy_exports];
pub mod impl32 {
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_uv_ll_tcp_server_and_request() unsafe {
pub fn test_uv_ll_tcp_server_and_request() unsafe {
impl_uv_tcp_server_and_request();
}
}