<commit_before>// Implements http://rosettacode.org/wiki/Hamming_numbers
// port of one of the scala solutions
extern crate num;
use num::bigint::BigUint;
use std::cmp::min;
use std::sync::spsc_queue::Queue;
use std::iter::range_inclusive;

fn int_to_biguint(i: int) -> BigUint {
    FromPrimitive::from_int(i).unwrap()
}

#[cfg(not(test))]
fn main() {
    let mut hamming = Hamming::new(1691);

    println!("first 20 Hamming numbers")
    for _ in range_inclusive(0,19) {
        print!("{} ", hamming.next().unwrap());
    }

    println!("\n\n1691st Hamming number");
    println!("{}",hamming.nth(1691-20).unwrap())
}

struct Hamming {
    q2: Queue<BigUint>,
    q3: Queue<BigUint>,
    q5: Queue<BigUint>
}

impl Hamming {
    fn new(n: uint) -> Hamming {
        let h = Hamming {
            q2: Queue::new(n),
            q3: Queue::new(n),
            q5: Queue::new(n)
        };

        h.q2.push(int_to_biguint(1));
        h.q3.push(int_to_biguint(1));
        h.q5.push(int_to_biguint(1));

        h
    }

    fn enqueue(&self, n: BigUint) {
        self.q2.push(n * int_to_biguint(2));
        self.q3.push(n * int_to_biguint(3));
        self.q5.push(n * int_to_biguint(5));
    }

}

impl Iterator<BigUint> for Hamming {
    fn next(&mut self) -> Option<BigUint> {
        let (head2, head3, head5) =
            (   self.q2.peek().unwrap(),
                self.q3.peek().unwrap(),
                self.q5.peek().unwrap());

        let n = min(head2.clone(), min(head3.clone(), head5.clone()));

        if *head2 == n {self.q2.pop();}
        if *head3 == n {self.q3.pop();}
        if *head5 == n {self.q5.pop();}

        self.enqueue(n.clone());
        Some(n)
    }
}

#[test]
fn create() {
    let h = Hamming::new(5);
    h.q2.push(int_to_biguint(1));
    h.q2.push(int_to_biguint(2));
    h.q2.push(int_to_biguint(4));

    let _ = h.q2.peek();
    assert!(h.q2.pop().unwrap() == int_to_biguint(1));
}

#[test]
fn try_enqueue() {
    let h = Hamming::new(5);
    h.enqueue(int_to_biguint(1));
    h.enqueue(int_to_biguint(2));
    h.enqueue(int_to_biguint(3));

    assert!(h.q2.pop().unwrap() == int_to_biguint(1));
    assert!(h.q3.pop().unwrap() == int_to_biguint(1));
    assert!(h.q5.pop().unwrap() == int_to_biguint(1));
    assert!(h.q2.pop().unwrap() == int_to_biguint(2));
    assert!(h.q3.pop().unwrap() == int_to_biguint(3));
    assert!(h.q5.pop().unwrap() == int_to_biguint(5));
 }

#[test]
fn hamming_iter() {
    let mut hamming = Hamming::new(20);
    assert!(hamming.nth(19).unwrap() == int_to_biguint(36));
}<commit_msg>changed from range_inclusive to range to fight unused import warning<commit_after>// Implements http://rosettacode.org/wiki/Hamming_numbers
// port of one of the scala solutions
extern crate num;
use num::bigint::BigUint;
use std::cmp::min;
use std::sync::spsc_queue::Queue;

fn int_to_biguint(i: int) -> BigUint {
    FromPrimitive::from_int(i).unwrap()
}

#[cfg(not(test))]
fn main() {
    let mut hamming = Hamming::new(1691);

    println!("first 20 Hamming numbers")
    for _ in range(0,20) {
        print!("{} ", hamming.next().unwrap());
    }

    println!("\n\n1691st Hamming number");
    println!("{}",hamming.nth(1691-20).unwrap())
}

struct Hamming {
    q2: Queue<BigUint>,
    q3: Queue<BigUint>,
    q5: Queue<BigUint>
}

impl Hamming {
    fn new(n: uint) -> Hamming {
        let h = Hamming {
            q2: Queue::new(n),
            q3: Queue::new(n),
            q5: Queue::new(n)
        };

        h.q2.push(int_to_biguint(1));
        h.q3.push(int_to_biguint(1));
        h.q5.push(int_to_biguint(1));

        h
    }

    fn enqueue(&self, n: BigUint) {
        self.q2.push(n * int_to_biguint(2));
        self.q3.push(n * int_to_biguint(3));
        self.q5.push(n * int_to_biguint(5));
    }

}

impl Iterator<BigUint> for Hamming {
    fn next(&mut self) -> Option<BigUint> {
        let (head2, head3, head5) =
            (   self.q2.peek().unwrap(),
                self.q3.peek().unwrap(),
                self.q5.peek().unwrap());

        let n = min(head2.clone(), min(head3.clone(), head5.clone()));

        if *head2 == n {self.q2.pop();}
        if *head3 == n {self.q3.pop();}
        if *head5 == n {self.q5.pop();}

        self.enqueue(n.clone());
        Some(n)
    }
}

#[test]
fn create() {
    let h = Hamming::new(5);
    h.q2.push(int_to_biguint(1));
    h.q2.push(int_to_biguint(2));
    h.q2.push(int_to_biguint(4));

    let _ = h.q2.peek();
    assert!(h.q2.pop().unwrap() == int_to_biguint(1));
}

#[test]
fn try_enqueue() {
    let h = Hamming::new(5);
    h.enqueue(int_to_biguint(1));
    h.enqueue(int_to_biguint(2));
    h.enqueue(int_to_biguint(3));

    assert!(h.q2.pop().unwrap() == int_to_biguint(1));
    assert!(h.q3.pop().unwrap() == int_to_biguint(1));
    assert!(h.q5.pop().unwrap() == int_to_biguint(1));
    assert!(h.q2.pop().unwrap() == int_to_biguint(2));
    assert!(h.q3.pop().unwrap() == int_to_biguint(3));
    assert!(h.q5.pop().unwrap() == int_to_biguint(5));
 }

#[test]
fn hamming_iter() {
    let mut hamming = Hamming::new(20);
    assert!(hamming.nth(19).unwrap() == int_to_biguint(36));
}<|endoftext|>


<commit_before>use bson::Document as BsonDocument;
use bson;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags, OpReplyFlags};
use client::wire_protocol::header::{Header, OpCode};
use std::io::{Read, Write};
use std::mem;
use std::result::Result::{Ok, Err};

trait ByteLength {
    /// Calculates the number of bytes in the serialized version of the struct.
    fn byte_length(&self) -> Result<i32, String>;
}

impl ByteLength for BsonDocument {
    /// Gets the length of a BSON document.
    ///
    /// # Return value
    ///
    /// Returns the number of bytes in the serialized BSON document.
    fn byte_length(&self) -> Result<i32, String> {
        let mut temp_buffer = vec![];

        match bson::encode_document(&mut temp_buffer, self) {
            Ok(_) => Ok(temp_buffer.len() as i32),
            Err(_) => Err("unable to serialize BSON document".to_owned())
        }
    }
}

/// Represents a message in the MongoDB Wire Protocol.
pub enum Message {
    OpReply {
        header: Header,
        flags: OpReplyFlags,
        cursor_id: i64,
        starting_from: i32,
        number_returned: i32,
        documents: Vec<BsonDocument>,
    },
    OpInsert {
        header: Header,
        flags: OpInsertFlags,
        full_collection_name: String,
        documents: Vec<BsonDocument>,
    },
    OpQuery {
        header: Header,
        flags: OpQueryFlags,
        full_collection_name: String,
        number_to_skip: i32,
        number_to_return: i32,
        query: BsonDocument,
        return_field_selector: Option<BsonDocument>,
    },
}

impl Message {
    fn with_reply(header: Header, flags: i32, cursor_id: i64,
                  starting_from: i32, number_returned: i32,
                  documents: Vec<BsonDocument>) -> Message {
        Message::OpReply { header: header, flags: OpReplyFlags::from_i32(flags),
                           cursor_id: cursor_id, starting_from: starting_from,
                           number_returned: number_returned,
                           documents: documents }
    }

    pub fn with_insert(request_id: i32, flags: OpInsertFlags,
                       full_collection_name: String,
                       documents: Vec<BsonDocument>) -> Result<Message, String> {
        let header_length = mem::size_of::<Header>() as i32;
        let flags_length = mem::size_of::<i32>() as i32;

        // Add an extra byte after the string for null-termination.
        let string_length = full_collection_name.len() as i32 + 1;

        let mut total_length = header_length + flags_length + string_length;

        for bson in documents.iter() {
            total_length += match bson.byte_length() {
                Ok(i) => i,
                Err(_) => return Err("Unable to serialize documents".to_owned())
            }
        }

        let header = Header::with_insert(total_length, request_id);

        Ok(Message::OpInsert { header: header, flags: flags,
                               full_collection_name: full_collection_name,
                               documents: documents })
    }

    /// Constructs a new message request for a query.
    ///
    /// # Arguments
    ///
    /// `header_request_id` - The request ID to be placed in the message header.
    /// `flags` - Bit vector of query options.
    /// `full_collection_name` - The full qualified name of the collection,
    ///                          beginning with the database name and a dot.
    /// `number_to_skip` - The number of initial documents to skip over in the query
    ///                    results.
    /// `number_to_return - The total number of documents that should be returned by
    ///                     the query.
    /// `return_field_selector - An optional projection of which fields should be
    ///                          present in the documents to be returned by the
    ///                          query.
    ///
    /// # Return value
    ///
    /// Returns the newly-created Message.
    pub fn with_query(header_request_id: i32, flags: OpQueryFlags,
                     full_collection_name: String, number_to_skip: i32,
                     number_to_return: i32, query: BsonDocument,
                     return_field_selector: Option<BsonDocument>) -> Result<Message, String> {
        let header_length = mem::size_of::<Header>() as i32;

        // There are three i32 fields in the an OpQuery (since OpQueryFlags is
        // represented as an 32-bit vector in the wire protocol).
        let i32_length = 3 * mem::size_of::<i32>() as i32;

        // Add an extra byte after the string for null-termination.
        let string_length = full_collection_name.len() as i32 + 1;

        let bson_length = match query.byte_length() {
            Ok(i) => i,
            Err(_) => return Err("Unable to serialize query".to_owned())
        };

        // Add the length of the optional BSON document only if it exists.
        let option_length = match return_field_selector {
            Some(ref bson) => match bson.byte_length() {
                Ok(i) => i,
                Err(_) => return Err("Unable to serialize return_field_selector".to_owned())
            },
            None => 0
        };

        let total_length = header_length + i32_length + string_length +
                           bson_length + option_length;

        let header = Header::with_query(total_length, header_request_id);

        Ok(Message::OpQuery { header: header, flags: flags,
                              full_collection_name: full_collection_name,
                              number_to_skip: number_to_skip,
                              number_to_return: number_to_return, query: query,
                              return_field_selector: return_field_selector })
    }

    /// Writes a serialized BSON document to a given buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    /// `bson` - The document to serialize and write.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    fn write_bson_document(buffer: &mut Write, bson: &BsonDocument) -> Result<(), String>{
        let mut temp_buffer = vec![];

        match bson::encode_document(&mut temp_buffer, bson) {
            Ok(_) => match buffer.write(&temp_buffer) {
                Ok(_) => Ok(()),
                Err(_) => Err("unable to write BSON".to_owned())
            },
            Err(_) => Err("unable to encode BSON".to_owned())
        }
    }

    /// Writes a serialized query message to a given buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    /// `header` - The header for the given message.
    /// `flags` - Bit vector of query option.
    /// `full_collection_name` - The full qualified name of the collection,
    ///                          beginning with the database name and a dot.
    /// `number_to_skip` - The number of initial documents to skip over in the
    ///                    query results.
    /// `number_to_return - The total number of documents that should be
    ///                     returned by the query.
    /// `return_field_selector - An optional projection of which fields should
    ///                          be present in the documents to be returned by
    ///                          the query.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    fn write_query(buffer: &mut Write, header: &Header,
                   flags: &OpQueryFlags, full_collection_name: &str,
                   number_to_skip: i32, number_to_return: i32, query: &BsonDocument,
                   return_field_selector: &Option<BsonDocument>) -> Result<(), String> {
        match header.write(buffer) {
            Ok(_) => (),
            Err(e) => return Err(e)
        };

        match buffer.write_i32::<LittleEndian>(flags.to_i32()) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write flags".to_owned())
        };

        for byte in full_collection_name.bytes() {
            let _byte_reponse = match buffer.write_u8(byte) {
                Ok(_) => (),
                Err(_) => return Err("Unable to write full_collection_name".to_owned())
            };
        }

        // Writes the null terminator for the collection name string.
        match buffer.write_u8(0) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write full_collection_name".to_owned())
        };

        match buffer.write_i32::<LittleEndian>(number_to_skip) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write number_to_skip".to_owned())
        };

        match buffer.write_i32::<LittleEndian>(number_to_return) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write number_to_return".to_owned())
        };

        match Message::write_bson_document(buffer, query) {
            Ok(_) => (),
            Err(s) => return Err(format!("Unable to write query: {}", s))
        };

        match return_field_selector {
            &Some(ref bson) => match Message::write_bson_document(buffer, bson) {
                Ok(_) => (),
                Err(s) => {
                    let str = format!("Unable to write return_field_selector: {}", s);

                    return Err(str)
                }
            },
            &None => ()
        };

        let _ = buffer.flush();

        Ok(())
    }

    fn write_insert(buffer: &mut Write, header: &Header, flags: &OpInsertFlags,
                    full_collection_name: &str,
                    documents: &[BsonDocument]) -> Result<(), String> {
        match header.write(buffer) {
            Ok(_) => (),
            Err(e) => return Err(e)
        };

        match buffer.write_i32::<LittleEndian>(flags.to_i32()) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write flags".to_owned())
        };

        for byte in full_collection_name.bytes() {
            let _byte_reponse = match buffer.write_u8(byte) {
                Ok(_) => (),
                Err(_) => return Err("Unable to write full_collection_name".to_owned())
            };
        }

        // Writes the null terminator for the collection name string.
        match buffer.write_u8(0) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write full_collection_name".to_owned())
        };

        for bson in documents {
            match Message::write_bson_document(buffer, bson) {
                Ok(_) => (),
                Err(s) => return Err(format!("Unable to insert document: {}", s))
            };

        }

        let _ = buffer.flush();

        Ok(())
    }

    /// Attemps to write a serialized message to a buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    pub fn write(&self, buffer: &mut Write) -> Result<(), String> {
        match self {
            /// Only the server should sent replies
            &Message::OpReply {..} =>
                Err("OP_REPLY should not be sent by the client".to_owned()),
            &Message::OpInsert { ref header, ref flags,
                                 ref full_collection_name, ref documents,
            } => Message::write_insert(buffer, &header, &flags,
                                       &full_collection_name, &documents),
            &Message::OpQuery { ref header, ref flags, ref full_collection_name,
                                number_to_skip, number_to_return, ref query,
                                ref return_field_selector
            } => Message::write_query(buffer, &header, &flags,
                                      &full_collection_name, number_to_skip,
                                      number_to_return, &query,
                                      &return_field_selector)
        }
    }

    /// Reads a serialized reply message from a buffer
    ///
    /// Right now, this returns only the first BSON document from the
    /// response; if there are more, it ignores the rest, and if there are none,
    /// it fails.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to read from.
    ///
    /// # Return value
    ///
    /// Returns a single BSON document on success, or an error string on
    /// failure.
    fn read_reply(buffer: &mut Read, h: Header) -> Result<Message, String> {
        let mut length = h.message_length - mem::size_of::<Header>() as i32;

        let flags = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read flags".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let cid = match buffer.read_i64::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read cursor_id".to_owned())
        };

        length -= mem::size_of::<i64>() as i32;

        let sf = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read starting_from".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let nr = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read number_returned".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let mut v = vec![];

        while length > 0 {
            match bson::decode_document(buffer) {
                Ok(bson) => {
                    match bson.byte_length() {
                        Ok(i) => length -= i,
                        Err(e) => return Err(e)
                    };

                    v.push(bson);
                },
                Err(_) => return Err("Unable to read BSON".to_owned())
            }
        }

        Ok(Message::with_reply(h, flags, cid, sf, nr, v))
    }

    /// Attempts to read a serialized reply Message from a buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to read from.
    ///
    /// # Return value
    ///
    /// Returns a single BSON document on success, or an error string on
    /// failure.
    pub fn read<T>(buffer: &mut T) -> Result<Message, String> where T: Read + Write {
        let header = match Header::read(buffer) {
            Ok(h) => h,
            Err(s) => {
                let str = format!("Unable to read reply header: {}", s);

                return Err(str)
            }
        };

        match header.op_code {
            OpCode::Reply => {
                Message::read_reply(buffer, header)
            },
            opcode => {
                let s = opcode.to_string();
                Err(format!("Expected to read response but instead found: {}", s))
            }
        }
    }
}
<commit_msg>removed another unecessary variable<commit_after>use bson::Document as BsonDocument;
use bson;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use client::wire_protocol::flags::{OpInsertFlags, OpQueryFlags, OpReplyFlags};
use client::wire_protocol::header::{Header, OpCode};
use std::io::{Read, Write};
use std::mem;
use std::result::Result::{Ok, Err};

trait ByteLength {
    /// Calculates the number of bytes in the serialized version of the struct.
    fn byte_length(&self) -> Result<i32, String>;
}

impl ByteLength for BsonDocument {
    /// Gets the length of a BSON document.
    ///
    /// # Return value
    ///
    /// Returns the number of bytes in the serialized BSON document.
    fn byte_length(&self) -> Result<i32, String> {
        let mut temp_buffer = vec![];

        match bson::encode_document(&mut temp_buffer, self) {
            Ok(_) => Ok(temp_buffer.len() as i32),
            Err(_) => Err("unable to serialize BSON document".to_owned())
        }
    }
}

/// Represents a message in the MongoDB Wire Protocol.
pub enum Message {
    OpReply {
        header: Header,
        flags: OpReplyFlags,
        cursor_id: i64,
        starting_from: i32,
        number_returned: i32,
        documents: Vec<BsonDocument>,
    },
    OpInsert {
        header: Header,
        flags: OpInsertFlags,
        full_collection_name: String,
        documents: Vec<BsonDocument>,
    },
    OpQuery {
        header: Header,
        flags: OpQueryFlags,
        full_collection_name: String,
        number_to_skip: i32,
        number_to_return: i32,
        query: BsonDocument,
        return_field_selector: Option<BsonDocument>,
    },
}

impl Message {
    fn with_reply(header: Header, flags: i32, cursor_id: i64,
                  starting_from: i32, number_returned: i32,
                  documents: Vec<BsonDocument>) -> Message {
        Message::OpReply { header: header, flags: OpReplyFlags::from_i32(flags),
                           cursor_id: cursor_id, starting_from: starting_from,
                           number_returned: number_returned,
                           documents: documents }
    }

    pub fn with_insert(request_id: i32, flags: OpInsertFlags,
                       full_collection_name: String,
                       documents: Vec<BsonDocument>) -> Result<Message, String> {
        let header_length = mem::size_of::<Header>() as i32;
        let flags_length = mem::size_of::<i32>() as i32;

        // Add an extra byte after the string for null-termination.
        let string_length = full_collection_name.len() as i32 + 1;

        let mut total_length = header_length + flags_length + string_length;

        for bson in documents.iter() {
            total_length += match bson.byte_length() {
                Ok(i) => i,
                Err(_) => return Err("Unable to serialize documents".to_owned())
            }
        }

        let header = Header::with_insert(total_length, request_id);

        Ok(Message::OpInsert { header: header, flags: flags,
                               full_collection_name: full_collection_name,
                               documents: documents })
    }

    /// Constructs a new message request for a query.
    ///
    /// # Arguments
    ///
    /// `header_request_id` - The request ID to be placed in the message header.
    /// `flags` - Bit vector of query options.
    /// `full_collection_name` - The full qualified name of the collection,
    ///                          beginning with the database name and a dot.
    /// `number_to_skip` - The number of initial documents to skip over in the query
    ///                    results.
    /// `number_to_return - The total number of documents that should be returned by
    ///                     the query.
    /// `return_field_selector - An optional projection of which fields should be
    ///                          present in the documents to be returned by the
    ///                          query.
    ///
    /// # Return value
    ///
    /// Returns the newly-created Message.
    pub fn with_query(header_request_id: i32, flags: OpQueryFlags,
                     full_collection_name: String, number_to_skip: i32,
                     number_to_return: i32, query: BsonDocument,
                     return_field_selector: Option<BsonDocument>) -> Result<Message, String> {
        let header_length = mem::size_of::<Header>() as i32;

        // There are three i32 fields in the an OpQuery (since OpQueryFlags is
        // represented as an 32-bit vector in the wire protocol).
        let i32_length = 3 * mem::size_of::<i32>() as i32;

        // Add an extra byte after the string for null-termination.
        let string_length = full_collection_name.len() as i32 + 1;

        let bson_length = match query.byte_length() {
            Ok(i) => i,
            Err(_) => return Err("Unable to serialize query".to_owned())
        };

        // Add the length of the optional BSON document only if it exists.
        let option_length = match return_field_selector {
            Some(ref bson) => match bson.byte_length() {
                Ok(i) => i,
                Err(_) => return Err("Unable to serialize return_field_selector".to_owned())
            },
            None => 0
        };

        let total_length = header_length + i32_length + string_length +
                           bson_length + option_length;

        let header = Header::with_query(total_length, header_request_id);

        Ok(Message::OpQuery { header: header, flags: flags,
                              full_collection_name: full_collection_name,
                              number_to_skip: number_to_skip,
                              number_to_return: number_to_return, query: query,
                              return_field_selector: return_field_selector })
    }

    /// Writes a serialized BSON document to a given buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    /// `bson` - The document to serialize and write.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    fn write_bson_document(buffer: &mut Write, bson: &BsonDocument) -> Result<(), String>{
        let mut temp_buffer = vec![];

        match bson::encode_document(&mut temp_buffer, bson) {
            Ok(_) => match buffer.write(&temp_buffer) {
                Ok(_) => Ok(()),
                Err(_) => Err("unable to write BSON".to_owned())
            },
            Err(_) => Err("unable to encode BSON".to_owned())
        }
    }

    /// Writes a serialized query message to a given buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    /// `header` - The header for the given message.
    /// `flags` - Bit vector of query option.
    /// `full_collection_name` - The full qualified name of the collection,
    ///                          beginning with the database name and a dot.
    /// `number_to_skip` - The number of initial documents to skip over in the
    ///                    query results.
    /// `number_to_return - The total number of documents that should be
    ///                     returned by the query.
    /// `return_field_selector - An optional projection of which fields should
    ///                          be present in the documents to be returned by
    ///                          the query.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    fn write_query(buffer: &mut Write, header: &Header,
                   flags: &OpQueryFlags, full_collection_name: &str,
                   number_to_skip: i32, number_to_return: i32, query: &BsonDocument,
                   return_field_selector: &Option<BsonDocument>) -> Result<(), String> {
        match header.write(buffer) {
            Ok(_) => (),
            Err(e) => return Err(e)
        };

        match buffer.write_i32::<LittleEndian>(flags.to_i32()) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write flags".to_owned())
        };

        for byte in full_collection_name.bytes() {
            let _byte_reponse = match buffer.write_u8(byte) {
                Ok(_) => (),
                Err(_) => return Err("Unable to write full_collection_name".to_owned())
            };
        }

        // Writes the null terminator for the collection name string.
        match buffer.write_u8(0) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write full_collection_name".to_owned())
        };

        match buffer.write_i32::<LittleEndian>(number_to_skip) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write number_to_skip".to_owned())
        };

        match buffer.write_i32::<LittleEndian>(number_to_return) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write number_to_return".to_owned())
        };

        match Message::write_bson_document(buffer, query) {
            Ok(_) => (),
            Err(s) => return Err(format!("Unable to write query: {}", s))
        };

        match return_field_selector {
            &Some(ref bson) => match Message::write_bson_document(buffer, bson) {
                Ok(_) => (),
                Err(s) => {
                    let str = format!("Unable to write return_field_selector: {}", s);

                    return Err(str)
                }
            },
            &None => ()
        };

        let _ = buffer.flush();

        Ok(())
    }

    fn write_insert(buffer: &mut Write, header: &Header, flags: &OpInsertFlags,
                    full_collection_name: &str,
                    documents: &[BsonDocument]) -> Result<(), String> {
        match header.write(buffer) {
            Ok(_) => (),
            Err(e) => return Err(e)
        };

        match buffer.write_i32::<LittleEndian>(flags.to_i32()) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write flags".to_owned())
        };

        for byte in full_collection_name.bytes() {
            let _byte_reponse = match buffer.write_u8(byte) {
                Ok(_) => (),
                Err(_) => return Err("Unable to write full_collection_name".to_owned())
            };
        }

        // Writes the null terminator for the collection name string.
        match buffer.write_u8(0) {
            Ok(_) => (),
            Err(_) => return Err("Unable to write full_collection_name".to_owned())
        };

        for bson in documents {
            match Message::write_bson_document(buffer, bson) {
                Ok(_) => (),
                Err(s) => return Err(format!("Unable to insert document: {}", s))
            };

        }

        let _ = buffer.flush();

        Ok(())
    }

    /// Attemps to write a serialized message to a buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to write to.
    ///
    /// # Return value
    ///
    /// Returns nothing on success, or an error string on failure.
    pub fn write(&self, buffer: &mut Write) -> Result<(), String> {
        match self {
            /// Only the server should sent replies
            &Message::OpReply {..} =>
                Err("OP_REPLY should not be sent by the client".to_owned()),
            &Message::OpInsert { ref header, ref flags,
                                 ref full_collection_name, ref documents,
            } => Message::write_insert(buffer, &header, &flags,
                                       &full_collection_name, &documents),
            &Message::OpQuery { ref header, ref flags, ref full_collection_name,
                                number_to_skip, number_to_return, ref query,
                                ref return_field_selector
            } => Message::write_query(buffer, &header, &flags,
                                      &full_collection_name, number_to_skip,
                                      number_to_return, &query,
                                      &return_field_selector)
        }
    }

    /// Reads a serialized reply message from a buffer
    ///
    /// Right now, this returns only the first BSON document from the
    /// response; if there are more, it ignores the rest, and if there are none,
    /// it fails.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to read from.
    ///
    /// # Return value
    ///
    /// Returns a single BSON document on success, or an error string on
    /// failure.
    fn read_reply(buffer: &mut Read, h: Header) -> Result<Message, String> {
        let mut length = h.message_length - mem::size_of::<Header>() as i32;

        let flags = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read flags".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let cid = match buffer.read_i64::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read cursor_id".to_owned())
        };

        length -= mem::size_of::<i64>() as i32;

        let sf = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read starting_from".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let nr = match buffer.read_i32::<LittleEndian>() {
            Ok(i) => i,
            Err(_) => return Err("Unable to read number_returned".to_owned())
        };

        length -= mem::size_of::<i32>() as i32;

        let mut v = vec![];

        while length > 0 {
            match bson::decode_document(buffer) {
                Ok(bson) => {
                    match bson.byte_length() {
                        Ok(i) => length -= i,
                        Err(e) => return Err(e)
                    };

                    v.push(bson);
                },
                Err(_) => return Err("Unable to read BSON".to_owned())
            }
        }

        Ok(Message::with_reply(h, flags, cid, sf, nr, v))
    }

    /// Attempts to read a serialized reply Message from a buffer.
    ///
    /// # Arguments
    ///
    /// `buffer` - The buffer to read from.
    ///
    /// # Return value
    ///
    /// Returns a single BSON document on success, or an error string on
    /// failure.
    pub fn read<T>(buffer: &mut T) -> Result<Message, String> where T: Read + Write {
        let header = match Header::read(buffer) {
            Ok(h) => h,
            Err(s) => {
                let str = format!("Unable to read reply header: {}", s);

                return Err(str)
            }
        };

        match header.op_code {
            OpCode::Reply => {
                Message::read_reply(buffer, header)
            },
            opcode => {
                Err(format!("Expected to read response but instead found: {}",
                            opcode.to_string()))
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate emval_sys;

extern crate libc;

use emval_sys::*;

use std;
use std::mem::{transmute, size_of};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use std::ptr;

use self::libc::malloc;

pub static STR_ID: &'static str = "string\0";
pub static OBJ_ID: &'static str = "object\0";
pub static INT_ID: &'static str = "integer\0";
pub static DOUBLE_ID: &'static str = "double\0";

pub trait JSSerializable {
    fn id(&self) -> *const c_void;
    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE;
}

pub fn to_wire_type(data: usize) -> EM_GENERIC_WIRE_TYPE {
    let mut result: EM_GENERIC_WIRE_TYPE = 0f64;
    unsafe {
        ptr::write(transmute::<_, *mut usize>(&mut result as *mut f64), data);
    }

    result
}

impl JSSerializable for str {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_std_wstring(transmute(STR_ID.as_ptr()),
                                             size_of::<char>(),
                                             transmute(STR_ID.as_ptr()));
            }
        });

        unsafe {
            transmute(STR_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        let chars: Vec<char> = self.chars().collect();
        let len = chars.len();
        let bytes_len = len * size_of::<char>();
        println!("{}", len);
        unsafe {
            let s: *mut usize = malloc(size_of::<usize>() + bytes_len) as _;
            ptr::write(s, len);
            let c = s.offset(1) as *mut u8;
            ptr::copy(chars.as_ptr() as _, c, bytes_len);

            to_wire_type(transmute(s))
        }
    }
}

impl JSSerializable for isize {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_integer(transmute(INT_ID.as_ptr()),
                                         transmute(INT_ID.as_ptr()),
                                         size_of::<isize>(),
                                         std::isize::MIN as _,
                                         std::isize::MAX as _);
            }
        });

        unsafe {
            transmute(INT_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        unsafe {
            to_wire_type(transmute(*self))
        }
    }
}

impl JSSerializable for f64 {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_float(transmute(DOUBLE_ID.as_ptr()),
                                       transmute(DOUBLE_ID.as_ptr()),
                                       size_of::<f64>());
            }
        });

        unsafe {
            transmute(DOUBLE_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        *self
    }
}
<commit_msg>delete debug code<commit_after>extern crate emval_sys;

extern crate libc;

use emval_sys::*;

use std;
use std::mem::{transmute, size_of};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use std::ptr;

use self::libc::malloc;

pub static STR_ID: &'static str = "string\0";
pub static OBJ_ID: &'static str = "object\0";
pub static INT_ID: &'static str = "integer\0";
pub static DOUBLE_ID: &'static str = "double\0";

pub trait JSSerializable {
    fn id(&self) -> *const c_void;
    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE;
}

pub fn to_wire_type(data: usize) -> EM_GENERIC_WIRE_TYPE {
    let mut result: EM_GENERIC_WIRE_TYPE = 0f64;
    unsafe {
        ptr::write(transmute::<_, *mut usize>(&mut result as *mut f64), data);
    }

    result
}

impl JSSerializable for str {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_std_wstring(transmute(STR_ID.as_ptr()),
                                             size_of::<char>(),
                                             transmute(STR_ID.as_ptr()));
            }
        });

        unsafe {
            transmute(STR_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        let chars: Vec<char> = self.chars().collect();
        let len = chars.len();
        let bytes_len = len * size_of::<char>();
        unsafe {
            let s: *mut usize = malloc(size_of::<usize>() + bytes_len) as _;
            ptr::write(s, len);
            let c = s.offset(1) as *mut u8;
            ptr::copy(chars.as_ptr() as _, c, bytes_len);

            to_wire_type(transmute(s))
        }
    }
}

impl JSSerializable for isize {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_integer(transmute(INT_ID.as_ptr()),
                                         transmute(INT_ID.as_ptr()),
                                         size_of::<isize>(),
                                         std::isize::MIN as _,
                                         std::isize::MAX as _);
            }
        });

        unsafe {
            transmute(INT_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        unsafe {
            to_wire_type(transmute(*self))
        }
    }
}

impl JSSerializable for f64 {
    fn id(&self) -> *const c_void {
        static REGISTER: Once = ONCE_INIT;

        REGISTER.call_once(|| {
            unsafe {
                _embind_register_float(transmute(DOUBLE_ID.as_ptr()),
                                       transmute(DOUBLE_ID.as_ptr()),
                                       size_of::<f64>());
            }
        });

        unsafe {
            transmute(DOUBLE_ID.as_ptr())
        }
    }

    fn serialize(&self) -> EM_GENERIC_WIRE_TYPE {
        *self
    }
}
<|endoftext|>


<commit_before>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::cell::RefCell;
use std::collections::{HashSet, HashMap};
use std::dynamic_lib::DynamicLibrary;
use std::env;
use std::ffi::OsString;
use std::io::prelude::*;
use std::io;
use std::path::PathBuf;
use std::process::Command;
use std::str;
use std::sync::{Arc, Mutex};
use std::thunk::Thunk;

use testing;
use rustc_lint;
use rustc::session::{self, config};
use rustc::session::config::get_unstable_features_setting;
use rustc::session::search_paths::{SearchPaths, PathKind};
use rustc_back::tempdir::TempDir;
use rustc_driver::{driver, Compilation};
use syntax::codemap::CodeMap;
use syntax::diagnostic;

use core;
use clean;
use clean::Clean;
use fold::DocFolder;
use html::markdown;
use passes;
use visit_ast::RustdocVisitor;

pub fn run(input: &str,
           cfgs: Vec<String>,
           libs: SearchPaths,
           externs: core::Externs,
           mut test_args: Vec<String>,
           crate_name: Option<String>)
           -> isize {
    let input_path = PathBuf::from(input);
    let input = config::Input::File(input_path.clone());

    let sessopts = config::Options {
        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
                                              .parent().unwrap().to_path_buf()),
        search_paths: libs.clone(),
        crate_types: vec!(config::CrateTypeDylib),
        externs: externs.clone(),
        unstable_features: get_unstable_features_setting(),
        ..config::basic_options().clone()
    };

    let codemap = CodeMap::new();
    let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None, true);
    let span_diagnostic_handler =
    diagnostic::mk_span_handler(diagnostic_handler, codemap);

    let sess = session::build_session_(sessopts,
                                      Some(input_path.clone()),
                                      span_diagnostic_handler);
    rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));

    let mut cfg = config::build_configuration(&sess);
    cfg.extend(config::parse_cfgspecs(cfgs).into_iter());
    let krate = driver::phase_1_parse_input(&sess, cfg, &input);
    let krate = driver::phase_2_configure_and_expand(&sess, krate,
                                                     "rustdoc-test", None)
        .expect("phase_2_configure_and_expand aborted in rustdoc!");

    let inject_crate = should_inject_crate(&krate);

    let ctx = core::DocContext {
        krate: &krate,
        maybe_typed: core::NotTyped(sess),
        input: input,
        external_paths: RefCell::new(Some(HashMap::new())),
        external_traits: RefCell::new(None),
        external_typarams: RefCell::new(None),
        inlined: RefCell::new(None),
        populated_crate_impls: RefCell::new(HashSet::new()),
    };

    let mut v = RustdocVisitor::new(&ctx, None);
    v.visit(ctx.krate);
    let mut krate = v.clean(&ctx);
    match crate_name {
        Some(name) => krate.name = name,
        None => {}
    }
    let (krate, _) = passes::collapse_docs(krate);
    let (krate, _) = passes::unindent_comments(krate);

    let mut collector = Collector::new(krate.name.to_string(),
                                       libs,
                                       externs,
                                       false,
                                       inject_crate);
    collector.fold_crate(krate);

    test_args.insert(0, "rustdoctest".to_string());

    testing::test_main(&test_args,
                       collector.tests.into_iter().collect());
    0
}

// Look for #![doc(test(no_crate_inject))], used by crates in the std facade
fn should_inject_crate(krate: &::syntax::ast::Crate) -> bool {
    use syntax::attr::AttrMetaMethods;

    let mut inject_crate = true;

    for attr in &krate.attrs {
        if attr.check_name("doc") {
            for list in attr.meta_item_list().into_iter() {
                for attr in list {
                    if attr.check_name("test") {
                        for list in attr.meta_item_list().into_iter() {
                            for attr in list {
                                if attr.check_name("no_crate_inject") {
                                    inject_crate = false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return inject_crate;
}

#[allow(deprecated)]
fn runtest(test: &str, cratename: &str, libs: SearchPaths,
           externs: core::Externs,
           should_panic: bool, no_run: bool, as_test_harness: bool,
           inject_crate: bool) {
    // the test harness wants its own `main` & top level functions, so
    // never wrap the test in `fn main() { ... }`
    let test = maketest(test, Some(cratename), true, as_test_harness,
                        inject_crate);
    let input = config::Input::Str(test.to_string());

    let sessopts = config::Options {
        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
                                              .parent().unwrap().to_path_buf()),
        search_paths: libs,
        crate_types: vec!(config::CrateTypeExecutable),
        output_types: vec!(config::OutputTypeExe),
        externs: externs,
        cg: config::CodegenOptions {
            prefer_dynamic: true,
            .. config::basic_codegen_options()
        },
        test: as_test_harness,
        unstable_features: get_unstable_features_setting(),
        ..config::basic_options().clone()
    };

    // Shuffle around a few input and output handles here. We're going to pass
    // an explicit handle into rustc to collect output messages, but we also
    // want to catch the error message that rustc prints when it fails.
    //
    // We take our task-local stderr (likely set by the test runner) and replace
    // it with a sink that is also passed to rustc itself. When this function
    // returns the output of the sink is copied onto the output of our own task.
    //
    // The basic idea is to not use a default_handler() for rustc, and then also
    // not print things by default to the actual stderr.
    struct Sink(Arc<Mutex<Vec<u8>>>);
    impl Write for Sink {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            Write::write(&mut *self.0.lock().unwrap(), data)
        }
        fn flush(&mut self) -> io::Result<()> { Ok(()) }
    }
    struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
    impl Drop for Bomb {
        fn drop(&mut self) {
            let _ = self.1.write_all(&self.0.lock().unwrap());
        }
    }
    let data = Arc::new(Mutex::new(Vec::new()));
    let emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
    let old = io::set_panic(box Sink(data.clone()));
    let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));

    // Compile the code
    let codemap = CodeMap::new();
    let diagnostic_handler = diagnostic::mk_handler(true, box emitter);
    let span_diagnostic_handler =
        diagnostic::mk_span_handler(diagnostic_handler, codemap);

    let sess = session::build_session_(sessopts,
                                       None,
                                       span_diagnostic_handler);
    rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));

    let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
    let out = Some(outdir.path().to_path_buf());
    let cfg = config::build_configuration(&sess);
    let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
    let mut control = driver::CompileController::basic();
    if no_run {
        control.after_analysis.stop = Compilation::Stop;
    }
    driver::compile_input(sess, cfg, &input, &out, &None, None, control);

    if no_run { return }

    // Run the code!
    //
    // We're careful to prepend the *target* dylib search path to the child's
    // environment to ensure that the target loads the right libraries at
    // runtime. It would be a sad day if the *host* libraries were loaded as a
    // mistake.
    let mut cmd = Command::new(&outdir.path().join("rust_out"));
    let var = DynamicLibrary::envvar();
    let newpath = {
        let path = env::var_os(var).unwrap_or(OsString::new());
        let mut path = env::split_paths(&path).collect::<Vec<_>>();
        path.insert(0, libdir.clone());
        env::join_paths(path.iter()).unwrap()
    };
    cmd.env(var, &newpath);

    match cmd.output() {
        Err(e) => panic!("couldn't run the test: {}{}", e,
                        if e.kind() == io::ErrorKind::PermissionDenied {
                            " - maybe your tempdir is mounted with noexec?"
                        } else { "" }),
        Ok(out) => {
            if should_panic && out.status.success() {
                panic!("test executable succeeded when it should have failed");
            } else if !should_panic && !out.status.success() {
                panic!("test executable failed:\n{:?}",
                      str::from_utf8(&out.stdout));
            }
        }
    }
}

pub fn maketest(s: &str, cratename: Option<&str>, lints: bool,
                dont_insert_main: bool, inject_crate: bool) -> String {
    let (crate_attrs, everything_else) = partition_source(s);

    let mut prog = String::new();

    // First push any outer attributes from the example, assuming they
    // are intended to be crate attributes.
    prog.push_str(&crate_attrs);

    if lints {
        prog.push_str(r"
#![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
");
    }

    // Don't inject `extern crate std` because it's already injected by the
    // compiler.
    if !s.contains("extern crate") && inject_crate {
        match cratename {
            Some(cratename) => {
                if s.contains(cratename) {
                    prog.push_str(&format!("extern crate {};\n",
                                           cratename));
                }
            }
            None => {}
        }
    }
    if dont_insert_main || s.contains("fn main") {
        prog.push_str(&everything_else);
    } else {
        prog.push_str("fn main() {\n    ");
        prog.push_str(&everything_else.replace("\n", "\n    "));
        prog.push_str("\n}");
    }

    info!("final test program: {}", prog);

    return prog
}

fn partition_source(s: &str) -> (String, String) {
    use unicode::str::UnicodeStr;

    let mut after_header = false;
    let mut before = String::new();
    let mut after = String::new();

    for line in s.lines() {
        let trimline = line.trim();
        let header = trimline.is_whitespace() ||
            trimline.starts_with("#![feature");
        if !header || after_header {
            after_header = true;
            after.push_str(line);
            after.push_str("\n");
        } else {
            before.push_str(line);
            before.push_str("\n");
        }
    }

    return (before, after);
}

pub struct Collector {
    pub tests: Vec<testing::TestDescAndFn>,
    names: Vec<String>,
    libs: SearchPaths,
    externs: core::Externs,
    cnt: usize,
    use_headers: bool,
    current_header: Option<String>,
    cratename: String,
    inject_crate: bool
}

impl Collector {
    pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
               use_headers: bool, inject_crate: bool) -> Collector {
        Collector {
            tests: Vec::new(),
            names: Vec::new(),
            libs: libs,
            externs: externs,
            cnt: 0,
            use_headers: use_headers,
            current_header: None,
            cratename: cratename,
            inject_crate: inject_crate
        }
    }

    pub fn add_test(&mut self, test: String,
                    should_panic: bool, no_run: bool, should_ignore: bool,
                    as_test_harness: bool) {
        let name = if self.use_headers {
            let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
            format!("{}_{}", s, self.cnt)
        } else {
            format!("{}_{}", self.names.connect("::"), self.cnt)
        };
        self.cnt += 1;
        let libs = self.libs.clone();
        let externs = self.externs.clone();
        let cratename = self.cratename.to_string();
        let inject_crate = self.inject_crate;
        debug!("Creating test {}: {}", name, test);
        self.tests.push(testing::TestDescAndFn {
            desc: testing::TestDesc {
                name: testing::DynTestName(name),
                ignore: should_ignore,
                should_panic: testing::ShouldPanic::No, // compiler failures are test failures
            },
            testfn: testing::DynTestFn(Thunk::new(move|| {
                runtest(&test,
                        &cratename,
                        libs,
                        externs,
                        should_panic,
                        no_run,
                        as_test_harness,
                        inject_crate);
            }))
        });
    }

    pub fn register_header(&mut self, name: &str, level: u32) {
        if self.use_headers && level == 1 {
            // we use these headings as test names, so it's good if
            // they're valid identifiers.
            let name = name.chars().enumerate().map(|(i, c)| {
                    if (i == 0 && c.is_xid_start()) ||
                        (i != 0 && c.is_xid_continue()) {
                        c
                    } else {
                        '_'
                    }
                }).collect::<String>();

            // new header => reset count.
            self.cnt = 0;
            self.current_header = Some(name);
        }
    }
}

impl DocFolder for Collector {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        let pushed = match item.name {
            Some(ref name) if name.len() == 0 => false,
            Some(ref name) => { self.names.push(name.to_string()); true }
            None => false
        };
        match item.doc_value() {
            Some(doc) => {
                self.cnt = 0;
                markdown::find_testable_code(doc, &mut *self);
            }
            None => {}
        }
        let ret = self.fold_item_recur(item);
        if pushed {
            self.names.pop();
        }
        return ret;
    }
}
<commit_msg>Rollup merge of #23846 - rayglover:patch-rustdoc-stderr, r=alexcrichton<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::cell::RefCell;
use std::collections::{HashSet, HashMap};
use std::dynamic_lib::DynamicLibrary;
use std::env;
use std::ffi::OsString;
use std::io::prelude::*;
use std::io;
use std::path::PathBuf;
use std::process::Command;
use std::str;
use std::sync::{Arc, Mutex};
use std::thunk::Thunk;

use testing;
use rustc_lint;
use rustc::session::{self, config};
use rustc::session::config::get_unstable_features_setting;
use rustc::session::search_paths::{SearchPaths, PathKind};
use rustc_back::tempdir::TempDir;
use rustc_driver::{driver, Compilation};
use syntax::codemap::CodeMap;
use syntax::diagnostic;

use core;
use clean;
use clean::Clean;
use fold::DocFolder;
use html::markdown;
use passes;
use visit_ast::RustdocVisitor;

pub fn run(input: &str,
           cfgs: Vec<String>,
           libs: SearchPaths,
           externs: core::Externs,
           mut test_args: Vec<String>,
           crate_name: Option<String>)
           -> isize {
    let input_path = PathBuf::from(input);
    let input = config::Input::File(input_path.clone());

    let sessopts = config::Options {
        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
                                              .parent().unwrap().to_path_buf()),
        search_paths: libs.clone(),
        crate_types: vec!(config::CrateTypeDylib),
        externs: externs.clone(),
        unstable_features: get_unstable_features_setting(),
        ..config::basic_options().clone()
    };

    let codemap = CodeMap::new();
    let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None, true);
    let span_diagnostic_handler =
    diagnostic::mk_span_handler(diagnostic_handler, codemap);

    let sess = session::build_session_(sessopts,
                                      Some(input_path.clone()),
                                      span_diagnostic_handler);
    rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));

    let mut cfg = config::build_configuration(&sess);
    cfg.extend(config::parse_cfgspecs(cfgs).into_iter());
    let krate = driver::phase_1_parse_input(&sess, cfg, &input);
    let krate = driver::phase_2_configure_and_expand(&sess, krate,
                                                     "rustdoc-test", None)
        .expect("phase_2_configure_and_expand aborted in rustdoc!");

    let inject_crate = should_inject_crate(&krate);

    let ctx = core::DocContext {
        krate: &krate,
        maybe_typed: core::NotTyped(sess),
        input: input,
        external_paths: RefCell::new(Some(HashMap::new())),
        external_traits: RefCell::new(None),
        external_typarams: RefCell::new(None),
        inlined: RefCell::new(None),
        populated_crate_impls: RefCell::new(HashSet::new()),
    };

    let mut v = RustdocVisitor::new(&ctx, None);
    v.visit(ctx.krate);
    let mut krate = v.clean(&ctx);
    match crate_name {
        Some(name) => krate.name = name,
        None => {}
    }
    let (krate, _) = passes::collapse_docs(krate);
    let (krate, _) = passes::unindent_comments(krate);

    let mut collector = Collector::new(krate.name.to_string(),
                                       libs,
                                       externs,
                                       false,
                                       inject_crate);
    collector.fold_crate(krate);

    test_args.insert(0, "rustdoctest".to_string());

    testing::test_main(&test_args,
                       collector.tests.into_iter().collect());
    0
}

// Look for #![doc(test(no_crate_inject))], used by crates in the std facade
fn should_inject_crate(krate: &::syntax::ast::Crate) -> bool {
    use syntax::attr::AttrMetaMethods;

    let mut inject_crate = true;

    for attr in &krate.attrs {
        if attr.check_name("doc") {
            for list in attr.meta_item_list().into_iter() {
                for attr in list {
                    if attr.check_name("test") {
                        for list in attr.meta_item_list().into_iter() {
                            for attr in list {
                                if attr.check_name("no_crate_inject") {
                                    inject_crate = false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return inject_crate;
}

#[allow(deprecated)]
fn runtest(test: &str, cratename: &str, libs: SearchPaths,
           externs: core::Externs,
           should_panic: bool, no_run: bool, as_test_harness: bool,
           inject_crate: bool) {
    // the test harness wants its own `main` & top level functions, so
    // never wrap the test in `fn main() { ... }`
    let test = maketest(test, Some(cratename), true, as_test_harness,
                        inject_crate);
    let input = config::Input::Str(test.to_string());

    let sessopts = config::Options {
        maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
                                              .parent().unwrap().to_path_buf()),
        search_paths: libs,
        crate_types: vec!(config::CrateTypeExecutable),
        output_types: vec!(config::OutputTypeExe),
        externs: externs,
        cg: config::CodegenOptions {
            prefer_dynamic: true,
            .. config::basic_codegen_options()
        },
        test: as_test_harness,
        unstable_features: get_unstable_features_setting(),
        ..config::basic_options().clone()
    };

    // Shuffle around a few input and output handles here. We're going to pass
    // an explicit handle into rustc to collect output messages, but we also
    // want to catch the error message that rustc prints when it fails.
    //
    // We take our task-local stderr (likely set by the test runner) and replace
    // it with a sink that is also passed to rustc itself. When this function
    // returns the output of the sink is copied onto the output of our own task.
    //
    // The basic idea is to not use a default_handler() for rustc, and then also
    // not print things by default to the actual stderr.
    struct Sink(Arc<Mutex<Vec<u8>>>);
    impl Write for Sink {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            Write::write(&mut *self.0.lock().unwrap(), data)
        }
        fn flush(&mut self) -> io::Result<()> { Ok(()) }
    }
    struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
    impl Drop for Bomb {
        fn drop(&mut self) {
            let _ = self.1.write_all(&self.0.lock().unwrap());
        }
    }
    let data = Arc::new(Mutex::new(Vec::new()));
    let emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
    let old = io::set_panic(box Sink(data.clone()));
    let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));

    // Compile the code
    let codemap = CodeMap::new();
    let diagnostic_handler = diagnostic::mk_handler(true, box emitter);
    let span_diagnostic_handler =
        diagnostic::mk_span_handler(diagnostic_handler, codemap);

    let sess = session::build_session_(sessopts,
                                       None,
                                       span_diagnostic_handler);
    rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));

    let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
    let out = Some(outdir.path().to_path_buf());
    let cfg = config::build_configuration(&sess);
    let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
    let mut control = driver::CompileController::basic();
    if no_run {
        control.after_analysis.stop = Compilation::Stop;
    }
    driver::compile_input(sess, cfg, &input, &out, &None, None, control);

    if no_run { return }

    // Run the code!
    //
    // We're careful to prepend the *target* dylib search path to the child's
    // environment to ensure that the target loads the right libraries at
    // runtime. It would be a sad day if the *host* libraries were loaded as a
    // mistake.
    let mut cmd = Command::new(&outdir.path().join("rust_out"));
    let var = DynamicLibrary::envvar();
    let newpath = {
        let path = env::var_os(var).unwrap_or(OsString::new());
        let mut path = env::split_paths(&path).collect::<Vec<_>>();
        path.insert(0, libdir.clone());
        env::join_paths(path.iter()).unwrap()
    };
    cmd.env(var, &newpath);

    match cmd.output() {
        Err(e) => panic!("couldn't run the test: {}{}", e,
                        if e.kind() == io::ErrorKind::PermissionDenied {
                            " - maybe your tempdir is mounted with noexec?"
                        } else { "" }),
        Ok(out) => {
            if should_panic && out.status.success() {
                panic!("test executable succeeded when it should have failed");
            } else if !should_panic && !out.status.success() {
                panic!("test executable failed:\n{}\n{}",
                       str::from_utf8(&out.stdout).unwrap_or(""),
                       str::from_utf8(&out.stderr).unwrap_or(""));
            }
        }
    }
}

pub fn maketest(s: &str, cratename: Option<&str>, lints: bool,
                dont_insert_main: bool, inject_crate: bool) -> String {
    let (crate_attrs, everything_else) = partition_source(s);

    let mut prog = String::new();

    // First push any outer attributes from the example, assuming they
    // are intended to be crate attributes.
    prog.push_str(&crate_attrs);

    if lints {
        prog.push_str(r"
#![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
");
    }

    // Don't inject `extern crate std` because it's already injected by the
    // compiler.
    if !s.contains("extern crate") && inject_crate {
        match cratename {
            Some(cratename) => {
                if s.contains(cratename) {
                    prog.push_str(&format!("extern crate {};\n",
                                           cratename));
                }
            }
            None => {}
        }
    }
    if dont_insert_main || s.contains("fn main") {
        prog.push_str(&everything_else);
    } else {
        prog.push_str("fn main() {\n    ");
        prog.push_str(&everything_else.replace("\n", "\n    "));
        prog.push_str("\n}");
    }

    info!("final test program: {}", prog);

    return prog
}

fn partition_source(s: &str) -> (String, String) {
    use unicode::str::UnicodeStr;

    let mut after_header = false;
    let mut before = String::new();
    let mut after = String::new();

    for line in s.lines() {
        let trimline = line.trim();
        let header = trimline.is_whitespace() ||
            trimline.starts_with("#![feature");
        if !header || after_header {
            after_header = true;
            after.push_str(line);
            after.push_str("\n");
        } else {
            before.push_str(line);
            before.push_str("\n");
        }
    }

    return (before, after);
}

pub struct Collector {
    pub tests: Vec<testing::TestDescAndFn>,
    names: Vec<String>,
    libs: SearchPaths,
    externs: core::Externs,
    cnt: usize,
    use_headers: bool,
    current_header: Option<String>,
    cratename: String,
    inject_crate: bool
}

impl Collector {
    pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
               use_headers: bool, inject_crate: bool) -> Collector {
        Collector {
            tests: Vec::new(),
            names: Vec::new(),
            libs: libs,
            externs: externs,
            cnt: 0,
            use_headers: use_headers,
            current_header: None,
            cratename: cratename,
            inject_crate: inject_crate
        }
    }

    pub fn add_test(&mut self, test: String,
                    should_panic: bool, no_run: bool, should_ignore: bool,
                    as_test_harness: bool) {
        let name = if self.use_headers {
            let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
            format!("{}_{}", s, self.cnt)
        } else {
            format!("{}_{}", self.names.connect("::"), self.cnt)
        };
        self.cnt += 1;
        let libs = self.libs.clone();
        let externs = self.externs.clone();
        let cratename = self.cratename.to_string();
        let inject_crate = self.inject_crate;
        debug!("Creating test {}: {}", name, test);
        self.tests.push(testing::TestDescAndFn {
            desc: testing::TestDesc {
                name: testing::DynTestName(name),
                ignore: should_ignore,
                should_panic: testing::ShouldPanic::No, // compiler failures are test failures
            },
            testfn: testing::DynTestFn(Thunk::new(move|| {
                runtest(&test,
                        &cratename,
                        libs,
                        externs,
                        should_panic,
                        no_run,
                        as_test_harness,
                        inject_crate);
            }))
        });
    }

    pub fn register_header(&mut self, name: &str, level: u32) {
        if self.use_headers && level == 1 {
            // we use these headings as test names, so it's good if
            // they're valid identifiers.
            let name = name.chars().enumerate().map(|(i, c)| {
                    if (i == 0 && c.is_xid_start()) ||
                        (i != 0 && c.is_xid_continue()) {
                        c
                    } else {
                        '_'
                    }
                }).collect::<String>();

            // new header => reset count.
            self.cnt = 0;
            self.current_header = Some(name);
        }
    }
}

impl DocFolder for Collector {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        let pushed = match item.name {
            Some(ref name) if name.len() == 0 => false,
            Some(ref name) => { self.names.push(name.to_string()); true }
            None => false
        };
        match item.doc_value() {
            Some(doc) => {
                self.cnt = 0;
                markdown::find_testable_code(doc, &mut *self);
            }
            None => {}
        }
        let ret = self.fold_item_recur(item);
        if pushed {
            self.names.pop();
        }
        return ret;
    }
}
<|endoftext|>


<commit_before>use DocId;
use std::borrow::Borrow;
use std::borrow::BorrowMut;
use std::cmp::Ordering;

/// Expresses the outcome of a call to `DocSet`'s `.skip_next(...)`.
#[derive(PartialEq, Eq, Debug)]
pub enum SkipResult {
    /// target was in the docset
    Reached,
    /// target was not in the docset, skipping stopped as a greater element was found
    OverStep,
    /// the docset was entirely consumed without finding the target, nor any
    /// element greater than the target.
    End,
}

/// Represents an iterable set of sorted doc ids.
pub trait DocSet {
    /// Goes to the next element.
    /// `.advance(...)` needs to be called a first time to point to the correct
    /// element.
    fn advance(&mut self) -> bool;

    /// After skipping, position the iterator in such a way that `.doc()`
    /// will return a value greater than or equal to target.
    ///
    /// SkipResult expresses whether the `target value` was reached, overstepped,
    /// or if the `DocSet` was entirely consumed without finding any value
    /// greater or equal to the `target`.
    ///
    /// WARNING: Calling skip always advances the docset.
    /// More specifically, if the docset is already positionned on the target
    /// skipping will advance to the next position and return SkipResult::Overstep.
    ///
    fn skip_next(&mut self, target: DocId) -> SkipResult {
        if !self.advance() {
            return SkipResult::End;
        }
        loop {
            match self.doc().cmp(&target) {
                Ordering::Less => {
                    if !self.advance() {
                        return SkipResult::End;
                    }
                }
                Ordering::Equal => return SkipResult::Reached,
                Ordering::Greater => return SkipResult::OverStep,
            }
        }
    }

    fn fill_buffer(&mut self, buffer: &mut [DocId]) -> bool {
        for buffer_val in buffer.iter_mut() {
            if self.advance() {
                *buffer_val = self.doc();
            }
            else {
                return false;
            }
        }
        return true;
    }

    /// Returns the current document
    fn doc(&self) -> DocId;

    /// Advances the cursor to the next document
    /// None is returned if the iterator has `DocSet`
    /// has already been entirely consumed.
    fn next(&mut self) -> Option<DocId> {
        if self.advance() {
            Some(self.doc())
        } else {
            None
        }
    }

    /// Returns a best-effort hint of the
    /// length of the docset.
    fn size_hint(&self) -> usize;
}

impl<TDocSet: DocSet + ?Sized> DocSet for Box<TDocSet> {
    fn advance(&mut self) -> bool {
        let unboxed: &mut TDocSet = self.borrow_mut();
        unboxed.advance()
    }

    fn skip_next(&mut self, target: DocId) -> SkipResult {
        let unboxed: &mut TDocSet = self.borrow_mut();
        unboxed.skip_next(target)
    }

    fn doc(&self) -> DocId {
        let unboxed: &TDocSet = self.borrow();
        unboxed.doc()
    }

    fn size_hint(&self) -> usize {
        let unboxed: &TDocSet = self.borrow();
        unboxed.size_hint()
    }
}

impl<'a, TDocSet: DocSet> DocSet for &'a mut TDocSet {
    fn advance(&mut self) -> bool {
        let unref: &mut TDocSet = *self;
        unref.advance()
    }

    fn skip_next(&mut self, target: DocId) -> SkipResult {
        let unref: &mut TDocSet = *self;
        unref.skip_next(target)
    }

    fn doc(&self) -> DocId {
        let unref: &TDocSet = *self;
        unref.doc()
    }

    fn size_hint(&self) -> usize {
        let unref: &TDocSet = *self;
        unref.size_hint()
    }
}
<commit_msg>fill_buffer<commit_after>use DocId;
use std::borrow::Borrow;
use std::borrow::BorrowMut;
use std::cmp::Ordering;

/// Expresses the outcome of a call to `DocSet`'s `.skip_next(...)`.
#[derive(PartialEq, Eq, Debug)]
pub enum SkipResult {
    /// target was in the docset
    Reached,
    /// target was not in the docset, skipping stopped as a greater element was found
    OverStep,
    /// the docset was entirely consumed without finding the target, nor any
    /// element greater than the target.
    End,
}

/// Represents an iterable set of sorted doc ids.
pub trait DocSet {
    /// Goes to the next element.
    /// `.advance(...)` needs to be called a first time to point to the correct
    /// element.
    fn advance(&mut self) -> bool;

    /// After skipping, position the iterator in such a way that `.doc()`
    /// will return a value greater than or equal to target.
    ///
    /// SkipResult expresses whether the `target value` was reached, overstepped,
    /// or if the `DocSet` was entirely consumed without finding any value
    /// greater or equal to the `target`.
    ///
    /// WARNING: Calling skip always advances the docset.
    /// More specifically, if the docset is already positionned on the target
    /// skipping will advance to the next position and return SkipResult::Overstep.
    ///
    fn skip_next(&mut self, target: DocId) -> SkipResult {
        if !self.advance() {
            return SkipResult::End;
        }
        loop {
            match self.doc().cmp(&target) {
                Ordering::Less => {
                    if !self.advance() {
                        return SkipResult::End;
                    }
                }
                Ordering::Equal => return SkipResult::Reached,
                Ordering::Greater => return SkipResult::OverStep,
            }
        }
    }

    fn fill_buffer(&mut self, buffer: &mut [DocId]) -> usize {
        for (i, buffer_val) in buffer.iter_mut().enumerate() {
            if self.advance() {
                *buffer_val = self.doc();
            }
            else {
                return i;
            }
        }
        return buffer.len();
    }

    /// Returns the current document
    fn doc(&self) -> DocId;

    /// Advances the cursor to the next document
    /// None is returned if the iterator has `DocSet`
    /// has already been entirely consumed.
    fn next(&mut self) -> Option<DocId> {
        if self.advance() {
            Some(self.doc())
        } else {
            None
        }
    }

    /// Returns a best-effort hint of the
    /// length of the docset.
    fn size_hint(&self) -> usize;
}

impl<TDocSet: DocSet + ?Sized> DocSet for Box<TDocSet> {
    fn advance(&mut self) -> bool {
        let unboxed: &mut TDocSet = self.borrow_mut();
        unboxed.advance()
    }

    fn skip_next(&mut self, target: DocId) -> SkipResult {
        let unboxed: &mut TDocSet = self.borrow_mut();
        unboxed.skip_next(target)
    }

    fn doc(&self) -> DocId {
        let unboxed: &TDocSet = self.borrow();
        unboxed.doc()
    }

    fn size_hint(&self) -> usize {
        let unboxed: &TDocSet = self.borrow();
        unboxed.size_hint()
    }
}

impl<'a, TDocSet: DocSet> DocSet for &'a mut TDocSet {
    fn advance(&mut self) -> bool {
        let unref: &mut TDocSet = *self;
        unref.advance()
    }

    fn skip_next(&mut self, target: DocId) -> SkipResult {
        let unref: &mut TDocSet = *self;
        unref.skip_next(target)
    }

    fn doc(&self) -> DocId {
        let unref: &TDocSet = *self;
        unref.doc()
    }

    fn size_hint(&self) -> usize {
        let unref: &TDocSet = *self;
        unref.size_hint()
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that the simd_select intrinsics produces correct results.

#![feature(repr_simd, platform_intrinsics)]
#[allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct i32x4(pub i32, pub i32, pub i32, pub i32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct u32x4(pub u32, pub u32, pub u32, pub u32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct b8x4(pub i8, pub i8, pub i8, pub i8);

extern "platform-intrinsic" {
    fn simd_select<T, U>(x: T, a: U, b: U) -> U;
}

fn main() {
    let m0 = b8x4(!0, !0, !0, !0);
    let m1 = b8x4(0, 0, 0, 0);
    let m2 = b8x4(!0, !0, 0, 0);
    let m3 = b8x4(0, 0, !0, !0);
    let m4 = b8x4(!0, 0, !0, 0);

    unsafe {
        let a = i32x4(1, -2, 3, 4);
        let b = i32x4(5, 6, -7, 8);

        let r: i32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m2, a, b);
        let e = i32x4(1, -2, -7, 8);
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m3, a, b);
        let e = i32x4(5, 6, 3, 4);
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m4, a, b);
        let e = i32x4(1, 6, 3, 8);
        assert_eq!(r, e);
    }

    unsafe {
        let a = u32x4(1, 2, 3, 4);
        let b = u32x4(5, 6, 7, 8);

        let r: u32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m2, a, b);
        let e = u32x4(1, 2, 7, 8);
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m3, a, b);
        let e = u32x4(5, 6, 3, 4);
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m4, a, b);
        let e = u32x4(1, 6, 3, 8);
        assert_eq!(r, e);
    }

    unsafe {
        let a = f32x4(1., 2., 3., 4.);
        let b = f32x4(5., 6., 7., 8.);

        let r: f32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m2, a, b);
        let e = f32x4(1., 2., 7., 8.);
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m3, a, b);
        let e = f32x4(5., 6., 3., 4.);
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m4, a, b);
        let e = f32x4(1., 6., 3., 8.);
        assert_eq!(r, e);
    }

    unsafe {
        let t = !0 as i8;
        let f = 0 as i8;
        let a = b8x4(t, f, t, f);
        let b = b8x4(f, f, f, t);

        let r: b8x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m2, a, b);
        let e = b8x4(t, f, f, t);
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m3, a, b);
        let e = b8x4(f, f, t, f);
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m4, a, b);
        let e = b8x4(t, f, t, t);
        assert_eq!(r, e);
    }
}
<commit_msg>ignore emscripten in run-pass test<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten

// Test that the simd_select intrinsics produces correct results.

#![feature(repr_simd, platform_intrinsics)]
#[allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct i32x4(pub i32, pub i32, pub i32, pub i32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct u32x4(pub u32, pub u32, pub u32, pub u32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct b8x4(pub i8, pub i8, pub i8, pub i8);

extern "platform-intrinsic" {
    fn simd_select<T, U>(x: T, a: U, b: U) -> U;
}

fn main() {
    let m0 = b8x4(!0, !0, !0, !0);
    let m1 = b8x4(0, 0, 0, 0);
    let m2 = b8x4(!0, !0, 0, 0);
    let m3 = b8x4(0, 0, !0, !0);
    let m4 = b8x4(!0, 0, !0, 0);

    unsafe {
        let a = i32x4(1, -2, 3, 4);
        let b = i32x4(5, 6, -7, 8);

        let r: i32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m2, a, b);
        let e = i32x4(1, -2, -7, 8);
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m3, a, b);
        let e = i32x4(5, 6, 3, 4);
        assert_eq!(r, e);

        let r: i32x4 = simd_select(m4, a, b);
        let e = i32x4(1, 6, 3, 8);
        assert_eq!(r, e);
    }

    unsafe {
        let a = u32x4(1, 2, 3, 4);
        let b = u32x4(5, 6, 7, 8);

        let r: u32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m2, a, b);
        let e = u32x4(1, 2, 7, 8);
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m3, a, b);
        let e = u32x4(5, 6, 3, 4);
        assert_eq!(r, e);

        let r: u32x4 = simd_select(m4, a, b);
        let e = u32x4(1, 6, 3, 8);
        assert_eq!(r, e);
    }

    unsafe {
        let a = f32x4(1., 2., 3., 4.);
        let b = f32x4(5., 6., 7., 8.);

        let r: f32x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m2, a, b);
        let e = f32x4(1., 2., 7., 8.);
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m3, a, b);
        let e = f32x4(5., 6., 3., 4.);
        assert_eq!(r, e);

        let r: f32x4 = simd_select(m4, a, b);
        let e = f32x4(1., 6., 3., 8.);
        assert_eq!(r, e);
    }

    unsafe {
        let t = !0 as i8;
        let f = 0 as i8;
        let a = b8x4(t, f, t, f);
        let b = b8x4(f, f, f, t);

        let r: b8x4 = simd_select(m0, a, b);
        let e = a;
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m1, a, b);
        let e = b;
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m2, a, b);
        let e = b8x4(t, f, f, t);
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m3, a, b);
        let e = b8x4(f, f, t, f);
        assert_eq!(r, e);

        let r: b8x4 = simd_select(m4, a, b);
        let e = b8x4(t, f, t, t);
        assert_eq!(r, e);
    }
}
<|endoftext|>