CombinedText stringlengths 4 3.42M |
|---|
use std::cmp::{min, max};
use std::collections::{LinkedList, VecDeque};
use std::old_io::net::ip::SocketAddr;
use std::old_io::net::udp::UdpSocket;
use std::old_io::{IoResult, IoError, TimedOut, ConnectionFailed, EndOfFile, Closed, ConnectionReset};
use std::iter::{range_inclusive, repeat};
use std::num::SignedInt;
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, ExtensionType, HEADER_SIZE};
use rand;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{}", e) })
}
#[derive(PartialEq,Eq,Debug,Copy)]
enum SocketState {
New,
Connected,
SynSent,
FinReceived,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelaySample {
received_at: TimestampReceived,
sent_at: TimestampSender,
}
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: LinkedList<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the received FIN packet, if any
fin_seq_nr: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<DelaySample>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = rand::random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: LinkedList::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
fin_seq_nr: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(self.receiver_connection_id);
packet.set_seq_nr(self.seq_nr);
let mut len = 0;
let mut addr = self.connected_to;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = self.congestion_timeout;
for _ in (0u8..5) {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", other);
try!(self.socket.send_to(packet.bytes().as_slice(), other));
self.state = SocketState::SynSent;
// Validate response
self.socket.set_read_timeout(Some(syn_timeout));
match self.socket.recv_from(&mut buf) {
Ok((read, src)) => { len = read; addr = src; break; },
Err(ref e) if e.kind == TimedOut => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = Packet::decode(buf.slice_to(len));
if packet.get_type() != PacketType::State {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
try!(self.handle_packet(&packet, addr));
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
try!(self.recv_from(&mut buf));
}
// Nothing to do if the socket's already closed
if self.state == SocketState::Closed {
return Ok(());
}
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = SocketState::FinSent;
// Receive JAKE
while self.state != SocketState::Closed {
try!(self.recv_from(&mut buf));
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns `Closed` after receiving a FIN packet when the remaining
/// inflight packets are consumed.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(usize,SocketAddr)> {
if self.state == SocketState::Closed {
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == SocketState::ResetReceived {
return Err(IoError {
kind: Closed,
desc: "Connection reset",
detail: None,
});
}
match self.flush_incoming_buffer(buf) {
0 => self.recv(buf),
read => Ok((read, self.connected_to)),
}
}
fn recv(&mut self, buf: &mut[u8]) -> IoResult<(usize,SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.socket.set_read_timeout(Some(self.congestion_timeout));
}
let (read, src) = match self.socket.recv_from(&mut b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = Packet::decode(b.slice_to(read));
debug!("received {:?}", packet);
let shallow_clone = packet.shallow_clone();
if packet.get_type() == PacketType::Data && packet.seq_nr().wrapping_sub(self.ack_nr) >= 1 {
self.insert_into_buffer(packet);
}
if let Some(pkt) = try!(self.handle_packet(&shallow_clone, src)) {
let mut pkt = pkt;
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {:?}", pkt);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Remove packet in incoming buffer and update current acknowledgement
/// number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
let mut idx = 0;
// Check if there is any pending data from a partially flushed packet
if !self.pending_data.is_empty() {
let len = buf.clone_from_slice(self.pending_data.as_slice());
// If all the data in the pending data buffer fits the given output
// buffer, remove the corresponding packet from the incoming buffer
// and clear the pending data buffer
if len == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
return idx + len;
} else {
// Remove the bytes copied to the output buffer from the pending
// data buffer (i.e., pending -= output)
self.pending_data = self.pending_data.slice_from(len).to_vec();
}
}
// Copy the payload of as many packets in the incoming buffer as possible
while !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let len = min(buf.len() - idx, self.incoming_buffer[0].payload.len());
for i in (0..len) {
buf[idx] = self.incoming_buffer[0].payload[i];
idx += 1;
}
// Remove top packet if its payload fits the output buffer
if self.incoming_buffer[0].payload.len() == len {
self.advance_incoming_buffer();
} else {
self.pending_data.push_all(self.incoming_buffer[0].payload.slice_from(len));
}
// Stop if the output buffer is full
if buf.len() == idx {
return idx;
}
}
return idx;
}
/// Send data on socket to the remote peer. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8]) -> IoResult<()> {
if self.state == SocketState::Closed {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.payload = chunk.to_vec();
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Flush unsent packet queue
try!(self.send());
// Consume acknowledgements until latest packet
let mut buf = [0; BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(&mut buf));
}
Ok(())
}
/// Send every packet in the unsent packet queue.
fn send(&mut self) -> IoResult<()> {
let dst = self.connected_to;
while let Some(packet) = self.unsent_queue.pop_front() {
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
while self.curr_window + packet.len() as u32 > max_inflight {
let mut buf = [0; BUF_SIZE];
iotry!(self.recv_from(&mut buf));
}
let mut packet = packet;
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {:?}", packet);
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_ack_nr(self.ack_nr);
packet.set_seq_nr(self.seq_nr);
packet.set_connection_id(self.sender_connection_id);
for _ in (0u8..3) {
let t = now_microseconds();
packet.set_timestamp_microseconds(t);
packet.set_timestamp_difference_microseconds((t - self.last_acked_timestamp));
iotry!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
debug!("sent {:?}", packet);
}
}
fn update_base_delay(&mut self, v: i64, now: i64) {
use std::num::Int;
let minute_in_microseconds = 60 * 10.pow(6);
if self.base_delays.is_empty() || now - self.base_delays[0].received_at > minute_in_microseconds {
// Drop the oldest sample and save minimum for current minute
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_back();
}
self.base_delays.push_front(DelaySample{ received_at: now, sent_at: v });
} else {
// Replace sample for the current minute if the delay is lower
if v < self.base_delays[0].sent_at {
self.base_delays[0] = DelaySample{ received_at: now, sent_at: v};
}
}
}
/// Insert a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64, MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculate the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculate the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
match self.base_delays.iter().min_by(|&x| (x.received_at - x.sent_at).abs()) {
Some(ref x) => x.received_at - x.sent_at,
None => 0
}
}
/// Build the selective acknowledgment payload for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|&pkt| pkt.seq_nr() > self.ack_nr);
let mut sack = Vec::new();
for packet in stashed {
let diff = packet.seq_nr() - self.ack_nr - 2;
let byte = (diff / 8) as usize;
let bit = (diff % 8) as usize;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.extend(repeat(0).take((len / 4 + 1) * 4 - len));
}
return sack;
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
match self.send_window.iter().find(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(packet) => {
iotry!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
debug!("sent {:?}", packet);
}
}
}
/// Forget sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in range_inclusive(0, position) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> IoResult<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if (self.state, packet.get_type()) != (SocketState::New, PacketType::Syn) &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
self.remote_wnd_size = packet.wnd_size() as u32;
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(SocketState::SynSent, PacketType::State) => {
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
})
}
(SocketState::Connected, PacketType::Syn) => Ok(None), // ignore
(SocketState::Connected, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) => {
self.state = SocketState::FinReceived;
self.fin_seq_nr = packet.seq_nr();
// If all packets are received and handled
if self.no_pending_data() && self.ack_nr == self.fin_seq_nr
{
self.state = SocketState::Closed;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
} else {
debug!("FIN received but there are missing packets");
Ok(None)
}
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
})
},
(state, ty) => panic!("Unimplemented handling for ({:?},{:?})", state, ty)
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(Some(sack));
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay.abs() - min_base_delay.abs();
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
let flightsize = self.curr_window;
self.cwnd += (GAIN * off_target * bytes_newly_acked as f64 * MSS as f64 / self.cwnd as f64) as u32;
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update base and current delay
let now = now_microseconds() as i64;
self.update_base_delay(packet.timestamp_microseconds() as i64, now);
self.update_current_delay(packet.timestamp_difference_microseconds() as i64, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
// Update congestion window size
self.update_congestion_window(off_target, packet.len() as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
let bits = extension.iter();
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
let bits = extension.iter();
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = packet.ack_nr() + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if !self.send_window.is_empty() &&
seq_nr < self.send_window.last().unwrap().seq_nr()
{
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 {
for i in (0..self.send_window.len()) {
let seq_nr = self.send_window[i].seq_nr();
if seq_nr <= packet.ack_nr() { continue; }
self.resend_lost_packet(seq_nr);
}
}
// Success, advance send window
self.advance_send_window();
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if pkt.seq_nr() >= packet.seq_nr() {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].seq_nr() == packet.seq_nr() {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
/// Checks whether there is pending data (to be returned on a `recv_from` call) on the socket
fn no_pending_data(&self) -> bool {
self.pending_data.is_empty() && self.incoming_buffer.is_empty()
}
}
#[cfg(test)]
mod test {
use std::old_io::test::next_test_ip4;
use std::old_io::{EndOfFile, Closed};
use std::old_io::net::udp::UdpSocket;
use std::thread;
use super::{UtpSocket, SocketState, BUF_SIZE};
use packet::{Packet, PacketType};
use util::now_microseconds;
use rand;
#[test]
fn test_socket_ipv4() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == SocketState::Connected);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Connected);
// Closing the connection is fine
match server.recv_from(&mut buf) {
Err(e) => panic!("{}", e),
_ => {},
}
assert_eq!(server.state, SocketState::Closed);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(&mut buf) {
Err(e) => assert_eq!(e.kind, EndOfFile),
v => panic!("expected {:?}, got {:?}", EndOfFile, v),
}
assert_eq!(server.state, SocketState::Closed);
// Trying again raises a EndOfFile error
match server.recv_from(&mut buf) {
Err(e) => assert_eq!(e.kind, EndOfFile),
v => panic!("expected {:?}, got {:?}", EndOfFile, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
thread::spawn(move || {
let client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut buf = [0u8; BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(&mut buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert!(server.state == SocketState::Connected);
iotry!(server.close());
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(&buf) {
Err(e) => assert_eq!(e.kind, Closed),
v => panic!("expected {:?}, got {:?}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(client_addr));
let server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut s = client.socket;
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>().as_slice().chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(window[3].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[2].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[1].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[0].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[4].bytes().as_slice(), server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UdpSocket::bind(client_addr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = Packet::decode(&test_syn_raw);
let seq_nr = test_syn_pkt.seq_nr();
thread::spawn(move || {
let mut client = client;
iotry!(client.send_to(&test_syn_raw, server_addr));
client.set_timeout(Some(10));
let mut buf = [0; BUF_SIZE];
let packet = match client.recv_from(&mut buf) {
Ok((nread, _src)) => Packet::decode(buf.slice_to(nread)),
Err(e) => panic!("{}", e),
};
assert_eq!(packet.ack_nr(), seq_nr);
drop(client);
});
let mut server = server;
let mut buf = [0; 20];
iotry!(server.recv_from(&mut buf));
assert!(server.ack_nr != 0);
assert_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(d.as_slice()));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(&mut buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => {
data_packet = Packet::decode(buf.slice_to(read));
assert!(data_packet.get_type() == PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => panic!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), client_addr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = Packet::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(d.as_slice()));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{:?}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut s = client.socket.clone();
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(s.send_to(packet.bytes().as_slice(), server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1,2,3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_selective_ack_response() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
// Client
thread::spawn(move || {
let client = iotry!(UtpSocket::bind(client_addr));
let mut client = iotry!(client.connect(server_addr));
client.congestion_timeout = 50;
iotry!(client.send_to(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(server_addr));
let mut buf = [0; BUF_SIZE];
// Connect
iotry!(server.recv_from(&mut buf));
// Discard packets
iotry!(server.socket.recv_from(&mut buf));
iotry!(server.socket.recv_from(&mut buf));
iotry!(server.socket.recv_from(&mut buf));
// Generate SACK
let mut packet = Packet::new();
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr - 1);
packet.set_connection_id(server.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::State);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert!(!received.is_empty());
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_correct_packet_loss() {
let (client_addr, server_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let client = iotry!(UtpSocket::bind(client_addr));
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(to_send.as_slice()));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => (),
Ok((len, _src)) => read.push_all(small_buffer.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(client.connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(to_send.as_slice()));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
}
Workaround for meaninglessly large cwnd increases.
use std::cmp::{min, max};
use std::collections::{LinkedList, VecDeque};
use std::old_io::net::ip::SocketAddr;
use std::old_io::net::udp::UdpSocket;
use std::old_io::{IoResult, IoError, TimedOut, ConnectionFailed, EndOfFile, Closed, ConnectionReset};
use std::iter::{range_inclusive, repeat};
use std::num::SignedInt;
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, ExtensionType, HEADER_SIZE};
use rand;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{}", e) })
}
#[derive(PartialEq,Eq,Debug,Copy)]
enum SocketState {
New,
Connected,
SynSent,
FinReceived,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelaySample {
received_at: TimestampReceived,
sent_at: TimestampSender,
}
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: LinkedList<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the received FIN packet, if any
fin_seq_nr: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<DelaySample>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = rand::random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: LinkedList::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
fin_seq_nr: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(self.receiver_connection_id);
packet.set_seq_nr(self.seq_nr);
let mut len = 0;
let mut addr = self.connected_to;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = self.congestion_timeout;
for _ in (0u8..5) {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", other);
try!(self.socket.send_to(packet.bytes().as_slice(), other));
self.state = SocketState::SynSent;
// Validate response
self.socket.set_read_timeout(Some(syn_timeout));
match self.socket.recv_from(&mut buf) {
Ok((read, src)) => { len = read; addr = src; break; },
Err(ref e) if e.kind == TimedOut => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = Packet::decode(buf.slice_to(len));
if packet.get_type() != PacketType::State {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
try!(self.handle_packet(&packet, addr));
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
try!(self.recv_from(&mut buf));
}
// Nothing to do if the socket's already closed
if self.state == SocketState::Closed {
return Ok(());
}
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = SocketState::FinSent;
// Receive JAKE
while self.state != SocketState::Closed {
try!(self.recv_from(&mut buf));
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns `Closed` after receiving a FIN packet when the remaining
/// inflight packets are consumed.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(usize,SocketAddr)> {
if self.state == SocketState::Closed {
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == SocketState::ResetReceived {
return Err(IoError {
kind: Closed,
desc: "Connection reset",
detail: None,
});
}
match self.flush_incoming_buffer(buf) {
0 => self.recv(buf),
read => Ok((read, self.connected_to)),
}
}
fn recv(&mut self, buf: &mut[u8]) -> IoResult<(usize,SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.socket.set_read_timeout(Some(self.congestion_timeout));
}
let (read, src) = match self.socket.recv_from(&mut b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = Packet::decode(b.slice_to(read));
debug!("received {:?}", packet);
let shallow_clone = packet.shallow_clone();
if packet.get_type() == PacketType::Data && packet.seq_nr().wrapping_sub(self.ack_nr) >= 1 {
self.insert_into_buffer(packet);
}
if let Some(pkt) = try!(self.handle_packet(&shallow_clone, src)) {
let mut pkt = pkt;
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {:?}", pkt);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Remove packet in incoming buffer and update current acknowledgement
/// number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
let mut idx = 0;
// Check if there is any pending data from a partially flushed packet
if !self.pending_data.is_empty() {
let len = buf.clone_from_slice(self.pending_data.as_slice());
// If all the data in the pending data buffer fits the given output
// buffer, remove the corresponding packet from the incoming buffer
// and clear the pending data buffer
if len == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
return idx + len;
} else {
// Remove the bytes copied to the output buffer from the pending
// data buffer (i.e., pending -= output)
self.pending_data = self.pending_data.slice_from(len).to_vec();
}
}
// Copy the payload of as many packets in the incoming buffer as possible
while !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let len = min(buf.len() - idx, self.incoming_buffer[0].payload.len());
for i in (0..len) {
buf[idx] = self.incoming_buffer[0].payload[i];
idx += 1;
}
// Remove top packet if its payload fits the output buffer
if self.incoming_buffer[0].payload.len() == len {
self.advance_incoming_buffer();
} else {
self.pending_data.push_all(self.incoming_buffer[0].payload.slice_from(len));
}
// Stop if the output buffer is full
if buf.len() == idx {
return idx;
}
}
return idx;
}
/// Send data on socket to the remote peer. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8]) -> IoResult<()> {
if self.state == SocketState::Closed {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.payload = chunk.to_vec();
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Flush unsent packet queue
try!(self.send());
// Consume acknowledgements until latest packet
let mut buf = [0; BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(&mut buf));
}
Ok(())
}
/// Send every packet in the unsent packet queue.
fn send(&mut self) -> IoResult<()> {
let dst = self.connected_to;
while let Some(packet) = self.unsent_queue.pop_front() {
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
while self.curr_window + packet.len() as u32 > max_inflight {
let mut buf = [0; BUF_SIZE];
iotry!(self.recv_from(&mut buf));
}
let mut packet = packet;
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {:?}", packet);
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_ack_nr(self.ack_nr);
packet.set_seq_nr(self.seq_nr);
packet.set_connection_id(self.sender_connection_id);
for _ in (0u8..3) {
let t = now_microseconds();
packet.set_timestamp_microseconds(t);
packet.set_timestamp_difference_microseconds((t - self.last_acked_timestamp));
iotry!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
debug!("sent {:?}", packet);
}
}
fn update_base_delay(&mut self, v: i64, now: i64) {
use std::num::Int;
let minute_in_microseconds = 60 * 10.pow(6);
if self.base_delays.is_empty() || now - self.base_delays[0].received_at > minute_in_microseconds {
// Drop the oldest sample and save minimum for current minute
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_back();
}
self.base_delays.push_front(DelaySample{ received_at: now, sent_at: v });
} else {
// Replace sample for the current minute if the delay is lower
if v < self.base_delays[0].sent_at {
self.base_delays[0] = DelaySample{ received_at: now, sent_at: v};
}
}
}
/// Insert a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64, MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculate the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculate the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
match self.base_delays.iter().min_by(|&x| (x.received_at - x.sent_at).abs()) {
Some(ref x) => x.received_at - x.sent_at,
None => 0
}
}
/// Build the selective acknowledgment payload for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|&pkt| pkt.seq_nr() > self.ack_nr);
let mut sack = Vec::new();
for packet in stashed {
let diff = packet.seq_nr() - self.ack_nr - 2;
let byte = (diff / 8) as usize;
let bit = (diff % 8) as usize;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.extend(repeat(0).take((len / 4 + 1) * 4 - len));
}
return sack;
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
match self.send_window.iter().find(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(packet) => {
iotry!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
debug!("sent {:?}", packet);
}
}
}
/// Forget sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in range_inclusive(0, position) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> IoResult<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if (self.state, packet.get_type()) != (SocketState::New, PacketType::Syn) &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
self.remote_wnd_size = packet.wnd_size() as u32;
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(SocketState::SynSent, PacketType::State) => {
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
})
}
(SocketState::Connected, PacketType::Syn) => Ok(None), // ignore
(SocketState::Connected, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) => {
self.state = SocketState::FinReceived;
self.fin_seq_nr = packet.seq_nr();
// If all packets are received and handled
if self.no_pending_data() && self.ack_nr == self.fin_seq_nr
{
self.state = SocketState::Closed;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
} else {
debug!("FIN received but there are missing packets");
Ok(None)
}
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
})
},
(state, ty) => panic!("Unimplemented handling for ({:?},{:?})", state, ty)
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(Some(sack));
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay.abs() - min_base_delay.abs();
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
use std::num::Int;
let flightsize = self.curr_window;
match self.cwnd.checked_add((GAIN * off_target * bytes_newly_acked as f64 * MSS as f64 / self.cwnd as f64) as u32) {
Some(_) => {
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
None => {
// FIXME: This shouldn't happen at all, more investigation is needed to ascertain the
// true cause of the miscalculation of the congestion window increase. For now, we
// simply ignore meaningly large increases.
}
}
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update base and current delay
let now = now_microseconds() as i64;
self.update_base_delay(packet.timestamp_microseconds() as i64, now);
self.update_current_delay(packet.timestamp_difference_microseconds() as i64, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
// Update congestion window size
self.update_congestion_window(off_target, packet.len() as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
let bits = extension.iter();
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
let bits = extension.iter();
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = packet.ack_nr() + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if !self.send_window.is_empty() &&
seq_nr < self.send_window.last().unwrap().seq_nr()
{
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 {
for i in (0..self.send_window.len()) {
let seq_nr = self.send_window[i].seq_nr();
if seq_nr <= packet.ack_nr() { continue; }
self.resend_lost_packet(seq_nr);
}
}
// Success, advance send window
self.advance_send_window();
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if pkt.seq_nr() >= packet.seq_nr() {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].seq_nr() == packet.seq_nr() {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
/// Checks whether there is pending data (to be returned on a `recv_from` call) on the socket
fn no_pending_data(&self) -> bool {
self.pending_data.is_empty() && self.incoming_buffer.is_empty()
}
}
#[cfg(test)]
mod test {
use std::old_io::test::next_test_ip4;
use std::old_io::{EndOfFile, Closed};
use std::old_io::net::udp::UdpSocket;
use std::thread;
use super::{UtpSocket, SocketState, BUF_SIZE};
use packet::{Packet, PacketType};
use util::now_microseconds;
use rand;
#[test]
fn test_socket_ipv4() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == SocketState::Connected);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Connected);
// Closing the connection is fine
match server.recv_from(&mut buf) {
Err(e) => panic!("{}", e),
_ => {},
}
assert_eq!(server.state, SocketState::Closed);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(&mut buf) {
Err(e) => assert_eq!(e.kind, EndOfFile),
v => panic!("expected {:?}, got {:?}", EndOfFile, v),
}
assert_eq!(server.state, SocketState::Closed);
// Trying again raises a EndOfFile error
match server.recv_from(&mut buf) {
Err(e) => assert_eq!(e.kind, EndOfFile),
v => panic!("expected {:?}, got {:?}", EndOfFile, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
thread::spawn(move || {
let client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut buf = [0u8; BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(&mut buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert!(server.state == SocketState::Connected);
iotry!(server.close());
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(&buf) {
Err(e) => assert_eq!(e.kind, Closed),
v => panic!("expected {:?}, got {:?}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(client_addr));
let server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut s = client.socket;
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>().as_slice().chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(window[3].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[2].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[1].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[0].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[4].bytes().as_slice(), server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UdpSocket::bind(client_addr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = Packet::decode(&test_syn_raw);
let seq_nr = test_syn_pkt.seq_nr();
thread::spawn(move || {
let mut client = client;
iotry!(client.send_to(&test_syn_raw, server_addr));
client.set_timeout(Some(10));
let mut buf = [0; BUF_SIZE];
let packet = match client.recv_from(&mut buf) {
Ok((nread, _src)) => Packet::decode(buf.slice_to(nread)),
Err(e) => panic!("{}", e),
};
assert_eq!(packet.ack_nr(), seq_nr);
drop(client);
});
let mut server = server;
let mut buf = [0; 20];
iotry!(server.recv_from(&mut buf));
assert!(server.ack_nr != 0);
assert_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(d.as_slice()));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(&mut buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => {
data_packet = Packet::decode(buf.slice_to(read));
assert!(data_packet.get_type() == PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => panic!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), client_addr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = Packet::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(d.as_slice()));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{:?}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut s = client.socket.clone();
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(s.send_to(packet.bytes().as_slice(), server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1,2,3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_selective_ack_response() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
// Client
thread::spawn(move || {
let client = iotry!(UtpSocket::bind(client_addr));
let mut client = iotry!(client.connect(server_addr));
client.congestion_timeout = 50;
iotry!(client.send_to(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(server_addr));
let mut buf = [0; BUF_SIZE];
// Connect
iotry!(server.recv_from(&mut buf));
// Discard packets
iotry!(server.socket.recv_from(&mut buf));
iotry!(server.socket.recv_from(&mut buf));
iotry!(server.socket.recv_from(&mut buf));
// Generate SACK
let mut packet = Packet::new();
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr - 1);
packet.set_connection_id(server.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::State);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{:?}", e)
}
}
assert!(!received.is_empty());
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_correct_packet_loss() {
let (client_addr, server_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(client.connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let client = iotry!(UtpSocket::bind(client_addr));
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(to_send.as_slice()));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => (),
Ok((len, _src)) => read.push_all(small_buffer.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(client.connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(to_send.as_slice()));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((len, _src)) => received.push_all(buf.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
}
|
use std::cmp::{min, max};
use std::collections::VecDeque;
use std::net::{ToSocketAddrs, SocketAddr, UdpSocket};
use std::io::{Result, Error, ErrorKind};
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, Encodable, Decodable, ExtensionType, HEADER_SIZE};
use rand::{self, Rng};
use with_read_timeout::WithReadTimeout;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
const MAX_SYN_RETRIES: u32 = 5; // maximum connection retries
const MAX_RETRANSMISSION_RETRIES: u32 = 5; // maximum retransmission retries
#[derive(Debug)]
pub enum SocketError {
ConnectionClosed,
ConnectionReset,
ConnectionTimedOut,
InvalidAddress,
InvalidPacket,
InvalidReply,
}
impl From<SocketError> for Error {
fn from(error: SocketError) -> Error {
use self::SocketError::*;
let (kind, message) = match error {
ConnectionClosed => (ErrorKind::NotConnected, "The socket is closed"),
ConnectionReset => (ErrorKind::ConnectionReset, "Connection reset by remote peer"),
ConnectionTimedOut => (ErrorKind::TimedOut, "Connection timed out"),
InvalidAddress => (ErrorKind::InvalidInput, "Invalid address"),
InvalidPacket => (ErrorKind::Other, "Error parsing packet"),
InvalidReply => (ErrorKind::ConnectionRefused, "The remote peer sent an invalid reply"),
};
Error::new(kind, message)
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
enum SocketState {
New,
Connected,
SynSent,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// Returns the first valid address in a `ToSocketAddrs` iterator.
fn take_address<A: ToSocketAddrs>(addr: A) -> Result<SocketAddr> {
addr.to_socket_addrs()
.and_then(|mut it| it.next().ok_or(From::from(SocketError::InvalidAddress)))
}
/// A structure that represents a uTP (Micro Transport Protocol) connection between a local socket
/// and a remote socket.
///
/// The socket will be closed when the value is dropped (either explicitly or when it goes out of
/// scope).
///
/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be
/// changed by assigning the desired maximum retransmission retries to a socket's
/// `max_retransmission_retries` field. Notice that the initial congestion timeout is 500 ms and
/// doubles with each timeout.
///
/// # Examples
///
/// ```no_run
/// use utp::UtpSocket;
///
/// let mut socket = UtpSocket::bind("127.0.0.1:1234").unwrap();
///
/// let mut buf = [0; 1000];
/// let (amt, _src) = socket.recv_from(&mut buf).ok().unwrap();
///
/// let mut buf = &mut buf[..amt];
/// buf.reverse();
/// let _ = socket.send_to(buf).unwrap();
///
/// // Close the socket. You can either call `close` on the socket,
/// // explicitly drop it or just let it go out of scope.
/// socket.close();
/// ```
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: VecDeque<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the last packet removed from the incoming buffer
last_dropped: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<i64>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Difference between timestamp of the latest packet received and time of reception
their_delay: u32,
/// Start of the current minute for sampling purposes
last_rollover: i64,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
/// Maximum retransmission retries
pub max_retransmission_retries: u32,
}
impl UtpSocket {
/// Creates a new UTP from the given UDP socket and remote peer's address.
///
/// The connection identifier of the resulting socket is randomly generated.
fn from_raw_parts(s: UdpSocket, src: SocketAddr) -> UtpSocket {
// Safely generate the two sequential connection identifiers.
// This avoids a panic when the generated receiver id is the largest representable value in
// u16 and one increments it to yield the corresponding sender id.
let (receiver_id, sender_id) = || -> (u16, u16) {
let mut rng = rand::thread_rng();
loop {
let id = rng.gen::<u16>();
if id.checked_add(1).is_some() { return (id, id + 1) }
}
}();
UtpSocket {
socket: s,
connected_to: src,
receiver_connection_id: receiver_id,
sender_connection_id: sender_id,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: VecDeque::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
last_dropped: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
their_delay: 0,
last_rollover: 0,
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
max_retransmission_retries: MAX_RETRANSMISSION_RETRIES,
}
}
/// Creates a new UTP socket from the given address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpSocket> {
take_address(addr).and_then(|a| UdpSocket::bind(a).map(|s| UtpSocket::from_raw_parts(s, a)))
}
/// Returns the socket address that this socket was created from.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
/// Opens a connection to a remote host by hostname or IP address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn connect<A: ToSocketAddrs>(other: A) -> Result<UtpSocket> {
let addr = try!(take_address(other));
let my_addr = match addr {
SocketAddr::V4(_) => "0.0.0.0:0",
SocketAddr::V6(_) => ":::0",
};
let mut socket = try!(UtpSocket::bind(my_addr));
socket.connected_to = addr;
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(socket.receiver_connection_id);
packet.set_seq_nr(socket.seq_nr);
let mut len = 0;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = socket.congestion_timeout as i64;
for _ in 0..MAX_SYN_RETRIES {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", socket.connected_to);
try!(socket.socket.send_to(&packet.to_bytes()[..], socket.connected_to));
socket.state = SocketState::SynSent;
debug!("sent {:?}", packet);
// Validate response
match socket.socket.recv_timeout(&mut buf, syn_timeout) {
Ok((read, src)) => { socket.connected_to = src; len = read; break; },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
let addr = socket.connected_to;
let packet = try!(Packet::from_bytes(&buf[..len]).or(Err(SocketError::InvalidPacket)));
debug!("received {:?}", packet);
try!(socket.handle_packet(&packet, addr));
debug!("connected to: {}", socket.connected_to);
return Ok(socket);
}
/// Gracefully closes connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
pub fn close(&mut self) -> Result<()> {
// Nothing to do if the socket's already closed or not connected
if self.state == SocketState::Closed ||
self.state == SocketState::New ||
self.state == SocketState::SynSent {
return Ok(());
}
// Flush unsent and unacknowledged packets
try!(self.flush());
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("sent {:?}", packet);
self.state = SocketState::FinSent;
// Receive JAKE
let mut buf = [0; BUF_SIZE];
while self.state != SocketState::Closed {
try!(self.recv(&mut buf));
}
Ok(())
}
/// Receives data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns 0 bytes read after receiving a FIN packet when the remaining
/// inflight packets are consumed.
pub fn recv_from(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let read = self.flush_incoming_buffer(buf);
if read > 0 {
return Ok((read, self.connected_to));
} else {
// If the socket received a reset packet and all data has been flushed, then it can't
// receive anything else
if self.state == SocketState::ResetReceived {
return Err(Error::from(SocketError::ConnectionReset));
}
loop {
// A closed socket with no pending data can only "read" 0 new bytes.
if self.state == SocketState::Closed {
return Ok((0, self.connected_to));
}
match self.recv(buf) {
Ok((0, _src)) => continue,
Ok(x) => return Ok(x),
Err(e) => return Err(e)
}
}
}
}
fn recv(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
let now = now_microseconds();
let (read, src);
let mut retries = 0;
// Try to receive a packet and handle timeouts
loop {
// Abort loop if the current try exceeds the maximum number of retransmission retries.
if retries >= self.max_retransmission_retries {
self.state = SocketState::Closed;
return Err(Error::from(SocketError::ConnectionTimedOut));
}
let timeout = if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.congestion_timeout as i64
} else { 0 };
match self.socket.recv_timeout(&mut b, timeout) {
Ok((r, s)) => { read = r; src = s; break },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("recv_from timed out");
try!(self.handle_receive_timeout());
},
Err(e) => return Err(e),
};
let elapsed = now_microseconds() - now;
debug!("now_microseconds() - now = {} ms", elapsed/1000);
retries += 1;
}
// Decode received data into a packet
let packet = match Packet::from_bytes(&b[..read]) {
Ok(packet) => packet,
Err(e) => {
debug!("{}", e);
debug!("Ignoring invalid packet");
return Ok((0, self.connected_to));
}
};
debug!("received {:?}", packet);
// Process packet, including sending a reply if necessary
if let Some(mut pkt) = try!(self.handle_packet(&packet, src)) {
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(&pkt.to_bytes()[..], src));
debug!("sent {:?}", pkt);
}
// Insert data packet into the incoming buffer if it isn't a duplicate of a previously
// discarded packet
if packet.get_type() == PacketType::Data &&
packet.seq_nr().wrapping_sub(self.last_dropped) > 0 {
self.insert_into_buffer(packet);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn handle_receive_timeout(&mut self) -> Result<()> {
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
// There are three possible cases here:
//
// - If the socket is sending and waiting for acknowledgements (the send window is
// not empty), resend the first unacknowledged packet;
//
// - If the socket is not sending and it hasn't sent a FIN yet, then it's waiting
// for incoming packets: send a fast resend request;
//
// - If the socket sent a FIN previously, resend it.
debug!("self.send_window: {:?}", self.send_window.iter()
.map(Packet::seq_nr).collect::<Vec<u16>>());
if self.send_window.is_empty() {
// The socket is trying to close, all sent packets were acknowledged, and it has
// already sent a FIN: resend it.
if self.state == SocketState::FinSent {
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent FIN: {:?}", packet);
} else {
// The socket is waiting for incoming packets but the remote peer is silent:
// send a fast resend request.
debug!("sending fast resend request");
self.send_fast_resend_request();
}
} else {
// The socket is sending data packets but there is no reply from the remote
// peer: resend the first unacknowledged packet with the current timestamp.
let mut packet = &mut self.send_window[0];
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent {:?}", packet);
}
Ok(())
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Removes a packet in the incoming buffer and updates the current acknowledgement number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
self.last_dropped = self.ack_nr;
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
fn unsafe_copy(src: &[u8], dst: &mut [u8]) -> usize {
let max_len = min(src.len(), dst.len());
unsafe {
use std::ptr::copy;
copy(src.as_ptr(), dst.as_mut_ptr(), max_len);
}
return max_len;
}
// Return pending data from a partially read packet
if !self.pending_data.is_empty() {
let flushed = unsafe_copy(&self.pending_data[..], buf);
if flushed == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
} else {
self.pending_data = self.pending_data[flushed..].to_vec();
}
return flushed;
}
if !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let flushed = unsafe_copy(&self.incoming_buffer[0].payload[..], buf);
if flushed == self.incoming_buffer[0].payload.len() {
self.advance_incoming_buffer();
} else {
self.pending_data = self.incoming_buffer[0].payload[flushed..].to_vec();
}
return flushed;
}
return 0;
}
/// Sends data on the socket to the remote peer. On success, returns the number of bytes
/// written.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
pub fn send_to(&mut self, buf: &[u8]) -> Result<usize> {
if self.state == SocketState::Closed {
return Err(Error::from(SocketError::ConnectionClosed));
}
let total_length = buf.len();
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::with_payload(chunk);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
// `OverflowingOps` is marked unstable, so we can't use `overflowing_add` here
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Send every packet in the queue
try!(self.send());
Ok(total_length)
}
/// Consumes acknowledgements for every pending packet.
pub fn flush(&mut self) -> Result<()> {
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
debug!("packets in send window: {}", self.send_window.len());
try!(self.recv(&mut buf));
}
Ok(())
}
/// Sends every packet in the unsent packet queue.
fn send(&mut self) -> Result<()> {
while let Some(mut packet) = self.unsent_queue.pop_front() {
try!(self.send_packet(&mut packet));
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send one packet.
#[inline(always)]
fn send_packet(&mut self, packet: &mut Packet) -> Result<()> {
let dst = self.connected_to;
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
let now = now_microseconds();
// Wait until enough inflight packets are acknowledged for rate control purposes, but don't
// wait more than 500 ms before sending the packet.
while self.curr_window >= max_inflight && now_microseconds() - now < 500_000 {
debug!("self.curr_window: {}", self.curr_window);
debug!("max_inflight: {}", max_inflight);
debug!("self.duplicate_ack_count: {}", self.duplicate_ack_count);
debug!("now_microseconds() - now = {}", now_microseconds() - now);
let mut buf = [0; BUF_SIZE];
try!(self.recv(&mut buf));
}
debug!("out: now_microseconds() - now = {}", now_microseconds() - now);
// Check if it still makes sense to send packet, as we might be trying to resend a lost
// packet acknowledged in the receive loop above.
// If there were no wrapping around of sequence numbers, we'd simply check if the packet's
// sequence number is greater than `last_acked`.
let distance_a = packet.seq_nr().wrapping_sub(self.last_acked);
let distance_b = self.last_acked.wrapping_sub(packet.seq_nr());
if distance_a > distance_b {
debug!("Packet already acknowledged, skipping...");
return Ok(());
}
packet.set_timestamp_microseconds(now_microseconds());
packet.set_timestamp_difference_microseconds(self.their_delay);
try!(self.socket.send_to(&packet.to_bytes()[..], dst));
debug!("sent {:?}", packet);
Ok(())
}
// Insert a new sample in the base delay list.
//
// The base delay list contains at most `BASE_HISTORY` samples, each sample is the minimum
// measured over a period of a minute.
fn update_base_delay(&mut self, base_delay: i64, now: i64) {
let minute_in_microseconds = 60 * 10i64.pow(6);
if self.base_delays.is_empty() || now - self.last_rollover > minute_in_microseconds {
// Update last rollover
self.last_rollover = now;
// Drop the oldest sample, if need be
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_front();
}
// Insert new sample
self.base_delays.push_back(base_delay);
} else {
// Replace sample for the current minute if the delay is lower
let last_idx = self.base_delays.len() - 1;
if base_delay < self.base_delays[last_idx] {
self.base_delays[last_idx] = base_delay;
}
}
}
/// Inserts a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64,
MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculates the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculates the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
self.base_delays.iter().map(|x| *x).min().unwrap_or(0)
}
/// Builds the selective acknowledgment extension data for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|ref pkt| pkt.seq_nr() > self.ack_nr + 1)
.map(|ref pkt| (pkt.seq_nr() - self.ack_nr - 2) as usize)
.map(|diff| (diff / 8, diff % 8));
let mut sack = Vec::new();
for (byte, bit) in stashed {
// Make sure the amount of elements in the SACK vector is a
// multiple of 4 and enough to represent the lost packets
while byte >= sack.len() || sack.len() % 4 != 0 {
sack.push(0u8);
}
sack[byte] |= 1 << bit;
}
return sack;
}
/// Sends a fast resend request to the remote peer.
///
/// A fast resend request consists of sending three STATE packets (acknowledging the last
/// received packet) in quick succession.
fn send_fast_resend_request(&self) {
for _ in 0..3 {
let mut packet = Packet::new();
packet.set_type(PacketType::State);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = 0;
packet.set_timestamp_microseconds(self_t_micro);
packet.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
let _ = self.socket.send_to(&packet.to_bytes()[..], self.connected_to);
}
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
debug!("---> resend_lost_packet({}) <---", lost_packet_nr);
match self.send_window.iter().position(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(position) => {
debug!("self.send_window.len(): {}", self.send_window.len());
debug!("position: {}", position);
let mut packet = self.send_window[position].clone();
// FIXME: Unchecked result
let _ = self.send_packet(&mut packet);
// We intentionally don't increase `curr_window` because otherwise a packet's length
// would be counted more than once
}
}
debug!("---> END resend_lost_packet <---");
}
/// Forgets sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
// The reason I'm not removing the first element in a loop while its sequence number is
// smaller than `last_acked` is because of wrapping sequence numbers, which would create the
// sequence [..., 65534, 65535, 0, 1, ...]. If `last_acked` is smaller than the first
// packet's sequence number because of wraparound (for instance, 1), no packets would be
// removed, as the condition `seq_nr < last_acked` would fail immediately.
//
// On the other hand, I can't keep removing the first packet in a loop until its sequence
// number matches `last_acked` because it might never match, and in that case no packets
// should be removed.
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in (0..position + 1) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handles an incoming packet, updating socket state accordingly.
///
/// Returns the appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> Result<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != PacketType::Syn &&
self.state != SocketState::SynSent &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
// Update remote window size
self.remote_wnd_size = packet.wnd_size();
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
// Update remote peer's delay between them sending the packet and us receiving it
let now = now_microseconds();
self.their_delay = if now > packet.timestamp_microseconds() {
now - packet.timestamp_microseconds()
} else {
packet.timestamp_microseconds() - now
};
debug!("self.their_delay: {}", self.their_delay);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
self.last_dropped = self.ack_nr;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(_, PacketType::Syn) => {
Ok(Some(self.prepare_reply(packet, PacketType::Reset)))
}
(SocketState::SynSent, PacketType::State) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(Error::from(SocketError::InvalidReply))
}
(SocketState::Connected, PacketType::Data) |
(SocketState::FinSent, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) |
(SocketState::FinSent, PacketType::Fin) => {
if packet.ack_nr() < self.seq_nr {
debug!("FIN received but there are missing acknowledgments for sent packets");
}
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
// Give up, the remote peer might not care about our missing packets
self.state = SocketState::Closed;
Ok(Some(reply))
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
} else {
self.handle_state_packet(packet);
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(Error::from(SocketError::ConnectionReset))
},
(state, ty) => {
let message = format!("Unimplemented handling for ({:?},{:?})", state, ty);
debug!("{}", message);
Err(Error::new(ErrorKind::Other, message))
}
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
// If a FIN was previously sent, reply with a FIN packet acknowledging the received packet.
let packet_type = if self.state == SocketState::FinSent {
PacketType::Fin
} else {
PacketType::State
};
let mut reply = self.prepare_reply(packet, packet_type);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay - min_base_delay;
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
/// Calculates the new congestion window size, increasing it or decreasing it.
///
/// This is the core of uTP, the [LEDBAT][ledbat_rfc] congestion algorithm. It depends on
/// estimating the queuing delay between the two peers, and adjusting the congestion window
/// accordingly.
///
/// `off_target` is a normalized value representing the difference between the current queuing
/// delay and a fixed target delay (`TARGET`). `off_target` ranges between -1.0 and 1.0. A
/// positive value makes the congestion window increase, while a negative value makes the
/// congestion window decrease.
///
/// `bytes_newly_acked` is the number of bytes acknowledged by an inbound `State` packet. It may
/// be the size of the packet explicitly acknowledged by the inbound packet (i.e., with sequence
/// number equal to the inbound packet's acknowledgement number), or every packet implicitly
/// acknowledged (every packet with sequence number between the previous inbound `State`
/// packet's acknowledgement number and the current inbound `State` packet's acknowledgement
/// number).
///
///[ledbat_rfc]: https://tools.ietf.org/html/rfc6817
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
let flightsize = self.curr_window;
let cwnd_increase = GAIN * off_target * bytes_newly_acked as f64 * MSS as f64;
let cwnd_increase = cwnd_increase / self.cwnd as f64;
debug!("cwnd_increase: {}", cwnd_increase);
self.cwnd = (self.cwnd as f64 + cwnd_increase) as u32;
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update congestion window size
if let Some(index) = self.send_window.iter().position(|p| packet.ack_nr() == p.seq_nr()) {
// Calculate the sum of the size of every packet implicitly and explictly acknowledged
// by the inbout packet (i.e., every packet whose sequence number precedes the inbound
// packet's acknowledgement number, plus the packet whose sequence number matches)
let bytes_newly_acked = self.send_window.iter()
.take(index + 1)
.fold(0, |acc, p| acc + p.len());
// Update base and current delay
let now = now_microseconds() as i64;
let our_delay = now - self.send_window[index].timestamp_microseconds() as i64;
debug!("our_delay: {}", our_delay);
self.update_base_delay(our_delay, now);
self.update_current_delay(our_delay, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
self.update_congestion_window(off_target, bytes_newly_acked as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
}
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if extension.iter().count_ones() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
for seq_nr in extension.iter().enumerate()
.filter(|&(_idx, received)| !received)
.map(|(idx, _received)| packet.ack_nr() + 2 + idx as u16) {
if self.send_window.last().map(|p| seq_nr < p.seq_nr()).unwrap_or(false) {
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Three duplicate ACKs mean a fast resend request. Resend the first unacknowledged packet
// if the incoming packet doesn't have a SACK extension. If it does, the lost packets were
// already resent.
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 &&
!packet.extensions.iter().any(|ext| ext.get_type() == ExtensionType::SelectiveAck) {
self.resend_lost_packet(packet.ack_nr() + 1);
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Success, advance send window
self.advance_send_window();
}
/// Inserts a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
// Immediately push to the end if the packet's sequence number comes after the last
// packet's.
if self.incoming_buffer.last().map(|p| packet.seq_nr() > p.seq_nr()).unwrap_or(false) {
self.incoming_buffer.push(packet);
} else {
// Find index following the most recent packet before the one we wish to insert
let i = self.incoming_buffer.iter().filter(|p| p.seq_nr() < packet.seq_nr()).count();
// Replace packet if it's a duplicate
if self.incoming_buffer.get(i).map(|p| p.seq_nr() == packet.seq_nr()).unwrap_or(false) {
self.incoming_buffer[i] = packet;
} else {
self.incoming_buffer.insert(i, packet);
}
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
let _ = self.close();
}
}
/// A structure representing a socket server.
///
/// # Examples
///
/// ```no_run
/// use utp::{UtpListener, UtpSocket};
/// use std::thread;
///
/// fn handle_client(socket: UtpSocket) {
/// // ...
/// }
///
/// fn main() {
/// // Create a listener
/// let addr = "127.0.0.1:8080";
/// let listener = UtpListener::bind(addr).unwrap();
///
/// for connection in listener.incoming() {
/// // Spawn a new handler for each new connection
/// match connection {
/// Ok((socket, _src)) => { thread::spawn(move || { handle_client(socket) }); },
/// _ => ()
/// }
/// }
/// }
/// ```
pub struct UtpListener {
/// The public facing UDP socket
socket: UdpSocket,
}
impl UtpListener {
/// Creates a new `UtpListener` bound to a specific address.
///
/// The resulting listener is ready for accepting connections.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpListener> {
UdpSocket::bind(addr).and_then(|s| Ok(UtpListener { socket: s}))
}
/// Accepts a new incoming connection from this listener.
///
/// This function will block the caller until a new uTP connection is established. When
/// established, the corresponding `UtpSocket` and the peer's remote address will be returned.
///
/// Notice that the resulting `UtpSocket` is bound to a different local port than the public
/// listening port (which `UtpListener` holds). This may confuse the remote peer!
pub fn accept(&self) -> Result<(UtpSocket, SocketAddr)> {
let mut buf = [0; BUF_SIZE];
match self.socket.recv_from(&mut buf) {
Ok((nread, src)) => {
let packet = try!(Packet::from_bytes(&buf[..nread])
.or(Err(SocketError::InvalidPacket)));
// Ignore non-SYN packets
if packet.get_type() != PacketType::Syn {
return Err(Error::from(SocketError::InvalidPacket));
}
// The address of the new socket will depend on the type of the listener.
let inner_socket = self.socket.local_addr().and_then(|addr| match addr {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0"),
SocketAddr::V6(_) => UdpSocket::bind(":::0"),
});
let mut socket = try!(inner_socket.map(|s| UtpSocket::from_raw_parts(s, src)));
// Establish connection with remote peer
match socket.handle_packet(&packet, src) {
Ok(Some(reply)) => { try!(socket.socket.send_to(&reply.to_bytes()[..], src)) },
Ok(None) => return Err(Error::from(SocketError::InvalidPacket)),
Err(e) => return Err(e)
};
Ok((socket, src))
},
Err(e) => Err(e)
}
}
/// Returns an iterator over the connections being received by this listener.
///
/// The returned iterator will never return `None`.
pub fn incoming(&self) -> Incoming {
Incoming { listener: self }
}
/// Returns the local socket address of this listener.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
}
pub struct Incoming<'a> { listener: &'a UtpListener }
impl<'a> Iterator for Incoming<'a> {
type Item = Result<(UtpSocket, SocketAddr)>;
fn next(&mut self) -> Option<Result<(UtpSocket, SocketAddr)>> {
Some(self.listener.accept())
}
}
#[cfg(test)]
mod test {
use std::thread;
use std::net::ToSocketAddrs;
use std::io::ErrorKind;
use super::{UtpSocket, UtpListener, SocketState, BUF_SIZE, take_address};
use packet::{Packet, PacketType, Encodable, Decodable};
use util::now_microseconds;
use rand;
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{:?}", e) })
}
fn next_test_port() -> u16 {
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
const BASE_PORT: u16 = 9600;
BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
fn next_test_ip4<'a>() -> (&'a str, u16) {
("127.0.0.1", next_test_port())
}
fn next_test_ip6<'a>() -> (&'a str, u16) {
("::1", next_test_port())
}
#[test]
fn test_socket_ipv4() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_socket_ipv6() {
let server_addr = next_test_ip6();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert!(client.close().is_ok());
});
// Make the server listen for incoming connections until the end of the input
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Closed);
// Trying to receive again returns Ok(0) [EndOfFile]
match server.recv_from(&mut buf) {
Ok((0, _src)) => {},
e => panic!("Expected Ok(0), got {:?}", e),
}
assert_eq!(server.state, SocketState::Closed);
}
#[test]
fn test_sendto_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
iotry!(client.close());
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an error
match server.send_to(&buf) {
Err(ref e) if e.kind() == ErrorKind::NotConnected => (),
v => panic!("expected {:?}, got {:?}", ErrorKind::NotConnected, v),
}
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let server_addr = next_test_ip4();
let (tx, rx) = channel();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert!(client.close().is_ok());
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1, 2, 3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4, 5, 6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_socket_unordered_packets() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
let s = client.socket.try_clone().ok().expect("Error cloning internal UDP socket");
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>()[..].chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
client.curr_window += packet.len() as u32;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(&window[3].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[2].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[1].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[0].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[4].to_bytes()[..], server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0; BUF_SIZE];
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.state, SocketState::Closed);
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_response_to_triple_ack() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&d[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv(&mut buf));
// Receive data
let data_packet = match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => iotry!(Packet::from_bytes(&buf[..read])),
Err(e) => panic!("{}", e),
};
assert_eq!(data_packet.get_type(), PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to));
}
// Receive data again and check that it's the same we reported as missing
let client_addr = server.connected_to;
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..read]));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(&response.to_bytes()[..], server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(&d[..]));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
server.recv(&mut buf).unwrap();
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1, 2, 3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(client.socket.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
iotry!(server.recv(&mut buf));
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1, 2, 3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
// #[test]
// #[ignore]
// fn test_selective_ack_response() {
// let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
// const LEN: usize = 1024 * 10;
// let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
// let to_send = data.clone();
// // Client
// thread::spawn(move || {
// let client = iotry!(UtpSocket::bind(client_addr));
// let mut client = iotry!(UtpSocket::connect(server_addr));
// client.congestion_timeout = 50;
// iotry!(client.send_to(&to_send[..]));
// iotry!(client.close());
// });
// // Server
// let mut server = iotry!(UtpSocket::bind(server_addr));
// let mut buf = [0; BUF_SIZE];
// // Connect
// iotry!(server.recv_from(&mut buf));
// // Discard packets
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// // Generate SACK
// let mut packet = Packet::new();
// packet.set_seq_nr(server.seq_nr);
// packet.set_ack_nr(server.ack_nr - 1);
// packet.set_connection_id(server.sender_connection_id);
// packet.set_timestamp_microseconds(now_microseconds());
// packet.set_type(PacketType::State);
// packet.set_sack(vec!(12, 0, 0, 0));
// // Send SACK
// iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to.clone()));
// // Expect to receive "missing" packets
// let mut received: Vec<u8> = vec!();
// loop {
// match server.recv_from(&mut buf) {
// Ok((0, _src)) => break,
// Ok((len, _src)) => received.extend(buf[..len].to_vec()),
// Err(e) => panic!("{:?}", e)
// }
// }
// assert!(!received.is_empty());
// assert_eq!(received.len(), data.len());
// assert_eq!(received, data);
// }
#[test]
fn test_correct_packet_loss() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send[..].chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(&packet.to_bytes()[..], dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => break,
Ok((len, _src)) => read.extend(small_buffer[..len].to_vec()),
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(&to_send[..]));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_drop_unused_socket() {
let server_addr = next_test_ip4();
let server = iotry!(UtpSocket::bind(server_addr));
// Explicitly dropping socket. This test should not hang.
drop(server);
}
#[test]
fn test_invalid_packet_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => { iotry!(server.send_to(&[], client_addr)); },
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::Other => (), // OK
Err(e) => panic!("Expected ErrorKind::Other, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receive_unexpected_reply_type_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => {
iotry!(server.send_to(&packet.to_bytes()[..], client_addr));
},
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::ConnectionRefused => (), // OK
Err(e) => panic!("Expected ErrorKind::ConnectionRefused, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receiving_syn_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(e) => panic!("{:?}", e)
}
}
});
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let reply = Packet::from_bytes(&buf[..len]).ok().unwrap();
assert_eq!(reply.get_type(), PacketType::Reset);
}
Err(e) => panic!("{:?}", e)
}
}
#[test]
fn test_receiving_reset_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Reset);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((_len, _src)) => (),
Err(e) => panic!("{:?}", e)
}
});
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(ref e) if e.kind() == ErrorKind::ConnectionReset => return,
Err(e) => panic!("{:?}", e)
}
}
panic!("Should have received Reset");
}
#[test]
fn test_premature_fin() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Accept connection
iotry!(server.recv(&mut buf));
// Send FIN without acknowledging packets received
let mut packet = Packet::new();
packet.set_connection_id(server.sender_connection_id);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
iotry!(server.socket.send_to(&packet.to_bytes()[..], client_addr));
// Receive until end
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_base_delay_calculation() {
let minute_in_microseconds = 60 * 10i64.pow(6);
let samples = vec![(0, 10), (1, 8), (2, 12), (3, 7),
(minute_in_microseconds + 1, 11),
(minute_in_microseconds + 2, 19),
(minute_in_microseconds + 3, 9)];
let addr = next_test_ip4();
let mut socket = UtpSocket::bind(addr).unwrap();
for (timestamp, delay) in samples{
socket.update_base_delay(delay, timestamp + delay);
}
let expected = vec![7, 9];
let actual = socket.base_delays.iter().map(|&x| x).collect::<Vec<_>>();
assert_eq!(expected, actual);
assert_eq!(socket.min_base_delay(), 7);
}
#[test]
fn test_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let socket = UtpSocket::bind(addr).unwrap();
assert!(socket.local_addr().is_ok());
assert_eq!(socket.local_addr().unwrap(), addr);
}
#[test]
fn test_listener_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let listener = UtpListener::bind(addr).unwrap();
assert!(listener.local_addr().is_ok());
assert_eq!(listener.local_addr().unwrap(), addr);
}
#[test]
fn test_take_address() {
// Expected succcesses
assert!(take_address(("0.0.0.0:0")).is_ok());
assert!(take_address((":::0")).is_ok());
assert!(take_address(("0.0.0.0", 0)).is_ok());
assert!(take_address(("::", 0)).is_ok());
assert!(take_address(("1.2.3.4", 5)).is_ok());
// Expected failures
assert!(take_address("999.0.0.0:0").is_err());
assert!(take_address(("1.2.3.4:70000")).is_err());
assert!(take_address("").is_err());
assert!(take_address("this is not an address").is_err());
assert!(take_address("no.dns.resolution.com").is_err());
}
// Test reaction to connection loss when sending data packets
#[test]
fn test_connection_loss_data() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Data),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
iotry!(server.send_to(&[0]));
// Try to receive ACKs, time out too many times on flush, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when sending FIN
#[test]
fn test_connection_loss_fin() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Fin),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Send FIN, time out too many times, and fail with `TimedOut`
match server.close() {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when waiting for data packets
#[test]
fn test_connection_loss_waiting() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let seq_nr = client.seq_nr;
let mut buf = [0; BUF_SIZE];
for _ in 0..(3 * attempts) {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..len]));
assert_eq!(packet.get_type(), PacketType::State);
assert_eq!(packet.ack_nr(), seq_nr - 1);
},
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Try to receive data, time out too many times, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
}
Fix typo.
use std::cmp::{min, max};
use std::collections::VecDeque;
use std::net::{ToSocketAddrs, SocketAddr, UdpSocket};
use std::io::{Result, Error, ErrorKind};
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, Encodable, Decodable, ExtensionType, HEADER_SIZE};
use rand::{self, Rng};
use with_read_timeout::WithReadTimeout;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
const MAX_SYN_RETRIES: u32 = 5; // maximum connection retries
const MAX_RETRANSMISSION_RETRIES: u32 = 5; // maximum retransmission retries
#[derive(Debug)]
pub enum SocketError {
ConnectionClosed,
ConnectionReset,
ConnectionTimedOut,
InvalidAddress,
InvalidPacket,
InvalidReply,
}
impl From<SocketError> for Error {
fn from(error: SocketError) -> Error {
use self::SocketError::*;
let (kind, message) = match error {
ConnectionClosed => (ErrorKind::NotConnected, "The socket is closed"),
ConnectionReset => (ErrorKind::ConnectionReset, "Connection reset by remote peer"),
ConnectionTimedOut => (ErrorKind::TimedOut, "Connection timed out"),
InvalidAddress => (ErrorKind::InvalidInput, "Invalid address"),
InvalidPacket => (ErrorKind::Other, "Error parsing packet"),
InvalidReply => (ErrorKind::ConnectionRefused, "The remote peer sent an invalid reply"),
};
Error::new(kind, message)
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
enum SocketState {
New,
Connected,
SynSent,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// Returns the first valid address in a `ToSocketAddrs` iterator.
fn take_address<A: ToSocketAddrs>(addr: A) -> Result<SocketAddr> {
addr.to_socket_addrs()
.and_then(|mut it| it.next().ok_or(From::from(SocketError::InvalidAddress)))
}
/// A structure that represents a uTP (Micro Transport Protocol) connection between a local socket
/// and a remote socket.
///
/// The socket will be closed when the value is dropped (either explicitly or when it goes out of
/// scope).
///
/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be
/// changed by assigning the desired maximum retransmission retries to a socket's
/// `max_retransmission_retries` field. Notice that the initial congestion timeout is 500 ms and
/// doubles with each timeout.
///
/// # Examples
///
/// ```no_run
/// use utp::UtpSocket;
///
/// let mut socket = UtpSocket::bind("127.0.0.1:1234").unwrap();
///
/// let mut buf = [0; 1000];
/// let (amt, _src) = socket.recv_from(&mut buf).ok().unwrap();
///
/// let mut buf = &mut buf[..amt];
/// buf.reverse();
/// let _ = socket.send_to(buf).unwrap();
///
/// // Close the socket. You can either call `close` on the socket,
/// // explicitly drop it or just let it go out of scope.
/// socket.close();
/// ```
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: VecDeque<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the last packet removed from the incoming buffer
last_dropped: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<i64>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Difference between timestamp of the latest packet received and time of reception
their_delay: u32,
/// Start of the current minute for sampling purposes
last_rollover: i64,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
/// Maximum retransmission retries
pub max_retransmission_retries: u32,
}
impl UtpSocket {
/// Creates a new UTP from the given UDP socket and remote peer's address.
///
/// The connection identifier of the resulting socket is randomly generated.
fn from_raw_parts(s: UdpSocket, src: SocketAddr) -> UtpSocket {
// Safely generate the two sequential connection identifiers.
// This avoids a panic when the generated receiver id is the largest representable value in
// u16 and one increments it to yield the corresponding sender id.
let (receiver_id, sender_id) = || -> (u16, u16) {
let mut rng = rand::thread_rng();
loop {
let id = rng.gen::<u16>();
if id.checked_add(1).is_some() { return (id, id + 1) }
}
}();
UtpSocket {
socket: s,
connected_to: src,
receiver_connection_id: receiver_id,
sender_connection_id: sender_id,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: VecDeque::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
last_dropped: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
their_delay: 0,
last_rollover: 0,
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
max_retransmission_retries: MAX_RETRANSMISSION_RETRIES,
}
}
/// Creates a new UTP socket from the given address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpSocket> {
take_address(addr).and_then(|a| UdpSocket::bind(a).map(|s| UtpSocket::from_raw_parts(s, a)))
}
/// Returns the socket address that this socket was created from.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
/// Opens a connection to a remote host by hostname or IP address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn connect<A: ToSocketAddrs>(other: A) -> Result<UtpSocket> {
let addr = try!(take_address(other));
let my_addr = match addr {
SocketAddr::V4(_) => "0.0.0.0:0",
SocketAddr::V6(_) => ":::0",
};
let mut socket = try!(UtpSocket::bind(my_addr));
socket.connected_to = addr;
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(socket.receiver_connection_id);
packet.set_seq_nr(socket.seq_nr);
let mut len = 0;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = socket.congestion_timeout as i64;
for _ in 0..MAX_SYN_RETRIES {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", socket.connected_to);
try!(socket.socket.send_to(&packet.to_bytes()[..], socket.connected_to));
socket.state = SocketState::SynSent;
debug!("sent {:?}", packet);
// Validate response
match socket.socket.recv_timeout(&mut buf, syn_timeout) {
Ok((read, src)) => { socket.connected_to = src; len = read; break; },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
let addr = socket.connected_to;
let packet = try!(Packet::from_bytes(&buf[..len]).or(Err(SocketError::InvalidPacket)));
debug!("received {:?}", packet);
try!(socket.handle_packet(&packet, addr));
debug!("connected to: {}", socket.connected_to);
return Ok(socket);
}
/// Gracefully closes connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
pub fn close(&mut self) -> Result<()> {
// Nothing to do if the socket's already closed or not connected
if self.state == SocketState::Closed ||
self.state == SocketState::New ||
self.state == SocketState::SynSent {
return Ok(());
}
// Flush unsent and unacknowledged packets
try!(self.flush());
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("sent {:?}", packet);
self.state = SocketState::FinSent;
// Receive JAKE
let mut buf = [0; BUF_SIZE];
while self.state != SocketState::Closed {
try!(self.recv(&mut buf));
}
Ok(())
}
/// Receives data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns 0 bytes read after receiving a FIN packet when the remaining
/// inflight packets are consumed.
pub fn recv_from(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let read = self.flush_incoming_buffer(buf);
if read > 0 {
return Ok((read, self.connected_to));
} else {
// If the socket received a reset packet and all data has been flushed, then it can't
// receive anything else
if self.state == SocketState::ResetReceived {
return Err(Error::from(SocketError::ConnectionReset));
}
loop {
// A closed socket with no pending data can only "read" 0 new bytes.
if self.state == SocketState::Closed {
return Ok((0, self.connected_to));
}
match self.recv(buf) {
Ok((0, _src)) => continue,
Ok(x) => return Ok(x),
Err(e) => return Err(e)
}
}
}
}
fn recv(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
let now = now_microseconds();
let (read, src);
let mut retries = 0;
// Try to receive a packet and handle timeouts
loop {
// Abort loop if the current try exceeds the maximum number of retransmission retries.
if retries >= self.max_retransmission_retries {
self.state = SocketState::Closed;
return Err(Error::from(SocketError::ConnectionTimedOut));
}
let timeout = if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.congestion_timeout as i64
} else { 0 };
match self.socket.recv_timeout(&mut b, timeout) {
Ok((r, s)) => { read = r; src = s; break },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("recv_from timed out");
try!(self.handle_receive_timeout());
},
Err(e) => return Err(e),
};
let elapsed = now_microseconds() - now;
debug!("now_microseconds() - now = {} ms", elapsed/1000);
retries += 1;
}
// Decode received data into a packet
let packet = match Packet::from_bytes(&b[..read]) {
Ok(packet) => packet,
Err(e) => {
debug!("{}", e);
debug!("Ignoring invalid packet");
return Ok((0, self.connected_to));
}
};
debug!("received {:?}", packet);
// Process packet, including sending a reply if necessary
if let Some(mut pkt) = try!(self.handle_packet(&packet, src)) {
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(&pkt.to_bytes()[..], src));
debug!("sent {:?}", pkt);
}
// Insert data packet into the incoming buffer if it isn't a duplicate of a previously
// discarded packet
if packet.get_type() == PacketType::Data &&
packet.seq_nr().wrapping_sub(self.last_dropped) > 0 {
self.insert_into_buffer(packet);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn handle_receive_timeout(&mut self) -> Result<()> {
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
// There are three possible cases here:
//
// - If the socket is sending and waiting for acknowledgements (the send window is
// not empty), resend the first unacknowledged packet;
//
// - If the socket is not sending and it hasn't sent a FIN yet, then it's waiting
// for incoming packets: send a fast resend request;
//
// - If the socket sent a FIN previously, resend it.
debug!("self.send_window: {:?}", self.send_window.iter()
.map(Packet::seq_nr).collect::<Vec<u16>>());
if self.send_window.is_empty() {
// The socket is trying to close, all sent packets were acknowledged, and it has
// already sent a FIN: resend it.
if self.state == SocketState::FinSent {
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent FIN: {:?}", packet);
} else {
// The socket is waiting for incoming packets but the remote peer is silent:
// send a fast resend request.
debug!("sending fast resend request");
self.send_fast_resend_request();
}
} else {
// The socket is sending data packets but there is no reply from the remote
// peer: resend the first unacknowledged packet with the current timestamp.
let mut packet = &mut self.send_window[0];
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent {:?}", packet);
}
Ok(())
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Removes a packet in the incoming buffer and updates the current acknowledgement number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
self.last_dropped = self.ack_nr;
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
fn unsafe_copy(src: &[u8], dst: &mut [u8]) -> usize {
let max_len = min(src.len(), dst.len());
unsafe {
use std::ptr::copy;
copy(src.as_ptr(), dst.as_mut_ptr(), max_len);
}
return max_len;
}
// Return pending data from a partially read packet
if !self.pending_data.is_empty() {
let flushed = unsafe_copy(&self.pending_data[..], buf);
if flushed == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
} else {
self.pending_data = self.pending_data[flushed..].to_vec();
}
return flushed;
}
if !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let flushed = unsafe_copy(&self.incoming_buffer[0].payload[..], buf);
if flushed == self.incoming_buffer[0].payload.len() {
self.advance_incoming_buffer();
} else {
self.pending_data = self.incoming_buffer[0].payload[flushed..].to_vec();
}
return flushed;
}
return 0;
}
/// Sends data on the socket to the remote peer. On success, returns the number of bytes
/// written.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
pub fn send_to(&mut self, buf: &[u8]) -> Result<usize> {
if self.state == SocketState::Closed {
return Err(Error::from(SocketError::ConnectionClosed));
}
let total_length = buf.len();
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::with_payload(chunk);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
// `OverflowingOps` is marked unstable, so we can't use `overflowing_add` here
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Send every packet in the queue
try!(self.send());
Ok(total_length)
}
/// Consumes acknowledgements for every pending packet.
pub fn flush(&mut self) -> Result<()> {
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
debug!("packets in send window: {}", self.send_window.len());
try!(self.recv(&mut buf));
}
Ok(())
}
/// Sends every packet in the unsent packet queue.
fn send(&mut self) -> Result<()> {
while let Some(mut packet) = self.unsent_queue.pop_front() {
try!(self.send_packet(&mut packet));
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send one packet.
#[inline(always)]
fn send_packet(&mut self, packet: &mut Packet) -> Result<()> {
let dst = self.connected_to;
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
let now = now_microseconds();
// Wait until enough inflight packets are acknowledged for rate control purposes, but don't
// wait more than 500 ms before sending the packet.
while self.curr_window >= max_inflight && now_microseconds() - now < 500_000 {
debug!("self.curr_window: {}", self.curr_window);
debug!("max_inflight: {}", max_inflight);
debug!("self.duplicate_ack_count: {}", self.duplicate_ack_count);
debug!("now_microseconds() - now = {}", now_microseconds() - now);
let mut buf = [0; BUF_SIZE];
try!(self.recv(&mut buf));
}
debug!("out: now_microseconds() - now = {}", now_microseconds() - now);
// Check if it still makes sense to send packet, as we might be trying to resend a lost
// packet acknowledged in the receive loop above.
// If there were no wrapping around of sequence numbers, we'd simply check if the packet's
// sequence number is greater than `last_acked`.
let distance_a = packet.seq_nr().wrapping_sub(self.last_acked);
let distance_b = self.last_acked.wrapping_sub(packet.seq_nr());
if distance_a > distance_b {
debug!("Packet already acknowledged, skipping...");
return Ok(());
}
packet.set_timestamp_microseconds(now_microseconds());
packet.set_timestamp_difference_microseconds(self.their_delay);
try!(self.socket.send_to(&packet.to_bytes()[..], dst));
debug!("sent {:?}", packet);
Ok(())
}
// Insert a new sample in the base delay list.
//
// The base delay list contains at most `BASE_HISTORY` samples, each sample is the minimum
// measured over a period of a minute.
fn update_base_delay(&mut self, base_delay: i64, now: i64) {
let minute_in_microseconds = 60 * 10i64.pow(6);
if self.base_delays.is_empty() || now - self.last_rollover > minute_in_microseconds {
// Update last rollover
self.last_rollover = now;
// Drop the oldest sample, if need be
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_front();
}
// Insert new sample
self.base_delays.push_back(base_delay);
} else {
// Replace sample for the current minute if the delay is lower
let last_idx = self.base_delays.len() - 1;
if base_delay < self.base_delays[last_idx] {
self.base_delays[last_idx] = base_delay;
}
}
}
/// Inserts a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64,
MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculates the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculates the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
self.base_delays.iter().map(|x| *x).min().unwrap_or(0)
}
/// Builds the selective acknowledgment extension data for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|ref pkt| pkt.seq_nr() > self.ack_nr + 1)
.map(|ref pkt| (pkt.seq_nr() - self.ack_nr - 2) as usize)
.map(|diff| (diff / 8, diff % 8));
let mut sack = Vec::new();
for (byte, bit) in stashed {
// Make sure the amount of elements in the SACK vector is a
// multiple of 4 and enough to represent the lost packets
while byte >= sack.len() || sack.len() % 4 != 0 {
sack.push(0u8);
}
sack[byte] |= 1 << bit;
}
return sack;
}
/// Sends a fast resend request to the remote peer.
///
/// A fast resend request consists of sending three STATE packets (acknowledging the last
/// received packet) in quick succession.
fn send_fast_resend_request(&self) {
for _ in 0..3 {
let mut packet = Packet::new();
packet.set_type(PacketType::State);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = 0;
packet.set_timestamp_microseconds(self_t_micro);
packet.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
let _ = self.socket.send_to(&packet.to_bytes()[..], self.connected_to);
}
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
debug!("---> resend_lost_packet({}) <---", lost_packet_nr);
match self.send_window.iter().position(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(position) => {
debug!("self.send_window.len(): {}", self.send_window.len());
debug!("position: {}", position);
let mut packet = self.send_window[position].clone();
// FIXME: Unchecked result
let _ = self.send_packet(&mut packet);
// We intentionally don't increase `curr_window` because otherwise a packet's length
// would be counted more than once
}
}
debug!("---> END resend_lost_packet <---");
}
/// Forgets sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
// The reason I'm not removing the first element in a loop while its sequence number is
// smaller than `last_acked` is because of wrapping sequence numbers, which would create the
// sequence [..., 65534, 65535, 0, 1, ...]. If `last_acked` is smaller than the first
// packet's sequence number because of wraparound (for instance, 1), no packets would be
// removed, as the condition `seq_nr < last_acked` would fail immediately.
//
// On the other hand, I can't keep removing the first packet in a loop until its sequence
// number matches `last_acked` because it might never match, and in that case no packets
// should be removed.
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in (0..position + 1) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handles an incoming packet, updating socket state accordingly.
///
/// Returns the appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> Result<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != PacketType::Syn &&
self.state != SocketState::SynSent &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
// Update remote window size
self.remote_wnd_size = packet.wnd_size();
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
// Update remote peer's delay between them sending the packet and us receiving it
let now = now_microseconds();
self.their_delay = if now > packet.timestamp_microseconds() {
now - packet.timestamp_microseconds()
} else {
packet.timestamp_microseconds() - now
};
debug!("self.their_delay: {}", self.their_delay);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
self.last_dropped = self.ack_nr;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(_, PacketType::Syn) => {
Ok(Some(self.prepare_reply(packet, PacketType::Reset)))
}
(SocketState::SynSent, PacketType::State) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(Error::from(SocketError::InvalidReply))
}
(SocketState::Connected, PacketType::Data) |
(SocketState::FinSent, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) |
(SocketState::FinSent, PacketType::Fin) => {
if packet.ack_nr() < self.seq_nr {
debug!("FIN received but there are missing acknowledgments for sent packets");
}
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
// Give up, the remote peer might not care about our missing packets
self.state = SocketState::Closed;
Ok(Some(reply))
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
} else {
self.handle_state_packet(packet);
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(Error::from(SocketError::ConnectionReset))
},
(state, ty) => {
let message = format!("Unimplemented handling for ({:?},{:?})", state, ty);
debug!("{}", message);
Err(Error::new(ErrorKind::Other, message))
}
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
// If a FIN was previously sent, reply with a FIN packet acknowledging the received packet.
let packet_type = if self.state == SocketState::FinSent {
PacketType::Fin
} else {
PacketType::State
};
let mut reply = self.prepare_reply(packet, packet_type);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay - min_base_delay;
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
/// Calculates the new congestion window size, increasing it or decreasing it.
///
/// This is the core of uTP, the [LEDBAT][ledbat_rfc] congestion algorithm. It depends on
/// estimating the queuing delay between the two peers, and adjusting the congestion window
/// accordingly.
///
/// `off_target` is a normalized value representing the difference between the current queuing
/// delay and a fixed target delay (`TARGET`). `off_target` ranges between -1.0 and 1.0. A
/// positive value makes the congestion window increase, while a negative value makes the
/// congestion window decrease.
///
/// `bytes_newly_acked` is the number of bytes acknowledged by an inbound `State` packet. It may
/// be the size of the packet explicitly acknowledged by the inbound packet (i.e., with sequence
/// number equal to the inbound packet's acknowledgement number), or every packet implicitly
/// acknowledged (every packet with sequence number between the previous inbound `State`
/// packet's acknowledgement number and the current inbound `State` packet's acknowledgement
/// number).
///
///[ledbat_rfc]: https://tools.ietf.org/html/rfc6817
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
let flightsize = self.curr_window;
let cwnd_increase = GAIN * off_target * bytes_newly_acked as f64 * MSS as f64;
let cwnd_increase = cwnd_increase / self.cwnd as f64;
debug!("cwnd_increase: {}", cwnd_increase);
self.cwnd = (self.cwnd as f64 + cwnd_increase) as u32;
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update congestion window size
if let Some(index) = self.send_window.iter().position(|p| packet.ack_nr() == p.seq_nr()) {
// Calculate the sum of the size of every packet implicitly and explictly acknowledged
// by the inbound packet (i.e., every packet whose sequence number precedes the inbound
// packet's acknowledgement number, plus the packet whose sequence number matches)
let bytes_newly_acked = self.send_window.iter()
.take(index + 1)
.fold(0, |acc, p| acc + p.len());
// Update base and current delay
let now = now_microseconds() as i64;
let our_delay = now - self.send_window[index].timestamp_microseconds() as i64;
debug!("our_delay: {}", our_delay);
self.update_base_delay(our_delay, now);
self.update_current_delay(our_delay, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
self.update_congestion_window(off_target, bytes_newly_acked as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
}
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if extension.iter().count_ones() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
for seq_nr in extension.iter().enumerate()
.filter(|&(_idx, received)| !received)
.map(|(idx, _received)| packet.ack_nr() + 2 + idx as u16) {
if self.send_window.last().map(|p| seq_nr < p.seq_nr()).unwrap_or(false) {
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Three duplicate ACKs mean a fast resend request. Resend the first unacknowledged packet
// if the incoming packet doesn't have a SACK extension. If it does, the lost packets were
// already resent.
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 &&
!packet.extensions.iter().any(|ext| ext.get_type() == ExtensionType::SelectiveAck) {
self.resend_lost_packet(packet.ack_nr() + 1);
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Success, advance send window
self.advance_send_window();
}
/// Inserts a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
// Immediately push to the end if the packet's sequence number comes after the last
// packet's.
if self.incoming_buffer.last().map(|p| packet.seq_nr() > p.seq_nr()).unwrap_or(false) {
self.incoming_buffer.push(packet);
} else {
// Find index following the most recent packet before the one we wish to insert
let i = self.incoming_buffer.iter().filter(|p| p.seq_nr() < packet.seq_nr()).count();
// Replace packet if it's a duplicate
if self.incoming_buffer.get(i).map(|p| p.seq_nr() == packet.seq_nr()).unwrap_or(false) {
self.incoming_buffer[i] = packet;
} else {
self.incoming_buffer.insert(i, packet);
}
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
let _ = self.close();
}
}
/// A structure representing a socket server.
///
/// # Examples
///
/// ```no_run
/// use utp::{UtpListener, UtpSocket};
/// use std::thread;
///
/// fn handle_client(socket: UtpSocket) {
/// // ...
/// }
///
/// fn main() {
/// // Create a listener
/// let addr = "127.0.0.1:8080";
/// let listener = UtpListener::bind(addr).unwrap();
///
/// for connection in listener.incoming() {
/// // Spawn a new handler for each new connection
/// match connection {
/// Ok((socket, _src)) => { thread::spawn(move || { handle_client(socket) }); },
/// _ => ()
/// }
/// }
/// }
/// ```
pub struct UtpListener {
/// The public facing UDP socket
socket: UdpSocket,
}
impl UtpListener {
/// Creates a new `UtpListener` bound to a specific address.
///
/// The resulting listener is ready for accepting connections.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpListener> {
UdpSocket::bind(addr).and_then(|s| Ok(UtpListener { socket: s}))
}
/// Accepts a new incoming connection from this listener.
///
/// This function will block the caller until a new uTP connection is established. When
/// established, the corresponding `UtpSocket` and the peer's remote address will be returned.
///
/// Notice that the resulting `UtpSocket` is bound to a different local port than the public
/// listening port (which `UtpListener` holds). This may confuse the remote peer!
pub fn accept(&self) -> Result<(UtpSocket, SocketAddr)> {
let mut buf = [0; BUF_SIZE];
match self.socket.recv_from(&mut buf) {
Ok((nread, src)) => {
let packet = try!(Packet::from_bytes(&buf[..nread])
.or(Err(SocketError::InvalidPacket)));
// Ignore non-SYN packets
if packet.get_type() != PacketType::Syn {
return Err(Error::from(SocketError::InvalidPacket));
}
// The address of the new socket will depend on the type of the listener.
let inner_socket = self.socket.local_addr().and_then(|addr| match addr {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0"),
SocketAddr::V6(_) => UdpSocket::bind(":::0"),
});
let mut socket = try!(inner_socket.map(|s| UtpSocket::from_raw_parts(s, src)));
// Establish connection with remote peer
match socket.handle_packet(&packet, src) {
Ok(Some(reply)) => { try!(socket.socket.send_to(&reply.to_bytes()[..], src)) },
Ok(None) => return Err(Error::from(SocketError::InvalidPacket)),
Err(e) => return Err(e)
};
Ok((socket, src))
},
Err(e) => Err(e)
}
}
/// Returns an iterator over the connections being received by this listener.
///
/// The returned iterator will never return `None`.
pub fn incoming(&self) -> Incoming {
Incoming { listener: self }
}
/// Returns the local socket address of this listener.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
}
pub struct Incoming<'a> { listener: &'a UtpListener }
impl<'a> Iterator for Incoming<'a> {
type Item = Result<(UtpSocket, SocketAddr)>;
fn next(&mut self) -> Option<Result<(UtpSocket, SocketAddr)>> {
Some(self.listener.accept())
}
}
#[cfg(test)]
mod test {
use std::thread;
use std::net::ToSocketAddrs;
use std::io::ErrorKind;
use super::{UtpSocket, UtpListener, SocketState, BUF_SIZE, take_address};
use packet::{Packet, PacketType, Encodable, Decodable};
use util::now_microseconds;
use rand;
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{:?}", e) })
}
fn next_test_port() -> u16 {
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
const BASE_PORT: u16 = 9600;
BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
fn next_test_ip4<'a>() -> (&'a str, u16) {
("127.0.0.1", next_test_port())
}
fn next_test_ip6<'a>() -> (&'a str, u16) {
("::1", next_test_port())
}
#[test]
fn test_socket_ipv4() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_socket_ipv6() {
let server_addr = next_test_ip6();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert!(client.close().is_ok());
});
// Make the server listen for incoming connections until the end of the input
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Closed);
// Trying to receive again returns Ok(0) [EndOfFile]
match server.recv_from(&mut buf) {
Ok((0, _src)) => {},
e => panic!("Expected Ok(0), got {:?}", e),
}
assert_eq!(server.state, SocketState::Closed);
}
#[test]
fn test_sendto_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
iotry!(client.close());
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an error
match server.send_to(&buf) {
Err(ref e) if e.kind() == ErrorKind::NotConnected => (),
v => panic!("expected {:?}, got {:?}", ErrorKind::NotConnected, v),
}
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let server_addr = next_test_ip4();
let (tx, rx) = channel();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert!(client.close().is_ok());
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1, 2, 3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4, 5, 6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_socket_unordered_packets() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
let s = client.socket.try_clone().ok().expect("Error cloning internal UDP socket");
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>()[..].chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
client.curr_window += packet.len() as u32;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(&window[3].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[2].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[1].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[0].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[4].to_bytes()[..], server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0; BUF_SIZE];
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.state, SocketState::Closed);
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_response_to_triple_ack() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&d[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv(&mut buf));
// Receive data
let data_packet = match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => iotry!(Packet::from_bytes(&buf[..read])),
Err(e) => panic!("{}", e),
};
assert_eq!(data_packet.get_type(), PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to));
}
// Receive data again and check that it's the same we reported as missing
let client_addr = server.connected_to;
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..read]));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(&response.to_bytes()[..], server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(&d[..]));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
server.recv(&mut buf).unwrap();
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1, 2, 3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(client.socket.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
iotry!(server.recv(&mut buf));
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1, 2, 3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
// #[test]
// #[ignore]
// fn test_selective_ack_response() {
// let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
// const LEN: usize = 1024 * 10;
// let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
// let to_send = data.clone();
// // Client
// thread::spawn(move || {
// let client = iotry!(UtpSocket::bind(client_addr));
// let mut client = iotry!(UtpSocket::connect(server_addr));
// client.congestion_timeout = 50;
// iotry!(client.send_to(&to_send[..]));
// iotry!(client.close());
// });
// // Server
// let mut server = iotry!(UtpSocket::bind(server_addr));
// let mut buf = [0; BUF_SIZE];
// // Connect
// iotry!(server.recv_from(&mut buf));
// // Discard packets
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// // Generate SACK
// let mut packet = Packet::new();
// packet.set_seq_nr(server.seq_nr);
// packet.set_ack_nr(server.ack_nr - 1);
// packet.set_connection_id(server.sender_connection_id);
// packet.set_timestamp_microseconds(now_microseconds());
// packet.set_type(PacketType::State);
// packet.set_sack(vec!(12, 0, 0, 0));
// // Send SACK
// iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to.clone()));
// // Expect to receive "missing" packets
// let mut received: Vec<u8> = vec!();
// loop {
// match server.recv_from(&mut buf) {
// Ok((0, _src)) => break,
// Ok((len, _src)) => received.extend(buf[..len].to_vec()),
// Err(e) => panic!("{:?}", e)
// }
// }
// assert!(!received.is_empty());
// assert_eq!(received.len(), data.len());
// assert_eq!(received, data);
// }
#[test]
fn test_correct_packet_loss() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send[..].chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(&packet.to_bytes()[..], dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => break,
Ok((len, _src)) => read.extend(small_buffer[..len].to_vec()),
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(&to_send[..]));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_drop_unused_socket() {
let server_addr = next_test_ip4();
let server = iotry!(UtpSocket::bind(server_addr));
// Explicitly dropping socket. This test should not hang.
drop(server);
}
#[test]
fn test_invalid_packet_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => { iotry!(server.send_to(&[], client_addr)); },
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::Other => (), // OK
Err(e) => panic!("Expected ErrorKind::Other, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receive_unexpected_reply_type_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => {
iotry!(server.send_to(&packet.to_bytes()[..], client_addr));
},
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::ConnectionRefused => (), // OK
Err(e) => panic!("Expected ErrorKind::ConnectionRefused, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receiving_syn_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(e) => panic!("{:?}", e)
}
}
});
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let reply = Packet::from_bytes(&buf[..len]).ok().unwrap();
assert_eq!(reply.get_type(), PacketType::Reset);
}
Err(e) => panic!("{:?}", e)
}
}
#[test]
fn test_receiving_reset_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Reset);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((_len, _src)) => (),
Err(e) => panic!("{:?}", e)
}
});
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(ref e) if e.kind() == ErrorKind::ConnectionReset => return,
Err(e) => panic!("{:?}", e)
}
}
panic!("Should have received Reset");
}
#[test]
fn test_premature_fin() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Accept connection
iotry!(server.recv(&mut buf));
// Send FIN without acknowledging packets received
let mut packet = Packet::new();
packet.set_connection_id(server.sender_connection_id);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
iotry!(server.socket.send_to(&packet.to_bytes()[..], client_addr));
// Receive until end
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_base_delay_calculation() {
let minute_in_microseconds = 60 * 10i64.pow(6);
let samples = vec![(0, 10), (1, 8), (2, 12), (3, 7),
(minute_in_microseconds + 1, 11),
(minute_in_microseconds + 2, 19),
(minute_in_microseconds + 3, 9)];
let addr = next_test_ip4();
let mut socket = UtpSocket::bind(addr).unwrap();
for (timestamp, delay) in samples{
socket.update_base_delay(delay, timestamp + delay);
}
let expected = vec![7, 9];
let actual = socket.base_delays.iter().map(|&x| x).collect::<Vec<_>>();
assert_eq!(expected, actual);
assert_eq!(socket.min_base_delay(), 7);
}
#[test]
fn test_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let socket = UtpSocket::bind(addr).unwrap();
assert!(socket.local_addr().is_ok());
assert_eq!(socket.local_addr().unwrap(), addr);
}
#[test]
fn test_listener_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let listener = UtpListener::bind(addr).unwrap();
assert!(listener.local_addr().is_ok());
assert_eq!(listener.local_addr().unwrap(), addr);
}
#[test]
fn test_take_address() {
// Expected succcesses
assert!(take_address(("0.0.0.0:0")).is_ok());
assert!(take_address((":::0")).is_ok());
assert!(take_address(("0.0.0.0", 0)).is_ok());
assert!(take_address(("::", 0)).is_ok());
assert!(take_address(("1.2.3.4", 5)).is_ok());
// Expected failures
assert!(take_address("999.0.0.0:0").is_err());
assert!(take_address(("1.2.3.4:70000")).is_err());
assert!(take_address("").is_err());
assert!(take_address("this is not an address").is_err());
assert!(take_address("no.dns.resolution.com").is_err());
}
// Test reaction to connection loss when sending data packets
#[test]
fn test_connection_loss_data() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Data),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
iotry!(server.send_to(&[0]));
// Try to receive ACKs, time out too many times on flush, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when sending FIN
#[test]
fn test_connection_loss_fin() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Fin),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Send FIN, time out too many times, and fail with `TimedOut`
match server.close() {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when waiting for data packets
#[test]
fn test_connection_loss_waiting() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let seq_nr = client.seq_nr;
let mut buf = [0; BUF_SIZE];
for _ in 0..(3 * attempts) {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..len]));
assert_eq!(packet.get_type(), PacketType::State);
assert_eq!(packet.ack_nr(), seq_nr - 1);
},
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Try to receive data, time out too many times, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
}
|
/// Context:
/// * Rust does not have tail call optimization, so we cannot recurse wildly
/// * data lifetimes makes sure that the result of a function applied to a producer cannot live longer than the producer's data (unless there is cloning)
/// * previous implementation of Producer and Consumer spent its time copying buffers
/// * the old Consumer was handling everything and buffering data. The new design has the producer handle data, but the consumer makes seeking decision
use std::io::{self,Read,Write,Seek,SeekFrom};
use std::fs::File;
use std::path::Path;
use std::ptr;
use std::iter::repeat;
use internal::Needed;
//pub type Computation<I,O,S,E> = Box<Fn(S, Input<I>) -> (I,Consumer<I,O,S,E>)>;
#[derive(Debug,Clone)]
pub enum Input<I> {
Element(I),
Empty,
Eof(Option<I>)
}
/// Stores a consumer's current computation state
#[derive(Debug,Clone)]
pub enum ConsumerState<O,E=(),M=()> {
/// A value pf type O has been produced
Done(M,O),
/// An error of type E has been encountered
Error(E),
/// Continue applying, and pass a message of type M to the data source
Continue(M)
}
impl<O:Clone,E:Copy,M:Copy> ConsumerState<O,E,M> {
pub fn map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(O) -> P {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => ConsumerState::Done(m, f(o.clone()))
}
}
pub fn flat_map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(M, O) -> ConsumerState<P,E,M> {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => f(m, o.clone())
}
}
}
/// The Consumer trait wraps a computation and its state
///
/// it depends on the input type I, the produced value's type O, the error type E, and the message type M
pub trait Consumer<I,O,E,M> {
/// implement hndle for the current computation, returning the new state of the consumer
fn handle(&mut self, input: Input<I>) -> &ConsumerState<O,E,M>;
/// returns the current state
fn state(&self) -> &ConsumerState<O,E,M>;
}
/// The producer wraps a data source, like file or network, and applies a consumer on it
///
/// it handles buffer copying and reallocation, to provide streaming patterns.
/// it depends on the input type I, and the message type M.
/// the consumer can change the way data is produced (for example, to seek in the source) by sending a message of type M.
pub trait Producer<'b,I,M: 'b> {
/// Applies a consumer once on the produced data, and return the consumer's state
///
/// a new producer has to implement this method
fn apply<'a, O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M>;
/// Applies a consumer once on the produced data, and returns the generated value if there is one
fn run<'a: 'b,O,E: 'b>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> Option<&O> {
if let &ConsumerState::Done(_,ref o) = self.apply(consumer) {
Some(o)
} else {
None
}
}
// fn fromFile, FromSocket, fromRead
}
/// ProducerRepeat takes a single value, and generates it at each step
pub struct ProducerRepeat<I:Copy> {
value: I
}
impl<'b,I:Copy,M: 'b> Producer<'b,I,M> for ProducerRepeat<I> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M> {
if {
if let &ConsumerState::Continue(_) = consumer.state() {
true
} else {
false
}
}
{
consumer.handle(Input::Element(self.value))
} else {
consumer.state()
}
}
}
/// A MemProducer generates values from an in memory byte buffer
///
/// it generates data by chunks, and keeps track of how much was consumed.
/// It can receive messages of type `Move` to handle consumption and seeking
pub struct MemProducer<'x> {
buffer: &'x [u8],
chunk_size: usize,
length: usize,
index: usize
}
impl<'x> MemProducer<'x> {
pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer {
MemProducer {
buffer: buffer,
chunk_size: chunk_size,
length: buffer.len(),
index: 0
}
}
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub enum Move {
/// indcates how much data was consumed
Consume(usize),
/// indicates where in the input the consumer must seek
Seek(SeekFrom),
/// indicates more data is needed
Await(Needed)
}
impl<'x,'b> Producer<'b,&'x[u8],Move> for MemProducer<'x> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
if self.length - self.index >= s {
self.index += s
} else {
panic!("cannot consume past the end of the buffer");
}
},
Move::Await(a) => {
panic!("not handled for now: await({:?}", a);
}
Move::Seek(SeekFrom::Start(position)) => {
if position as usize > self.length {
self.index = self.length
} else {
self.index = position as usize
}
},
Move::Seek(SeekFrom::Current(offset)) => {
let next = if offset >= 0 {
(self.index as u64).checked_add(offset as u64)
} else {
(self.index as u64).checked_sub(-offset as u64)
};
match next {
None => None,
Some(u) => {
if u as usize > self.length {
self.index = self.length
} else {
self.index = u as usize
}
Some(self.index as u64)
}
};
},
Move::Seek(SeekFrom::End(i)) => {
let next = if i < 0 {
(self.length as u64).checked_sub(-i as u64)
} else {
// std::io::SeekFrom documentation explicitly allows
// seeking beyond the end of the stream, so we seek
// to the end of the content if the offset is 0 or
// greater.
Some(self.length as u64)
};
match next {
// std::io:SeekFrom documentation states that it `is an
// error to seek before byte 0.' So it's the sensible
// thing to refuse to seek on underflow.
None => None,
Some(u) => {
self.index = u as usize;
Some(u)
}
};
}
}
true
} else {
false
}
}
{
use std::cmp;
let end = cmp::min(self.index + self.chunk_size, self.length);
consumer.handle(Input::Element(&self.buffer[self.index..end]))
} else {
consumer.state()
}
}
}
#[derive(Debug,Copy,Clone,PartialEq,Eq)]
pub enum FileProducerState {
Normal,
Error,
Eof
}
#[derive(Debug)]
pub struct FileProducer {
size: usize,
file: File,
position: usize,
v: Vec<u8>,
start: usize,
end: usize,
state: FileProducerState,
}
impl FileProducer {
pub fn new(filename: &str, buffer_size: usize) -> io::Result<FileProducer> {
File::open(&Path::new(filename)).and_then(|mut f| {
f.seek(SeekFrom::Start(0)).map(|_| {
let mut v = Vec::with_capacity(buffer_size);
v.extend(repeat(0).take(buffer_size));
FileProducer {size: buffer_size, file: f, position: 0, v: v, start: 0, end: 0, state: FileProducerState::Normal }
})
})
}
pub fn state(&self) -> FileProducerState {
self.state
}
// FIXME: should handle refill until a certain size is obtained
pub fn refill(&mut self) -> Option<usize> {
shift(&mut self.v, self.start, self.end);
self.end = self.end - self.start;
self.start = 0;
match self.file.read(&mut self.v[self.end..]) {
Err(_) => {
self.state = FileProducerState::Error;
None
},
Ok(n) => {
//println!("read: {} bytes\ndata:\n{:?}", n, &self.v);
if n == 0 {
self.state = FileProducerState::Eof;
}
self.end += n;
Some(0)
}
}
}
/// Resize the internal buffer, copy the data to the new one and returned how much data was copied
///
/// If the new buffer is smaller, the prefix will be copied, and the rest of the data will be dropped
pub fn resize(&mut self, s: usize) -> usize {
let mut v = vec![0; s];
let length = self.end - self.start;
let size = if length <= s { length } else { s };
// Use `Write` for `&mut [u8]`
(&mut v[..]).write(&self.v[self.start..self.start + size]).unwrap();
self.v = v;
self.start = 0;
self.end = size;
size
}
}
pub fn shift(s: &mut[u8], start: usize, end: usize) {
if start > 0 {
unsafe {
let length = end - start;
ptr::copy( (&s[start..end]).as_ptr(), (&mut s[..length]).as_mut_ptr(), length);
}
}
}
impl<'x> Producer<'x,&'x [u8],Move> for FileProducer {
fn apply<'a,O,E>(&'x mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
//consumer.handle(Input::Element(&self.v[self.start..self.end]))
//self.my_apply(consumer)
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
//println!("start: {}, end: {}, consumed: {}", self.start, self.end, s);
if self.end - self.start >= s {
self.start = self.start + s;
self.position = self.position + s;
} else {
panic!("cannot consume past the end of the buffer");
}
if self.start == self.end {
self.refill();
}
},
Move::Await(_) => {
self.refill();
},
// FIXME: naive seeking for now
Move::Seek(position) => {
let pos = match position {
// take into account data in the buffer
SeekFrom::Current(c) => SeekFrom::Current(c - (self.end - self.start) as i64),
default => default
};
match self.file.seek(pos) {
Ok(pos) => {
//println!("file got seek to position {:?}. New position is {:?}", position, next);
self.position = pos as usize;
self.start = 0;
self.end = 0;
self.refill();
},
Err(_) => {
self.state = FileProducerState::Error;
}
}
}
}
true
} else {
false
}
}
{
//println!("producer state: {:?}", self.state);
match self.state {
FileProducerState::Normal => consumer.handle(Input::Element(&self.v[self.start..self.end])),
FileProducerState::Eof => {
let slice = &self.v[self.start..self.end];
if slice.is_empty() {
consumer.handle(Input::Eof(None))
} else {
consumer.handle(Input::Eof(Some(slice)))
}
}
// is it right?
FileProducerState::Error => consumer.state()
}
} else {
consumer.state()
}
}
}
use std::marker::PhantomData;
/// MapConsumer takes a function S -> T and applies it on a consumer producing values of type S
pub struct MapConsumer<'a, C:'a,R,S,T,E,M,F> {
state: ConsumerState<T,E,M>,
consumer: &'a mut C,
f: F,
consumer_input_type: PhantomData<R>,
f_input_type: PhantomData<S>,
f_output_type: PhantomData<T>
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> MapConsumer<'a,C,R,S,T,E,M,F> {
pub fn new(c: &'a mut C, f: F) -> MapConsumer<'a,C,R,S,T,E,M,F> {
//let state = c.state();
let initial = match *c.state() {
ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), f(o.clone())),
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
MapConsumer {
state: initial,
consumer: c,
f: f,
consumer_input_type: PhantomData,
f_input_type: PhantomData,
f_output_type: PhantomData
}
}
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> Consumer<R,T,E,M> for MapConsumer<'a,C,R,S,T,E,M,F> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer.handle(input);
self.state = match res {
&ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), (self.f)(o.clone())),
&ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
&ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
/// ChainConsumer takes a consumer C1 R -> S, and a consumer C2 S -> T, and makes a consumer R -> T by applying C2 on C1's result
pub struct ChainConsumer<'a,'b, C1:'a,C2:'b,R,S,T,E,M> {
state: ConsumerState<T,E,M>,
consumer1: &'a mut C1,
consumer2: &'b mut C2,
input_type: PhantomData<R>,
temp_type: PhantomData<S>
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
pub fn new(c1: &'a mut C1, c2: &'b mut C2) -> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
let initial = match *c1.state() {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *c2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m2) => ConsumerState::Continue(m2.clone()),
ConsumerState::Done(_,ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
ChainConsumer {
state: initial,
consumer1: c1,
consumer2: c2,
input_type: PhantomData,
temp_type: PhantomData
}
}
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> Consumer<R,T,E,M> for ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer1.handle(input);
self.state = match *res {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *self.consumer2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(_, ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
#[macro_export]
macro_rules! consumer_from_parser (
//FIXME: should specify the error and move type
($name:ident<$input:ty, $output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl $crate::Consumer<$input, $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<$input>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl<'a> $crate::Consumer<&'a[u8], $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<&'a[u8]>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$input:ty, $output:ty>, $f:expr) => (
consumer_from_parser!($name<$input, $output>, call!($f));
);
($name:ident<$output:ty>, $f:expr) => (
consumer_from_parser!($name<$output>, call!($f));
);
);
#[cfg(test)]
mod tests {
use super::*;
use internal::IResult;
use util::HexDisplay;
use std::str::from_utf8;
use std::io::SeekFrom;
#[derive(Debug)]
struct AbcdConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>
}
named!(abcd, tag!("abcd"));
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for AbcdConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8],(),Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
};
&self.state
}
Input::Eof(Some(sl)) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
// we cannot return incomplete on Eof
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
#[test]
fn mem() {
let mut m = MemProducer::new(&b"abcdabcdabcdabcdabcd"[..], 8);
let mut a = AbcdConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
named!(efgh, tag!("efgh"));
named!(ijkl, tag!("ijkl"));
#[derive(Debug)]
enum State {
Initial,
A,
B,
End,
Error
}
#[derive(Debug)]
struct StateConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>,
parsing_state: State
}
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for StateConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8], (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
Input::Eof(Some(sl)) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Error(())
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Error(())
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
impl<'a> StateConsumer<'a> {
fn parsing(&self) -> &State {
&self.parsing_state
}
}
#[test]
fn mem2() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut a = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
//assert!(false);
}
#[test]
fn map() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut a = MapConsumer::new(&mut s, from_utf8);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
#[derive(Debug)]
struct StrConsumer<'a> {
state: ConsumerState<&'a str, (), Move>
}
impl<'a> Consumer<&'a [u8], &'a str, (), Move> for StrConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a str, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
self.state = ConsumerState::Done(Move::Consume(sl.len()), from_utf8(sl).unwrap());
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a str, (), Move> {
&self.state
}
}
#[test]
fn chain() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s1 = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut s2 = StrConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
let mut a = ChainConsumer::new(&mut s1, &mut s2);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
//
//let x = [0, 1, 2, 3, 4];
//let b = [1, 2, 3];
//assert_eq!(&x[1..3], &b[..]);
}
#[test]
fn shift_test() {
let mut v = vec![0,1,2,3,4,5];
shift(&mut v, 1, 3);
assert_eq!(&v[..2], &[1,2][..]);
let mut v2 = vec![0,1,2,3,4,5];
shift(&mut v2, 2, 6);
assert_eq!(&v2[..4], &[2,3,4,5][..]);
}
/*#[derive(Debug)]
struct LineConsumer {
state: ConsumerState<String, (), Move>
}
impl<'a> Consumer<&'a [u8], String, (), Move> for LineConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<String, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
//println!("got slice: {:?}", sl);
self.state = match line(sl) {
IResult::Incomplete(n) => {
println!("line not complete, continue (line was \"{}\")", from_utf8(sl).unwrap());
ConsumerState::Continue(Move::Await(n))
},
IResult::Error(e) => {
println!("LineConsumer parsing error: {:?}", e);
ConsumerState::Error(())
},
IResult::Done(i,o) => {
let res = String::from(from_utf8(o).unwrap());
println!("found: {}", res);
//println!("sl: {:?}\ni:{:?}\noffset:{}", sl, i, sl.offset(i));
ConsumerState::Done(Move::Consume(sl.offset(i)), res)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<String, (), Move> {
&self.state
}
}*/
fn lf(i:& u8) -> bool {
*i == '\n' as u8
}
fn to_utf8_string(input:&[u8]) -> String {
String::from(from_utf8(input).unwrap())
}
//named!(line<&[u8]>, terminated!(take_till!(lf), tag!("\n")));
consumer_from_parser!(LineConsumer<String>, map!(terminated!(take_till!(lf), tag!("\n")), to_utf8_string));
fn get_line(producer: &mut FileProducer, mv: Move) -> Option<(Move,String)> {
let mut a = LineConsumer { state: ConsumerState::Continue(mv) };
while let &ConsumerState::Continue(_) = producer.apply(&mut a) {
println!("continue");
}
if let &ConsumerState::Done(ref m, ref s) = a.state() {
Some((m.clone(), s.clone()))
} else {
None
}
}
#[test]
fn file() {
let mut f = FileProducer::new("LICENSE", 200).unwrap();
f.refill();
let mut mv = Move::Consume(0);
for i in 1..10 {
if let Some((m,s)) = get_line(&mut f, mv.clone()) {
println!("got line[{}]: {}", i, s);
mv = m;
} else {
assert!(false, "LineConsumer should not have failed");
}
}
//assert!(false);
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
enum SeekState {
Begin,
SeekedToEnd,
ShouldEof,
IsEof
}
#[derive(Debug)]
struct SeekingConsumer {
state: ConsumerState<(), u8, Move>,
position: SeekState
}
impl SeekingConsumer {
fn position(&self) -> SeekState {
self.position
}
}
impl<'a> Consumer<&'a [u8], (), u8, Move> for SeekingConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<(), u8, Move> {
println!("input: {:?}", input);
match self.position {
SeekState::Begin => {
self.state = ConsumerState::Continue(Move::Seek(SeekFrom::End(-4)));
self.position = SeekState::SeekedToEnd;
},
SeekState::SeekedToEnd => match input {
Input::Element(sl) => {
if sl.len() == 4 {
self.state = ConsumerState::Continue(Move::Consume(4));
self.position = SeekState::ShouldEof;
} else {
self.state = ConsumerState::Error(0);
}
},
Input::Eof(Some(sl)) => {
if sl.len() == 4 {
self.state = ConsumerState::Done(Move::Consume(4), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(1);
}
},
_ => self.state = ConsumerState::Error(2)
},
SeekState::ShouldEof => match input {
Input::Eof(Some(sl)) => {
if sl.len() == 0 {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(3);
}
},
Input::Eof(None) => {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
},
_ => self.state = ConsumerState::Error(4)
},
_ => self.state = ConsumerState::Error(5)
};
&self.state
}
fn state(&self) -> &ConsumerState<(), u8, Move> {
&self.state
}
}
#[test]
fn seeking_consumer() {
let mut f = FileProducer::new("assets/testfile.txt", 200).unwrap();
f.refill();
let mut a = SeekingConsumer { state: ConsumerState::Continue(Move::Consume(0)), position: SeekState::Begin };
for _ in 1..4 {
println!("file apply {:?}", f.apply(&mut a));
}
println!("consumer is now: {:?}", a);
if let &ConsumerState::Done(Move::Consume(0), ()) = a.state() {
println!("end");
} else {
println!("invalid state is {:?}", a.state());
assert!(false, "consumer is not at EOF");
}
assert_eq!(a.position(), SeekState::IsEof);
}
}
More documentation for Producer::apply()
/// Context:
/// * Rust does not have tail call optimization, so we cannot recurse wildly
/// * data lifetimes makes sure that the result of a function applied to a producer cannot live longer than the producer's data (unless there is cloning)
/// * previous implementation of Producer and Consumer spent its time copying buffers
/// * the old Consumer was handling everything and buffering data. The new design has the producer handle data, but the consumer makes seeking decision
use std::io::{self,Read,Write,Seek,SeekFrom};
use std::fs::File;
use std::path::Path;
use std::ptr;
use std::iter::repeat;
use internal::Needed;
//pub type Computation<I,O,S,E> = Box<Fn(S, Input<I>) -> (I,Consumer<I,O,S,E>)>;
#[derive(Debug,Clone)]
pub enum Input<I> {
Element(I),
Empty,
Eof(Option<I>)
}
/// Stores a consumer's current computation state
#[derive(Debug,Clone)]
pub enum ConsumerState<O,E=(),M=()> {
/// A value pf type O has been produced
Done(M,O),
/// An error of type E has been encountered
Error(E),
/// Continue applying, and pass a message of type M to the data source
Continue(M)
}
impl<O:Clone,E:Copy,M:Copy> ConsumerState<O,E,M> {
pub fn map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(O) -> P {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => ConsumerState::Done(m, f(o.clone()))
}
}
pub fn flat_map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(M, O) -> ConsumerState<P,E,M> {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => f(m, o.clone())
}
}
}
/// The Consumer trait wraps a computation and its state
///
/// it depends on the input type I, the produced value's type O, the error type E, and the message type M
pub trait Consumer<I,O,E,M> {
/// implement hndle for the current computation, returning the new state of the consumer
fn handle(&mut self, input: Input<I>) -> &ConsumerState<O,E,M>;
/// returns the current state
fn state(&self) -> &ConsumerState<O,E,M>;
}
/// The producer wraps a data source, like file or network, and applies a consumer on it
///
/// it handles buffer copying and reallocation, to provide streaming patterns.
/// it depends on the input type I, and the message type M.
/// the consumer can change the way data is produced (for example, to seek in the source) by sending a message of type M.
pub trait Producer<'b,I,M: 'b> {
/// Applies a consumer once on the produced data, and return the consumer's state
///
/// a new producer has to implement this method.
///
/// WARNING: if the `ConsumerState` generated by your consumer has a reference
/// to the input, it will generate borrow checking errors such as
/// `error: cannot borrow `producer` as mutable more than once at a time [E0499]`.
///
/// It is caused by the producer's ability to refill the input at will, so it can modify
/// the input slice the `ConsumerState` is referring to.
///
/// To avoid that kind of issue, try to do all the computations on input slices inside the
/// `Consumer` chain
fn apply<'a, O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M>;
/// Applies a consumer once on the produced data, and returns the generated value if there is one
fn run<'a: 'b,O,E: 'b>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> Option<&O> {
if let &ConsumerState::Done(_,ref o) = self.apply(consumer) {
Some(o)
} else {
None
}
}
// fn fromFile, FromSocket, fromRead
}
/// ProducerRepeat takes a single value, and generates it at each step
pub struct ProducerRepeat<I:Copy> {
value: I
}
impl<'b,I:Copy,M: 'b> Producer<'b,I,M> for ProducerRepeat<I> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M> {
if {
if let &ConsumerState::Continue(_) = consumer.state() {
true
} else {
false
}
}
{
consumer.handle(Input::Element(self.value))
} else {
consumer.state()
}
}
}
/// A MemProducer generates values from an in memory byte buffer
///
/// it generates data by chunks, and keeps track of how much was consumed.
/// It can receive messages of type `Move` to handle consumption and seeking
pub struct MemProducer<'x> {
buffer: &'x [u8],
chunk_size: usize,
length: usize,
index: usize
}
impl<'x> MemProducer<'x> {
pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer {
MemProducer {
buffer: buffer,
chunk_size: chunk_size,
length: buffer.len(),
index: 0
}
}
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub enum Move {
/// indcates how much data was consumed
Consume(usize),
/// indicates where in the input the consumer must seek
Seek(SeekFrom),
/// indicates more data is needed
Await(Needed)
}
impl<'x,'b> Producer<'b,&'x[u8],Move> for MemProducer<'x> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
if self.length - self.index >= s {
self.index += s
} else {
panic!("cannot consume past the end of the buffer");
}
},
Move::Await(a) => {
panic!("not handled for now: await({:?}", a);
}
Move::Seek(SeekFrom::Start(position)) => {
if position as usize > self.length {
self.index = self.length
} else {
self.index = position as usize
}
},
Move::Seek(SeekFrom::Current(offset)) => {
let next = if offset >= 0 {
(self.index as u64).checked_add(offset as u64)
} else {
(self.index as u64).checked_sub(-offset as u64)
};
match next {
None => None,
Some(u) => {
if u as usize > self.length {
self.index = self.length
} else {
self.index = u as usize
}
Some(self.index as u64)
}
};
},
Move::Seek(SeekFrom::End(i)) => {
let next = if i < 0 {
(self.length as u64).checked_sub(-i as u64)
} else {
// std::io::SeekFrom documentation explicitly allows
// seeking beyond the end of the stream, so we seek
// to the end of the content if the offset is 0 or
// greater.
Some(self.length as u64)
};
match next {
// std::io:SeekFrom documentation states that it `is an
// error to seek before byte 0.' So it's the sensible
// thing to refuse to seek on underflow.
None => None,
Some(u) => {
self.index = u as usize;
Some(u)
}
};
}
}
true
} else {
false
}
}
{
use std::cmp;
let end = cmp::min(self.index + self.chunk_size, self.length);
consumer.handle(Input::Element(&self.buffer[self.index..end]))
} else {
consumer.state()
}
}
}
#[derive(Debug,Copy,Clone,PartialEq,Eq)]
pub enum FileProducerState {
Normal,
Error,
Eof
}
#[derive(Debug)]
pub struct FileProducer {
size: usize,
file: File,
position: usize,
v: Vec<u8>,
start: usize,
end: usize,
state: FileProducerState,
}
impl FileProducer {
pub fn new(filename: &str, buffer_size: usize) -> io::Result<FileProducer> {
File::open(&Path::new(filename)).and_then(|mut f| {
f.seek(SeekFrom::Start(0)).map(|_| {
let mut v = Vec::with_capacity(buffer_size);
v.extend(repeat(0).take(buffer_size));
FileProducer {size: buffer_size, file: f, position: 0, v: v, start: 0, end: 0, state: FileProducerState::Normal }
})
})
}
pub fn state(&self) -> FileProducerState {
self.state
}
// FIXME: should handle refill until a certain size is obtained
pub fn refill(&mut self) -> Option<usize> {
shift(&mut self.v, self.start, self.end);
self.end = self.end - self.start;
self.start = 0;
match self.file.read(&mut self.v[self.end..]) {
Err(_) => {
self.state = FileProducerState::Error;
None
},
Ok(n) => {
//println!("read: {} bytes\ndata:\n{:?}", n, &self.v);
if n == 0 {
self.state = FileProducerState::Eof;
}
self.end += n;
Some(0)
}
}
}
/// Resize the internal buffer, copy the data to the new one and returned how much data was copied
///
/// If the new buffer is smaller, the prefix will be copied, and the rest of the data will be dropped
pub fn resize(&mut self, s: usize) -> usize {
let mut v = vec![0; s];
let length = self.end - self.start;
let size = if length <= s { length } else { s };
// Use `Write` for `&mut [u8]`
(&mut v[..]).write(&self.v[self.start..self.start + size]).unwrap();
self.v = v;
self.start = 0;
self.end = size;
size
}
}
pub fn shift(s: &mut[u8], start: usize, end: usize) {
if start > 0 {
unsafe {
let length = end - start;
ptr::copy( (&s[start..end]).as_ptr(), (&mut s[..length]).as_mut_ptr(), length);
}
}
}
impl<'x> Producer<'x,&'x [u8],Move> for FileProducer {
fn apply<'a,O,E>(&'x mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
//consumer.handle(Input::Element(&self.v[self.start..self.end]))
//self.my_apply(consumer)
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
//println!("start: {}, end: {}, consumed: {}", self.start, self.end, s);
if self.end - self.start >= s {
self.start = self.start + s;
self.position = self.position + s;
} else {
panic!("cannot consume past the end of the buffer");
}
if self.start == self.end {
self.refill();
}
},
Move::Await(_) => {
self.refill();
},
// FIXME: naive seeking for now
Move::Seek(position) => {
let pos = match position {
// take into account data in the buffer
SeekFrom::Current(c) => SeekFrom::Current(c - (self.end - self.start) as i64),
default => default
};
match self.file.seek(pos) {
Ok(pos) => {
//println!("file got seek to position {:?}. New position is {:?}", position, next);
self.position = pos as usize;
self.start = 0;
self.end = 0;
self.refill();
},
Err(_) => {
self.state = FileProducerState::Error;
}
}
}
}
true
} else {
false
}
}
{
//println!("producer state: {:?}", self.state);
match self.state {
FileProducerState::Normal => consumer.handle(Input::Element(&self.v[self.start..self.end])),
FileProducerState::Eof => {
let slice = &self.v[self.start..self.end];
if slice.is_empty() {
consumer.handle(Input::Eof(None))
} else {
consumer.handle(Input::Eof(Some(slice)))
}
}
// is it right?
FileProducerState::Error => consumer.state()
}
} else {
consumer.state()
}
}
}
use std::marker::PhantomData;
/// MapConsumer takes a function S -> T and applies it on a consumer producing values of type S
pub struct MapConsumer<'a, C:'a,R,S,T,E,M,F> {
state: ConsumerState<T,E,M>,
consumer: &'a mut C,
f: F,
consumer_input_type: PhantomData<R>,
f_input_type: PhantomData<S>,
f_output_type: PhantomData<T>
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> MapConsumer<'a,C,R,S,T,E,M,F> {
pub fn new(c: &'a mut C, f: F) -> MapConsumer<'a,C,R,S,T,E,M,F> {
//let state = c.state();
let initial = match *c.state() {
ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), f(o.clone())),
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
MapConsumer {
state: initial,
consumer: c,
f: f,
consumer_input_type: PhantomData,
f_input_type: PhantomData,
f_output_type: PhantomData
}
}
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> Consumer<R,T,E,M> for MapConsumer<'a,C,R,S,T,E,M,F> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer.handle(input);
self.state = match res {
&ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), (self.f)(o.clone())),
&ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
&ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
/// ChainConsumer takes a consumer C1 R -> S, and a consumer C2 S -> T, and makes a consumer R -> T by applying C2 on C1's result
pub struct ChainConsumer<'a,'b, C1:'a,C2:'b,R,S,T,E,M> {
state: ConsumerState<T,E,M>,
consumer1: &'a mut C1,
consumer2: &'b mut C2,
input_type: PhantomData<R>,
temp_type: PhantomData<S>
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
pub fn new(c1: &'a mut C1, c2: &'b mut C2) -> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
let initial = match *c1.state() {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *c2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m2) => ConsumerState::Continue(m2.clone()),
ConsumerState::Done(_,ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
ChainConsumer {
state: initial,
consumer1: c1,
consumer2: c2,
input_type: PhantomData,
temp_type: PhantomData
}
}
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> Consumer<R,T,E,M> for ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer1.handle(input);
self.state = match *res {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *self.consumer2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(_, ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
#[macro_export]
macro_rules! consumer_from_parser (
//FIXME: should specify the error and move type
($name:ident<$input:ty, $output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl $crate::Consumer<$input, $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<$input>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl<'a> $crate::Consumer<&'a[u8], $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<&'a[u8]>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$input:ty, $output:ty>, $f:expr) => (
consumer_from_parser!($name<$input, $output>, call!($f));
);
($name:ident<$output:ty>, $f:expr) => (
consumer_from_parser!($name<$output>, call!($f));
);
);
#[cfg(test)]
mod tests {
use super::*;
use internal::IResult;
use util::HexDisplay;
use std::str::from_utf8;
use std::io::SeekFrom;
#[derive(Debug)]
struct AbcdConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>
}
named!(abcd, tag!("abcd"));
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for AbcdConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8],(),Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
};
&self.state
}
Input::Eof(Some(sl)) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
// we cannot return incomplete on Eof
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
#[test]
fn mem() {
let mut m = MemProducer::new(&b"abcdabcdabcdabcdabcd"[..], 8);
let mut a = AbcdConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
named!(efgh, tag!("efgh"));
named!(ijkl, tag!("ijkl"));
#[derive(Debug)]
enum State {
Initial,
A,
B,
End,
Error
}
#[derive(Debug)]
struct StateConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>,
parsing_state: State
}
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for StateConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8], (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
Input::Eof(Some(sl)) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Error(())
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Error(())
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
impl<'a> StateConsumer<'a> {
fn parsing(&self) -> &State {
&self.parsing_state
}
}
#[test]
fn mem2() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut a = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
//assert!(false);
}
#[test]
fn map() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut a = MapConsumer::new(&mut s, from_utf8);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
#[derive(Debug)]
struct StrConsumer<'a> {
state: ConsumerState<&'a str, (), Move>
}
impl<'a> Consumer<&'a [u8], &'a str, (), Move> for StrConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a str, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
self.state = ConsumerState::Done(Move::Consume(sl.len()), from_utf8(sl).unwrap());
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a str, (), Move> {
&self.state
}
}
#[test]
fn chain() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s1 = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut s2 = StrConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
let mut a = ChainConsumer::new(&mut s1, &mut s2);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
//
//let x = [0, 1, 2, 3, 4];
//let b = [1, 2, 3];
//assert_eq!(&x[1..3], &b[..]);
}
#[test]
fn shift_test() {
let mut v = vec![0,1,2,3,4,5];
shift(&mut v, 1, 3);
assert_eq!(&v[..2], &[1,2][..]);
let mut v2 = vec![0,1,2,3,4,5];
shift(&mut v2, 2, 6);
assert_eq!(&v2[..4], &[2,3,4,5][..]);
}
/*#[derive(Debug)]
struct LineConsumer {
state: ConsumerState<String, (), Move>
}
impl<'a> Consumer<&'a [u8], String, (), Move> for LineConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<String, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
//println!("got slice: {:?}", sl);
self.state = match line(sl) {
IResult::Incomplete(n) => {
println!("line not complete, continue (line was \"{}\")", from_utf8(sl).unwrap());
ConsumerState::Continue(Move::Await(n))
},
IResult::Error(e) => {
println!("LineConsumer parsing error: {:?}", e);
ConsumerState::Error(())
},
IResult::Done(i,o) => {
let res = String::from(from_utf8(o).unwrap());
println!("found: {}", res);
//println!("sl: {:?}\ni:{:?}\noffset:{}", sl, i, sl.offset(i));
ConsumerState::Done(Move::Consume(sl.offset(i)), res)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<String, (), Move> {
&self.state
}
}*/
fn lf(i:& u8) -> bool {
*i == '\n' as u8
}
fn to_utf8_string(input:&[u8]) -> String {
String::from(from_utf8(input).unwrap())
}
//named!(line<&[u8]>, terminated!(take_till!(lf), tag!("\n")));
consumer_from_parser!(LineConsumer<String>, map!(terminated!(take_till!(lf), tag!("\n")), to_utf8_string));
fn get_line(producer: &mut FileProducer, mv: Move) -> Option<(Move,String)> {
let mut a = LineConsumer { state: ConsumerState::Continue(mv) };
while let &ConsumerState::Continue(_) = producer.apply(&mut a) {
println!("continue");
}
if let &ConsumerState::Done(ref m, ref s) = a.state() {
Some((m.clone(), s.clone()))
} else {
None
}
}
#[test]
fn file() {
let mut f = FileProducer::new("LICENSE", 200).unwrap();
f.refill();
let mut mv = Move::Consume(0);
for i in 1..10 {
if let Some((m,s)) = get_line(&mut f, mv.clone()) {
println!("got line[{}]: {}", i, s);
mv = m;
} else {
assert!(false, "LineConsumer should not have failed");
}
}
//assert!(false);
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
enum SeekState {
Begin,
SeekedToEnd,
ShouldEof,
IsEof
}
#[derive(Debug)]
struct SeekingConsumer {
state: ConsumerState<(), u8, Move>,
position: SeekState
}
impl SeekingConsumer {
fn position(&self) -> SeekState {
self.position
}
}
impl<'a> Consumer<&'a [u8], (), u8, Move> for SeekingConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<(), u8, Move> {
println!("input: {:?}", input);
match self.position {
SeekState::Begin => {
self.state = ConsumerState::Continue(Move::Seek(SeekFrom::End(-4)));
self.position = SeekState::SeekedToEnd;
},
SeekState::SeekedToEnd => match input {
Input::Element(sl) => {
if sl.len() == 4 {
self.state = ConsumerState::Continue(Move::Consume(4));
self.position = SeekState::ShouldEof;
} else {
self.state = ConsumerState::Error(0);
}
},
Input::Eof(Some(sl)) => {
if sl.len() == 4 {
self.state = ConsumerState::Done(Move::Consume(4), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(1);
}
},
_ => self.state = ConsumerState::Error(2)
},
SeekState::ShouldEof => match input {
Input::Eof(Some(sl)) => {
if sl.len() == 0 {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(3);
}
},
Input::Eof(None) => {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
},
_ => self.state = ConsumerState::Error(4)
},
_ => self.state = ConsumerState::Error(5)
};
&self.state
}
fn state(&self) -> &ConsumerState<(), u8, Move> {
&self.state
}
}
#[test]
fn seeking_consumer() {
let mut f = FileProducer::new("assets/testfile.txt", 200).unwrap();
f.refill();
let mut a = SeekingConsumer { state: ConsumerState::Continue(Move::Consume(0)), position: SeekState::Begin };
for _ in 1..4 {
println!("file apply {:?}", f.apply(&mut a));
}
println!("consumer is now: {:?}", a);
if let &ConsumerState::Done(Move::Consume(0), ()) = a.state() {
println!("end");
} else {
println!("invalid state is {:?}", a.state());
assert!(false, "consumer is not at EOF");
}
assert_eq!(a.position(), SeekState::IsEof);
}
}
|
use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub struct Stream<P: StreamProducer> {
info: StreamInfo,
metadata: Vec<Metadata>,
producer: P,
}
/// Alias for a FLAC stream produced from `Read`.
pub type StreamReader<R> = Stream<ReadStream<R>>;
/// Alias for a FLAC stream produced from a byte stream buffer.
pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
impl<P> Stream<P> where P: StreamProducer {
/// Constructor for the default state of a FLAC stream.
#[inline]
pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
}
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// slice.
#[inline]
pub fn metadata(&self) -> &[Metadata] {
&self.metadata
}
/// Constructs a decoder with the given file name.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
/// filename isn't found.
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_file(filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
///
/// This constructor assumes that an entire FLAC file is in the buffer.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
let producer = ByteStream::new(buffer);
Stream::from_stream_producer(producer)
}
fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
let mut stream_info = Default::default();
let mut metadata = Vec::new();
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data {
stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
let samples_left = self.info.total_samples;
let channels = self.info.channels as usize;
let block_size = self.info.max_block_size as usize;
let buffer_size = block_size * channels;
Iter {
stream: self,
channel: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
buffer: vec![S::Extended::from_i8(0); buffer_size]
}
}
fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
where S: Sample {
let stream_info = &self.info;
loop {
match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
Ok(frame) => {
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let mut channel = 0;
for subframe in &frame.subframes[0..channels] {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut buffer[start..end];
subframe::decode(&subframe, block_size, output);
channel += 1;
}
frame::decode(frame.header.channel_assignment, buffer);
return Some(block_size);
}
Err(ErrorKind::Continue) => continue,
Err(_) => return None,
}
}
}
}
/// An iterator over a reference of the decoded FLAC stream.
pub struct Iter<'a, P, S>
where P: 'a + StreamProducer,
S: Sample{
stream: &'a mut Stream<P>,
channel: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
buffer: Vec<S>,
}
impl<'a, P, S> Iterator for Iter<'a, P, S>
where P: StreamProducer,
S: Sample {
type Item = S::Normal;
fn next(&mut self) -> Option<Self::Item> {
if self.sample_index == self.block_size {
let buffer = &mut self.buffer;
if let Some(block_size) = self.stream.next_frame(buffer) {
self.sample_index = 0;
self.block_size = block_size;
} else {
return None;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = self.buffer[index];
self.channel += 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
self.samples_left -= 1;
}
S::to_normal(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a chance that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
// where P: StreamProducer,
// S: Sample {
// type Item = S::Normal;
// type IntoIter = Iter<'a, P, S>;
//
// #[inline]
// fn into_iter(self) -> Self::IntoIter {
// self.iter()
// }
//}
Add unchecked array for the decode iterator
use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub struct Stream<P: StreamProducer> {
info: StreamInfo,
metadata: Vec<Metadata>,
producer: P,
}
/// Alias for a FLAC stream produced from `Read`.
pub type StreamReader<R> = Stream<ReadStream<R>>;
/// Alias for a FLAC stream produced from a byte stream buffer.
pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
impl<P> Stream<P> where P: StreamProducer {
/// Constructor for the default state of a FLAC stream.
#[inline]
pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
}
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// slice.
#[inline]
pub fn metadata(&self) -> &[Metadata] {
&self.metadata
}
/// Constructs a decoder with the given file name.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
/// filename isn't found.
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_file(filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
///
/// This constructor assumes that an entire FLAC file is in the buffer.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
let producer = ByteStream::new(buffer);
Stream::from_stream_producer(producer)
}
fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
let mut stream_info = Default::default();
let mut metadata = Vec::new();
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data {
stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
let samples_left = self.info.total_samples;
let channels = self.info.channels as usize;
let block_size = self.info.max_block_size as usize;
let buffer_size = block_size * channels;
Iter {
stream: self,
channel: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
buffer: vec![S::Extended::from_i8(0); buffer_size]
}
}
fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
where S: Sample {
let stream_info = &self.info;
loop {
match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
Ok(frame) => {
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let mut channel = 0;
for subframe in &frame.subframes[0..channels] {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut buffer[start..end];
subframe::decode(&subframe, block_size, output);
channel += 1;
}
frame::decode(frame.header.channel_assignment, buffer);
return Some(block_size);
}
Err(ErrorKind::Continue) => continue,
Err(_) => return None,
}
}
}
}
/// An iterator over a reference of the decoded FLAC stream.
pub struct Iter<'a, P, S>
where P: 'a + StreamProducer,
S: Sample{
stream: &'a mut Stream<P>,
channel: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
buffer: Vec<S>,
}
impl<'a, P, S> Iterator for Iter<'a, P, S>
where P: StreamProducer,
S: Sample {
type Item = S::Normal;
fn next(&mut self) -> Option<Self::Item> {
if self.sample_index == self.block_size {
let buffer = &mut self.buffer;
if let Some(block_size) = self.stream.next_frame(buffer) {
self.sample_index = 0;
self.block_size = block_size;
} else {
return None;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = unsafe { *self.buffer.get_unchecked(index) };
self.channel += 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
self.samples_left -= 1;
}
S::to_normal(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a chance that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
// where P: StreamProducer,
// S: Sample {
// type Item = S::Normal;
// type IntoIter = Iter<'a, P, S>;
//
// #[inline]
// fn into_iter(self) -> Self::IntoIter {
// self.iter()
// }
//}
|
use ll;
use pa::{PaError, PaResult};
use device::DeviceIndex;
use util::{to_pa_result, pa_time_to_duration};
use std::raw::Slice;
use std::mem;
use std::time::duration::Duration;
use libc::c_void;
#[repr(u32)]
pub enum StreamCallbackResult
{
Continue = ll::paContinue,
Complete = ll::paComplete,
Abort = ll::paAbort,
}
pub type StreamCallback<'a, I, O> = |input: &[I], output: &mut [O], timeinfo: StreamTimeInfo, StreamCallbackFlags|:'a -> StreamCallbackResult;
pub type StreamFinishedCallback<'a> = ||:'a;
struct StreamUserData<'a, I, O>
{
num_input: uint,
num_output: uint,
callback: Option<StreamCallback<'a, I, O>>,
finished_callback: Option<StreamFinishedCallback<'a>>,
}
pub struct StreamTimeInfo
{
pub input_adc_time: Duration,
pub current_time: Duration,
pub output_dac_time: Duration,
}
bitflags!(
flags StreamCallbackFlags: u64 {
static inputUnderflow = 0x01,
static inputOverflow = 0x02,
static outputUnderflow = 0x04,
static outputOverflow = 0x08,
static primingOutput = 0x10
}
)
bitflags!(
flags StreamFlags: u64 {
static ClipOff = 0x00000001,
static DitherOff = 0x00000002,
static NeverDropInput = 0x00000004,
static PrimeOutputBuffersUsingStreamCallback = 0x00000008,
static PlatformSpecific = 0xFFFF0000
}
)
extern "C" fn stream_callback<I, O>(input: *const c_void,
output: *mut c_void,
frame_count: ::libc::c_ulong,
time_info: *const ll::PaStreamCallbackTimeInfo,
status_flags: ll::PaStreamCallbackFlags,
user_data: *mut c_void) -> ::libc::c_int
{
let mut stream_data: Box<StreamUserData<I, O>> = unsafe { mem::transmute(user_data) };
let input_buffer: &[I] = unsafe
{
mem::transmute(
Slice { data: input as *const I, len: frame_count as uint * stream_data.num_input }
)
};
let output_buffer: &mut [O] = unsafe
{
mem::transmute(
Slice { data: output as *const O, len: frame_count as uint * stream_data.num_output }
)
};
let flags = StreamCallbackFlags::from_bits_truncate(status_flags);
let timeinfo = match unsafe { time_info.to_option() }
{
Some(ref info) => StreamTimeInfo { input_adc_time: pa_time_to_duration(info.inputBufferAdcTime),
current_time: pa_time_to_duration(info.currentTime),
output_dac_time: pa_time_to_duration(info.outputBufferDacTime) },
None => StreamTimeInfo { input_adc_time: Duration::seconds(0),
current_time: Duration::seconds(0),
output_dac_time: Duration::seconds(0), },
};
let result = match stream_data.callback
{
Some(ref mut f) => (*f)(input_buffer, output_buffer, timeinfo, flags),
None => Abort,
};
unsafe { mem::forget(stream_data); }
result as i32
}
extern "C" fn stream_finished_callback<I, O>(user_data: *mut c_void)
{
let mut stream_data: Box<StreamUserData<I, O>> = unsafe { mem::transmute(user_data) };
match stream_data.finished_callback
{
Some(ref mut f) => (*f)(),
None => {},
};
unsafe { mem::forget(stream_data); }
}
trait SampleType
{
fn sample_format(_: Option<Self>) -> u64;
}
impl SampleType for f32 { fn sample_format(_: Option<f32>) -> u64 { 0x00000001 } }
impl SampleType for i32 { fn sample_format(_: Option<i32>) -> u64 { 0x00000002 } }
impl SampleType for i16 { fn sample_format(_: Option<i16>) -> u64 { 0x00000008 } }
impl SampleType for i8 { fn sample_format(_: Option<i8>) -> u64 { 0x00000010 } }
impl SampleType for u8 { fn sample_format(_: Option<u8>) -> u64 { 0x00000020 } }
fn get_sample_format<T: SampleType>() -> u64
{
SampleType::sample_format(None::<T>)
}
pub fn get_sample_size<T: SampleType>() -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetSampleSize(get_sample_format::<T>()) }
{
n if n >= 0 => Ok(n as uint),
m => to_pa_result(m).map(|_| 0),
}
}
pub struct Stream<'a, I, O>
{
pa_stream: *mut ll::PaStream,
inputs: uint,
outputs: uint,
user_data: Box<StreamUserData<'a, I, O>>,
}
impl<'a, T: SampleType + Send> Stream<'a, T, T>
{
pub fn open_default(num_input_channels: uint,
num_output_channels: uint,
sample_rate: f64,
frames_per_buffer: u64,
callback: Option<StreamCallback<'a, T, T>>)
-> Result<Stream<'a, T, T>, PaError>
{
unsafe
{
let callback_pointer = match callback
{
Some(_) => Some(stream_callback::<T, T>),
None => None,
};
let userdata = box StreamUserData
{
num_input: num_input_channels,
num_output: num_output_channels,
callback: callback,
finished_callback: None,
};
let mut pa_stream = ::std::ptr::mut_null();
let ud_pointer: *mut c_void = mem::transmute(userdata);
let ud_pointer_2 = ud_pointer.clone();
let code = ll::Pa_OpenDefaultStream(&mut pa_stream as *mut *mut ll::PaStream,
num_input_channels as i32,
num_output_channels as i32,
get_sample_format::<T>(),
sample_rate,
frames_per_buffer,
callback_pointer,
ud_pointer);
match to_pa_result(code)
{
Ok(()) => Ok(Stream { pa_stream: pa_stream,
user_data: mem::transmute(ud_pointer_2),
inputs: num_input_channels,
outputs: num_output_channels,
}),
Err(v) => Err(v),
}
}
}
}
impl<'a, I: SampleType + Send, O: SampleType + Send> Stream<'a, I, O>
{
pub fn open(input: StreamParameters<I>,
output: StreamParameters<O>,
sample_rate: f64,
frames_per_buffer: u64,
flags: StreamFlags,
callback: Option<StreamCallback<'a, I, O>>)
-> Result<Stream<'a, I, O>, PaError>
{
unsafe
{
let callback_pointer = match callback
{
Some(_) => Some(stream_callback::<I, O>),
None => None,
};
let user_data = box StreamUserData
{
num_input: input.channel_count,
num_output: output.channel_count,
callback: callback,
finished_callback: None,
};
let mut pa_stream = ::std::ptr::mut_null();
let ud_pointer: *mut c_void = mem::transmute(user_data);
let ud_pointer_2 = ud_pointer.clone();
let result = ll::Pa_OpenStream(&mut pa_stream,
&input.to_ll(),
&output.to_ll(),
sample_rate,
frames_per_buffer,
flags.bits,
callback_pointer,
ud_pointer);
match to_pa_result(result)
{
Ok(()) => Ok(Stream { pa_stream: pa_stream,
user_data: mem::transmute(ud_pointer_2),
inputs: input.channel_count,
outputs: output.channel_count,
}),
Err(v) => Err(v),
}
}
}
pub fn start(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_StartStream(self.pa_stream) })
}
pub fn stop(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_StopStream(self.pa_stream) })
}
pub fn abort(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_AbortStream(self.pa_stream) })
}
fn close(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_CloseStream(self.pa_stream) })
}
pub fn is_stopped(&self) -> Result<bool, PaError>
{
match unsafe { ll::Pa_IsStreamStopped(self.pa_stream) }
{
1 => Ok(true),
n => to_pa_result(n).map(|_| false),
}
}
pub fn is_active(&self) -> Result<bool, PaError>
{
match unsafe { ll::Pa_IsStreamActive(self.pa_stream) }
{
1 => Ok(true),
n => to_pa_result(n).map(|_| false),
}
}
pub fn read_available(&self) -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetStreamReadAvailable(self.pa_stream) }
{
n if n >= 0 => { Ok(n as uint) },
n => to_pa_result(n as i32).map(|_| 0),
}
}
pub fn write_available(&self) -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetStreamWriteAvailable(self.pa_stream) }
{
n if n >= 0 => { Ok(n as uint) },
n => to_pa_result(n as i32).map(|_| 0),
}
}
pub fn write(&self, buffer: &[O]) -> PaResult
{
if self.outputs == 0 { return Err(::pa::CanNotWriteToAnInputOnlyStream) }
let pointer = buffer.as_ptr() as *const c_void;
let frames = (buffer.len() / self.outputs) as u64;
to_pa_result(unsafe { ll::Pa_WriteStream(self.pa_stream, pointer, frames) })
}
pub fn read(&self, buffer: &mut [I]) -> PaResult
{
if self.inputs == 0 { return Err(::pa::CanNotReadFromAnOutputOnlyStream) }
let pointer = buffer.as_mut_ptr() as *mut c_void;
let frames = (buffer.len() / self.inputs) as u64;
to_pa_result(unsafe { ll::Pa_ReadStream(self.pa_stream, pointer, frames) })
}
pub fn cpu_load(&self) -> f64
{
unsafe { ll::Pa_GetStreamCpuLoad(self.pa_stream) }
}
pub fn time(&self) -> Duration
{
let time = unsafe { ll::Pa_GetStreamTime(self.pa_stream) };
pa_time_to_duration(time)
}
pub fn info(&self) -> Option<StreamInfo>
{
unsafe
{
ll::Pa_GetStreamInfo(self.pa_stream)
.to_option()
.map(|s| StreamInfo::from_ll(s))
}
}
pub fn set_finished_callback(&mut self, finished_callback: StreamFinishedCallback<'a>) -> PaResult
{
self.user_data.finished_callback = Some(finished_callback);
let callback_pointer = Some(stream_finished_callback::<I, O>);
to_pa_result(unsafe { ll::Pa_SetStreamFinishedCallback(self.pa_stream, callback_pointer) })
}
pub fn unset_finished_callback(&mut self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_SetStreamFinishedCallback(self.pa_stream, None) })
}
}
#[unsafe_destructor]
impl<'a, I: SampleType + Send, O: SampleType + Send> Drop for Stream<'a, I, O>
{
fn drop(&mut self)
{
match self.close()
{
Err(v) => error!("Error: {}", v),
Ok(_) => {},
};
}
}
pub struct StreamParameters<T>
{
pub device: DeviceIndex,
pub channel_count: uint,
pub suggested_latency: Duration,
}
impl<T: SampleType> StreamParameters<T>
{
fn to_ll(&self) -> ll::Struct_PaStreamParameters
{
ll::Struct_PaStreamParameters
{
device: self.device as i32,
channelCount: self.channel_count as i32,
sampleFormat: get_sample_format::<T>(),
suggestedLatency: self.suggested_latency.num_milliseconds() as f64 / 1000.0,
hostApiSpecificStreamInfo: ::std::ptr::mut_null(),
}
}
}
pub fn is_format_supported<I: SampleType, O: SampleType>(input: StreamParameters<I>, output: StreamParameters<O>, sample_rate: f64) -> PaResult
{
to_pa_result(unsafe { ll::Pa_IsFormatSupported(&input.to_ll(), &output.to_ll(), sample_rate) })
}
pub struct StreamInfo
{
pub input_latency: Duration,
pub output_latency: Duration,
pub sample_rate: f64,
}
impl StreamInfo
{
fn from_ll(data: &ll::PaStreamInfo) -> StreamInfo
{
StreamInfo
{
input_latency: pa_time_to_duration(data.inputLatency),
output_latency: pa_time_to_duration(data.outputLatency),
sample_rate: data.sampleRate,
}
}
}
#[cfg(test)]
mod test
{
use super::SampleType;
// This test asserts that the sizes used by PortAudio are the same as
// those used by Rust
#[test]
fn sample_sizes()
{
test_sample_size::<f32>();
test_sample_size::<i32>();
test_sample_size::<i16>();
test_sample_size::<i8>();
test_sample_size::<u8>();
}
fn test_sample_size<T: SampleType>()
{
use std::mem;
let pa_size = super::get_sample_size::<T>();
let rs_size = Ok(mem::size_of::<T>());
assert_eq!(rs_size, pa_size);
}
// In the FFI some assumptions are made as to how Some(p) and None are
// represented when used as function pointers. This test asserts these
// assumptions.
#[test]
fn option_pointer()
{
use std::{mem, ptr};
use libc::c_void;
unsafe
{
assert! (mem::transmute::<Option<extern "C" fn()>, *const c_void>(Some(external_function)) != ptr::null());
assert_eq!(mem::transmute::<Option<extern "C" fn()>, *const c_void>(None) , ptr::null());
}
}
extern "C" fn external_function() {}
}
Modified the tests slightly
use ll;
use pa::{PaError, PaResult};
use device::DeviceIndex;
use util::{to_pa_result, pa_time_to_duration};
use std::raw::Slice;
use std::mem;
use std::time::duration::Duration;
use libc::c_void;
#[repr(u32)]
pub enum StreamCallbackResult
{
Continue = ll::paContinue,
Complete = ll::paComplete,
Abort = ll::paAbort,
}
pub type StreamCallback<'a, I, O> = |input: &[I], output: &mut [O], timeinfo: StreamTimeInfo, StreamCallbackFlags|:'a -> StreamCallbackResult;
pub type StreamFinishedCallback<'a> = ||:'a;
struct StreamUserData<'a, I, O>
{
num_input: uint,
num_output: uint,
callback: Option<StreamCallback<'a, I, O>>,
finished_callback: Option<StreamFinishedCallback<'a>>,
}
pub struct StreamTimeInfo
{
pub input_adc_time: Duration,
pub current_time: Duration,
pub output_dac_time: Duration,
}
bitflags!(
flags StreamCallbackFlags: u64 {
static inputUnderflow = 0x01,
static inputOverflow = 0x02,
static outputUnderflow = 0x04,
static outputOverflow = 0x08,
static primingOutput = 0x10
}
)
bitflags!(
flags StreamFlags: u64 {
static ClipOff = 0x00000001,
static DitherOff = 0x00000002,
static NeverDropInput = 0x00000004,
static PrimeOutputBuffersUsingStreamCallback = 0x00000008,
static PlatformSpecific = 0xFFFF0000
}
)
extern "C" fn stream_callback<I, O>(input: *const c_void,
output: *mut c_void,
frame_count: ::libc::c_ulong,
time_info: *const ll::PaStreamCallbackTimeInfo,
status_flags: ll::PaStreamCallbackFlags,
user_data: *mut c_void) -> ::libc::c_int
{
let mut stream_data: Box<StreamUserData<I, O>> = unsafe { mem::transmute(user_data) };
let input_buffer: &[I] = unsafe
{
mem::transmute(
Slice { data: input as *const I, len: frame_count as uint * stream_data.num_input }
)
};
let output_buffer: &mut [O] = unsafe
{
mem::transmute(
Slice { data: output as *const O, len: frame_count as uint * stream_data.num_output }
)
};
let flags = StreamCallbackFlags::from_bits_truncate(status_flags);
let timeinfo = match unsafe { time_info.to_option() }
{
Some(ref info) => StreamTimeInfo { input_adc_time: pa_time_to_duration(info.inputBufferAdcTime),
current_time: pa_time_to_duration(info.currentTime),
output_dac_time: pa_time_to_duration(info.outputBufferDacTime) },
None => StreamTimeInfo { input_adc_time: Duration::seconds(0),
current_time: Duration::seconds(0),
output_dac_time: Duration::seconds(0), },
};
let result = match stream_data.callback
{
Some(ref mut f) => (*f)(input_buffer, output_buffer, timeinfo, flags),
None => Abort,
};
unsafe { mem::forget(stream_data); }
result as i32
}
extern "C" fn stream_finished_callback<I, O>(user_data: *mut c_void)
{
let mut stream_data: Box<StreamUserData<I, O>> = unsafe { mem::transmute(user_data) };
match stream_data.finished_callback
{
Some(ref mut f) => (*f)(),
None => {},
};
unsafe { mem::forget(stream_data); }
}
trait SampleType
{
fn sample_format(_: Option<Self>) -> u64;
}
impl SampleType for f32 { fn sample_format(_: Option<f32>) -> u64 { 0x00000001 } }
impl SampleType for i32 { fn sample_format(_: Option<i32>) -> u64 { 0x00000002 } }
impl SampleType for i16 { fn sample_format(_: Option<i16>) -> u64 { 0x00000008 } }
impl SampleType for i8 { fn sample_format(_: Option<i8>) -> u64 { 0x00000010 } }
impl SampleType for u8 { fn sample_format(_: Option<u8>) -> u64 { 0x00000020 } }
fn get_sample_format<T: SampleType>() -> u64
{
SampleType::sample_format(None::<T>)
}
pub fn get_sample_size<T: SampleType>() -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetSampleSize(get_sample_format::<T>()) }
{
n if n >= 0 => Ok(n as uint),
m => to_pa_result(m).map(|_| 0),
}
}
pub struct Stream<'a, I, O>
{
pa_stream: *mut ll::PaStream,
inputs: uint,
outputs: uint,
user_data: Box<StreamUserData<'a, I, O>>,
}
impl<'a, T: SampleType + Send> Stream<'a, T, T>
{
pub fn open_default(num_input_channels: uint,
num_output_channels: uint,
sample_rate: f64,
frames_per_buffer: u64,
callback: Option<StreamCallback<'a, T, T>>)
-> Result<Stream<'a, T, T>, PaError>
{
unsafe
{
let callback_pointer = match callback
{
Some(_) => Some(stream_callback::<T, T>),
None => None,
};
let userdata = box StreamUserData
{
num_input: num_input_channels,
num_output: num_output_channels,
callback: callback,
finished_callback: None,
};
let mut pa_stream = ::std::ptr::mut_null();
let ud_pointer: *mut c_void = mem::transmute(userdata);
let ud_pointer_2 = ud_pointer.clone();
let code = ll::Pa_OpenDefaultStream(&mut pa_stream as *mut *mut ll::PaStream,
num_input_channels as i32,
num_output_channels as i32,
get_sample_format::<T>(),
sample_rate,
frames_per_buffer,
callback_pointer,
ud_pointer);
match to_pa_result(code)
{
Ok(()) => Ok(Stream { pa_stream: pa_stream,
user_data: mem::transmute(ud_pointer_2),
inputs: num_input_channels,
outputs: num_output_channels,
}),
Err(v) => Err(v),
}
}
}
}
impl<'a, I: SampleType + Send, O: SampleType + Send> Stream<'a, I, O>
{
pub fn open(input: StreamParameters<I>,
output: StreamParameters<O>,
sample_rate: f64,
frames_per_buffer: u64,
flags: StreamFlags,
callback: Option<StreamCallback<'a, I, O>>)
-> Result<Stream<'a, I, O>, PaError>
{
unsafe
{
let callback_pointer = match callback
{
Some(_) => Some(stream_callback::<I, O>),
None => None,
};
let user_data = box StreamUserData
{
num_input: input.channel_count,
num_output: output.channel_count,
callback: callback,
finished_callback: None,
};
let mut pa_stream = ::std::ptr::mut_null();
let ud_pointer: *mut c_void = mem::transmute(user_data);
let ud_pointer_2 = ud_pointer.clone();
let result = ll::Pa_OpenStream(&mut pa_stream,
&input.to_ll(),
&output.to_ll(),
sample_rate,
frames_per_buffer,
flags.bits,
callback_pointer,
ud_pointer);
match to_pa_result(result)
{
Ok(()) => Ok(Stream { pa_stream: pa_stream,
user_data: mem::transmute(ud_pointer_2),
inputs: input.channel_count,
outputs: output.channel_count,
}),
Err(v) => Err(v),
}
}
}
pub fn start(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_StartStream(self.pa_stream) })
}
pub fn stop(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_StopStream(self.pa_stream) })
}
pub fn abort(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_AbortStream(self.pa_stream) })
}
fn close(&self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_CloseStream(self.pa_stream) })
}
pub fn is_stopped(&self) -> Result<bool, PaError>
{
match unsafe { ll::Pa_IsStreamStopped(self.pa_stream) }
{
1 => Ok(true),
n => to_pa_result(n).map(|_| false),
}
}
pub fn is_active(&self) -> Result<bool, PaError>
{
match unsafe { ll::Pa_IsStreamActive(self.pa_stream) }
{
1 => Ok(true),
n => to_pa_result(n).map(|_| false),
}
}
pub fn read_available(&self) -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetStreamReadAvailable(self.pa_stream) }
{
n if n >= 0 => { Ok(n as uint) },
n => to_pa_result(n as i32).map(|_| 0),
}
}
pub fn write_available(&self) -> Result<uint, PaError>
{
match unsafe { ll::Pa_GetStreamWriteAvailable(self.pa_stream) }
{
n if n >= 0 => { Ok(n as uint) },
n => to_pa_result(n as i32).map(|_| 0),
}
}
pub fn write(&self, buffer: &[O]) -> PaResult
{
if self.outputs == 0 { return Err(::pa::CanNotWriteToAnInputOnlyStream) }
let pointer = buffer.as_ptr() as *const c_void;
let frames = (buffer.len() / self.outputs) as u64;
to_pa_result(unsafe { ll::Pa_WriteStream(self.pa_stream, pointer, frames) })
}
pub fn read(&self, buffer: &mut [I]) -> PaResult
{
if self.inputs == 0 { return Err(::pa::CanNotReadFromAnOutputOnlyStream) }
let pointer = buffer.as_mut_ptr() as *mut c_void;
let frames = (buffer.len() / self.inputs) as u64;
to_pa_result(unsafe { ll::Pa_ReadStream(self.pa_stream, pointer, frames) })
}
pub fn cpu_load(&self) -> f64
{
unsafe { ll::Pa_GetStreamCpuLoad(self.pa_stream) }
}
pub fn time(&self) -> Duration
{
let time = unsafe { ll::Pa_GetStreamTime(self.pa_stream) };
pa_time_to_duration(time)
}
pub fn info(&self) -> Option<StreamInfo>
{
unsafe
{
ll::Pa_GetStreamInfo(self.pa_stream)
.to_option()
.map(|s| StreamInfo::from_ll(s))
}
}
pub fn set_finished_callback(&mut self, finished_callback: StreamFinishedCallback<'a>) -> PaResult
{
self.user_data.finished_callback = Some(finished_callback);
let callback_pointer = Some(stream_finished_callback::<I, O>);
to_pa_result(unsafe { ll::Pa_SetStreamFinishedCallback(self.pa_stream, callback_pointer) })
}
pub fn unset_finished_callback(&mut self) -> PaResult
{
to_pa_result(unsafe { ll::Pa_SetStreamFinishedCallback(self.pa_stream, None) })
}
}
#[unsafe_destructor]
impl<'a, I: SampleType + Send, O: SampleType + Send> Drop for Stream<'a, I, O>
{
fn drop(&mut self)
{
match self.close()
{
Err(v) => error!("Error: {}", v),
Ok(_) => {},
};
}
}
pub struct StreamParameters<T>
{
pub device: DeviceIndex,
pub channel_count: uint,
pub suggested_latency: Duration,
}
impl<T: SampleType> StreamParameters<T>
{
fn to_ll(&self) -> ll::Struct_PaStreamParameters
{
ll::Struct_PaStreamParameters
{
device: self.device as i32,
channelCount: self.channel_count as i32,
sampleFormat: get_sample_format::<T>(),
suggestedLatency: self.suggested_latency.num_milliseconds() as f64 / 1000.0,
hostApiSpecificStreamInfo: ::std::ptr::mut_null(),
}
}
}
pub fn is_format_supported<I: SampleType, O: SampleType>(input: StreamParameters<I>, output: StreamParameters<O>, sample_rate: f64) -> PaResult
{
to_pa_result(unsafe { ll::Pa_IsFormatSupported(&input.to_ll(), &output.to_ll(), sample_rate) })
}
pub struct StreamInfo
{
pub input_latency: Duration,
pub output_latency: Duration,
pub sample_rate: f64,
}
impl StreamInfo
{
fn from_ll(data: &ll::PaStreamInfo) -> StreamInfo
{
StreamInfo
{
input_latency: pa_time_to_duration(data.inputLatency),
output_latency: pa_time_to_duration(data.outputLatency),
sample_rate: data.sampleRate,
}
}
}
#[cfg(test)]
mod test
{
use super::SampleType;
// This test asserts that the sizes used by PortAudio are the same as
// those used by Rust
#[test]
fn sample_sizes()
{
test_sample_size::<f32>();
test_sample_size::<i32>();
test_sample_size::<i16>();
test_sample_size::<i8>();
test_sample_size::<u8>();
}
fn test_sample_size<T: SampleType>()
{
use std::mem;
let pa_size = super::get_sample_size::<T>().unwrap();
let rs_size = mem::size_of::<T>();
assert_eq!(rs_size, pa_size);
}
// In the FFI some assumptions are made as to how Some(p) and None are
// represented when used as function pointers. This test asserts these
// assumptions.
#[test]
fn option_pointer()
{
use std::{mem, ptr};
use libc::c_void;
unsafe
{
assert_eq!(mem::transmute::<Option<extern "C" fn()>, *const c_void>(Some(external_function)), external_function as *const c_void);
assert_eq!(mem::transmute::<Option<extern "C" fn()>, *const c_void>(None) , ptr::null());
}
}
extern "C" fn external_function() {}
}
|
//! Licensed under the Apache License, Version 2.0
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
//! http://opensource.org/licenses/MIT, at your
//! option. This file may not be copied, modified, or distributed
//! except according to those terms.
use std::kinds;
use std::mem;
use std::ptr;
use std::fmt;
use std::num::Saturating;
/// Similar to the slice iterator, but with a certain number of steps
/// (stride) skipped per iteration.
///
/// Does not support zero-sized `T`.
pub struct Stride<'a, T> {
begin: *const T,
// Unlike the slice iterator, end is inclusive and the last
// pointer we will visit. This makes it possible to have
// safe stride iterators for columns in matrices etc.
end: *const T,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
}
impl<'a, T> Stride<'a, T>
{
/// Create Stride iterator from a slice and the element step count
///
/// ## Example
///
/// ```
/// let xs = [0i, 1, 2, 3, 4, 5];
/// let mut iter = Stride::from_slice(xs.as_slice(), 2);
/// ```
pub fn from_slice(xs: &'a [T], step: uint) -> Stride<'a, T>
{
assert!(step != 0);
let mut begin = ptr::null();
let mut end = ptr::null();
let nelem = xs.len().saturating_add(step - 1) / step;
unsafe {
if nelem != 0 {
begin = xs.as_ptr();
end = begin.offset(((nelem - 1) * step) as int);
}
Stride::from_ptrs(begin, end, step as int)
}
}
/// Create Stride iterator from raw pointers from the *inclusive*
/// pointer range [begin, end].
///
/// **Note:** `end` **must** be a whole number of `stride` steps away
/// from `begin`
pub unsafe fn from_ptrs(begin: *const T, end: *const T, stride: int) -> Stride<'a, T>
{
Stride {
begin: begin,
end: end,
stride: stride,
life: kinds::marker::ContravariantLifetime,
}
}
}
impl<'a, T> Iterator<&'a T> for Stride<'a, T>
{
#[inline]
fn next(&mut self) -> Option<&'a T>
{
if self.begin.is_null() {
None
} else {
unsafe {
let elt: &'a T = mem::transmute(self.begin);
if self.begin == self.end {
self.begin = ptr::null();
} else {
self.begin = self.begin.offset(self.stride);
}
Some(elt)
}
}
}
fn size_hint(&self) -> (uint, Option<uint>)
{
let len;
if self.begin.is_null() {
len = 0;
} else {
len = (self.end as uint - self.begin as uint) as int / self.stride
/ mem::size_of::<T>() as int + 1;
}
(len as uint, Some(len as uint))
}
}
impl<'a, T> DoubleEndedIterator<&'a T> for Stride<'a, T>
{
#[inline]
fn next_back(&mut self) -> Option<&'a T>
{
if self.begin.is_null() {
None
} else {
unsafe {
let elt: &'a T = mem::transmute(self.end);
if self.begin == self.end {
self.begin = ptr::null();
} else {
self.end = self.end.offset(-self.stride);
}
Some(elt)
}
}
}
}
impl<'a, T> ExactSize<&'a T> for Stride<'a, T> { }
impl<'a, T> Index<uint, T> for Stride<'a, T>
{
fn index<'b>(&'b self, i: &uint) -> &'b T
{
assert!(*i < self.size_hint().val0());
unsafe {
let ptr = self.begin.offset(self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
impl<'a, T: fmt::Show> fmt::Show for Stride<'a, T>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
let mut it = *self;
let mut res = write!(f, "[");
for elt in it {
res = res.and(write!(f, "{}, ", *elt));
}
res.and(write!(f, "]"))
}
}
impl<'a, T> Clone for Stride<'a, T>
{
fn clone(&self) -> Stride<'a, T>
{
*self
}
}
stride: Fix Show impl for Stride
//! Licensed under the Apache License, Version 2.0
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
//! http://opensource.org/licenses/MIT, at your
//! option. This file may not be copied, modified, or distributed
//! except according to those terms.
use std::kinds;
use std::mem;
use std::ptr;
use std::fmt;
use std::num::Saturating;
/// Similar to the slice iterator, but with a certain number of steps
/// (stride) skipped per iteration.
///
/// Does not support zero-sized `T`.
pub struct Stride<'a, T> {
begin: *const T,
// Unlike the slice iterator, end is inclusive and the last
// pointer we will visit. This makes it possible to have
// safe stride iterators for columns in matrices etc.
end: *const T,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
}
impl<'a, T> Stride<'a, T>
{
/// Create Stride iterator from a slice and the element step count
///
/// ## Example
///
/// ```
/// let xs = [0i, 1, 2, 3, 4, 5];
/// let mut iter = Stride::from_slice(xs.as_slice(), 2);
/// ```
pub fn from_slice(xs: &'a [T], step: uint) -> Stride<'a, T>
{
assert!(step != 0);
let mut begin = ptr::null();
let mut end = ptr::null();
let nelem = xs.len().saturating_add(step - 1) / step;
unsafe {
if nelem != 0 {
begin = xs.as_ptr();
end = begin.offset(((nelem - 1) * step) as int);
}
Stride::from_ptrs(begin, end, step as int)
}
}
/// Create Stride iterator from raw pointers from the *inclusive*
/// pointer range [begin, end].
///
/// **Note:** `end` **must** be a whole number of `stride` steps away
/// from `begin`
pub unsafe fn from_ptrs(begin: *const T, end: *const T, stride: int) -> Stride<'a, T>
{
Stride {
begin: begin,
end: end,
stride: stride,
life: kinds::marker::ContravariantLifetime,
}
}
}
impl<'a, T> Iterator<&'a T> for Stride<'a, T>
{
#[inline]
fn next(&mut self) -> Option<&'a T>
{
if self.begin.is_null() {
None
} else {
unsafe {
let elt: &'a T = mem::transmute(self.begin);
if self.begin == self.end {
self.begin = ptr::null();
} else {
self.begin = self.begin.offset(self.stride);
}
Some(elt)
}
}
}
fn size_hint(&self) -> (uint, Option<uint>)
{
let len;
if self.begin.is_null() {
len = 0;
} else {
len = (self.end as uint - self.begin as uint) as int / self.stride
/ mem::size_of::<T>() as int + 1;
}
(len as uint, Some(len as uint))
}
}
impl<'a, T> DoubleEndedIterator<&'a T> for Stride<'a, T>
{
#[inline]
fn next_back(&mut self) -> Option<&'a T>
{
if self.begin.is_null() {
None
} else {
unsafe {
let elt: &'a T = mem::transmute(self.end);
if self.begin == self.end {
self.begin = ptr::null();
} else {
self.end = self.end.offset(-self.stride);
}
Some(elt)
}
}
}
}
impl<'a, T> ExactSize<&'a T> for Stride<'a, T> { }
impl<'a, T> Index<uint, T> for Stride<'a, T>
{
fn index<'b>(&'b self, i: &uint) -> &'b T
{
assert!(*i < self.size_hint().val0());
unsafe {
let ptr = self.begin.offset(self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
impl<'a, T: fmt::Show> fmt::Show for Stride<'a, T>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
let it = *self;
try!(write!(f, "["));
for (i, elt) in it.enumerate() {
if i != 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", *elt));
}
write!(f, "]")
}
}
impl<'a, T> Clone for Stride<'a, T>
{
fn clone(&self) -> Stride<'a, T>
{
*self
}
}
|
//! Licensed under the Apache License, Version 2.0
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
//! http://opensource.org/licenses/MIT, at your
//! option. This file may not be copied, modified, or distributed
//! except according to those terms.
use std::fmt;
use std::kinds;
use std::mem;
use std::num;
/// Stride is similar to the slice iterator, but with a certain number of steps
/// (the stride) skipped per iteration.
///
/// Stride does not support zero-sized types for `A`.
///
/// Iterator element type is `&'a A`.
#[deriving(Copy)]
pub struct Stride<'a, A> {
/// base pointer -- does not change during iteration
begin: *const A,
/// current offset from begin
offset: int,
/// offset where we end (exclusive end).
end: int,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
}
/// StrideMut is like Stride, but with mutable elements.
///
/// Iterator element type is `&'a mut A`.
pub struct StrideMut<'a, A> {
begin: *mut A,
offset: int,
end: int,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
nocopy: kinds::marker::NoCopy
}
impl<'a, A> Stride<'a, A>
{
/// Create a Stride iterator from a raw pointer.
pub unsafe fn from_ptr_len(begin: *const A, nelem: uint, stride: int) -> Stride<'a, A>
{
Stride {
begin: begin,
offset: 0,
end: stride * nelem as int,
stride: stride,
life: kinds::marker::ContravariantLifetime,
}
}
}
impl<'a, A> StrideMut<'a, A>
{
/// Create a StrideMut iterator from a raw pointer.
pub unsafe fn from_ptr_len(begin: *mut A, nelem: uint, stride: int) -> StrideMut<'a, A>
{
StrideMut {
begin: begin,
offset: 0,
end: stride * nelem as int,
stride: stride,
life: kinds::marker::ContravariantLifetime,
nocopy: kinds::marker::NoCopy,
}
}
}
macro_rules! stride_impl {
(struct $name:ident -> $slice:ty, $getptr:ident, $ptr:ty, $elem:ty) => {
impl<'a, A> $name<'a, A>
{
/// Create Stride iterator from a slice and the element step count.
///
/// If `step` is negative, start from the back.
///
/// ## Example
///
/// ```
/// use itertools::Stride;
///
/// let xs = [0i, 1, 2, 3, 4, 5];
///
/// let front = Stride::from_slice(xs.as_slice(), 2);
/// assert_eq!(front[0], 0);
/// assert_eq!(front[1], 2);
///
/// let back = Stride::from_slice(xs.as_slice(), -2);
/// assert_eq!(back[0], 5);
/// assert_eq!(back[1], 3);
/// ```
///
/// **Panics** if values of type `A` are zero-sized. <br>
/// **Panics** if `step` is 0.
#[inline]
pub fn from_slice(xs: $slice, step: int) -> $name<'a, A>
{
assert!(mem::size_of::<A>() != 0);
let ustep = if step < 0 { -step } else { step } as uint;
let nelem = if ustep <= 1 {
xs.len()
} else {
let (d, r) = num::div_rem(xs.len(), ustep);
d + if r > 0 { 1 } else { 0 }
};
let mut begin = xs. $getptr ();
unsafe {
if step > 0 {
$name::from_ptr_len(begin, nelem, step)
} else {
if nelem != 0 {
begin = begin.offset(xs.len() as int - 1)
}
$name::from_ptr_len(begin, nelem, step)
}
}
}
/// Create Stride iterator from an existing Stride iterator
///
/// **Panics** if `step` is 0.
#[inline]
pub fn from_stride(mut it: $name<'a, A>, mut step: int) -> $name<'a, A>
{
assert!(step != 0);
if step < 0 {
it.swap_ends();
step = -step;
}
let len = (it.end - it.offset) / it.stride;
let newstride = it.stride * step;
let (d, r) = num::div_rem(len as uint, step as uint);
let len = d as uint + if r > 0 { 1 } else { 0 };
unsafe {
$name::from_ptr_len(it.begin, len, newstride)
}
}
/// Swap the begin and end and reverse the stride,
/// in effect reversing the iterator.
#[inline]
pub fn swap_ends(&mut self) {
let len = (self.end - self.offset) / self.stride;
if len > 0 {
unsafe {
let endptr = self.begin.offset((len - 1) * self.stride);
*self = $name::from_ptr_len(endptr, len as uint, -self.stride);
}
}
}
/// Return the number of elements in the iterator.
#[inline]
pub fn len(&self) -> uint {
((self.end - self.offset) / self.stride) as uint
}
}
impl<'a, A> Iterator<$elem> for $name<'a, A>
{
#[inline]
fn next(&mut self) -> Option<$elem>
{
if self.offset == self.end {
None
} else {
unsafe {
let elt: $elem =
mem::transmute(self.begin.offset(self.offset));
self.offset += self.stride;
Some(elt)
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, A> DoubleEndedIterator<$elem> for $name<'a, A>
{
#[inline]
fn next_back(&mut self) -> Option<$elem>
{
if self.offset == self.end {
None
} else {
unsafe {
self.end -= self.stride;
let elt = mem::transmute(self.begin.offset(self.end));
Some(elt)
}
}
}
}
impl<'a, A> ExactSizeIterator<$elem> for $name<'a, A> { }
impl<'a, A> Index<uint, A> for $name<'a, A>
{
/// Return a reference to the element at a given index.
///
/// **Panics** if the index is out of bounds.
fn index<'b>(&'b self, i: &uint) -> &'b A
{
assert!(*i < self.len());
unsafe {
let ptr = self.begin.offset(self.offset + self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
impl<'a, A: fmt::Show> fmt::Show for $name<'a, A>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
try!(write!(f, "["));
for i in range(0, self.len()) {
if i != 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", (*self)[i]));
}
write!(f, "]")
}
}
}
}
stride_impl!{struct Stride -> &'a [A], as_ptr, *const A, &'a A}
stride_impl!{struct StrideMut -> &'a mut [A], as_mut_ptr, *mut A, &'a mut A}
impl<'a, A> Clone for Stride<'a, A>
{
fn clone(&self) -> Stride<'a, A>
{
*self
}
}
impl<'a, A> IndexMut<uint, A> for StrideMut<'a, A>
{
/// Return a mutable reference to the element at a given index.
///
/// **Panics** if the index is out of bounds.
fn index_mut<'b>(&'b mut self, i: &uint) -> &'b mut A
{
assert!(*i < self.len());
unsafe {
let ptr = self.begin.offset(self.offset + self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
Fix Copy for Stride
//! Licensed under the Apache License, Version 2.0
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
//! http://opensource.org/licenses/MIT, at your
//! option. This file may not be copied, modified, or distributed
//! except according to those terms.
use std::fmt;
use std::kinds;
use std::mem;
use std::num;
/// Stride is similar to the slice iterator, but with a certain number of steps
/// (the stride) skipped per iteration.
///
/// Stride does not support zero-sized types for `A`.
///
/// Iterator element type is `&'a A`.
pub struct Stride<'a, A> {
/// base pointer -- does not change during iteration
begin: *const A,
/// current offset from begin
offset: int,
/// offset where we end (exclusive end).
end: int,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
}
impl<'a, A> Copy for Stride<'a, A> {}
/// StrideMut is like Stride, but with mutable elements.
///
/// Iterator element type is `&'a mut A`.
pub struct StrideMut<'a, A> {
begin: *mut A,
offset: int,
end: int,
stride: int,
life: kinds::marker::ContravariantLifetime<'a>,
nocopy: kinds::marker::NoCopy
}
impl<'a, A> Stride<'a, A>
{
/// Create a Stride iterator from a raw pointer.
pub unsafe fn from_ptr_len(begin: *const A, nelem: uint, stride: int) -> Stride<'a, A>
{
Stride {
begin: begin,
offset: 0,
end: stride * nelem as int,
stride: stride,
life: kinds::marker::ContravariantLifetime,
}
}
}
impl<'a, A> StrideMut<'a, A>
{
/// Create a StrideMut iterator from a raw pointer.
pub unsafe fn from_ptr_len(begin: *mut A, nelem: uint, stride: int) -> StrideMut<'a, A>
{
StrideMut {
begin: begin,
offset: 0,
end: stride * nelem as int,
stride: stride,
life: kinds::marker::ContravariantLifetime,
nocopy: kinds::marker::NoCopy,
}
}
}
macro_rules! stride_impl {
(struct $name:ident -> $slice:ty, $getptr:ident, $ptr:ty, $elem:ty) => {
impl<'a, A> $name<'a, A>
{
/// Create Stride iterator from a slice and the element step count.
///
/// If `step` is negative, start from the back.
///
/// ## Example
///
/// ```
/// use itertools::Stride;
///
/// let xs = [0i, 1, 2, 3, 4, 5];
///
/// let front = Stride::from_slice(xs.as_slice(), 2);
/// assert_eq!(front[0], 0);
/// assert_eq!(front[1], 2);
///
/// let back = Stride::from_slice(xs.as_slice(), -2);
/// assert_eq!(back[0], 5);
/// assert_eq!(back[1], 3);
/// ```
///
/// **Panics** if values of type `A` are zero-sized. <br>
/// **Panics** if `step` is 0.
#[inline]
pub fn from_slice(xs: $slice, step: int) -> $name<'a, A>
{
assert!(mem::size_of::<A>() != 0);
let ustep = if step < 0 { -step } else { step } as uint;
let nelem = if ustep <= 1 {
xs.len()
} else {
let (d, r) = num::div_rem(xs.len(), ustep);
d + if r > 0 { 1 } else { 0 }
};
let mut begin = xs. $getptr ();
unsafe {
if step > 0 {
$name::from_ptr_len(begin, nelem, step)
} else {
if nelem != 0 {
begin = begin.offset(xs.len() as int - 1)
}
$name::from_ptr_len(begin, nelem, step)
}
}
}
/// Create Stride iterator from an existing Stride iterator
///
/// **Panics** if `step` is 0.
#[inline]
pub fn from_stride(mut it: $name<'a, A>, mut step: int) -> $name<'a, A>
{
assert!(step != 0);
if step < 0 {
it.swap_ends();
step = -step;
}
let len = (it.end - it.offset) / it.stride;
let newstride = it.stride * step;
let (d, r) = num::div_rem(len as uint, step as uint);
let len = d as uint + if r > 0 { 1 } else { 0 };
unsafe {
$name::from_ptr_len(it.begin, len, newstride)
}
}
/// Swap the begin and end and reverse the stride,
/// in effect reversing the iterator.
#[inline]
pub fn swap_ends(&mut self) {
let len = (self.end - self.offset) / self.stride;
if len > 0 {
unsafe {
let endptr = self.begin.offset((len - 1) * self.stride);
*self = $name::from_ptr_len(endptr, len as uint, -self.stride);
}
}
}
/// Return the number of elements in the iterator.
#[inline]
pub fn len(&self) -> uint {
((self.end - self.offset) / self.stride) as uint
}
}
impl<'a, A> Iterator<$elem> for $name<'a, A>
{
#[inline]
fn next(&mut self) -> Option<$elem>
{
if self.offset == self.end {
None
} else {
unsafe {
let elt: $elem =
mem::transmute(self.begin.offset(self.offset));
self.offset += self.stride;
Some(elt)
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, A> DoubleEndedIterator<$elem> for $name<'a, A>
{
#[inline]
fn next_back(&mut self) -> Option<$elem>
{
if self.offset == self.end {
None
} else {
unsafe {
self.end -= self.stride;
let elt = mem::transmute(self.begin.offset(self.end));
Some(elt)
}
}
}
}
impl<'a, A> ExactSizeIterator<$elem> for $name<'a, A> { }
impl<'a, A> Index<uint, A> for $name<'a, A>
{
/// Return a reference to the element at a given index.
///
/// **Panics** if the index is out of bounds.
fn index<'b>(&'b self, i: &uint) -> &'b A
{
assert!(*i < self.len());
unsafe {
let ptr = self.begin.offset(self.offset + self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
impl<'a, A: fmt::Show> fmt::Show for $name<'a, A>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
try!(write!(f, "["));
for i in range(0, self.len()) {
if i != 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", (*self)[i]));
}
write!(f, "]")
}
}
}
}
stride_impl!{struct Stride -> &'a [A], as_ptr, *const A, &'a A}
stride_impl!{struct StrideMut -> &'a mut [A], as_mut_ptr, *mut A, &'a mut A}
impl<'a, A> Clone for Stride<'a, A>
{
fn clone(&self) -> Stride<'a, A>
{
*self
}
}
impl<'a, A> IndexMut<uint, A> for StrideMut<'a, A>
{
/// Return a mutable reference to the element at a given index.
///
/// **Panics** if the index is out of bounds.
fn index_mut<'b>(&'b mut self, i: &uint) -> &'b mut A
{
assert!(*i < self.len());
unsafe {
let ptr = self.begin.offset(self.offset + self.stride * (*i as int));
mem::transmute(ptr)
}
}
}
|
use radians::{self, Radians};
use turtle_window::TurtleWindow;
use event::MouseButton;
use {Speed, Color, Event};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AngleUnit {
Degrees,
Radians,
}
impl AngleUnit {
fn to_radians(&self, angle: Angle) -> Radians {
match *self {
AngleUnit::Degrees => Radians::from_degrees_value(angle),
AngleUnit::Radians => Radians::from_radians_value(angle),
}
}
fn to_angle(&self, angle: Radians) -> Angle {
match *self {
AngleUnit::Degrees => angle.to_degrees(),
AngleUnit::Radians => angle.to_radians(),
}
}
}
/// A point in 2D space: [x, y]
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::Point;
/// # fn main() {
/// let p: Point = [100., 120.];
/// // get x coordinate
/// let x = p[0];
/// assert_eq!(x, 100.);
/// // get y coordinate
/// let y = p[1];
/// assert_eq!(y, 120.);
/// # }
pub type Point = [f64; 2];
/// Any distance value
pub type Distance = f64;
/// An angle value without a unit
///
/// The unit of the angle represented by this value depends on what
/// unit the Turtle was set to when this angle was retrieved
pub type Angle = f64;
/// A turtle with a pen attached to its tail.
///
/// **The idea:** You control a turtle with a pen tied to its tail. As it moves
/// across the screen, it draws the path that it follows. You can use this to draw
/// any picture you want just by moving the turtle across the screen.
///
/// 
///
/// See the documentation for the methods below to learn about the different drawing commands you
/// can use with the turtle.
pub struct Turtle {
window: TurtleWindow,
angle_unit: AngleUnit,
}
impl Turtle {
/// Create a new turtle.
///
/// This will immediately open a new window with the turtle at the center. As each line in
/// your program runs, the turtle shown in the window will update.
///
/// ```rust
/// # #![allow(unused_variables, unused_mut)]
/// extern crate turtle;
/// use turtle::Turtle;
///
/// fn main() {
/// let mut turtle = Turtle::new();
/// // Do things with the turtle...
/// }
/// ```
pub fn new() -> Turtle {
Turtle {
window: TurtleWindow::new(),
angle_unit: AngleUnit::Degrees,
}
}
/// Returns the current speed of the turtle
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.set_speed(8);
/// assert_eq!(turtle.speed(), Speed::Eight);
/// # }
/// ```
pub fn speed(&self) -> Speed {
self.window.turtle().speed
}
/// Set the turtle's movement speed to the given setting. This speed affects the animation of
/// the turtle's movement and rotation. The turtle's speed is limited to values between 0 and
/// 10. If you pass in values that are not integers or outside of that range, the closest
/// possible value will be chosen.
///
/// This method's types make it so that it can be called in a number of different ways:
///
/// ```rust,no_run
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.set_speed("normal");
/// turtle.set_speed("fast");
/// turtle.set_speed(2);
/// turtle.set_speed(10);
/// // Directly using a Speed variant works, but the methods above are usually more convenient.
/// turtle.set_speed(Speed::Six);
/// # }
/// ```
///
/// If input is a number greater than 10 or smaller than 1,
/// speed is set to 0 (`Speed::Instant`). Strings are converted as follows:
///
/// | String | Value |
/// | ----------- | -------------- |
/// | `"slowest"` | `Speed::One` |
/// | `"slow"` | `Speed::Three` |
/// | `"normal"` | `Speed::Six` |
/// | `"fast"` | `Speed::Eight` |
/// | `"fastest"` | `Speed::Ten` |
/// | `"instant"` | `Speed::Instant` |
///
/// Anything else will cause the program to `panic!` at runtime.
///
/// ## Moving Instantly
///
/// A speed of zero (`Speed::Instant`) results in no animation. The turtle moves instantly
/// and turns instantly. This is very useful for moving the turtle from its "home" position
/// before you start drawing. By setting the speed to instant, you don't have to wait for
/// the turtle to move into position.
///
/// ## Learning About Conversion Traits
///
/// Using this method is an excellent way to learn about conversion
/// traits `From` and `Into`. This method takes a *generic type* as its speed parameter. That type
/// is specified to implement the `Into` trait for the type `Speed`. That means that *any* type
/// that can be converted into a `Speed` can be passed to this method.
///
/// We have implemented that trait for several types like strings and 32-bit integers so that
/// those values can be passed into this method.
/// Rather than calling this function and passing `Speed::Six` directly, you can use just `6`.
/// Rust will then allow us to call `.into()` as provided by the `Into<Speed>` trait to get the
/// corresponding `Speed` value.
///
/// You can pass in strings, 32-bit integers, and even `Speed` enum variants because they all
/// implement the `Into<Speed>` trait.
pub fn set_speed<S: Into<Speed>>(&mut self, speed: S) {
self.window.turtle_mut().speed = speed.into();
}
/// Returns the turtle's current location (x, y)
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.forward(100.0);
/// let pos = turtle.position();
/// # // Cheating a bit here for rounding...
/// # let pos = [pos[0].round(), pos[1].round()];
/// assert_eq!(pos, [0.0, 100.0]);
/// # }
/// ```
pub fn position(&self) -> Point {
self.window.turtle().position
}
/// Returns the turtle's current heading.
///
/// Units are by default degrees, but can be set using the
/// [`Turtle::use_degrees`](struct.Turtle.html#method.use_degrees) or
/// [`Turtle::use_radians`](struct.Turtle.html#method.use_radians) methods.
///
/// The heading is relative to the positive x axis (east). When first created, the turtle
/// starts facing north. That means that its heading is 90.0 degrees. The following chart
/// contains many common directions and their angles.
///
/// | Cardinal Direction | Heading (degrees) | Heading (radians) |
/// | ------------------ | ----------------- | ----------------- |
/// | East | 0.0° | `0.0` |
/// | North | 90.0° | `PI/2` |
/// | West | 180.0° | `PI` |
/// | South | 270.0° | `3*PI/2` |
///
/// You can test the result of `heading()` with these values to see if the turtle is facing
/// a certain direction.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// // Turtles start facing north
/// let mut turtle = Turtle::new();
/// // The rounding is to account for floating-point error
/// assert_eq!(turtle.heading().round(), 90.0);
/// turtle.right(31.0);
/// assert_eq!(turtle.heading().round(), 59.0);
/// turtle.left(193.0);
/// assert_eq!(turtle.heading().round(), 252.0);
/// turtle.left(130.0);
/// // Angles should not exceed 360.0
/// assert_eq!(turtle.heading().round(), 22.0);
/// # }
/// ```
pub fn heading(&self) -> Angle {
let heading = self.window.turtle().heading;
self.angle_unit.to_angle(heading)
}
/// Returns true if `Angle` values will be interpreted as degrees.
///
/// See [Turtle::use_degrees()](struct.Turtle.html#method.use_degrees) for more information.
pub fn is_using_degrees(&self) -> bool {
self.angle_unit == AngleUnit::Degrees
}
/// Returns true if `Angle` values will be interpreted as radians.
///
/// See [Turtle::use_radians()](struct.Turtle.html#method.use_degrees) for more information.
pub fn is_using_radians(&self) -> bool {
self.angle_unit == AngleUnit::Radians
}
/// Change the angle unit to degrees.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.use_radians();
/// assert!(!turtle.is_using_degrees());
/// turtle.use_degrees();
/// assert!(turtle.is_using_degrees());
/// # }
/// ```
pub fn use_degrees(&mut self) {
self.angle_unit = AngleUnit::Degrees;
}
/// Change the angle unit to radians.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(!turtle.is_using_radians());
/// turtle.use_radians();
/// assert!(turtle.is_using_radians());
/// # }
/// ```
pub fn use_radians(&mut self) {
self.angle_unit = AngleUnit::Radians;
}
/// Return true if pen is down, false if it’s up.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_pen_down());
/// turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// turtle.pen_down();
/// assert!(turtle.is_pen_down());
/// # }
/// ```
pub fn is_pen_down(&self) -> bool {
self.window.drawing().pen.enabled
}
/// Pull the pen down so that the turtle draws while moving.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// // This will move the turtle, but not draw any lines
/// turtle.forward(100.0);
/// turtle.pen_down();
/// assert!(turtle.is_pen_down());
/// // The turtle will now draw lines again
/// turtle.forward(100.0);
/// # }
/// ```
pub fn pen_down(&mut self) {
self.window.drawing_mut().pen.enabled = true;
}
/// Pick the pen up so that the turtle does not draw while moving
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_pen_down());
/// // The turtle will move and draw a line
/// turtle.forward(100.0);
/// turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// // Now, the turtle will move, but not draw anything
/// turtle.forward(100.0);
/// # }
/// ```
pub fn pen_up(&mut self) {
self.window.drawing_mut().pen.enabled = false;
}
/// Returns the size (thickness) of the pen. The thickness is measured in pixels.
///
/// See [`Turtle::set_pen_size()`](struct.Turtle.html#method.set_pen_size) for more details.
pub fn pen_size(&self) -> f64 {
self.window.drawing().pen.thickness
}
/// Sets the thickness of the pen to the given size. The thickness is measured in pixels.
///
/// The turtle's pen has a flat tip. The value you set the pen's size to will change the
/// width of the stroke created by the turtle as it moves. See the example below for more
/// about what this means.
///
/// # Example
///
/// ```rust,no_run
/// extern crate turtle;
/// use turtle::Turtle;
///
/// fn main() {
/// let mut turtle = Turtle::new();
///
/// turtle.pen_up();
/// turtle.right(90.0);
/// turtle.backward(300.0);
/// turtle.pen_down();
///
/// turtle.set_pen_color("#2196F3"); // blue
/// turtle.set_pen_size(1.0);
/// turtle.forward(200.0);
///
/// turtle.set_pen_color("#f44336"); // red
/// turtle.set_pen_size(50.0);
/// turtle.forward(200.0);
///
/// turtle.set_pen_color("#4CAF50"); // green
/// turtle.set_pen_size(100.0);
/// turtle.forward(200.0);
/// }
/// ```
///
/// This will produce the following:
///
/// 
///
/// Notice that while the turtle travels in a straight line, it produces different thicknesses
/// of lines which appear like large rectangles.
pub fn set_pen_size(&mut self, thickness: f64) {
self.window.drawing_mut().pen.thickness = thickness;
}
/// Returns the color of the pen
pub fn pen_color(&self) -> Color {
self.window.drawing().pen.color
}
/// Sets the color of the pen to the given color
//TODO: Document this more like set_speed
pub fn set_pen_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().pen.color = color.into();
}
/// Returns the color of the background
pub fn background_color(&self) -> Color {
self.window.drawing().background
}
/// Sets the color of the background to the given color
//TODO: Document this more like set_speed
pub fn set_background_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().background = color.into();
}
/// Returns the current fill color
///
/// This will be used to fill the shape when `begin_fill()` and `end_fill()` are called.
//TODO: Hyperlink begin_fill() and end_fill() methods to their docs
pub fn fill_color(&self) -> Color {
self.window.drawing().fill_color
}
/// Sets the fill color to the given color
///
/// **Note:** Only the fill color set **before** `begin_fill()` is called will be used to fill
/// the shape.
//TODO: Document this more like set_speed
pub fn set_fill_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().fill_color = color.into();
}
/// Begin filling the shape drawn by the turtle's movements
pub fn begin_fill(&mut self) {
self.window.begin_fill();
}
/// Stop filling the shape drawn by the turtle's movements
pub fn end_fill(&mut self) {
self.window.end_fill();
}
/// Returns true if the turtle is visible.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// let mut turtle = Turtle::new();
/// assert!(turtle.is_visible());
/// turtle.hide();
/// assert!(!turtle.is_visible());
/// turtle.show();
/// assert!(turtle.is_visible());
/// # }
/// ```
pub fn is_visible(&self) -> bool {
self.window.turtle().visible
}
/// Makes the turtle invisible. The shell will not be shown, but drawings will continue.
///
/// Useful for some complex drawings.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_visible());
/// turtle.hide();
/// assert!(!turtle.is_visible());
/// # }
/// ```
pub fn hide(&mut self) {
self.window.turtle_mut().visible = false;
}
/// Makes the turtle visible.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.hide();
/// assert!(!turtle.is_visible());
/// turtle.show();
/// assert!(turtle.is_visible());
/// # }
/// ```
pub fn show(&mut self) {
self.window.turtle_mut().visible = true;
}
/// Delete the turtle's drawings from the screen.
///
/// Do not move turtle. Position and heading of the turtle are not affected.
pub fn clear(&mut self) {
self.window.clear();
}
/// Move the turtle forward by the given amount of `distance`. If the pen is down, the turtle
/// will draw a line as it moves.
///
/// `distance` is given in "pixels" which are like really small turtle steps.
/// `distance` can be negative in which case the turtle can move backward
/// using this method.
pub fn forward(&mut self, distance: Distance) {
self.window.forward(distance);
}
/// Move the turtle backward by the given amount of `distance`. If the pen is down, the turtle
/// will draw a line as it moves.
///
/// `distance` is given in "pixels" which are like really small turtle steps.
/// `distance` can be negative in which case the turtle can move forwards
/// using this method.
pub fn backward(&mut self, distance: Distance) {
// Moving backwards is essentially moving forwards with a negative distance
self.window.forward(-distance);
}
/// Rotate the turtle right (clockwise) by the given angle. Since the turtle rotates in place,
/// its position will not change and it will not draw anything at all.
///
/// Units are by default degrees, but can be set using the methods
/// [`Turtle::use_degrees`](struct.Turtle.html#method.use_degrees) or
/// [`Turtle::use_radians`](struct.Turtle.html#method.use_radians).
pub fn right(&mut self, angle: Angle) {
let angle = self.angle_unit.to_radians(angle);
self.window.rotate(angle, true);
}
/// Rotate the turtle left (counterclockwise) by the given angle. Since the turtle rotates
/// in place, its position will not change and it will not draw anything at all.
///
/// Units are by default degrees, but can be set using the methods
/// [`Turtle::use_degrees`](struct.Turtle.html#method.use_degrees) or
/// [`Turtle::use_radians`](struct.Turtle.html#method.use_radians).
pub fn left(&mut self, angle: Angle) {
let angle = self.angle_unit.to_radians(angle);
self.window.rotate(angle, false);
}
/// Rotates the turtle to face the given coordinates.
/// Coordinates are relative to the center of the window.
///
/// If the coordinates are the same as the turtle's current position, no rotation takes place.
/// Always rotates the least amount necessary in order to face the given point.
///
/// ## UNSTABLE
/// This feature is currently unstable and completely buggy. Do not use it until it is fixed.
pub fn turn_towards(&mut self, target: Point) {
let target_x = target[0];
let target_y = target[1];
let position = self.position();
let x = position[0];
let y = position[1];
if (target_x - x).abs() < 0.1 && (target_y - y).abs() < 0.1 {
return;
}
let heading = self.window.turtle().heading;
let angle = (target_y - y).atan2(target_x - x);
let angle = Radians::from_radians_value(angle);
let angle = (angle - heading) % radians::TWO_PI;
// Try to rotate as little as possible
let angle = if angle.abs() > radians::PI {
// Using signum to deal with negative angles properly
angle.signum()*(radians::TWO_PI - angle.abs())
}
else {
angle
};
self.window.rotate(angle, false);
}
/// Returns the next event (if any).
//TODO: Example of usage with an event loop
pub fn poll_event(&mut self) -> Option<Event> {
self.window.poll_event()
}
/// Convenience function that waits for a click to occur before returning.
///
/// Useful for when you want your program to wait for the user to click before continuing so
/// that it doesn't start right away.
pub fn wait_for_click(&mut self) {
loop {
if let Some(Event::MouseButtonReleased(MouseButton::Left)) = self.poll_event() {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_using_radians_degrees() {
// is_using_radians and is_using_degrees should be inverses of each other
let mut turtle = Turtle::new();
assert!(!turtle.is_using_radians());
assert!(turtle.is_using_degrees());
turtle.use_radians();
assert!(turtle.is_using_radians());
assert!(!turtle.is_using_degrees());
turtle.use_degrees();
assert!(!turtle.is_using_radians());
assert!(turtle.is_using_degrees());
}
}
Changed calling convention used in docs to refer to methods
use radians::{self, Radians};
use turtle_window::TurtleWindow;
use event::MouseButton;
use {Speed, Color, Event};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AngleUnit {
Degrees,
Radians,
}
impl AngleUnit {
fn to_radians(&self, angle: Angle) -> Radians {
match *self {
AngleUnit::Degrees => Radians::from_degrees_value(angle),
AngleUnit::Radians => Radians::from_radians_value(angle),
}
}
fn to_angle(&self, angle: Radians) -> Angle {
match *self {
AngleUnit::Degrees => angle.to_degrees(),
AngleUnit::Radians => angle.to_radians(),
}
}
}
/// A point in 2D space: [x, y]
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::Point;
/// # fn main() {
/// let p: Point = [100., 120.];
/// // get x coordinate
/// let x = p[0];
/// assert_eq!(x, 100.);
/// // get y coordinate
/// let y = p[1];
/// assert_eq!(y, 120.);
/// # }
pub type Point = [f64; 2];
/// Any distance value
pub type Distance = f64;
/// An angle value without a unit
///
/// The unit of the angle represented by this value depends on what
/// unit the Turtle was set to when this angle was retrieved
pub type Angle = f64;
/// A turtle with a pen attached to its tail.
///
/// **The idea:** You control a turtle with a pen tied to its tail. As it moves
/// across the screen, it draws the path that it follows. You can use this to draw
/// any picture you want just by moving the turtle across the screen.
///
/// 
///
/// See the documentation for the methods below to learn about the different drawing commands you
/// can use with the turtle.
pub struct Turtle {
window: TurtleWindow,
angle_unit: AngleUnit,
}
impl Turtle {
/// Create a new turtle.
///
/// This will immediately open a new window with the turtle at the center. As each line in
/// your program runs, the turtle shown in the window will update.
///
/// ```rust
/// # #![allow(unused_variables, unused_mut)]
/// extern crate turtle;
/// use turtle::Turtle;
///
/// fn main() {
/// let mut turtle = Turtle::new();
/// // Do things with the turtle...
/// }
/// ```
pub fn new() -> Turtle {
Turtle {
window: TurtleWindow::new(),
angle_unit: AngleUnit::Degrees,
}
}
/// Returns the current speed of the turtle
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.set_speed(8);
/// assert_eq!(turtle.speed(), Speed::Eight);
/// # }
/// ```
pub fn speed(&self) -> Speed {
self.window.turtle().speed
}
/// Set the turtle's movement speed to the given setting. This speed affects the animation of
/// the turtle's movement and rotation. The turtle's speed is limited to values between 0 and
/// 10. If you pass in values that are not integers or outside of that range, the closest
/// possible value will be chosen.
///
/// This method's types make it so that it can be called in a number of different ways:
///
/// ```rust,no_run
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.set_speed("normal");
/// turtle.set_speed("fast");
/// turtle.set_speed(2);
/// turtle.set_speed(10);
/// // Directly using a Speed variant works, but the methods above are usually more convenient.
/// turtle.set_speed(Speed::Six);
/// # }
/// ```
///
/// If input is a number greater than 10 or smaller than 1,
/// speed is set to 0 (`Speed::Instant`). Strings are converted as follows:
///
/// | String | Value |
/// | ----------- | -------------- |
/// | `"slowest"` | `Speed::One` |
/// | `"slow"` | `Speed::Three` |
/// | `"normal"` | `Speed::Six` |
/// | `"fast"` | `Speed::Eight` |
/// | `"fastest"` | `Speed::Ten` |
/// | `"instant"` | `Speed::Instant` |
///
/// Anything else will cause the program to `panic!` at runtime.
///
/// ## Moving Instantly
///
/// A speed of zero (`Speed::Instant`) results in no animation. The turtle moves instantly
/// and turns instantly. This is very useful for moving the turtle from its "home" position
/// before you start drawing. By setting the speed to instant, you don't have to wait for
/// the turtle to move into position.
///
/// ## Learning About Conversion Traits
///
/// Using this method is an excellent way to learn about conversion
/// traits `From` and `Into`. This method takes a *generic type* as its speed parameter. That type
/// is specified to implement the `Into` trait for the type `Speed`. That means that *any* type
/// that can be converted into a `Speed` can be passed to this method.
///
/// We have implemented that trait for several types like strings and 32-bit integers so that
/// those values can be passed into this method.
/// Rather than calling this function and passing `Speed::Six` directly, you can use just `6`.
/// Rust will then allow us to call `.into()` as provided by the `Into<Speed>` trait to get the
/// corresponding `Speed` value.
///
/// You can pass in strings, 32-bit integers, and even `Speed` enum variants because they all
/// implement the `Into<Speed>` trait.
pub fn set_speed<S: Into<Speed>>(&mut self, speed: S) {
self.window.turtle_mut().speed = speed.into();
}
/// Returns the turtle's current location (x, y)
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// turtle.forward(100.0);
/// let pos = turtle.position();
/// # // Cheating a bit here for rounding...
/// # let pos = [pos[0].round(), pos[1].round()];
/// assert_eq!(pos, [0.0, 100.0]);
/// # }
/// ```
pub fn position(&self) -> Point {
self.window.turtle().position
}
/// Returns the turtle's current heading.
///
/// Units are by default degrees, but can be set using the
/// [`use_degrees()`](struct.Turtle.html#method.use_degrees) or
/// [`use_radians()`](struct.Turtle.html#method.use_radians) methods.
///
/// The heading is relative to the positive x axis (east). When first created, the turtle
/// starts facing north. That means that its heading is 90.0 degrees. The following chart
/// contains many common directions and their angles.
///
/// | Cardinal Direction | Heading (degrees) | Heading (radians) |
/// | ------------------ | ----------------- | ----------------- |
/// | East | 0.0° | `0.0` |
/// | North | 90.0° | `PI/2` |
/// | West | 180.0° | `PI` |
/// | South | 270.0° | `3*PI/2` |
///
/// You can test the result of `heading()` with these values to see if the turtle is facing
/// a certain direction.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// // Turtles start facing north
/// let mut turtle = Turtle::new();
/// // The rounding is to account for floating-point error
/// assert_eq!(turtle.heading().round(), 90.0);
/// turtle.right(31.0);
/// assert_eq!(turtle.heading().round(), 59.0);
/// turtle.left(193.0);
/// assert_eq!(turtle.heading().round(), 252.0);
/// turtle.left(130.0);
/// // Angles should not exceed 360.0
/// assert_eq!(turtle.heading().round(), 22.0);
/// # }
/// ```
pub fn heading(&self) -> Angle {
let heading = self.window.turtle().heading;
self.angle_unit.to_angle(heading)
}
/// Returns true if `Angle` values will be interpreted as degrees.
///
/// See [`use_degrees()`](struct.Turtle.html#method.use_degrees) for more information.
pub fn is_using_degrees(&self) -> bool {
self.angle_unit == AngleUnit::Degrees
}
/// Returns true if `Angle` values will be interpreted as radians.
///
/// See [`use_radians()`](struct.Turtle.html#method.use_degrees) for more information.
pub fn is_using_radians(&self) -> bool {
self.angle_unit == AngleUnit::Radians
}
/// Change the angle unit to degrees.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.use_radians();
/// assert!(!turtle.is_using_degrees());
/// turtle.use_degrees();
/// assert!(turtle.is_using_degrees());
/// # }
/// ```
pub fn use_degrees(&mut self) {
self.angle_unit = AngleUnit::Degrees;
}
/// Change the angle unit to radians.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(!turtle.is_using_radians());
/// turtle.use_radians();
/// assert!(turtle.is_using_radians());
/// # }
/// ```
pub fn use_radians(&mut self) {
self.angle_unit = AngleUnit::Radians;
}
/// Return true if pen is down, false if it’s up.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_pen_down());
/// turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// turtle.pen_down();
/// assert!(turtle.is_pen_down());
/// # }
/// ```
pub fn is_pen_down(&self) -> bool {
self.window.drawing().pen.enabled
}
/// Pull the pen down so that the turtle draws while moving.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// // This will move the turtle, but not draw any lines
/// turtle.forward(100.0);
/// turtle.pen_down();
/// assert!(turtle.is_pen_down());
/// // The turtle will now draw lines again
/// turtle.forward(100.0);
/// # }
/// ```
pub fn pen_down(&mut self) {
self.window.drawing_mut().pen.enabled = true;
}
/// Pick the pen up so that the turtle does not draw while moving
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_pen_down());
/// // The turtle will move and draw a line
/// turtle.forward(100.0);
/// turtle.pen_up();
/// assert!(!turtle.is_pen_down());
/// // Now, the turtle will move, but not draw anything
/// turtle.forward(100.0);
/// # }
/// ```
pub fn pen_up(&mut self) {
self.window.drawing_mut().pen.enabled = false;
}
/// Returns the size (thickness) of the pen. The thickness is measured in pixels.
///
/// See [`set_pen_size()`](struct.Turtle.html#method.set_pen_size) for more details.
pub fn pen_size(&self) -> f64 {
self.window.drawing().pen.thickness
}
/// Sets the thickness of the pen to the given size. The thickness is measured in pixels.
///
/// The turtle's pen has a flat tip. The value you set the pen's size to will change the
/// width of the stroke created by the turtle as it moves. See the example below for more
/// about what this means.
///
/// # Example
///
/// ```rust,no_run
/// extern crate turtle;
/// use turtle::Turtle;
///
/// fn main() {
/// let mut turtle = Turtle::new();
///
/// turtle.pen_up();
/// turtle.right(90.0);
/// turtle.backward(300.0);
/// turtle.pen_down();
///
/// turtle.set_pen_color("#2196F3"); // blue
/// turtle.set_pen_size(1.0);
/// turtle.forward(200.0);
///
/// turtle.set_pen_color("#f44336"); // red
/// turtle.set_pen_size(50.0);
/// turtle.forward(200.0);
///
/// turtle.set_pen_color("#4CAF50"); // green
/// turtle.set_pen_size(100.0);
/// turtle.forward(200.0);
/// }
/// ```
///
/// This will produce the following:
///
/// 
///
/// Notice that while the turtle travels in a straight line, it produces different thicknesses
/// of lines which appear like large rectangles.
pub fn set_pen_size(&mut self, thickness: f64) {
self.window.drawing_mut().pen.thickness = thickness;
}
/// Returns the color of the pen
pub fn pen_color(&self) -> Color {
self.window.drawing().pen.color
}
/// Sets the color of the pen to the given color
//TODO: Document this more like set_speed
pub fn set_pen_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().pen.color = color.into();
}
/// Returns the color of the background
pub fn background_color(&self) -> Color {
self.window.drawing().background
}
/// Sets the color of the background to the given color
//TODO: Document this more like set_speed
pub fn set_background_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().background = color.into();
}
/// Returns the current fill color
///
/// This will be used to fill the shape when `begin_fill()` and `end_fill()` are called.
//TODO: Hyperlink begin_fill() and end_fill() methods to their docs
pub fn fill_color(&self) -> Color {
self.window.drawing().fill_color
}
/// Sets the fill color to the given color
///
/// **Note:** Only the fill color set **before** `begin_fill()` is called will be used to fill
/// the shape.
//TODO: Document this more like set_speed
pub fn set_fill_color<C: Into<Color>>(&mut self, color: C) {
self.window.drawing_mut().fill_color = color.into();
}
/// Begin filling the shape drawn by the turtle's movements
pub fn begin_fill(&mut self) {
self.window.begin_fill();
}
/// Stop filling the shape drawn by the turtle's movements
pub fn end_fill(&mut self) {
self.window.end_fill();
}
/// Returns true if the turtle is visible.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// let mut turtle = Turtle::new();
/// assert!(turtle.is_visible());
/// turtle.hide();
/// assert!(!turtle.is_visible());
/// turtle.show();
/// assert!(turtle.is_visible());
/// # }
/// ```
pub fn is_visible(&self) -> bool {
self.window.turtle().visible
}
/// Makes the turtle invisible. The shell will not be shown, but drawings will continue.
///
/// Useful for some complex drawings.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// assert!(turtle.is_visible());
/// turtle.hide();
/// assert!(!turtle.is_visible());
/// # }
/// ```
pub fn hide(&mut self) {
self.window.turtle_mut().visible = false;
}
/// Makes the turtle visible.
///
/// ```rust
/// # extern crate turtle;
/// # use turtle::*;
/// # fn main() {
/// # let mut turtle = Turtle::new();
/// # turtle.hide();
/// assert!(!turtle.is_visible());
/// turtle.show();
/// assert!(turtle.is_visible());
/// # }
/// ```
pub fn show(&mut self) {
self.window.turtle_mut().visible = true;
}
/// Delete the turtle's drawings from the screen.
///
/// Do not move turtle. Position and heading of the turtle are not affected.
pub fn clear(&mut self) {
self.window.clear();
}
/// Move the turtle forward by the given amount of `distance`. If the pen is down, the turtle
/// will draw a line as it moves.
///
/// `distance` is given in "pixels" which are like really small turtle steps.
/// `distance` can be negative in which case the turtle can move backward
/// using this method.
pub fn forward(&mut self, distance: Distance) {
self.window.forward(distance);
}
/// Move the turtle backward by the given amount of `distance`. If the pen is down, the turtle
/// will draw a line as it moves.
///
/// `distance` is given in "pixels" which are like really small turtle steps.
/// `distance` can be negative in which case the turtle can move forwards
/// using this method.
pub fn backward(&mut self, distance: Distance) {
// Moving backwards is essentially moving forwards with a negative distance
self.window.forward(-distance);
}
/// Rotate the turtle right (clockwise) by the given angle. Since the turtle rotates in place,
/// its position will not change and it will not draw anything at all.
///
/// Units are by default degrees, but can be set using the methods
/// [`use_degrees()`](struct.Turtle.html#method.use_degrees) or
/// [`use_radians()`](struct.Turtle.html#method.use_radians).
pub fn right(&mut self, angle: Angle) {
let angle = self.angle_unit.to_radians(angle);
self.window.rotate(angle, true);
}
/// Rotate the turtle left (counterclockwise) by the given angle. Since the turtle rotates
/// in place, its position will not change and it will not draw anything at all.
///
/// Units are by default degrees, but can be set using the methods
/// [`use_degrees()`](struct.Turtle.html#method.use_degrees) or
/// [`use_radians()`](struct.Turtle.html#method.use_radians).
pub fn left(&mut self, angle: Angle) {
let angle = self.angle_unit.to_radians(angle);
self.window.rotate(angle, false);
}
/// Rotates the turtle to face the given coordinates.
/// Coordinates are relative to the center of the window.
///
/// If the coordinates are the same as the turtle's current position, no rotation takes place.
/// Always rotates the least amount necessary in order to face the given point.
///
/// ## UNSTABLE
/// This feature is currently unstable and completely buggy. Do not use it until it is fixed.
pub fn turn_towards(&mut self, target: Point) {
let target_x = target[0];
let target_y = target[1];
let position = self.position();
let x = position[0];
let y = position[1];
if (target_x - x).abs() < 0.1 && (target_y - y).abs() < 0.1 {
return;
}
let heading = self.window.turtle().heading;
let angle = (target_y - y).atan2(target_x - x);
let angle = Radians::from_radians_value(angle);
let angle = (angle - heading) % radians::TWO_PI;
// Try to rotate as little as possible
let angle = if angle.abs() > radians::PI {
// Using signum to deal with negative angles properly
angle.signum()*(radians::TWO_PI - angle.abs())
}
else {
angle
};
self.window.rotate(angle, false);
}
/// Returns the next event (if any).
//TODO: Example of usage with an event loop
pub fn poll_event(&mut self) -> Option<Event> {
self.window.poll_event()
}
/// Convenience function that waits for a click to occur before returning.
///
/// Useful for when you want your program to wait for the user to click before continuing so
/// that it doesn't start right away.
pub fn wait_for_click(&mut self) {
loop {
if let Some(Event::MouseButtonReleased(MouseButton::Left)) = self.poll_event() {
break;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_using_radians_degrees() {
// is_using_radians and is_using_degrees should be inverses of each other
let mut turtle = Turtle::new();
assert!(!turtle.is_using_radians());
assert!(turtle.is_using_degrees());
turtle.use_radians();
assert!(turtle.is_using_radians());
assert!(!turtle.is_using_degrees());
turtle.use_degrees();
assert!(!turtle.is_using_radians());
assert!(turtle.is_using_degrees());
}
}
|
use std::ptr::null;
use libc::{c_int, c_char, c_double};
use std::sync::{StaticMutex, MUTEX_INIT};
use utils::_string;
#[link(name="gdal")]
extern {
fn OGRRegisterAll();
fn OGROpen(pszName: *const c_char, bUpdate: c_int, pahDriverList: *const ()) -> *const ();
fn OGR_DS_GetLayerCount(hDS: *const ()) -> c_int;
fn OGR_DS_Destroy(hDataSource: *const ());
fn OGR_DS_GetLayer(hDS: *const (), iLayer: c_int) -> *const ();
fn OGR_L_GetLayerDefn(hLayer: *const ()) -> *const ();
fn OGR_L_GetNextFeature(hLayer: *const ()) -> *const ();
fn OGR_FD_GetFieldCount(hDefn: *const ()) -> c_int;
fn OGR_FD_GetFieldDefn(hDefn: *const (), iField: c_int) -> *const ();
fn OGR_F_GetFieldIndex(hFeat: *const (), pszName: *const c_char) -> c_int;
fn OGR_F_GetFieldDefnRef(hFeat: *const (), i: c_int) -> *const ();
fn OGR_F_GetFieldAsString(hFeat: *const (), iField: c_int) -> *const c_char;
fn OGR_F_GetFieldAsDouble(hFeat: *const (), iField: c_int) -> c_double;
fn OGR_F_GetGeometryRef(hFeat: *const ()) -> *const ();
fn OGR_F_Destroy(hFeat: *const ());
fn OGR_G_ExportToWkt(hGeom: *const (), ppszSrcText: *const *const c_char) -> c_int;
fn OGR_G_ExportToJson(hGeometry: *const ()) -> *const c_char;
fn OGR_Fld_GetNameRef(hDefn: *const ()) -> *const c_char;
fn OGR_Fld_GetType(hDefn: *const ()) -> c_int;
fn OGRFree(ptr: *const ());
fn VSIFree(ptr: *const ());
}
const OFT_REAL: c_int = 2;
const OFT_STRING: c_int = 4;
static mut LOCK: StaticMutex = MUTEX_INIT;
static mut registered_drivers: bool = false;
fn register_drivers() {
unsafe {
let _g = LOCK.lock();
if ! registered_drivers {
OGRRegisterAll();
registered_drivers = true;
}
}
}
pub struct VectorDataset {
c_dataset: *const (),
}
impl VectorDataset {
pub fn count(&self) -> int {
return unsafe { OGR_DS_GetLayerCount(self.c_dataset) } as int;
}
pub fn layer<'a>(&'a self, idx: int) -> Option<Layer<'a>> {
let c_layer = unsafe { OGR_DS_GetLayer(self.c_dataset, idx as c_int) };
return match c_layer.is_null() {
true => None,
false => Some(Layer{vector_dataset: self, c_layer: c_layer}),
};
}
}
impl Drop for VectorDataset {
fn drop(&mut self) {
unsafe { OGR_DS_Destroy(self.c_dataset); }
}
}
pub struct Layer<'a> {
vector_dataset: &'a VectorDataset,
c_layer: *const (),
}
impl<'a> Layer<'a> {
pub fn fields(&'a self) -> FieldIterator<'a> {
let c_feature_defn = unsafe { OGR_L_GetLayerDefn(self.c_layer) };
let total = unsafe { OGR_FD_GetFieldCount(c_feature_defn) } as int;
return FieldIterator{
layer: self,
c_feature_defn: c_feature_defn,
next_id: 0,
total: total
};
}
pub fn features(&'a self) -> FeatureIterator<'a> {
return FeatureIterator{layer: self};
}
}
pub struct FieldIterator<'a> {
layer: &'a Layer<'a>,
c_feature_defn: *const (),
next_id: int,
total: int,
}
impl<'a> Iterator<Field<'a>> for FieldIterator<'a> {
#[inline]
fn next(&mut self) -> Option<Field<'a>> {
if self.next_id == self.total {
return None;
}
let field = Field{
layer: self.layer,
c_field_defn: unsafe { OGR_FD_GetFieldDefn(
self.c_feature_defn,
self.next_id as c_int
) }
};
self.next_id += 1;
return Some(field);
}
}
pub struct Field<'a> {
layer: &'a Layer<'a>,
c_field_defn: *const (),
}
impl<'a> Field<'a> {
pub fn name(&'a self) -> String {
let rv = unsafe { OGR_Fld_GetNameRef(self.c_field_defn) };
return _string(rv);
}
}
pub struct FeatureIterator<'a> {
layer: &'a Layer<'a>,
}
impl<'a> Iterator<Feature<'a>> for FeatureIterator<'a> {
#[inline]
fn next(&mut self) -> Option<Feature<'a>> {
let c_feature = unsafe { OGR_L_GetNextFeature(self.layer.c_layer) };
return match c_feature.is_null() {
true => None,
false => Some(Feature{layer: self.layer, c_feature: c_feature}),
};
}
}
pub struct Feature<'a> {
layer: &'a Layer<'a>,
c_feature: *const (),
}
impl<'a> Feature<'a> {
pub fn field(&self, name: &str) -> Option<FieldValue> {
return name.with_c_str(|c_name| unsafe {
let field_id = OGR_F_GetFieldIndex(self.c_feature, c_name);
if field_id == -1 {
return None;
}
let field_defn = OGR_F_GetFieldDefnRef(self.c_feature, field_id);
let field_type = OGR_Fld_GetType(field_defn);
return match field_type {
OFT_STRING => {
let rv = OGR_F_GetFieldAsString(self.c_feature, field_id);
return Some(FieldValue::StringValue(_string(rv)));
},
OFT_REAL => {
let rv = OGR_F_GetFieldAsDouble(self.c_feature, field_id);
return Some(FieldValue::RealValue(rv as f64));
},
_ => panic!("Unknown field type {}", field_type)
}
});
}
pub fn wkt(&self) -> String {
unsafe {
let c_geom = OGR_F_GetGeometryRef(self.c_feature);
let c_wkt: *const c_char = null();
OGR_G_ExportToWkt(c_geom, &c_wkt);
let wkt = _string(c_wkt);
OGRFree(c_wkt as *const ());
return wkt;
}
}
pub fn json(&self) -> String {
unsafe {
let c_geom = OGR_F_GetGeometryRef(self.c_feature);
let c_json = OGR_G_ExportToJson(c_geom);
let json = _string(c_json);
VSIFree(c_json as *const ());
return json;
}
}
}
#[unsafe_destructor]
impl<'a> Drop for Feature<'a> {
fn drop(&mut self) {
unsafe { OGR_F_Destroy(self.c_feature); }
}
}
pub fn open(path: &Path) -> Option<VectorDataset> {
register_drivers();
let filename = path.as_str().unwrap();
let c_dataset = filename.with_c_str(|c_filename| {
return unsafe { OGROpen(c_filename, 0, null()) };
});
return match c_dataset.is_null() {
true => None,
false => Some(VectorDataset{c_dataset: c_dataset}),
};
}
pub enum FieldValue {
StringValue(String),
RealValue(f64),
}
impl FieldValue {
pub fn as_string(self) -> String {
match self {
FieldValue::StringValue(rv) => rv,
_ => panic!("not a StringValue")
}
}
pub fn as_real(self) -> f64 {
match self {
FieldValue::RealValue(rv) => rv,
_ => panic!("not a RealValue")
}
}
}
#[cfg(test)]
mod test {
use std::path::Path;
use super::{Feature, FeatureIterator, open};
fn fixtures() -> Path {
return Path::new(file!()).dir_path().dir_path().join("fixtures");
}
fn assert_almost_eq(a: f64, b: f64) {
let f: f64 = a / b;
assert!(f < 1.00001);
assert!(f > 0.99999);
}
#[test]
fn test_layer_count() {
let ds = open(&fixtures().join("roads.geojson")).unwrap();
assert_eq!(ds.count(), 1);
}
fn with_features(fixture: &str, f: |FeatureIterator|) {
let ds = open(&fixtures().join(fixture)).unwrap();
let layer = ds.layer(0).unwrap();
f(layer.features());
}
fn with_first_feature(fixture: &str, f: |Feature|) {
with_features(fixture, |mut features| f(features.next().unwrap()));
}
#[test]
fn test_iterate_features() {
with_features("roads.geojson", |features| {
let feature_vec: Vec<Feature> = features.collect();
assert_eq!(feature_vec.len(), 21);
});
}
#[test]
fn test_string_field() {
with_features("roads.geojson", |mut features| {
let feature = features.next().unwrap();
assert_eq!(feature.field("highway")
.unwrap()
.as_string(),
"footway".to_string());
assert_eq!(
features.filter(|field| {
let highway = field.field("highway")
.unwrap()
.as_string();
highway == "residential".to_string() })
.count(),
2);
});
}
#[test]
fn test_float_field() {
with_first_feature("roads.geojson", |feature| {
assert_almost_eq(
feature.field("sort_key")
.unwrap()
.as_real(),
-9.0
);
});
}
#[test]
fn test_missing_field() {
with_first_feature("roads.geojson", |feature| {
assert!(feature.field("no such field").is_none());
});
}
#[test]
fn test_wkt() {
with_first_feature("roads.geojson", |feature| {
let wkt = feature.wkt();
let wkt_ok = format!("{}{}",
"LINESTRING (26.1019276 44.4302748,",
"26.1019382 44.4303191,26.1020002 44.4304202)"
).to_string();
assert_eq!(wkt, wkt_ok);
});
}
#[test]
fn test_json() {
with_first_feature("roads.geojson", |feature| {
let json = feature.json();
let json_ok = format!("{}{}{}{}",
"{ \"type\": \"LineString\", \"coordinates\": [ ",
"[ 26.1019276, 44.4302748 ], ",
"[ 26.1019382, 44.4303191 ], ",
"[ 26.1020002, 44.4304202 ] ] }"
).to_string();
assert_eq!(json, json_ok);
});
}
#[test]
fn test_schema() {
let ds = open(&fixtures().join("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
let name_list: Vec<String> = layer
.fields()
.map(|f| f.name())
.collect();
let ok_names: Vec<String> = vec!(
"kind", "sort_key", "is_link", "is_tunnel",
"is_bridge", "railway", "highway")
.iter().map(|s| s.to_string()).collect();
assert_eq!(name_list, ok_names);
}
}
rename fields to remove dead_code warnings
use std::ptr::null;
use libc::{c_int, c_char, c_double};
use std::sync::{StaticMutex, MUTEX_INIT};
use utils::_string;
#[link(name="gdal")]
extern {
fn OGRRegisterAll();
fn OGROpen(pszName: *const c_char, bUpdate: c_int, pahDriverList: *const ()) -> *const ();
fn OGR_DS_GetLayerCount(hDS: *const ()) -> c_int;
fn OGR_DS_Destroy(hDataSource: *const ());
fn OGR_DS_GetLayer(hDS: *const (), iLayer: c_int) -> *const ();
fn OGR_L_GetLayerDefn(hLayer: *const ()) -> *const ();
fn OGR_L_GetNextFeature(hLayer: *const ()) -> *const ();
fn OGR_FD_GetFieldCount(hDefn: *const ()) -> c_int;
fn OGR_FD_GetFieldDefn(hDefn: *const (), iField: c_int) -> *const ();
fn OGR_F_GetFieldIndex(hFeat: *const (), pszName: *const c_char) -> c_int;
fn OGR_F_GetFieldDefnRef(hFeat: *const (), i: c_int) -> *const ();
fn OGR_F_GetFieldAsString(hFeat: *const (), iField: c_int) -> *const c_char;
fn OGR_F_GetFieldAsDouble(hFeat: *const (), iField: c_int) -> c_double;
fn OGR_F_GetGeometryRef(hFeat: *const ()) -> *const ();
fn OGR_F_Destroy(hFeat: *const ());
fn OGR_G_ExportToWkt(hGeom: *const (), ppszSrcText: *const *const c_char) -> c_int;
fn OGR_G_ExportToJson(hGeometry: *const ()) -> *const c_char;
fn OGR_Fld_GetNameRef(hDefn: *const ()) -> *const c_char;
fn OGR_Fld_GetType(hDefn: *const ()) -> c_int;
fn OGRFree(ptr: *const ());
fn VSIFree(ptr: *const ());
}
const OFT_REAL: c_int = 2;
const OFT_STRING: c_int = 4;
static mut LOCK: StaticMutex = MUTEX_INIT;
static mut registered_drivers: bool = false;
fn register_drivers() {
unsafe {
let _g = LOCK.lock();
if ! registered_drivers {
OGRRegisterAll();
registered_drivers = true;
}
}
}
pub struct VectorDataset {
c_dataset: *const (),
}
impl VectorDataset {
pub fn count(&self) -> int {
return unsafe { OGR_DS_GetLayerCount(self.c_dataset) } as int;
}
pub fn layer<'a>(&'a self, idx: int) -> Option<Layer<'a>> {
let c_layer = unsafe { OGR_DS_GetLayer(self.c_dataset, idx as c_int) };
return match c_layer.is_null() {
true => None,
false => Some(Layer{_vector_dataset: self, c_layer: c_layer}),
};
}
}
impl Drop for VectorDataset {
fn drop(&mut self) {
unsafe { OGR_DS_Destroy(self.c_dataset); }
}
}
pub struct Layer<'a> {
_vector_dataset: &'a VectorDataset,
c_layer: *const (),
}
impl<'a> Layer<'a> {
pub fn fields(&'a self) -> FieldIterator<'a> {
let c_feature_defn = unsafe { OGR_L_GetLayerDefn(self.c_layer) };
let total = unsafe { OGR_FD_GetFieldCount(c_feature_defn) } as int;
return FieldIterator{
layer: self,
c_feature_defn: c_feature_defn,
next_id: 0,
total: total
};
}
pub fn features(&'a self) -> FeatureIterator<'a> {
return FeatureIterator{layer: self};
}
}
pub struct FieldIterator<'a> {
layer: &'a Layer<'a>,
c_feature_defn: *const (),
next_id: int,
total: int,
}
impl<'a> Iterator<Field<'a>> for FieldIterator<'a> {
#[inline]
fn next(&mut self) -> Option<Field<'a>> {
if self.next_id == self.total {
return None;
}
let field = Field{
_layer: self.layer,
c_field_defn: unsafe { OGR_FD_GetFieldDefn(
self.c_feature_defn,
self.next_id as c_int
) }
};
self.next_id += 1;
return Some(field);
}
}
pub struct Field<'a> {
_layer: &'a Layer<'a>,
c_field_defn: *const (),
}
impl<'a> Field<'a> {
pub fn name(&'a self) -> String {
let rv = unsafe { OGR_Fld_GetNameRef(self.c_field_defn) };
return _string(rv);
}
}
pub struct FeatureIterator<'a> {
layer: &'a Layer<'a>,
}
impl<'a> Iterator<Feature<'a>> for FeatureIterator<'a> {
#[inline]
fn next(&mut self) -> Option<Feature<'a>> {
let c_feature = unsafe { OGR_L_GetNextFeature(self.layer.c_layer) };
return match c_feature.is_null() {
true => None,
false => Some(Feature{_layer: self.layer, c_feature: c_feature}),
};
}
}
pub struct Feature<'a> {
_layer: &'a Layer<'a>,
c_feature: *const (),
}
impl<'a> Feature<'a> {
pub fn field(&self, name: &str) -> Option<FieldValue> {
return name.with_c_str(|c_name| unsafe {
let field_id = OGR_F_GetFieldIndex(self.c_feature, c_name);
if field_id == -1 {
return None;
}
let field_defn = OGR_F_GetFieldDefnRef(self.c_feature, field_id);
let field_type = OGR_Fld_GetType(field_defn);
return match field_type {
OFT_STRING => {
let rv = OGR_F_GetFieldAsString(self.c_feature, field_id);
return Some(FieldValue::StringValue(_string(rv)));
},
OFT_REAL => {
let rv = OGR_F_GetFieldAsDouble(self.c_feature, field_id);
return Some(FieldValue::RealValue(rv as f64));
},
_ => panic!("Unknown field type {}", field_type)
}
});
}
pub fn wkt(&self) -> String {
unsafe {
let c_geom = OGR_F_GetGeometryRef(self.c_feature);
let c_wkt: *const c_char = null();
OGR_G_ExportToWkt(c_geom, &c_wkt);
let wkt = _string(c_wkt);
OGRFree(c_wkt as *const ());
return wkt;
}
}
pub fn json(&self) -> String {
unsafe {
let c_geom = OGR_F_GetGeometryRef(self.c_feature);
let c_json = OGR_G_ExportToJson(c_geom);
let json = _string(c_json);
VSIFree(c_json as *const ());
return json;
}
}
}
#[unsafe_destructor]
impl<'a> Drop for Feature<'a> {
fn drop(&mut self) {
unsafe { OGR_F_Destroy(self.c_feature); }
}
}
pub fn open(path: &Path) -> Option<VectorDataset> {
register_drivers();
let filename = path.as_str().unwrap();
let c_dataset = filename.with_c_str(|c_filename| {
return unsafe { OGROpen(c_filename, 0, null()) };
});
return match c_dataset.is_null() {
true => None,
false => Some(VectorDataset{c_dataset: c_dataset}),
};
}
pub enum FieldValue {
StringValue(String),
RealValue(f64),
}
impl FieldValue {
pub fn as_string(self) -> String {
match self {
FieldValue::StringValue(rv) => rv,
_ => panic!("not a StringValue")
}
}
pub fn as_real(self) -> f64 {
match self {
FieldValue::RealValue(rv) => rv,
_ => panic!("not a RealValue")
}
}
}
#[cfg(test)]
mod test {
use std::path::Path;
use super::{Feature, FeatureIterator, open};
fn fixtures() -> Path {
return Path::new(file!()).dir_path().dir_path().join("fixtures");
}
fn assert_almost_eq(a: f64, b: f64) {
let f: f64 = a / b;
assert!(f < 1.00001);
assert!(f > 0.99999);
}
#[test]
fn test_layer_count() {
let ds = open(&fixtures().join("roads.geojson")).unwrap();
assert_eq!(ds.count(), 1);
}
fn with_features(fixture: &str, f: |FeatureIterator|) {
let ds = open(&fixtures().join(fixture)).unwrap();
let layer = ds.layer(0).unwrap();
f(layer.features());
}
fn with_first_feature(fixture: &str, f: |Feature|) {
with_features(fixture, |mut features| f(features.next().unwrap()));
}
#[test]
fn test_iterate_features() {
with_features("roads.geojson", |features| {
let feature_vec: Vec<Feature> = features.collect();
assert_eq!(feature_vec.len(), 21);
});
}
#[test]
fn test_string_field() {
with_features("roads.geojson", |mut features| {
let feature = features.next().unwrap();
assert_eq!(feature.field("highway")
.unwrap()
.as_string(),
"footway".to_string());
assert_eq!(
features.filter(|field| {
let highway = field.field("highway")
.unwrap()
.as_string();
highway == "residential".to_string() })
.count(),
2);
});
}
#[test]
fn test_float_field() {
with_first_feature("roads.geojson", |feature| {
assert_almost_eq(
feature.field("sort_key")
.unwrap()
.as_real(),
-9.0
);
});
}
#[test]
fn test_missing_field() {
with_first_feature("roads.geojson", |feature| {
assert!(feature.field("no such field").is_none());
});
}
#[test]
fn test_wkt() {
with_first_feature("roads.geojson", |feature| {
let wkt = feature.wkt();
let wkt_ok = format!("{}{}",
"LINESTRING (26.1019276 44.4302748,",
"26.1019382 44.4303191,26.1020002 44.4304202)"
).to_string();
assert_eq!(wkt, wkt_ok);
});
}
#[test]
fn test_json() {
with_first_feature("roads.geojson", |feature| {
let json = feature.json();
let json_ok = format!("{}{}{}{}",
"{ \"type\": \"LineString\", \"coordinates\": [ ",
"[ 26.1019276, 44.4302748 ], ",
"[ 26.1019382, 44.4303191 ], ",
"[ 26.1020002, 44.4304202 ] ] }"
).to_string();
assert_eq!(json, json_ok);
});
}
#[test]
fn test_schema() {
let ds = open(&fixtures().join("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
let name_list: Vec<String> = layer
.fields()
.map(|f| f.name())
.collect();
let ok_names: Vec<String> = vec!(
"kind", "sort_key", "is_link", "is_tunnel",
"is_bridge", "railway", "highway")
.iter().map(|s| s.to_string()).collect();
assert_eq!(name_list, ok_names);
}
}
|
//! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use glfw;
use std::libc;
use std::io::timer::Timer;
use std::num::Zero;
use std::hashmap::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use extra::time;
use extra::arc::RWArc;
use gl;
use gl::types::*;
use stb_image::image::*;
use nalgebra::na::{Vec2, Vec3, Vec4};
use nalgebra::na;
use camera::{Camera, ArcBall};
use object::Object;
use line_renderer::LineRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use builtin::ObjectMaterial;
use builtin::loader;
use event;
use loader::obj;
use loader::mtl::MtlMaterial;
use light::{Light, Absolute, StickToCamera};
use text::{TextRenderer, Font};
mod error;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window<'a> {
priv window: glfw::Window,
priv max_ms_per_frame: Option<u64>,
priv objects: ~[Object],
priv camera: &'a mut Camera,
priv light_mode: Light,
priv wireframe_mode: bool,
priv geometries: HashMap<~str, Rc<RefCell<Mesh>>>,
priv background: Vec3<GLfloat>,
priv line_renderer: LineRenderer,
priv text_renderer: TextRenderer,
priv framebuffer_manager: FramebufferManager,
priv post_processing: Option<&'a mut PostProcessingEffect>,
priv post_process_render_target: RenderTarget,
priv events: RWArc<~[event::Event]>,
priv object_material: Rc<RefCell<~Material>>
}
impl<'a> Window<'a> {
/// Access the glfw window.
pub fn glfw_window<'r>(&'r self) -> &'r glfw::Window {
&self.window
}
/// Sets the current processing effect.
pub fn set_post_processing_effect(&mut self, effect: Option<&'a mut PostProcessingEffect>) {
self.post_processing = effect;
}
/// The window width.
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The current camera.
pub fn camera<'b>(&'b self) -> &'b &'a mut Camera {
&'b self.camera
}
/// The current camera.
pub fn set_camera(&mut self, camera: &'a mut Camera) {
let (w, h) = self.window.get_size();
self.camera = camera;
self.camera.handle_event(&self.window, &event::FramebufferSize(w as f32, h as f32));
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Closes the window.
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
pub fn show(&mut self) {
self.window.show()
}
/// Switch on or off wireframe rendering mode. When set to `true`, everything in the scene will
/// be drawn using wireframes. Wireframe rendering mode cannot be enabled on a per-object basis.
pub fn set_wireframe_mode(&mut self, mode: bool) {
self.wireframe_mode = mode;
}
/// Sets the background color.
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
/// Adds a line to be drawn during the next frame.
pub fn draw_line(&mut self, a: &Vec3<f32>, b: &Vec3<f32>, color: &Vec3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
/// Adds a string to be drawn during the next frame.
pub fn draw_text(&mut self, text: &str, pos: &Vec2<f32>, font: &Rc<Font>, color: &Vec3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, o: Object) {
match self.objects.iter().rposition(|e| o == *e) {
Some(i) => {
let _ = self.objects.swap_remove(i);
},
None => { }
}
}
/// Loads a mesh from an obj file located at `path` and registers its geometry as
/// `geometry_name`.
pub fn load_obj(&mut self, path: &Path, mtl_dir: &Path, geometry_name: &str) -> ~[(~str, Rc<RefCell<Mesh>>, Option<MtlMaterial>)] {
let ms = obj::parse_file(path, mtl_dir, geometry_name).expect("Unable to parse the obj file: " + path.as_str().unwrap());
let mut res = ~[];
for (n, m, mat) in ms.move_iter() {
let m = Rc::new(RefCell::new(m));
self.geometries.insert(geometry_name.to_owned(), m.clone());
res.push((n, m, mat));
}
res
}
/// Gets the geometry named `geometry_name` if it has been already registered.
pub fn get_mesh(&mut self, geometry_name: &str) -> Option<Rc<RefCell<Mesh>>> {
self.geometries.find(&geometry_name.to_owned()).map(|m| m.clone())
}
/// Registers the geometry `mesh` with the name `geometry_name`.
pub fn register_mesh(&mut self, geometry_name: &str, mesh: Mesh) {
self.geometries.insert(geometry_name.to_owned(), Rc::new(RefCell::new(mesh)));
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - uniform scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: GLfloat) -> ~[Object] {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let objs = self.load_obj(path, mtl_dir, path.as_str().unwrap());
println!("Parsing complete.");
let mut res = ~[];
for (_, mesh, mtl) in objs.move_iter() {
let mut object = Object::new(
mesh,
1.0, 1.0, 1.0,
tex.clone(),
scale, scale, scale,
self.object_material.clone()
);
match mtl {
None => { },
Some(mtl) => {
object.set_color(mtl.diffuse.x, mtl.diffuse.y, mtl.diffuse.z);
for t in mtl.diffuse_texture.iter() {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
}
for t in mtl.ambiant_texture.iter() {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
}
}
}
res.push(object.clone());
self.objects.push(object);
}
res
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Mesh, scale: GLfloat) -> Object {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let res = Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add(&mut self, geometry_name: &str, scale: GLfloat) -> Option<Object> {
self.geometries.find(&geometry_name.to_owned()).map(|m| {
let res = Object::new(
m.clone(),
1.0, 1.0, 1.0,
TextureManager::get_global_manager(|tm| tm.get_default()),
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
})
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cube").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
wx, wy, wz,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"sphere").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, r / 0.5, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cone").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cylinder").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"capsule").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a double-sided quad to the scene. The cylinder is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width
/// * `h` - the quad height
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, wsubdivs: uint, hsubdivs: uint) -> Object {
assert!(wsubdivs > 0 && hsubdivs > 0, "The number of subdivisions cannot be zero");
let wstep = w / (wsubdivs as GLfloat);
let hstep = h / (hsubdivs as GLfloat);
let wtexstep = 1.0 / (wsubdivs as GLfloat);
let htexstep = 1.0 / (hsubdivs as GLfloat);
let cw = w / 2.0;
let ch = h / 2.0;
let mut vertices = ~[];
let mut normals = ~[];
let mut triangles = ~[];
let mut tex_coords = ~[];
// create the vertices
for i in range(0u, hsubdivs + 1) {
for j in range(0u, wsubdivs + 1) {
vertices.push(Vec3::new(j as GLfloat * wstep - cw, i as GLfloat * hstep - ch, 0.0));
tex_coords.push(Vec2::new(1.0 - j as GLfloat * wtexstep, 1.0 - i as GLfloat * htexstep))
}
}
// create the normals
for _ in range(0, (hsubdivs + 1) * (wsubdivs + 1)) {
{ normals.push(Vec3::new(1.0, 0.0, 0.0)) }
}
// create triangles
fn dl_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new((i + 1) * ws + j, i * ws + j, (i + 1) * ws + j + 1)
}
fn ur_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new(i * ws + j, i * ws + (j + 1), (i + 1) * ws + j + 1)
}
for i in range(0u, hsubdivs) {
for j in range(0u, wsubdivs) {
// build two triangles...
triangles.push(dl_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
triangles.push(ur_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
}
}
let mesh = Mesh::new(vertices, triangles, Some(normals), Some(tex_coords), true);
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
1.0, 1.0, 1.0,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Converts a 3d point to 2d screen coordinates.
pub fn project(&self, world_coord: &Vec3<f32>) -> Vec2<f32> {
let h_world_coord = na::to_homogeneous(world_coord);
let h_normalized_coord = self.camera.transformation() * h_world_coord;
let normalized_coord: Vec3<f32> = na::from_homogeneous(&h_normalized_coord);
let (w, h) = self.window.get_size();
Vec2::new(
(1.0 + normalized_coord.x) * (w as f32) / 2.0,
(1.0 + normalized_coord.y) * (h as f32) / 2.0)
}
/// Converts a point in 2d screen coordinates to a ray (a 3d position and a direction).
pub fn unproject(&self, window_coord: &Vec2<f32>) -> (Vec3<f32>, Vec3<f32>) {
let (w, h) = self.window.get_size();
let normalized_coord = Vec2::new(
2.0 * window_coord.x / (w as f32) - 1.0,
2.0 * -window_coord.y / (h as f32) + 1.0);
let normalized_begin = Vec4::new(normalized_coord.x, normalized_coord.y, -1.0, 1.0);
let normalized_end = Vec4::new(normalized_coord.x, normalized_coord.y, 1.0, 1.0);
let cam = self.camera.inv_transformation();
let h_unprojected_begin = cam * normalized_begin;
let h_unprojected_end = cam * normalized_end;
let unprojected_begin: Vec3<f32> = na::from_homogeneous(&h_unprojected_begin);
let unprojected_end: Vec3<f32> = na::from_homogeneous(&h_unprojected_end);
(unprojected_begin, na::normalize(&(unprojected_end - unprojected_begin)))
}
/// The list of objects on the scene.
pub fn objects<'r>(&'r self) -> &'r [Object] {
let res: &'r [Object] = self.objects;
res
}
/// The list of objects on the scene.
pub fn objects_mut<'r>(&'r mut self) -> &'r mut [Object] {
let res: &'r mut [Object] = self.objects;
res
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline(always)]
pub fn poll_events(&mut self, events_handler: |&mut Window, &event::Event| -> bool) {
// redispatch them
let events = self.events.clone();
events.read(|es| {
for e in es.iter() {
if events_handler(self, e) {
match *e {
event::KeyReleased(key) => {
if key == glfw::KeyEscape {
self.close();
continue
}
},
event::FramebufferSize(w, h) => {
self.update_viewport(w, h);
},
_ => { }
}
self.camera.handle_event(&self.window, e);
}
}
});
// clear the events collector
self.events.write(|c| c.clear());
}
/// Starts an infinite loop polling events, calling an user-defined callback, and drawing the
/// scene.
pub fn render_loop(&mut self, callback: |&mut Window| -> ()) {
let mut timer = Timer::new().unwrap();
let mut curr = time::precise_time_ns();
while !self.window.should_close() {
// collect events
glfw::poll_events();
callback(self);
self.poll_events(|_, _| true);
self.draw(&mut curr, &mut timer)
}
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
// FIXME /// The camera used to render the scene.
// FIXME pub fn camera(&self) -> &Camera {
// FIXME self.camera.clone()
// FIXME }
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_hidden(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), true, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_size(title: &str, width: u32, height: u32, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, width, height, callback)
}
fn do_spawn(title: ~str, hide: bool, width: u32, height: u32, callback: proc(&mut Window)) {
glfw::set_error_callback(~ErrorCallback);
glfw::start(proc() {
let window = glfw::Window::create(width, height, title, glfw::Windowed).expect("Unable to open a glfw window.");
window.make_context_current();
verify!(gl::load_with(glfw::get_proc_address));
init_gl();
let builtins = loader::load();
let mut camera = ArcBall::new(-Vec3::z(), Zero::zero());
let mut usr_window = Window {
max_ms_per_frame: None,
window: window,
objects: ~[],
camera: &mut camera as &mut Camera,
light_mode: Absolute(Vec3::new(0.0, 10.0, 0.0)),
wireframe_mode: false,
geometries: builtins,
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
text_renderer: TextRenderer::new(),
post_processing: None,
post_process_render_target: FramebufferManager::new_render_target(width as uint, height as uint),
framebuffer_manager: FramebufferManager::new(),
events: RWArc::new(~[]),
object_material: Rc::new(RefCell::new(~ObjectMaterial::new() as ~Material))
};
// setup callbacks
let collector = usr_window.events.clone();
usr_window.window.set_framebuffer_size_callback(~FramebufferSizeCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_key_callback(~KeyCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_mouse_button_callback(~MouseButtonCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_cursor_pos_callback(~CursorPosCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_scroll_callback(~ScrollCallback::new(collector));
let (w, h) = usr_window.window.get_size();
usr_window.camera.handle_event(
&usr_window.window,
&event::FramebufferSize(w as f32, h as f32));
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
usr_window.set_light(usr_window.light_mode);
callback(&mut usr_window);
})
}
fn draw(&mut self, curr: &mut u64, timer: &mut Timer) {
self.camera.update(&self.window);
match self.light_mode {
StickToCamera => self.set_light(StickToCamera),
_ => { }
}
if self.post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in range(0u, self.camera.num_passes()) {
self.camera.start_pass(pass, &self.window);
self.render_scene(pass);
}
self.camera.render_complete(&self.window);
let w = self.width();
let h = self.height();
let (znear, zfar) = self.camera.clip_planes();
match self.post_processing {
Some(ref mut p) => {
// remove the wireframe mode
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - *curr) / 1000000;
if elapsed < ms {
timer.sleep(ms - elapsed);
}
}
}
*curr = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
}
fn render_scene(&mut self, pass: uint) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, self.camera);
}
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE));
}
else {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
for o in self.objects.iter() {
o.render(pass, self.camera, &self.light_mode)
}
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0 as i32, 0 as i32, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
}
//
// Cursor Pos Callback
//
struct ScrollCallback {
collector: RWArc<~[event::Event]>
}
impl ScrollCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> ScrollCallback {
ScrollCallback {
collector: collector
}
}
}
impl glfw::ScrollCallback for ScrollCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::Scroll(x as f32, y as f32)))
}
}
//
// Cursor Pos Callback
//
struct CursorPosCallback {
collector: RWArc<~[event::Event]>
}
impl CursorPosCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> CursorPosCallback {
CursorPosCallback {
collector: collector
}
}
}
impl glfw::CursorPosCallback for CursorPosCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::CursorPos(x as f32, y as f32)))
}
}
//
// Mouse Button Callback
//
struct MouseButtonCallback {
collector: RWArc<~[event::Event]>
}
impl MouseButtonCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> MouseButtonCallback {
MouseButtonCallback {
collector: collector
}
}
}
impl glfw::MouseButtonCallback for MouseButtonCallback {
fn call(&self,
_: &glfw::Window,
button: glfw::MouseButton,
action: glfw::Action,
mods: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::ButtonPressed(button, mods)))
}
else {
self.collector.write(|c| c.push(event::ButtonReleased(button, mods)))
}
}
}
//
// Key callback
//
struct KeyCallback {
collector: RWArc<~[event::Event]>
}
impl KeyCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> KeyCallback {
KeyCallback {
collector: collector
}
}
}
impl glfw::KeyCallback for KeyCallback {
fn call(&self,
_: &glfw::Window,
key: glfw::Key,
_: libc::c_int,
action: glfw::Action,
_: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::KeyPressed(key)))
}
else {
self.collector.write(|c| c.push(event::KeyReleased(key)))
}
}
}
//
// Framebuffer callback
//
struct FramebufferSizeCallback {
collector: RWArc<~[event::Event]>
}
impl FramebufferSizeCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> FramebufferSizeCallback {
FramebufferSizeCallback {
collector: collector
}
}
}
impl glfw::FramebufferSizeCallback for FramebufferSizeCallback {
fn call(&self, _: &glfw::Window, w: i32, h: i32) {
self.collector.write(|c| c.push(event::FramebufferSize(w as f32, h as f32)))
}
}
//
// Error callback
//
struct ErrorCallback;
impl glfw::ErrorCallback for ErrorCallback {
fn call(&self, _: glfw::Error, description: ~str) {
println!("Kiss3d Error: {}", description);
}
}
Deactivate the wireframe mode before text rendering.
//! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use glfw;
use std::libc;
use std::io::timer::Timer;
use std::num::Zero;
use std::hashmap::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use extra::time;
use extra::arc::RWArc;
use gl;
use gl::types::*;
use stb_image::image::*;
use nalgebra::na::{Vec2, Vec3, Vec4};
use nalgebra::na;
use camera::{Camera, ArcBall};
use object::Object;
use line_renderer::LineRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use builtin::ObjectMaterial;
use builtin::loader;
use event;
use loader::obj;
use loader::mtl::MtlMaterial;
use light::{Light, Absolute, StickToCamera};
use text::{TextRenderer, Font};
mod error;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window<'a> {
priv window: glfw::Window,
priv max_ms_per_frame: Option<u64>,
priv objects: ~[Object],
priv camera: &'a mut Camera,
priv light_mode: Light,
priv wireframe_mode: bool,
priv geometries: HashMap<~str, Rc<RefCell<Mesh>>>,
priv background: Vec3<GLfloat>,
priv line_renderer: LineRenderer,
priv text_renderer: TextRenderer,
priv framebuffer_manager: FramebufferManager,
priv post_processing: Option<&'a mut PostProcessingEffect>,
priv post_process_render_target: RenderTarget,
priv events: RWArc<~[event::Event]>,
priv object_material: Rc<RefCell<~Material>>
}
impl<'a> Window<'a> {
/// Access the glfw window.
pub fn glfw_window<'r>(&'r self) -> &'r glfw::Window {
&self.window
}
/// Sets the current processing effect.
pub fn set_post_processing_effect(&mut self, effect: Option<&'a mut PostProcessingEffect>) {
self.post_processing = effect;
}
/// The window width.
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The current camera.
pub fn camera<'b>(&'b self) -> &'b &'a mut Camera {
&'b self.camera
}
/// The current camera.
pub fn set_camera(&mut self, camera: &'a mut Camera) {
let (w, h) = self.window.get_size();
self.camera = camera;
self.camera.handle_event(&self.window, &event::FramebufferSize(w as f32, h as f32));
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Closes the window.
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
pub fn show(&mut self) {
self.window.show()
}
/// Switch on or off wireframe rendering mode. When set to `true`, everything in the scene will
/// be drawn using wireframes. Wireframe rendering mode cannot be enabled on a per-object basis.
pub fn set_wireframe_mode(&mut self, mode: bool) {
self.wireframe_mode = mode;
}
/// Sets the background color.
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
/// Adds a line to be drawn during the next frame.
pub fn draw_line(&mut self, a: &Vec3<f32>, b: &Vec3<f32>, color: &Vec3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
/// Adds a string to be drawn during the next frame.
pub fn draw_text(&mut self, text: &str, pos: &Vec2<f32>, font: &Rc<Font>, color: &Vec3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
/// Removes an object from the scene.
pub fn remove(&mut self, o: Object) {
match self.objects.iter().rposition(|e| o == *e) {
Some(i) => {
let _ = self.objects.swap_remove(i);
},
None => { }
}
}
/// Loads a mesh from an obj file located at `path` and registers its geometry as
/// `geometry_name`.
pub fn load_obj(&mut self, path: &Path, mtl_dir: &Path, geometry_name: &str) -> ~[(~str, Rc<RefCell<Mesh>>, Option<MtlMaterial>)] {
let ms = obj::parse_file(path, mtl_dir, geometry_name).expect("Unable to parse the obj file: " + path.as_str().unwrap());
let mut res = ~[];
for (n, m, mat) in ms.move_iter() {
let m = Rc::new(RefCell::new(m));
self.geometries.insert(geometry_name.to_owned(), m.clone());
res.push((n, m, mat));
}
res
}
/// Gets the geometry named `geometry_name` if it has been already registered.
pub fn get_mesh(&mut self, geometry_name: &str) -> Option<Rc<RefCell<Mesh>>> {
self.geometries.find(&geometry_name.to_owned()).map(|m| m.clone())
}
/// Registers the geometry `mesh` with the name `geometry_name`.
pub fn register_mesh(&mut self, geometry_name: &str, mesh: Mesh) {
self.geometries.insert(geometry_name.to_owned(), Rc::new(RefCell::new(mesh)));
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - uniform scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: GLfloat) -> ~[Object] {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let objs = self.load_obj(path, mtl_dir, path.as_str().unwrap());
println!("Parsing complete.");
let mut res = ~[];
for (_, mesh, mtl) in objs.move_iter() {
let mut object = Object::new(
mesh,
1.0, 1.0, 1.0,
tex.clone(),
scale, scale, scale,
self.object_material.clone()
);
match mtl {
None => { },
Some(mtl) => {
object.set_color(mtl.diffuse.x, mtl.diffuse.y, mtl.diffuse.z);
for t in mtl.diffuse_texture.iter() {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
}
for t in mtl.ambiant_texture.iter() {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
}
}
}
res.push(object.clone());
self.objects.push(object);
}
res
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Mesh, scale: GLfloat) -> Object {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let res = Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add(&mut self, geometry_name: &str, scale: GLfloat) -> Option<Object> {
self.geometries.find(&geometry_name.to_owned()).map(|m| {
let res = Object::new(
m.clone(),
1.0, 1.0, 1.0,
TextureManager::get_global_manager(|tm| tm.get_default()),
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
})
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cube").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
wx, wy, wz,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"sphere").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, r / 0.5, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cone").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cylinder").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"capsule").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a double-sided quad to the scene. The cylinder is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width
/// * `h` - the quad height
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, wsubdivs: uint, hsubdivs: uint) -> Object {
assert!(wsubdivs > 0 && hsubdivs > 0, "The number of subdivisions cannot be zero");
let wstep = w / (wsubdivs as GLfloat);
let hstep = h / (hsubdivs as GLfloat);
let wtexstep = 1.0 / (wsubdivs as GLfloat);
let htexstep = 1.0 / (hsubdivs as GLfloat);
let cw = w / 2.0;
let ch = h / 2.0;
let mut vertices = ~[];
let mut normals = ~[];
let mut triangles = ~[];
let mut tex_coords = ~[];
// create the vertices
for i in range(0u, hsubdivs + 1) {
for j in range(0u, wsubdivs + 1) {
vertices.push(Vec3::new(j as GLfloat * wstep - cw, i as GLfloat * hstep - ch, 0.0));
tex_coords.push(Vec2::new(1.0 - j as GLfloat * wtexstep, 1.0 - i as GLfloat * htexstep))
}
}
// create the normals
for _ in range(0, (hsubdivs + 1) * (wsubdivs + 1)) {
{ normals.push(Vec3::new(1.0, 0.0, 0.0)) }
}
// create triangles
fn dl_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new((i + 1) * ws + j, i * ws + j, (i + 1) * ws + j + 1)
}
fn ur_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new(i * ws + j, i * ws + (j + 1), (i + 1) * ws + j + 1)
}
for i in range(0u, hsubdivs) {
for j in range(0u, wsubdivs) {
// build two triangles...
triangles.push(dl_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
triangles.push(ur_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
}
}
let mesh = Mesh::new(vertices, triangles, Some(normals), Some(tex_coords), true);
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
1.0, 1.0, 1.0,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Converts a 3d point to 2d screen coordinates.
pub fn project(&self, world_coord: &Vec3<f32>) -> Vec2<f32> {
let h_world_coord = na::to_homogeneous(world_coord);
let h_normalized_coord = self.camera.transformation() * h_world_coord;
let normalized_coord: Vec3<f32> = na::from_homogeneous(&h_normalized_coord);
let (w, h) = self.window.get_size();
Vec2::new(
(1.0 + normalized_coord.x) * (w as f32) / 2.0,
(1.0 + normalized_coord.y) * (h as f32) / 2.0)
}
/// Converts a point in 2d screen coordinates to a ray (a 3d position and a direction).
pub fn unproject(&self, window_coord: &Vec2<f32>) -> (Vec3<f32>, Vec3<f32>) {
let (w, h) = self.window.get_size();
let normalized_coord = Vec2::new(
2.0 * window_coord.x / (w as f32) - 1.0,
2.0 * -window_coord.y / (h as f32) + 1.0);
let normalized_begin = Vec4::new(normalized_coord.x, normalized_coord.y, -1.0, 1.0);
let normalized_end = Vec4::new(normalized_coord.x, normalized_coord.y, 1.0, 1.0);
let cam = self.camera.inv_transformation();
let h_unprojected_begin = cam * normalized_begin;
let h_unprojected_end = cam * normalized_end;
let unprojected_begin: Vec3<f32> = na::from_homogeneous(&h_unprojected_begin);
let unprojected_end: Vec3<f32> = na::from_homogeneous(&h_unprojected_end);
(unprojected_begin, na::normalize(&(unprojected_end - unprojected_begin)))
}
/// The list of objects on the scene.
pub fn objects<'r>(&'r self) -> &'r [Object] {
let res: &'r [Object] = self.objects;
res
}
/// The list of objects on the scene.
pub fn objects_mut<'r>(&'r mut self) -> &'r mut [Object] {
let res: &'r mut [Object] = self.objects;
res
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline(always)]
pub fn poll_events(&mut self, events_handler: |&mut Window, &event::Event| -> bool) {
// redispatch them
let events = self.events.clone();
events.read(|es| {
for e in es.iter() {
if events_handler(self, e) {
match *e {
event::KeyReleased(key) => {
if key == glfw::KeyEscape {
self.close();
continue
}
},
event::FramebufferSize(w, h) => {
self.update_viewport(w, h);
},
_ => { }
}
self.camera.handle_event(&self.window, e);
}
}
});
// clear the events collector
self.events.write(|c| c.clear());
}
/// Starts an infinite loop polling events, calling an user-defined callback, and drawing the
/// scene.
pub fn render_loop(&mut self, callback: |&mut Window| -> ()) {
let mut timer = Timer::new().unwrap();
let mut curr = time::precise_time_ns();
while !self.window.should_close() {
// collect events
glfw::poll_events();
callback(self);
self.poll_events(|_, _| true);
self.draw(&mut curr, &mut timer)
}
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
// FIXME /// The camera used to render the scene.
// FIXME pub fn camera(&self) -> &Camera {
// FIXME self.camera.clone()
// FIXME }
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_hidden(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), true, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_size(title: &str, width: u32, height: u32, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, width, height, callback)
}
fn do_spawn(title: ~str, hide: bool, width: u32, height: u32, callback: proc(&mut Window)) {
glfw::set_error_callback(~ErrorCallback);
glfw::start(proc() {
let window = glfw::Window::create(width, height, title, glfw::Windowed).expect("Unable to open a glfw window.");
window.make_context_current();
verify!(gl::load_with(glfw::get_proc_address));
init_gl();
let builtins = loader::load();
let mut camera = ArcBall::new(-Vec3::z(), Zero::zero());
let mut usr_window = Window {
max_ms_per_frame: None,
window: window,
objects: ~[],
camera: &mut camera as &mut Camera,
light_mode: Absolute(Vec3::new(0.0, 10.0, 0.0)),
wireframe_mode: false,
geometries: builtins,
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
text_renderer: TextRenderer::new(),
post_processing: None,
post_process_render_target: FramebufferManager::new_render_target(width as uint, height as uint),
framebuffer_manager: FramebufferManager::new(),
events: RWArc::new(~[]),
object_material: Rc::new(RefCell::new(~ObjectMaterial::new() as ~Material))
};
// setup callbacks
let collector = usr_window.events.clone();
usr_window.window.set_framebuffer_size_callback(~FramebufferSizeCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_key_callback(~KeyCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_mouse_button_callback(~MouseButtonCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_cursor_pos_callback(~CursorPosCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_scroll_callback(~ScrollCallback::new(collector));
let (w, h) = usr_window.window.get_size();
usr_window.camera.handle_event(
&usr_window.window,
&event::FramebufferSize(w as f32, h as f32));
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
usr_window.set_light(usr_window.light_mode);
callback(&mut usr_window);
})
}
fn draw(&mut self, curr: &mut u64, timer: &mut Timer) {
self.camera.update(&self.window);
match self.light_mode {
StickToCamera => self.set_light(StickToCamera),
_ => { }
}
if self.post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in range(0u, self.camera.num_passes()) {
self.camera.start_pass(pass, &self.window);
self.render_scene(pass);
}
self.camera.render_complete(&self.window);
let w = self.width();
let h = self.height();
let (znear, zfar) = self.camera.clip_planes();
// swatch off the wireframe mode for post processing and text rendering.
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
match self.post_processing {
Some(ref mut p) => {
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - *curr) / 1000000;
if elapsed < ms {
timer.sleep(ms - elapsed);
}
}
}
*curr = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
}
fn render_scene(&mut self, pass: uint) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, self.camera);
}
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE));
}
else {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
for o in self.objects.iter() {
o.render(pass, self.camera, &self.light_mode)
}
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0 as i32, 0 as i32, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
}
//
// Cursor Pos Callback
//
struct ScrollCallback {
collector: RWArc<~[event::Event]>
}
impl ScrollCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> ScrollCallback {
ScrollCallback {
collector: collector
}
}
}
impl glfw::ScrollCallback for ScrollCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::Scroll(x as f32, y as f32)))
}
}
//
// Cursor Pos Callback
//
struct CursorPosCallback {
collector: RWArc<~[event::Event]>
}
impl CursorPosCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> CursorPosCallback {
CursorPosCallback {
collector: collector
}
}
}
impl glfw::CursorPosCallback for CursorPosCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::CursorPos(x as f32, y as f32)))
}
}
//
// Mouse Button Callback
//
struct MouseButtonCallback {
collector: RWArc<~[event::Event]>
}
impl MouseButtonCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> MouseButtonCallback {
MouseButtonCallback {
collector: collector
}
}
}
impl glfw::MouseButtonCallback for MouseButtonCallback {
fn call(&self,
_: &glfw::Window,
button: glfw::MouseButton,
action: glfw::Action,
mods: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::ButtonPressed(button, mods)))
}
else {
self.collector.write(|c| c.push(event::ButtonReleased(button, mods)))
}
}
}
//
// Key callback
//
struct KeyCallback {
collector: RWArc<~[event::Event]>
}
impl KeyCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> KeyCallback {
KeyCallback {
collector: collector
}
}
}
impl glfw::KeyCallback for KeyCallback {
fn call(&self,
_: &glfw::Window,
key: glfw::Key,
_: libc::c_int,
action: glfw::Action,
_: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::KeyPressed(key)))
}
else {
self.collector.write(|c| c.push(event::KeyReleased(key)))
}
}
}
//
// Framebuffer callback
//
struct FramebufferSizeCallback {
collector: RWArc<~[event::Event]>
}
impl FramebufferSizeCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> FramebufferSizeCallback {
FramebufferSizeCallback {
collector: collector
}
}
}
impl glfw::FramebufferSizeCallback for FramebufferSizeCallback {
fn call(&self, _: &glfw::Window, w: i32, h: i32) {
self.collector.write(|c| c.push(event::FramebufferSize(w as f32, h as f32)))
}
}
//
// Error callback
//
struct ErrorCallback;
impl glfw::ErrorCallback for ErrorCallback {
fn call(&self, _: glfw::Error, description: ~str) {
println!("Kiss3d Error: {}", description);
}
}
|
//! The nannou [**Window**](./struct.Window.html) API. Create a new window via `.app.new_window()`.
//! This produces a [**Builder**](./struct.Builder.html) which can be used to build a window.
use crate::event::{
Key, MouseButton, MouseScrollDelta, TouchEvent, TouchPhase, TouchpadPressure, WindowEvent,
};
use crate::frame::{self, Frame, RawFrame};
use crate::geom;
use crate::geom::{Point2, Vector2};
use crate::wgpu;
use crate::App;
use std::any::Any;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fmt};
use winit::dpi::LogicalSize;
pub use winit::window::WindowId as Id;
/// The default dimensions used for a window in the case that none are specified.
pub const DEFAULT_DIMENSIONS: LogicalSize<geom::scalar::Default> = LogicalSize {
width: 1024.0,
height: 768.0,
};
/// A context for building a window.
pub struct Builder<'app> {
app: &'app App,
window: winit::window::WindowBuilder,
title_was_set: bool,
swap_chain_builder: SwapChainBuilder,
request_adapter_opts: Option<wgpu::RequestAdapterOptions>,
device_desc: Option<wgpu::DeviceDescriptor>,
user_functions: UserFunctions,
msaa_samples: Option<u32>,
}
/// For storing all user functions within the window.
#[derive(Debug, Default)]
pub(crate) struct UserFunctions {
pub(crate) view: Option<View>,
pub(crate) event: Option<EventFnAny>,
pub(crate) raw_event: Option<RawEventFnAny>,
pub(crate) key_pressed: Option<KeyPressedFnAny>,
pub(crate) key_released: Option<KeyReleasedFnAny>,
pub(crate) mouse_moved: Option<MouseMovedFnAny>,
pub(crate) mouse_pressed: Option<MousePressedFnAny>,
pub(crate) mouse_released: Option<MouseReleasedFnAny>,
pub(crate) mouse_entered: Option<MouseEnteredFnAny>,
pub(crate) mouse_exited: Option<MouseExitedFnAny>,
pub(crate) mouse_wheel: Option<MouseWheelFnAny>,
pub(crate) moved: Option<MovedFnAny>,
pub(crate) resized: Option<ResizedFnAny>,
pub(crate) touch: Option<TouchFnAny>,
pub(crate) touchpad_pressure: Option<TouchpadPressureFnAny>,
pub(crate) hovered_file: Option<HoveredFileFnAny>,
pub(crate) hovered_file_cancelled: Option<HoveredFileCancelledFnAny>,
pub(crate) dropped_file: Option<DroppedFileFnAny>,
pub(crate) focused: Option<FocusedFnAny>,
pub(crate) unfocused: Option<UnfocusedFnAny>,
pub(crate) closed: Option<ClosedFnAny>,
}
/// The user function type for drawing their model to the surface of a single window.
pub type ViewFn<Model> = fn(&App, &Model, Frame);
/// The user function type for drawing their model to the surface of a single window.
///
/// Unlike the `ViewFn`, the `RawViewFn` is designed for drawing directly to a window's swap chain
/// images rather than to a convenient intermediary image.
pub type RawViewFn<Model> = fn(&App, &Model, RawFrame);
/// The same as `ViewFn`, but provides no user model to draw from.
///
/// Useful for simple, stateless sketching.
pub type SketchFn = fn(&App, Frame);
/// The user's view function, whether with a model or without one.
#[derive(Clone)]
pub(crate) enum View {
WithModel(ViewFnAny),
WithModelRaw(RawViewFnAny),
Sketch(SketchFn),
}
/// A function for processing raw winit window events.
pub type RawEventFn<Model> = fn(&App, &mut Model, &winit::event::WindowEvent);
/// A function for processing window events.
pub type EventFn<Model> = fn(&App, &mut Model, WindowEvent);
/// A function for processing key press events.
pub type KeyPressedFn<Model> = fn(&App, &mut Model, Key);
/// A function for processing key release events.
pub type KeyReleasedFn<Model> = fn(&App, &mut Model, Key);
/// A function for processing mouse moved events.
pub type MouseMovedFn<Model> = fn(&App, &mut Model, Point2);
/// A function for processing mouse pressed events.
pub type MousePressedFn<Model> = fn(&App, &mut Model, MouseButton);
/// A function for processing mouse released events.
pub type MouseReleasedFn<Model> = fn(&App, &mut Model, MouseButton);
/// A function for processing mouse entered events.
pub type MouseEnteredFn<Model> = fn(&App, &mut Model);
/// A function for processing mouse exited events.
pub type MouseExitedFn<Model> = fn(&App, &mut Model);
/// A function for processing mouse wheel events.
pub type MouseWheelFn<Model> = fn(&App, &mut Model, MouseScrollDelta, TouchPhase);
/// A function for processing window moved events.
pub type MovedFn<Model> = fn(&App, &mut Model, Vector2);
/// A function for processing window resized events.
pub type ResizedFn<Model> = fn(&App, &mut Model, Vector2);
/// A function for processing touch events.
pub type TouchFn<Model> = fn(&App, &mut Model, TouchEvent);
/// A function for processing touchpad pressure events.
pub type TouchpadPressureFn<Model> = fn(&App, &mut Model, TouchpadPressure);
/// A function for processing hovered file events.
pub type HoveredFileFn<Model> = fn(&App, &mut Model, PathBuf);
/// A function for processing hovered file cancelled events.
pub type HoveredFileCancelledFn<Model> = fn(&App, &mut Model);
/// A function for processing dropped file events.
pub type DroppedFileFn<Model> = fn(&App, &mut Model, PathBuf);
/// A function for processing window focused events.
pub type FocusedFn<Model> = fn(&App, &mut Model);
/// A function for processing window unfocused events.
pub type UnfocusedFn<Model> = fn(&App, &mut Model);
/// A function for processing window closed events.
pub type ClosedFn<Model> = fn(&App, &mut Model);
/// Errors that might occur while building the window.
#[derive(Debug)]
pub enum BuildError {
NoAvailableAdapter,
WinitOsError(winit::error::OsError),
}
// A macro for generating a handle to a function that can be stored within the Window without
// requiring a type param. $TFn is the function pointer type that will be wrapped by $TFnAny.
macro_rules! fn_any {
($TFn:ident<M>, $TFnAny:ident) => {
// A handle to a function that can be stored without requiring a type param.
#[derive(Clone)]
pub(crate) struct $TFnAny {
fn_ptr: Arc<dyn Any>,
}
impl $TFnAny {
// Create the `$TFnAny` from a view function pointer.
pub fn from_fn_ptr<M>(fn_ptr: $TFn<M>) -> Self
where
M: 'static,
{
let fn_ptr = Arc::new(fn_ptr) as Arc<dyn Any>;
$TFnAny { fn_ptr }
}
// Retrieve the view function pointer from the `$TFnAny`.
pub fn to_fn_ptr<M>(&self) -> Option<&$TFn<M>>
where
M: 'static,
{
self.fn_ptr.downcast_ref::<$TFn<M>>()
}
}
impl fmt::Debug for $TFnAny {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", stringify!($TFnAny))
}
}
};
}
fn_any!(ViewFn<M>, ViewFnAny);
fn_any!(RawViewFn<M>, RawViewFnAny);
fn_any!(EventFn<M>, EventFnAny);
fn_any!(RawEventFn<M>, RawEventFnAny);
fn_any!(KeyPressedFn<M>, KeyPressedFnAny);
fn_any!(KeyReleasedFn<M>, KeyReleasedFnAny);
fn_any!(MouseMovedFn<M>, MouseMovedFnAny);
fn_any!(MousePressedFn<M>, MousePressedFnAny);
fn_any!(MouseReleasedFn<M>, MouseReleasedFnAny);
fn_any!(MouseEnteredFn<M>, MouseEnteredFnAny);
fn_any!(MouseExitedFn<M>, MouseExitedFnAny);
fn_any!(MouseWheelFn<M>, MouseWheelFnAny);
fn_any!(MovedFn<M>, MovedFnAny);
fn_any!(ResizedFn<M>, ResizedFnAny);
fn_any!(TouchFn<M>, TouchFnAny);
fn_any!(TouchpadPressureFn<M>, TouchpadPressureFnAny);
fn_any!(HoveredFileFn<M>, HoveredFileFnAny);
fn_any!(HoveredFileCancelledFn<M>, HoveredFileCancelledFnAny);
fn_any!(DroppedFileFn<M>, DroppedFileFnAny);
fn_any!(FocusedFn<M>, FocusedFnAny);
fn_any!(UnfocusedFn<M>, UnfocusedFnAny);
fn_any!(ClosedFn<M>, ClosedFnAny);
/// A nannou window.
///
/// The **Window** acts as a wrapper around the `winit::window::Window` and the `wgpu::Surface`
/// types. It also manages the associated swap chain, providing a more nannou-friendly API.
#[derive(Debug)]
pub struct Window {
pub(crate) window: winit::window::Window,
pub(crate) surface: wgpu::Surface,
pub(crate) device_queue_pair: Arc<wgpu::DeviceQueuePair>,
msaa_samples: u32,
pub(crate) swap_chain: WindowSwapChain,
pub(crate) frame_data: Option<FrameData>,
pub(crate) frame_count: u64,
pub(crate) user_functions: UserFunctions,
pub(crate) tracked_state: TrackedState,
}
// Data related to `Frame`s produced for this window's swapchain textures.
#[derive(Debug)]
pub(crate) struct FrameData {
// Data for rendering a `Frame`'s intermediary image to a swap chain image.
pub(crate) render: frame::RenderData,
// Data for capturing a `Frame`'s intermediary image before submission.
pub(crate) capture: frame::CaptureData,
}
// Track and store some information about the window in order to avoid making repeated internal
// queries to the platform-specific API. This is beneficial in some cases where queries to the
// platform-specific API can be very slow (e.g. macOS cocoa).
#[derive(Debug)]
pub(crate) struct TrackedState {
// Updated on `ScaleFactorChanged`.
pub(crate) scale_factor: f64,
// Updated on `Resized`.
pub(crate) physical_size: winit::dpi::PhysicalSize<u32>,
}
/// A swap_chain and its images associated with a single window.
pub(crate) struct WindowSwapChain {
// The descriptor used to create the original swap chain. Useful for recreation.
pub(crate) descriptor: wgpu::SwapChainDescriptor,
// This is an `Option` in order to allow for separating ownership of the swapchain from the
// window during a `RedrawRequest`. Other than during `RedrawRequest`, this should always be
// `Some`.
pub(crate) swap_chain: Option<wgpu::SwapChain>,
}
/// SwapChain building parameters for which Nannou will provide a default if unspecified.
///
/// See the builder methods for more details on each parameter.
#[derive(Clone, Debug, Default)]
pub struct SwapChainBuilder {
pub usage: Option<wgpu::TextureUsage>,
pub format: Option<wgpu::TextureFormat>,
pub present_mode: Option<wgpu::PresentMode>,
}
impl SwapChainBuilder {
pub const DEFAULT_USAGE: wgpu::TextureUsage = wgpu::TextureUsage::OUTPUT_ATTACHMENT;
pub const DEFAULT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
pub const DEFAULT_PRESENT_MODE: wgpu::PresentMode = wgpu::PresentMode::Vsync;
/// A new empty **SwapChainBuilder** with all parameters set to `None`.
pub fn new() -> Self {
Default::default()
}
/// Create a **SwapChainBuilder** from an existing descriptor.
///
/// The resulting swap chain parameters will match that of the given `SwapChainDescriptor`.
pub fn from_descriptor(desc: &wgpu::SwapChainDescriptor) -> Self {
SwapChainBuilder::new()
.usage(desc.usage)
.format(desc.format)
.present_mode(desc.present_mode)
}
/// Specify the texture usage for the swap chain.
pub fn usage(mut self, usage: wgpu::TextureUsage) -> Self {
self.usage = Some(usage);
self
}
/// Specify the texture format for the swap chain.
pub fn format(mut self, format: wgpu::TextureFormat) -> Self {
self.format = Some(format);
self
}
/// The way in which swap chain images are presented to the display.
///
/// By default, nannou will attempt to select the ideal present mode depending on the current
/// app `LoopMode`.
pub fn present_mode(mut self, present_mode: wgpu::PresentMode) -> Self {
self.present_mode = Some(present_mode);
self
}
/// Build the swap chain.
pub(crate) fn build(
self,
device: &wgpu::Device,
surface: &wgpu::Surface,
[width_px, height_px]: [u32; 2],
) -> (wgpu::SwapChain, wgpu::SwapChainDescriptor) {
let usage = self.usage.unwrap_or(Self::DEFAULT_USAGE);
let format = self.format.unwrap_or(Self::DEFAULT_FORMAT);
let present_mode = self.present_mode.unwrap_or(Self::DEFAULT_PRESENT_MODE);
let desc = wgpu::SwapChainDescriptor {
usage,
format,
width: width_px,
height: height_px,
present_mode,
};
let swap_chain = device.create_swap_chain(surface, &desc);
(swap_chain, desc)
}
}
impl<'app> Builder<'app> {
/// Begin building a new window.
pub fn new(app: &'app App) -> Self {
Builder {
app,
window: winit::window::WindowBuilder::new(),
title_was_set: false,
swap_chain_builder: Default::default(),
request_adapter_opts: None,
device_desc: None,
user_functions: Default::default(),
msaa_samples: None,
}
}
/// Build the window with some custom window parameters.
pub fn window(mut self, window: winit::window::WindowBuilder) -> Self {
self.window = window;
self
}
/// Specify a set of parameters for building the window surface swap chain.
pub fn swap_chain_builder(mut self, swap_chain_builder: SwapChainBuilder) -> Self {
self.swap_chain_builder = swap_chain_builder;
self
}
/// Specify a custom set of options to request an adapter with. This is useful for describing a
/// set of desired properties for the requested physical device.
pub fn request_adapter_options(mut self, opts: wgpu::RequestAdapterOptions) -> Self {
self.request_adapter_opts = Some(opts);
self
}
/// Specify a device descriptor to use when requesting the logical device from the adapter.
/// This allows for specifying custom wgpu device extensions.
pub fn device_descriptor(mut self, device_desc: wgpu::DeviceDescriptor) -> Self {
self.device_desc = Some(device_desc);
self
}
/// Specify the number of samples per pixel for the multisample anti-aliasing render pass.
///
/// If `msaa_samples` is unspecified, the first default value that nannou will attempt to use
/// can be found via the `Frame::DEFAULT_MSAA_SAMPLES` constant.
///
/// **Note:** This parameter has no meaning if the window uses a **raw_view** function for
/// rendering graphics to the window rather than a **view** function. This is because the
/// **raw_view** function provides a **RawFrame** with direct access to the swap chain image
/// itself and thus must manage their own MSAA pass.
///
/// On the other hand, the `view` function provides the `Frame` type which allows the user to
/// render to a multisampled intermediary image allowing Nannou to take care of resolving the
/// multisampled image to the swap chain image. In order to avoid confusion, The `Window::build`
/// method will `panic!` if the user tries to specify `msaa_samples` as well as a `raw_view`
/// method.
///
/// *TODO: Perhaps it would be worth adding two separate methods for specifying msaa samples.
/// One for forcing a certain number of samples and returning an error otherwise, and another
/// for attempting to use the given number of samples but falling back to a supported value in
/// the case that the specified number is not supported.*
pub fn msaa_samples(mut self, msaa_samples: u32) -> Self {
self.msaa_samples = Some(msaa_samples);
self
}
/// Provide a simple function for drawing to the window.
///
/// This is similar to `view` but does not provide access to user data via a Model type. This
/// is useful for sketches where you don't require tracking any state.
pub fn sketch(mut self, sketch_fn: SketchFn) -> Self {
self.user_functions.view = Some(View::Sketch(sketch_fn));
self
}
/// The **view** function that the app will call to allow you to present your Model to the
/// surface of the window on your display.
pub fn view<M>(mut self, view_fn: ViewFn<M>) -> Self
where
M: 'static,
{
self.user_functions.view = Some(View::WithModel(ViewFnAny::from_fn_ptr(view_fn)));
self
}
/// The **view** function that the app will call to allow you to present your Model to the
/// surface of the window on your display.
///
/// Unlike the **ViewFn**, the **RawViewFn** provides a **RawFrame** that is designed for
/// drawing directly to a window's swap chain images, rather than to a convenient intermediary
/// image.
pub fn raw_view<M>(mut self, raw_view_fn: RawViewFn<M>) -> Self
where
M: 'static,
{
self.user_functions.view = Some(View::WithModelRaw(RawViewFnAny::from_fn_ptr(raw_view_fn)));
self
}
/// A function for updating your model on `WindowEvent`s associated with this window.
///
/// These include events such as key presses, mouse movement, clicks, resizing, etc.
///
/// ## Event Function Call Order
///
/// In nannou, if multiple functions require being called for a single kind of event, the more
/// general event function will always be called before the more specific event function.
///
/// If an `event` function was also submitted to the `App`, that function will always be called
/// immediately before window-specific event functions. Similarly, if a function associated
/// with a more specific event type (e.g. `key_pressed`) was given, that function will be
/// called *after* this function will be called.
///
/// ## Specific Events Variants
///
/// Note that if you only care about a certain kind of event, you can submit a function that
/// only gets called for that specific event instead. For example, if you only care about key
/// presses, you may wish to use the `key_pressed` method instead.
pub fn event<M>(mut self, event_fn: EventFn<M>) -> Self
where
M: 'static,
{
self.user_functions.event = Some(EventFnAny::from_fn_ptr(event_fn));
self
}
/// The same as the `event` method, but allows for processing raw `winit::event::WindowEvent`s rather
/// than Nannou's simplified `event::WindowEvent`s.
///
/// ## Event Function Call Order
///
/// If both `raw_event` and `event` functions have been provided, the given `raw_event`
/// function will always be called immediately before the given `event` function.
pub fn raw_event<M>(mut self, raw_event_fn: RawEventFn<M>) -> Self
where
M: 'static,
{
self.user_functions.raw_event = Some(RawEventFnAny::from_fn_ptr(raw_event_fn));
self
}
/// A function for processing key press events associated with this window.
pub fn key_pressed<M>(mut self, f: KeyPressedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.key_pressed = Some(KeyPressedFnAny::from_fn_ptr(f));
self
}
/// A function for processing key release events associated with this window.
pub fn key_released<M>(mut self, f: KeyReleasedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.key_released = Some(KeyReleasedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse moved events associated with this window.
pub fn mouse_moved<M>(mut self, f: MouseMovedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_moved = Some(MouseMovedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse pressed events associated with this window.
pub fn mouse_pressed<M>(mut self, f: MousePressedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_pressed = Some(MousePressedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse released events associated with this window.
pub fn mouse_released<M>(mut self, f: MouseReleasedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_released = Some(MouseReleasedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse wheel events associated with this window.
pub fn mouse_wheel<M>(mut self, f: MouseWheelFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_wheel = Some(MouseWheelFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse entered events associated with this window.
pub fn mouse_entered<M>(mut self, f: MouseEnteredFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_entered = Some(MouseEnteredFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse exited events associated with this window.
pub fn mouse_exited<M>(mut self, f: MouseExitedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_exited = Some(MouseExitedFnAny::from_fn_ptr(f));
self
}
/// A function for processing touch events associated with this window.
pub fn touch<M>(mut self, f: TouchFn<M>) -> Self
where
M: 'static,
{
self.user_functions.touch = Some(TouchFnAny::from_fn_ptr(f));
self
}
/// A function for processing touchpad pressure events associated with this window.
pub fn touchpad_pressure<M>(mut self, f: TouchpadPressureFn<M>) -> Self
where
M: 'static,
{
self.user_functions.touchpad_pressure = Some(TouchpadPressureFnAny::from_fn_ptr(f));
self
}
/// A function for processing window moved events associated with this window.
pub fn moved<M>(mut self, f: MovedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.moved = Some(MovedFnAny::from_fn_ptr(f));
self
}
/// A function for processing window resized events associated with this window.
pub fn resized<M>(mut self, f: ResizedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.resized = Some(ResizedFnAny::from_fn_ptr(f));
self
}
/// A function for processing hovered file events associated with this window.
pub fn hovered_file<M>(mut self, f: HoveredFileFn<M>) -> Self
where
M: 'static,
{
self.user_functions.hovered_file = Some(HoveredFileFnAny::from_fn_ptr(f));
self
}
/// A function for processing hovered file cancelled events associated with this window.
pub fn hovered_file_cancelled<M>(mut self, f: HoveredFileCancelledFn<M>) -> Self
where
M: 'static,
{
self.user_functions.hovered_file_cancelled =
Some(HoveredFileCancelledFnAny::from_fn_ptr(f));
self
}
/// A function for processing dropped file events associated with this window.
pub fn dropped_file<M>(mut self, f: DroppedFileFn<M>) -> Self
where
M: 'static,
{
self.user_functions.dropped_file = Some(DroppedFileFnAny::from_fn_ptr(f));
self
}
/// A function for processing the focused event associated with this window.
pub fn focused<M>(mut self, f: FocusedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.focused = Some(FocusedFnAny::from_fn_ptr(f));
self
}
/// A function for processing the unfocused event associated with this window.
pub fn unfocused<M>(mut self, f: UnfocusedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.unfocused = Some(UnfocusedFnAny::from_fn_ptr(f));
self
}
/// A function for processing the window closed event associated with this window.
pub fn closed<M>(mut self, f: ClosedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.closed = Some(ClosedFnAny::from_fn_ptr(f));
self
}
/// Builds the window, inserts it into the `App`'s display map and returns the unique ID.
pub fn build(self) -> Result<Id, BuildError> {
let Builder {
app,
mut window,
title_was_set,
swap_chain_builder,
request_adapter_opts,
device_desc,
user_functions,
msaa_samples,
} = self;
// If the title was not set, default to the "nannou - <exe_name>".
if !title_was_set {
if let Ok(exe_path) = env::current_exe() {
if let Some(os_str) = exe_path.file_stem() {
if let Some(exe_name) = os_str.to_str() {
let title = format!("nannou - {}", exe_name);
window = window.with_title(title);
}
}
}
}
// Set default dimensions in the case that none were given.
let initial_window_size = window
.window
.inner_size
.or_else(|| {
window
.window
.fullscreen
.as_ref()
.map(|fullscreen| match fullscreen {
winit::window::Fullscreen::Exclusive(video_mode) => {
let monitor = video_mode.monitor();
video_mode
.size()
.to_logical::<f32>(monitor.scale_factor())
.into()
}
winit::window::Fullscreen::Borderless(monitor) => monitor
.size()
.to_logical::<f32>(monitor.scale_factor())
.into(),
})
})
.unwrap_or_else(|| {
let mut dim = DEFAULT_DIMENSIONS;
if let Some(min) = window.window.min_inner_size {
match min {
winit::dpi::Size::Logical(min) => {
dim.width = dim.width.max(min.width as _);
dim.height = dim.height.max(min.height as _);
}
winit::dpi::Size::Physical(min) => {
dim.width = dim.width.max(min.width as _);
dim.height = dim.height.max(min.height as _);
unimplemented!("consider scale factor");
}
}
}
if let Some(max) = window.window.max_inner_size {
match max {
winit::dpi::Size::Logical(max) => {
dim.width = dim.width.min(max.width as _);
dim.height = dim.height.min(max.height as _);
}
winit::dpi::Size::Physical(max) => {
dim.width = dim.width.min(max.width as _);
dim.height = dim.height.min(max.height as _);
unimplemented!("consider scale factor");
}
}
}
dim.into()
});
// Use the `initial_swapchain_dimensions` as the default dimensions for the window if none
// were specified.
if window.window.inner_size.is_none() && window.window.fullscreen.is_none() {
window.window.inner_size = Some(initial_window_size);
}
// Build the window.
let window = {
let window_target = app
.event_loop_window_target
.as_ref()
.expect("unexpected invalid App.event_loop_window_target state - please report")
.as_ref();
window.build(window_target)?
};
// Build the wgpu surface.
let surface = wgpu::Surface::create(&window);
// Request the adapter.
let request_adapter_opts =
request_adapter_opts.unwrap_or(wgpu::DEFAULT_ADAPTER_REQUEST_OPTIONS);
let adapter = app
.wgpu_adapters()
.get_or_request(request_adapter_opts)
.ok_or(BuildError::NoAvailableAdapter)?;
// Instantiate the logical device.
let device_desc = device_desc.unwrap_or_else(wgpu::default_device_descriptor);
let device_queue_pair = adapter.get_or_request_device(device_desc);
// Build the swapchain.
let win_physical_size = window.inner_size();
let win_dims_px: [u32; 2] = win_physical_size.into();
let device = device_queue_pair.device();
let (swap_chain, swap_chain_desc) =
swap_chain_builder.build(&device, &surface, win_dims_px);
// If we're using an intermediary image for rendering frames to swap_chain images, create
// the necessary render data.
let (frame_data, msaa_samples) = match user_functions.view {
Some(View::WithModel(_)) | Some(View::Sketch(_)) | None => {
let msaa_samples = msaa_samples.unwrap_or(Frame::DEFAULT_MSAA_SAMPLES);
// TODO: Verity that requested sample count is valid for surface?
let swap_chain_dims = [swap_chain_desc.width, swap_chain_desc.height];
let render = frame::RenderData::new(
&device,
swap_chain_dims,
swap_chain_desc.format,
msaa_samples,
);
let capture = frame::CaptureData::default();
let frame_data = FrameData { render, capture };
(Some(frame_data), msaa_samples)
}
Some(View::WithModelRaw(_)) => (None, 1),
};
let window_id = window.id();
let frame_count = 0;
let swap_chain = WindowSwapChain {
descriptor: swap_chain_desc,
swap_chain: Some(swap_chain),
};
let tracked_state = TrackedState {
scale_factor: window.scale_factor(),
physical_size: win_physical_size,
};
let window = Window {
window,
surface,
device_queue_pair,
msaa_samples,
swap_chain,
frame_data,
frame_count,
user_functions,
tracked_state,
};
app.windows.borrow_mut().insert(window_id, window);
// If this is the first window, set it as the app's "focused" window.
if app.windows.borrow().len() == 1 {
*app.focused_window.borrow_mut() = Some(window_id);
}
Ok(window_id)
}
fn map_window<F>(self, map: F) -> Self
where
F: FnOnce(winit::window::WindowBuilder) -> winit::window::WindowBuilder,
{
let Builder {
app,
window,
title_was_set,
device_desc,
request_adapter_opts,
swap_chain_builder,
user_functions,
msaa_samples,
} = self;
let window = map(window);
Builder {
app,
window,
title_was_set,
device_desc,
request_adapter_opts,
swap_chain_builder,
user_functions,
msaa_samples,
}
}
// Window builder methods.
//
// NOTE: On new versions of winit, we should check whether or not new `WindowBuilder` methods
// have been added that we should expose.
/// Requests the window to be a specific size in points.
///
/// This describes to the "inner" part of the window, not including desktop decorations like the
/// title bar.
pub fn size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Set the minimum size in points for the window.
pub fn min_size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_min_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Set the maximum size in points for the window.
pub fn max_size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_max_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Requests the window to be a specific size in points.
///
/// This describes to the "inner" part of the window, not including desktop decorations like the
/// title bar.
pub fn size_pixels(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_inner_size(winit::dpi::PhysicalSize { width, height }))
}
/// Whether or not the window should be resizable after creation.
pub fn resizble(self, resizable: bool) -> Self {
self.map_window(|w| w.with_resizable(resizable))
}
/// Requests a specific title for the window.
pub fn title<T>(mut self, title: T) -> Self
where
T: Into<String>,
{
self.title_was_set = true;
self.map_window(|w| w.with_title(title))
}
/// Sets the window fullscreen state.
///
/// None means a normal window, Some(MonitorId) means a fullscreen window on that specific
/// monitor.
pub fn fullscreen(self, fullscreen: Option<winit::window::Fullscreen>) -> Self {
self.map_window(|w| w.with_fullscreen(fullscreen))
}
/// Requests maximized mode.
pub fn maximized(self, maximized: bool) -> Self {
self.map_window(|w| w.with_maximized(maximized))
}
/// Sets whether the window will be initially hidden or visible.
pub fn visible(self, visible: bool) -> Self {
self.map_window(|w| w.with_visible(visible))
}
/// Sets whether the background of the window should be transparent.
pub fn transparent(self, transparent: bool) -> Self {
self.map_window(|w| w.with_transparent(transparent))
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn decorations(self, decorations: bool) -> Self {
self.map_window(|w| w.with_decorations(decorations))
}
/// Sets whether or not the window will always be on top of other windows.
pub fn always_on_top(self, always_on_top: bool) -> Self {
self.map_window(|w| w.with_always_on_top(always_on_top))
}
/// Sets the window icon.
pub fn window_icon(self, window_icon: Option<winit::window::Icon>) -> Self {
self.map_window(|w| w.with_window_icon(window_icon))
}
}
impl Window {
// `winit::window::Window` methods.
//
// NOTE: On new versions of winit, we should check whether or not new `Window` methods have
// been added that we should expose. Most of the following method docs are copied from the
// winit documentation. It would be nice if we could automate this inlining somehow.
/// A unique identifier associated with this window.
pub fn id(&self) -> Id {
self.window.id()
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels and vice
/// versa.
///
/// Throughout nannou, you will see "logical pixels" referred to as "points", and "physical
/// pixels" referred to as "pixels".
///
/// This is typically `1.0` for a normal display, `2.0` for a retina display and higher on more
/// modern displays.
///
/// You can read more about what this scale factor means within winit's [dpi module
/// documentation](https://docs.rs/winit/latest/winit/dpi/index.html).
///
/// ## Platform-specific
///
/// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_X11_SCALE_FACTOR`
/// environment variable.
/// - **Android:** Always returns 1.0.
/// - **iOS:** Can only be called on the main thread. Returns the underlying `UiView`'s
/// `contentScaleFactor`.
pub fn scale_factor(&self) -> geom::scalar::Default {
self.window.scale_factor() as _
}
/// The position of the top-left hand corner of the window relative to the top-left hand corner
/// of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as the
/// screen. If the user uses a desktop with multiple monitors, the top-left hand corner of the
/// desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside of the
/// visible screen region.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the
/// window in the screen space coordinate system.
/// - **Web:** Returns the top-left coordinates relative to the viewport.
pub fn outer_position_pixels(&self) -> Result<(i32, i32), winit::error::NotSupportedError> {
self.window.outer_position().map(Into::into)
}
/// Modifies the position of the window.
///
/// See `outer_position_pixels` for more information about the returned coordinates. This
/// automatically un-maximizes the window if it is maximized.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Sets the top left coordinates of the
/// window in the screen space coordinate system.
/// - **Web:** Sets the top-left coordinates relative to the viewport.
pub fn set_outer_position_pixels(&self, x: i32, y: i32) {
self.window
.set_outer_position(winit::dpi::PhysicalPosition { x, y })
}
/// The width and height in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
pub fn inner_size_pixels(&self) -> (u32, u32) {
self.window.inner_size().into()
}
/// The size in points of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
///
/// This is the same as dividing the result of `inner_size_pixels()` by `scale_factor()`.
pub fn inner_size_points(&self) -> (geom::scalar::Default, geom::scalar::Default) {
self.window
.inner_size()
.to_logical::<f32>(self.tracked_state.scale_factor)
.into()
}
/// Modifies the inner size of the window.
///
/// See the `inner_size` methods for more informations about the values.
pub fn set_inner_size_pixels(&self, width: u32, height: u32) {
self.window
.set_inner_size(winit::dpi::PhysicalSize { width, height })
}
/// Modifies the inner size of the window using point values.
///
/// See the `inner_size` methods for more informations about the values.
pub fn set_inner_size_points(&self, width: f32, height: f32) {
self.window
.set_inner_size(winit::dpi::LogicalSize { width, height })
}
/// The width and height of the window in pixels.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// `inner_size_pixels` instead.
pub fn outer_size_pixels(&self) -> (u32, u32) {
self.window.outer_size().into()
}
/// The size of the window in points.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// `inner_size_points` instead.
///
/// This is the same as dividing the result of `outer_size_pixels()` by `scale_factor()`.
pub fn outer_size_points(&self) -> (f32, f32) {
self.window
.outer_size()
.to_logical::<f32>(self.tracked_state.scale_factor)
.into()
}
/// Sets a minimum size for the window.
pub fn set_min_inner_size_points(&self, size: Option<(f32, f32)>) {
let size = size.map(|(width, height)| winit::dpi::LogicalSize { width, height });
self.window.set_min_inner_size(size)
}
/// Sets a maximum size for the window.
pub fn set_max_inner_size_points(&self, size: Option<(f32, f32)>) {
let size = size.map(|(width, height)| winit::dpi::LogicalSize { width, height });
self.window.set_max_inner_size(size)
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
pub fn set_title(&self, title: &str) {
self.window.set_title(title);
}
/// Set the visibility of the window.
///
/// ## Platform-specific
///
/// - Android: Has no effect.
/// - iOS: Can only be called on the main thread.
/// - Web: Has no effect.
pub fn set_visible(&self, visible: bool) {
self.window.set_visible(visible)
}
/// Sets whether the window is resizable or not.
///
/// Note that making the window unresizable doesn't exempt you from handling **Resized**, as
/// that event can still be triggered by DPI scaling, entering fullscreen mode, etc.
pub fn set_resizable(&self, resizable: bool) {
self.window.set_resizable(resizable)
}
/// Sets the window to minimized or back.
pub fn set_minimized(&self, minimized: bool) {
self.window.set_minimized(minimized)
}
/// Sets the window to maximized or back.
pub fn set_maximized(&self, maximized: bool) {
self.window.set_maximized(maximized)
}
/// Set the window to fullscreen.
///
/// Call this method again with `None` to revert back from fullscreen.
///
/// ## Platform-specific
///
/// - macOS: `Fullscreen::Exclusive` provides true exclusive mode with a video mode change.
/// Caveat! macOS doesn't provide task switching (or spaces!) while in exclusive fullscreen
/// mode. This mode should be used when a video mode change is desired, but for a better user
/// experience, borderless fullscreen might be preferred.
///
/// `Fullscreen::Borderless` provides a borderless fullscreen window on a separate space.
/// This is the idiomatic way for fullscreen games to work on macOS. See
/// WindowExtMacOs::set_simple_fullscreen if separate spaces are not preferred.
///
/// The dock and the menu bar are always disabled in fullscreen mode.
///
/// - iOS: Can only be called on the main thread.
/// - Wayland: Does not support exclusive fullscreen mode.
/// - Windows: Screen saver is disabled in fullscreen mode.
pub fn set_fullscreen(&self, monitor: Option<winit::window::Fullscreen>) {
self.window.set_fullscreen(monitor)
}
/// Gets the window's current fullscreen state.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread.
pub fn fullscreen(&self) -> Option<winit::window::Fullscreen> {
self.window.fullscreen()
}
/// Turn window decorations on or off.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Controls whether the status bar is hidden
/// via `setPrefersStatusBarHidden`.
/// - **Web:** Has no effect.
pub fn set_decorations(&self, decorations: bool) {
self.window.set_decorations(decorations)
}
/// Change whether or not the window will always be on top of other windows.
pub fn set_always_on_top(&self, always_on_top: bool) {
self.window.set_always_on_top(always_on_top)
}
/// Sets the window icon. On Windows and X11, this is typically the small icon in the top-left
/// corner of the titlebar.
///
/// ## Platform-specific
///
/// This only has effect on Windows and X11.
///
/// On Windows, this sets ICON_SMALL. The base size for a window icon is 16x16, but it's
/// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32.
///
/// X11 has no universal guidelines for icon sizes, so you're at the whims of the WM. That
/// said, it's usually in the same ballpark as on Windows.
pub fn set_window_icon(&self, window_icon: Option<winit::window::Icon>) {
self.window.set_window_icon(window_icon)
}
/// Sets the location of IME candidate box in client area coordinates relative to the top left.
///
/// ## Platform-specific
///
/// - **iOS:** Has no effect.
/// - **Web:** Has no effect.
pub fn set_ime_position_points(&self, x: f32, y: f32) {
self.window
.set_ime_position(winit::dpi::LogicalPosition { x, y })
}
/// Modifies the mouse cursor of the window.
///
/// ## Platform-specific
///
/// - **iOS:** Has no effect.
/// - **Android:** Has no effect.
pub fn set_cursor_icon(&self, state: winit::window::CursorIcon) {
self.window.set_cursor_icon(state);
}
/// Changes the position of the cursor in logical window coordinates.
///
/// ## Platform-specific
///
/// - **iOS:** Always returns an `Err`.
/// - **Web:** Has no effect.
pub fn set_cursor_position_points(
&self,
x: f32,
y: f32,
) -> Result<(), winit::error::ExternalError> {
self.window
.set_cursor_position(winit::dpi::LogicalPosition { x, y })
}
/// Grabs the cursor, preventing it from leaving the window.
///
/// ## Platform-specific
///
/// - **macOS:** Locks the cursor in a fixed location.
/// - **Wayland:** Locks the cursor in a fixed location.
/// - **Android:** Has no effect.
/// - **iOS:** Always returns an Err.
/// - **Web:** Has no effect.
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), winit::error::ExternalError> {
self.window.set_cursor_grab(grab)
}
/// Set the cursor's visibility.
///
/// If `false`, hides the cursor. If `true`, shows the cursor.
///
/// ## Platform-specific
///
/// On **Windows**, **X11** and **Wayland**, the cursor is only hidden within the confines of
/// the window.
///
/// On **macOS**, the cursor is hidden as long as the window has input focus, even if the
/// cursor is outside of the window.
///
/// This has no effect on **Android** or **iOS**.
pub fn set_cursor_visible(&self, visible: bool) {
self.window.set_cursor_visible(visible)
}
/// The current monitor that the window is on or the primary monitor if nothing matches.
pub fn current_monitor(&self) -> winit::monitor::MonitorHandle {
self.window.current_monitor()
}
// Access to wgpu API.
/// Returns a reference to the window's wgpu swap chain surface.
pub fn surface(&self) -> &wgpu::Surface {
&self.surface
}
/// The descriptor for the swap chain associated with this window's wgpu surface.
pub fn swap_chain_descriptor(&self) -> &wgpu::SwapChainDescriptor {
&self.swap_chain.descriptor
}
/// The wgpu logical device on which the window's swap chain is running.
///
/// This is shorthand for `DeviceOwned::device(window.swap_chain())`.
pub fn swap_chain_device(&self) -> &wgpu::Device {
self.device_queue_pair.device()
}
/// The wgpu graphics queue on which the window swap chain work is run.
///
/// The queue is guarded by a `Mutex` in order to synchronise submissions of command buffers in
/// cases that the queue is shared between more than one window.
pub fn swap_chain_queue(&self) -> &Mutex<wgpu::Queue> {
self.device_queue_pair.queue()
}
/// Provides access to the device queue pair and the `Arc` behind which it is stored. This can
/// be useful in cases where using references provided by the `swap_chain_device` or
/// `swap_chain_queue` methods cause awkward ownership problems.
pub fn swap_chain_device_queue_pair(&self) -> &Arc<wgpu::DeviceQueuePair> {
&self.device_queue_pair
}
/// The number of samples used in the MSAA for the image associated with the `view` function's
/// `Frame` type.
///
/// **Note:** If the user specified a `raw_view` function rather than a `view` function, this
/// value will always return `1`.
pub fn msaa_samples(&self) -> u32 {
self.msaa_samples
}
// Custom methods.
// A utility function to simplify the recreation of a swap_chain.
pub(crate) fn rebuild_swap_chain(&mut self, size_px: [u32; 2]) {
std::mem::drop(self.swap_chain.swap_chain.take());
let [width, height] = size_px;
self.swap_chain.descriptor.width = width;
self.swap_chain.descriptor.height = height;
self.swap_chain.swap_chain = Some(
self.swap_chain_device()
.create_swap_chain(&self.surface, &self.swap_chain.descriptor),
);
if self.frame_data.is_some() {
let render_data = frame::RenderData::new(
self.swap_chain_device(),
size_px,
self.swap_chain.descriptor.format,
self.msaa_samples,
);
self.frame_data.as_mut().unwrap().render = render_data;
}
}
/// Attempts to determine whether or not the window is currently fullscreen.
pub fn is_fullscreen(&self) -> bool {
self.fullscreen().is_some()
}
/// The number of times `view` has been called with a `Frame` for this window.
pub fn elapsed_frames(&self) -> u64 {
self.frame_count
}
/// The rectangle representing the position and dimensions of the window.
///
/// The window's position will always be `[0.0, 0.0]`, as positions are generally described
/// relative to the centre of the window itself.
///
/// The dimensions will be equal to the result of `inner_size_points`. This represents the area
/// of the that we can draw to in a DPI-agnostic manner, typically useful for drawing and UI
/// positioning.
pub fn rect(&self) -> geom::Rect {
let (w, h) = self.inner_size_points();
geom::Rect::from_w_h(w, h)
}
/// Capture the next frame right before it is drawn to this window and write it to an image
/// file at the given path. If a frame already exists, it will be captured before its `submit`
/// method is called or before it is `drop`ped.
///
/// The destination image file type will be inferred from the extension given in the path.
///
pub fn capture_frame<P>(&self, path: P)
where
P: AsRef<Path>,
{
self.capture_frame_with_threaded(path.as_ref(), false);
}
/// The same as **capture_frame**, but uses a separate pool of threads for writing image files
/// in order to free up the main application thread.
///
/// Note that if you are capturing every frame and your window size is very large or the file
/// type you are writing to is expensive to encode, this capturing thread may fall behind the
/// main thread, resulting in a large delay before the exiting the program. This is because the
/// capturing thread needs more time to write the captured images.
pub fn capture_frame_threaded<P>(&self, path: P)
where
P: AsRef<Path>,
{
let path = path.as_ref();
self.capture_frame_with_threaded(path.as_ref(), false);
}
fn capture_frame_with_threaded(&self, path: &Path, threaded: bool) {
// If the parent directory does not exist, create it.
let dir = path.parent().expect("capture_frame path has no directory");
if !dir.exists() {
std::fs::create_dir_all(&dir).expect("failed to create `capture_frame` directory");
}
let mut capture_next_frame_path = self
.frame_data
.as_ref()
.expect("window capture requires that `view` draws to a `Frame` (not a `RawFrame`)")
.capture
.next_frame_path
.lock()
.expect("failed to lock `capture_next_frame_path`");
*capture_next_frame_path = Some((path.to_path_buf(), threaded));
}
}
// Debug implementations for function wrappers.
impl fmt::Debug for View {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let variant = match *self {
View::WithModel(ref v) => format!("WithModel({:?})", v),
View::WithModelRaw(ref v) => format!("WithModelRaw({:?})", v),
View::Sketch(_) => "Sketch".to_string(),
};
write!(f, "View::{}", variant)
}
}
// Deref implementations.
impl fmt::Debug for WindowSwapChain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WindowSwapChain ( descriptor: {:?}, swap_chain: {:?} )",
self.descriptor, self.swap_chain,
)
}
}
// Error implementations.
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BuildError::NoAvailableAdapter => write!(f, "no available wgpu adapter detected"),
BuildError::WinitOsError(ref e) => e.fmt(f),
}
}
}
impl From<winit::error::OsError> for BuildError {
fn from(e: winit::error::OsError) -> Self {
BuildError::WinitOsError(e)
}
}
replaces 'size' with explicit 'width and height'
//! The nannou [**Window**](./struct.Window.html) API. Create a new window via `.app.new_window()`.
//! This produces a [**Builder**](./struct.Builder.html) which can be used to build a window.
use crate::event::{
Key, MouseButton, MouseScrollDelta, TouchEvent, TouchPhase, TouchpadPressure, WindowEvent,
};
use crate::frame::{self, Frame, RawFrame};
use crate::geom;
use crate::geom::{Point2, Vector2};
use crate::wgpu;
use crate::App;
use std::any::Any;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fmt};
use winit::dpi::LogicalSize;
pub use winit::window::WindowId as Id;
/// The default dimensions used for a window in the case that none are specified.
pub const DEFAULT_DIMENSIONS: LogicalSize<geom::scalar::Default> = LogicalSize {
width: 1024.0,
height: 768.0,
};
/// A context for building a window.
pub struct Builder<'app> {
app: &'app App,
window: winit::window::WindowBuilder,
title_was_set: bool,
swap_chain_builder: SwapChainBuilder,
request_adapter_opts: Option<wgpu::RequestAdapterOptions>,
device_desc: Option<wgpu::DeviceDescriptor>,
user_functions: UserFunctions,
msaa_samples: Option<u32>,
}
/// For storing all user functions within the window.
#[derive(Debug, Default)]
pub(crate) struct UserFunctions {
pub(crate) view: Option<View>,
pub(crate) event: Option<EventFnAny>,
pub(crate) raw_event: Option<RawEventFnAny>,
pub(crate) key_pressed: Option<KeyPressedFnAny>,
pub(crate) key_released: Option<KeyReleasedFnAny>,
pub(crate) mouse_moved: Option<MouseMovedFnAny>,
pub(crate) mouse_pressed: Option<MousePressedFnAny>,
pub(crate) mouse_released: Option<MouseReleasedFnAny>,
pub(crate) mouse_entered: Option<MouseEnteredFnAny>,
pub(crate) mouse_exited: Option<MouseExitedFnAny>,
pub(crate) mouse_wheel: Option<MouseWheelFnAny>,
pub(crate) moved: Option<MovedFnAny>,
pub(crate) resized: Option<ResizedFnAny>,
pub(crate) touch: Option<TouchFnAny>,
pub(crate) touchpad_pressure: Option<TouchpadPressureFnAny>,
pub(crate) hovered_file: Option<HoveredFileFnAny>,
pub(crate) hovered_file_cancelled: Option<HoveredFileCancelledFnAny>,
pub(crate) dropped_file: Option<DroppedFileFnAny>,
pub(crate) focused: Option<FocusedFnAny>,
pub(crate) unfocused: Option<UnfocusedFnAny>,
pub(crate) closed: Option<ClosedFnAny>,
}
/// The user function type for drawing their model to the surface of a single window.
pub type ViewFn<Model> = fn(&App, &Model, Frame);
/// The user function type for drawing their model to the surface of a single window.
///
/// Unlike the `ViewFn`, the `RawViewFn` is designed for drawing directly to a window's swap chain
/// images rather than to a convenient intermediary image.
pub type RawViewFn<Model> = fn(&App, &Model, RawFrame);
/// The same as `ViewFn`, but provides no user model to draw from.
///
/// Useful for simple, stateless sketching.
pub type SketchFn = fn(&App, Frame);
/// The user's view function, whether with a model or without one.
#[derive(Clone)]
pub(crate) enum View {
WithModel(ViewFnAny),
WithModelRaw(RawViewFnAny),
Sketch(SketchFn),
}
/// A function for processing raw winit window events.
pub type RawEventFn<Model> = fn(&App, &mut Model, &winit::event::WindowEvent);
/// A function for processing window events.
pub type EventFn<Model> = fn(&App, &mut Model, WindowEvent);
/// A function for processing key press events.
pub type KeyPressedFn<Model> = fn(&App, &mut Model, Key);
/// A function for processing key release events.
pub type KeyReleasedFn<Model> = fn(&App, &mut Model, Key);
/// A function for processing mouse moved events.
pub type MouseMovedFn<Model> = fn(&App, &mut Model, Point2);
/// A function for processing mouse pressed events.
pub type MousePressedFn<Model> = fn(&App, &mut Model, MouseButton);
/// A function for processing mouse released events.
pub type MouseReleasedFn<Model> = fn(&App, &mut Model, MouseButton);
/// A function for processing mouse entered events.
pub type MouseEnteredFn<Model> = fn(&App, &mut Model);
/// A function for processing mouse exited events.
pub type MouseExitedFn<Model> = fn(&App, &mut Model);
/// A function for processing mouse wheel events.
pub type MouseWheelFn<Model> = fn(&App, &mut Model, MouseScrollDelta, TouchPhase);
/// A function for processing window moved events.
pub type MovedFn<Model> = fn(&App, &mut Model, Vector2);
/// A function for processing window resized events.
pub type ResizedFn<Model> = fn(&App, &mut Model, Vector2);
/// A function for processing touch events.
pub type TouchFn<Model> = fn(&App, &mut Model, TouchEvent);
/// A function for processing touchpad pressure events.
pub type TouchpadPressureFn<Model> = fn(&App, &mut Model, TouchpadPressure);
/// A function for processing hovered file events.
pub type HoveredFileFn<Model> = fn(&App, &mut Model, PathBuf);
/// A function for processing hovered file cancelled events.
pub type HoveredFileCancelledFn<Model> = fn(&App, &mut Model);
/// A function for processing dropped file events.
pub type DroppedFileFn<Model> = fn(&App, &mut Model, PathBuf);
/// A function for processing window focused events.
pub type FocusedFn<Model> = fn(&App, &mut Model);
/// A function for processing window unfocused events.
pub type UnfocusedFn<Model> = fn(&App, &mut Model);
/// A function for processing window closed events.
pub type ClosedFn<Model> = fn(&App, &mut Model);
/// Errors that might occur while building the window.
#[derive(Debug)]
pub enum BuildError {
NoAvailableAdapter,
WinitOsError(winit::error::OsError),
}
// A macro for generating a handle to a function that can be stored within the Window without
// requiring a type param. $TFn is the function pointer type that will be wrapped by $TFnAny.
macro_rules! fn_any {
($TFn:ident<M>, $TFnAny:ident) => {
// A handle to a function that can be stored without requiring a type param.
#[derive(Clone)]
pub(crate) struct $TFnAny {
fn_ptr: Arc<dyn Any>,
}
impl $TFnAny {
// Create the `$TFnAny` from a view function pointer.
pub fn from_fn_ptr<M>(fn_ptr: $TFn<M>) -> Self
where
M: 'static,
{
let fn_ptr = Arc::new(fn_ptr) as Arc<dyn Any>;
$TFnAny { fn_ptr }
}
// Retrieve the view function pointer from the `$TFnAny`.
pub fn to_fn_ptr<M>(&self) -> Option<&$TFn<M>>
where
M: 'static,
{
self.fn_ptr.downcast_ref::<$TFn<M>>()
}
}
impl fmt::Debug for $TFnAny {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", stringify!($TFnAny))
}
}
};
}
fn_any!(ViewFn<M>, ViewFnAny);
fn_any!(RawViewFn<M>, RawViewFnAny);
fn_any!(EventFn<M>, EventFnAny);
fn_any!(RawEventFn<M>, RawEventFnAny);
fn_any!(KeyPressedFn<M>, KeyPressedFnAny);
fn_any!(KeyReleasedFn<M>, KeyReleasedFnAny);
fn_any!(MouseMovedFn<M>, MouseMovedFnAny);
fn_any!(MousePressedFn<M>, MousePressedFnAny);
fn_any!(MouseReleasedFn<M>, MouseReleasedFnAny);
fn_any!(MouseEnteredFn<M>, MouseEnteredFnAny);
fn_any!(MouseExitedFn<M>, MouseExitedFnAny);
fn_any!(MouseWheelFn<M>, MouseWheelFnAny);
fn_any!(MovedFn<M>, MovedFnAny);
fn_any!(ResizedFn<M>, ResizedFnAny);
fn_any!(TouchFn<M>, TouchFnAny);
fn_any!(TouchpadPressureFn<M>, TouchpadPressureFnAny);
fn_any!(HoveredFileFn<M>, HoveredFileFnAny);
fn_any!(HoveredFileCancelledFn<M>, HoveredFileCancelledFnAny);
fn_any!(DroppedFileFn<M>, DroppedFileFnAny);
fn_any!(FocusedFn<M>, FocusedFnAny);
fn_any!(UnfocusedFn<M>, UnfocusedFnAny);
fn_any!(ClosedFn<M>, ClosedFnAny);
/// A nannou window.
///
/// The **Window** acts as a wrapper around the `winit::window::Window` and the `wgpu::Surface`
/// types. It also manages the associated swap chain, providing a more nannou-friendly API.
#[derive(Debug)]
pub struct Window {
pub(crate) window: winit::window::Window,
pub(crate) surface: wgpu::Surface,
pub(crate) device_queue_pair: Arc<wgpu::DeviceQueuePair>,
msaa_samples: u32,
pub(crate) swap_chain: WindowSwapChain,
pub(crate) frame_data: Option<FrameData>,
pub(crate) frame_count: u64,
pub(crate) user_functions: UserFunctions,
pub(crate) tracked_state: TrackedState,
}
// Data related to `Frame`s produced for this window's swapchain textures.
#[derive(Debug)]
pub(crate) struct FrameData {
// Data for rendering a `Frame`'s intermediary image to a swap chain image.
pub(crate) render: frame::RenderData,
// Data for capturing a `Frame`'s intermediary image before submission.
pub(crate) capture: frame::CaptureData,
}
// Track and store some information about the window in order to avoid making repeated internal
// queries to the platform-specific API. This is beneficial in some cases where queries to the
// platform-specific API can be very slow (e.g. macOS cocoa).
#[derive(Debug)]
pub(crate) struct TrackedState {
// Updated on `ScaleFactorChanged`.
pub(crate) scale_factor: f64,
// Updated on `Resized`.
pub(crate) physical_size: winit::dpi::PhysicalSize<u32>,
}
/// A swap_chain and its images associated with a single window.
pub(crate) struct WindowSwapChain {
// The descriptor used to create the original swap chain. Useful for recreation.
pub(crate) descriptor: wgpu::SwapChainDescriptor,
// This is an `Option` in order to allow for separating ownership of the swapchain from the
// window during a `RedrawRequest`. Other than during `RedrawRequest`, this should always be
// `Some`.
pub(crate) swap_chain: Option<wgpu::SwapChain>,
}
/// SwapChain building parameters for which Nannou will provide a default if unspecified.
///
/// See the builder methods for more details on each parameter.
#[derive(Clone, Debug, Default)]
pub struct SwapChainBuilder {
pub usage: Option<wgpu::TextureUsage>,
pub format: Option<wgpu::TextureFormat>,
pub present_mode: Option<wgpu::PresentMode>,
}
impl SwapChainBuilder {
pub const DEFAULT_USAGE: wgpu::TextureUsage = wgpu::TextureUsage::OUTPUT_ATTACHMENT;
pub const DEFAULT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
pub const DEFAULT_PRESENT_MODE: wgpu::PresentMode = wgpu::PresentMode::Vsync;
/// A new empty **SwapChainBuilder** with all parameters set to `None`.
pub fn new() -> Self {
Default::default()
}
/// Create a **SwapChainBuilder** from an existing descriptor.
///
/// The resulting swap chain parameters will match that of the given `SwapChainDescriptor`.
pub fn from_descriptor(desc: &wgpu::SwapChainDescriptor) -> Self {
SwapChainBuilder::new()
.usage(desc.usage)
.format(desc.format)
.present_mode(desc.present_mode)
}
/// Specify the texture usage for the swap chain.
pub fn usage(mut self, usage: wgpu::TextureUsage) -> Self {
self.usage = Some(usage);
self
}
/// Specify the texture format for the swap chain.
pub fn format(mut self, format: wgpu::TextureFormat) -> Self {
self.format = Some(format);
self
}
/// The way in which swap chain images are presented to the display.
///
/// By default, nannou will attempt to select the ideal present mode depending on the current
/// app `LoopMode`.
pub fn present_mode(mut self, present_mode: wgpu::PresentMode) -> Self {
self.present_mode = Some(present_mode);
self
}
/// Build the swap chain.
pub(crate) fn build(
self,
device: &wgpu::Device,
surface: &wgpu::Surface,
[width_px, height_px]: [u32; 2],
) -> (wgpu::SwapChain, wgpu::SwapChainDescriptor) {
let usage = self.usage.unwrap_or(Self::DEFAULT_USAGE);
let format = self.format.unwrap_or(Self::DEFAULT_FORMAT);
let present_mode = self.present_mode.unwrap_or(Self::DEFAULT_PRESENT_MODE);
let desc = wgpu::SwapChainDescriptor {
usage,
format,
width: width_px,
height: height_px,
present_mode,
};
let swap_chain = device.create_swap_chain(surface, &desc);
(swap_chain, desc)
}
}
impl<'app> Builder<'app> {
/// Begin building a new window.
pub fn new(app: &'app App) -> Self {
Builder {
app,
window: winit::window::WindowBuilder::new(),
title_was_set: false,
swap_chain_builder: Default::default(),
request_adapter_opts: None,
device_desc: None,
user_functions: Default::default(),
msaa_samples: None,
}
}
/// Build the window with some custom window parameters.
pub fn window(mut self, window: winit::window::WindowBuilder) -> Self {
self.window = window;
self
}
/// Specify a set of parameters for building the window surface swap chain.
pub fn swap_chain_builder(mut self, swap_chain_builder: SwapChainBuilder) -> Self {
self.swap_chain_builder = swap_chain_builder;
self
}
/// Specify a custom set of options to request an adapter with. This is useful for describing a
/// set of desired properties for the requested physical device.
pub fn request_adapter_options(mut self, opts: wgpu::RequestAdapterOptions) -> Self {
self.request_adapter_opts = Some(opts);
self
}
/// Specify a device descriptor to use when requesting the logical device from the adapter.
/// This allows for specifying custom wgpu device extensions.
pub fn device_descriptor(mut self, device_desc: wgpu::DeviceDescriptor) -> Self {
self.device_desc = Some(device_desc);
self
}
/// Specify the number of samples per pixel for the multisample anti-aliasing render pass.
///
/// If `msaa_samples` is unspecified, the first default value that nannou will attempt to use
/// can be found via the `Frame::DEFAULT_MSAA_SAMPLES` constant.
///
/// **Note:** This parameter has no meaning if the window uses a **raw_view** function for
/// rendering graphics to the window rather than a **view** function. This is because the
/// **raw_view** function provides a **RawFrame** with direct access to the swap chain image
/// itself and thus must manage their own MSAA pass.
///
/// On the other hand, the `view` function provides the `Frame` type which allows the user to
/// render to a multisampled intermediary image allowing Nannou to take care of resolving the
/// multisampled image to the swap chain image. In order to avoid confusion, The `Window::build`
/// method will `panic!` if the user tries to specify `msaa_samples` as well as a `raw_view`
/// method.
///
/// *TODO: Perhaps it would be worth adding two separate methods for specifying msaa samples.
/// One for forcing a certain number of samples and returning an error otherwise, and another
/// for attempting to use the given number of samples but falling back to a supported value in
/// the case that the specified number is not supported.*
pub fn msaa_samples(mut self, msaa_samples: u32) -> Self {
self.msaa_samples = Some(msaa_samples);
self
}
/// Provide a simple function for drawing to the window.
///
/// This is similar to `view` but does not provide access to user data via a Model type. This
/// is useful for sketches where you don't require tracking any state.
pub fn sketch(mut self, sketch_fn: SketchFn) -> Self {
self.user_functions.view = Some(View::Sketch(sketch_fn));
self
}
/// The **view** function that the app will call to allow you to present your Model to the
/// surface of the window on your display.
pub fn view<M>(mut self, view_fn: ViewFn<M>) -> Self
where
M: 'static,
{
self.user_functions.view = Some(View::WithModel(ViewFnAny::from_fn_ptr(view_fn)));
self
}
/// The **view** function that the app will call to allow you to present your Model to the
/// surface of the window on your display.
///
/// Unlike the **ViewFn**, the **RawViewFn** provides a **RawFrame** that is designed for
/// drawing directly to a window's swap chain images, rather than to a convenient intermediary
/// image.
pub fn raw_view<M>(mut self, raw_view_fn: RawViewFn<M>) -> Self
where
M: 'static,
{
self.user_functions.view = Some(View::WithModelRaw(RawViewFnAny::from_fn_ptr(raw_view_fn)));
self
}
/// A function for updating your model on `WindowEvent`s associated with this window.
///
/// These include events such as key presses, mouse movement, clicks, resizing, etc.
///
/// ## Event Function Call Order
///
/// In nannou, if multiple functions require being called for a single kind of event, the more
/// general event function will always be called before the more specific event function.
///
/// If an `event` function was also submitted to the `App`, that function will always be called
/// immediately before window-specific event functions. Similarly, if a function associated
/// with a more specific event type (e.g. `key_pressed`) was given, that function will be
/// called *after* this function will be called.
///
/// ## Specific Events Variants
///
/// Note that if you only care about a certain kind of event, you can submit a function that
/// only gets called for that specific event instead. For example, if you only care about key
/// presses, you may wish to use the `key_pressed` method instead.
pub fn event<M>(mut self, event_fn: EventFn<M>) -> Self
where
M: 'static,
{
self.user_functions.event = Some(EventFnAny::from_fn_ptr(event_fn));
self
}
/// The same as the `event` method, but allows for processing raw `winit::event::WindowEvent`s rather
/// than Nannou's simplified `event::WindowEvent`s.
///
/// ## Event Function Call Order
///
/// If both `raw_event` and `event` functions have been provided, the given `raw_event`
/// function will always be called immediately before the given `event` function.
pub fn raw_event<M>(mut self, raw_event_fn: RawEventFn<M>) -> Self
where
M: 'static,
{
self.user_functions.raw_event = Some(RawEventFnAny::from_fn_ptr(raw_event_fn));
self
}
/// A function for processing key press events associated with this window.
pub fn key_pressed<M>(mut self, f: KeyPressedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.key_pressed = Some(KeyPressedFnAny::from_fn_ptr(f));
self
}
/// A function for processing key release events associated with this window.
pub fn key_released<M>(mut self, f: KeyReleasedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.key_released = Some(KeyReleasedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse moved events associated with this window.
pub fn mouse_moved<M>(mut self, f: MouseMovedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_moved = Some(MouseMovedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse pressed events associated with this window.
pub fn mouse_pressed<M>(mut self, f: MousePressedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_pressed = Some(MousePressedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse released events associated with this window.
pub fn mouse_released<M>(mut self, f: MouseReleasedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_released = Some(MouseReleasedFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse wheel events associated with this window.
pub fn mouse_wheel<M>(mut self, f: MouseWheelFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_wheel = Some(MouseWheelFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse entered events associated with this window.
pub fn mouse_entered<M>(mut self, f: MouseEnteredFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_entered = Some(MouseEnteredFnAny::from_fn_ptr(f));
self
}
/// A function for processing mouse exited events associated with this window.
pub fn mouse_exited<M>(mut self, f: MouseExitedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.mouse_exited = Some(MouseExitedFnAny::from_fn_ptr(f));
self
}
/// A function for processing touch events associated with this window.
pub fn touch<M>(mut self, f: TouchFn<M>) -> Self
where
M: 'static,
{
self.user_functions.touch = Some(TouchFnAny::from_fn_ptr(f));
self
}
/// A function for processing touchpad pressure events associated with this window.
pub fn touchpad_pressure<M>(mut self, f: TouchpadPressureFn<M>) -> Self
where
M: 'static,
{
self.user_functions.touchpad_pressure = Some(TouchpadPressureFnAny::from_fn_ptr(f));
self
}
/// A function for processing window moved events associated with this window.
pub fn moved<M>(mut self, f: MovedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.moved = Some(MovedFnAny::from_fn_ptr(f));
self
}
/// A function for processing window resized events associated with this window.
pub fn resized<M>(mut self, f: ResizedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.resized = Some(ResizedFnAny::from_fn_ptr(f));
self
}
/// A function for processing hovered file events associated with this window.
pub fn hovered_file<M>(mut self, f: HoveredFileFn<M>) -> Self
where
M: 'static,
{
self.user_functions.hovered_file = Some(HoveredFileFnAny::from_fn_ptr(f));
self
}
/// A function for processing hovered file cancelled events associated with this window.
pub fn hovered_file_cancelled<M>(mut self, f: HoveredFileCancelledFn<M>) -> Self
where
M: 'static,
{
self.user_functions.hovered_file_cancelled =
Some(HoveredFileCancelledFnAny::from_fn_ptr(f));
self
}
/// A function for processing dropped file events associated with this window.
pub fn dropped_file<M>(mut self, f: DroppedFileFn<M>) -> Self
where
M: 'static,
{
self.user_functions.dropped_file = Some(DroppedFileFnAny::from_fn_ptr(f));
self
}
/// A function for processing the focused event associated with this window.
pub fn focused<M>(mut self, f: FocusedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.focused = Some(FocusedFnAny::from_fn_ptr(f));
self
}
/// A function for processing the unfocused event associated with this window.
pub fn unfocused<M>(mut self, f: UnfocusedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.unfocused = Some(UnfocusedFnAny::from_fn_ptr(f));
self
}
/// A function for processing the window closed event associated with this window.
pub fn closed<M>(mut self, f: ClosedFn<M>) -> Self
where
M: 'static,
{
self.user_functions.closed = Some(ClosedFnAny::from_fn_ptr(f));
self
}
/// Builds the window, inserts it into the `App`'s display map and returns the unique ID.
pub fn build(self) -> Result<Id, BuildError> {
let Builder {
app,
mut window,
title_was_set,
swap_chain_builder,
request_adapter_opts,
device_desc,
user_functions,
msaa_samples,
} = self;
// If the title was not set, default to the "nannou - <exe_name>".
if !title_was_set {
if let Ok(exe_path) = env::current_exe() {
if let Some(os_str) = exe_path.file_stem() {
if let Some(exe_name) = os_str.to_str() {
let title = format!("nannou - {}", exe_name);
window = window.with_title(title);
}
}
}
}
// Set default dimensions in the case that none were given.
let initial_window_size = window
.window
.inner_size
.or_else(|| {
window
.window
.fullscreen
.as_ref()
.map(|fullscreen| match fullscreen {
winit::window::Fullscreen::Exclusive(video_mode) => {
let monitor = video_mode.monitor();
video_mode
.size()
.to_logical::<f32>(monitor.scale_factor())
.into()
}
winit::window::Fullscreen::Borderless(monitor) => monitor
.size()
.to_logical::<f32>(monitor.scale_factor())
.into(),
})
})
.unwrap_or_else(|| {
let mut dim = DEFAULT_DIMENSIONS;
if let Some(min) = window.window.min_inner_size {
match min {
winit::dpi::Size::Logical(min) => {
dim.width = dim.width.max(min.width as _);
dim.height = dim.height.max(min.height as _);
}
winit::dpi::Size::Physical(min) => {
dim.width = dim.width.max(min.width as _);
dim.height = dim.height.max(min.height as _);
unimplemented!("consider scale factor");
}
}
}
if let Some(max) = window.window.max_inner_size {
match max {
winit::dpi::Size::Logical(max) => {
dim.width = dim.width.min(max.width as _);
dim.height = dim.height.min(max.height as _);
}
winit::dpi::Size::Physical(max) => {
dim.width = dim.width.min(max.width as _);
dim.height = dim.height.min(max.height as _);
unimplemented!("consider scale factor");
}
}
}
dim.into()
});
// Use the `initial_swapchain_dimensions` as the default dimensions for the window if none
// were specified.
if window.window.inner_size.is_none() && window.window.fullscreen.is_none() {
window.window.inner_size = Some(initial_window_size);
}
// Build the window.
let window = {
let window_target = app
.event_loop_window_target
.as_ref()
.expect("unexpected invalid App.event_loop_window_target state - please report")
.as_ref();
window.build(window_target)?
};
// Build the wgpu surface.
let surface = wgpu::Surface::create(&window);
// Request the adapter.
let request_adapter_opts =
request_adapter_opts.unwrap_or(wgpu::DEFAULT_ADAPTER_REQUEST_OPTIONS);
let adapter = app
.wgpu_adapters()
.get_or_request(request_adapter_opts)
.ok_or(BuildError::NoAvailableAdapter)?;
// Instantiate the logical device.
let device_desc = device_desc.unwrap_or_else(wgpu::default_device_descriptor);
let device_queue_pair = adapter.get_or_request_device(device_desc);
// Build the swapchain.
let win_physical_size = window.inner_size();
let win_dims_px: [u32; 2] = win_physical_size.into();
let device = device_queue_pair.device();
let (swap_chain, swap_chain_desc) =
swap_chain_builder.build(&device, &surface, win_dims_px);
// If we're using an intermediary image for rendering frames to swap_chain images, create
// the necessary render data.
let (frame_data, msaa_samples) = match user_functions.view {
Some(View::WithModel(_)) | Some(View::Sketch(_)) | None => {
let msaa_samples = msaa_samples.unwrap_or(Frame::DEFAULT_MSAA_SAMPLES);
// TODO: Verity that requested sample count is valid for surface?
let swap_chain_dims = [swap_chain_desc.width, swap_chain_desc.height];
let render = frame::RenderData::new(
&device,
swap_chain_dims,
swap_chain_desc.format,
msaa_samples,
);
let capture = frame::CaptureData::default();
let frame_data = FrameData { render, capture };
(Some(frame_data), msaa_samples)
}
Some(View::WithModelRaw(_)) => (None, 1),
};
let window_id = window.id();
let frame_count = 0;
let swap_chain = WindowSwapChain {
descriptor: swap_chain_desc,
swap_chain: Some(swap_chain),
};
let tracked_state = TrackedState {
scale_factor: window.scale_factor(),
physical_size: win_physical_size,
};
let window = Window {
window,
surface,
device_queue_pair,
msaa_samples,
swap_chain,
frame_data,
frame_count,
user_functions,
tracked_state,
};
app.windows.borrow_mut().insert(window_id, window);
// If this is the first window, set it as the app's "focused" window.
if app.windows.borrow().len() == 1 {
*app.focused_window.borrow_mut() = Some(window_id);
}
Ok(window_id)
}
fn map_window<F>(self, map: F) -> Self
where
F: FnOnce(winit::window::WindowBuilder) -> winit::window::WindowBuilder,
{
let Builder {
app,
window,
title_was_set,
device_desc,
request_adapter_opts,
swap_chain_builder,
user_functions,
msaa_samples,
} = self;
let window = map(window);
Builder {
app,
window,
title_was_set,
device_desc,
request_adapter_opts,
swap_chain_builder,
user_functions,
msaa_samples,
}
}
// Window builder methods.
//
// NOTE: On new versions of winit, we should check whether or not new `WindowBuilder` methods
// have been added that we should expose.
/// Requests the window to be a specific size in points.
///
/// This describes to the "inner" part of the window, not including desktop decorations like the
/// title bar.
pub fn size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Set the minimum size in points for the window.
pub fn min_size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_min_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Set the maximum size in points for the window.
pub fn max_size(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_max_inner_size(winit::dpi::LogicalSize { width, height }))
}
/// Requests the window to be a specific size in points.
///
/// This describes to the "inner" part of the window, not including desktop decorations like the
/// title bar.
pub fn size_pixels(self, width: u32, height: u32) -> Self {
self.map_window(|w| w.with_inner_size(winit::dpi::PhysicalSize { width, height }))
}
/// Whether or not the window should be resizable after creation.
pub fn resizble(self, resizable: bool) -> Self {
self.map_window(|w| w.with_resizable(resizable))
}
/// Requests a specific title for the window.
pub fn title<T>(mut self, title: T) -> Self
where
T: Into<String>,
{
self.title_was_set = true;
self.map_window(|w| w.with_title(title))
}
/// Sets the window fullscreen state.
///
/// None means a normal window, Some(MonitorId) means a fullscreen window on that specific
/// monitor.
pub fn fullscreen(self, fullscreen: Option<winit::window::Fullscreen>) -> Self {
self.map_window(|w| w.with_fullscreen(fullscreen))
}
/// Requests maximized mode.
pub fn maximized(self, maximized: bool) -> Self {
self.map_window(|w| w.with_maximized(maximized))
}
/// Sets whether the window will be initially hidden or visible.
pub fn visible(self, visible: bool) -> Self {
self.map_window(|w| w.with_visible(visible))
}
/// Sets whether the background of the window should be transparent.
pub fn transparent(self, transparent: bool) -> Self {
self.map_window(|w| w.with_transparent(transparent))
}
/// Sets whether the window should have a border, a title bar, etc.
pub fn decorations(self, decorations: bool) -> Self {
self.map_window(|w| w.with_decorations(decorations))
}
/// Sets whether or not the window will always be on top of other windows.
pub fn always_on_top(self, always_on_top: bool) -> Self {
self.map_window(|w| w.with_always_on_top(always_on_top))
}
/// Sets the window icon.
pub fn window_icon(self, window_icon: Option<winit::window::Icon>) -> Self {
self.map_window(|w| w.with_window_icon(window_icon))
}
}
impl Window {
// `winit::window::Window` methods.
//
// NOTE: On new versions of winit, we should check whether or not new `Window` methods have
// been added that we should expose. Most of the following method docs are copied from the
// winit documentation. It would be nice if we could automate this inlining somehow.
/// A unique identifier associated with this window.
pub fn id(&self) -> Id {
self.window.id()
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels and vice
/// versa.
///
/// Throughout nannou, you will see "logical pixels" referred to as "points", and "physical
/// pixels" referred to as "pixels".
///
/// This is typically `1.0` for a normal display, `2.0` for a retina display and higher on more
/// modern displays.
///
/// You can read more about what this scale factor means within winit's [dpi module
/// documentation](https://docs.rs/winit/latest/winit/dpi/index.html).
///
/// ## Platform-specific
///
/// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_X11_SCALE_FACTOR`
/// environment variable.
/// - **Android:** Always returns 1.0.
/// - **iOS:** Can only be called on the main thread. Returns the underlying `UiView`'s
/// `contentScaleFactor`.
pub fn scale_factor(&self) -> geom::scalar::Default {
self.window.scale_factor() as _
}
/// The position of the top-left hand corner of the window relative to the top-left hand corner
/// of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as the
/// screen. If the user uses a desktop with multiple monitors, the top-left hand corner of the
/// desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside of the
/// visible screen region.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the
/// window in the screen space coordinate system.
/// - **Web:** Returns the top-left coordinates relative to the viewport.
pub fn outer_position_pixels(&self) -> Result<(i32, i32), winit::error::NotSupportedError> {
self.window.outer_position().map(Into::into)
}
/// Modifies the position of the window.
///
/// See `outer_position_pixels` for more information about the returned coordinates. This
/// automatically un-maximizes the window if it is maximized.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Sets the top left coordinates of the
/// window in the screen space coordinate system.
/// - **Web:** Sets the top-left coordinates relative to the viewport.
pub fn set_outer_position_pixels(&self, x: i32, y: i32) {
self.window
.set_outer_position(winit::dpi::PhysicalPosition { x, y })
}
/// The width and height in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
pub fn inner_size_pixels(&self) -> (u32, u32) {
self.window.inner_size().into()
}
/// The width and height in points of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
///
/// This is the same as dividing the result of `inner_size_pixels()` by `scale_factor()`.
pub fn inner_size_points(&self) -> (geom::scalar::Default, geom::scalar::Default) {
self.window
.inner_size()
.to_logical::<f32>(self.tracked_state.scale_factor)
.into()
}
/// Modifies the inner size of the window.
///
/// See the `inner_size` methods for more informations about the values.
pub fn set_inner_size_pixels(&self, width: u32, height: u32) {
self.window
.set_inner_size(winit::dpi::PhysicalSize { width, height })
}
/// Modifies the inner size of the window using point values.
///
/// See the `inner_size` methods for more informations about the values.
pub fn set_inner_size_points(&self, width: f32, height: f32) {
self.window
.set_inner_size(winit::dpi::LogicalSize { width, height })
}
/// The width and height of the window in pixels.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// `inner_size_pixels` instead.
pub fn outer_size_pixels(&self) -> (u32, u32) {
self.window.outer_size().into()
}
/// The width and height of the window in points.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// `inner_size_points` instead.
///
/// This is the same as dividing the result of `outer_size_pixels()` by `scale_factor()`.
pub fn outer_size_points(&self) -> (f32, f32) {
self.window
.outer_size()
.to_logical::<f32>(self.tracked_state.scale_factor)
.into()
}
/// Sets a minimum size for the window.
pub fn set_min_inner_size_points(&self, size: Option<(f32, f32)>) {
let size = size.map(|(width, height)| winit::dpi::LogicalSize { width, height });
self.window.set_min_inner_size(size)
}
/// Sets a maximum size for the window.
pub fn set_max_inner_size_points(&self, size: Option<(f32, f32)>) {
let size = size.map(|(width, height)| winit::dpi::LogicalSize { width, height });
self.window.set_max_inner_size(size)
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
pub fn set_title(&self, title: &str) {
self.window.set_title(title);
}
/// Set the visibility of the window.
///
/// ## Platform-specific
///
/// - Android: Has no effect.
/// - iOS: Can only be called on the main thread.
/// - Web: Has no effect.
pub fn set_visible(&self, visible: bool) {
self.window.set_visible(visible)
}
/// Sets whether the window is resizable or not.
///
/// Note that making the window unresizable doesn't exempt you from handling **Resized**, as
/// that event can still be triggered by DPI scaling, entering fullscreen mode, etc.
pub fn set_resizable(&self, resizable: bool) {
self.window.set_resizable(resizable)
}
/// Sets the window to minimized or back.
pub fn set_minimized(&self, minimized: bool) {
self.window.set_minimized(minimized)
}
/// Sets the window to maximized or back.
pub fn set_maximized(&self, maximized: bool) {
self.window.set_maximized(maximized)
}
/// Set the window to fullscreen.
///
/// Call this method again with `None` to revert back from fullscreen.
///
/// ## Platform-specific
///
/// - macOS: `Fullscreen::Exclusive` provides true exclusive mode with a video mode change.
/// Caveat! macOS doesn't provide task switching (or spaces!) while in exclusive fullscreen
/// mode. This mode should be used when a video mode change is desired, but for a better user
/// experience, borderless fullscreen might be preferred.
///
/// `Fullscreen::Borderless` provides a borderless fullscreen window on a separate space.
/// This is the idiomatic way for fullscreen games to work on macOS. See
/// WindowExtMacOs::set_simple_fullscreen if separate spaces are not preferred.
///
/// The dock and the menu bar are always disabled in fullscreen mode.
///
/// - iOS: Can only be called on the main thread.
/// - Wayland: Does not support exclusive fullscreen mode.
/// - Windows: Screen saver is disabled in fullscreen mode.
pub fn set_fullscreen(&self, monitor: Option<winit::window::Fullscreen>) {
self.window.set_fullscreen(monitor)
}
/// Gets the window's current fullscreen state.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread.
pub fn fullscreen(&self) -> Option<winit::window::Fullscreen> {
self.window.fullscreen()
}
/// Turn window decorations on or off.
///
/// ## Platform-specific
///
/// - **iOS:** Can only be called on the main thread. Controls whether the status bar is hidden
/// via `setPrefersStatusBarHidden`.
/// - **Web:** Has no effect.
pub fn set_decorations(&self, decorations: bool) {
self.window.set_decorations(decorations)
}
/// Change whether or not the window will always be on top of other windows.
pub fn set_always_on_top(&self, always_on_top: bool) {
self.window.set_always_on_top(always_on_top)
}
/// Sets the window icon. On Windows and X11, this is typically the small icon in the top-left
/// corner of the titlebar.
///
/// ## Platform-specific
///
/// This only has effect on Windows and X11.
///
/// On Windows, this sets ICON_SMALL. The base size for a window icon is 16x16, but it's
/// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32.
///
/// X11 has no universal guidelines for icon sizes, so you're at the whims of the WM. That
/// said, it's usually in the same ballpark as on Windows.
pub fn set_window_icon(&self, window_icon: Option<winit::window::Icon>) {
self.window.set_window_icon(window_icon)
}
/// Sets the location of IME candidate box in client area coordinates relative to the top left.
///
/// ## Platform-specific
///
/// - **iOS:** Has no effect.
/// - **Web:** Has no effect.
pub fn set_ime_position_points(&self, x: f32, y: f32) {
self.window
.set_ime_position(winit::dpi::LogicalPosition { x, y })
}
/// Modifies the mouse cursor of the window.
///
/// ## Platform-specific
///
/// - **iOS:** Has no effect.
/// - **Android:** Has no effect.
pub fn set_cursor_icon(&self, state: winit::window::CursorIcon) {
self.window.set_cursor_icon(state);
}
/// Changes the position of the cursor in logical window coordinates.
///
/// ## Platform-specific
///
/// - **iOS:** Always returns an `Err`.
/// - **Web:** Has no effect.
pub fn set_cursor_position_points(
&self,
x: f32,
y: f32,
) -> Result<(), winit::error::ExternalError> {
self.window
.set_cursor_position(winit::dpi::LogicalPosition { x, y })
}
/// Grabs the cursor, preventing it from leaving the window.
///
/// ## Platform-specific
///
/// - **macOS:** Locks the cursor in a fixed location.
/// - **Wayland:** Locks the cursor in a fixed location.
/// - **Android:** Has no effect.
/// - **iOS:** Always returns an Err.
/// - **Web:** Has no effect.
pub fn set_cursor_grab(&self, grab: bool) -> Result<(), winit::error::ExternalError> {
self.window.set_cursor_grab(grab)
}
/// Set the cursor's visibility.
///
/// If `false`, hides the cursor. If `true`, shows the cursor.
///
/// ## Platform-specific
///
/// On **Windows**, **X11** and **Wayland**, the cursor is only hidden within the confines of
/// the window.
///
/// On **macOS**, the cursor is hidden as long as the window has input focus, even if the
/// cursor is outside of the window.
///
/// This has no effect on **Android** or **iOS**.
pub fn set_cursor_visible(&self, visible: bool) {
self.window.set_cursor_visible(visible)
}
/// The current monitor that the window is on or the primary monitor if nothing matches.
pub fn current_monitor(&self) -> winit::monitor::MonitorHandle {
self.window.current_monitor()
}
// Access to wgpu API.
/// Returns a reference to the window's wgpu swap chain surface.
pub fn surface(&self) -> &wgpu::Surface {
&self.surface
}
/// The descriptor for the swap chain associated with this window's wgpu surface.
pub fn swap_chain_descriptor(&self) -> &wgpu::SwapChainDescriptor {
&self.swap_chain.descriptor
}
/// The wgpu logical device on which the window's swap chain is running.
///
/// This is shorthand for `DeviceOwned::device(window.swap_chain())`.
pub fn swap_chain_device(&self) -> &wgpu::Device {
self.device_queue_pair.device()
}
/// The wgpu graphics queue on which the window swap chain work is run.
///
/// The queue is guarded by a `Mutex` in order to synchronise submissions of command buffers in
/// cases that the queue is shared between more than one window.
pub fn swap_chain_queue(&self) -> &Mutex<wgpu::Queue> {
self.device_queue_pair.queue()
}
/// Provides access to the device queue pair and the `Arc` behind which it is stored. This can
/// be useful in cases where using references provided by the `swap_chain_device` or
/// `swap_chain_queue` methods cause awkward ownership problems.
pub fn swap_chain_device_queue_pair(&self) -> &Arc<wgpu::DeviceQueuePair> {
&self.device_queue_pair
}
/// The number of samples used in the MSAA for the image associated with the `view` function's
/// `Frame` type.
///
/// **Note:** If the user specified a `raw_view` function rather than a `view` function, this
/// value will always return `1`.
pub fn msaa_samples(&self) -> u32 {
self.msaa_samples
}
// Custom methods.
// A utility function to simplify the recreation of a swap_chain.
pub(crate) fn rebuild_swap_chain(&mut self, size_px: [u32; 2]) {
std::mem::drop(self.swap_chain.swap_chain.take());
let [width, height] = size_px;
self.swap_chain.descriptor.width = width;
self.swap_chain.descriptor.height = height;
self.swap_chain.swap_chain = Some(
self.swap_chain_device()
.create_swap_chain(&self.surface, &self.swap_chain.descriptor),
);
if self.frame_data.is_some() {
let render_data = frame::RenderData::new(
self.swap_chain_device(),
size_px,
self.swap_chain.descriptor.format,
self.msaa_samples,
);
self.frame_data.as_mut().unwrap().render = render_data;
}
}
/// Attempts to determine whether or not the window is currently fullscreen.
pub fn is_fullscreen(&self) -> bool {
self.fullscreen().is_some()
}
/// The number of times `view` has been called with a `Frame` for this window.
pub fn elapsed_frames(&self) -> u64 {
self.frame_count
}
/// The rectangle representing the position and dimensions of the window.
///
/// The window's position will always be `[0.0, 0.0]`, as positions are generally described
/// relative to the centre of the window itself.
///
/// The dimensions will be equal to the result of `inner_size_points`. This represents the area
/// of the that we can draw to in a DPI-agnostic manner, typically useful for drawing and UI
/// positioning.
pub fn rect(&self) -> geom::Rect {
let (w, h) = self.inner_size_points();
geom::Rect::from_w_h(w, h)
}
/// Capture the next frame right before it is drawn to this window and write it to an image
/// file at the given path. If a frame already exists, it will be captured before its `submit`
/// method is called or before it is `drop`ped.
///
/// The destination image file type will be inferred from the extension given in the path.
///
pub fn capture_frame<P>(&self, path: P)
where
P: AsRef<Path>,
{
self.capture_frame_with_threaded(path.as_ref(), false);
}
/// The same as **capture_frame**, but uses a separate pool of threads for writing image files
/// in order to free up the main application thread.
///
/// Note that if you are capturing every frame and your window size is very large or the file
/// type you are writing to is expensive to encode, this capturing thread may fall behind the
/// main thread, resulting in a large delay before the exiting the program. This is because the
/// capturing thread needs more time to write the captured images.
pub fn capture_frame_threaded<P>(&self, path: P)
where
P: AsRef<Path>,
{
let path = path.as_ref();
self.capture_frame_with_threaded(path.as_ref(), false);
}
fn capture_frame_with_threaded(&self, path: &Path, threaded: bool) {
// If the parent directory does not exist, create it.
let dir = path.parent().expect("capture_frame path has no directory");
if !dir.exists() {
std::fs::create_dir_all(&dir).expect("failed to create `capture_frame` directory");
}
let mut capture_next_frame_path = self
.frame_data
.as_ref()
.expect("window capture requires that `view` draws to a `Frame` (not a `RawFrame`)")
.capture
.next_frame_path
.lock()
.expect("failed to lock `capture_next_frame_path`");
*capture_next_frame_path = Some((path.to_path_buf(), threaded));
}
}
// Debug implementations for function wrappers.
impl fmt::Debug for View {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let variant = match *self {
View::WithModel(ref v) => format!("WithModel({:?})", v),
View::WithModelRaw(ref v) => format!("WithModelRaw({:?})", v),
View::Sketch(_) => "Sketch".to_string(),
};
write!(f, "View::{}", variant)
}
}
// Deref implementations.
impl fmt::Debug for WindowSwapChain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"WindowSwapChain ( descriptor: {:?}, swap_chain: {:?} )",
self.descriptor, self.swap_chain,
)
}
}
// Error implementations.
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BuildError::NoAvailableAdapter => write!(f, "no available wgpu adapter detected"),
BuildError::WinitOsError(ref e) => e.fmt(f),
}
}
}
impl From<winit::error::OsError> for BuildError {
fn from(e: winit::error::OsError) -> Self {
BuildError::WinitOsError(e)
}
}
|
//! Formats a DOM structure to a Writer
//!
//! ### Example
//! ```
//! use document::Package;
//! use document::writer::format_document;
//!
//! let package = Package::new();
//! let doc = package.as_document();
//!
//! let hello = doc.create_element("hello");
//! hello.set_attribute_value("planet", "Earth");
//! doc.root().append_child(hello);
//!
//! let mut output = std::io::stdio::stdout();
//! format_document(&doc, &mut output).ok().expect("unable to output XML");
//! ```
//!
//! ### Known issues
//!
//! Output is not escaped in any way,
//! it's very easy to create malformed XML!
//!
//! ### Potential options to support
//!
//! - Space before `/>`
//! - Single vs double quotes
//! - Fixed ordering of attributes
use std::io::IoResult;
use self::Content::*;
use super::dom4;
use super::dom4::ChildOfElement::*;
use super::dom4::ChildOfRoot::*;
enum Content<'d> {
Element(dom4::Element<'d>),
ElementEnd(dom4::Element<'d>),
Text(dom4::Text<'d>),
Comment(dom4::Comment<'d>),
ProcessingInstruction(dom4::ProcessingInstruction<'d>),
}
fn format_element<'d, W : Writer>(element: dom4::Element<'d>, todo: &mut Vec<Content<'d>>, writer: &mut W) -> IoResult<()> {
try!(write!(writer, "<{}", element.name()));
for attr in element.attributes().iter() {
try!(write!(writer, " {}='{}'", attr.name(), attr.value()));
}
let mut children = element.children();
if children.is_empty() {
writer.write_str("/>")
} else {
try!(writer.write_str(">"));
todo.push(ElementEnd(element));
children.reverse();
let x = children.into_iter().map(|c| match c {
ElementCOE(element) => Element(element),
TextCOE(t) => Text(t),
CommentCOE(c) => Comment(c),
ProcessingInstructionCOE(p) => ProcessingInstruction(p),
});
todo.extend(x);
Ok(())
}
}
fn format_comment<W : Writer>(comment: dom4::Comment, writer: &mut W) -> IoResult<()> {
write!(writer, "<!--{}-->", comment.text())
}
fn format_processing_instruction<W : Writer>(pi: dom4::ProcessingInstruction, writer: &mut W) -> IoResult<()> {
match pi.value() {
None => write!(writer, "<?{}?>", pi.target()),
Some(v) => write!(writer, "<?{} {}?>", pi.target(), v),
}
}
fn format_one<'d, W : Writer>(content: Content<'d>, todo: &mut Vec<Content<'d>>, writer: &mut W) -> IoResult<()> {
match content {
Element(e) => format_element(e, todo, writer),
ElementEnd(e) => write!(writer, "</{}>", e.name()),
Text(t) => writer.write_str(t.text().as_slice()),
Comment(c) => format_comment(c, writer),
ProcessingInstruction(p) => format_processing_instruction(p, writer),
}
}
fn format_body<W : Writer>(element: dom4::Element, writer: &mut W) -> IoResult<()> {
let mut todo = vec![Element(element)];
while ! todo.is_empty() {
try!(format_one(todo.pop().unwrap(), &mut todo, writer));
}
Ok(())
}
/// Formats a document into a Writer
pub fn format_document<'d, W : Writer>(doc: &'d dom4::Document<'d>, writer: &mut W) -> IoResult<()> {
try!(writer.write_str("<?xml version='1.0'?>"));
for child in doc.root().children().into_iter() {
try!(match child {
ElementCOR(e) => format_body(e, writer),
CommentCOR(c) => format_comment(c, writer),
ProcessingInstructionCOR(p) => format_processing_instruction(p, writer),
})
}
Ok(())
}
#[cfg(test)]
mod test {
use std::io::MemWriter;
use super::super::Package;
use super::super::dom4;
use super::format_document;
macro_rules! assert_str_eq(
($l:expr, $r:expr) => (assert_eq!($l.as_slice(), $r.as_slice()));
)
fn format_xml<'d>(doc: &'d dom4::Document<'d>) -> String {
let mut w = MemWriter::new();
format_document(doc, &mut w).ok().expect("Not formatted");
String::from_utf8(w.unwrap()).ok().expect("Not a string")
}
#[test]
fn top_element() {
let p = Package::new();
let d = p.as_document();
let e = d.create_element("hello");
d.root().append_child(e);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello/>");
}
#[test]
fn element_with_attributes() {
let p = Package::new();
let d = p.as_document();
let e = d.create_element("hello");
e.set_attribute_value("a", "b");
d.root().append_child(e);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello a='b'/>");
}
#[test]
fn nested_element() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let world = d.create_element("world");
hello.append_child(world);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><world/></hello>");
}
#[test]
fn nested_text() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let text = d.create_text("A fine day to you!");
hello.append_child(text);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello>A fine day to you!</hello>");
}
#[test]
fn nested_comment() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let comment = d.create_comment(" Fill this in ");
hello.append_child(comment);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><!-- Fill this in --></hello>");
}
#[test]
fn nested_processing_instruction_without_value() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let pi = d.create_processing_instruction("display", None);
hello.append_child(pi);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><?display?></hello>");
}
#[test]
fn nested_processing_instruction_with_value() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let pi = d.create_processing_instruction("display", Some("screen"));
hello.append_child(pi);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><?display screen?></hello>");
}
#[test]
fn top_level_comment() {
let p = Package::new();
let d = p.as_document();
let comment = d.create_comment(" Fill this in ");
d.root().append_child(comment);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><!-- Fill this in -->");
}
#[test]
fn top_level_processing_instruction() {
let p = Package::new();
let d = p.as_document();
let pi = d.create_processing_instruction("display", None);
d.root().append_child(pi);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><?display?>");
}
}
Update deprecated MemWriter::unwrap
//! Formats a DOM structure to a Writer
//!
//! ### Example
//! ```
//! use document::Package;
//! use document::writer::format_document;
//!
//! let package = Package::new();
//! let doc = package.as_document();
//!
//! let hello = doc.create_element("hello");
//! hello.set_attribute_value("planet", "Earth");
//! doc.root().append_child(hello);
//!
//! let mut output = std::io::stdio::stdout();
//! format_document(&doc, &mut output).ok().expect("unable to output XML");
//! ```
//!
//! ### Known issues
//!
//! Output is not escaped in any way,
//! it's very easy to create malformed XML!
//!
//! ### Potential options to support
//!
//! - Space before `/>`
//! - Single vs double quotes
//! - Fixed ordering of attributes
use std::io::IoResult;
use self::Content::*;
use super::dom4;
use super::dom4::ChildOfElement::*;
use super::dom4::ChildOfRoot::*;
enum Content<'d> {
Element(dom4::Element<'d>),
ElementEnd(dom4::Element<'d>),
Text(dom4::Text<'d>),
Comment(dom4::Comment<'d>),
ProcessingInstruction(dom4::ProcessingInstruction<'d>),
}
fn format_element<'d, W : Writer>(element: dom4::Element<'d>, todo: &mut Vec<Content<'d>>, writer: &mut W) -> IoResult<()> {
try!(write!(writer, "<{}", element.name()));
for attr in element.attributes().iter() {
try!(write!(writer, " {}='{}'", attr.name(), attr.value()));
}
let mut children = element.children();
if children.is_empty() {
writer.write_str("/>")
} else {
try!(writer.write_str(">"));
todo.push(ElementEnd(element));
children.reverse();
let x = children.into_iter().map(|c| match c {
ElementCOE(element) => Element(element),
TextCOE(t) => Text(t),
CommentCOE(c) => Comment(c),
ProcessingInstructionCOE(p) => ProcessingInstruction(p),
});
todo.extend(x);
Ok(())
}
}
fn format_comment<W : Writer>(comment: dom4::Comment, writer: &mut W) -> IoResult<()> {
write!(writer, "<!--{}-->", comment.text())
}
fn format_processing_instruction<W : Writer>(pi: dom4::ProcessingInstruction, writer: &mut W) -> IoResult<()> {
match pi.value() {
None => write!(writer, "<?{}?>", pi.target()),
Some(v) => write!(writer, "<?{} {}?>", pi.target(), v),
}
}
fn format_one<'d, W : Writer>(content: Content<'d>, todo: &mut Vec<Content<'d>>, writer: &mut W) -> IoResult<()> {
match content {
Element(e) => format_element(e, todo, writer),
ElementEnd(e) => write!(writer, "</{}>", e.name()),
Text(t) => writer.write_str(t.text().as_slice()),
Comment(c) => format_comment(c, writer),
ProcessingInstruction(p) => format_processing_instruction(p, writer),
}
}
fn format_body<W : Writer>(element: dom4::Element, writer: &mut W) -> IoResult<()> {
let mut todo = vec![Element(element)];
while ! todo.is_empty() {
try!(format_one(todo.pop().unwrap(), &mut todo, writer));
}
Ok(())
}
/// Formats a document into a Writer
pub fn format_document<'d, W : Writer>(doc: &'d dom4::Document<'d>, writer: &mut W) -> IoResult<()> {
try!(writer.write_str("<?xml version='1.0'?>"));
for child in doc.root().children().into_iter() {
try!(match child {
ElementCOR(e) => format_body(e, writer),
CommentCOR(c) => format_comment(c, writer),
ProcessingInstructionCOR(p) => format_processing_instruction(p, writer),
})
}
Ok(())
}
#[cfg(test)]
mod test {
use std::io::MemWriter;
use super::super::Package;
use super::super::dom4;
use super::format_document;
macro_rules! assert_str_eq(
($l:expr, $r:expr) => (assert_eq!($l.as_slice(), $r.as_slice()));
)
fn format_xml<'d>(doc: &'d dom4::Document<'d>) -> String {
let mut w = MemWriter::new();
format_document(doc, &mut w).ok().expect("Not formatted");
String::from_utf8(w.into_inner()).ok().expect("Not a string")
}
#[test]
fn top_element() {
let p = Package::new();
let d = p.as_document();
let e = d.create_element("hello");
d.root().append_child(e);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello/>");
}
#[test]
fn element_with_attributes() {
let p = Package::new();
let d = p.as_document();
let e = d.create_element("hello");
e.set_attribute_value("a", "b");
d.root().append_child(e);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello a='b'/>");
}
#[test]
fn nested_element() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let world = d.create_element("world");
hello.append_child(world);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><world/></hello>");
}
#[test]
fn nested_text() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let text = d.create_text("A fine day to you!");
hello.append_child(text);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello>A fine day to you!</hello>");
}
#[test]
fn nested_comment() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let comment = d.create_comment(" Fill this in ");
hello.append_child(comment);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><!-- Fill this in --></hello>");
}
#[test]
fn nested_processing_instruction_without_value() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let pi = d.create_processing_instruction("display", None);
hello.append_child(pi);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><?display?></hello>");
}
#[test]
fn nested_processing_instruction_with_value() {
let p = Package::new();
let d = p.as_document();
let hello = d.create_element("hello");
let pi = d.create_processing_instruction("display", Some("screen"));
hello.append_child(pi);
d.root().append_child(hello);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><hello><?display screen?></hello>");
}
#[test]
fn top_level_comment() {
let p = Package::new();
let d = p.as_document();
let comment = d.create_comment(" Fill this in ");
d.root().append_child(comment);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><!-- Fill this in -->");
}
#[test]
fn top_level_processing_instruction() {
let p = Package::new();
let d = p.as_document();
let pi = d.create_processing_instruction("display", None);
d.root().append_child(pi);
let xml = format_xml(&d);
assert_str_eq!(xml, "<?xml version='1.0'?><?display?>");
}
}
|
use crate::core::compiler::{BuildConfig, MessageFormat};
use crate::core::Workspace;
use crate::ops::{CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
use crate::sources::CRATES_IO_REGISTRY;
use crate::util::important_paths::find_root_manifest_for_wd;
use crate::util::{paths, toml::TomlProfile, validate_package_name};
use crate::util::{
print_available_benches, print_available_binaries, print_available_examples,
print_available_tests,
};
use crate::CargoResult;
use clap::{self, SubCommand};
use failure::bail;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::PathBuf;
pub use crate::core::compiler::{CompileMode, ProfileKind};
pub use crate::{CliError, CliResult, Config};
pub use clap::{AppSettings, Arg, ArgMatches};
pub type App = clap::App<'static, 'static>;
pub trait AppExt: Sized {
fn _arg(self, arg: Arg<'static, 'static>) -> Self;
fn arg_package_spec(
self,
package: &'static str,
all: &'static str,
exclude: &'static str,
) -> Self {
self.arg_package_spec_simple(package)
._arg(opt("all", "Alias for --workspace (deprecated)"))
._arg(opt("workspace", all))
._arg(multi_opt("exclude", "SPEC", exclude))
}
fn arg_package_spec_simple(self, package: &'static str) -> Self {
self._arg(multi_opt("package", "SPEC", package).short("p"))
}
fn arg_package(self, package: &'static str) -> Self {
self._arg(opt("package", package).short("p").value_name("SPEC"))
}
fn arg_jobs(self) -> Self {
self._arg(
opt("jobs", "Number of parallel jobs, defaults to # of CPUs")
.short("j")
.value_name("N"),
)
}
fn arg_targets_all(
self,
lib: &'static str,
bin: &'static str,
bins: &'static str,
example: &'static str,
examples: &'static str,
test: &'static str,
tests: &'static str,
bench: &'static str,
benches: &'static str,
all: &'static str,
) -> Self {
self.arg_targets_lib_bin(lib, bin, bins)
._arg(optional_multi_opt("example", "NAME", example))
._arg(opt("examples", examples))
._arg(optional_multi_opt("test", "NAME", test))
._arg(opt("tests", tests))
._arg(optional_multi_opt("bench", "NAME", bench))
._arg(opt("benches", benches))
._arg(opt("all-targets", all))
}
fn arg_targets_lib_bin(self, lib: &'static str, bin: &'static str, bins: &'static str) -> Self {
self._arg(opt("lib", lib))
._arg(optional_multi_opt("bin", "NAME", bin))
._arg(opt("bins", bins))
}
fn arg_targets_bins_examples(
self,
bin: &'static str,
bins: &'static str,
example: &'static str,
examples: &'static str,
) -> Self {
self._arg(optional_multi_opt("bin", "NAME", bin))
._arg(opt("bins", bins))
._arg(optional_multi_opt("example", "NAME", example))
._arg(opt("examples", examples))
}
fn arg_targets_bin_example(self, bin: &'static str, example: &'static str) -> Self {
self._arg(optional_multi_opt("bin", "NAME", bin))
._arg(optional_multi_opt("example", "NAME", example))
}
fn arg_features(self) -> Self {
self._arg(multi_opt(
"features",
"FEATURES",
"Space-separated list of features to activate",
))
._arg(opt("all-features", "Activate all available features"))
._arg(opt(
"no-default-features",
"Do not activate the `default` feature",
))
}
fn arg_release(self, release: &'static str) -> Self {
self._arg(opt("release", release))
}
fn arg_profile(self, profile: &'static str) -> Self {
self._arg(opt("profile", profile).value_name("PROFILE-NAME"))
}
fn arg_doc(self, doc: &'static str) -> Self {
self._arg(opt("doc", doc))
}
fn arg_target_triple(self, target: &'static str) -> Self {
self._arg(opt("target", target).value_name("TRIPLE"))
}
fn arg_target_dir(self) -> Self {
self._arg(
opt("target-dir", "Directory for all generated artifacts").value_name("DIRECTORY"),
)
}
fn arg_manifest_path(self) -> Self {
self._arg(opt("manifest-path", "Path to Cargo.toml").value_name("PATH"))
}
fn arg_message_format(self) -> Self {
self._arg(multi_opt("message-format", "FMT", "Error format"))
}
fn arg_build_plan(self) -> Self {
self._arg(opt(
"build-plan",
"Output the build plan in JSON (unstable)",
))
}
fn arg_new_opts(self) -> Self {
self._arg(
opt(
"vcs",
"Initialize a new repository for the given version \
control system (git, hg, pijul, or fossil) or do not \
initialize any version control at all (none), overriding \
a global configuration.",
)
.value_name("VCS")
.possible_values(&["git", "hg", "pijul", "fossil", "none"]),
)
._arg(opt("bin", "Use a binary (application) template [default]"))
._arg(opt("lib", "Use a library template"))
._arg(
opt("edition", "Edition to set for the crate generated")
.possible_values(&["2015", "2018"])
.value_name("YEAR"),
)
._arg(
opt(
"name",
"Set the resulting package name, defaults to the directory name",
)
.value_name("NAME"),
)
}
fn arg_index(self) -> Self {
self._arg(opt("index", "Registry index URL to upload the package to").value_name("INDEX"))
._arg(
opt("host", "DEPRECATED, renamed to '--index'")
.value_name("HOST")
.hidden(true),
)
}
fn arg_dry_run(self, dry_run: &'static str) -> Self {
self._arg(opt("dry-run", dry_run))
}
}
impl AppExt for App {
fn _arg(self, arg: Arg<'static, 'static>) -> Self {
self.arg(arg)
}
}
pub fn opt(name: &'static str, help: &'static str) -> Arg<'static, 'static> {
Arg::with_name(name).long(name).help(help)
}
pub fn optional_multi_opt(
name: &'static str,
value_name: &'static str,
help: &'static str,
) -> Arg<'static, 'static> {
opt(name, help)
.value_name(value_name)
.multiple(true)
.min_values(0)
.number_of_values(1)
}
pub fn multi_opt(
name: &'static str,
value_name: &'static str,
help: &'static str,
) -> Arg<'static, 'static> {
// Note that all `.multiple(true)` arguments in Cargo should specify
// `.number_of_values(1)` as well, so that `--foo val1 val2` is
// *not* parsed as `foo` with values ["val1", "val2"].
// `number_of_values` should become the default in clap 3.
opt(name, help)
.value_name(value_name)
.multiple(true)
.number_of_values(1)
}
pub fn subcommand(name: &'static str) -> App {
SubCommand::with_name(name).settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
}
// Determines whether or not to gate `--profile` as unstable when resolving it.
pub enum ProfileChecking {
Checked,
Unchecked,
}
pub trait ArgMatchesExt {
fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
let arg = match self._value_of(name) {
None => None,
Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
clap::Error::value_validation_auto(format!("could not parse `{}` as a number", arg))
})?),
};
Ok(arg)
}
/// Returns value of the `name` command-line argument as an absolute path
fn value_of_path(&self, name: &str, config: &Config) -> Option<PathBuf> {
self._value_of(name).map(|path| config.cwd().join(path))
}
fn root_manifest(&self, config: &Config) -> CargoResult<PathBuf> {
if let Some(path) = self.value_of_path("manifest-path", config) {
// In general, we try to avoid normalizing paths in Cargo,
// but in this particular case we need it to fix #3586.
let path = paths::normalize_path(&path);
if !path.ends_with("Cargo.toml") {
failure::bail!("the manifest-path must be a path to a Cargo.toml file")
}
if fs::metadata(&path).is_err() {
failure::bail!(
"manifest path `{}` does not exist",
self._value_of("manifest-path").unwrap()
)
}
return Ok(path);
}
find_root_manifest_for_wd(config.cwd())
}
fn workspace<'a>(&self, config: &'a Config) -> CargoResult<Workspace<'a>> {
let root = self.root_manifest(config)?;
let mut ws = Workspace::new(&root, config)?;
if config.cli_unstable().avoid_dev_deps {
ws.set_require_optional_deps(false);
}
Ok(ws)
}
fn jobs(&self) -> CargoResult<Option<u32>> {
self.value_of_u32("jobs")
}
fn target(&self) -> Option<String> {
self._value_of("target").map(|s| s.to_string())
}
fn get_profile_kind(
&self,
config: &Config,
default: ProfileKind,
profile_checking: ProfileChecking,
) -> CargoResult<ProfileKind> {
let specified_profile = match self._value_of("profile") {
None => None,
Some("dev") => Some(ProfileKind::Dev),
Some("release") => Some(ProfileKind::Release),
Some(name) => {
TomlProfile::validate_name(name, "profile name")?;
Some(ProfileKind::Custom(name.to_string()))
}
};
match profile_checking {
ProfileChecking::Unchecked => {}
ProfileChecking::Checked => {
if specified_profile.is_some() {
if !config.cli_unstable().unstable_options {
failure::bail!("Usage of `--profile` requires `-Z unstable-options`")
}
}
}
}
if self._is_present("release") {
match specified_profile {
None | Some(ProfileKind::Release) => Ok(ProfileKind::Release),
_ => failure::bail!("Conflicting usage of --profile and --release"),
}
} else if self._is_present("debug") {
match specified_profile {
None | Some(ProfileKind::Dev) => Ok(ProfileKind::Dev),
_ => failure::bail!("Conflicting usage of --profile and --debug"),
}
} else {
Ok(specified_profile.unwrap_or(default))
}
}
fn compile_options<'a>(
&self,
config: &'a Config,
mode: CompileMode,
workspace: Option<&Workspace<'a>>,
profile_checking: ProfileChecking,
) -> CargoResult<CompileOptions<'a>> {
let spec = Packages::from_flags(
// TODO Integrate into 'workspace'
self._is_present("workspace") || self._is_present("all"),
self._values_of("exclude"),
self._values_of("package"),
)?;
let mut message_format = None;
let default_json = MessageFormat::Json {
short: false,
ansi: false,
render_diagnostics: false,
};
for fmt in self._values_of("message-format") {
for fmt in fmt.split(',') {
let fmt = fmt.to_ascii_lowercase();
match fmt.as_str() {
"json" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(default_json);
}
"human" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(MessageFormat::Human);
}
"short" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(MessageFormat::Short);
}
"json-render-diagnostics" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json {
render_diagnostics, ..
}) => *render_diagnostics = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
"json-diagnostic-short" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json { short, .. }) => *short = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
"json-diagnostic-rendered-ansi" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json { ansi, .. }) => *ansi = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
s => bail!("invalid message format specifier: `{}`", s),
}
}
}
let mut build_config = BuildConfig::new(config, self.jobs()?, &self.target(), mode)?;
build_config.message_format = message_format.unwrap_or(MessageFormat::Human);
build_config.profile_kind =
self.get_profile_kind(config, ProfileKind::Dev, profile_checking)?;
build_config.build_plan = self._is_present("build-plan");
if build_config.build_plan {
config
.cli_unstable()
.fail_if_stable_opt("--build-plan", 5579)?;
};
let opts = CompileOptions {
config,
build_config,
features: self._values_of("features"),
all_features: self._is_present("all-features"),
no_default_features: self._is_present("no-default-features"),
spec,
filter: CompileFilter::from_raw_arguments(
self._is_present("lib"),
self._values_of("bin"),
self._is_present("bins"),
self._values_of("test"),
self._is_present("tests"),
self._values_of("example"),
self._is_present("examples"),
self._values_of("bench"),
self._is_present("benches"),
self._is_present("all-targets"),
),
target_rustdoc_args: None,
target_rustc_args: None,
local_rustdoc_args: None,
export_dir: None,
};
if let Some(ws) = workspace {
self.check_optional_opts(ws, &opts)?;
}
Ok(opts)
}
fn compile_options_for_single_package<'a>(
&self,
config: &'a Config,
mode: CompileMode,
workspace: Option<&Workspace<'a>>,
profile_checking: ProfileChecking,
) -> CargoResult<CompileOptions<'a>> {
let mut compile_opts = self.compile_options(config, mode, workspace, profile_checking)?;
compile_opts.spec = Packages::Packages(self._values_of("package"));
Ok(compile_opts)
}
fn new_options(&self, config: &Config) -> CargoResult<NewOptions> {
let vcs = self._value_of("vcs").map(|vcs| match vcs {
"git" => VersionControl::Git,
"hg" => VersionControl::Hg,
"pijul" => VersionControl::Pijul,
"fossil" => VersionControl::Fossil,
"none" => VersionControl::NoVcs,
vcs => panic!("Impossible vcs: {:?}", vcs),
});
NewOptions::new(
vcs,
self._is_present("bin"),
self._is_present("lib"),
self.value_of_path("path", config).unwrap(),
self._value_of("name").map(|s| s.to_string()),
self._value_of("edition").map(|s| s.to_string()),
self.registry(config)?,
)
}
fn registry(&self, config: &Config) -> CargoResult<Option<String>> {
match self._value_of("registry") {
Some(registry) => {
validate_package_name(registry, "registry name", "")?;
if registry == CRATES_IO_REGISTRY {
// If "crates.io" is specified, then we just need to return `None`,
// as that will cause cargo to use crates.io. This is required
// for the case where a default alternative registry is used
// but the user wants to switch back to crates.io for a single
// command.
Ok(None)
} else {
Ok(Some(registry.to_string()))
}
}
None => config.default_registry(),
}
}
fn index(&self, config: &Config) -> CargoResult<Option<String>> {
// TODO: deprecated. Remove once it has been decided `--host` can be removed
// We may instead want to repurpose the host flag, as mentioned in issue
// rust-lang/cargo#4208.
let msg = "The flag '--host' is no longer valid.
Previous versions of Cargo accepted this flag, but it is being
deprecated. The flag is being renamed to 'index', as the flag
wants the location of the index. Please use '--index' instead.
This will soon become a hard error, so it's either recommended
to update to a fixed version or contact the upstream maintainer
about this warning.";
let index = match self._value_of("host") {
Some(host) => {
config.shell().warn(&msg)?;
Some(host.to_string())
}
None => self._value_of("index").map(|s| s.to_string()),
};
Ok(index)
}
fn check_optional_opts(
&self,
workspace: &Workspace<'_>,
compile_opts: &CompileOptions<'_>,
) -> CargoResult<()> {
if self.is_present_with_zero_values("example") {
print_available_examples(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("bin") {
print_available_binaries(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("bench") {
print_available_benches(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("test") {
print_available_tests(workspace, compile_opts)?;
}
Ok(())
}
fn is_present_with_zero_values(&self, name: &str) -> bool {
self._is_present(name) && self._value_of(name).is_none()
}
fn _value_of(&self, name: &str) -> Option<&str>;
fn _values_of(&self, name: &str) -> Vec<String>;
fn _value_of_os(&self, name: &str) -> Option<&OsStr>;
fn _values_of_os(&self, name: &str) -> Vec<OsString>;
fn _is_present(&self, name: &str) -> bool;
}
impl<'a> ArgMatchesExt for ArgMatches<'a> {
fn _value_of(&self, name: &str) -> Option<&str> {
self.value_of(name)
}
fn _value_of_os(&self, name: &str) -> Option<&OsStr> {
self.value_of_os(name)
}
fn _values_of(&self, name: &str) -> Vec<String> {
self.values_of(name)
.unwrap_or_default()
.map(|s| s.to_string())
.collect()
}
fn _values_of_os(&self, name: &str) -> Vec<OsString> {
self.values_of_os(name)
.unwrap_or_default()
.map(|s| s.to_os_string())
.collect()
}
fn _is_present(&self, name: &str) -> bool {
self.is_present(name)
}
}
pub fn values(args: &ArgMatches<'_>, name: &str) -> Vec<String> {
args._values_of(name)
}
pub fn values_os(args: &ArgMatches<'_>, name: &str) -> Vec<OsString> {
args._values_of_os(name)
}
#[derive(PartialEq, PartialOrd, Eq, Ord)]
pub enum CommandInfo {
BuiltIn { name: String, about: Option<String> },
External { name: String, path: PathBuf },
}
impl CommandInfo {
pub fn name(&self) -> &str {
match self {
CommandInfo::BuiltIn { name, .. } => name,
CommandInfo::External { name, .. } => name,
}
}
}
named-profiles: when -Z unstable-options not specified, don't validate --profile
Fixes #7488.
use crate::core::compiler::{BuildConfig, MessageFormat};
use crate::core::Workspace;
use crate::ops::{CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
use crate::sources::CRATES_IO_REGISTRY;
use crate::util::important_paths::find_root_manifest_for_wd;
use crate::util::{paths, toml::TomlProfile, validate_package_name};
use crate::util::{
print_available_benches, print_available_binaries, print_available_examples,
print_available_tests,
};
use crate::CargoResult;
use clap::{self, SubCommand};
use failure::bail;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::PathBuf;
pub use crate::core::compiler::{CompileMode, ProfileKind};
pub use crate::{CliError, CliResult, Config};
pub use clap::{AppSettings, Arg, ArgMatches};
pub type App = clap::App<'static, 'static>;
pub trait AppExt: Sized {
fn _arg(self, arg: Arg<'static, 'static>) -> Self;
fn arg_package_spec(
self,
package: &'static str,
all: &'static str,
exclude: &'static str,
) -> Self {
self.arg_package_spec_simple(package)
._arg(opt("all", "Alias for --workspace (deprecated)"))
._arg(opt("workspace", all))
._arg(multi_opt("exclude", "SPEC", exclude))
}
fn arg_package_spec_simple(self, package: &'static str) -> Self {
self._arg(multi_opt("package", "SPEC", package).short("p"))
}
fn arg_package(self, package: &'static str) -> Self {
self._arg(opt("package", package).short("p").value_name("SPEC"))
}
fn arg_jobs(self) -> Self {
self._arg(
opt("jobs", "Number of parallel jobs, defaults to # of CPUs")
.short("j")
.value_name("N"),
)
}
fn arg_targets_all(
self,
lib: &'static str,
bin: &'static str,
bins: &'static str,
example: &'static str,
examples: &'static str,
test: &'static str,
tests: &'static str,
bench: &'static str,
benches: &'static str,
all: &'static str,
) -> Self {
self.arg_targets_lib_bin(lib, bin, bins)
._arg(optional_multi_opt("example", "NAME", example))
._arg(opt("examples", examples))
._arg(optional_multi_opt("test", "NAME", test))
._arg(opt("tests", tests))
._arg(optional_multi_opt("bench", "NAME", bench))
._arg(opt("benches", benches))
._arg(opt("all-targets", all))
}
fn arg_targets_lib_bin(self, lib: &'static str, bin: &'static str, bins: &'static str) -> Self {
self._arg(opt("lib", lib))
._arg(optional_multi_opt("bin", "NAME", bin))
._arg(opt("bins", bins))
}
fn arg_targets_bins_examples(
self,
bin: &'static str,
bins: &'static str,
example: &'static str,
examples: &'static str,
) -> Self {
self._arg(optional_multi_opt("bin", "NAME", bin))
._arg(opt("bins", bins))
._arg(optional_multi_opt("example", "NAME", example))
._arg(opt("examples", examples))
}
fn arg_targets_bin_example(self, bin: &'static str, example: &'static str) -> Self {
self._arg(optional_multi_opt("bin", "NAME", bin))
._arg(optional_multi_opt("example", "NAME", example))
}
fn arg_features(self) -> Self {
self._arg(multi_opt(
"features",
"FEATURES",
"Space-separated list of features to activate",
))
._arg(opt("all-features", "Activate all available features"))
._arg(opt(
"no-default-features",
"Do not activate the `default` feature",
))
}
fn arg_release(self, release: &'static str) -> Self {
self._arg(opt("release", release))
}
fn arg_profile(self, profile: &'static str) -> Self {
self._arg(opt("profile", profile).value_name("PROFILE-NAME"))
}
fn arg_doc(self, doc: &'static str) -> Self {
self._arg(opt("doc", doc))
}
fn arg_target_triple(self, target: &'static str) -> Self {
self._arg(opt("target", target).value_name("TRIPLE"))
}
fn arg_target_dir(self) -> Self {
self._arg(
opt("target-dir", "Directory for all generated artifacts").value_name("DIRECTORY"),
)
}
fn arg_manifest_path(self) -> Self {
self._arg(opt("manifest-path", "Path to Cargo.toml").value_name("PATH"))
}
fn arg_message_format(self) -> Self {
self._arg(multi_opt("message-format", "FMT", "Error format"))
}
fn arg_build_plan(self) -> Self {
self._arg(opt(
"build-plan",
"Output the build plan in JSON (unstable)",
))
}
fn arg_new_opts(self) -> Self {
self._arg(
opt(
"vcs",
"Initialize a new repository for the given version \
control system (git, hg, pijul, or fossil) or do not \
initialize any version control at all (none), overriding \
a global configuration.",
)
.value_name("VCS")
.possible_values(&["git", "hg", "pijul", "fossil", "none"]),
)
._arg(opt("bin", "Use a binary (application) template [default]"))
._arg(opt("lib", "Use a library template"))
._arg(
opt("edition", "Edition to set for the crate generated")
.possible_values(&["2015", "2018"])
.value_name("YEAR"),
)
._arg(
opt(
"name",
"Set the resulting package name, defaults to the directory name",
)
.value_name("NAME"),
)
}
fn arg_index(self) -> Self {
self._arg(opt("index", "Registry index URL to upload the package to").value_name("INDEX"))
._arg(
opt("host", "DEPRECATED, renamed to '--index'")
.value_name("HOST")
.hidden(true),
)
}
fn arg_dry_run(self, dry_run: &'static str) -> Self {
self._arg(opt("dry-run", dry_run))
}
}
impl AppExt for App {
fn _arg(self, arg: Arg<'static, 'static>) -> Self {
self.arg(arg)
}
}
pub fn opt(name: &'static str, help: &'static str) -> Arg<'static, 'static> {
Arg::with_name(name).long(name).help(help)
}
pub fn optional_multi_opt(
name: &'static str,
value_name: &'static str,
help: &'static str,
) -> Arg<'static, 'static> {
opt(name, help)
.value_name(value_name)
.multiple(true)
.min_values(0)
.number_of_values(1)
}
pub fn multi_opt(
name: &'static str,
value_name: &'static str,
help: &'static str,
) -> Arg<'static, 'static> {
// Note that all `.multiple(true)` arguments in Cargo should specify
// `.number_of_values(1)` as well, so that `--foo val1 val2` is
// *not* parsed as `foo` with values ["val1", "val2"].
// `number_of_values` should become the default in clap 3.
opt(name, help)
.value_name(value_name)
.multiple(true)
.number_of_values(1)
}
pub fn subcommand(name: &'static str) -> App {
SubCommand::with_name(name).settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
}
// Determines whether or not to gate `--profile` as unstable when resolving it.
pub enum ProfileChecking {
Checked,
Unchecked,
}
pub trait ArgMatchesExt {
fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
let arg = match self._value_of(name) {
None => None,
Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
clap::Error::value_validation_auto(format!("could not parse `{}` as a number", arg))
})?),
};
Ok(arg)
}
/// Returns value of the `name` command-line argument as an absolute path
fn value_of_path(&self, name: &str, config: &Config) -> Option<PathBuf> {
self._value_of(name).map(|path| config.cwd().join(path))
}
fn root_manifest(&self, config: &Config) -> CargoResult<PathBuf> {
if let Some(path) = self.value_of_path("manifest-path", config) {
// In general, we try to avoid normalizing paths in Cargo,
// but in this particular case we need it to fix #3586.
let path = paths::normalize_path(&path);
if !path.ends_with("Cargo.toml") {
failure::bail!("the manifest-path must be a path to a Cargo.toml file")
}
if fs::metadata(&path).is_err() {
failure::bail!(
"manifest path `{}` does not exist",
self._value_of("manifest-path").unwrap()
)
}
return Ok(path);
}
find_root_manifest_for_wd(config.cwd())
}
fn workspace<'a>(&self, config: &'a Config) -> CargoResult<Workspace<'a>> {
let root = self.root_manifest(config)?;
let mut ws = Workspace::new(&root, config)?;
if config.cli_unstable().avoid_dev_deps {
ws.set_require_optional_deps(false);
}
Ok(ws)
}
fn jobs(&self) -> CargoResult<Option<u32>> {
self.value_of_u32("jobs")
}
fn target(&self) -> Option<String> {
self._value_of("target").map(|s| s.to_string())
}
fn get_profile_kind(
&self,
config: &Config,
default: ProfileKind,
profile_checking: ProfileChecking,
) -> CargoResult<ProfileKind> {
let specified_profile = match self._value_of("profile") {
None => None,
Some("dev") => Some(ProfileKind::Dev),
Some("release") => Some(ProfileKind::Release),
Some(name) => {
TomlProfile::validate_name(name, "profile name")?;
Some(ProfileKind::Custom(name.to_string()))
}
};
match profile_checking {
ProfileChecking::Unchecked => {}
ProfileChecking::Checked => {
if specified_profile.is_some() {
if !config.cli_unstable().unstable_options {
failure::bail!("Usage of `--profile` requires `-Z unstable-options`")
}
}
}
}
if self._is_present("release") {
if !config.cli_unstable().unstable_options {
Ok(ProfileKind::Release)
} else {
match specified_profile {
None | Some(ProfileKind::Release) => Ok(ProfileKind::Release),
_ => failure::bail!("Conflicting usage of --profile and --release"),
}
}
} else if self._is_present("debug") {
if !config.cli_unstable().unstable_options {
Ok(ProfileKind::Dev)
} else {
match specified_profile {
None | Some(ProfileKind::Dev) => Ok(ProfileKind::Dev),
_ => failure::bail!("Conflicting usage of --profile and --debug"),
}
}
} else {
Ok(specified_profile.unwrap_or(default))
}
}
fn compile_options<'a>(
&self,
config: &'a Config,
mode: CompileMode,
workspace: Option<&Workspace<'a>>,
profile_checking: ProfileChecking,
) -> CargoResult<CompileOptions<'a>> {
let spec = Packages::from_flags(
// TODO Integrate into 'workspace'
self._is_present("workspace") || self._is_present("all"),
self._values_of("exclude"),
self._values_of("package"),
)?;
let mut message_format = None;
let default_json = MessageFormat::Json {
short: false,
ansi: false,
render_diagnostics: false,
};
for fmt in self._values_of("message-format") {
for fmt in fmt.split(',') {
let fmt = fmt.to_ascii_lowercase();
match fmt.as_str() {
"json" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(default_json);
}
"human" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(MessageFormat::Human);
}
"short" => {
if message_format.is_some() {
bail!("cannot specify two kinds of `message-format` arguments");
}
message_format = Some(MessageFormat::Short);
}
"json-render-diagnostics" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json {
render_diagnostics, ..
}) => *render_diagnostics = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
"json-diagnostic-short" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json { short, .. }) => *short = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
"json-diagnostic-rendered-ansi" => {
if message_format.is_none() {
message_format = Some(default_json);
}
match &mut message_format {
Some(MessageFormat::Json { ansi, .. }) => *ansi = true,
_ => bail!("cannot specify two kinds of `message-format` arguments"),
}
}
s => bail!("invalid message format specifier: `{}`", s),
}
}
}
let mut build_config = BuildConfig::new(config, self.jobs()?, &self.target(), mode)?;
build_config.message_format = message_format.unwrap_or(MessageFormat::Human);
build_config.profile_kind =
self.get_profile_kind(config, ProfileKind::Dev, profile_checking)?;
build_config.build_plan = self._is_present("build-plan");
if build_config.build_plan {
config
.cli_unstable()
.fail_if_stable_opt("--build-plan", 5579)?;
};
let opts = CompileOptions {
config,
build_config,
features: self._values_of("features"),
all_features: self._is_present("all-features"),
no_default_features: self._is_present("no-default-features"),
spec,
filter: CompileFilter::from_raw_arguments(
self._is_present("lib"),
self._values_of("bin"),
self._is_present("bins"),
self._values_of("test"),
self._is_present("tests"),
self._values_of("example"),
self._is_present("examples"),
self._values_of("bench"),
self._is_present("benches"),
self._is_present("all-targets"),
),
target_rustdoc_args: None,
target_rustc_args: None,
local_rustdoc_args: None,
export_dir: None,
};
if let Some(ws) = workspace {
self.check_optional_opts(ws, &opts)?;
}
Ok(opts)
}
fn compile_options_for_single_package<'a>(
&self,
config: &'a Config,
mode: CompileMode,
workspace: Option<&Workspace<'a>>,
profile_checking: ProfileChecking,
) -> CargoResult<CompileOptions<'a>> {
let mut compile_opts = self.compile_options(config, mode, workspace, profile_checking)?;
compile_opts.spec = Packages::Packages(self._values_of("package"));
Ok(compile_opts)
}
fn new_options(&self, config: &Config) -> CargoResult<NewOptions> {
let vcs = self._value_of("vcs").map(|vcs| match vcs {
"git" => VersionControl::Git,
"hg" => VersionControl::Hg,
"pijul" => VersionControl::Pijul,
"fossil" => VersionControl::Fossil,
"none" => VersionControl::NoVcs,
vcs => panic!("Impossible vcs: {:?}", vcs),
});
NewOptions::new(
vcs,
self._is_present("bin"),
self._is_present("lib"),
self.value_of_path("path", config).unwrap(),
self._value_of("name").map(|s| s.to_string()),
self._value_of("edition").map(|s| s.to_string()),
self.registry(config)?,
)
}
fn registry(&self, config: &Config) -> CargoResult<Option<String>> {
match self._value_of("registry") {
Some(registry) => {
validate_package_name(registry, "registry name", "")?;
if registry == CRATES_IO_REGISTRY {
// If "crates.io" is specified, then we just need to return `None`,
// as that will cause cargo to use crates.io. This is required
// for the case where a default alternative registry is used
// but the user wants to switch back to crates.io for a single
// command.
Ok(None)
} else {
Ok(Some(registry.to_string()))
}
}
None => config.default_registry(),
}
}
fn index(&self, config: &Config) -> CargoResult<Option<String>> {
// TODO: deprecated. Remove once it has been decided `--host` can be removed
// We may instead want to repurpose the host flag, as mentioned in issue
// rust-lang/cargo#4208.
let msg = "The flag '--host' is no longer valid.
Previous versions of Cargo accepted this flag, but it is being
deprecated. The flag is being renamed to 'index', as the flag
wants the location of the index. Please use '--index' instead.
This will soon become a hard error, so it's either recommended
to update to a fixed version or contact the upstream maintainer
about this warning.";
let index = match self._value_of("host") {
Some(host) => {
config.shell().warn(&msg)?;
Some(host.to_string())
}
None => self._value_of("index").map(|s| s.to_string()),
};
Ok(index)
}
fn check_optional_opts(
&self,
workspace: &Workspace<'_>,
compile_opts: &CompileOptions<'_>,
) -> CargoResult<()> {
if self.is_present_with_zero_values("example") {
print_available_examples(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("bin") {
print_available_binaries(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("bench") {
print_available_benches(workspace, compile_opts)?;
}
if self.is_present_with_zero_values("test") {
print_available_tests(workspace, compile_opts)?;
}
Ok(())
}
fn is_present_with_zero_values(&self, name: &str) -> bool {
self._is_present(name) && self._value_of(name).is_none()
}
fn _value_of(&self, name: &str) -> Option<&str>;
fn _values_of(&self, name: &str) -> Vec<String>;
fn _value_of_os(&self, name: &str) -> Option<&OsStr>;
fn _values_of_os(&self, name: &str) -> Vec<OsString>;
fn _is_present(&self, name: &str) -> bool;
}
impl<'a> ArgMatchesExt for ArgMatches<'a> {
fn _value_of(&self, name: &str) -> Option<&str> {
self.value_of(name)
}
fn _value_of_os(&self, name: &str) -> Option<&OsStr> {
self.value_of_os(name)
}
fn _values_of(&self, name: &str) -> Vec<String> {
self.values_of(name)
.unwrap_or_default()
.map(|s| s.to_string())
.collect()
}
fn _values_of_os(&self, name: &str) -> Vec<OsString> {
self.values_of_os(name)
.unwrap_or_default()
.map(|s| s.to_os_string())
.collect()
}
fn _is_present(&self, name: &str) -> bool {
self.is_present(name)
}
}
pub fn values(args: &ArgMatches<'_>, name: &str) -> Vec<String> {
args._values_of(name)
}
pub fn values_os(args: &ArgMatches<'_>, name: &str) -> Vec<OsString> {
args._values_of_os(name)
}
#[derive(PartialEq, PartialOrd, Eq, Ord)]
pub enum CommandInfo {
BuiltIn { name: String, about: Option<String> },
External { name: String, path: PathBuf },
}
impl CommandInfo {
pub fn name(&self) -> &str {
match self {
CommandInfo::BuiltIn { name, .. } => name,
CommandInfo::External { name, .. } => name,
}
}
}
|
//! Module containing the `import()` function
use std::io::Read;
use serde_json;
use result::Result;
use task::Task;
use error::{TaskError, TaskErrorKind};
/// Import taskwarrior-exported JSON. This expects an JSON Array of objects, as exported by
/// taskwarrior.
pub fn import<R: Read>(r: R) -> Result<Vec<Task>> {
serde_json::from_reader(r)
.map_err(|e| {
TaskError::new(TaskErrorKind::ParserError, Some(Box::new(e)))
})
}
#[test]
fn test_one() {
let s = r#"
[
{
"id": 1,
"description": "some description",
"entry": "20150619T165438Z",
"modified": "20160327T164007Z",
"project": "someproject",
"status": "waiting",
"tags": ["some", "tags", "are", "here"],
"uuid": "8ca953d5-18b4-4eb9-bd56-18f2e5b752f0",
"wait": "20160508T164007Z",
"urgency": 0.583562
}
]
"#;
let imported = import(s.as_bytes());
assert!(imported.is_ok());
let imported = imported.unwrap();
assert!(imported.len() == 1);
}
#[test]
fn test_two() {
let s = r#"
[
{
"id" : 1,
"description" : "test",
"entry" : "20150619T165438Z",
"modified" : "20160327T164007Z",
"project" : "self.software",
"status" : "waiting",
"tags" : ["check", "this", "crate", "out"],
"uuid" : "8ca953d5-18b4-4eb9-bd56-18f2e5b752f0",
"wait" : "20160508T164007Z",
"urgency" : 0.583562
},
{
"id" : 2,
"description" : "another test",
"entry" : "20150623T181011Z",
"modified" : "20160327T163718Z",
"priority" : "L",
"project" : "studying",
"status" : "waiting",
"tags" : ["I", "have", "awesome", "kittens"],
"uuid" : "54d49ffc-a06b-4dd8-b7d1-db5f50594312",
"wait" : "20160508T163718Z",
"annotations" : [
{
"entry" : "20150623T181018Z",
"description" : "fooooooobar"
}
],
"urgency" : 3.16164
},
{
"id" : 3,
"description" : "I love kittens, really!",
"entry" : "20150919T222323Z",
"modified" : "20160327T163718Z",
"project" : "getkittens",
"status" : "waiting",
"tags" : ["kittens", "are", "so", "damn", "awesome"],
"uuid" : "08ee8dce-cb97-4c8c-9940-c9a440e90119",
"wait" : "20160508T163718Z",
"urgency" : 1.07397
}
]
"#;
let imported = import(s.as_bytes());
assert!(imported.is_ok());
let imported = imported.unwrap();
assert!(imported.len() == 3);
}
impl import_task
//! Module containing the `import()` function
use std::io::Read;
use serde_json;
use result::Result;
use task::Task;
use error::{TaskError, TaskErrorKind};
/// Import taskwarrior-exported JSON. This expects an JSON Array of objects, as exported by
/// taskwarrior.
pub fn import<R: Read>(r: R) -> Result<Vec<Task>> {
serde_json::from_reader(r)
.map_err(|e| {
TaskError::new(TaskErrorKind::ParserError, Some(Box::new(e)))
})
}
/// Import a single JSON-formatted Task
pub fn import_task(s : &str) -> Result<Task> {
serde_json::from_str(s)
.map_err(|e| {
TaskError::new(TaskErrorKind::ParserError, Some(Box::new(e)))
})
}
#[test]
fn test_one() {
let s = r#"
[
{
"id": 1,
"description": "some description",
"entry": "20150619T165438Z",
"modified": "20160327T164007Z",
"project": "someproject",
"status": "waiting",
"tags": ["some", "tags", "are", "here"],
"uuid": "8ca953d5-18b4-4eb9-bd56-18f2e5b752f0",
"wait": "20160508T164007Z",
"urgency": 0.583562
}
]
"#;
let imported = import(s.as_bytes());
assert!(imported.is_ok());
let imported = imported.unwrap();
assert!(imported.len() == 1);
}
#[test]
fn test_two() {
let s = r#"
[
{
"id" : 1,
"description" : "test",
"entry" : "20150619T165438Z",
"modified" : "20160327T164007Z",
"project" : "self.software",
"status" : "waiting",
"tags" : ["check", "this", "crate", "out"],
"uuid" : "8ca953d5-18b4-4eb9-bd56-18f2e5b752f0",
"wait" : "20160508T164007Z",
"urgency" : 0.583562
},
{
"id" : 2,
"description" : "another test",
"entry" : "20150623T181011Z",
"modified" : "20160327T163718Z",
"priority" : "L",
"project" : "studying",
"status" : "waiting",
"tags" : ["I", "have", "awesome", "kittens"],
"uuid" : "54d49ffc-a06b-4dd8-b7d1-db5f50594312",
"wait" : "20160508T163718Z",
"annotations" : [
{
"entry" : "20150623T181018Z",
"description" : "fooooooobar"
}
],
"urgency" : 3.16164
},
{
"id" : 3,
"description" : "I love kittens, really!",
"entry" : "20150919T222323Z",
"modified" : "20160327T163718Z",
"project" : "getkittens",
"status" : "waiting",
"tags" : ["kittens", "are", "so", "damn", "awesome"],
"uuid" : "08ee8dce-cb97-4c8c-9940-c9a440e90119",
"wait" : "20160508T163718Z",
"urgency" : 1.07397
}
]
"#;
let imported = import(s.as_bytes());
assert!(imported.is_ok());
let imported = imported.unwrap();
assert!(imported.len() == 3);
}
#[test]
fn test_one_single() {
use status::TaskStatus;
let s = r#"
{
"id": 1,
"description": "some description",
"entry": "20150619T165438Z",
"modified": "20160327T164007Z",
"project": "someproject",
"status": "waiting",
"tags": ["some", "tags", "are", "here"],
"uuid": "8ca953d5-18b4-4eb9-bd56-18f2e5b752f0",
"wait": "20160508T164007Z",
"urgency": 0.583562
}
"#;
let imported = import_task(&s);
assert!(imported.is_ok());
let imported = imported.unwrap();
assert!(imported.status() == &TaskStatus::Waiting);
}
|
use libc::{c_uint, c_ushort, c_int, c_double, size_t, c_void, c_longlong};
pub type cef_string_map_t = c_void;
pub type cef_string_list_t = c_void;
pub type cef_text_input_context_t = c_void;
pub type cef_event_handle_t = c_void;
//these all need to be done...
pub type cef_binary_value = *c_void;
pub type cef_dictionary_value = *c_void;
pub type cef_client_t = c_void;
pub type cef_request_t = c_void;
pub type cef_response_t = c_void;
pub type cef_urlrequest_client_t = c_void;
pub type cef_frame = *c_void;
pub type cef_domnode = *c_void;
pub type cef_load_handler = *c_void;
pub type cef_request = *c_void;
pub type cef_navigation_type = *c_void;
pub type cef_request_context_t = c_void;
pub type cef_window_info_t = c_void;
pub type cef_browser_settings_t = c_void;
pub type cef_v8context = *c_void;
pub type cef_v8exception = *c_void;
pub type cef_v8stack_trace = *c_void;
pub type cef_window_handle_t = c_void; //FIXME: wtf is this
pub type cef_string_t = cef_string_utf8; //FIXME: this is #defined...
pub type cef_string_userfree_t = cef_string_t; //FIXME: this is #defined...
pub type cef_string_utf8_t = cef_string_utf8;
pub struct cef_string_utf8 {
pub str: *u8,
pub length: size_t,
pub dtor: *fn(str: *u8),
}
pub type cef_string_utf16_t = cef_string_utf16;
pub struct cef_string_utf16 {
pub str: *c_ushort,
pub length: size_t,
pub dtor: *fn(str: *c_ushort),
}
pub type cef_string_wide_t = cef_string_wide;
pub struct cef_string_wide {
pub str: *c_uint, //FIXME: not sure if correct...
pub length: size_t,
pub dtor: *fn(str: *c_uint),
}
pub type cef_main_args_t = cef_main_args;
pub struct cef_main_args {
pub argc: c_int,
pub argv: **u8
}
pub type cef_color_t = c_uint;
///
// Existing thread IDs.
///
pub enum cef_thread_id_t {
// BROWSER PROCESS THREADS -- Only available in the browser process.
///
// The main thread in the browser. This will be the same as the main
// application thread if CefInitialize() is called with a
// CefSettings.multi_threaded_message_loop value of false.
///
TID_UI,
///
// Used to interact with the database.
///
TID_DB,
///
// Used to interact with the file system.
///
TID_FILE,
///
// Used for file system operations that block user interactions.
// Responsiveness of this thread affects users.
///
TID_FILE_USER_BLOCKING,
///
// Used to launch and terminate browser processes.
///
TID_PROCESS_LAUNCHER,
///
// Used to handle slow HTTP cache operations.
///
TID_CACHE,
///
// Used to process IPC and network messages.
///
TID_IO,
// RENDER PROCESS THREADS -- Only available in the render process.
///
// The main thread in the renderer. Used for all WebKit and V8 interaction.
///
TID_RENDERER,
}
///
// Navigation types.
///
pub enum cef_navigation_type_t {
NAVIGATION_LINK_CLICKED = 0,
NAVIGATION_FORM_SUBMITTED,
NAVIGATION_BACK_FORWARD,
NAVIGATION_RELOAD,
NAVIGATION_FORM_RESUBMITTED,
NAVIGATION_OTHER,
}
///
// Mouse button types.
///
pub enum cef_mouse_button_type_t {
MBT_LEFT = 0,
MBT_MIDDLE,
MBT_RIGHT,
}
///
// Structure representing mouse event information.
///
pub type cef_mouse_event_t = cef_mouse_event;
pub struct cef_mouse_event {
///
// X coordinate relative to the left side of the view.
///
pub x: c_int,
///
// Y coordinate relative to the top side of the view.
///
pub y: c_int,
///
// Bit flags describing any pressed modifier keys. See
// cef_event_flags_t for values.
///
pub modifiers: c_uint,
}
///
// Post data elements may represent either bytes or files.
///
pub enum cef_postdataelement_type_t {
PDE_TYPE_EMPTY = 0,
PDE_TYPE_BYTES,
PDE_TYPE_FILE,
}
///
// Flags used to customize the behavior of CefURLRequest.
///
pub enum cef_urlrequest_flags_t {
///
// Default behavior.
///
UR_FLAG_NONE = 0,
///
// If set the cache will be skipped when handling the request.
///
UR_FLAG_SKIP_CACHE = 1 << 0,
///
// If set user name, password, and cookies may be sent with the request.
///
UR_FLAG_ALLOW_CACHED_CREDENTIALS = 1 << 1,
///
// If set cookies may be sent with the request and saved from the response.
// UR_FLAG_ALLOW_CACHED_CREDENTIALS must also be set.
///
UR_FLAG_ALLOW_COOKIES = 1 << 2,
///
// If set upload progress events will be generated when a request has a body.
///
UR_FLAG_REPORT_UPLOAD_PROGRESS = 1 << 3,
///
// If set load timing info will be collected for the request.
///
UR_FLAG_REPORT_LOAD_TIMING = 1 << 4,
///
// If set the headers sent and received for the request will be recorded.
///
UR_FLAG_REPORT_RAW_HEADERS = 1 << 5,
///
// If set the CefURLRequestClient::OnDownloadData method will not be called.
///
UR_FLAG_NO_DOWNLOAD_DATA = 1 << 6,
///
// If set 5XX redirect errors will be propagated to the observer instead of
// automatically re-tried. This currently only applies for requests
// originated in the browser process.
///
UR_FLAG_NO_RETRY_ON_5XX = 1 << 7,
}
///
// Flags that represent CefURLRequest status.
///
pub enum cef_urlrequest_status_t {
///
// Unknown status.
///
UR_UNKNOWN = 0,
///
// Request succeeded.
///
UR_SUCCESS,
///
// An IO request is pending, and the caller will be informed when it is
// completed.
///
UR_IO_PENDING,
///
// Request was canceled programatically.
///
UR_CANCELED,
///
// Request failed for some reason.
///
UR_FAILED,
}
///
// Supported error code values. See net\base\net_error_list.h for complete
// descriptions of the error codes.
///
pub enum cef_errorcode_t {
ERR_NONE = 0,
ERR_FAILED = -2,
ERR_ABORTED = -3,
ERR_INVALID_ARGUMENT = -4,
ERR_INVALID_HANDLE = -5,
ERR_FILE_NOT_FOUND = -6,
ERR_TIMED_OUT = -7,
ERR_FILE_TOO_BIG = -8,
ERR_UNEXPECTED = -9,
ERR_ACCESS_DENIED = -10,
ERR_NOT_IMPLEMENTED = -11,
ERR_CONNECTION_CLOSED = -100,
ERR_CONNECTION_RESET = -101,
ERR_CONNECTION_REFUSED = -102,
ERR_CONNECTION_ABORTED = -103,
ERR_CONNECTION_FAILED = -104,
ERR_NAME_NOT_RESOLVED = -105,
ERR_INTERNET_DISCONNECTED = -106,
ERR_SSL_PROTOCOL_ERROR = -107,
ERR_ADDRESS_INVALID = -108,
ERR_ADDRESS_UNREACHABLE = -109,
ERR_SSL_CLIENT_AUTH_CERT_NEEDED = -110,
ERR_TUNNEL_CONNECTION_FAILED = -111,
ERR_NO_SSL_VERSIONS_ENABLED = -112,
ERR_SSL_VERSION_OR_CIPHER_MISMATCH = -113,
ERR_SSL_RENEGOTIATION_REQUESTED = -114,
ERR_CERT_COMMON_NAME_INVALID = -200,
ERR_CERT_DATE_INVALID = -201,
ERR_CERT_AUTHORITY_INVALID = -202,
ERR_CERT_CONTAINS_ERRORS = -203,
ERR_CERT_NO_REVOCATION_MECHANISM = -204,
ERR_CERT_UNABLE_TO_CHECK_REVOCATION = -205,
ERR_CERT_REVOKED = -206,
ERR_CERT_INVALID = -207,
ERR_CERT_END = -208,
ERR_INVALID_URL = -300,
ERR_DISALLOWED_URL_SCHEME = -301,
ERR_UNKNOWN_URL_SCHEME = -302,
ERR_TOO_MANY_REDIRECTS = -310,
ERR_UNSAFE_REDIRECT = -311,
ERR_UNSAFE_PORT = -312,
ERR_INVALID_RESPONSE = -320,
ERR_INVALID_CHUNKED_ENCODING = -321,
ERR_METHOD_NOT_SUPPORTED = -322,
ERR_UNEXPECTED_PROXY_AUTH = -323,
ERR_EMPTY_RESPONSE = -324,
ERR_RESPONSE_HEADERS_TOO_BIG = -325,
ERR_CACHE_MISS = -400,
ERR_INSECURE_RESPONSE = -501,
}
///
// Key event types.
///
pub enum cef_key_event_type_t {
KEYEVENT_RAWKEYDOWN = 0,
KEYEVENT_KEYDOWN,
KEYEVENT_KEYUP,
KEYEVENT_CHAR
}
///
// Structure representing keyboard event information.
///
pub type cef_key_event_t = cef_key_event;
pub struct cef_key_event {
///
// The type of keyboard event.
///
pub t: cef_key_event_type_t,
///
// Bit flags describing any pressed modifier keys. See
// cef_event_flags_t for values.
///
pub modifiers: c_uint,
///
// The Windows key code for the key event. This value is used by the DOM
// specification. Sometimes it comes directly from the event (i.e. on
// Windows) and sometimes it's determined using a mapping function. See
// WebCore/platform/chromium/KeyboardCodes.h for the list of values.
///
pub windows_key_code: c_int,
///
// The actual key code genenerated by the platform.
///
pub native_key_code: c_int,
///
// Indicates whether the event is considered a "system key" event (see
// http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx for details).
// This value will always be false on non-Windows platforms.
///
pub is_system_key: c_int,
///
// The character generated by the keystroke.
///
pub character: c_ushort, //FIXME: can be wchar_t also?
///
// Same as |character| but unmodified by any concurrently-held modifiers
// (except shift). This is useful for working out shortcut keys.
///
pub unmodified_character: c_ushort, //FIXME: can be wchar_t also?
///
// True if the focus is currently on an editable field on the page. This is
// useful for determining if standard key events should be intercepted.
///
pub focus_on_editable_field: c_int,
}
///
// Structure representing a rectangle.
///
pub type cef_rect_t = cef_rect;
pub struct cef_rect {
pub x: c_int,
pub y: c_int,
pub width: c_int,
pub height: c_int,
}
///
// Paint element types.
///
pub enum cef_paint_element_type_t {
PET_VIEW = 0,
PET_POPUP,
}
///
// Supported file dialog modes.
///
pub enum cef_file_dialog_mode_t {
///
// Requires that the file exists before allowing the user to pick it.
///
FILE_DIALOG_OPEN = 0,
///
// Like Open, but allows picking multiple files to open.
///
FILE_DIALOG_OPEN_MULTIPLE,
///
// Allows picking a nonexistent file, and prompts to overwrite if the file
// already exists.
///
FILE_DIALOG_SAVE,
}
///
// Supported value types.
///
pub enum cef_value_type_t {
VTYPE_INVALID = 0,
VTYPE_NULL,
VTYPE_BOOL,
VTYPE_INT,
VTYPE_DOUBLE,
VTYPE_STRING,
VTYPE_BINARY,
VTYPE_DICTIONARY,
VTYPE_LIST,
}
///
// Existing process IDs.
///
pub enum cef_process_id_t {
///
// Browser process.
///
PID_BROWSER,
///
// Renderer process.
///
PID_RENDERER,
}
///
// Log severity levels.
///
pub enum cef_log_severity_t {
///
// Default logging (currently INFO logging).
///
LOGSEVERITY_DEFAULT,
///
// Verbose logging.
///
LOGSEVERITY_VERBOSE,
///
// INFO logging.
///
LOGSEVERITY_INFO,
///
// WARNING logging.
///
LOGSEVERITY_WARNING,
///
// ERROR logging.
///
LOGSEVERITY_ERROR,
///
// ERROR_REPORT logging.
///
LOGSEVERITY_ERROR_REPORT,
///
// Completely disable logging.
///
LOGSEVERITY_DISABLE = 99
}
///
// Structure representing a message. Can be used on any process and thread.
///
pub type cef_process_message_t = cef_process_message;
pub struct cef_process_message {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(process_message: *mut cef_process_message) -> c_int,
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(process_message: *mut cef_process_message) -> c_int,
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_process_message,
///
// Returns the message name.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_string_userfree_t,
///
// Returns the list of arguments.
///
pub get_argument_list: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_list_value,
}
///
// Initialization settings. Specify NULL or 0 to get the recommended default
// values. Many of these and other settings can also configured using command-
// line switches.
///
pub type cef_settings_t = cef_settings;
pub struct cef_settings {
///
// Size of this structure.
///
pub size: size_t,
///
// Set to true (1) to use a single process for the browser and renderer. This
// run mode is not officially supported by Chromium and is less stable than
// the multi-process default. Also configurable using the "single-process"
// command-line switch.
///
pub single_process: c_int,
///
// Set to true (1) to disable the sandbox for sub-processes. See
// cef_sandbox_win.h for requirements to enable the sandbox on Windows. Also
// configurable using the "no-sandbox" command-line switch.
///
pub no_sandbox: c_int,
///
// The path to a separate executable that will be launched for sub-processes.
// By default the browser process executable is used. See the comments on
// CefExecuteProcess() for details. Also configurable using the
// "browser-subprocess-path" command-line switch.
///
pub browser_subprocess_path: cef_string_t,
///
// Set to true (1) to have the browser process message loop run in a separate
// thread. If false (0) than the CefDoMessageLoopWork() function must be
// called from your application message loop.
///
pub multi_threaded_message_loop: c_int,
///
// Set to true to enable windowless (off-screen) rendering support. Do not
// enable this value if the application does not use windowless rendering as
// it may reduce rendering performance on some systems.
///
pub windowless_rendering_enabled: bool,
///
// Set to true (1) to disable configuration of browser process features using
// standard CEF and Chromium command-line arguments. Configuration can still
// be specified using CEF data structures or via the
// CefApp::OnBeforeCommandLineProcessing() method.
///
pub command_line_args_disabled: c_int,
///
// The location where cache data will be stored on disk. If empty an in-memory
// cache will be used for some features and a temporary disk cache for others.
// HTML5 databases such as localStorage will only persist across sessions if a
// cache path is specified.
///
pub cache_path: cef_string_t,
///
// To persist session cookies (cookies without an expiry date or validity
// interval) by default when using the global cookie manager set this value to
// true. Session cookies are generally intended to be transient and most Web
// browsers do not persist them. A |cache_path| value must also be specified to
// enable this feature. Also configurable using the "persist-session-cookies"
// command-line switch.
///
pub persist_session_cookies: c_int,
///
// Value that will be returned as the User-Agent HTTP header. If empty the
// default User-Agent string will be used. Also configurable using the
// "user-agent" command-line switch.
///
pub user_agent: cef_string_t,
///
// Value that will be inserted as the product portion of the default
// User-Agent string. If empty the Chromium product version will be used. If
// |userAgent| is specified this value will be ignored. Also configurable
// using the "product-version" command-line switch.
///
pub product_version: cef_string_t,
///
// The locale string that will be passed to WebKit. If empty the default
// locale of "en-US" will be used. This value is ignored on Linux where locale
// is determined using environment variable parsing with the precedence order:
// LANGUAGE, LC_ALL, LC_MESSAGES and LANG. Also configurable using the "lang"
// command-line switch.
///
pub locale: cef_string_t,
///
// The directory and file name to use for the debug log. If empty, the
// default name of "debug.log" will be used and the file will be written
// to the application directory. Also configurable using the "log-file"
// command-line switch.
///
pub log_file: cef_string_t,
///
// The log severity. Only messages of this severity level or higher will be
// logged. Also configurable using the "log-severity" command-line switch with
// a value of "verbose", "info", "warning", "error", "error-report" or
// "disable".
///
pub log_severity: cef_log_severity_t,
///
// Enable DCHECK in release mode to ease debugging. Also configurable using the
// "enable-release-dcheck" command-line switch.
///
pub release_dcheck_enabled: c_int,
///
// Custom flags that will be used when initializing the V8 JavaScript engine.
// The consequences of using custom flags may not be well tested. Also
// configurable using the "js-flags" command-line switch.
///
pub javascript_flags: cef_string_t,
///
// The fully qualified path for the resources directory. If this value is
// empty the cef.pak and/or devtools_resources.pak files must be located in
// the module directory on Windows/Linux or the app bundle Resources directory
// on Mac OS X. Also configurable using the "resources-dir-path" command-line
// switch.
///
pub resources_dir_path: cef_string_t,
///
// The fully qualified path for the locales directory. If this value is empty
// the locales directory must be located in the module directory. This value
// is ignored on Mac OS X where pack files are always loaded from the app
// bundle Resources directory. Also configurable using the "locales-dir-path"
// command-line switch.
///
pub locales_dir_path: cef_string_t,
///
// Set to true (1) to disable loading of pack files for resources and locales.
// A resource bundle handler must be provided for the browser and render
// processes via CefApp::GetResourceBundleHandler() if loading of pack files
// is disabled. Also configurable using the "disable-pack-loading" command-
// line switch.
///
pub pack_loading_disabled: c_int,
///
// Set to a value between 1024 and 65535 to enable remote debugging on the
// specified port. For example, if 8080 is specified the remote debugging URL
// will be http://localhost:8080. CEF can be remotely debugged from any CEF or
// Chrome browser window. Also configurable using the "remote-debugging-port"
// command-line switch.
///
pub remote_debugging_port: c_int,
///
// The number of stack trace frames to capture for uncaught exceptions.
// Specify a positive value to enable the CefV8ContextHandler::
// OnUncaughtException() callback. Specify 0 (default value) and
// OnUncaughtException() will not be called. Also configurable using the
// "uncaught-exception-stack-size" command-line switch.
///
pub uncaught_exception_stack_size: c_int,
///
// By default CEF V8 references will be invalidated (the IsValid() method will
// return false) after the owning context has been released. This reduces the
// need for external record keeping and avoids crashes due to the use of V8
// references after the associated context has been released.
//
// CEF currently offers two context safety implementations with different
// performance characteristics. The default implementation (value of 0) uses a
// map of hash values and should provide better performance in situations with
// a small number contexts. The alternate implementation (value of 1) uses a
// hidden value attached to each context and should provide better performance
// in situations with a large number of contexts.
//
// If you need better performance in the creation of V8 references and you
// plan to manually track context lifespan you can disable context safety by
// specifying a value of -1.
//
// Also configurable using the "context-safety-implementation" command-line
// switch.
///
pub context_safety_implementation: c_int,
///
// Set to true (1) to ignore errors related to invalid SSL certificates.
// Enabling this setting can lead to potential security vulnerabilities like
// "man in the middle" attacks. Applications that load content from the
// internet should not enable this setting. Also configurable using the
// "ignore-certificate-errors" command-line switch.
///
pub ignore_certificate_errors: c_int,
///
// Opaque background color used for accelerated content. By default the
// background color will be white. Only the RGB compontents of the specified
// value will be used. The alpha component must greater than 0 to enable use
// of the background color but will be otherwise ignored.
///
pub background_color: cef_color_t,
}
///
// Structure defining the reference count implementation functions. All
// framework structures must include the cef_base_t structure first.
///
pub type cef_base_t = cef_base;
pub struct cef_base {
///
// Size of the data structure.
///
pub size: size_t,
///
// Increment the reference count.
///
pub add_ref: extern "C" fn(base: *mut cef_base) -> c_int,
///
// Decrement the reference count. Delete this object when no references
// remain.
///
pub release: extern "C" fn(base: *mut cef_base) -> c_int,
///
// Returns the current number of references.
///
pub get_refct: extern "C" fn(base: *mut cef_base) -> c_int,
}
///
// Structure used to create and/or parse command line arguments. Arguments with
// '--', '-' and, on Windows, '/' prefixes are considered switches. Switches
// will always precede any arguments without switch prefixes. Switches can
// optionally have a value specified using the '=' delimiter (e.g.
// "-switch=value"). An argument of "--" will terminate switch parsing with all
// subsequent tokens, regardless of prefix, being interpreted as non-switch
// arguments. Switch names are considered case-insensitive. This structure can
// be used before cef_initialize() is called.
///
pub type cef_command_line_t = cef_command_line;
pub struct cef_command_line {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(cmd: *mut cef_command_line),
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(cmd: *mut cef_command_line),
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_command_line,
///
// Initialize the command line with the specified |argc| and |argv| values.
// The first argument must be the name of the program. This function is only
// supported on non-Windows platforms.
///
pub init_from_argv: extern "C" fn(cmd: *mut cef_command_line, argc: c_int, argv: *u8),
///
// Initialize the command line with the string returned by calling
// GetCommandLineW(). This function is only supported on Windows.
///
pub init_from_string: extern "C" fn(cmd: *mut cef_command_line, command_line: *cef_string_t),
///
// Reset the command-line switches and arguments but leave the program
// component unchanged.
///
pub reset: extern "C" fn(cmd: *mut cef_command_line),
///
// Retrieve the original command line string as a vector of strings. The argv
// array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
///
pub get_argv: extern "C" fn(cmd: *mut cef_command_line, argv: *mut cef_string_list_t),
///
// Constructs and returns the represented command line string. Use this
// function cautiously because quoting behavior is unclear.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_command_line_string: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_string_userfree_t,
///
// Get the program part of the command line string (the first item).
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_program: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_string_userfree_t,
///
// Set the program part of the command line string (the first item).
///
pub set_program: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t),
///
// Returns true (1) if the command line has switches.
///
pub has_switches: extern "C" fn(cmd: *mut cef_command_line) -> c_int,
///
// Returns true (1) if the command line contains the given switch.
///
pub has_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> c_int,
///
// Returns the value associated with the given switch. If the switch has no
// value or isn't present this function returns the NULL string.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_switch_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> *mut cef_string_userfree_t,
///
// Returns the map of switch names and values. If a switch has no value an
// NULL string is returned.
///
pub get_switches: extern "C" fn(cmd: *mut cef_command_line, switches: cef_string_map_t),
///
// Add a switch to the end of the command line. If the switch has no value
// pass an NULL value string.
///
pub append_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t),
///
// Add a switch with the specified value to the end of the command line.
///
pub append_switch_with_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t, value: *cef_string_t),
///
// True if there are remaining command line arguments.
///
pub has_arguments: extern "C" fn(cmd: *mut cef_command_line) -> c_int,
///
// Get the remaining command line arguments.
///
pub get_arguments: extern "C" fn(cmd: *mut cef_command_line, arguments: *mut cef_string_list_t),
///
// Add an argument to the end of the command line.
///
pub append_argument: extern "C" fn(cmd: *mut cef_command_line, argument: *cef_string_t),
///
// Insert a command before the current command. Common for debuggers, like
// "valgrind" or "gdb --args".
///
pub prepend_wrapper: extern "C" fn(cmd: *mut cef_command_line, wrapper: *cef_string_t),
}
///
// Structure that manages custom scheme registrations.
///
pub type cef_scheme_registrar_t = cef_scheme_registrar;
pub struct cef_scheme_registrar {
///
// Base structure.
///
pub base: cef_base,
///
// Register a custom scheme. This function should not be called for the built-
// in HTTP, HTTPS, FILE, FTP, ABOUT and DATA schemes.
//
// If |is_standard| is true (1) the scheme will be treated as a standard
// scheme. Standard schemes are subject to URL canonicalization and parsing
// rules as defined in the Common Internet Scheme Syntax RFC 1738 Section 3.1
// available at http://www.ietf.org/rfc/rfc1738.txt
//
// In particular, the syntax for standard scheme URLs must be of the form:
// <pre>
// [scheme]://[username]:[password]@[host]:[port]/[url-path]
// </pre Standard scheme URLs must have a host component that is a fully
// qualified domain name as defined in Section 3.5 of RFC 1034 [13] and
// Section 2.1 of RFC 1123. These URLs will be canonicalized to
// "scheme://host/path" in the simplest case and
// "scheme://username:password@host:port/path" in the most explicit case. For
// example, "scheme:host/path" and "scheme:///host/path" will both be
// canonicalized to "scheme://host/path". The origin of a standard scheme URL
// is the combination of scheme, host and port (i.e., "scheme://host:port" in
// the most explicit case).
//
// For non-standard scheme URLs only the "scheme:" component is parsed and
// canonicalized. The remainder of the URL will be passed to the handler as-
// is. For example, "scheme:///some%20text" will remain the same. Non-standard
// scheme URLs cannot be used as a target for form submission.
//
// If |is_local| is true (1) the scheme will be treated as local (i.e., with
// the same security rules as those applied to "file" URLs). Normal pages
// cannot link to or access local URLs. Also, by default, local URLs can only
// perform XMLHttpRequest calls to the same URL (origin + path) that
// originated the request. To allow XMLHttpRequest calls from a local URL to
// other URLs with the same origin set the
// CefSettings.file_access_from_file_urls_allowed value to true (1). To allow
// XMLHttpRequest calls from a local URL to all origins set the
// CefSettings.universal_access_from_file_urls_allowed value to true (1).
//
// If |is_display_isolated| is true (1) the scheme will be treated as display-
// isolated. This means that pages cannot display these URLs unless they are
// from the same scheme. For example, pages in another origin cannot create
// iframes or hyperlinks to URLs with this scheme.
//
// This function may be called on any thread. It should only be called once
// per unique |scheme_name| value. If |scheme_name| is already registered or
// if an error occurs this function will return false (0).
///
add_custom_scheme: extern "C" fn(registrar: *mut cef_scheme_registrar,
scheme_name: *cef_string_t,
is_standard: c_int, is_local: c_int, is_display_isolated: c_int),
}
///
// Structure used to implement a custom resource bundle structure. The functions
// of this structure may be called on multiple threads.
///
pub type cef_resource_bundle_handler_t = cef_resource_bundle_handler;
pub struct cef_resource_bundle_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called to retrieve a localized translation for the string specified by
// |message_id|. To provide the translation set |string| to the translation
// string and return true (1). To use the default translation return false
// (0). Supported message IDs are listed in cef_pack_strings.h.
///
pub get_localized_string: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler,
message_id: c_int, string: *mut cef_string_t) -> c_int,
///
// Called to retrieve data for the resource specified by |resource_id|. To
// provide the resource data set |data| and |data_size| to the data pointer
// and size respectively and return true (1). To use the default resource data
// return false (0). The resource data will not be copied and must remain
// resident in memory. Supported resource IDs are listed in
// cef_pack_resources.h.
///
pub get_data_resource: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler,
resource_id: c_int, data: **mut c_void, data_size: *mut size_t) -> c_int,
}
///
// Structure representing a list value. Can be used on any process and thread.
///
pub type cef_list_value_t = cef_list_value;
pub struct cef_list_value {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns true (1) if this object is currently owned by another object.
///
pub is_owned: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(list_value: *mut cef_list_value) -> *mut cef_list_value,
///
// Sets the number of values. If the number of values is expanded all new
// value slots will default to type null. Returns true (1) on success.
///
pub set_size: extern "C" fn(list_value: *mut cef_list_value, size: size_t) -> c_int,
///
// Returns the number of values.
///
pub get_size: extern "C" fn(list_value: *mut cef_list_value) -> size_t,
///
// Removes all values. Returns true (1) on success.
///
pub clear: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Removes the value at the specified index.
///
pub remove: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns the value type at the specified index.
///
pub get_type: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> cef_value_type_t,
///
// Returns the value at the specified index as type bool.
///
pub get_bool: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Returns the value at the specified index as type int.
///
pub get_int: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Returns the value at the specified index as type double.
///
pub get_double: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_double,
///
// Returns the value at the specified index as type string.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_string_userfree_t,
///
// Returns the value at the specified index as type binary.
///
pub get_binary: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_binary_value,
///
// Returns the value at the specified index as type dictionary.
///
pub get_dictionary: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_dictionary_value,
///
// Returns the value at the specified index as type list.
///
pub get_list: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_list_value,
///
// Sets the value at the specified index as type null. Returns true (1) if the
// value was set successfully.
///
pub set_null: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Sets the value at the specified index as type bool. Returns true (1) if the
// value was set successfully.
///
pub set_bool: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_int) -> c_int,
///
// Sets the value at the specified index as type int. Returns true (1) if the
// value was set successfully.
///
pub set_int: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_int) -> c_int,
///
// Sets the value at the specified index as type double. Returns true (1) if
// the value was set successfully.
///
pub set_double: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_double) -> c_int,
///
// Sets the value at the specified index as type string. Returns true (1) if
// the value was set successfully.
///
pub set_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *cef_string_t) -> c_int,
///
// Sets the value at the specified index as type binary. Returns true (1) if
// the value was set successfully. After calling this function the |value|
// object will no longer be valid. If |value| is currently owned by another
// object then the value will be copied and the |value| reference will not
// change. Otherwise, ownership will be transferred to this object and the
// |value| reference will be invalidated.
///
pub set_binary: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_binary_value) -> c_int,
///
// Sets the value at the specified index as type dict. Returns true (1) if the
// value was set successfully. After calling this function the |value| object
// will no longer be valid. If |value| is currently owned by another object
// then the value will be copied and the |value| reference will not change.
// Otherwise, ownership will be transferred to this object and the |value|
// reference will be invalidated.
///
pub set_dictionary: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_dictionary_value) -> c_int,
///
// Sets the value at the specified index as type list. Returns true (1) if the
// value was set successfully. After calling this function the |value| object
// will no longer be valid. If |value| is currently owned by another object
// then the value will be copied and the |value| reference will not change.
// Otherwise, ownership will be transferred to this object and the |value|
// reference will be invalidated.
///
pub set_list: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_list_value) -> c_int,
}
///
// Structure used to implement browser process callbacks. The functions of this
// structure will be called on the browser process main thread unless otherwise
// indicated.
///
pub type cef_browser_process_handler_t = cef_browser_process_handler;
pub struct cef_browser_process_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called on the browser process UI thread immediately after the CEF context
// has been initialized.
///
pub on_context_initialized: extern "C" fn(browser_handler: *mut cef_browser_process_handler),
///
// Called before a child process is launched. Will be called on the browser
// process UI thread when launching a render process and on the browser
// process IO thread when launching a GPU or plugin process. Provides an
// opportunity to modify the child process command line. Do not keep a
// reference to |command_line| outside of this function.
///
pub on_before_child_process_launch: extern "C" fn(browser_handler: *mut cef_browser_process_handler, command_line: *mut cef_command_line),
///
// Called on the browser process IO thread after the main thread has been
// created for a new render process. Provides an opportunity to specify extra
// information that will be passed to
// cef_render_process_handler_t::on_render_thread_created() in the render
// process. Do not keep a reference to |extra_info| outside of this function.
///
pub on_render_process_thread_created: extern "C" fn(browser_handler: *mut cef_browser_process_handler, extra_info: *mut cef_list_value),
}
///
// Callback structure for cef_browser_host_t::RunFileDialog. The functions of
// this structure will be called on the browser process UI thread.
///
pub type cef_run_file_dialog_callback_t = cef_run_file_dialog_callback;
pub struct cef_run_file_dialog_callback {
///
// Base structure.
///
pub base: cef_base,
///
// Called asynchronously after the file dialog is dismissed. If the selection
// was successful |file_paths| will be a single value or a list of values
// depending on the dialog mode. If the selection was cancelled |file_paths|
// will be NULL.
///
pub cont: extern "C" fn(run_file_dialog_callback: *mut cef_run_file_dialog_callback,
browser_host: *mut cef_browser_host,
file_paths: *mut cef_string_list_t),
}
///
// Structure used to represent the browser process aspects of a browser window.
// The functions of this structure can only be called in the browser process.
// They may be called on any thread in that process unless otherwise indicated
// in the comments.
///
pub type cef_browser_host_t = cef_browser_host;
pub struct cef_browser_host {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the hosted browser object.
///
pub get_browser: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_browser,
///
// Call this function before destroying a contained browser window. This
// function performs any internal cleanup that may be needed before the
// browser window is destroyed. See cef_life_span_handler_t::do_close()
// documentation for additional usage information.
///
pub parent_window_will_close: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Request that the browser close. The JavaScript 'onbeforeunload' event will
// be fired. If |force_close| is false (0) the event handler, if any, will be
// allowed to prompt the user and the user can optionally cancel the close. If
// |force_close| is true (1) the prompt will not be displayed and the close
// will proceed. Results in a call to cef_life_span_handler_t::do_close() if
// the event handler allows the close or if |force_close| is true (1). See
// cef_life_span_handler_t::do_close() documentation for additional usage
// information.
///
pub close_browser: extern "C" fn(browser_host: *mut cef_browser_host, force_close: c_int),
///
// Set focus for the browser window. If |enable| is true (1) focus will be set
// to the window. Otherwise, focus will be removed.
///
pub set_focus: extern "C" fn(browser_host: *mut cef_browser_host, force_close: c_int),
///
// Retrieve the window handle for this browser.
///
pub get_window_handle: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_window_handle_t,
///
// Retrieve the window handle of the browser that opened this browser. Will
// return NULL for non-popup windows. This function can be used in combination
// with custom handling of modal windows.
///
pub get_opener_window_handle: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_window_handle_t,
///
// Returns the client for this browser.
///
pub get_client: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_client_t,
///
// Returns the request context for this browser.
///
pub get_request_context: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_request_context_t,
///
// Get the current zoom level. The default zoom level is 0.0. This function
// can only be called on the UI thread.
///
pub get_zoom_level: extern "C" fn(browser_host: *mut cef_browser_host) -> c_double,
///
// Change the zoom level to the specified value. Specify 0.0 to reset the zoom
// level. If called on the UI thread the change will be applied immediately.
// Otherwise, the change will be applied asynchronously on the UI thread.
///
pub set_zoom_level: extern "C" fn(browser_host: *mut cef_browser_host, zoomLevel: c_double),
///
// Call to run a file chooser dialog. Only a single file chooser dialog may be
// pending at any given time. |mode| represents the type of dialog to display.
// |title| to the title to be used for the dialog and may be NULL to show the
// default title ("Open" or "Save" depending on the mode). |default_file_name|
// is the default file name to select in the dialog. |accept_types| is a list
// of valid lower-cased MIME types or file extensions specified in an input
// element and is used to restrict selectable files to such types. |callback|
// will be executed after the dialog is dismissed or immediately if another
// dialog is already pending. The dialog will be initiated asynchronously on
// the UI thread.
///
pub run_file_dialog: extern "C" fn(browser_host: *mut cef_browser_host,
mode: cef_file_dialog_mode_t, title: *cef_string_t,
default_file_name: *cef_string_t, accept_types: *mut cef_string_list_t,
callback: *mut cef_run_file_dialog_callback),
///
// Download the file at |url| using cef_download_handler_t.
///
pub start_download: extern "C" fn(browser_host: *mut cef_browser_host, url: *cef_string_t),
///
// Print the current browser contents.
///
pub print: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Search for |searchText|. |identifier| can be used to have multiple searches
// running simultaniously. |forward| indicates whether to search forward or
// backward within the page. |matchCase| indicates whether the search should
// be case-sensitive. |findNext| indicates whether this is the first request
// or a follow-up.
///
pub find: extern "C" fn(browser_host: *mut cef_browser_host, identifier: c_int, searchText: *cef_string_t,
forward: c_int, matchCase: c_int, findNext: c_int),
///
// Cancel all searches that are currently going on.
///
pub stop_finding: extern "C" fn(browser_host: *mut cef_browser_host, clearSelection: c_int),
///
// Open developer tools in its own window.
///
pub show_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host,
windowInfo: *cef_window_info_t,
client: *mut cef_client_t,
settings: *cef_browser_settings_t),
///
// Explicitly close the developer tools window if one exists for this browser
// instance.
///
pub close_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Set whether mouse cursor change is disabled.
///
pub set_mouse_cursor_change_disabled: extern "C" fn(browser_host: *mut cef_browser_host,
disabled: c_int),
///
// Returns true (1) if mouse cursor change is disabled.
///
pub is_mouse_cursor_change_disabled: extern "C" fn(browser_host: *mut cef_browser_host) -> c_int,
///
// Returns true (1) if window rendering is disabled.
///
pub is_window_rendering_disabled: extern "C" fn(browser_host: *mut cef_browser_host) -> c_int,
///
// Notify the browser that the widget has been resized. The browser will first
// call cef_render_handler_t::GetViewRect to get the new size and then call
// cef_render_handler_t::OnPaint asynchronously with the updated regions. This
// function is only used when window rendering is disabled.
///
pub was_resized: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Notify the browser that it has been hidden or shown. Layouting and
// cef_render_handler_t::OnPaint notification will stop when the browser is
// hidden. This function is only used when window rendering is disabled.
///
pub was_hidden: extern "C" fn(browser_host: *mut cef_browser_host, hidden: c_int),
///
// Send a notification to the browser that the screen info has changed. The
// browser will then call cef_render_handler_t::GetScreenInfo to update the
// screen information with the new values. This simulates moving the webview
// window from one display to another, or changing the properties of the
// current display. This function is only used when window rendering is
// disabled.
///
pub notify_screen_info_changed: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Invalidate the |dirtyRect| region of the view. The browser will call
// cef_render_handler_t::OnPaint asynchronously with the updated regions. This
// function is only used when window rendering is disabled.
///
pub invalidate: extern "C" fn(browser_host: *mut cef_browser_host,
dirtyRect: *cef_rect, t: cef_paint_element_type_t),
///
// Send a key event to the browser.
///
pub send_key_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_key_event),
///
// Send a mouse click event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view.
///
pub send_mouse_click_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event,
t: cef_mouse_button_type_t,
mouseUp: c_int, clickCount: c_int),
///
// Send a mouse move event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view.
///
pub send_mouse_move_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, mouseLeave: c_int),
///
// Send a mouse wheel event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view. The |deltaX| and |deltaY|
// values represent the movement delta in the X and Y directions respectively.
// In order to scroll inside select popups with window rendering disabled
// cef_render_handler_t::GetScreenPoint should be implemented properly.
///
pub send_mouse_wheel_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, deltaX: c_int, deltaY: c_int),
///
// Send a focus event to the browser.
///
pub send_focus_event: extern "C" fn(browser_host: *mut cef_browser_host, setFocus: c_int),
///
// Send a capture lost event to the browser.
///
pub send_capture_lost_event: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Get the NSTextInputContext implementation for enabling IME on Mac when
// window rendering is disabled.
///
pub get_nstext_input_context: extern "C" fn(browser_host: *mut cef_browser_host) -> cef_text_input_context_t,
///
// Handles a keyDown event prior to passing it through the NSTextInputClient
// machinery.
///
pub handle_key_event_before_text_input_client: extern "C" fn(browser_host: *mut cef_browser_host,
key_event: *mut cef_event_handle_t),
///
// Performs any additional actions after NSTextInputClient handles the event.
///
pub handle_key_event_after_text_input_client: extern "C" fn(browser_host: *mut cef_browser_host,
key_event: *mut cef_event_handle_t),
}
///
// Structure used to represent a browser window. When used in the browser
// process the functions of this structure may be called on any thread unless
// otherwise indicated in the comments. When used in the render process the
// functions of this structure may only be called on the main thread.
///
pub type cef_browser_t = cef_browser;
pub struct cef_browser {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the browser host object. This function can only be called in the
// browser process.
///
pub get_host: extern "C" fn(browser: *mut cef_browser) -> *mut cef_browser_host,
///
// Returns true (1) if the browser can navigate backwards.
///
pub can_go_back: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Navigate backwards.
///
pub go_back: extern "C" fn(browser: *mut cef_browser),
///
// Returns true (1) if the browser can navigate forwards.
///
pub can_go_forward: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Navigate forwards.
///
pub go_forward: extern "C" fn(browser: *mut cef_browser),
///
// Returns true (1) if the browser is currently loading.
///
pub is_loading: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Reload the current page.
///
pub reload: extern "C" fn(browser: *mut cef_browser),
///
// Reload the current page ignoring any cached data.
///
pub reload_ignore_cache: extern "C" fn(browser: *mut cef_browser),
///
// Stop loading the page.
///
pub stop_load: extern "C" fn(browser: *mut cef_browser),
///
// Returns the globally unique identifier for this browser.
///
pub get_identifier: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns true (1) if this object is pointing to the same handle as |that|
// object.
///
pub is_same: extern "C" fn(browser: *mut cef_browser, that: *mut cef_browser) -> c_int,
///
// Returns true (1) if the window is a popup window.
///
pub is_popup: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns true (1) if a document has been loaded in the browser.
///
pub has_document: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns the main (top-level) frame for the browser window.
///
pub get_main_frame: extern "C" fn(browser: *mut cef_browser) -> *mut cef_frame,
///
// Returns the focused frame for the browser window.
///
pub get_focused_frame: extern "C" fn(browser: *mut cef_browser) -> *mut cef_frame,
///
// Returns the frame with the specified identifier, or NULL if not found.
///
pub get_frame_byident: extern "C" fn(browser: *mut cef_browser, identifier: c_longlong) -> *mut cef_frame,
///
// Returns the frame with the specified name, or NULL if not found.
///
pub get_frame: extern "C" fn(browser: *mut cef_browser, name: *cef_string_t) -> *mut cef_frame,
///
// Returns the number of frames that currently exist.
///
pub get_frame_count: extern "C" fn(browser: *mut cef_browser) -> size_t,
///
// Returns the identifiers of all existing frames.
///
pub get_frame_identifiers: extern "C" fn(browser: *mut cef_browser,
identifiersCount: *mut size_t,
identifiers: *mut c_longlong),
///
// Returns the names of all existing frames.
///
pub get_frame_names: extern "C" fn(browser: *mut cef_browser, names: *mut cef_string_list_t),
//
// Send a message to the specified |target_process|. Returns true (1) if the
// message was sent successfully.
///
pub send_process_message: extern "C" fn(browser: *mut cef_browser, target_process: cef_process_id_t,
message: *mut cef_process_message) -> c_int,
}
///
// Structure used to implement render process callbacks. The functions of this
// structure will be called on the render process main thread (TID_RENDERER)
// unless otherwise indicated.
///
pub type cef_render_process_handler_t = cef_render_process_handler;
pub struct cef_render_process_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called after the render process main thread has been created. |extra_info|
// is a read-only value originating from
// cef_browser_process_handler_t::on_render_process_thread_created(). Do not
// keep a reference to |extra_info| outside of this function.
///
pub on_render_thread_created: extern "C" fn(render_handler: *mut cef_render_process_handler, extra_info: *mut cef_list_value),
///
// Called after WebKit has been initialized.
///
pub on_web_kit_initialized: extern "C" fn(render_handler: *mut cef_render_process_handler),
///
// Called after a browser has been created. When browsing cross-origin a new
// browser will be created before the old browser with the same identifier is
// destroyed.
///
pub on_browser_created: extern "C" fn(render_handler: *mut cef_render_process_handler, browser: *mut cef_browser),
///
// Called before a browser is destroyed.
///
pub on_browser_destroyed: extern "C" fn(render_handler: *mut cef_render_process_handler, browser: *mut cef_browser),
///
// Return the handler for browser load status events.
///
pub get_load_handler: extern "C" fn(render_handler: *mut cef_render_process_handler) -> *mut cef_load_handler,
///
// Called before browser navigation. Return true (1) to cancel the navigation
// or false (0) to allow the navigation to proceed. The |request| object
// cannot be modified in this callback.
///
pub on_before_navigation: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
request: *mut cef_request,
navigation_type: *mut cef_navigation_type,
is_redirect: c_int) -> c_int,
///
// Called immediately after the V8 context for a frame has been created. To
// retrieve the JavaScript 'window' object use the
// cef_v8context_t::get_global() function. V8 handles can only be accessed
// from the thread on which they are created. A task runner for posting tasks
// on the associated thread can be retrieved via the
// cef_v8context_t::get_task_runner() function.
///
pub on_context_created: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context),
///
// Called immediately before the V8 context for a frame is released. No
// references to the context should be kept after this function is called.
///
pub on_context_released: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context),
///
// Called for global uncaught exceptions in a frame. Execution of this
// callback is disabled by default. To enable set
// CefSettings.uncaught_exception_stack_size 0.
///
pub on_uncaught_exception: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context,
exception: *mut cef_v8exception,
stackTrace: *mut cef_v8stack_trace),
///
// Called when a new node in the the browser gets focus. The |node| value may
// be NULL if no specific node has gained focus. The node object passed to
// this function represents a snapshot of the DOM at the time this function is
// executed. DOM objects are only valid for the scope of this function. Do not
// keep references to or attempt to access any DOM objects outside the scope
// of this function.
///
pub on_focused_node_changed: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
node: *mut cef_domnode),
///
// Called when a new message is received from a different process. Return true
// (1) if the message was handled or false (0) otherwise. Do not keep a
// reference to or attempt to access the message outside of this callback.
///
pub on_process_message_received: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
source_process: cef_process_id_t,
message: *mut cef_process_message) ->c_int,
}
///
// Implement this structure to provide handler implementations. Methods will be
// called by the process and/or thread indicated.
///
pub type cef_app_t = cef_app;
pub struct cef_app {
///
// Base structure.
///
pub base: cef_base,
///
// Provides an opportunity to view and/or modify command-line arguments before
// processing by CEF and Chromium. The |process_type| value will be NULL for
// the browser process. Do not keep a reference to the cef_command_line_t
// object passed to this function. The CefSettings.command_line_args_disabled
// value can be used to start with an NULL command-line object. Any values
// specified in CefSettings that equate to command-line arguments will be set
// before this function is called. Be cautious when using this function to
// modify command-line arguments for non-browser processes as this may result
// in undefined behavior including crashes.
///
pub on_before_command_line_processing: extern "C" fn(app: *mut cef_app_t, process_type: *cef_string_t, command_line: *mut cef_command_line),
///
// Provides an opportunity to register custom schemes. Do not keep a reference
// to the |registrar| object. This function is called on the main thread for
// each process and the registered schemes should be the same across all
// processes.
///
pub on_register_custom_schemes: extern "C" fn(app: *mut cef_app_t, registrar: *mut cef_scheme_registrar),
///
// Return the handler for resource bundle events. If
// CefSettings.pack_loading_disabled is true (1) a handler must be returned.
// If no handler is returned resources will be loaded from pack files. This
// function is called by the browser and render processes on multiple threads.
///
pub get_resource_bundle_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_resource_bundle_handler,
///
// Return the handler for functionality specific to the browser process. This
// function is called on multiple threads in the browser process.
///
pub get_browser_process_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_browser_process_handler,
///
// Return the handler for functionality specific to the render process. This
// function is called on the render process main thread.
///
pub get_render_process_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_render_process_handler,
}
///
// Structure used to make a URL request. URL requests are not associated with a
// browser instance so no cef_client_t callbacks will be executed. URL requests
// can be created on any valid CEF thread in either the browser or render
// process. Once created the functions of the URL request object must be
// accessed on the same thread that created it.
///
pub type cef_urlrequest_t = cef_urlrequest;
pub struct cef_urlrequest {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the request object used to create this URL request. The returned
// object is read-only and should not be modified.
///
pub get_request: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_request_t,
///
// Returns the client.
///
pub get_client: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_urlrequest_client_t,
///
// Returns the request status.
///
pub get_request_status: extern "C" fn(url_req: *mut cef_urlrequest) -> cef_urlrequest_status_t,
///
// Returns the request error if status is UR_CANCELED or UR_FAILED, or 0
// otherwise.
///
pub get_request_error: extern "C" fn(url_req: *mut cef_urlrequest) -> cef_errorcode_t,
///
// Returns the response, or NULL if no response information is available.
// Response information will only be available after the upload has completed.
// The returned object is read-only and should not be modified.
///
pub get_response: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_response_t,
///
// Cancel the request.
///
pub cancel: extern "C" fn(url_req: *mut cef_urlrequest),
}
///
// Structure used to represent a single element in the request post data. The
// functions of this structure may be called on any thread.
///
pub type cef_post_data_element_t = cef_post_data_element;
pub struct cef_post_data_element {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is read-only.
///
pub is_read_only: extern "C" fn(post_data_element: *mut cef_post_data_element) -> c_int,
///
// Remove all contents from the post data element.
///
pub set_to_empty: extern "C" fn(post_data_element: *mut cef_post_data_element),
///
// The post data element will represent a file.
///
pub set_to_file: extern "C" fn(post_data_element: *mut cef_post_data_element, fileName: *cef_string_t),
///
// The post data element will represent bytes. The bytes passed in will be
// copied.
///
pub set_to_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element,
size: size_t, bytes: *c_void),
///
// Return the type of this post data element.
///
pub get_type: extern "C" fn(post_data_element: *mut cef_post_data_element) -> cef_postdataelement_type_t,
///
// Return the file name.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_file: extern "C" fn(post_data_element: *mut cef_post_data_element) -> *mut cef_string_userfree_t,
///
// Return the number of bytes.
///
pub get_bytes_count: extern "C" fn(post_data_element: *mut cef_post_data_element) -> size_t,
///
// Read up to |size| bytes into |bytes| and return the number of bytes
// actually read.
///
pub get_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element,
size: size_t, bytes: *mut c_void) -> size_t,
}
///
// Structure used to represent post data for a web request. The functions of
// this structure may be called on any thread.
///
pub type cef_post_data_t = cef_post_data;
pub struct cef_post_data {
///
// Base structure.
///
pub base: cef_base_t,
///
// Returns true (1) if this object is read-only.
///
pub is_read_only: extern "C" fn(post_data: *mut cef_post_data) -> c_int,
///
// Returns the number of existing post data elements.
///
pub get_element_count: extern "C" fn(post_data: *mut cef_post_data) -> size_t,
///
// Retrieve the post data elements.
///
pub get_elements: extern "C" fn(post_data: *mut cef_post_data,
elements_count: *mut size_t, elements: **mut cef_post_data_element),
///
// Remove the specified post data element. Returns true (1) if the removal
// succeeds.
///
pub remove_element: extern "C" fn(post_data: *mut cef_post_data,
element: *mut cef_post_data_element) -> c_int,
///
// Add the specified post data element. Returns true (1) if the add succeeds.
///
pub add_element: extern "C" fn(post_data: *mut cef_post_data,
element: *mut cef_post_data_element) -> c_int,
///
// Remove all existing post data elements.
///
pub remove_elements: extern "C" fn(post_data: *mut cef_post_data),
}
add MPL header
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use libc::{c_uint, c_ushort, c_int, c_double, size_t, c_void, c_longlong};
pub type cef_string_map_t = c_void;
pub type cef_string_list_t = c_void;
pub type cef_text_input_context_t = c_void;
pub type cef_event_handle_t = c_void;
//these all need to be done...
pub type cef_binary_value = *c_void;
pub type cef_dictionary_value = *c_void;
pub type cef_client_t = c_void;
pub type cef_request_t = c_void;
pub type cef_response_t = c_void;
pub type cef_urlrequest_client_t = c_void;
pub type cef_frame = *c_void;
pub type cef_domnode = *c_void;
pub type cef_load_handler = *c_void;
pub type cef_request = *c_void;
pub type cef_navigation_type = *c_void;
pub type cef_request_context_t = c_void;
pub type cef_window_info_t = c_void;
pub type cef_browser_settings_t = c_void;
pub type cef_v8context = *c_void;
pub type cef_v8exception = *c_void;
pub type cef_v8stack_trace = *c_void;
pub type cef_window_handle_t = c_void; //FIXME: wtf is this
pub type cef_string_t = cef_string_utf8; //FIXME: this is #defined...
pub type cef_string_userfree_t = cef_string_t; //FIXME: this is #defined...
pub type cef_string_utf8_t = cef_string_utf8;
pub struct cef_string_utf8 {
pub str: *u8,
pub length: size_t,
pub dtor: *fn(str: *u8),
}
pub type cef_string_utf16_t = cef_string_utf16;
pub struct cef_string_utf16 {
pub str: *c_ushort,
pub length: size_t,
pub dtor: *fn(str: *c_ushort),
}
pub type cef_string_wide_t = cef_string_wide;
pub struct cef_string_wide {
pub str: *c_uint, //FIXME: not sure if correct...
pub length: size_t,
pub dtor: *fn(str: *c_uint),
}
pub type cef_main_args_t = cef_main_args;
pub struct cef_main_args {
pub argc: c_int,
pub argv: **u8
}
pub type cef_color_t = c_uint;
///
// Existing thread IDs.
///
pub enum cef_thread_id_t {
// BROWSER PROCESS THREADS -- Only available in the browser process.
///
// The main thread in the browser. This will be the same as the main
// application thread if CefInitialize() is called with a
// CefSettings.multi_threaded_message_loop value of false.
///
TID_UI,
///
// Used to interact with the database.
///
TID_DB,
///
// Used to interact with the file system.
///
TID_FILE,
///
// Used for file system operations that block user interactions.
// Responsiveness of this thread affects users.
///
TID_FILE_USER_BLOCKING,
///
// Used to launch and terminate browser processes.
///
TID_PROCESS_LAUNCHER,
///
// Used to handle slow HTTP cache operations.
///
TID_CACHE,
///
// Used to process IPC and network messages.
///
TID_IO,
// RENDER PROCESS THREADS -- Only available in the render process.
///
// The main thread in the renderer. Used for all WebKit and V8 interaction.
///
TID_RENDERER,
}
///
// Navigation types.
///
pub enum cef_navigation_type_t {
NAVIGATION_LINK_CLICKED = 0,
NAVIGATION_FORM_SUBMITTED,
NAVIGATION_BACK_FORWARD,
NAVIGATION_RELOAD,
NAVIGATION_FORM_RESUBMITTED,
NAVIGATION_OTHER,
}
///
// Mouse button types.
///
pub enum cef_mouse_button_type_t {
MBT_LEFT = 0,
MBT_MIDDLE,
MBT_RIGHT,
}
///
// Structure representing mouse event information.
///
pub type cef_mouse_event_t = cef_mouse_event;
pub struct cef_mouse_event {
///
// X coordinate relative to the left side of the view.
///
pub x: c_int,
///
// Y coordinate relative to the top side of the view.
///
pub y: c_int,
///
// Bit flags describing any pressed modifier keys. See
// cef_event_flags_t for values.
///
pub modifiers: c_uint,
}
///
// Post data elements may represent either bytes or files.
///
pub enum cef_postdataelement_type_t {
PDE_TYPE_EMPTY = 0,
PDE_TYPE_BYTES,
PDE_TYPE_FILE,
}
///
// Flags used to customize the behavior of CefURLRequest.
///
pub enum cef_urlrequest_flags_t {
///
// Default behavior.
///
UR_FLAG_NONE = 0,
///
// If set the cache will be skipped when handling the request.
///
UR_FLAG_SKIP_CACHE = 1 << 0,
///
// If set user name, password, and cookies may be sent with the request.
///
UR_FLAG_ALLOW_CACHED_CREDENTIALS = 1 << 1,
///
// If set cookies may be sent with the request and saved from the response.
// UR_FLAG_ALLOW_CACHED_CREDENTIALS must also be set.
///
UR_FLAG_ALLOW_COOKIES = 1 << 2,
///
// If set upload progress events will be generated when a request has a body.
///
UR_FLAG_REPORT_UPLOAD_PROGRESS = 1 << 3,
///
// If set load timing info will be collected for the request.
///
UR_FLAG_REPORT_LOAD_TIMING = 1 << 4,
///
// If set the headers sent and received for the request will be recorded.
///
UR_FLAG_REPORT_RAW_HEADERS = 1 << 5,
///
// If set the CefURLRequestClient::OnDownloadData method will not be called.
///
UR_FLAG_NO_DOWNLOAD_DATA = 1 << 6,
///
// If set 5XX redirect errors will be propagated to the observer instead of
// automatically re-tried. This currently only applies for requests
// originated in the browser process.
///
UR_FLAG_NO_RETRY_ON_5XX = 1 << 7,
}
///
// Flags that represent CefURLRequest status.
///
pub enum cef_urlrequest_status_t {
///
// Unknown status.
///
UR_UNKNOWN = 0,
///
// Request succeeded.
///
UR_SUCCESS,
///
// An IO request is pending, and the caller will be informed when it is
// completed.
///
UR_IO_PENDING,
///
// Request was canceled programatically.
///
UR_CANCELED,
///
// Request failed for some reason.
///
UR_FAILED,
}
///
// Supported error code values. See net\base\net_error_list.h for complete
// descriptions of the error codes.
///
pub enum cef_errorcode_t {
ERR_NONE = 0,
ERR_FAILED = -2,
ERR_ABORTED = -3,
ERR_INVALID_ARGUMENT = -4,
ERR_INVALID_HANDLE = -5,
ERR_FILE_NOT_FOUND = -6,
ERR_TIMED_OUT = -7,
ERR_FILE_TOO_BIG = -8,
ERR_UNEXPECTED = -9,
ERR_ACCESS_DENIED = -10,
ERR_NOT_IMPLEMENTED = -11,
ERR_CONNECTION_CLOSED = -100,
ERR_CONNECTION_RESET = -101,
ERR_CONNECTION_REFUSED = -102,
ERR_CONNECTION_ABORTED = -103,
ERR_CONNECTION_FAILED = -104,
ERR_NAME_NOT_RESOLVED = -105,
ERR_INTERNET_DISCONNECTED = -106,
ERR_SSL_PROTOCOL_ERROR = -107,
ERR_ADDRESS_INVALID = -108,
ERR_ADDRESS_UNREACHABLE = -109,
ERR_SSL_CLIENT_AUTH_CERT_NEEDED = -110,
ERR_TUNNEL_CONNECTION_FAILED = -111,
ERR_NO_SSL_VERSIONS_ENABLED = -112,
ERR_SSL_VERSION_OR_CIPHER_MISMATCH = -113,
ERR_SSL_RENEGOTIATION_REQUESTED = -114,
ERR_CERT_COMMON_NAME_INVALID = -200,
ERR_CERT_DATE_INVALID = -201,
ERR_CERT_AUTHORITY_INVALID = -202,
ERR_CERT_CONTAINS_ERRORS = -203,
ERR_CERT_NO_REVOCATION_MECHANISM = -204,
ERR_CERT_UNABLE_TO_CHECK_REVOCATION = -205,
ERR_CERT_REVOKED = -206,
ERR_CERT_INVALID = -207,
ERR_CERT_END = -208,
ERR_INVALID_URL = -300,
ERR_DISALLOWED_URL_SCHEME = -301,
ERR_UNKNOWN_URL_SCHEME = -302,
ERR_TOO_MANY_REDIRECTS = -310,
ERR_UNSAFE_REDIRECT = -311,
ERR_UNSAFE_PORT = -312,
ERR_INVALID_RESPONSE = -320,
ERR_INVALID_CHUNKED_ENCODING = -321,
ERR_METHOD_NOT_SUPPORTED = -322,
ERR_UNEXPECTED_PROXY_AUTH = -323,
ERR_EMPTY_RESPONSE = -324,
ERR_RESPONSE_HEADERS_TOO_BIG = -325,
ERR_CACHE_MISS = -400,
ERR_INSECURE_RESPONSE = -501,
}
///
// Key event types.
///
pub enum cef_key_event_type_t {
KEYEVENT_RAWKEYDOWN = 0,
KEYEVENT_KEYDOWN,
KEYEVENT_KEYUP,
KEYEVENT_CHAR
}
///
// Structure representing keyboard event information.
///
pub type cef_key_event_t = cef_key_event;
pub struct cef_key_event {
///
// The type of keyboard event.
///
pub t: cef_key_event_type_t,
///
// Bit flags describing any pressed modifier keys. See
// cef_event_flags_t for values.
///
pub modifiers: c_uint,
///
// The Windows key code for the key event. This value is used by the DOM
// specification. Sometimes it comes directly from the event (i.e. on
// Windows) and sometimes it's determined using a mapping function. See
// WebCore/platform/chromium/KeyboardCodes.h for the list of values.
///
pub windows_key_code: c_int,
///
// The actual key code genenerated by the platform.
///
pub native_key_code: c_int,
///
// Indicates whether the event is considered a "system key" event (see
// http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx for details).
// This value will always be false on non-Windows platforms.
///
pub is_system_key: c_int,
///
// The character generated by the keystroke.
///
pub character: c_ushort, //FIXME: can be wchar_t also?
///
// Same as |character| but unmodified by any concurrently-held modifiers
// (except shift). This is useful for working out shortcut keys.
///
pub unmodified_character: c_ushort, //FIXME: can be wchar_t also?
///
// True if the focus is currently on an editable field on the page. This is
// useful for determining if standard key events should be intercepted.
///
pub focus_on_editable_field: c_int,
}
///
// Structure representing a rectangle.
///
pub type cef_rect_t = cef_rect;
pub struct cef_rect {
pub x: c_int,
pub y: c_int,
pub width: c_int,
pub height: c_int,
}
///
// Paint element types.
///
pub enum cef_paint_element_type_t {
PET_VIEW = 0,
PET_POPUP,
}
///
// Supported file dialog modes.
///
pub enum cef_file_dialog_mode_t {
///
// Requires that the file exists before allowing the user to pick it.
///
FILE_DIALOG_OPEN = 0,
///
// Like Open, but allows picking multiple files to open.
///
FILE_DIALOG_OPEN_MULTIPLE,
///
// Allows picking a nonexistent file, and prompts to overwrite if the file
// already exists.
///
FILE_DIALOG_SAVE,
}
///
// Supported value types.
///
pub enum cef_value_type_t {
VTYPE_INVALID = 0,
VTYPE_NULL,
VTYPE_BOOL,
VTYPE_INT,
VTYPE_DOUBLE,
VTYPE_STRING,
VTYPE_BINARY,
VTYPE_DICTIONARY,
VTYPE_LIST,
}
///
// Existing process IDs.
///
pub enum cef_process_id_t {
///
// Browser process.
///
PID_BROWSER,
///
// Renderer process.
///
PID_RENDERER,
}
///
// Log severity levels.
///
pub enum cef_log_severity_t {
///
// Default logging (currently INFO logging).
///
LOGSEVERITY_DEFAULT,
///
// Verbose logging.
///
LOGSEVERITY_VERBOSE,
///
// INFO logging.
///
LOGSEVERITY_INFO,
///
// WARNING logging.
///
LOGSEVERITY_WARNING,
///
// ERROR logging.
///
LOGSEVERITY_ERROR,
///
// ERROR_REPORT logging.
///
LOGSEVERITY_ERROR_REPORT,
///
// Completely disable logging.
///
LOGSEVERITY_DISABLE = 99
}
///
// Structure representing a message. Can be used on any process and thread.
///
pub type cef_process_message_t = cef_process_message;
pub struct cef_process_message {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(process_message: *mut cef_process_message) -> c_int,
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(process_message: *mut cef_process_message) -> c_int,
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_process_message,
///
// Returns the message name.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_name: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_string_userfree_t,
///
// Returns the list of arguments.
///
pub get_argument_list: extern "C" fn(process_message: *mut cef_process_message) -> *mut cef_list_value,
}
///
// Initialization settings. Specify NULL or 0 to get the recommended default
// values. Many of these and other settings can also configured using command-
// line switches.
///
pub type cef_settings_t = cef_settings;
pub struct cef_settings {
///
// Size of this structure.
///
pub size: size_t,
///
// Set to true (1) to use a single process for the browser and renderer. This
// run mode is not officially supported by Chromium and is less stable than
// the multi-process default. Also configurable using the "single-process"
// command-line switch.
///
pub single_process: c_int,
///
// Set to true (1) to disable the sandbox for sub-processes. See
// cef_sandbox_win.h for requirements to enable the sandbox on Windows. Also
// configurable using the "no-sandbox" command-line switch.
///
pub no_sandbox: c_int,
///
// The path to a separate executable that will be launched for sub-processes.
// By default the browser process executable is used. See the comments on
// CefExecuteProcess() for details. Also configurable using the
// "browser-subprocess-path" command-line switch.
///
pub browser_subprocess_path: cef_string_t,
///
// Set to true (1) to have the browser process message loop run in a separate
// thread. If false (0) than the CefDoMessageLoopWork() function must be
// called from your application message loop.
///
pub multi_threaded_message_loop: c_int,
///
// Set to true to enable windowless (off-screen) rendering support. Do not
// enable this value if the application does not use windowless rendering as
// it may reduce rendering performance on some systems.
///
pub windowless_rendering_enabled: bool,
///
// Set to true (1) to disable configuration of browser process features using
// standard CEF and Chromium command-line arguments. Configuration can still
// be specified using CEF data structures or via the
// CefApp::OnBeforeCommandLineProcessing() method.
///
pub command_line_args_disabled: c_int,
///
// The location where cache data will be stored on disk. If empty an in-memory
// cache will be used for some features and a temporary disk cache for others.
// HTML5 databases such as localStorage will only persist across sessions if a
// cache path is specified.
///
pub cache_path: cef_string_t,
///
// To persist session cookies (cookies without an expiry date or validity
// interval) by default when using the global cookie manager set this value to
// true. Session cookies are generally intended to be transient and most Web
// browsers do not persist them. A |cache_path| value must also be specified to
// enable this feature. Also configurable using the "persist-session-cookies"
// command-line switch.
///
pub persist_session_cookies: c_int,
///
// Value that will be returned as the User-Agent HTTP header. If empty the
// default User-Agent string will be used. Also configurable using the
// "user-agent" command-line switch.
///
pub user_agent: cef_string_t,
///
// Value that will be inserted as the product portion of the default
// User-Agent string. If empty the Chromium product version will be used. If
// |userAgent| is specified this value will be ignored. Also configurable
// using the "product-version" command-line switch.
///
pub product_version: cef_string_t,
///
// The locale string that will be passed to WebKit. If empty the default
// locale of "en-US" will be used. This value is ignored on Linux where locale
// is determined using environment variable parsing with the precedence order:
// LANGUAGE, LC_ALL, LC_MESSAGES and LANG. Also configurable using the "lang"
// command-line switch.
///
pub locale: cef_string_t,
///
// The directory and file name to use for the debug log. If empty, the
// default name of "debug.log" will be used and the file will be written
// to the application directory. Also configurable using the "log-file"
// command-line switch.
///
pub log_file: cef_string_t,
///
// The log severity. Only messages of this severity level or higher will be
// logged. Also configurable using the "log-severity" command-line switch with
// a value of "verbose", "info", "warning", "error", "error-report" or
// "disable".
///
pub log_severity: cef_log_severity_t,
///
// Enable DCHECK in release mode to ease debugging. Also configurable using the
// "enable-release-dcheck" command-line switch.
///
pub release_dcheck_enabled: c_int,
///
// Custom flags that will be used when initializing the V8 JavaScript engine.
// The consequences of using custom flags may not be well tested. Also
// configurable using the "js-flags" command-line switch.
///
pub javascript_flags: cef_string_t,
///
// The fully qualified path for the resources directory. If this value is
// empty the cef.pak and/or devtools_resources.pak files must be located in
// the module directory on Windows/Linux or the app bundle Resources directory
// on Mac OS X. Also configurable using the "resources-dir-path" command-line
// switch.
///
pub resources_dir_path: cef_string_t,
///
// The fully qualified path for the locales directory. If this value is empty
// the locales directory must be located in the module directory. This value
// is ignored on Mac OS X where pack files are always loaded from the app
// bundle Resources directory. Also configurable using the "locales-dir-path"
// command-line switch.
///
pub locales_dir_path: cef_string_t,
///
// Set to true (1) to disable loading of pack files for resources and locales.
// A resource bundle handler must be provided for the browser and render
// processes via CefApp::GetResourceBundleHandler() if loading of pack files
// is disabled. Also configurable using the "disable-pack-loading" command-
// line switch.
///
pub pack_loading_disabled: c_int,
///
// Set to a value between 1024 and 65535 to enable remote debugging on the
// specified port. For example, if 8080 is specified the remote debugging URL
// will be http://localhost:8080. CEF can be remotely debugged from any CEF or
// Chrome browser window. Also configurable using the "remote-debugging-port"
// command-line switch.
///
pub remote_debugging_port: c_int,
///
// The number of stack trace frames to capture for uncaught exceptions.
// Specify a positive value to enable the CefV8ContextHandler::
// OnUncaughtException() callback. Specify 0 (default value) and
// OnUncaughtException() will not be called. Also configurable using the
// "uncaught-exception-stack-size" command-line switch.
///
pub uncaught_exception_stack_size: c_int,
///
// By default CEF V8 references will be invalidated (the IsValid() method will
// return false) after the owning context has been released. This reduces the
// need for external record keeping and avoids crashes due to the use of V8
// references after the associated context has been released.
//
// CEF currently offers two context safety implementations with different
// performance characteristics. The default implementation (value of 0) uses a
// map of hash values and should provide better performance in situations with
// a small number contexts. The alternate implementation (value of 1) uses a
// hidden value attached to each context and should provide better performance
// in situations with a large number of contexts.
//
// If you need better performance in the creation of V8 references and you
// plan to manually track context lifespan you can disable context safety by
// specifying a value of -1.
//
// Also configurable using the "context-safety-implementation" command-line
// switch.
///
pub context_safety_implementation: c_int,
///
// Set to true (1) to ignore errors related to invalid SSL certificates.
// Enabling this setting can lead to potential security vulnerabilities like
// "man in the middle" attacks. Applications that load content from the
// internet should not enable this setting. Also configurable using the
// "ignore-certificate-errors" command-line switch.
///
pub ignore_certificate_errors: c_int,
///
// Opaque background color used for accelerated content. By default the
// background color will be white. Only the RGB compontents of the specified
// value will be used. The alpha component must greater than 0 to enable use
// of the background color but will be otherwise ignored.
///
pub background_color: cef_color_t,
}
///
// Structure defining the reference count implementation functions. All
// framework structures must include the cef_base_t structure first.
///
pub type cef_base_t = cef_base;
pub struct cef_base {
///
// Size of the data structure.
///
pub size: size_t,
///
// Increment the reference count.
///
pub add_ref: extern "C" fn(base: *mut cef_base) -> c_int,
///
// Decrement the reference count. Delete this object when no references
// remain.
///
pub release: extern "C" fn(base: *mut cef_base) -> c_int,
///
// Returns the current number of references.
///
pub get_refct: extern "C" fn(base: *mut cef_base) -> c_int,
}
///
// Structure used to create and/or parse command line arguments. Arguments with
// '--', '-' and, on Windows, '/' prefixes are considered switches. Switches
// will always precede any arguments without switch prefixes. Switches can
// optionally have a value specified using the '=' delimiter (e.g.
// "-switch=value"). An argument of "--" will terminate switch parsing with all
// subsequent tokens, regardless of prefix, being interpreted as non-switch
// arguments. Switch names are considered case-insensitive. This structure can
// be used before cef_initialize() is called.
///
pub type cef_command_line_t = cef_command_line;
pub struct cef_command_line {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(cmd: *mut cef_command_line),
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(cmd: *mut cef_command_line),
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_command_line,
///
// Initialize the command line with the specified |argc| and |argv| values.
// The first argument must be the name of the program. This function is only
// supported on non-Windows platforms.
///
pub init_from_argv: extern "C" fn(cmd: *mut cef_command_line, argc: c_int, argv: *u8),
///
// Initialize the command line with the string returned by calling
// GetCommandLineW(). This function is only supported on Windows.
///
pub init_from_string: extern "C" fn(cmd: *mut cef_command_line, command_line: *cef_string_t),
///
// Reset the command-line switches and arguments but leave the program
// component unchanged.
///
pub reset: extern "C" fn(cmd: *mut cef_command_line),
///
// Retrieve the original command line string as a vector of strings. The argv
// array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
///
pub get_argv: extern "C" fn(cmd: *mut cef_command_line, argv: *mut cef_string_list_t),
///
// Constructs and returns the represented command line string. Use this
// function cautiously because quoting behavior is unclear.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_command_line_string: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_string_userfree_t,
///
// Get the program part of the command line string (the first item).
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_program: extern "C" fn(cmd: *mut cef_command_line) -> *mut cef_string_userfree_t,
///
// Set the program part of the command line string (the first item).
///
pub set_program: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t),
///
// Returns true (1) if the command line has switches.
///
pub has_switches: extern "C" fn(cmd: *mut cef_command_line) -> c_int,
///
// Returns true (1) if the command line contains the given switch.
///
pub has_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> c_int,
///
// Returns the value associated with the given switch. If the switch has no
// value or isn't present this function returns the NULL string.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_switch_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> *mut cef_string_userfree_t,
///
// Returns the map of switch names and values. If a switch has no value an
// NULL string is returned.
///
pub get_switches: extern "C" fn(cmd: *mut cef_command_line, switches: cef_string_map_t),
///
// Add a switch to the end of the command line. If the switch has no value
// pass an NULL value string.
///
pub append_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t),
///
// Add a switch with the specified value to the end of the command line.
///
pub append_switch_with_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t, value: *cef_string_t),
///
// True if there are remaining command line arguments.
///
pub has_arguments: extern "C" fn(cmd: *mut cef_command_line) -> c_int,
///
// Get the remaining command line arguments.
///
pub get_arguments: extern "C" fn(cmd: *mut cef_command_line, arguments: *mut cef_string_list_t),
///
// Add an argument to the end of the command line.
///
pub append_argument: extern "C" fn(cmd: *mut cef_command_line, argument: *cef_string_t),
///
// Insert a command before the current command. Common for debuggers, like
// "valgrind" or "gdb --args".
///
pub prepend_wrapper: extern "C" fn(cmd: *mut cef_command_line, wrapper: *cef_string_t),
}
///
// Structure that manages custom scheme registrations.
///
pub type cef_scheme_registrar_t = cef_scheme_registrar;
pub struct cef_scheme_registrar {
///
// Base structure.
///
pub base: cef_base,
///
// Register a custom scheme. This function should not be called for the built-
// in HTTP, HTTPS, FILE, FTP, ABOUT and DATA schemes.
//
// If |is_standard| is true (1) the scheme will be treated as a standard
// scheme. Standard schemes are subject to URL canonicalization and parsing
// rules as defined in the Common Internet Scheme Syntax RFC 1738 Section 3.1
// available at http://www.ietf.org/rfc/rfc1738.txt
//
// In particular, the syntax for standard scheme URLs must be of the form:
// <pre>
// [scheme]://[username]:[password]@[host]:[port]/[url-path]
// </pre Standard scheme URLs must have a host component that is a fully
// qualified domain name as defined in Section 3.5 of RFC 1034 [13] and
// Section 2.1 of RFC 1123. These URLs will be canonicalized to
// "scheme://host/path" in the simplest case and
// "scheme://username:password@host:port/path" in the most explicit case. For
// example, "scheme:host/path" and "scheme:///host/path" will both be
// canonicalized to "scheme://host/path". The origin of a standard scheme URL
// is the combination of scheme, host and port (i.e., "scheme://host:port" in
// the most explicit case).
//
// For non-standard scheme URLs only the "scheme:" component is parsed and
// canonicalized. The remainder of the URL will be passed to the handler as-
// is. For example, "scheme:///some%20text" will remain the same. Non-standard
// scheme URLs cannot be used as a target for form submission.
//
// If |is_local| is true (1) the scheme will be treated as local (i.e., with
// the same security rules as those applied to "file" URLs). Normal pages
// cannot link to or access local URLs. Also, by default, local URLs can only
// perform XMLHttpRequest calls to the same URL (origin + path) that
// originated the request. To allow XMLHttpRequest calls from a local URL to
// other URLs with the same origin set the
// CefSettings.file_access_from_file_urls_allowed value to true (1). To allow
// XMLHttpRequest calls from a local URL to all origins set the
// CefSettings.universal_access_from_file_urls_allowed value to true (1).
//
// If |is_display_isolated| is true (1) the scheme will be treated as display-
// isolated. This means that pages cannot display these URLs unless they are
// from the same scheme. For example, pages in another origin cannot create
// iframes or hyperlinks to URLs with this scheme.
//
// This function may be called on any thread. It should only be called once
// per unique |scheme_name| value. If |scheme_name| is already registered or
// if an error occurs this function will return false (0).
///
add_custom_scheme: extern "C" fn(registrar: *mut cef_scheme_registrar,
scheme_name: *cef_string_t,
is_standard: c_int, is_local: c_int, is_display_isolated: c_int),
}
///
// Structure used to implement a custom resource bundle structure. The functions
// of this structure may be called on multiple threads.
///
pub type cef_resource_bundle_handler_t = cef_resource_bundle_handler;
pub struct cef_resource_bundle_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called to retrieve a localized translation for the string specified by
// |message_id|. To provide the translation set |string| to the translation
// string and return true (1). To use the default translation return false
// (0). Supported message IDs are listed in cef_pack_strings.h.
///
pub get_localized_string: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler,
message_id: c_int, string: *mut cef_string_t) -> c_int,
///
// Called to retrieve data for the resource specified by |resource_id|. To
// provide the resource data set |data| and |data_size| to the data pointer
// and size respectively and return true (1). To use the default resource data
// return false (0). The resource data will not be copied and must remain
// resident in memory. Supported resource IDs are listed in
// cef_pack_resources.h.
///
pub get_data_resource: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler,
resource_id: c_int, data: **mut c_void, data_size: *mut size_t) -> c_int,
}
///
// Structure representing a list value. Can be used on any process and thread.
///
pub type cef_list_value_t = cef_list_value;
pub struct cef_list_value {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is valid. Do not call any other functions
// if this function returns false (0).
///
pub is_valid: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns true (1) if this object is currently owned by another object.
///
pub is_owned: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns true (1) if the values of this object are read-only. Some APIs may
// expose read-only objects.
///
pub is_read_only: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns a writable copy of this object.
///
pub copy: extern "C" fn(list_value: *mut cef_list_value) -> *mut cef_list_value,
///
// Sets the number of values. If the number of values is expanded all new
// value slots will default to type null. Returns true (1) on success.
///
pub set_size: extern "C" fn(list_value: *mut cef_list_value, size: size_t) -> c_int,
///
// Returns the number of values.
///
pub get_size: extern "C" fn(list_value: *mut cef_list_value) -> size_t,
///
// Removes all values. Returns true (1) on success.
///
pub clear: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Removes the value at the specified index.
///
pub remove: extern "C" fn(list_value: *mut cef_list_value) -> c_int,
///
// Returns the value type at the specified index.
///
pub get_type: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> cef_value_type_t,
///
// Returns the value at the specified index as type bool.
///
pub get_bool: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Returns the value at the specified index as type int.
///
pub get_int: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Returns the value at the specified index as type double.
///
pub get_double: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_double,
///
// Returns the value at the specified index as type string.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_string_userfree_t,
///
// Returns the value at the specified index as type binary.
///
pub get_binary: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_binary_value,
///
// Returns the value at the specified index as type dictionary.
///
pub get_dictionary: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_dictionary_value,
///
// Returns the value at the specified index as type list.
///
pub get_list: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> *mut cef_list_value,
///
// Sets the value at the specified index as type null. Returns true (1) if the
// value was set successfully.
///
pub set_null: extern "C" fn(list_value: *mut cef_list_value, index: c_int) -> c_int,
///
// Sets the value at the specified index as type bool. Returns true (1) if the
// value was set successfully.
///
pub set_bool: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_int) -> c_int,
///
// Sets the value at the specified index as type int. Returns true (1) if the
// value was set successfully.
///
pub set_int: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_int) -> c_int,
///
// Sets the value at the specified index as type double. Returns true (1) if
// the value was set successfully.
///
pub set_double: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: c_double) -> c_int,
///
// Sets the value at the specified index as type string. Returns true (1) if
// the value was set successfully.
///
pub set_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *cef_string_t) -> c_int,
///
// Sets the value at the specified index as type binary. Returns true (1) if
// the value was set successfully. After calling this function the |value|
// object will no longer be valid. If |value| is currently owned by another
// object then the value will be copied and the |value| reference will not
// change. Otherwise, ownership will be transferred to this object and the
// |value| reference will be invalidated.
///
pub set_binary: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_binary_value) -> c_int,
///
// Sets the value at the specified index as type dict. Returns true (1) if the
// value was set successfully. After calling this function the |value| object
// will no longer be valid. If |value| is currently owned by another object
// then the value will be copied and the |value| reference will not change.
// Otherwise, ownership will be transferred to this object and the |value|
// reference will be invalidated.
///
pub set_dictionary: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_dictionary_value) -> c_int,
///
// Sets the value at the specified index as type list. Returns true (1) if the
// value was set successfully. After calling this function the |value| object
// will no longer be valid. If |value| is currently owned by another object
// then the value will be copied and the |value| reference will not change.
// Otherwise, ownership will be transferred to this object and the |value|
// reference will be invalidated.
///
pub set_list: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *mut cef_list_value) -> c_int,
}
///
// Structure used to implement browser process callbacks. The functions of this
// structure will be called on the browser process main thread unless otherwise
// indicated.
///
pub type cef_browser_process_handler_t = cef_browser_process_handler;
pub struct cef_browser_process_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called on the browser process UI thread immediately after the CEF context
// has been initialized.
///
pub on_context_initialized: extern "C" fn(browser_handler: *mut cef_browser_process_handler),
///
// Called before a child process is launched. Will be called on the browser
// process UI thread when launching a render process and on the browser
// process IO thread when launching a GPU or plugin process. Provides an
// opportunity to modify the child process command line. Do not keep a
// reference to |command_line| outside of this function.
///
pub on_before_child_process_launch: extern "C" fn(browser_handler: *mut cef_browser_process_handler, command_line: *mut cef_command_line),
///
// Called on the browser process IO thread after the main thread has been
// created for a new render process. Provides an opportunity to specify extra
// information that will be passed to
// cef_render_process_handler_t::on_render_thread_created() in the render
// process. Do not keep a reference to |extra_info| outside of this function.
///
pub on_render_process_thread_created: extern "C" fn(browser_handler: *mut cef_browser_process_handler, extra_info: *mut cef_list_value),
}
///
// Callback structure for cef_browser_host_t::RunFileDialog. The functions of
// this structure will be called on the browser process UI thread.
///
pub type cef_run_file_dialog_callback_t = cef_run_file_dialog_callback;
pub struct cef_run_file_dialog_callback {
///
// Base structure.
///
pub base: cef_base,
///
// Called asynchronously after the file dialog is dismissed. If the selection
// was successful |file_paths| will be a single value or a list of values
// depending on the dialog mode. If the selection was cancelled |file_paths|
// will be NULL.
///
pub cont: extern "C" fn(run_file_dialog_callback: *mut cef_run_file_dialog_callback,
browser_host: *mut cef_browser_host,
file_paths: *mut cef_string_list_t),
}
///
// Structure used to represent the browser process aspects of a browser window.
// The functions of this structure can only be called in the browser process.
// They may be called on any thread in that process unless otherwise indicated
// in the comments.
///
pub type cef_browser_host_t = cef_browser_host;
pub struct cef_browser_host {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the hosted browser object.
///
pub get_browser: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_browser,
///
// Call this function before destroying a contained browser window. This
// function performs any internal cleanup that may be needed before the
// browser window is destroyed. See cef_life_span_handler_t::do_close()
// documentation for additional usage information.
///
pub parent_window_will_close: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Request that the browser close. The JavaScript 'onbeforeunload' event will
// be fired. If |force_close| is false (0) the event handler, if any, will be
// allowed to prompt the user and the user can optionally cancel the close. If
// |force_close| is true (1) the prompt will not be displayed and the close
// will proceed. Results in a call to cef_life_span_handler_t::do_close() if
// the event handler allows the close or if |force_close| is true (1). See
// cef_life_span_handler_t::do_close() documentation for additional usage
// information.
///
pub close_browser: extern "C" fn(browser_host: *mut cef_browser_host, force_close: c_int),
///
// Set focus for the browser window. If |enable| is true (1) focus will be set
// to the window. Otherwise, focus will be removed.
///
pub set_focus: extern "C" fn(browser_host: *mut cef_browser_host, force_close: c_int),
///
// Retrieve the window handle for this browser.
///
pub get_window_handle: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_window_handle_t,
///
// Retrieve the window handle of the browser that opened this browser. Will
// return NULL for non-popup windows. This function can be used in combination
// with custom handling of modal windows.
///
pub get_opener_window_handle: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_window_handle_t,
///
// Returns the client for this browser.
///
pub get_client: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_client_t,
///
// Returns the request context for this browser.
///
pub get_request_context: extern "C" fn(browser_host: *mut cef_browser_host) -> *mut cef_request_context_t,
///
// Get the current zoom level. The default zoom level is 0.0. This function
// can only be called on the UI thread.
///
pub get_zoom_level: extern "C" fn(browser_host: *mut cef_browser_host) -> c_double,
///
// Change the zoom level to the specified value. Specify 0.0 to reset the zoom
// level. If called on the UI thread the change will be applied immediately.
// Otherwise, the change will be applied asynchronously on the UI thread.
///
pub set_zoom_level: extern "C" fn(browser_host: *mut cef_browser_host, zoomLevel: c_double),
///
// Call to run a file chooser dialog. Only a single file chooser dialog may be
// pending at any given time. |mode| represents the type of dialog to display.
// |title| to the title to be used for the dialog and may be NULL to show the
// default title ("Open" or "Save" depending on the mode). |default_file_name|
// is the default file name to select in the dialog. |accept_types| is a list
// of valid lower-cased MIME types or file extensions specified in an input
// element and is used to restrict selectable files to such types. |callback|
// will be executed after the dialog is dismissed or immediately if another
// dialog is already pending. The dialog will be initiated asynchronously on
// the UI thread.
///
pub run_file_dialog: extern "C" fn(browser_host: *mut cef_browser_host,
mode: cef_file_dialog_mode_t, title: *cef_string_t,
default_file_name: *cef_string_t, accept_types: *mut cef_string_list_t,
callback: *mut cef_run_file_dialog_callback),
///
// Download the file at |url| using cef_download_handler_t.
///
pub start_download: extern "C" fn(browser_host: *mut cef_browser_host, url: *cef_string_t),
///
// Print the current browser contents.
///
pub print: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Search for |searchText|. |identifier| can be used to have multiple searches
// running simultaniously. |forward| indicates whether to search forward or
// backward within the page. |matchCase| indicates whether the search should
// be case-sensitive. |findNext| indicates whether this is the first request
// or a follow-up.
///
pub find: extern "C" fn(browser_host: *mut cef_browser_host, identifier: c_int, searchText: *cef_string_t,
forward: c_int, matchCase: c_int, findNext: c_int),
///
// Cancel all searches that are currently going on.
///
pub stop_finding: extern "C" fn(browser_host: *mut cef_browser_host, clearSelection: c_int),
///
// Open developer tools in its own window.
///
pub show_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host,
windowInfo: *cef_window_info_t,
client: *mut cef_client_t,
settings: *cef_browser_settings_t),
///
// Explicitly close the developer tools window if one exists for this browser
// instance.
///
pub close_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Set whether mouse cursor change is disabled.
///
pub set_mouse_cursor_change_disabled: extern "C" fn(browser_host: *mut cef_browser_host,
disabled: c_int),
///
// Returns true (1) if mouse cursor change is disabled.
///
pub is_mouse_cursor_change_disabled: extern "C" fn(browser_host: *mut cef_browser_host) -> c_int,
///
// Returns true (1) if window rendering is disabled.
///
pub is_window_rendering_disabled: extern "C" fn(browser_host: *mut cef_browser_host) -> c_int,
///
// Notify the browser that the widget has been resized. The browser will first
// call cef_render_handler_t::GetViewRect to get the new size and then call
// cef_render_handler_t::OnPaint asynchronously with the updated regions. This
// function is only used when window rendering is disabled.
///
pub was_resized: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Notify the browser that it has been hidden or shown. Layouting and
// cef_render_handler_t::OnPaint notification will stop when the browser is
// hidden. This function is only used when window rendering is disabled.
///
pub was_hidden: extern "C" fn(browser_host: *mut cef_browser_host, hidden: c_int),
///
// Send a notification to the browser that the screen info has changed. The
// browser will then call cef_render_handler_t::GetScreenInfo to update the
// screen information with the new values. This simulates moving the webview
// window from one display to another, or changing the properties of the
// current display. This function is only used when window rendering is
// disabled.
///
pub notify_screen_info_changed: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Invalidate the |dirtyRect| region of the view. The browser will call
// cef_render_handler_t::OnPaint asynchronously with the updated regions. This
// function is only used when window rendering is disabled.
///
pub invalidate: extern "C" fn(browser_host: *mut cef_browser_host,
dirtyRect: *cef_rect, t: cef_paint_element_type_t),
///
// Send a key event to the browser.
///
pub send_key_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_key_event),
///
// Send a mouse click event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view.
///
pub send_mouse_click_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event,
t: cef_mouse_button_type_t,
mouseUp: c_int, clickCount: c_int),
///
// Send a mouse move event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view.
///
pub send_mouse_move_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, mouseLeave: c_int),
///
// Send a mouse wheel event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view. The |deltaX| and |deltaY|
// values represent the movement delta in the X and Y directions respectively.
// In order to scroll inside select popups with window rendering disabled
// cef_render_handler_t::GetScreenPoint should be implemented properly.
///
pub send_mouse_wheel_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, deltaX: c_int, deltaY: c_int),
///
// Send a focus event to the browser.
///
pub send_focus_event: extern "C" fn(browser_host: *mut cef_browser_host, setFocus: c_int),
///
// Send a capture lost event to the browser.
///
pub send_capture_lost_event: extern "C" fn(browser_host: *mut cef_browser_host),
///
// Get the NSTextInputContext implementation for enabling IME on Mac when
// window rendering is disabled.
///
pub get_nstext_input_context: extern "C" fn(browser_host: *mut cef_browser_host) -> cef_text_input_context_t,
///
// Handles a keyDown event prior to passing it through the NSTextInputClient
// machinery.
///
pub handle_key_event_before_text_input_client: extern "C" fn(browser_host: *mut cef_browser_host,
key_event: *mut cef_event_handle_t),
///
// Performs any additional actions after NSTextInputClient handles the event.
///
pub handle_key_event_after_text_input_client: extern "C" fn(browser_host: *mut cef_browser_host,
key_event: *mut cef_event_handle_t),
}
///
// Structure used to represent a browser window. When used in the browser
// process the functions of this structure may be called on any thread unless
// otherwise indicated in the comments. When used in the render process the
// functions of this structure may only be called on the main thread.
///
pub type cef_browser_t = cef_browser;
pub struct cef_browser {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the browser host object. This function can only be called in the
// browser process.
///
pub get_host: extern "C" fn(browser: *mut cef_browser) -> *mut cef_browser_host,
///
// Returns true (1) if the browser can navigate backwards.
///
pub can_go_back: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Navigate backwards.
///
pub go_back: extern "C" fn(browser: *mut cef_browser),
///
// Returns true (1) if the browser can navigate forwards.
///
pub can_go_forward: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Navigate forwards.
///
pub go_forward: extern "C" fn(browser: *mut cef_browser),
///
// Returns true (1) if the browser is currently loading.
///
pub is_loading: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Reload the current page.
///
pub reload: extern "C" fn(browser: *mut cef_browser),
///
// Reload the current page ignoring any cached data.
///
pub reload_ignore_cache: extern "C" fn(browser: *mut cef_browser),
///
// Stop loading the page.
///
pub stop_load: extern "C" fn(browser: *mut cef_browser),
///
// Returns the globally unique identifier for this browser.
///
pub get_identifier: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns true (1) if this object is pointing to the same handle as |that|
// object.
///
pub is_same: extern "C" fn(browser: *mut cef_browser, that: *mut cef_browser) -> c_int,
///
// Returns true (1) if the window is a popup window.
///
pub is_popup: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns true (1) if a document has been loaded in the browser.
///
pub has_document: extern "C" fn(browser: *mut cef_browser) -> c_int,
///
// Returns the main (top-level) frame for the browser window.
///
pub get_main_frame: extern "C" fn(browser: *mut cef_browser) -> *mut cef_frame,
///
// Returns the focused frame for the browser window.
///
pub get_focused_frame: extern "C" fn(browser: *mut cef_browser) -> *mut cef_frame,
///
// Returns the frame with the specified identifier, or NULL if not found.
///
pub get_frame_byident: extern "C" fn(browser: *mut cef_browser, identifier: c_longlong) -> *mut cef_frame,
///
// Returns the frame with the specified name, or NULL if not found.
///
pub get_frame: extern "C" fn(browser: *mut cef_browser, name: *cef_string_t) -> *mut cef_frame,
///
// Returns the number of frames that currently exist.
///
pub get_frame_count: extern "C" fn(browser: *mut cef_browser) -> size_t,
///
// Returns the identifiers of all existing frames.
///
pub get_frame_identifiers: extern "C" fn(browser: *mut cef_browser,
identifiersCount: *mut size_t,
identifiers: *mut c_longlong),
///
// Returns the names of all existing frames.
///
pub get_frame_names: extern "C" fn(browser: *mut cef_browser, names: *mut cef_string_list_t),
//
// Send a message to the specified |target_process|. Returns true (1) if the
// message was sent successfully.
///
pub send_process_message: extern "C" fn(browser: *mut cef_browser, target_process: cef_process_id_t,
message: *mut cef_process_message) -> c_int,
}
///
// Structure used to implement render process callbacks. The functions of this
// structure will be called on the render process main thread (TID_RENDERER)
// unless otherwise indicated.
///
pub type cef_render_process_handler_t = cef_render_process_handler;
pub struct cef_render_process_handler {
///
// Base structure.
///
pub base: cef_base,
///
// Called after the render process main thread has been created. |extra_info|
// is a read-only value originating from
// cef_browser_process_handler_t::on_render_process_thread_created(). Do not
// keep a reference to |extra_info| outside of this function.
///
pub on_render_thread_created: extern "C" fn(render_handler: *mut cef_render_process_handler, extra_info: *mut cef_list_value),
///
// Called after WebKit has been initialized.
///
pub on_web_kit_initialized: extern "C" fn(render_handler: *mut cef_render_process_handler),
///
// Called after a browser has been created. When browsing cross-origin a new
// browser will be created before the old browser with the same identifier is
// destroyed.
///
pub on_browser_created: extern "C" fn(render_handler: *mut cef_render_process_handler, browser: *mut cef_browser),
///
// Called before a browser is destroyed.
///
pub on_browser_destroyed: extern "C" fn(render_handler: *mut cef_render_process_handler, browser: *mut cef_browser),
///
// Return the handler for browser load status events.
///
pub get_load_handler: extern "C" fn(render_handler: *mut cef_render_process_handler) -> *mut cef_load_handler,
///
// Called before browser navigation. Return true (1) to cancel the navigation
// or false (0) to allow the navigation to proceed. The |request| object
// cannot be modified in this callback.
///
pub on_before_navigation: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
request: *mut cef_request,
navigation_type: *mut cef_navigation_type,
is_redirect: c_int) -> c_int,
///
// Called immediately after the V8 context for a frame has been created. To
// retrieve the JavaScript 'window' object use the
// cef_v8context_t::get_global() function. V8 handles can only be accessed
// from the thread on which they are created. A task runner for posting tasks
// on the associated thread can be retrieved via the
// cef_v8context_t::get_task_runner() function.
///
pub on_context_created: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context),
///
// Called immediately before the V8 context for a frame is released. No
// references to the context should be kept after this function is called.
///
pub on_context_released: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context),
///
// Called for global uncaught exceptions in a frame. Execution of this
// callback is disabled by default. To enable set
// CefSettings.uncaught_exception_stack_size 0.
///
pub on_uncaught_exception: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
context: *mut cef_v8context,
exception: *mut cef_v8exception,
stackTrace: *mut cef_v8stack_trace),
///
// Called when a new node in the the browser gets focus. The |node| value may
// be NULL if no specific node has gained focus. The node object passed to
// this function represents a snapshot of the DOM at the time this function is
// executed. DOM objects are only valid for the scope of this function. Do not
// keep references to or attempt to access any DOM objects outside the scope
// of this function.
///
pub on_focused_node_changed: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
frame: *mut cef_frame,
node: *mut cef_domnode),
///
// Called when a new message is received from a different process. Return true
// (1) if the message was handled or false (0) otherwise. Do not keep a
// reference to or attempt to access the message outside of this callback.
///
pub on_process_message_received: extern "C" fn(render_handler: *mut cef_render_process_handler,
browser: *mut cef_browser,
source_process: cef_process_id_t,
message: *mut cef_process_message) ->c_int,
}
///
// Implement this structure to provide handler implementations. Methods will be
// called by the process and/or thread indicated.
///
pub type cef_app_t = cef_app;
pub struct cef_app {
///
// Base structure.
///
pub base: cef_base,
///
// Provides an opportunity to view and/or modify command-line arguments before
// processing by CEF and Chromium. The |process_type| value will be NULL for
// the browser process. Do not keep a reference to the cef_command_line_t
// object passed to this function. The CefSettings.command_line_args_disabled
// value can be used to start with an NULL command-line object. Any values
// specified in CefSettings that equate to command-line arguments will be set
// before this function is called. Be cautious when using this function to
// modify command-line arguments for non-browser processes as this may result
// in undefined behavior including crashes.
///
pub on_before_command_line_processing: extern "C" fn(app: *mut cef_app_t, process_type: *cef_string_t, command_line: *mut cef_command_line),
///
// Provides an opportunity to register custom schemes. Do not keep a reference
// to the |registrar| object. This function is called on the main thread for
// each process and the registered schemes should be the same across all
// processes.
///
pub on_register_custom_schemes: extern "C" fn(app: *mut cef_app_t, registrar: *mut cef_scheme_registrar),
///
// Return the handler for resource bundle events. If
// CefSettings.pack_loading_disabled is true (1) a handler must be returned.
// If no handler is returned resources will be loaded from pack files. This
// function is called by the browser and render processes on multiple threads.
///
pub get_resource_bundle_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_resource_bundle_handler,
///
// Return the handler for functionality specific to the browser process. This
// function is called on multiple threads in the browser process.
///
pub get_browser_process_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_browser_process_handler,
///
// Return the handler for functionality specific to the render process. This
// function is called on the render process main thread.
///
pub get_render_process_handler: extern "C" fn(app: *mut cef_app_t) -> *mut cef_render_process_handler,
}
///
// Structure used to make a URL request. URL requests are not associated with a
// browser instance so no cef_client_t callbacks will be executed. URL requests
// can be created on any valid CEF thread in either the browser or render
// process. Once created the functions of the URL request object must be
// accessed on the same thread that created it.
///
pub type cef_urlrequest_t = cef_urlrequest;
pub struct cef_urlrequest {
///
// Base structure.
///
pub base: cef_base,
///
// Returns the request object used to create this URL request. The returned
// object is read-only and should not be modified.
///
pub get_request: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_request_t,
///
// Returns the client.
///
pub get_client: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_urlrequest_client_t,
///
// Returns the request status.
///
pub get_request_status: extern "C" fn(url_req: *mut cef_urlrequest) -> cef_urlrequest_status_t,
///
// Returns the request error if status is UR_CANCELED or UR_FAILED, or 0
// otherwise.
///
pub get_request_error: extern "C" fn(url_req: *mut cef_urlrequest) -> cef_errorcode_t,
///
// Returns the response, or NULL if no response information is available.
// Response information will only be available after the upload has completed.
// The returned object is read-only and should not be modified.
///
pub get_response: extern "C" fn(url_req: *mut cef_urlrequest) -> *mut cef_response_t,
///
// Cancel the request.
///
pub cancel: extern "C" fn(url_req: *mut cef_urlrequest),
}
///
// Structure used to represent a single element in the request post data. The
// functions of this structure may be called on any thread.
///
pub type cef_post_data_element_t = cef_post_data_element;
pub struct cef_post_data_element {
///
// Base structure.
///
pub base: cef_base,
///
// Returns true (1) if this object is read-only.
///
pub is_read_only: extern "C" fn(post_data_element: *mut cef_post_data_element) -> c_int,
///
// Remove all contents from the post data element.
///
pub set_to_empty: extern "C" fn(post_data_element: *mut cef_post_data_element),
///
// The post data element will represent a file.
///
pub set_to_file: extern "C" fn(post_data_element: *mut cef_post_data_element, fileName: *cef_string_t),
///
// The post data element will represent bytes. The bytes passed in will be
// copied.
///
pub set_to_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element,
size: size_t, bytes: *c_void),
///
// Return the type of this post data element.
///
pub get_type: extern "C" fn(post_data_element: *mut cef_post_data_element) -> cef_postdataelement_type_t,
///
// Return the file name.
///
// The resulting string must be freed by calling cef_string_userfree_free().
pub get_file: extern "C" fn(post_data_element: *mut cef_post_data_element) -> *mut cef_string_userfree_t,
///
// Return the number of bytes.
///
pub get_bytes_count: extern "C" fn(post_data_element: *mut cef_post_data_element) -> size_t,
///
// Read up to |size| bytes into |bytes| and return the number of bytes
// actually read.
///
pub get_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element,
size: size_t, bytes: *mut c_void) -> size_t,
}
///
// Structure used to represent post data for a web request. The functions of
// this structure may be called on any thread.
///
pub type cef_post_data_t = cef_post_data;
pub struct cef_post_data {
///
// Base structure.
///
pub base: cef_base_t,
///
// Returns true (1) if this object is read-only.
///
pub is_read_only: extern "C" fn(post_data: *mut cef_post_data) -> c_int,
///
// Returns the number of existing post data elements.
///
pub get_element_count: extern "C" fn(post_data: *mut cef_post_data) -> size_t,
///
// Retrieve the post data elements.
///
pub get_elements: extern "C" fn(post_data: *mut cef_post_data,
elements_count: *mut size_t, elements: **mut cef_post_data_element),
///
// Remove the specified post data element. Returns true (1) if the removal
// succeeds.
///
pub remove_element: extern "C" fn(post_data: *mut cef_post_data,
element: *mut cef_post_data_element) -> c_int,
///
// Add the specified post data element. Returns true (1) if the add succeeds.
///
pub add_element: extern "C" fn(post_data: *mut cef_post_data,
element: *mut cef_post_data_element) -> c_int,
///
// Remove all existing post data elements.
///
pub remove_elements: extern "C" fn(post_data: *mut cef_post_data),
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The core DOM types. Defines the basic DOM hierarchy as well as all the HTML elements.
use cssparser::tokenize;
use dom::attr::{Attr, AttrMethods};
use dom::bindings::codegen::InheritTypes::{CommentCast, DocumentCast, DocumentTypeCast};
use dom::bindings::codegen::InheritTypes::{ElementCast, TextCast, NodeCast, ElementDerived};
use dom::bindings::codegen::InheritTypes::{CharacterDataCast, NodeBase, NodeDerived};
use dom::bindings::codegen::InheritTypes::{ProcessingInstructionCast, EventTargetCast};
use dom::bindings::codegen::Bindings::NodeBinding::NodeConstants;
use dom::bindings::error::{ErrorResult, Fallible, NotFound, HierarchyRequest, Syntax};
use dom::bindings::global::{GlobalRef, Window};
use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, Root, OptionalUnrootable};
use dom::bindings::js::{OptionalSettable, TemporaryPushable, OptionalRootedRootable};
use dom::bindings::js::{ResultRootable, OptionalRootable};
use dom::bindings::trace::Traceable;
use dom::bindings::utils;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::characterdata::{CharacterData, CharacterDataMethods};
use dom::comment::Comment;
use dom::document::{Document, DocumentMethods, DocumentHelpers, HTMLDocument, NonHTMLDocument};
use dom::documentfragment::DocumentFragment;
use dom::documenttype::DocumentType;
use dom::element::{AttributeHandlers, Element, ElementMethods, ElementTypeId};
use dom::element::{HTMLAnchorElementTypeId, ElementHelpers};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::nodelist::{NodeList};
use dom::processinginstruction::{ProcessingInstruction, ProcessingInstructionMethods};
use dom::text::Text;
use dom::virtualmethods::{VirtualMethods, vtable_for};
use dom::window::Window;
use geom::rect::Rect;
use html::hubbub_html_parser::build_element_from_tag;
use layout_interface::{ContentBoxQuery, ContentBoxResponse, ContentBoxesQuery, ContentBoxesResponse,
LayoutChan, ReapLayoutDataMsg, TrustedNodeAddress, UntrustedNodeAddress};
use servo_util::geometry::Au;
use servo_util::str::{DOMString, null_str_as_empty};
use style::{parse_selector_list, matches_compound_selector, NamespaceMap};
use js::jsapi::{JSContext, JSObject, JSRuntime};
use js::jsfriendapi;
use libc;
use libc::uintptr_t;
use std::cell::{Cell, RefCell, Ref, RefMut};
use std::iter::{Map, Filter};
use std::mem;
use style;
use style::ComputedValues;
use sync::Arc;
use serialize::{Encoder, Encodable};
//
// The basic Node structure
//
/// An HTML node.
#[deriving(Encodable)]
pub struct Node {
/// The JavaScript reflector for this node.
pub eventtarget: EventTarget,
/// The type of node that this is.
pub type_id: NodeTypeId,
/// The parent of this node.
pub parent_node: Cell<Option<JS<Node>>>,
/// The first child of this node.
pub first_child: Cell<Option<JS<Node>>>,
/// The last child of this node.
pub last_child: Cell<Option<JS<Node>>>,
/// The next sibling of this node.
pub next_sibling: Cell<Option<JS<Node>>>,
/// The previous sibling of this node.
pub prev_sibling: Cell<Option<JS<Node>>>,
/// The document that this node belongs to.
owner_doc: Cell<Option<JS<Document>>>,
/// The live list of children return by .childNodes.
pub child_list: Cell<Option<JS<NodeList>>>,
/// A bitfield of flags for node items.
flags: Traceable<RefCell<NodeFlags>>,
/// Layout information. Only the layout task may touch this data.
///
/// FIXME(pcwalton): We need to send these back to the layout task to be destroyed when this
/// node is finalized.
pub layout_data: LayoutDataRef,
}
impl<S: Encoder<E>, E> Encodable<S, E> for LayoutDataRef {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}
impl NodeDerived for EventTarget {
fn is_node(&self) -> bool {
match self.type_id {
NodeTargetTypeId(_) => true,
_ => false
}
}
}
bitflags! {
#[doc = "Flags for node items."]
#[deriving(Encodable)]
flags NodeFlags: u8 {
#[doc = "Specifies whether this node is in a document."]
static IsInDoc = 0x01,
#[doc = "Specifies whether this node is hover state for this node"]
static InHoverState = 0x02
}
}
impl NodeFlags {
pub fn new(type_id: NodeTypeId) -> NodeFlags {
match type_id {
DocumentNodeTypeId => IsInDoc,
_ => NodeFlags::empty(),
}
}
}
#[unsafe_destructor]
impl Drop for Node {
fn drop(&mut self) {
unsafe {
self.reap_layout_data();
}
}
}
/// suppress observers flag
/// http://dom.spec.whatwg.org/#concept-node-insert
/// http://dom.spec.whatwg.org/#concept-node-remove
enum SuppressObserver {
Suppressed,
Unsuppressed
}
/// Layout data that is shared between the script and layout tasks.
pub struct SharedLayoutData {
/// The results of CSS styling for this node.
pub style: Option<Arc<ComputedValues>>,
}
/// Encapsulates the abstract layout data.
pub struct LayoutData {
chan: Option<LayoutChan>,
_shared_data: SharedLayoutData,
_data: *(),
}
pub struct LayoutDataRef {
pub data_cell: RefCell<Option<LayoutData>>,
}
impl LayoutDataRef {
pub fn new() -> LayoutDataRef {
LayoutDataRef {
data_cell: RefCell::new(None),
}
}
/// Returns true if there is layout data present.
#[inline]
pub fn is_present(&self) -> bool {
self.data_cell.borrow().is_some()
}
/// Take the chan out of the layout data if it is present.
pub fn take_chan(&self) -> Option<LayoutChan> {
let mut layout_data = self.data_cell.borrow_mut();
match *layout_data {
None => None,
Some(..) => Some(layout_data.get_mut_ref().chan.take_unwrap()),
}
}
/// Borrows the layout data immutably, *asserting that there are no mutators*. Bad things will
/// happen if you try to mutate the layout data while this is held. This is the only thread-
/// safe layout data accessor.
#[inline]
pub unsafe fn borrow_unchecked(&self) -> *Option<LayoutData> {
mem::transmute(&self.data_cell)
}
/// Borrows the layout data immutably. This function is *not* thread-safe.
#[inline]
pub fn borrow<'a>(&'a self) -> Ref<'a,Option<LayoutData>> {
self.data_cell.borrow()
}
/// Borrows the layout data mutably. This function is *not* thread-safe.
///
/// FIXME(pcwalton): We should really put this behind a `MutLayoutView` phantom type, to
/// prevent CSS selector matching from mutably accessing nodes it's not supposed to and racing
/// on it. This has already resulted in one bug!
#[inline]
pub fn borrow_mut<'a>(&'a self) -> RefMut<'a,Option<LayoutData>> {
self.data_cell.borrow_mut()
}
}
/// A trait that represents abstract layout data.
///
/// FIXME(pcwalton): Very very unsafe!!! We need to send these back to the layout task to be
/// destroyed when this node is finalized.
pub trait TLayoutData {}
/// The different types of nodes.
#[deriving(PartialEq,Encodable)]
pub enum NodeTypeId {
DoctypeNodeTypeId,
DocumentFragmentNodeTypeId,
CommentNodeTypeId,
DocumentNodeTypeId,
ElementNodeTypeId(ElementTypeId),
TextNodeTypeId,
ProcessingInstructionNodeTypeId,
}
trait PrivateNodeHelpers {
fn node_inserted(&self);
fn node_removed(&self, parent_in_doc: bool);
fn add_child(&self, new_child: &JSRef<Node>, before: Option<JSRef<Node>>);
fn remove_child(&self, child: &JSRef<Node>);
}
impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
// http://dom.spec.whatwg.org/#node-is-inserted
fn node_inserted(&self) {
assert!(self.parent_node().is_some());
let document = document_from_node(self).root();
let is_in_doc = self.is_in_doc();
for node in self.traverse_preorder() {
vtable_for(&node).bind_to_tree(is_in_doc);
}
let parent = self.parent_node().root();
parent.map(|parent| vtable_for(&*parent).child_inserted(self));
document.deref().content_changed();
}
// http://dom.spec.whatwg.org/#node-is-removed
fn node_removed(&self, parent_in_doc: bool) {
assert!(self.parent_node().is_none());
let document = document_from_node(self).root();
for node in self.traverse_preorder() {
vtable_for(&node).unbind_from_tree(parent_in_doc);
}
document.deref().content_changed();
}
//
// Pointer stitching
//
/// Adds a new child to the end of this node's list of children.
///
/// Fails unless `new_child` is disconnected from the tree.
fn add_child(&self, new_child: &JSRef<Node>, before: Option<JSRef<Node>>) {
let doc = self.owner_doc().root();
doc.deref().wait_until_safe_to_modify_dom();
assert!(new_child.parent_node().is_none());
assert!(new_child.prev_sibling().is_none());
assert!(new_child.next_sibling().is_none());
match before {
Some(ref before) => {
assert!(before.parent_node().root().root_ref() == Some(*self));
match before.prev_sibling().root() {
None => {
assert!(Some(*before) == self.first_child().root().root_ref());
self.first_child.assign(Some(*new_child));
},
Some(ref prev_sibling) => {
prev_sibling.next_sibling.assign(Some(*new_child));
new_child.prev_sibling.assign(Some(**prev_sibling));
},
}
before.prev_sibling.assign(Some(*new_child));
new_child.next_sibling.assign(Some(*before));
},
None => {
match self.last_child().root() {
None => self.first_child.assign(Some(*new_child)),
Some(ref last_child) => {
assert!(last_child.next_sibling().is_none());
last_child.next_sibling.assign(Some(*new_child));
new_child.prev_sibling.assign(Some(**last_child));
}
}
self.last_child.assign(Some(*new_child));
},
}
new_child.parent_node.assign(Some(*self));
}
/// Removes the given child from this node's list of children.
///
/// Fails unless `child` is a child of this node.
fn remove_child(&self, child: &JSRef<Node>) {
let doc = self.owner_doc().root();
doc.deref().wait_until_safe_to_modify_dom();
assert!(child.parent_node().root().root_ref() == Some(*self));
match child.prev_sibling.get().root() {
None => {
self.first_child.assign(child.next_sibling.get());
}
Some(ref prev_sibling) => {
prev_sibling.next_sibling.assign(child.next_sibling.get());
}
}
match child.next_sibling.get().root() {
None => {
self.last_child.assign(child.prev_sibling.get());
}
Some(ref next_sibling) => {
next_sibling.prev_sibling.assign(child.prev_sibling.get());
}
}
child.prev_sibling.set(None);
child.next_sibling.set(None);
child.parent_node.set(None);
}
}
pub trait NodeHelpers {
fn ancestors(&self) -> AncestorIterator;
fn children(&self) -> AbstractNodeChildrenIterator;
fn child_elements(&self) -> ChildElementIterator;
fn following_siblings(&self) -> AbstractNodeChildrenIterator;
fn is_in_doc(&self) -> bool;
fn is_inclusive_ancestor_of(&self, parent: &JSRef<Node>) -> bool;
fn is_parent_of(&self, child: &JSRef<Node>) -> bool;
fn type_id(&self) -> NodeTypeId;
fn parent_node(&self) -> Option<Temporary<Node>>;
fn first_child(&self) -> Option<Temporary<Node>>;
fn last_child(&self) -> Option<Temporary<Node>>;
fn prev_sibling(&self) -> Option<Temporary<Node>>;
fn next_sibling(&self) -> Option<Temporary<Node>>;
fn owner_doc(&self) -> Temporary<Document>;
fn set_owner_doc(&self, document: &JSRef<Document>);
fn wait_until_safe_to_modify_dom(&self);
fn is_element(&self) -> bool;
fn is_document(&self) -> bool;
fn is_doctype(&self) -> bool;
fn is_text(&self) -> bool;
fn is_anchor_element(&self) -> bool;
fn get_hover_state(&self) -> bool;
fn set_hover_state(&self, state: bool);
fn dump(&self);
fn dump_indent(&self, indent: uint);
fn debug_str(&self) -> String;
fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a>;
fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a>;
fn inclusively_following_siblings<'a>(&'a self) -> AbstractNodeChildrenIterator<'a>;
fn to_trusted_node_address(&self) -> TrustedNodeAddress;
fn get_bounding_content_box(&self) -> Rect<Au>;
fn get_content_boxes(&self) -> Vec<Rect<Au>>;
fn query_selector(&self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>>;
fn query_selector_all(&self, selectors: DOMString) -> Fallible<Temporary<NodeList>>;
fn remove_self(&self);
}
impl<'a> NodeHelpers for JSRef<'a, Node> {
/// Dumps the subtree rooted at this node, for debugging.
fn dump(&self) {
self.dump_indent(0);
}
/// Dumps the node tree, for debugging, with indentation.
fn dump_indent(&self, indent: uint) {
let mut s = String::new();
for _ in range(0, indent) {
s.push_str(" ");
}
s.push_str(self.debug_str().as_slice());
debug!("{:s}", s);
// FIXME: this should have a pure version?
for kid in self.children() {
kid.dump_indent(indent + 1u)
}
}
/// Returns a string that describes this node.
fn debug_str(&self) -> String {
format!("{:?}", self.type_id)
}
fn is_in_doc(&self) -> bool {
self.deref().flags.deref().borrow().contains(IsInDoc)
}
/// Returns the type ID of this node. Fails if this node is borrowed mutably.
fn type_id(&self) -> NodeTypeId {
self.deref().type_id
}
fn parent_node(&self) -> Option<Temporary<Node>> {
self.deref().parent_node.get().map(|node| Temporary::new(node))
}
fn first_child(&self) -> Option<Temporary<Node>> {
self.deref().first_child.get().map(|node| Temporary::new(node))
}
fn last_child(&self) -> Option<Temporary<Node>> {
self.deref().last_child.get().map(|node| Temporary::new(node))
}
/// Returns the previous sibling of this node. Fails if this node is borrowed mutably.
fn prev_sibling(&self) -> Option<Temporary<Node>> {
self.deref().prev_sibling.get().map(|node| Temporary::new(node))
}
/// Returns the next sibling of this node. Fails if this node is borrowed mutably.
fn next_sibling(&self) -> Option<Temporary<Node>> {
self.deref().next_sibling.get().map(|node| Temporary::new(node))
}
#[inline]
fn is_element(&self) -> bool {
match self.type_id {
ElementNodeTypeId(..) => true,
_ => false
}
}
#[inline]
fn is_document(&self) -> bool {
self.type_id == DocumentNodeTypeId
}
#[inline]
fn is_anchor_element(&self) -> bool {
self.type_id == ElementNodeTypeId(HTMLAnchorElementTypeId)
}
#[inline]
fn is_doctype(&self) -> bool {
self.type_id == DoctypeNodeTypeId
}
#[inline]
fn is_text(&self) -> bool {
self.type_id == TextNodeTypeId
}
fn get_hover_state(&self) -> bool {
self.flags.deref().borrow().contains(InHoverState)
}
fn set_hover_state(&self, state: bool) {
if state {
self.flags.deref().borrow_mut().insert(InHoverState);
} else {
self.flags.deref().borrow_mut().remove(InHoverState);
}
}
/// Iterates over this node and all its descendants, in preorder.
fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a> {
let mut nodes = vec!();
gather_abstract_nodes(self, &mut nodes, false);
TreeIterator::new(nodes)
}
/// Iterates over this node and all its descendants, in postorder.
fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a> {
let mut nodes = vec!();
gather_abstract_nodes(self, &mut nodes, true);
TreeIterator::new(nodes)
}
fn inclusively_following_siblings<'a>(&'a self) -> AbstractNodeChildrenIterator<'a> {
AbstractNodeChildrenIterator {
current_node: Some(self.clone()),
}
}
fn is_inclusive_ancestor_of(&self, parent: &JSRef<Node>) -> bool {
self == parent || parent.ancestors().any(|ancestor| &ancestor == self)
}
fn following_siblings(&self) -> AbstractNodeChildrenIterator {
AbstractNodeChildrenIterator {
current_node: self.next_sibling().root().map(|next| next.deref().clone()),
}
}
fn is_parent_of(&self, child: &JSRef<Node>) -> bool {
match child.parent_node() {
Some(ref parent) if *parent == Temporary::from_rooted(self) => true,
_ => false
}
}
fn to_trusted_node_address(&self) -> TrustedNodeAddress {
TrustedNodeAddress(self.deref() as *Node as *libc::c_void)
}
fn get_bounding_content_box(&self) -> Rect<Au> {
let window = window_from_node(self).root();
let page = window.deref().page();
let (chan, port) = channel();
let addr = self.to_trusted_node_address();
let ContentBoxResponse(rect) = page.query_layout(ContentBoxQuery(addr, chan), port);
rect
}
fn get_content_boxes(&self) -> Vec<Rect<Au>> {
let window = window_from_node(self).root();
let page = window.deref().page();
let (chan, port) = channel();
let addr = self.to_trusted_node_address();
let ContentBoxesResponse(rects) = page.query_layout(ContentBoxesQuery(addr, chan), port);
rects
}
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn query_selector(&self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> {
// Step 1.
let namespace = NamespaceMap::new();
match parse_selector_list(tokenize(selectors.as_slice()).map(|(token, _)| token).collect(), &namespace) {
// Step 2.
None => return Err(Syntax),
// Step 3.
Some(ref selectors) => {
let root = self.ancestors().last().unwrap_or(self.clone());
for selector in selectors.iter() {
assert!(selector.pseudo_element.is_none());
for node in root.traverse_preorder().filter(|node| node.is_element()) {
let mut _shareable: bool = false;
if matches_compound_selector(selector.compound_selectors.deref(), &node, &mut _shareable) {
let elem: &JSRef<Element> = ElementCast::to_ref(&node).unwrap();
return Ok(Some(Temporary::from_rooted(elem)));
}
}
}
}
}
Ok(None)
}
// http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn query_selector_all(&self, selectors: DOMString) -> Fallible<Temporary<NodeList>> {
// Step 1.
let mut nodes = vec!();
let root = self.ancestors().last().unwrap_or(self.clone());
let namespace = NamespaceMap::new();
match parse_selector_list(tokenize(selectors.as_slice()).map(|(token, _)| token).collect(), &namespace) {
// Step 2.
None => return Err(Syntax),
// Step 3.
Some(ref selectors) => {
for selector in selectors.iter() {
assert!(selector.pseudo_element.is_none());
for node in root.traverse_preorder().filter(|node| node.is_element()) {
let mut _shareable: bool = false;
if matches_compound_selector(selector.compound_selectors.deref(), &node, &mut _shareable) {
nodes.push(node.clone())
}
}
}
}
}
let window = window_from_node(self).root();
Ok(NodeList::new_simple_list(&window.root_ref(), nodes))
}
fn ancestors(&self) -> AncestorIterator {
AncestorIterator {
current: self.parent_node.get().map(|node| (*node.root()).clone()),
}
}
fn owner_doc(&self) -> Temporary<Document> {
Temporary::new(self.owner_doc.get().get_ref().clone())
}
fn set_owner_doc(&self, document: &JSRef<Document>) {
self.owner_doc.assign(Some(document.clone()));
}
fn children(&self) -> AbstractNodeChildrenIterator {
AbstractNodeChildrenIterator {
current_node: self.first_child.get().map(|node| (*node.root()).clone()),
}
}
fn child_elements(&self) -> ChildElementIterator {
self.children()
.filter(|node| {
node.is_element()
})
.map(|node| {
let elem: &JSRef<Element> = ElementCast::to_ref(&node).unwrap();
elem.clone()
})
}
fn wait_until_safe_to_modify_dom(&self) {
let document = self.owner_doc().root();
document.deref().wait_until_safe_to_modify_dom();
}
fn remove_self(&self) {
match self.parent_node().root() {
Some(ref parent) => parent.remove_child(self),
None => ()
}
}
}
/// If the given untrusted node address represents a valid DOM node in the given runtime,
/// returns it.
pub fn from_untrusted_node_address(runtime: *mut JSRuntime, candidate: UntrustedNodeAddress)
-> Temporary<Node> {
unsafe {
let candidate: uintptr_t = mem::transmute(candidate);
let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime,
candidate);
if object.is_null() {
fail!("Attempted to create a `JS<Node>` from an invalid pointer!")
}
let boxed_node: *Node = utils::unwrap(object);
Temporary::new(JS::from_raw(boxed_node))
}
}
pub trait LayoutNodeHelpers {
unsafe fn type_id_for_layout(&self) -> NodeTypeId;
unsafe fn parent_node_ref(&self) -> Option<JS<Node>>;
unsafe fn first_child_ref(&self) -> Option<JS<Node>>;
unsafe fn last_child_ref(&self) -> Option<JS<Node>>;
unsafe fn prev_sibling_ref(&self) -> Option<JS<Node>>;
unsafe fn next_sibling_ref(&self) -> Option<JS<Node>>;
unsafe fn owner_doc_for_layout(&self) -> JS<Document>;
unsafe fn is_element_for_layout(&self) -> bool;
}
impl LayoutNodeHelpers for JS<Node> {
#[inline]
unsafe fn type_id_for_layout(&self) -> NodeTypeId {
(*self.unsafe_get()).type_id
}
#[inline]
unsafe fn is_element_for_layout(&self) -> bool {
(*self.unsafe_get()).is_element()
}
#[inline]
unsafe fn parent_node_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).parent_node.get()
}
#[inline]
unsafe fn first_child_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).first_child.get()
}
#[inline]
unsafe fn last_child_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).last_child.get()
}
#[inline]
unsafe fn prev_sibling_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).prev_sibling.get()
}
#[inline]
unsafe fn next_sibling_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).next_sibling.get()
}
#[inline]
unsafe fn owner_doc_for_layout(&self) -> JS<Document> {
(*self.unsafe_get()).owner_doc.get().unwrap()
}
}
pub trait RawLayoutNodeHelpers {
unsafe fn get_hover_state_for_layout(&self) -> bool;
}
impl RawLayoutNodeHelpers for Node {
unsafe fn get_hover_state_for_layout(&self) -> bool {
self.flags.deref().borrow().contains(InHoverState)
}
}
//
// Iteration and traversal
//
pub type ChildElementIterator<'a, 'b> = Map<'a, JSRef<'b, Node>,
JSRef<'b, Element>,
Filter<'a, JSRef<'b, Node>, AbstractNodeChildrenIterator<'b>>>;
pub struct AbstractNodeChildrenIterator<'a> {
current_node: Option<JSRef<'a, Node>>,
}
impl<'a> Iterator<JSRef<'a, Node>> for AbstractNodeChildrenIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
let node = self.current_node.clone();
self.current_node = node.clone().and_then(|node| {
node.next_sibling().map(|node| (*node.root()).clone())
});
node
}
}
pub struct AncestorIterator<'a> {
current: Option<JSRef<'a, Node>>,
}
impl<'a> Iterator<JSRef<'a, Node>> for AncestorIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
if self.current.is_none() {
return None;
}
// FIXME: Do we need two clones here?
let x = self.current.get_ref().clone();
self.current = x.parent_node().map(|node| (*node.root()).clone());
Some(x)
}
}
// FIXME: Do this without precomputing a vector of refs.
// Easy for preorder; harder for postorder.
pub struct TreeIterator<'a> {
nodes: Vec<JSRef<'a, Node>>,
index: uint,
}
impl<'a> TreeIterator<'a> {
fn new(nodes: Vec<JSRef<'a, Node>>) -> TreeIterator<'a> {
TreeIterator {
nodes: nodes,
index: 0,
}
}
}
impl<'a> Iterator<JSRef<'a, Node>> for TreeIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
if self.index >= self.nodes.len() {
None
} else {
let v = self.nodes.get(self.index).clone();
self.index += 1;
Some(v)
}
}
}
pub struct NodeIterator {
pub start_node: JS<Node>,
pub current_node: Option<JS<Node>>,
pub depth: uint,
include_start: bool,
include_descendants_of_void: bool
}
impl NodeIterator {
pub fn new<'a>(start_node: &JSRef<'a, Node>,
include_start: bool,
include_descendants_of_void: bool) -> NodeIterator {
NodeIterator {
start_node: JS::from_rooted(start_node),
current_node: None,
depth: 0,
include_start: include_start,
include_descendants_of_void: include_descendants_of_void
}
}
fn next_child<'b>(&self, node: &JSRef<'b, Node>) -> Option<JSRef<Node>> {
if !self.include_descendants_of_void && node.is_element() {
let elem: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
if elem.deref().is_void() {
None
} else {
node.first_child().map(|child| (*child.root()).clone())
}
} else {
node.first_child().map(|child| (*child.root()).clone())
}
}
}
impl<'a> Iterator<JSRef<'a, Node>> for NodeIterator {
fn next(&mut self) -> Option<JSRef<Node>> {
self.current_node = match self.current_node.as_ref().map(|node| node.root()) {
None => {
if self.include_start {
Some(self.start_node)
} else {
self.next_child(&*self.start_node.root())
.map(|child| JS::from_rooted(&child))
}
},
Some(node) => {
match self.next_child(&*node) {
Some(child) => {
self.depth += 1;
Some(JS::from_rooted(&child))
},
None if JS::from_rooted(&*node) == self.start_node => None,
None => {
match node.deref().next_sibling().root() {
Some(sibling) => Some(JS::from_rooted(&*sibling)),
None => {
let mut candidate = node.deref().clone();
while candidate.next_sibling().is_none() {
candidate = (*candidate.parent_node()
.expect("Got to root without reaching start node")
.root()).clone();
self.depth -= 1;
if JS::from_rooted(&candidate) == self.start_node {
break;
}
}
if JS::from_rooted(&candidate) != self.start_node {
candidate.next_sibling().map(|node| JS::from_rooted(node.root().deref()))
} else {
None
}
}
}
}
}
}
};
self.current_node.map(|node| (*node.root()).clone())
}
}
fn gather_abstract_nodes<'a>(cur: &JSRef<'a, Node>, refs: &mut Vec<JSRef<'a, Node>>, postorder: bool) {
if !postorder {
refs.push(cur.clone());
}
for kid in cur.children() {
gather_abstract_nodes(&kid, refs, postorder)
}
if postorder {
refs.push(cur.clone());
}
}
/// Specifies whether children must be recursively cloned or not.
#[deriving(PartialEq)]
pub enum CloneChildrenFlag {
CloneChildren,
DoNotCloneChildren
}
fn as_uintptr<T>(t: &T) -> uintptr_t { t as *T as uintptr_t }
impl Node {
pub fn reflect_node<N: Reflectable+NodeBase>
(node: Box<N>,
document: &JSRef<Document>,
wrap_fn: extern "Rust" fn(*mut JSContext, &GlobalRef, Box<N>) -> Temporary<N>)
-> Temporary<N> {
let window = document.window.root();
reflect_dom_object(node, &Window(*window), wrap_fn)
}
pub fn new_inherited(type_id: NodeTypeId, doc: &JSRef<Document>) -> Node {
Node::new_(type_id, Some(doc.clone()))
}
pub fn new_without_doc(type_id: NodeTypeId) -> Node {
Node::new_(type_id, None)
}
fn new_(type_id: NodeTypeId, doc: Option<JSRef<Document>>) -> Node {
Node {
eventtarget: EventTarget::new_inherited(NodeTargetTypeId(type_id)),
type_id: type_id,
parent_node: Cell::new(None),
first_child: Cell::new(None),
last_child: Cell::new(None),
next_sibling: Cell::new(None),
prev_sibling: Cell::new(None),
owner_doc: Cell::new(doc.unrooted()),
child_list: Cell::new(None),
flags: Traceable::new(RefCell::new(NodeFlags::new(type_id))),
layout_data: LayoutDataRef::new(),
}
}
// http://dom.spec.whatwg.org/#concept-node-adopt
pub fn adopt(node: &JSRef<Node>, document: &JSRef<Document>) {
// Step 1.
match node.parent_node().root() {
Some(parent) => {
Node::remove(node, &*parent, Unsuppressed);
}
None => (),
}
// Step 2.
let node_doc = document_from_node(node).root();
if &*node_doc != document {
for descendant in node.traverse_preorder() {
descendant.set_owner_doc(document);
}
}
// Step 3.
// If node is an element, it is _affected by a base URL change_.
}
// http://dom.spec.whatwg.org/#concept-node-pre-insert
fn pre_insert(node: &JSRef<Node>, parent: &JSRef<Node>, child: Option<JSRef<Node>>)
-> Fallible<Temporary<Node>> {
// Step 1.
match parent.type_id() {
DocumentNodeTypeId |
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => (),
_ => return Err(HierarchyRequest)
}
// Step 2.
if node.is_inclusive_ancestor_of(parent) {
return Err(HierarchyRequest);
}
// Step 3.
match child {
Some(ref child) if !parent.is_parent_of(child) => return Err(NotFound),
_ => ()
}
// Step 4-5.
match node.type_id() {
TextNodeTypeId => {
match node.parent_node().root() {
Some(ref parent) if parent.is_document() => return Err(HierarchyRequest),
_ => ()
}
}
DoctypeNodeTypeId => {
match node.parent_node().root() {
Some(ref parent) if !parent.is_document() => return Err(HierarchyRequest),
_ => ()
}
}
DocumentFragmentNodeTypeId |
ElementNodeTypeId(_) |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => return Err(HierarchyRequest)
}
// Step 6.
match parent.type_id() {
DocumentNodeTypeId => {
match node.type_id() {
// Step 6.1
DocumentFragmentNodeTypeId => {
// Step 6.1.1(b)
if node.children().any(|c| c.is_text()) {
return Err(HierarchyRequest);
}
match node.child_elements().count() {
0 => (),
// Step 6.1.2
1 => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
match child {
Some(ref child) if child.inclusively_following_siblings()
.any(|child| child.is_doctype()) => {
return Err(HierarchyRequest);
}
_ => (),
}
},
// Step 6.1.1(a)
_ => return Err(HierarchyRequest),
}
},
// Step 6.2
ElementNodeTypeId(_) => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
match child {
Some(ref child) if child.inclusively_following_siblings()
.any(|child| child.is_doctype()) => {
return Err(HierarchyRequest);
}
_ => (),
}
},
// Step 6.3
DoctypeNodeTypeId => {
if parent.children().any(|c| c.is_doctype()) {
return Err(HierarchyRequest);
}
match child {
Some(ref child) => {
if parent.children()
.take_while(|c| c != child)
.any(|c| c.is_element()) {
return Err(HierarchyRequest);
}
},
None => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
},
}
},
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => unreachable!(),
}
},
_ => (),
}
// Step 7-8.
let referenceChild = match child {
Some(ref child) if child == node => node.next_sibling().map(|node| (*node.root()).clone()),
_ => child
};
// Step 9.
let document = document_from_node(parent).root();
Node::adopt(node, &*document);
// Step 10.
Node::insert(node, parent, referenceChild, Unsuppressed);
// Step 11.
return Ok(Temporary::from_rooted(node))
}
// http://dom.spec.whatwg.org/#concept-node-insert
fn insert(node: &JSRef<Node>,
parent: &JSRef<Node>,
child: Option<JSRef<Node>>,
suppress_observers: SuppressObserver) {
// XXX assert owner_doc
// Step 1-3: ranges.
// Step 4.
let mut nodes = match node.type_id() {
DocumentFragmentNodeTypeId => node.children().collect(),
_ => vec!(node.clone()),
};
// Step 5: DocumentFragment, mutation records.
// Step 6: DocumentFragment.
match node.type_id() {
DocumentFragmentNodeTypeId => {
for c in node.children() {
Node::remove(&c, node, Suppressed);
}
},
_ => (),
}
// Step 7: mutation records.
// Step 8.
for node in nodes.mut_iter() {
parent.add_child(node, child);
let is_in_doc = parent.is_in_doc();
for kid in node.traverse_preorder() {
if is_in_doc {
kid.flags.deref().borrow_mut().insert(IsInDoc);
} else {
kid.flags.deref().borrow_mut().remove(IsInDoc);
}
}
}
// Step 9.
match suppress_observers {
Unsuppressed => {
for node in nodes.iter() {
node.node_inserted();
}
}
Suppressed => ()
}
}
// http://dom.spec.whatwg.org/#concept-node-replace-all
fn replace_all(node: Option<JSRef<Node>>, parent: &JSRef<Node>) {
// Step 1.
match node {
Some(ref node) => {
let document = document_from_node(parent).root();
Node::adopt(node, &*document);
}
None => (),
}
// Step 2.
let removedNodes: Vec<JSRef<Node>> = parent.children().collect();
// Step 3.
let addedNodes = match node {
None => vec!(),
Some(ref node) => match node.type_id() {
DocumentFragmentNodeTypeId => node.children().collect(),
_ => vec!(node.clone()),
},
};
// Step 4.
for child in parent.children() {
Node::remove(&child, parent, Suppressed);
}
// Step 5.
match node {
Some(ref node) => Node::insert(node, parent, None, Suppressed),
None => (),
}
// Step 6: mutation records.
// Step 7.
let parent_in_doc = parent.is_in_doc();
for removedNode in removedNodes.iter() {
removedNode.node_removed(parent_in_doc);
}
for addedNode in addedNodes.iter() {
addedNode.node_inserted();
}
}
// http://dom.spec.whatwg.org/#concept-node-pre-remove
fn pre_remove(child: &JSRef<Node>, parent: &JSRef<Node>) -> Fallible<Temporary<Node>> {
// Step 1.
match child.parent_node() {
Some(ref node) if *node != Temporary::from_rooted(parent) => return Err(NotFound),
_ => ()
}
// Step 2.
Node::remove(child, parent, Unsuppressed);
// Step 3.
Ok(Temporary::from_rooted(child))
}
// http://dom.spec.whatwg.org/#concept-node-remove
fn remove(node: &JSRef<Node>, parent: &JSRef<Node>, suppress_observers: SuppressObserver) {
assert!(node.parent_node().map_or(false, |node_parent| node_parent == Temporary::from_rooted(parent)));
// Step 1-5: ranges.
// Step 6-7: mutation observers.
// Step 8.
parent.remove_child(node);
node.deref().flags.deref().borrow_mut().remove(IsInDoc);
// Step 9.
match suppress_observers {
Suppressed => (),
Unsuppressed => node.node_removed(parent.is_in_doc()),
}
}
// http://dom.spec.whatwg.org/#concept-node-clone
pub fn clone(node: &JSRef<Node>, maybe_doc: Option<&JSRef<Document>>,
clone_children: CloneChildrenFlag) -> Temporary<Node> {
// Step 1.
let document = match maybe_doc {
Some(doc) => JS::from_rooted(doc).root(),
None => node.owner_doc().root()
};
// Step 2.
// XXXabinader: clone() for each node as trait?
let copy: Root<Node> = match node.type_id() {
DoctypeNodeTypeId => {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap();
let doctype = doctype.deref();
let doctype = DocumentType::new(doctype.name.clone(),
Some(doctype.public_id.clone()),
Some(doctype.system_id.clone()), &*document);
NodeCast::from_temporary(doctype)
},
DocumentFragmentNodeTypeId => {
let doc_fragment = DocumentFragment::new(&*document);
NodeCast::from_temporary(doc_fragment)
},
CommentNodeTypeId => {
let comment: &JSRef<Comment> = CommentCast::to_ref(node).unwrap();
let comment = comment.deref();
let comment = Comment::new(comment.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(comment)
},
DocumentNodeTypeId => {
let document: &JSRef<Document> = DocumentCast::to_ref(node).unwrap();
let is_html_doc = match document.is_html_document {
true => HTMLDocument,
false => NonHTMLDocument
};
let window = document.window.root();
let document = Document::new(&*window, Some(document.url().clone()),
is_html_doc, None);
NodeCast::from_temporary(document)
},
ElementNodeTypeId(..) => {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let element = element.deref();
let element = build_element_from_tag(element.local_name.as_slice().to_string(),
element.namespace.clone(), &*document);
NodeCast::from_temporary(element)
},
TextNodeTypeId => {
let text: &JSRef<Text> = TextCast::to_ref(node).unwrap();
let text = text.deref();
let text = Text::new(text.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(text)
},
ProcessingInstructionNodeTypeId => {
let pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap();
let pi = pi.deref();
let pi = ProcessingInstruction::new(pi.target.clone(),
pi.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(pi)
},
}.root();
// Step 3.
let document = if copy.is_document() {
let doc: &JSRef<Document> = DocumentCast::to_ref(&*copy).unwrap();
JS::from_rooted(doc).root()
} else {
JS::from_rooted(&*document).root()
};
assert!(&*copy.owner_doc().root() == &*document);
// Step 4 (some data already copied in step 2).
match node.type_id() {
DocumentNodeTypeId => {
let node_doc: &JSRef<Document> = DocumentCast::to_ref(node).unwrap();
let copy_doc: &JSRef<Document> = DocumentCast::to_ref(&*copy).unwrap();
copy_doc.set_encoding_name(node_doc.encoding_name.deref().borrow().clone());
copy_doc.set_quirks_mode(node_doc.quirks_mode());
},
ElementNodeTypeId(..) => {
let node_elem: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let copy_elem: &JSRef<Element> = ElementCast::to_ref(&*copy).unwrap();
// FIXME: https://github.com/mozilla/servo/issues/1737
let window = document.deref().window.root();
for attr in node_elem.deref().attrs.borrow().iter().map(|attr| attr.root()) {
copy_elem.deref().attrs.borrow_mut().push_unrooted(
&Attr::new(&*window,
attr.deref().local_name.clone(), attr.deref().value().clone(),
attr.deref().name.clone(), attr.deref().namespace.clone(),
attr.deref().prefix.clone(), copy_elem));
}
},
_ => ()
}
// Step 5: cloning steps.
// Step 6.
if clone_children == CloneChildren {
for ref child in node.children() {
let child_copy = Node::clone(&*child, Some(&*document), clone_children).root();
let _inserted_node = Node::pre_insert(&*child_copy, &*copy, None);
}
}
// Step 7.
Temporary::from_rooted(&*copy)
}
/// Sends layout data, if any, back to the script task to be destroyed.
unsafe fn reap_layout_data(&mut self) {
if self.layout_data.is_present() {
let layout_data = mem::replace(&mut self.layout_data, LayoutDataRef::new());
let layout_chan = layout_data.take_chan();
match layout_chan {
None => {}
Some(chan) => {
let LayoutChan(chan) = chan;
chan.send(ReapLayoutDataMsg(layout_data))
},
}
}
}
}
pub trait NodeMethods {
fn NodeType(&self) -> u16;
fn NodeName(&self) -> DOMString;
fn GetBaseURI(&self) -> Option<DOMString>;
fn GetOwnerDocument(&self) -> Option<Temporary<Document>>;
fn GetParentNode(&self) -> Option<Temporary<Node>>;
fn GetParentElement(&self) -> Option<Temporary<Element>>;
fn HasChildNodes(&self) -> bool;
fn ChildNodes(&self) -> Temporary<NodeList>;
fn GetFirstChild(&self) -> Option<Temporary<Node>>;
fn GetLastChild(&self) -> Option<Temporary<Node>>;
fn GetPreviousSibling(&self) -> Option<Temporary<Node>>;
fn GetNextSibling(&self) -> Option<Temporary<Node>>;
fn GetNodeValue(&self) -> Option<DOMString>;
fn SetNodeValue(&self, val: Option<DOMString>) -> ErrorResult;
fn GetTextContent(&self) -> Option<DOMString>;
fn SetTextContent(&self, value: Option<DOMString>) -> ErrorResult;
fn InsertBefore(&self, node: &JSRef<Node>, child: Option<JSRef<Node>>) -> Fallible<Temporary<Node>>;
fn AppendChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn ReplaceChild(&self, node: &JSRef<Node>, child: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn RemoveChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn Normalize(&self);
fn CloneNode(&self, deep: bool) -> Temporary<Node>;
fn IsEqualNode(&self, maybe_node: Option<JSRef<Node>>) -> bool;
fn CompareDocumentPosition(&self, other: &JSRef<Node>) -> u16;
fn Contains(&self, maybe_other: Option<JSRef<Node>>) -> bool;
fn LookupPrefix(&self, _prefix: Option<DOMString>) -> Option<DOMString>;
fn LookupNamespaceURI(&self, _namespace: Option<DOMString>) -> Option<DOMString>;
fn IsDefaultNamespace(&self, _namespace: Option<DOMString>) -> bool;
}
impl<'a> NodeMethods for JSRef<'a, Node> {
// http://dom.spec.whatwg.org/#dom-node-nodetype
fn NodeType(&self) -> u16 {
match self.type_id {
ElementNodeTypeId(_) => NodeConstants::ELEMENT_NODE,
TextNodeTypeId => NodeConstants::TEXT_NODE,
ProcessingInstructionNodeTypeId => NodeConstants::PROCESSING_INSTRUCTION_NODE,
CommentNodeTypeId => NodeConstants::COMMENT_NODE,
DocumentNodeTypeId => NodeConstants::DOCUMENT_NODE,
DoctypeNodeTypeId => NodeConstants::DOCUMENT_TYPE_NODE,
DocumentFragmentNodeTypeId => NodeConstants::DOCUMENT_FRAGMENT_NODE,
}
}
// http://dom.spec.whatwg.org/#dom-node-nodename
fn NodeName(&self) -> DOMString {
match self.type_id {
ElementNodeTypeId(..) => {
let elem: &JSRef<Element> = ElementCast::to_ref(self).unwrap();
elem.TagName()
}
TextNodeTypeId => "#text".to_string(),
ProcessingInstructionNodeTypeId => {
let processing_instruction: &JSRef<ProcessingInstruction> =
ProcessingInstructionCast::to_ref(self).unwrap();
processing_instruction.Target()
}
CommentNodeTypeId => "#comment".to_string(),
DoctypeNodeTypeId => {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap();
doctype.deref().name.clone()
},
DocumentFragmentNodeTypeId => "#document-fragment".to_string(),
DocumentNodeTypeId => "#document".to_string()
}
}
// http://dom.spec.whatwg.org/#dom-node-baseuri
fn GetBaseURI(&self) -> Option<DOMString> {
// FIXME (#1824) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-ownerdocument
fn GetOwnerDocument(&self) -> Option<Temporary<Document>> {
match self.type_id {
ElementNodeTypeId(..) |
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
DoctypeNodeTypeId |
DocumentFragmentNodeTypeId => Some(self.owner_doc()),
DocumentNodeTypeId => None
}
}
// http://dom.spec.whatwg.org/#dom-node-parentnode
fn GetParentNode(&self) -> Option<Temporary<Node>> {
self.parent_node.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-parentelement
fn GetParentElement(&self) -> Option<Temporary<Element>> {
self.parent_node.get()
.and_then(|parent| {
let parent = parent.root();
ElementCast::to_ref(&*parent).map(|elem| {
Temporary::from_rooted(elem)
})
})
}
// http://dom.spec.whatwg.org/#dom-node-haschildnodes
fn HasChildNodes(&self) -> bool {
self.first_child.get().is_some()
}
// http://dom.spec.whatwg.org/#dom-node-childnodes
fn ChildNodes(&self) -> Temporary<NodeList> {
match self.child_list.get() {
None => (),
Some(ref list) => return Temporary::new(list.clone()),
}
let doc = self.owner_doc().root();
let window = doc.deref().window.root();
let child_list = NodeList::new_child_list(&*window, self);
self.child_list.assign(Some(child_list));
Temporary::new(self.child_list.get().get_ref().clone())
}
// http://dom.spec.whatwg.org/#dom-node-firstchild
fn GetFirstChild(&self) -> Option<Temporary<Node>> {
self.first_child.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-lastchild
fn GetLastChild(&self) -> Option<Temporary<Node>> {
self.last_child.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-previoussibling
fn GetPreviousSibling(&self) -> Option<Temporary<Node>> {
self.prev_sibling.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-nextsibling
fn GetNextSibling(&self) -> Option<Temporary<Node>> {
self.next_sibling.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-nodevalue
fn GetNodeValue(&self) -> Option<DOMString> {
match self.type_id {
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
let chardata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
Some(chardata.Data())
}
_ => {
None
}
}
}
// http://dom.spec.whatwg.org/#dom-node-nodevalue
fn SetNodeValue(&self, val: Option<DOMString>) -> ErrorResult {
match self.type_id {
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
self.SetTextContent(val)
}
_ => Ok(())
}
}
// http://dom.spec.whatwg.org/#dom-node-textcontent
fn GetTextContent(&self) -> Option<DOMString> {
match self.type_id {
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => {
let mut content = String::new();
for node in self.traverse_preorder() {
if node.is_text() {
let text: &JSRef<Text> = TextCast::to_ref(&node).unwrap();
content.push_str(text.deref().characterdata.data.deref().borrow().as_slice());
}
}
Some(content)
}
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
Some(characterdata.Data())
}
DoctypeNodeTypeId |
DocumentNodeTypeId => {
None
}
}
}
// http://dom.spec.whatwg.org/#dom-node-textcontent
fn SetTextContent(&self, value: Option<DOMString>) -> ErrorResult {
let value = null_str_as_empty(&value);
match self.type_id {
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => {
// Step 1-2.
let node = if value.len() == 0 {
None
} else {
let document = self.owner_doc().root();
Some(NodeCast::from_temporary(document.deref().CreateTextNode(value)))
}.root();
// Step 3.
Node::replace_all(node.root_ref(), self);
}
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
self.wait_until_safe_to_modify_dom();
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
*characterdata.data.deref().borrow_mut() = value;
// Notify the document that the content of this node is different
let document = self.owner_doc().root();
document.deref().content_changed();
}
DoctypeNodeTypeId |
DocumentNodeTypeId => {}
}
Ok(())
}
// http://dom.spec.whatwg.org/#dom-node-insertbefore
fn InsertBefore(&self, node: &JSRef<Node>, child: Option<JSRef<Node>>) -> Fallible<Temporary<Node>> {
Node::pre_insert(node, self, child)
}
// http://dom.spec.whatwg.org/#dom-node-appendchild
fn AppendChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>> {
Node::pre_insert(node, self, None)
}
// http://dom.spec.whatwg.org/#concept-node-replace
fn ReplaceChild(&self, node: &JSRef<Node>, child: &JSRef<Node>) -> Fallible<Temporary<Node>> {
// Step 1.
match self.type_id {
DocumentNodeTypeId |
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => (),
_ => return Err(HierarchyRequest)
}
// Step 2.
if node.is_inclusive_ancestor_of(self) {
return Err(HierarchyRequest);
}
// Step 3.
if !self.is_parent_of(child) {
return Err(NotFound);
}
// Step 4-5.
match node.type_id() {
TextNodeTypeId if self.is_document() => return Err(HierarchyRequest),
DoctypeNodeTypeId if !self.is_document() => return Err(HierarchyRequest),
DocumentFragmentNodeTypeId |
DoctypeNodeTypeId |
ElementNodeTypeId(..) |
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => return Err(HierarchyRequest)
}
// Step 6.
match self.type_id {
DocumentNodeTypeId => {
match node.type_id() {
// Step 6.1
DocumentFragmentNodeTypeId => {
// Step 6.1.1(b)
if node.children().any(|c| c.is_text()) {
return Err(HierarchyRequest);
}
match node.child_elements().count() {
0 => (),
// Step 6.1.2
1 => {
if self.child_elements().any(|c| NodeCast::from_ref(&c) != child) {
return Err(HierarchyRequest);
}
if child.following_siblings()
.any(|child| child.is_doctype()) {
return Err(HierarchyRequest);
}
},
// Step 6.1.1(a)
_ => return Err(HierarchyRequest)
}
},
// Step 6.2
ElementNodeTypeId(..) => {
if self.child_elements().any(|c| NodeCast::from_ref(&c) != child) {
return Err(HierarchyRequest);
}
if child.following_siblings()
.any(|child| child.is_doctype()) {
return Err(HierarchyRequest);
}
},
// Step 6.3
DoctypeNodeTypeId => {
if self.children().any(|c| c.is_doctype() && &c != child) {
return Err(HierarchyRequest);
}
if self.children()
.take_while(|c| c != child)
.any(|c| c.is_element()) {
return Err(HierarchyRequest);
}
},
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => unreachable!()
}
},
_ => ()
}
// Ok if not caught by previous error checks.
if *node == *child {
return Ok(Temporary::from_rooted(child));
}
// Step 7-8.
let next_sibling = child.next_sibling().map(|node| (*node.root()).clone());
let reference_child = match next_sibling {
Some(ref sibling) if sibling == node => node.next_sibling().map(|node| (*node.root()).clone()),
_ => next_sibling
};
// Step 9.
let document = document_from_node(self).root();
Node::adopt(node, &*document);
{
// Step 10.
Node::remove(child, self, Suppressed);
// Step 11.
Node::insert(node, self, reference_child, Suppressed);
}
// Step 12-14.
// Step 13: mutation records.
child.node_removed(self.is_in_doc());
if node.type_id() == DocumentFragmentNodeTypeId {
for child_node in node.children() {
child_node.node_inserted();
}
} else {
node.node_inserted();
}
// Step 15.
Ok(Temporary::from_rooted(child))
}
// http://dom.spec.whatwg.org/#dom-node-removechild
fn RemoveChild(&self, node: &JSRef<Node>)
-> Fallible<Temporary<Node>> {
Node::pre_remove(node, self)
}
// http://dom.spec.whatwg.org/#dom-node-normalize
fn Normalize(&self) {
let mut prev_text = None;
for child in self.children() {
if child.is_text() {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(&child).unwrap();
if characterdata.Length() == 0 {
self.remove_child(&child);
} else {
match prev_text {
Some(ref mut text_node) => {
let prev_characterdata: &mut JSRef<CharacterData> = CharacterDataCast::to_mut_ref(text_node).unwrap();
let _ = prev_characterdata.AppendData(characterdata.Data());
self.remove_child(&child);
},
None => prev_text = Some(child)
}
}
} else {
child.Normalize();
prev_text = None;
}
}
}
// http://dom.spec.whatwg.org/#dom-node-clonenode
fn CloneNode(&self, deep: bool) -> Temporary<Node> {
match deep {
true => Node::clone(self, None, CloneChildren),
false => Node::clone(self, None, DoNotCloneChildren)
}
}
// http://dom.spec.whatwg.org/#dom-node-isequalnode
fn IsEqualNode(&self, maybe_node: Option<JSRef<Node>>) -> bool {
fn is_equal_doctype(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap();
let other_doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(other).unwrap();
(doctype.deref().name == other_doctype.deref().name) &&
(doctype.deref().public_id == other_doctype.deref().public_id) &&
(doctype.deref().system_id == other_doctype.deref().system_id)
}
fn is_equal_element(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let other_element: &JSRef<Element> = ElementCast::to_ref(other).unwrap();
// FIXME: namespace prefix
let element = element.deref();
let other_element = other_element.deref();
(element.namespace == other_element.namespace) &&
(element.local_name == other_element.local_name) &&
(element.attrs.borrow().len() == other_element.attrs.borrow().len())
}
fn is_equal_processinginstruction(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap();
let other_pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(other).unwrap();
(pi.deref().target == other_pi.deref().target) &&
(*pi.deref().characterdata.data.deref().borrow() == *other_pi.deref().characterdata.data.deref().borrow())
}
fn is_equal_characterdata(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(node).unwrap();
let other_characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(other).unwrap();
*characterdata.deref().data.deref().borrow() == *other_characterdata.deref().data.deref().borrow()
}
fn is_equal_element_attrs(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let other_element: &JSRef<Element> = ElementCast::to_ref(other).unwrap();
let element = element.deref();
let other_element = other_element.deref();
assert!(element.attrs.borrow().len() == other_element.attrs.borrow().len());
element.attrs.borrow().iter().map(|attr| attr.root()).all(|attr| {
other_element.attrs.borrow().iter().map(|attr| attr.root()).any(|other_attr| {
(attr.namespace == other_attr.namespace) &&
(attr.local_name == other_attr.local_name) &&
(attr.deref().value().as_slice() == other_attr.deref().value().as_slice())
})
})
}
fn is_equal_node(this: &JSRef<Node>, node: &JSRef<Node>) -> bool {
// Step 2.
if this.type_id() != node.type_id() {
return false;
}
match node.type_id() {
// Step 3.
DoctypeNodeTypeId if !is_equal_doctype(this, node) => return false,
ElementNodeTypeId(..) if !is_equal_element(this, node) => return false,
ProcessingInstructionNodeTypeId if !is_equal_processinginstruction(this, node) => return false,
TextNodeTypeId |
CommentNodeTypeId if !is_equal_characterdata(this, node) => return false,
// Step 4.
ElementNodeTypeId(..) if !is_equal_element_attrs(this, node) => return false,
_ => ()
}
// Step 5.
if this.children().count() != node.children().count() {
return false;
}
// Step 6.
this.children().zip(node.children()).all(|(ref child, ref other_child)| {
is_equal_node(child, other_child)
})
}
match maybe_node {
// Step 1.
None => false,
// Step 2-6.
Some(ref node) => is_equal_node(self, node)
}
}
// http://dom.spec.whatwg.org/#dom-node-comparedocumentposition
fn CompareDocumentPosition(&self, other: &JSRef<Node>) -> u16 {
if self == other {
// step 2.
0
} else {
let mut lastself = self.clone();
let mut lastother = other.clone();
for ancestor in self.ancestors() {
if &ancestor == other {
// step 4.
return NodeConstants::DOCUMENT_POSITION_CONTAINS +
NodeConstants::DOCUMENT_POSITION_PRECEDING;
}
lastself = ancestor.clone();
}
for ancestor in other.ancestors() {
if &ancestor == self {
// step 5.
return NodeConstants::DOCUMENT_POSITION_CONTAINED_BY +
NodeConstants::DOCUMENT_POSITION_FOLLOWING;
}
lastother = ancestor.clone();
}
if lastself != lastother {
let abstract_uint: uintptr_t = as_uintptr(&*self);
let other_uint: uintptr_t = as_uintptr(&*other);
let random = if abstract_uint < other_uint {
NodeConstants::DOCUMENT_POSITION_FOLLOWING
} else {
NodeConstants::DOCUMENT_POSITION_PRECEDING
};
// step 3.
return random +
NodeConstants::DOCUMENT_POSITION_DISCONNECTED +
NodeConstants::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
}
for child in lastself.traverse_preorder() {
if &child == other {
// step 6.
return NodeConstants::DOCUMENT_POSITION_PRECEDING;
}
if &child == self {
// step 7.
return NodeConstants::DOCUMENT_POSITION_FOLLOWING;
}
}
unreachable!()
}
}
// http://dom.spec.whatwg.org/#dom-node-contains
fn Contains(&self, maybe_other: Option<JSRef<Node>>) -> bool {
match maybe_other {
None => false,
Some(ref other) => self.is_inclusive_ancestor_of(other)
}
}
// http://dom.spec.whatwg.org/#dom-node-lookupprefix
fn LookupPrefix(&self, _prefix: Option<DOMString>) -> Option<DOMString> {
// FIXME (#1826) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
fn LookupNamespaceURI(&self, _namespace: Option<DOMString>) -> Option<DOMString> {
// FIXME (#1826) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
fn IsDefaultNamespace(&self, _namespace: Option<DOMString>) -> bool {
// FIXME (#1826) implement.
false
}
}
impl Reflectable for Node {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
pub fn document_from_node<T: NodeBase>(derived: &JSRef<T>) -> Temporary<Document> {
let node: &JSRef<Node> = NodeCast::from_ref(derived);
node.owner_doc()
}
pub fn window_from_node<T: NodeBase>(derived: &JSRef<T>) -> Temporary<Window> {
let document = document_from_node(derived).root();
Temporary::new(document.deref().window.clone())
}
impl<'a> VirtualMethods for JSRef<'a, Node> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> {
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(self);
Some(eventtarget as &VirtualMethods+)
}
}
impl<'a> style::TNode<JSRef<'a, Element>> for JSRef<'a, Node> {
fn parent_node(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).parent_node().map(|node| *node.root())
}
fn prev_sibling(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).prev_sibling().map(|node| *node.root())
}
fn next_sibling(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).next_sibling().map(|node| *node.root())
}
fn is_document(&self) -> bool {
(self as &NodeHelpers).is_document()
}
fn is_element(&self) -> bool {
(self as &NodeHelpers).is_element()
}
fn as_element(&self) -> JSRef<'a, Element> {
let elem: Option<&JSRef<'a, Element>> = ElementCast::to_ref(self);
assert!(elem.is_some());
*elem.unwrap()
}
fn match_attr(&self, attr: &style::AttrSelector, test: |&str| -> bool) -> bool {
let name = {
let elem: Option<&JSRef<'a, Element>> = ElementCast::to_ref(self);
assert!(elem.is_some());
let elem: &ElementHelpers = elem.unwrap() as &ElementHelpers;
if elem.html_element_in_html_document() {
attr.lower_name.as_slice()
} else {
attr.name.as_slice()
}
};
match attr.namespace {
style::SpecificNamespace(ref ns) => {
self.as_element().get_attribute(ns.clone(), name).root()
.map_or(false, |attr| test(attr.deref().Value().as_slice()))
},
// FIXME: https://github.com/mozilla/servo/issues/1558
style::AnyNamespace => false,
}
}
}
Update comments about Node::layout_data
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The core DOM types. Defines the basic DOM hierarchy as well as all the HTML elements.
use cssparser::tokenize;
use dom::attr::{Attr, AttrMethods};
use dom::bindings::codegen::InheritTypes::{CommentCast, DocumentCast, DocumentTypeCast};
use dom::bindings::codegen::InheritTypes::{ElementCast, TextCast, NodeCast, ElementDerived};
use dom::bindings::codegen::InheritTypes::{CharacterDataCast, NodeBase, NodeDerived};
use dom::bindings::codegen::InheritTypes::{ProcessingInstructionCast, EventTargetCast};
use dom::bindings::codegen::Bindings::NodeBinding::NodeConstants;
use dom::bindings::error::{ErrorResult, Fallible, NotFound, HierarchyRequest, Syntax};
use dom::bindings::global::{GlobalRef, Window};
use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, Root, OptionalUnrootable};
use dom::bindings::js::{OptionalSettable, TemporaryPushable, OptionalRootedRootable};
use dom::bindings::js::{ResultRootable, OptionalRootable};
use dom::bindings::trace::Traceable;
use dom::bindings::utils;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::characterdata::{CharacterData, CharacterDataMethods};
use dom::comment::Comment;
use dom::document::{Document, DocumentMethods, DocumentHelpers, HTMLDocument, NonHTMLDocument};
use dom::documentfragment::DocumentFragment;
use dom::documenttype::DocumentType;
use dom::element::{AttributeHandlers, Element, ElementMethods, ElementTypeId};
use dom::element::{HTMLAnchorElementTypeId, ElementHelpers};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::nodelist::{NodeList};
use dom::processinginstruction::{ProcessingInstruction, ProcessingInstructionMethods};
use dom::text::Text;
use dom::virtualmethods::{VirtualMethods, vtable_for};
use dom::window::Window;
use geom::rect::Rect;
use html::hubbub_html_parser::build_element_from_tag;
use layout_interface::{ContentBoxQuery, ContentBoxResponse, ContentBoxesQuery, ContentBoxesResponse,
LayoutChan, ReapLayoutDataMsg, TrustedNodeAddress, UntrustedNodeAddress};
use servo_util::geometry::Au;
use servo_util::str::{DOMString, null_str_as_empty};
use style::{parse_selector_list, matches_compound_selector, NamespaceMap};
use js::jsapi::{JSContext, JSObject, JSRuntime};
use js::jsfriendapi;
use libc;
use libc::uintptr_t;
use std::cell::{Cell, RefCell, Ref, RefMut};
use std::iter::{Map, Filter};
use std::mem;
use style;
use style::ComputedValues;
use sync::Arc;
use serialize::{Encoder, Encodable};
//
// The basic Node structure
//
/// An HTML node.
#[deriving(Encodable)]
pub struct Node {
/// The JavaScript reflector for this node.
pub eventtarget: EventTarget,
/// The type of node that this is.
pub type_id: NodeTypeId,
/// The parent of this node.
pub parent_node: Cell<Option<JS<Node>>>,
/// The first child of this node.
pub first_child: Cell<Option<JS<Node>>>,
/// The last child of this node.
pub last_child: Cell<Option<JS<Node>>>,
/// The next sibling of this node.
pub next_sibling: Cell<Option<JS<Node>>>,
/// The previous sibling of this node.
pub prev_sibling: Cell<Option<JS<Node>>>,
/// The document that this node belongs to.
owner_doc: Cell<Option<JS<Document>>>,
/// The live list of children return by .childNodes.
pub child_list: Cell<Option<JS<NodeList>>>,
/// A bitfield of flags for node items.
flags: Traceable<RefCell<NodeFlags>>,
/// Layout information. Only the layout task may touch this data.
///
/// Must be sent back to the layout task to be destroyed when this
/// node is finalized.
pub layout_data: LayoutDataRef,
}
impl<S: Encoder<E>, E> Encodable<S, E> for LayoutDataRef {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}
impl NodeDerived for EventTarget {
fn is_node(&self) -> bool {
match self.type_id {
NodeTargetTypeId(_) => true,
_ => false
}
}
}
bitflags! {
#[doc = "Flags for node items."]
#[deriving(Encodable)]
flags NodeFlags: u8 {
#[doc = "Specifies whether this node is in a document."]
static IsInDoc = 0x01,
#[doc = "Specifies whether this node is hover state for this node"]
static InHoverState = 0x02
}
}
impl NodeFlags {
pub fn new(type_id: NodeTypeId) -> NodeFlags {
match type_id {
DocumentNodeTypeId => IsInDoc,
_ => NodeFlags::empty(),
}
}
}
#[unsafe_destructor]
impl Drop for Node {
fn drop(&mut self) {
unsafe {
self.reap_layout_data();
}
}
}
/// suppress observers flag
/// http://dom.spec.whatwg.org/#concept-node-insert
/// http://dom.spec.whatwg.org/#concept-node-remove
enum SuppressObserver {
Suppressed,
Unsuppressed
}
/// Layout data that is shared between the script and layout tasks.
pub struct SharedLayoutData {
/// The results of CSS styling for this node.
pub style: Option<Arc<ComputedValues>>,
}
/// Encapsulates the abstract layout data.
pub struct LayoutData {
chan: Option<LayoutChan>,
_shared_data: SharedLayoutData,
_data: *(),
}
pub struct LayoutDataRef {
pub data_cell: RefCell<Option<LayoutData>>,
}
impl LayoutDataRef {
pub fn new() -> LayoutDataRef {
LayoutDataRef {
data_cell: RefCell::new(None),
}
}
/// Returns true if there is layout data present.
#[inline]
pub fn is_present(&self) -> bool {
self.data_cell.borrow().is_some()
}
/// Take the chan out of the layout data if it is present.
pub fn take_chan(&self) -> Option<LayoutChan> {
let mut layout_data = self.data_cell.borrow_mut();
match *layout_data {
None => None,
Some(..) => Some(layout_data.get_mut_ref().chan.take_unwrap()),
}
}
/// Borrows the layout data immutably, *asserting that there are no mutators*. Bad things will
/// happen if you try to mutate the layout data while this is held. This is the only thread-
/// safe layout data accessor.
#[inline]
pub unsafe fn borrow_unchecked(&self) -> *Option<LayoutData> {
mem::transmute(&self.data_cell)
}
/// Borrows the layout data immutably. This function is *not* thread-safe.
#[inline]
pub fn borrow<'a>(&'a self) -> Ref<'a,Option<LayoutData>> {
self.data_cell.borrow()
}
/// Borrows the layout data mutably. This function is *not* thread-safe.
///
/// FIXME(pcwalton): We should really put this behind a `MutLayoutView` phantom type, to
/// prevent CSS selector matching from mutably accessing nodes it's not supposed to and racing
/// on it. This has already resulted in one bug!
#[inline]
pub fn borrow_mut<'a>(&'a self) -> RefMut<'a,Option<LayoutData>> {
self.data_cell.borrow_mut()
}
}
/// A trait that represents abstract layout data.
///
/// FIXME(pcwalton): Very very unsafe!!! We need to send these back to the layout task to be
/// destroyed when this node is finalized.
pub trait TLayoutData {}
/// The different types of nodes.
#[deriving(PartialEq,Encodable)]
pub enum NodeTypeId {
DoctypeNodeTypeId,
DocumentFragmentNodeTypeId,
CommentNodeTypeId,
DocumentNodeTypeId,
ElementNodeTypeId(ElementTypeId),
TextNodeTypeId,
ProcessingInstructionNodeTypeId,
}
trait PrivateNodeHelpers {
fn node_inserted(&self);
fn node_removed(&self, parent_in_doc: bool);
fn add_child(&self, new_child: &JSRef<Node>, before: Option<JSRef<Node>>);
fn remove_child(&self, child: &JSRef<Node>);
}
impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
// http://dom.spec.whatwg.org/#node-is-inserted
fn node_inserted(&self) {
assert!(self.parent_node().is_some());
let document = document_from_node(self).root();
let is_in_doc = self.is_in_doc();
for node in self.traverse_preorder() {
vtable_for(&node).bind_to_tree(is_in_doc);
}
let parent = self.parent_node().root();
parent.map(|parent| vtable_for(&*parent).child_inserted(self));
document.deref().content_changed();
}
// http://dom.spec.whatwg.org/#node-is-removed
fn node_removed(&self, parent_in_doc: bool) {
assert!(self.parent_node().is_none());
let document = document_from_node(self).root();
for node in self.traverse_preorder() {
vtable_for(&node).unbind_from_tree(parent_in_doc);
}
document.deref().content_changed();
}
//
// Pointer stitching
//
/// Adds a new child to the end of this node's list of children.
///
/// Fails unless `new_child` is disconnected from the tree.
fn add_child(&self, new_child: &JSRef<Node>, before: Option<JSRef<Node>>) {
let doc = self.owner_doc().root();
doc.deref().wait_until_safe_to_modify_dom();
assert!(new_child.parent_node().is_none());
assert!(new_child.prev_sibling().is_none());
assert!(new_child.next_sibling().is_none());
match before {
Some(ref before) => {
assert!(before.parent_node().root().root_ref() == Some(*self));
match before.prev_sibling().root() {
None => {
assert!(Some(*before) == self.first_child().root().root_ref());
self.first_child.assign(Some(*new_child));
},
Some(ref prev_sibling) => {
prev_sibling.next_sibling.assign(Some(*new_child));
new_child.prev_sibling.assign(Some(**prev_sibling));
},
}
before.prev_sibling.assign(Some(*new_child));
new_child.next_sibling.assign(Some(*before));
},
None => {
match self.last_child().root() {
None => self.first_child.assign(Some(*new_child)),
Some(ref last_child) => {
assert!(last_child.next_sibling().is_none());
last_child.next_sibling.assign(Some(*new_child));
new_child.prev_sibling.assign(Some(**last_child));
}
}
self.last_child.assign(Some(*new_child));
},
}
new_child.parent_node.assign(Some(*self));
}
/// Removes the given child from this node's list of children.
///
/// Fails unless `child` is a child of this node.
fn remove_child(&self, child: &JSRef<Node>) {
let doc = self.owner_doc().root();
doc.deref().wait_until_safe_to_modify_dom();
assert!(child.parent_node().root().root_ref() == Some(*self));
match child.prev_sibling.get().root() {
None => {
self.first_child.assign(child.next_sibling.get());
}
Some(ref prev_sibling) => {
prev_sibling.next_sibling.assign(child.next_sibling.get());
}
}
match child.next_sibling.get().root() {
None => {
self.last_child.assign(child.prev_sibling.get());
}
Some(ref next_sibling) => {
next_sibling.prev_sibling.assign(child.prev_sibling.get());
}
}
child.prev_sibling.set(None);
child.next_sibling.set(None);
child.parent_node.set(None);
}
}
pub trait NodeHelpers {
fn ancestors(&self) -> AncestorIterator;
fn children(&self) -> AbstractNodeChildrenIterator;
fn child_elements(&self) -> ChildElementIterator;
fn following_siblings(&self) -> AbstractNodeChildrenIterator;
fn is_in_doc(&self) -> bool;
fn is_inclusive_ancestor_of(&self, parent: &JSRef<Node>) -> bool;
fn is_parent_of(&self, child: &JSRef<Node>) -> bool;
fn type_id(&self) -> NodeTypeId;
fn parent_node(&self) -> Option<Temporary<Node>>;
fn first_child(&self) -> Option<Temporary<Node>>;
fn last_child(&self) -> Option<Temporary<Node>>;
fn prev_sibling(&self) -> Option<Temporary<Node>>;
fn next_sibling(&self) -> Option<Temporary<Node>>;
fn owner_doc(&self) -> Temporary<Document>;
fn set_owner_doc(&self, document: &JSRef<Document>);
fn wait_until_safe_to_modify_dom(&self);
fn is_element(&self) -> bool;
fn is_document(&self) -> bool;
fn is_doctype(&self) -> bool;
fn is_text(&self) -> bool;
fn is_anchor_element(&self) -> bool;
fn get_hover_state(&self) -> bool;
fn set_hover_state(&self, state: bool);
fn dump(&self);
fn dump_indent(&self, indent: uint);
fn debug_str(&self) -> String;
fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a>;
fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a>;
fn inclusively_following_siblings<'a>(&'a self) -> AbstractNodeChildrenIterator<'a>;
fn to_trusted_node_address(&self) -> TrustedNodeAddress;
fn get_bounding_content_box(&self) -> Rect<Au>;
fn get_content_boxes(&self) -> Vec<Rect<Au>>;
fn query_selector(&self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>>;
fn query_selector_all(&self, selectors: DOMString) -> Fallible<Temporary<NodeList>>;
fn remove_self(&self);
}
impl<'a> NodeHelpers for JSRef<'a, Node> {
/// Dumps the subtree rooted at this node, for debugging.
fn dump(&self) {
self.dump_indent(0);
}
/// Dumps the node tree, for debugging, with indentation.
fn dump_indent(&self, indent: uint) {
let mut s = String::new();
for _ in range(0, indent) {
s.push_str(" ");
}
s.push_str(self.debug_str().as_slice());
debug!("{:s}", s);
// FIXME: this should have a pure version?
for kid in self.children() {
kid.dump_indent(indent + 1u)
}
}
/// Returns a string that describes this node.
fn debug_str(&self) -> String {
format!("{:?}", self.type_id)
}
fn is_in_doc(&self) -> bool {
self.deref().flags.deref().borrow().contains(IsInDoc)
}
/// Returns the type ID of this node. Fails if this node is borrowed mutably.
fn type_id(&self) -> NodeTypeId {
self.deref().type_id
}
fn parent_node(&self) -> Option<Temporary<Node>> {
self.deref().parent_node.get().map(|node| Temporary::new(node))
}
fn first_child(&self) -> Option<Temporary<Node>> {
self.deref().first_child.get().map(|node| Temporary::new(node))
}
fn last_child(&self) -> Option<Temporary<Node>> {
self.deref().last_child.get().map(|node| Temporary::new(node))
}
/// Returns the previous sibling of this node. Fails if this node is borrowed mutably.
fn prev_sibling(&self) -> Option<Temporary<Node>> {
self.deref().prev_sibling.get().map(|node| Temporary::new(node))
}
/// Returns the next sibling of this node. Fails if this node is borrowed mutably.
fn next_sibling(&self) -> Option<Temporary<Node>> {
self.deref().next_sibling.get().map(|node| Temporary::new(node))
}
#[inline]
fn is_element(&self) -> bool {
match self.type_id {
ElementNodeTypeId(..) => true,
_ => false
}
}
#[inline]
fn is_document(&self) -> bool {
self.type_id == DocumentNodeTypeId
}
#[inline]
fn is_anchor_element(&self) -> bool {
self.type_id == ElementNodeTypeId(HTMLAnchorElementTypeId)
}
#[inline]
fn is_doctype(&self) -> bool {
self.type_id == DoctypeNodeTypeId
}
#[inline]
fn is_text(&self) -> bool {
self.type_id == TextNodeTypeId
}
fn get_hover_state(&self) -> bool {
self.flags.deref().borrow().contains(InHoverState)
}
fn set_hover_state(&self, state: bool) {
if state {
self.flags.deref().borrow_mut().insert(InHoverState);
} else {
self.flags.deref().borrow_mut().remove(InHoverState);
}
}
/// Iterates over this node and all its descendants, in preorder.
fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a> {
let mut nodes = vec!();
gather_abstract_nodes(self, &mut nodes, false);
TreeIterator::new(nodes)
}
/// Iterates over this node and all its descendants, in postorder.
fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a> {
let mut nodes = vec!();
gather_abstract_nodes(self, &mut nodes, true);
TreeIterator::new(nodes)
}
fn inclusively_following_siblings<'a>(&'a self) -> AbstractNodeChildrenIterator<'a> {
AbstractNodeChildrenIterator {
current_node: Some(self.clone()),
}
}
fn is_inclusive_ancestor_of(&self, parent: &JSRef<Node>) -> bool {
self == parent || parent.ancestors().any(|ancestor| &ancestor == self)
}
fn following_siblings(&self) -> AbstractNodeChildrenIterator {
AbstractNodeChildrenIterator {
current_node: self.next_sibling().root().map(|next| next.deref().clone()),
}
}
fn is_parent_of(&self, child: &JSRef<Node>) -> bool {
match child.parent_node() {
Some(ref parent) if *parent == Temporary::from_rooted(self) => true,
_ => false
}
}
fn to_trusted_node_address(&self) -> TrustedNodeAddress {
TrustedNodeAddress(self.deref() as *Node as *libc::c_void)
}
fn get_bounding_content_box(&self) -> Rect<Au> {
let window = window_from_node(self).root();
let page = window.deref().page();
let (chan, port) = channel();
let addr = self.to_trusted_node_address();
let ContentBoxResponse(rect) = page.query_layout(ContentBoxQuery(addr, chan), port);
rect
}
fn get_content_boxes(&self) -> Vec<Rect<Au>> {
let window = window_from_node(self).root();
let page = window.deref().page();
let (chan, port) = channel();
let addr = self.to_trusted_node_address();
let ContentBoxesResponse(rects) = page.query_layout(ContentBoxesQuery(addr, chan), port);
rects
}
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn query_selector(&self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> {
// Step 1.
let namespace = NamespaceMap::new();
match parse_selector_list(tokenize(selectors.as_slice()).map(|(token, _)| token).collect(), &namespace) {
// Step 2.
None => return Err(Syntax),
// Step 3.
Some(ref selectors) => {
let root = self.ancestors().last().unwrap_or(self.clone());
for selector in selectors.iter() {
assert!(selector.pseudo_element.is_none());
for node in root.traverse_preorder().filter(|node| node.is_element()) {
let mut _shareable: bool = false;
if matches_compound_selector(selector.compound_selectors.deref(), &node, &mut _shareable) {
let elem: &JSRef<Element> = ElementCast::to_ref(&node).unwrap();
return Ok(Some(Temporary::from_rooted(elem)));
}
}
}
}
}
Ok(None)
}
// http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn query_selector_all(&self, selectors: DOMString) -> Fallible<Temporary<NodeList>> {
// Step 1.
let mut nodes = vec!();
let root = self.ancestors().last().unwrap_or(self.clone());
let namespace = NamespaceMap::new();
match parse_selector_list(tokenize(selectors.as_slice()).map(|(token, _)| token).collect(), &namespace) {
// Step 2.
None => return Err(Syntax),
// Step 3.
Some(ref selectors) => {
for selector in selectors.iter() {
assert!(selector.pseudo_element.is_none());
for node in root.traverse_preorder().filter(|node| node.is_element()) {
let mut _shareable: bool = false;
if matches_compound_selector(selector.compound_selectors.deref(), &node, &mut _shareable) {
nodes.push(node.clone())
}
}
}
}
}
let window = window_from_node(self).root();
Ok(NodeList::new_simple_list(&window.root_ref(), nodes))
}
fn ancestors(&self) -> AncestorIterator {
AncestorIterator {
current: self.parent_node.get().map(|node| (*node.root()).clone()),
}
}
fn owner_doc(&self) -> Temporary<Document> {
Temporary::new(self.owner_doc.get().get_ref().clone())
}
fn set_owner_doc(&self, document: &JSRef<Document>) {
self.owner_doc.assign(Some(document.clone()));
}
fn children(&self) -> AbstractNodeChildrenIterator {
AbstractNodeChildrenIterator {
current_node: self.first_child.get().map(|node| (*node.root()).clone()),
}
}
fn child_elements(&self) -> ChildElementIterator {
self.children()
.filter(|node| {
node.is_element()
})
.map(|node| {
let elem: &JSRef<Element> = ElementCast::to_ref(&node).unwrap();
elem.clone()
})
}
fn wait_until_safe_to_modify_dom(&self) {
let document = self.owner_doc().root();
document.deref().wait_until_safe_to_modify_dom();
}
fn remove_self(&self) {
match self.parent_node().root() {
Some(ref parent) => parent.remove_child(self),
None => ()
}
}
}
/// If the given untrusted node address represents a valid DOM node in the given runtime,
/// returns it.
pub fn from_untrusted_node_address(runtime: *mut JSRuntime, candidate: UntrustedNodeAddress)
-> Temporary<Node> {
unsafe {
let candidate: uintptr_t = mem::transmute(candidate);
let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime,
candidate);
if object.is_null() {
fail!("Attempted to create a `JS<Node>` from an invalid pointer!")
}
let boxed_node: *Node = utils::unwrap(object);
Temporary::new(JS::from_raw(boxed_node))
}
}
pub trait LayoutNodeHelpers {
unsafe fn type_id_for_layout(&self) -> NodeTypeId;
unsafe fn parent_node_ref(&self) -> Option<JS<Node>>;
unsafe fn first_child_ref(&self) -> Option<JS<Node>>;
unsafe fn last_child_ref(&self) -> Option<JS<Node>>;
unsafe fn prev_sibling_ref(&self) -> Option<JS<Node>>;
unsafe fn next_sibling_ref(&self) -> Option<JS<Node>>;
unsafe fn owner_doc_for_layout(&self) -> JS<Document>;
unsafe fn is_element_for_layout(&self) -> bool;
}
impl LayoutNodeHelpers for JS<Node> {
#[inline]
unsafe fn type_id_for_layout(&self) -> NodeTypeId {
(*self.unsafe_get()).type_id
}
#[inline]
unsafe fn is_element_for_layout(&self) -> bool {
(*self.unsafe_get()).is_element()
}
#[inline]
unsafe fn parent_node_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).parent_node.get()
}
#[inline]
unsafe fn first_child_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).first_child.get()
}
#[inline]
unsafe fn last_child_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).last_child.get()
}
#[inline]
unsafe fn prev_sibling_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).prev_sibling.get()
}
#[inline]
unsafe fn next_sibling_ref(&self) -> Option<JS<Node>> {
(*self.unsafe_get()).next_sibling.get()
}
#[inline]
unsafe fn owner_doc_for_layout(&self) -> JS<Document> {
(*self.unsafe_get()).owner_doc.get().unwrap()
}
}
pub trait RawLayoutNodeHelpers {
unsafe fn get_hover_state_for_layout(&self) -> bool;
}
impl RawLayoutNodeHelpers for Node {
unsafe fn get_hover_state_for_layout(&self) -> bool {
self.flags.deref().borrow().contains(InHoverState)
}
}
//
// Iteration and traversal
//
pub type ChildElementIterator<'a, 'b> = Map<'a, JSRef<'b, Node>,
JSRef<'b, Element>,
Filter<'a, JSRef<'b, Node>, AbstractNodeChildrenIterator<'b>>>;
pub struct AbstractNodeChildrenIterator<'a> {
current_node: Option<JSRef<'a, Node>>,
}
impl<'a> Iterator<JSRef<'a, Node>> for AbstractNodeChildrenIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
let node = self.current_node.clone();
self.current_node = node.clone().and_then(|node| {
node.next_sibling().map(|node| (*node.root()).clone())
});
node
}
}
pub struct AncestorIterator<'a> {
current: Option<JSRef<'a, Node>>,
}
impl<'a> Iterator<JSRef<'a, Node>> for AncestorIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
if self.current.is_none() {
return None;
}
// FIXME: Do we need two clones here?
let x = self.current.get_ref().clone();
self.current = x.parent_node().map(|node| (*node.root()).clone());
Some(x)
}
}
// FIXME: Do this without precomputing a vector of refs.
// Easy for preorder; harder for postorder.
pub struct TreeIterator<'a> {
nodes: Vec<JSRef<'a, Node>>,
index: uint,
}
impl<'a> TreeIterator<'a> {
fn new(nodes: Vec<JSRef<'a, Node>>) -> TreeIterator<'a> {
TreeIterator {
nodes: nodes,
index: 0,
}
}
}
impl<'a> Iterator<JSRef<'a, Node>> for TreeIterator<'a> {
fn next(&mut self) -> Option<JSRef<'a, Node>> {
if self.index >= self.nodes.len() {
None
} else {
let v = self.nodes.get(self.index).clone();
self.index += 1;
Some(v)
}
}
}
pub struct NodeIterator {
pub start_node: JS<Node>,
pub current_node: Option<JS<Node>>,
pub depth: uint,
include_start: bool,
include_descendants_of_void: bool
}
impl NodeIterator {
pub fn new<'a>(start_node: &JSRef<'a, Node>,
include_start: bool,
include_descendants_of_void: bool) -> NodeIterator {
NodeIterator {
start_node: JS::from_rooted(start_node),
current_node: None,
depth: 0,
include_start: include_start,
include_descendants_of_void: include_descendants_of_void
}
}
fn next_child<'b>(&self, node: &JSRef<'b, Node>) -> Option<JSRef<Node>> {
if !self.include_descendants_of_void && node.is_element() {
let elem: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
if elem.deref().is_void() {
None
} else {
node.first_child().map(|child| (*child.root()).clone())
}
} else {
node.first_child().map(|child| (*child.root()).clone())
}
}
}
impl<'a> Iterator<JSRef<'a, Node>> for NodeIterator {
fn next(&mut self) -> Option<JSRef<Node>> {
self.current_node = match self.current_node.as_ref().map(|node| node.root()) {
None => {
if self.include_start {
Some(self.start_node)
} else {
self.next_child(&*self.start_node.root())
.map(|child| JS::from_rooted(&child))
}
},
Some(node) => {
match self.next_child(&*node) {
Some(child) => {
self.depth += 1;
Some(JS::from_rooted(&child))
},
None if JS::from_rooted(&*node) == self.start_node => None,
None => {
match node.deref().next_sibling().root() {
Some(sibling) => Some(JS::from_rooted(&*sibling)),
None => {
let mut candidate = node.deref().clone();
while candidate.next_sibling().is_none() {
candidate = (*candidate.parent_node()
.expect("Got to root without reaching start node")
.root()).clone();
self.depth -= 1;
if JS::from_rooted(&candidate) == self.start_node {
break;
}
}
if JS::from_rooted(&candidate) != self.start_node {
candidate.next_sibling().map(|node| JS::from_rooted(node.root().deref()))
} else {
None
}
}
}
}
}
}
};
self.current_node.map(|node| (*node.root()).clone())
}
}
fn gather_abstract_nodes<'a>(cur: &JSRef<'a, Node>, refs: &mut Vec<JSRef<'a, Node>>, postorder: bool) {
if !postorder {
refs.push(cur.clone());
}
for kid in cur.children() {
gather_abstract_nodes(&kid, refs, postorder)
}
if postorder {
refs.push(cur.clone());
}
}
/// Specifies whether children must be recursively cloned or not.
#[deriving(PartialEq)]
pub enum CloneChildrenFlag {
CloneChildren,
DoNotCloneChildren
}
fn as_uintptr<T>(t: &T) -> uintptr_t { t as *T as uintptr_t }
impl Node {
pub fn reflect_node<N: Reflectable+NodeBase>
(node: Box<N>,
document: &JSRef<Document>,
wrap_fn: extern "Rust" fn(*mut JSContext, &GlobalRef, Box<N>) -> Temporary<N>)
-> Temporary<N> {
let window = document.window.root();
reflect_dom_object(node, &Window(*window), wrap_fn)
}
pub fn new_inherited(type_id: NodeTypeId, doc: &JSRef<Document>) -> Node {
Node::new_(type_id, Some(doc.clone()))
}
pub fn new_without_doc(type_id: NodeTypeId) -> Node {
Node::new_(type_id, None)
}
fn new_(type_id: NodeTypeId, doc: Option<JSRef<Document>>) -> Node {
Node {
eventtarget: EventTarget::new_inherited(NodeTargetTypeId(type_id)),
type_id: type_id,
parent_node: Cell::new(None),
first_child: Cell::new(None),
last_child: Cell::new(None),
next_sibling: Cell::new(None),
prev_sibling: Cell::new(None),
owner_doc: Cell::new(doc.unrooted()),
child_list: Cell::new(None),
flags: Traceable::new(RefCell::new(NodeFlags::new(type_id))),
layout_data: LayoutDataRef::new(),
}
}
// http://dom.spec.whatwg.org/#concept-node-adopt
pub fn adopt(node: &JSRef<Node>, document: &JSRef<Document>) {
// Step 1.
match node.parent_node().root() {
Some(parent) => {
Node::remove(node, &*parent, Unsuppressed);
}
None => (),
}
// Step 2.
let node_doc = document_from_node(node).root();
if &*node_doc != document {
for descendant in node.traverse_preorder() {
descendant.set_owner_doc(document);
}
}
// Step 3.
// If node is an element, it is _affected by a base URL change_.
}
// http://dom.spec.whatwg.org/#concept-node-pre-insert
fn pre_insert(node: &JSRef<Node>, parent: &JSRef<Node>, child: Option<JSRef<Node>>)
-> Fallible<Temporary<Node>> {
// Step 1.
match parent.type_id() {
DocumentNodeTypeId |
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => (),
_ => return Err(HierarchyRequest)
}
// Step 2.
if node.is_inclusive_ancestor_of(parent) {
return Err(HierarchyRequest);
}
// Step 3.
match child {
Some(ref child) if !parent.is_parent_of(child) => return Err(NotFound),
_ => ()
}
// Step 4-5.
match node.type_id() {
TextNodeTypeId => {
match node.parent_node().root() {
Some(ref parent) if parent.is_document() => return Err(HierarchyRequest),
_ => ()
}
}
DoctypeNodeTypeId => {
match node.parent_node().root() {
Some(ref parent) if !parent.is_document() => return Err(HierarchyRequest),
_ => ()
}
}
DocumentFragmentNodeTypeId |
ElementNodeTypeId(_) |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => return Err(HierarchyRequest)
}
// Step 6.
match parent.type_id() {
DocumentNodeTypeId => {
match node.type_id() {
// Step 6.1
DocumentFragmentNodeTypeId => {
// Step 6.1.1(b)
if node.children().any(|c| c.is_text()) {
return Err(HierarchyRequest);
}
match node.child_elements().count() {
0 => (),
// Step 6.1.2
1 => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
match child {
Some(ref child) if child.inclusively_following_siblings()
.any(|child| child.is_doctype()) => {
return Err(HierarchyRequest);
}
_ => (),
}
},
// Step 6.1.1(a)
_ => return Err(HierarchyRequest),
}
},
// Step 6.2
ElementNodeTypeId(_) => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
match child {
Some(ref child) if child.inclusively_following_siblings()
.any(|child| child.is_doctype()) => {
return Err(HierarchyRequest);
}
_ => (),
}
},
// Step 6.3
DoctypeNodeTypeId => {
if parent.children().any(|c| c.is_doctype()) {
return Err(HierarchyRequest);
}
match child {
Some(ref child) => {
if parent.children()
.take_while(|c| c != child)
.any(|c| c.is_element()) {
return Err(HierarchyRequest);
}
},
None => {
// FIXME: change to empty() when https://github.com/mozilla/rust/issues/11218
// will be fixed
if parent.child_elements().count() > 0 {
return Err(HierarchyRequest);
}
},
}
},
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => unreachable!(),
}
},
_ => (),
}
// Step 7-8.
let referenceChild = match child {
Some(ref child) if child == node => node.next_sibling().map(|node| (*node.root()).clone()),
_ => child
};
// Step 9.
let document = document_from_node(parent).root();
Node::adopt(node, &*document);
// Step 10.
Node::insert(node, parent, referenceChild, Unsuppressed);
// Step 11.
return Ok(Temporary::from_rooted(node))
}
// http://dom.spec.whatwg.org/#concept-node-insert
fn insert(node: &JSRef<Node>,
parent: &JSRef<Node>,
child: Option<JSRef<Node>>,
suppress_observers: SuppressObserver) {
// XXX assert owner_doc
// Step 1-3: ranges.
// Step 4.
let mut nodes = match node.type_id() {
DocumentFragmentNodeTypeId => node.children().collect(),
_ => vec!(node.clone()),
};
// Step 5: DocumentFragment, mutation records.
// Step 6: DocumentFragment.
match node.type_id() {
DocumentFragmentNodeTypeId => {
for c in node.children() {
Node::remove(&c, node, Suppressed);
}
},
_ => (),
}
// Step 7: mutation records.
// Step 8.
for node in nodes.mut_iter() {
parent.add_child(node, child);
let is_in_doc = parent.is_in_doc();
for kid in node.traverse_preorder() {
if is_in_doc {
kid.flags.deref().borrow_mut().insert(IsInDoc);
} else {
kid.flags.deref().borrow_mut().remove(IsInDoc);
}
}
}
// Step 9.
match suppress_observers {
Unsuppressed => {
for node in nodes.iter() {
node.node_inserted();
}
}
Suppressed => ()
}
}
// http://dom.spec.whatwg.org/#concept-node-replace-all
fn replace_all(node: Option<JSRef<Node>>, parent: &JSRef<Node>) {
// Step 1.
match node {
Some(ref node) => {
let document = document_from_node(parent).root();
Node::adopt(node, &*document);
}
None => (),
}
// Step 2.
let removedNodes: Vec<JSRef<Node>> = parent.children().collect();
// Step 3.
let addedNodes = match node {
None => vec!(),
Some(ref node) => match node.type_id() {
DocumentFragmentNodeTypeId => node.children().collect(),
_ => vec!(node.clone()),
},
};
// Step 4.
for child in parent.children() {
Node::remove(&child, parent, Suppressed);
}
// Step 5.
match node {
Some(ref node) => Node::insert(node, parent, None, Suppressed),
None => (),
}
// Step 6: mutation records.
// Step 7.
let parent_in_doc = parent.is_in_doc();
for removedNode in removedNodes.iter() {
removedNode.node_removed(parent_in_doc);
}
for addedNode in addedNodes.iter() {
addedNode.node_inserted();
}
}
// http://dom.spec.whatwg.org/#concept-node-pre-remove
fn pre_remove(child: &JSRef<Node>, parent: &JSRef<Node>) -> Fallible<Temporary<Node>> {
// Step 1.
match child.parent_node() {
Some(ref node) if *node != Temporary::from_rooted(parent) => return Err(NotFound),
_ => ()
}
// Step 2.
Node::remove(child, parent, Unsuppressed);
// Step 3.
Ok(Temporary::from_rooted(child))
}
// http://dom.spec.whatwg.org/#concept-node-remove
fn remove(node: &JSRef<Node>, parent: &JSRef<Node>, suppress_observers: SuppressObserver) {
assert!(node.parent_node().map_or(false, |node_parent| node_parent == Temporary::from_rooted(parent)));
// Step 1-5: ranges.
// Step 6-7: mutation observers.
// Step 8.
parent.remove_child(node);
node.deref().flags.deref().borrow_mut().remove(IsInDoc);
// Step 9.
match suppress_observers {
Suppressed => (),
Unsuppressed => node.node_removed(parent.is_in_doc()),
}
}
// http://dom.spec.whatwg.org/#concept-node-clone
pub fn clone(node: &JSRef<Node>, maybe_doc: Option<&JSRef<Document>>,
clone_children: CloneChildrenFlag) -> Temporary<Node> {
// Step 1.
let document = match maybe_doc {
Some(doc) => JS::from_rooted(doc).root(),
None => node.owner_doc().root()
};
// Step 2.
// XXXabinader: clone() for each node as trait?
let copy: Root<Node> = match node.type_id() {
DoctypeNodeTypeId => {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap();
let doctype = doctype.deref();
let doctype = DocumentType::new(doctype.name.clone(),
Some(doctype.public_id.clone()),
Some(doctype.system_id.clone()), &*document);
NodeCast::from_temporary(doctype)
},
DocumentFragmentNodeTypeId => {
let doc_fragment = DocumentFragment::new(&*document);
NodeCast::from_temporary(doc_fragment)
},
CommentNodeTypeId => {
let comment: &JSRef<Comment> = CommentCast::to_ref(node).unwrap();
let comment = comment.deref();
let comment = Comment::new(comment.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(comment)
},
DocumentNodeTypeId => {
let document: &JSRef<Document> = DocumentCast::to_ref(node).unwrap();
let is_html_doc = match document.is_html_document {
true => HTMLDocument,
false => NonHTMLDocument
};
let window = document.window.root();
let document = Document::new(&*window, Some(document.url().clone()),
is_html_doc, None);
NodeCast::from_temporary(document)
},
ElementNodeTypeId(..) => {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let element = element.deref();
let element = build_element_from_tag(element.local_name.as_slice().to_string(),
element.namespace.clone(), &*document);
NodeCast::from_temporary(element)
},
TextNodeTypeId => {
let text: &JSRef<Text> = TextCast::to_ref(node).unwrap();
let text = text.deref();
let text = Text::new(text.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(text)
},
ProcessingInstructionNodeTypeId => {
let pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap();
let pi = pi.deref();
let pi = ProcessingInstruction::new(pi.target.clone(),
pi.characterdata.data.deref().borrow().clone(), &*document);
NodeCast::from_temporary(pi)
},
}.root();
// Step 3.
let document = if copy.is_document() {
let doc: &JSRef<Document> = DocumentCast::to_ref(&*copy).unwrap();
JS::from_rooted(doc).root()
} else {
JS::from_rooted(&*document).root()
};
assert!(&*copy.owner_doc().root() == &*document);
// Step 4 (some data already copied in step 2).
match node.type_id() {
DocumentNodeTypeId => {
let node_doc: &JSRef<Document> = DocumentCast::to_ref(node).unwrap();
let copy_doc: &JSRef<Document> = DocumentCast::to_ref(&*copy).unwrap();
copy_doc.set_encoding_name(node_doc.encoding_name.deref().borrow().clone());
copy_doc.set_quirks_mode(node_doc.quirks_mode());
},
ElementNodeTypeId(..) => {
let node_elem: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let copy_elem: &JSRef<Element> = ElementCast::to_ref(&*copy).unwrap();
// FIXME: https://github.com/mozilla/servo/issues/1737
let window = document.deref().window.root();
for attr in node_elem.deref().attrs.borrow().iter().map(|attr| attr.root()) {
copy_elem.deref().attrs.borrow_mut().push_unrooted(
&Attr::new(&*window,
attr.deref().local_name.clone(), attr.deref().value().clone(),
attr.deref().name.clone(), attr.deref().namespace.clone(),
attr.deref().prefix.clone(), copy_elem));
}
},
_ => ()
}
// Step 5: cloning steps.
// Step 6.
if clone_children == CloneChildren {
for ref child in node.children() {
let child_copy = Node::clone(&*child, Some(&*document), clone_children).root();
let _inserted_node = Node::pre_insert(&*child_copy, &*copy, None);
}
}
// Step 7.
Temporary::from_rooted(&*copy)
}
/// Sends layout data, if any, back to the layout task to be destroyed.
unsafe fn reap_layout_data(&mut self) {
if self.layout_data.is_present() {
let layout_data = mem::replace(&mut self.layout_data, LayoutDataRef::new());
let layout_chan = layout_data.take_chan();
match layout_chan {
None => {}
Some(chan) => {
let LayoutChan(chan) = chan;
chan.send(ReapLayoutDataMsg(layout_data))
},
}
}
}
}
pub trait NodeMethods {
fn NodeType(&self) -> u16;
fn NodeName(&self) -> DOMString;
fn GetBaseURI(&self) -> Option<DOMString>;
fn GetOwnerDocument(&self) -> Option<Temporary<Document>>;
fn GetParentNode(&self) -> Option<Temporary<Node>>;
fn GetParentElement(&self) -> Option<Temporary<Element>>;
fn HasChildNodes(&self) -> bool;
fn ChildNodes(&self) -> Temporary<NodeList>;
fn GetFirstChild(&self) -> Option<Temporary<Node>>;
fn GetLastChild(&self) -> Option<Temporary<Node>>;
fn GetPreviousSibling(&self) -> Option<Temporary<Node>>;
fn GetNextSibling(&self) -> Option<Temporary<Node>>;
fn GetNodeValue(&self) -> Option<DOMString>;
fn SetNodeValue(&self, val: Option<DOMString>) -> ErrorResult;
fn GetTextContent(&self) -> Option<DOMString>;
fn SetTextContent(&self, value: Option<DOMString>) -> ErrorResult;
fn InsertBefore(&self, node: &JSRef<Node>, child: Option<JSRef<Node>>) -> Fallible<Temporary<Node>>;
fn AppendChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn ReplaceChild(&self, node: &JSRef<Node>, child: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn RemoveChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>>;
fn Normalize(&self);
fn CloneNode(&self, deep: bool) -> Temporary<Node>;
fn IsEqualNode(&self, maybe_node: Option<JSRef<Node>>) -> bool;
fn CompareDocumentPosition(&self, other: &JSRef<Node>) -> u16;
fn Contains(&self, maybe_other: Option<JSRef<Node>>) -> bool;
fn LookupPrefix(&self, _prefix: Option<DOMString>) -> Option<DOMString>;
fn LookupNamespaceURI(&self, _namespace: Option<DOMString>) -> Option<DOMString>;
fn IsDefaultNamespace(&self, _namespace: Option<DOMString>) -> bool;
}
impl<'a> NodeMethods for JSRef<'a, Node> {
// http://dom.spec.whatwg.org/#dom-node-nodetype
fn NodeType(&self) -> u16 {
match self.type_id {
ElementNodeTypeId(_) => NodeConstants::ELEMENT_NODE,
TextNodeTypeId => NodeConstants::TEXT_NODE,
ProcessingInstructionNodeTypeId => NodeConstants::PROCESSING_INSTRUCTION_NODE,
CommentNodeTypeId => NodeConstants::COMMENT_NODE,
DocumentNodeTypeId => NodeConstants::DOCUMENT_NODE,
DoctypeNodeTypeId => NodeConstants::DOCUMENT_TYPE_NODE,
DocumentFragmentNodeTypeId => NodeConstants::DOCUMENT_FRAGMENT_NODE,
}
}
// http://dom.spec.whatwg.org/#dom-node-nodename
fn NodeName(&self) -> DOMString {
match self.type_id {
ElementNodeTypeId(..) => {
let elem: &JSRef<Element> = ElementCast::to_ref(self).unwrap();
elem.TagName()
}
TextNodeTypeId => "#text".to_string(),
ProcessingInstructionNodeTypeId => {
let processing_instruction: &JSRef<ProcessingInstruction> =
ProcessingInstructionCast::to_ref(self).unwrap();
processing_instruction.Target()
}
CommentNodeTypeId => "#comment".to_string(),
DoctypeNodeTypeId => {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap();
doctype.deref().name.clone()
},
DocumentFragmentNodeTypeId => "#document-fragment".to_string(),
DocumentNodeTypeId => "#document".to_string()
}
}
// http://dom.spec.whatwg.org/#dom-node-baseuri
fn GetBaseURI(&self) -> Option<DOMString> {
// FIXME (#1824) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-ownerdocument
fn GetOwnerDocument(&self) -> Option<Temporary<Document>> {
match self.type_id {
ElementNodeTypeId(..) |
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
DoctypeNodeTypeId |
DocumentFragmentNodeTypeId => Some(self.owner_doc()),
DocumentNodeTypeId => None
}
}
// http://dom.spec.whatwg.org/#dom-node-parentnode
fn GetParentNode(&self) -> Option<Temporary<Node>> {
self.parent_node.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-parentelement
fn GetParentElement(&self) -> Option<Temporary<Element>> {
self.parent_node.get()
.and_then(|parent| {
let parent = parent.root();
ElementCast::to_ref(&*parent).map(|elem| {
Temporary::from_rooted(elem)
})
})
}
// http://dom.spec.whatwg.org/#dom-node-haschildnodes
fn HasChildNodes(&self) -> bool {
self.first_child.get().is_some()
}
// http://dom.spec.whatwg.org/#dom-node-childnodes
fn ChildNodes(&self) -> Temporary<NodeList> {
match self.child_list.get() {
None => (),
Some(ref list) => return Temporary::new(list.clone()),
}
let doc = self.owner_doc().root();
let window = doc.deref().window.root();
let child_list = NodeList::new_child_list(&*window, self);
self.child_list.assign(Some(child_list));
Temporary::new(self.child_list.get().get_ref().clone())
}
// http://dom.spec.whatwg.org/#dom-node-firstchild
fn GetFirstChild(&self) -> Option<Temporary<Node>> {
self.first_child.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-lastchild
fn GetLastChild(&self) -> Option<Temporary<Node>> {
self.last_child.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-previoussibling
fn GetPreviousSibling(&self) -> Option<Temporary<Node>> {
self.prev_sibling.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-nextsibling
fn GetNextSibling(&self) -> Option<Temporary<Node>> {
self.next_sibling.get().map(|node| Temporary::new(node))
}
// http://dom.spec.whatwg.org/#dom-node-nodevalue
fn GetNodeValue(&self) -> Option<DOMString> {
match self.type_id {
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
let chardata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
Some(chardata.Data())
}
_ => {
None
}
}
}
// http://dom.spec.whatwg.org/#dom-node-nodevalue
fn SetNodeValue(&self, val: Option<DOMString>) -> ErrorResult {
match self.type_id {
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
self.SetTextContent(val)
}
_ => Ok(())
}
}
// http://dom.spec.whatwg.org/#dom-node-textcontent
fn GetTextContent(&self) -> Option<DOMString> {
match self.type_id {
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => {
let mut content = String::new();
for node in self.traverse_preorder() {
if node.is_text() {
let text: &JSRef<Text> = TextCast::to_ref(&node).unwrap();
content.push_str(text.deref().characterdata.data.deref().borrow().as_slice());
}
}
Some(content)
}
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
Some(characterdata.Data())
}
DoctypeNodeTypeId |
DocumentNodeTypeId => {
None
}
}
}
// http://dom.spec.whatwg.org/#dom-node-textcontent
fn SetTextContent(&self, value: Option<DOMString>) -> ErrorResult {
let value = null_str_as_empty(&value);
match self.type_id {
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => {
// Step 1-2.
let node = if value.len() == 0 {
None
} else {
let document = self.owner_doc().root();
Some(NodeCast::from_temporary(document.deref().CreateTextNode(value)))
}.root();
// Step 3.
Node::replace_all(node.root_ref(), self);
}
CommentNodeTypeId |
TextNodeTypeId |
ProcessingInstructionNodeTypeId => {
self.wait_until_safe_to_modify_dom();
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap();
*characterdata.data.deref().borrow_mut() = value;
// Notify the document that the content of this node is different
let document = self.owner_doc().root();
document.deref().content_changed();
}
DoctypeNodeTypeId |
DocumentNodeTypeId => {}
}
Ok(())
}
// http://dom.spec.whatwg.org/#dom-node-insertbefore
fn InsertBefore(&self, node: &JSRef<Node>, child: Option<JSRef<Node>>) -> Fallible<Temporary<Node>> {
Node::pre_insert(node, self, child)
}
// http://dom.spec.whatwg.org/#dom-node-appendchild
fn AppendChild(&self, node: &JSRef<Node>) -> Fallible<Temporary<Node>> {
Node::pre_insert(node, self, None)
}
// http://dom.spec.whatwg.org/#concept-node-replace
fn ReplaceChild(&self, node: &JSRef<Node>, child: &JSRef<Node>) -> Fallible<Temporary<Node>> {
// Step 1.
match self.type_id {
DocumentNodeTypeId |
DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => (),
_ => return Err(HierarchyRequest)
}
// Step 2.
if node.is_inclusive_ancestor_of(self) {
return Err(HierarchyRequest);
}
// Step 3.
if !self.is_parent_of(child) {
return Err(NotFound);
}
// Step 4-5.
match node.type_id() {
TextNodeTypeId if self.is_document() => return Err(HierarchyRequest),
DoctypeNodeTypeId if !self.is_document() => return Err(HierarchyRequest),
DocumentFragmentNodeTypeId |
DoctypeNodeTypeId |
ElementNodeTypeId(..) |
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => return Err(HierarchyRequest)
}
// Step 6.
match self.type_id {
DocumentNodeTypeId => {
match node.type_id() {
// Step 6.1
DocumentFragmentNodeTypeId => {
// Step 6.1.1(b)
if node.children().any(|c| c.is_text()) {
return Err(HierarchyRequest);
}
match node.child_elements().count() {
0 => (),
// Step 6.1.2
1 => {
if self.child_elements().any(|c| NodeCast::from_ref(&c) != child) {
return Err(HierarchyRequest);
}
if child.following_siblings()
.any(|child| child.is_doctype()) {
return Err(HierarchyRequest);
}
},
// Step 6.1.1(a)
_ => return Err(HierarchyRequest)
}
},
// Step 6.2
ElementNodeTypeId(..) => {
if self.child_elements().any(|c| NodeCast::from_ref(&c) != child) {
return Err(HierarchyRequest);
}
if child.following_siblings()
.any(|child| child.is_doctype()) {
return Err(HierarchyRequest);
}
},
// Step 6.3
DoctypeNodeTypeId => {
if self.children().any(|c| c.is_doctype() && &c != child) {
return Err(HierarchyRequest);
}
if self.children()
.take_while(|c| c != child)
.any(|c| c.is_element()) {
return Err(HierarchyRequest);
}
},
TextNodeTypeId |
ProcessingInstructionNodeTypeId |
CommentNodeTypeId => (),
DocumentNodeTypeId => unreachable!()
}
},
_ => ()
}
// Ok if not caught by previous error checks.
if *node == *child {
return Ok(Temporary::from_rooted(child));
}
// Step 7-8.
let next_sibling = child.next_sibling().map(|node| (*node.root()).clone());
let reference_child = match next_sibling {
Some(ref sibling) if sibling == node => node.next_sibling().map(|node| (*node.root()).clone()),
_ => next_sibling
};
// Step 9.
let document = document_from_node(self).root();
Node::adopt(node, &*document);
{
// Step 10.
Node::remove(child, self, Suppressed);
// Step 11.
Node::insert(node, self, reference_child, Suppressed);
}
// Step 12-14.
// Step 13: mutation records.
child.node_removed(self.is_in_doc());
if node.type_id() == DocumentFragmentNodeTypeId {
for child_node in node.children() {
child_node.node_inserted();
}
} else {
node.node_inserted();
}
// Step 15.
Ok(Temporary::from_rooted(child))
}
// http://dom.spec.whatwg.org/#dom-node-removechild
fn RemoveChild(&self, node: &JSRef<Node>)
-> Fallible<Temporary<Node>> {
Node::pre_remove(node, self)
}
// http://dom.spec.whatwg.org/#dom-node-normalize
fn Normalize(&self) {
let mut prev_text = None;
for child in self.children() {
if child.is_text() {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(&child).unwrap();
if characterdata.Length() == 0 {
self.remove_child(&child);
} else {
match prev_text {
Some(ref mut text_node) => {
let prev_characterdata: &mut JSRef<CharacterData> = CharacterDataCast::to_mut_ref(text_node).unwrap();
let _ = prev_characterdata.AppendData(characterdata.Data());
self.remove_child(&child);
},
None => prev_text = Some(child)
}
}
} else {
child.Normalize();
prev_text = None;
}
}
}
// http://dom.spec.whatwg.org/#dom-node-clonenode
fn CloneNode(&self, deep: bool) -> Temporary<Node> {
match deep {
true => Node::clone(self, None, CloneChildren),
false => Node::clone(self, None, DoNotCloneChildren)
}
}
// http://dom.spec.whatwg.org/#dom-node-isequalnode
fn IsEqualNode(&self, maybe_node: Option<JSRef<Node>>) -> bool {
fn is_equal_doctype(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap();
let other_doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(other).unwrap();
(doctype.deref().name == other_doctype.deref().name) &&
(doctype.deref().public_id == other_doctype.deref().public_id) &&
(doctype.deref().system_id == other_doctype.deref().system_id)
}
fn is_equal_element(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let other_element: &JSRef<Element> = ElementCast::to_ref(other).unwrap();
// FIXME: namespace prefix
let element = element.deref();
let other_element = other_element.deref();
(element.namespace == other_element.namespace) &&
(element.local_name == other_element.local_name) &&
(element.attrs.borrow().len() == other_element.attrs.borrow().len())
}
fn is_equal_processinginstruction(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap();
let other_pi: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(other).unwrap();
(pi.deref().target == other_pi.deref().target) &&
(*pi.deref().characterdata.data.deref().borrow() == *other_pi.deref().characterdata.data.deref().borrow())
}
fn is_equal_characterdata(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(node).unwrap();
let other_characterdata: &JSRef<CharacterData> = CharacterDataCast::to_ref(other).unwrap();
*characterdata.deref().data.deref().borrow() == *other_characterdata.deref().data.deref().borrow()
}
fn is_equal_element_attrs(node: &JSRef<Node>, other: &JSRef<Node>) -> bool {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
let other_element: &JSRef<Element> = ElementCast::to_ref(other).unwrap();
let element = element.deref();
let other_element = other_element.deref();
assert!(element.attrs.borrow().len() == other_element.attrs.borrow().len());
element.attrs.borrow().iter().map(|attr| attr.root()).all(|attr| {
other_element.attrs.borrow().iter().map(|attr| attr.root()).any(|other_attr| {
(attr.namespace == other_attr.namespace) &&
(attr.local_name == other_attr.local_name) &&
(attr.deref().value().as_slice() == other_attr.deref().value().as_slice())
})
})
}
fn is_equal_node(this: &JSRef<Node>, node: &JSRef<Node>) -> bool {
// Step 2.
if this.type_id() != node.type_id() {
return false;
}
match node.type_id() {
// Step 3.
DoctypeNodeTypeId if !is_equal_doctype(this, node) => return false,
ElementNodeTypeId(..) if !is_equal_element(this, node) => return false,
ProcessingInstructionNodeTypeId if !is_equal_processinginstruction(this, node) => return false,
TextNodeTypeId |
CommentNodeTypeId if !is_equal_characterdata(this, node) => return false,
// Step 4.
ElementNodeTypeId(..) if !is_equal_element_attrs(this, node) => return false,
_ => ()
}
// Step 5.
if this.children().count() != node.children().count() {
return false;
}
// Step 6.
this.children().zip(node.children()).all(|(ref child, ref other_child)| {
is_equal_node(child, other_child)
})
}
match maybe_node {
// Step 1.
None => false,
// Step 2-6.
Some(ref node) => is_equal_node(self, node)
}
}
// http://dom.spec.whatwg.org/#dom-node-comparedocumentposition
fn CompareDocumentPosition(&self, other: &JSRef<Node>) -> u16 {
if self == other {
// step 2.
0
} else {
let mut lastself = self.clone();
let mut lastother = other.clone();
for ancestor in self.ancestors() {
if &ancestor == other {
// step 4.
return NodeConstants::DOCUMENT_POSITION_CONTAINS +
NodeConstants::DOCUMENT_POSITION_PRECEDING;
}
lastself = ancestor.clone();
}
for ancestor in other.ancestors() {
if &ancestor == self {
// step 5.
return NodeConstants::DOCUMENT_POSITION_CONTAINED_BY +
NodeConstants::DOCUMENT_POSITION_FOLLOWING;
}
lastother = ancestor.clone();
}
if lastself != lastother {
let abstract_uint: uintptr_t = as_uintptr(&*self);
let other_uint: uintptr_t = as_uintptr(&*other);
let random = if abstract_uint < other_uint {
NodeConstants::DOCUMENT_POSITION_FOLLOWING
} else {
NodeConstants::DOCUMENT_POSITION_PRECEDING
};
// step 3.
return random +
NodeConstants::DOCUMENT_POSITION_DISCONNECTED +
NodeConstants::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
}
for child in lastself.traverse_preorder() {
if &child == other {
// step 6.
return NodeConstants::DOCUMENT_POSITION_PRECEDING;
}
if &child == self {
// step 7.
return NodeConstants::DOCUMENT_POSITION_FOLLOWING;
}
}
unreachable!()
}
}
// http://dom.spec.whatwg.org/#dom-node-contains
fn Contains(&self, maybe_other: Option<JSRef<Node>>) -> bool {
match maybe_other {
None => false,
Some(ref other) => self.is_inclusive_ancestor_of(other)
}
}
// http://dom.spec.whatwg.org/#dom-node-lookupprefix
fn LookupPrefix(&self, _prefix: Option<DOMString>) -> Option<DOMString> {
// FIXME (#1826) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
fn LookupNamespaceURI(&self, _namespace: Option<DOMString>) -> Option<DOMString> {
// FIXME (#1826) implement.
None
}
// http://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
fn IsDefaultNamespace(&self, _namespace: Option<DOMString>) -> bool {
// FIXME (#1826) implement.
false
}
}
impl Reflectable for Node {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.eventtarget.reflector()
}
}
pub fn document_from_node<T: NodeBase>(derived: &JSRef<T>) -> Temporary<Document> {
let node: &JSRef<Node> = NodeCast::from_ref(derived);
node.owner_doc()
}
pub fn window_from_node<T: NodeBase>(derived: &JSRef<T>) -> Temporary<Window> {
let document = document_from_node(derived).root();
Temporary::new(document.deref().window.clone())
}
impl<'a> VirtualMethods for JSRef<'a, Node> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> {
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(self);
Some(eventtarget as &VirtualMethods+)
}
}
impl<'a> style::TNode<JSRef<'a, Element>> for JSRef<'a, Node> {
fn parent_node(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).parent_node().map(|node| *node.root())
}
fn prev_sibling(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).prev_sibling().map(|node| *node.root())
}
fn next_sibling(&self) -> Option<JSRef<'a, Node>> {
(self as &NodeHelpers).next_sibling().map(|node| *node.root())
}
fn is_document(&self) -> bool {
(self as &NodeHelpers).is_document()
}
fn is_element(&self) -> bool {
(self as &NodeHelpers).is_element()
}
fn as_element(&self) -> JSRef<'a, Element> {
let elem: Option<&JSRef<'a, Element>> = ElementCast::to_ref(self);
assert!(elem.is_some());
*elem.unwrap()
}
fn match_attr(&self, attr: &style::AttrSelector, test: |&str| -> bool) -> bool {
let name = {
let elem: Option<&JSRef<'a, Element>> = ElementCast::to_ref(self);
assert!(elem.is_some());
let elem: &ElementHelpers = elem.unwrap() as &ElementHelpers;
if elem.html_element_in_html_document() {
attr.lower_name.as_slice()
} else {
attr.name.as_slice()
}
};
match attr.namespace {
style::SpecificNamespace(ref ns) => {
self.as_element().get_attribute(ns.clone(), name).root()
.map_or(false, |attr| test(attr.deref().Value().as_slice()))
},
// FIXME: https://github.com/mozilla/servo/issues/1558
style::AnyNamespace => false,
}
}
}
|
use std::io::buffered::BufferedStream;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::vec::bytes::push_bytes;
pub enum Result {
Nil,
Int(int),
Data(~[u8]),
List(~[Result]),
Error(~str),
Status(~str)
}
fn read_char(io: &mut BufferedStream<TcpStream>) -> char {
match io.read_byte() {
Some(ch) => ch as char,
None => fail!()
}
}
fn parse_data(len: uint, io: &mut BufferedStream<TcpStream>) -> Result {
let res =
if (len > 0) {
let bytes = io.read_bytes(len);
assert!(bytes.len() == len);
Data(bytes)
} else {
Data(~[])
};
assert!(io.read_byte() == Some(13));
assert!(io.read_byte() == Some(10));
return res;
}
fn parse_list(len: uint, io: &mut BufferedStream<TcpStream>) -> Result {
List(std::vec::from_fn(len, |_| { parse_response(io) }))
}
fn parse_int_line(io: &mut BufferedStream<TcpStream>) -> int {
let mut i: int = 0;
let mut digits: uint = 0;
let mut negative: bool = false;
loop {
let ch = read_char(io);
match ch {
'0' .. '9' => {
digits += 1;
i = (i * 10) + (ch as int - '0' as int);
},
'-' => {
if negative { fail!() }
negative = true
},
'\r' => {
assert!(read_char(io) == '\n');
break
},
'\n' => break,
_ => fail!()
}
}
if digits == 0 { fail!() }
if negative { -i }
else { i }
}
fn parse_n(io: &mut BufferedStream<TcpStream>, f: |uint, &mut BufferedStream<TcpStream>| -> Result) -> Result {
match parse_int_line(io) {
-1 => Nil,
len if len >= 0 => f(len as uint, io),
_ => fail!()
}
}
fn parse_status(io: &mut BufferedStream<TcpStream>) -> Result {
match io.read_line() {
Some(line) => Status(line),
None => fail!()
}
}
fn parse_error(io: &mut BufferedStream<TcpStream>) -> Result {
match io.read_line() {
Some(line) => Error(line),
None => fail!()
}
}
fn parse_response(io: &mut BufferedStream<TcpStream>) -> Result {
match read_char(io) {
'$' => parse_n(io, parse_data),
'*' => parse_n(io, parse_list),
'+' => parse_status(io),
'-' => parse_error(io),
':' => Int(parse_int_line(io)),
_ => fail!()
}
}
fn prepare_cmd(cmd: ~[~str]) -> ~[u8] {
let mut res: ~[u8] = ~[];
push_bytes(&mut res, bytes!("*"));
push_bytes(&mut res, cmd.len().to_str().into_bytes());
push_bytes(&mut res, bytes!("\r\n"));
for c in cmd.iter() {
push_bytes(&mut res, bytes!("$"));
push_bytes(&mut res, c.len().to_str().into_bytes());
push_bytes(&mut res, bytes!("\r\n"));
push_bytes(&mut res, c.as_bytes());
push_bytes(&mut res, bytes!("\r\n"));
}
res
}
fn send_query(cmd: &[u8], io: &mut BufferedStream<TcpStream>) {
io.write(cmd);
io.flush();
}
fn recv_query(io: &mut BufferedStream<TcpStream>) -> Result {
parse_response(io)
}
fn query(cmd: &[u8], io: &mut BufferedStream<TcpStream>) -> Result {
send_query(cmd, io);
let res = recv_query(io);
res
}
fn main() {
let addr = from_str::<SocketAddr>("127.0.0.1:6379").unwrap();
let tcp_stream = TcpStream::connect(addr).unwrap();
let mut reader = BufferedStream::new(tcp_stream);
let cmd = prepare_cmd(~[~"SET", ~"def", ~"abc"]);
for i in std::iter::range(1, 100_000) {
query(cmd, &mut reader);
}
}
Introduce a CommandWriter
This makes it cleaner to construct Redis commands in memory.
use std::io::buffered::BufferedStream;
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::vec::bytes::push_bytes;
pub enum Result {
Nil,
Int(int),
Data(~[u8]),
List(~[Result]),
Error(~str),
Status(~str)
}
fn read_char(io: &mut BufferedStream<TcpStream>) -> char {
match io.read_byte() {
Some(ch) => ch as char,
None => fail!()
}
}
fn parse_data(len: uint, io: &mut BufferedStream<TcpStream>) -> Result {
let res =
if (len > 0) {
let bytes = io.read_bytes(len);
assert!(bytes.len() == len);
Data(bytes)
} else {
Data(~[])
};
assert!(io.read_byte() == Some(13));
assert!(io.read_byte() == Some(10));
return res;
}
fn parse_list(len: uint, io: &mut BufferedStream<TcpStream>) -> Result {
List(std::vec::from_fn(len, |_| { parse_response(io) }))
}
fn parse_int_line(io: &mut BufferedStream<TcpStream>) -> int {
let mut i: int = 0;
let mut digits: uint = 0;
let mut negative: bool = false;
loop {
let ch = read_char(io);
match ch {
'0' .. '9' => {
digits += 1;
i = (i * 10) + (ch as int - '0' as int);
},
'-' => {
if negative { fail!() }
negative = true
},
'\r' => {
assert!(read_char(io) == '\n');
break
},
'\n' => break,
_ => fail!()
}
}
if digits == 0 { fail!() }
if negative { -i }
else { i }
}
fn parse_n(io: &mut BufferedStream<TcpStream>, f: |uint, &mut BufferedStream<TcpStream>| -> Result) -> Result {
match parse_int_line(io) {
-1 => Nil,
len if len >= 0 => f(len as uint, io),
_ => fail!()
}
}
fn parse_status(io: &mut BufferedStream<TcpStream>) -> Result {
match io.read_line() {
Some(line) => Status(line),
None => fail!()
}
}
fn parse_error(io: &mut BufferedStream<TcpStream>) -> Result {
match io.read_line() {
Some(line) => Error(line),
None => fail!()
}
}
fn parse_response(io: &mut BufferedStream<TcpStream>) -> Result {
match read_char(io) {
'$' => parse_n(io, parse_data),
'*' => parse_n(io, parse_list),
'+' => parse_status(io),
'-' => parse_error(io),
':' => Int(parse_int_line(io)),
_ => fail!()
}
}
struct CommandWriter {
buf: ~[u8]
}
impl CommandWriter {
fn new() -> CommandWriter {
CommandWriter { buf: ~[] }
}
fn args(&mut self, n: uint) {
self.write_char('*');
self.write_uint(n);
self.write_crnl();
}
fn arg(&mut self, arg: &str) {
self.write_char('$');
self.write_uint(arg.len());
self.write_crnl();
self.write_str(arg);
self.write_crnl();
}
fn write_crnl(&mut self) {
self.write_byte(13);
self.write_byte(10);
}
fn write_uint(&mut self, n: uint) {
if n < 10 {
self.write_byte('0' as u8 + (n as u8));
}
else {
push_bytes(&mut self.buf, n.to_str().into_bytes());
}
}
fn write_str(&mut self, s: &str) {
push_bytes(&mut self.buf, s.as_bytes());
}
fn write_char(&mut self, s: char) {
self.buf.push(s as u8);
}
fn write_byte(&mut self, b: u8) {
self.buf.push(b);
}
fn with_buf<T>(&self, f: |&[u8]| -> T) -> T {
f(self.buf.as_slice())
}
}
fn execute(cmd: &[u8], io: &mut BufferedStream<TcpStream>) -> Result {
io.write(cmd);
io.flush();
parse_response(io)
}
pub struct Redis<'a> {
priv io: &'a mut BufferedStream<TcpStream>
}
impl<'a> Redis<'a> {
pub fn get(&mut self, key: &str) -> Result {
let mut cwr = CommandWriter::new();
cwr.args(2);
cwr.arg("GET");
cwr.arg(key);
cwr.with_buf(|cmd| execute(cmd, self.io))
}
pub fn set(&mut self, key: &str, val: &str) -> Result {
let mut cwr = CommandWriter::new();
cwr.args(3);
cwr.arg("SET");
cwr.arg(key);
cwr.arg(val);
cwr.with_buf(|cmd| execute(cmd, self.io))
}
}
fn main() {
let addr = from_str::<SocketAddr>("127.0.0.1:6379").unwrap();
let tcp_stream = TcpStream::connect(addr).unwrap();
let mut reader = BufferedStream::new(tcp_stream);
let mut redis = Redis { io: &mut reader };
//let x = redis.get("key");
//println!("{:?}", x);
for i in std::iter::range(1, 100_000) {
redis.set("key", "abc");
}
}
|
/*
* Copyright 2019 Jeehoon Kang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::ops::Deref;
use core::ptr;
use core::sync::atomic::Ordering;
use crate::abi::*;
use crate::addr::*;
use crate::arch::*;
use crate::cpu::*;
use crate::mm::*;
use crate::mpool::*;
use crate::page::*;
use crate::spci::*;
use crate::spinlock::*;
use crate::std::*;
use crate::types::*;
use crate::utils::*;
use crate::vm::*;
// To eliminate the risk of deadlocks, we define a partial order for the acquisition of locks held
// concurrently by the same physical CPU. Our current ordering requirements are as follows:
//
// vcpu::execution_lock -> vm::lock -> vcpu::interrupts_lock -> mm_stage1_lock -> dlog sl
//
// Locks of the same kind require the lock of lowest address to be locked first, see
// `sl_lock_both()`.
// Currently, a page is mapped for the send and receive buffers so the maximum request is the size
// of a page.
const_assert_eq!(hf_mailbox_size; HF_MAILBOX_SIZE, PAGE_SIZE);
/// A global page pool for sharing memories. Its mutability is needed only for
/// initialization.
static mut API_PAGE_POOL: MaybeUninit<MPool> = MaybeUninit::uninit();
/// Initialises the API page pool by taking ownership of the contents of the
/// given page pool.
/// TODO(HfO2): The ownership of `ppool` is actually moved from `one_time_init`
/// to here. Refactor this function like `Api::new(ppool: MPool) -> Api`. (#31)
#[no_mangle]
pub unsafe extern "C" fn api_init(ppool: *const MPool) {
API_PAGE_POOL = MaybeUninit::new(MPool::new_from(&*ppool));
}
/// Switches the physical CPU back to the corresponding vcpu of the primary VM.
///
/// This triggers the scheduling logic to run. Run in the context of secondary
/// VM to cause HF_VCPU_RUN to return and the primary VM to regain control of
/// the cpu.
unsafe fn switch_to_primary(
current: &mut VCpuExecutionLocked,
mut primary_ret: HfVCpuRunReturn,
secondary_state: VCpuStatus,
) -> *mut VCpu {
let primary = vm_find(HF_PRIMARY_VM_ID);
let next = vm_get_vcpu(
primary,
cpu_index(current.get_inner().cpu) as spci_vcpu_index_t,
);
// If the secondary is blocked but has a timer running, sleep until the
// timer fires rather than indefinitely.
match &mut primary_ret {
HfVCpuRunReturn::WaitForInterrupt { ns } | HfVCpuRunReturn::WaitForMessage { ns } => {
*ns = if arch_timer_enabled_current() {
arch_timer_remaining_ns_current()
} else {
HF_SLEEP_INDEFINITE
};
}
_ => {}
}
// Set the return value for the primary VM's call to HF_VCPU_RUN.
//
// The use of `get_mut_unchecked()` is safe because the currently running pCPU implicitly owns
// `next`. Notice that `next` is the vCPU of the primary VM that corresponds to the currently
// running pCPU.
(*next)
.inner
.get_mut_unchecked()
.regs
.set_retval(primary_ret.into_raw());
// Mark the current vcpu as waiting.
current.get_inner_mut().state = secondary_state;
next
}
/// Returns to the primary vm and signals that the vcpu still has work to do so.
#[no_mangle]
pub unsafe extern "C" fn api_preempt(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::Preempted;
switch_to_primary(&mut current, ret, VCpuStatus::Ready)
}
/// Puts the current vcpu in wait for interrupt mode, and returns to the primary
/// vm.
#[no_mangle]
pub unsafe extern "C" fn api_wait_for_interrupt(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::WaitForInterrupt {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
};
switch_to_primary(&mut current, ret, VCpuStatus::BlockedInterrupt)
}
/// Puts the current vCPU in off mode, and returns to the primary VM.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_off(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::WaitForInterrupt {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
};
// Disable the timer, so the scheduler doesn't get told to call back
// based on it.
arch_timer_disable_current();
switch_to_primary(&mut current, ret, VCpuStatus::Off)
}
/// Returns to the primary vm to allow this cpu to be used for other tasks as
/// the vcpu does not have work to do at this moment. The current vcpu is masked
/// as ready to be scheduled again. This SPCI function always returns
/// SpciReturn::Success.
#[no_mangle]
pub unsafe extern "C" fn api_spci_yield(current: *mut VCpu, next: *mut *mut VCpu) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::Yield;
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// Noop on the primary as it makes the scheduling decisions.
return SpciReturn::Success;
}
*next = switch_to_primary(&mut current, ret, VCpuStatus::Ready);
// SPCI_YIELD always returns SPCI_SUCCESS.
SpciReturn::Success
}
unsafe fn wake_up(current: &mut VCpuExecutionLocked, target_vcpu: &VCpu) -> *mut VCpu {
let ret = HfVCpuRunReturn::WakeUp {
vm_id: (*target_vcpu.vm).id,
vcpu: vcpu_index(target_vcpu),
};
switch_to_primary(current, ret, VCpuStatus::Ready)
}
/// Switches to the primary so that it can switch to the target, or kick tit if
/// it is already running on a different physical CPU.
#[no_mangle]
pub unsafe extern "C" fn api_wake_up(current: *mut VCpu, target_vcpu: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
wake_up(&mut current, &*target_vcpu)
}
/// Aborts the vCPU and triggers its VM to abort fully.
#[no_mangle]
pub unsafe extern "C" fn api_abort(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::Aborted;
dlog!(
"Aborting VM {} vCPU {}\n",
(*current.get_vcpu().vm).id,
vcpu_index(current.get_vcpu())
);
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// TODO: what to do when the primary aborts?
spin_loop();
}
(*current.get_vcpu().vm)
.aborting
.store(true, Ordering::Relaxed);
// TODO: free resources once all vCPUs abort.
switch_to_primary(&mut current, ret, VCpuStatus::Aborted)
}
/// Returns the ID of the VM.
#[no_mangle]
pub unsafe extern "C" fn api_vm_get_id(current: *const VCpu) -> spci_vm_id_t {
(*(*current).vm).id
}
/// Returns the number of VMs configured to run.
#[no_mangle]
pub unsafe extern "C" fn api_vm_get_count() -> spci_vm_count_t {
vm_get_count()
}
/// Returns the number of vCPUs configured in the given VM, or 0 if there is no
/// such VM or the caller is not the primary VM.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_get_count(
vm_id: spci_vm_id_t,
current: *const VCpu,
) -> spci_vcpu_count_t {
let vm;
// Only the primary VM needs to know about vcpus for scheduling.
if (*(*current).vm).id != HF_PRIMARY_VM_ID {
return 0;
}
vm = vm_find(vm_id);
if vm.is_null() {
return 0;
}
(*vm).vcpu_count
}
/// This function is called by the architecture-specific context switching
/// function to indicate that register state for the given vcpu has been saved
/// and can therefore be used by other pcpus.
#[no_mangle]
pub unsafe extern "C" fn api_regs_state_saved(vcpu: *mut VCpu) {
(*vcpu).inner.unlock_unchecked();
}
/// Assuming that the arguments have already been checked by the caller, injects
/// a virtual interrupt of the given ID into the given target vCPU. This doesn't
/// cause the vCPU to actually be run immediately; it will be taken when the
/// vCPU is next run, which is up to the scheduler.
///
/// Returns:
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick the target vCPU.
/// TODO: this function was using `goto` originally and it is just
/// implemented as copy-paste in Rust.
unsafe fn internal_interrupt_inject(
target_vcpu: &VCpu,
intid: intid_t,
current: &mut VCpuExecutionLocked,
next: *mut *mut VCpu,
) -> i64 {
if target_vcpu.interrupts.lock().inject(intid).is_ok() {
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// If the call came from the primary VM, let it know that it should
// run or kick the target vCPU.
return 1;
} else if current.get_vcpu() as *const _ != target_vcpu as *const _ && !next.is_null() {
*next = wake_up(current, target_vcpu);
}
}
0
}
/// Prepares the vcpu to run by updating its state and fetching whether a return
/// value needs to be forced onto the vCPU.
///
/// Returns:
/// - false if it fails to prepare `vcpu` to run.
/// - true if it succeeds to prepare `vcpu` to run. In this case,
/// `vcpu.execution_lock` has acquired.
unsafe fn vcpu_prepare_run(
current: &VCpuExecutionLocked,
vcpu: *mut VCpu,
run_ret: HfVCpuRunReturn,
) -> Result<VCpuExecutionLocked, HfVCpuRunReturn> {
let mut vcpu_inner = (*vcpu).inner.try_lock().map_err(|_| {
// vCPU is running or prepared to run on another pCPU.
//
// It's ok not to return the sleep duration here because the other
// physical CPU that is currently running this vCPU will return the
// sleep duration if needed. The default return value is
// HfVCpuRunReturn::WaitForInterrupt, so no need to set it
// explicitly.
run_ret
})?;
if (*(*vcpu).vm).aborting.load(Ordering::Relaxed) {
if vcpu_inner.state != VCpuStatus::Aborted {
dlog!(
"Aborting VM {} vCPU {}\n",
(*(*vcpu).vm).id,
vcpu_index(vcpu)
);
vcpu_inner.state = VCpuStatus::Aborted;
}
return Err(run_ret);
}
match vcpu_inner.state {
VCpuStatus::Off | VCpuStatus::Aborted => {
return Err(run_ret);
}
// A pending message allows the vCPU to run so the message can be
// delivered directly.
// The VM needs to be locked to deliver mailbox messages.
// The VM lock is not needed in the common case so it must only be taken
// when it is going to be needed. This ensures there are no inter-vCPU
// dependencies in the common run case meaning the sensitive context
// switch performance is consistent.
VCpuStatus::BlockedMailbox if (*(*vcpu).vm).inner.lock().try_read().is_ok() => {
vcpu_inner.regs.set_retval(SpciReturn::Success as uintreg_t);
}
// Allow virtual interrupts to be delivered.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt
if (*vcpu).interrupts.lock().is_interrupted() =>
{
// break;
}
// The timer expired so allow the interrupt to be delivered.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt
if vcpu_inner.regs.timer_pending() =>
{
// break;
}
// The vCPU is not ready to run, return the appropriate code to the
// primary which called vcpu_run.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt => {
let run_ret = if !vcpu_inner.regs.timer_enabled() {
run_ret
} else {
let ns = vcpu_inner.regs.timer_remaining_ns();
if vcpu_inner.state == VCpuStatus::BlockedMailbox {
HfVCpuRunReturn::WaitForMessage { ns }
} else {
HfVCpuRunReturn::WaitForInterrupt { ns }
}
};
return Err(run_ret);
}
VCpuStatus::Ready => {
// break;
}
}
// It has been decided that the vCPU should be run.
vcpu_inner.cpu = current.get_inner().cpu;
// We want to keep the lock of vcpu.state because we're going to run.
mem::forget(vcpu_inner);
Ok(VCpuExecutionLocked::from_raw(vcpu))
}
/// Runs the given vcpu of the given vm.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_run(
vm_id: spci_vm_id_t,
vcpu_idx: spci_vcpu_index_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> u64 {
let current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::WaitForInterrupt {
ns: HF_SLEEP_INDEFINITE,
};
// Only the primary VM can switch vcpus.
if (*current.get_vcpu().vm).id != HF_PRIMARY_VM_ID {
return ret.into_raw();
}
// Only the secondary VM vcpus can be run.
if vm_id == HF_PRIMARY_VM_ID {
return ret.into_raw();
}
// The requested VM must exist.
let vm = vm_find(vm_id);
if vm.is_null() {
return ret.into_raw();
}
// The requested vcpu must exist.
if vcpu_idx >= (*vm).vcpu_count {
return ret.into_raw();
}
// Update state if allowed.
let vcpu = vm_get_vcpu(vm, vcpu_idx);
let mut vcpu_locked = match vcpu_prepare_run(¤t, vcpu, ret) {
Ok(locked) => locked,
Err(ret) => return ret.into_raw(),
};
// Inject timer interrupt if timer has expired. It's safe to access
// vcpu->regs here because vcpu_prepare_run already made sure that
// regs_available was true (and then set it to false) before returning
// true.
if vcpu_locked.get_inner().regs.timer_pending() {
// Make virtual timer interrupt pending.
internal_interrupt_inject(
&*vcpu,
HF_VIRTUAL_TIMER_INTID,
&mut vcpu_locked,
ptr::null_mut(),
);
// Set the mask bit so the hardware interrupt doesn't fire again.
// Ideally we wouldn't do this because it affects what the secondary
// vcPU sees, but if we don't then we end up with a loop of the
// interrupt firing each time we try to return to the secondary vCPU.
vcpu_locked.get_inner_mut().regs.timer_mask();
}
// Switch to the vcpu.
*next = vcpu_locked.into_raw() as *const _ as *mut _;
// Set a placeholder return code to the scheduler. This will be overwritten
// when the switch back to the primary occurs.
HfVCpuRunReturn::Preempted.into_raw()
}
/// Determines the value to be returned by api_vm_configure and
/// api_mailbox_clear after they've succeeded. If a secondary VM is running and
/// there are waiters, it also switches back to the primary VM for it to wake
/// waiters up.
unsafe fn waiter_result(
vm_id: spci_vm_id_t,
vm_inner: &VmInner,
current: &mut VCpuExecutionLocked,
next: *mut *mut VCpu,
) -> i64 {
let ret = HfVCpuRunReturn::NotifyWaiters;
if vm_inner.is_waiter_list_empty() {
// No waiters, nothing else to do.
return 0;
}
if vm_id == HF_PRIMARY_VM_ID {
// The caller is the primary VM. Tell it to wake up waiters.
return 1;
}
// Switch back to the primary VM, informing it that there are waiters
// that need to be notified.
*next = switch_to_primary(current, ret, VCpuStatus::Ready);
0
}
/// Configures the VM to send/receive data through the specified pages. The
/// pages must not be shared.
///
/// Returns:
/// - -1 on failure.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick waiters. Waiters should be retrieved by calling
/// hf_mailbox_waiter_get.
#[no_mangle]
pub unsafe extern "C" fn api_vm_configure(
send: ipaddr_t,
recv: ipaddr_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = current.get_vcpu().vm;
// The hypervisor's memory map must be locked for the duration of this
// operation to ensure there will be sufficient memory to recover from
// any failures.
//
// TODO: the scope of the can be reduced but will require restructing
// to keep a single unlock point.
let mut vm_inner = (*vm).inner.lock();
if vm_inner
.configure(send, recv, API_PAGE_POOL.get_ref())
.is_err()
{
return -1;
}
// Tell caller about waiters, if any.
waiter_result((*vm).id, &vm_inner, &mut current, next)
}
/// Copies data from the sender's send buffer to the recipient's receive buffer
/// and notifies the recipient.
///
/// If the recipient's receive buffer is busy, it can optionally register the
/// caller to be notified when the recipient's receive buffer becomes available.
#[no_mangle]
pub unsafe extern "C" fn api_spci_msg_send(
attributes: SpciMsgSendAttributes,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let from = current.get_vcpu().vm;
// TODO: Refactor the control flow of this function, and make this variable
// immutable.
let mut ret;
let notify = attributes.contains(SpciMsgSendAttributes::NOTIFY);
// Check that the sender has configured its send buffer. Copy the message
// header. If the tx mailbox at from_msg is configured (i.e.
// from_msg != ptr::null()) then it can be safely accessed after releasing
// the lock since the tx mailbox address can only be configured once.
let from_msg = (*from).inner.lock().get_send_ptr();
if from_msg.is_null() {
return SpciReturn::InvalidParameters;
}
// Note that the payload is not copied when the message header is.
let mut from_msg_replica = ptr::read(from_msg);
// Ensure source VM id corresponds to the current VM.
if from_msg_replica.source_vm_id != (*from).id {
return SpciReturn::InvalidParameters;
}
let size = from_msg_replica.length as usize;
// Limit the size of transfer.
if size > SPCI_MSG_PAYLOAD_MAX {
return SpciReturn::InvalidParameters;
}
// Disallow reflexive requests as this suggests an error in the VM.
if from_msg_replica.target_vm_id == (*from).id {
return SpciReturn::InvalidParameters;
}
// Ensure the target VM exists.
let to = vm_find(from_msg_replica.target_vm_id);
if to.is_null() {
return SpciReturn::InvalidParameters;
}
// Hf needs to hold the lock on `to` before the mailbox state is checked.
// The lock on `to` must be held until the information is copied to `to` Rx
// buffer. Since in spci_msg_handle_architected_message we may call
// api_spci_share_memory which must hold the `from` lock, we must hold the
// `from` lock at this point to prevent a deadlock scenario.
let (mut to_inner, mut from_inner) = SpinLock::lock_both(&(*to).inner, &(*from).inner);
if !to_inner.is_empty() || !to_inner.is_configured() {
// Fail if the target isn't currently ready to receive data,
// setting up for notification if requested.
if notify {
let _ = from_inner.wait(&mut to_inner, (*to).id);
}
return SpciReturn::Busy;
}
let to_msg = to_inner.get_recv_ptr();
// Handle architected messages.
if !from_msg_replica.flags.contains(SpciMessageFlags::IMPDEF) {
// Buffer holding the internal copy of the shared memory regions.
// TODO: Buffer is temporarily in the stack.
let mut message_buffer: [u8; mem::size_of::<SpciArchitectedMessageHeader>()
+ mem::size_of::<SpciMemoryRegionConstituent>()
+ mem::size_of::<SpciMemoryRegion>()] = MaybeUninit::uninit().assume_init();
let architected_header = spci_get_architected_message_header(from_msg);
if from_msg_replica.length as usize > message_buffer.len() {
return SpciReturn::InvalidParameters;
}
if (from_msg_replica.length as usize) < mem::size_of::<SpciArchitectedMessageHeader>() {
return SpciReturn::InvalidParameters;
}
// Copy the architected message into an internal buffer.
memcpy_s(
message_buffer.as_mut_ptr() as _,
message_buffer.len(),
architected_header as _,
from_msg_replica.length as usize,
);
let architected_message_replica: *mut SpciArchitectedMessageHeader =
message_buffer.as_mut_ptr() as usize as *mut _;
// Note that message_buffer is passed as the third parameter to
// spci_msg_handle_architected_message. The execution flow commencing
// at spci_msg_handle_architected_message will make several accesses to
// fields in message_buffer. The memory area message_buffer must be
// exclusively owned by Hf so that TOCTOU issues do not arise.
// TODO(HfO2): This code looks unsafe. Port spci_architected_message.c
// and avoid creating VmLocked manually.
ret = spci_msg_handle_architected_message(
VmLocked::from_raw(to),
VmLocked::from_raw(from),
architected_message_replica,
&mut from_msg_replica,
to_msg,
);
if ret != SpciReturn::Success {
return ret;
}
} else {
// Copy data.
memcpy_s(
&mut (*to_msg).payload as *mut _ as usize as _,
SPCI_MSG_PAYLOAD_MAX,
// HfO2: below was &(*(*from).mailbox.send).payload, but we can
// safely assume it is equal to &(*from_msg).payload, even though
// from_msg was defined before entering critical section. That's
// because we do not allow vm to be configured more than once.
&(*from_msg).payload as *const _ as usize as _,
size,
);
*to_msg = from_msg_replica;
}
let primary_ret = HfVCpuRunReturn::Message { vm_id: (*to).id };
ret = SpciReturn::Success;
// Messages for the primary VM are delivered directly.
if (*to).id == HF_PRIMARY_VM_ID {
to_inner.set_read();
*next = switch_to_primary(&mut current, primary_ret, VCpuStatus::Ready);
return ret;
}
to_inner.set_received();
// Return to the primary VM directly or with a switch.
if (*from).id != HF_PRIMARY_VM_ID {
*next = switch_to_primary(&mut current, primary_ret, VCpuStatus::Ready);
}
ret
}
/// Receives a message from the mailbox. If one isn't available, this function
/// can optionally block the caller until one becomes available.
///
/// No new messages can be received until the mailbox has been cleared.
#[no_mangle]
pub unsafe extern "C" fn api_spci_msg_recv(
attributes: SpciMsgRecvAttributes,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = &*current.get_vcpu().vm;
let return_code: SpciReturn;
let block = attributes.contains(SpciMsgRecvAttributes::BLOCK);
// The primary VM will receive messages as a status code from running vcpus
// and must not call this function.
if vm.id == HF_PRIMARY_VM_ID {
return SpciReturn::Interrupted;
}
let mut vm_inner = vm.inner.lock();
// Return pending messages without blocking.
if vm_inner.try_read().is_ok() {
return SpciReturn::Success;
}
// No pending message so fail if not allowed to block.
if !block {
return SpciReturn::Retry;
}
// From this point onward this call can only be interrupted or a message
// received. If a message is received the return value will be set at that
// time to SPCI_SUCCESS.
return_code = SpciReturn::Interrupted;
// Don't block if there are enabled and pending interrupts, to match
// behaviour of wait_for_interrupt.
if current.get_vcpu().interrupts.lock().is_interrupted() {
return return_code;
}
// Switch back to primary vm to block.
{
let run_return = HfVCpuRunReturn::WaitForMessage {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
};
*next = switch_to_primary(&mut current, run_return, VCpuStatus::BlockedMailbox);
}
return_code
}
/// Retrieves the next VM whose mailbox became writable. For a VM to be notified
/// by this function, the caller must have called api_mailbox_send before with
/// the notify argument set to true, and this call must have failed because the
/// mailbox was not available.
///
/// It should be called repeatedly to retrieve a list of VMs.
///
/// Returns -1 if no VM became writable, or the id of the VM whose mailbox
/// became writable.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_writable_get(current: *const VCpu) -> i64 {
let vm = (*current).vm;
let mut vm_inner = (*vm).inner.lock();
match vm_inner.dequeue_ready_list() {
Some(id) => i64::from(id),
None => -1,
}
}
/// Retrieves the next VM waiting to be notified that the mailbox of the
/// specified VM became writable. Only primary VMs are allowed to call this.
///
/// Returns -1 on failure or if there are no waiters; the VM id of the next
/// waiter otherwise.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_waiter_get(vm_id: spci_vm_id_t, current: *const VCpu) -> i64 {
// Only primary VMs are allowed to call this function.
if (*(*current).vm).id != HF_PRIMARY_VM_ID {
return -1;
}
let vm = vm_find(vm_id);
if vm.is_null() {
return -1;
}
// Check if there are outstanding notifications from given vm.
let entry = (*vm).inner.lock().fetch_waiter();
if entry.is_null() {
return -1;
}
// Enqueue notification to waiting VM.
let waiting_vm = (*entry).waiting_vm;
let mut vm_inner = (*waiting_vm).inner.lock();
if !(*entry).is_in_ready_list() {
vm_inner.enqueue_ready_list(&mut *entry);
}
i64::from((*waiting_vm).id)
}
/// Clears the caller's mailbox so that a new message can be received. The
/// caller must have copied out all data they wish to preserve as new messages
/// will overwrite the old and will arrive asynchronously.
///
/// Returns:
/// - -1 on failure, if the mailbox hasn't been read.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick waiters. Waiters should be retrieved by calling
/// hf_mailbox_waiter_get.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_clear(current: *mut VCpu, next: *mut *mut VCpu) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = current.get_vcpu().vm;
let ret;
let mut vm_inner = (*vm).inner.lock();
match vm_inner.get_state() {
MailboxState::Empty => {
ret = 0;
}
MailboxState::Received => {
ret = -1;
}
MailboxState::Read => {
ret = waiter_result((*vm).id, &vm_inner, &mut current, next);
vm_inner.set_empty();
}
}
ret
}
/// Enables or disables a given interrupt ID for the calling vCPU.
///
/// Returns 0 on success, or -1 if the intid is invalid.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_enable(
intid: intid_t,
enable: bool,
current: *mut VCpu,
) -> i64 {
if (*current).interrupts.lock().enable(intid, enable).is_ok() {
0
} else {
-1
}
}
/// Returns the ID of the next pending interrupt for the calling vCPU, and
/// acknowledges it (i.e. marks it as no longer pending). Returns
/// HF_INVALID_INTID if there are no pending interrupts.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_get(current: *mut VCpu) -> intid_t {
(*current).interrupts.lock().get()
}
/// Returns whether the current vCPU is allowed to inject an interrupt into the
/// given VM and vCPU.
#[inline]
fn is_injection_allowed(target_vm_id: spci_vm_id_t, current: &VCpu) -> bool {
let current_vm_id = unsafe { (*current.vm).id };
// The primary VM is allowed to inject interrupts into any VM. Secondary
// VMs are only allowed to inject interrupts into their own vCPUs.
current_vm_id == HF_PRIMARY_VM_ID || current_vm_id == target_vm_id
}
/// Injects a virtual interrupt of the given ID into the given target vCPU.
/// This doesn't cause the vCPU to actually be run immediately; it will be taken
/// when the vCPU is next run, which is up to the scheduler.
///
/// Returns:
/// - -1 on failure because the target VM or vCPU doesn't exist, the interrupt
/// ID is invalid, or the current VM is not allowed to inject interrupts to
/// the target VM.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick the target vCPU.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_inject(
target_vm_id: spci_vm_id_t,
target_vcpu_idx: spci_vcpu_index_t,
intid: intid_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let target_vm = vm_find(target_vm_id);
if intid >= HF_NUM_INTIDS {
return -1;
}
if target_vm.is_null() {
return -1;
}
if target_vcpu_idx >= (*target_vm).vcpu_count {
// The requested vcpu must exist.
return -1;
}
if !is_injection_allowed(target_vm_id, current.get_vcpu()) {
return -1;
}
let target_vcpu = vm_get_vcpu(target_vm, target_vcpu_idx);
dlog!(
"Injecting IRQ {} for VM {} VCPU {} from VM {} VCPU {}\n",
intid,
target_vm_id,
target_vcpu_idx,
(*current.get_vcpu().vm).id,
(*current.get_inner().cpu).id
);
internal_interrupt_inject(&*target_vcpu, intid, &mut current, next)
}
/// Clears a region of physical memory by overwriting it with zeros. The data is
/// flushed from the cache so the memory has been cleared across the system.
fn clear_memory(begin: paddr_t, end: paddr_t, ppool: &MPool) -> Result<(), ()> {
let mut hypervisor_ptable = HYPERVISOR_PAGE_TABLE.lock();
let size = pa_difference(begin, end);
let region = pa_addr(begin);
// TODO: change this to a cpu local single page window rather than a global
// mapping of the whole range. Such an approach will limit the
// changes to stage-1 tables and will allow only local invalidation.
if hypervisor_ptable
.identity_map(begin, end, Mode::W, ppool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
hypervisor_ptable.defrag(ppool);
return Err(());
}
unsafe {
memset_s(region as usize as _, size, 0, size);
arch_mm_write_back_dcache(region as usize, size);
}
hypervisor_ptable.unmap(begin, end, ppool).unwrap();
Ok(())
}
// TODO: Move function to spci_architectted_message.c. (How in Rust?)
/// Shares memory from the calling VM with another. The memory can be shared in
/// different modes.
///
/// This function requires the calling context to hold the <to> and <from>
/// locks.
///
/// Returns:
/// In case of error one of the following values is returned:
/// 1) SPCI_INVALID_PARAMETERS - The endpoint provided parameters were
/// erroneous;
/// 2) SPCI_NO_MEMORY - Hf did not have sufficient memory to complete
/// the request.
/// Success is indicated by SPCI_SUCCESS.
#[no_mangle]
pub unsafe extern "C" fn api_spci_share_memory(
to_locked: VmLocked,
from_locked: VmLocked,
memory_region: *mut SpciMemoryRegion,
memory_to_attributes: u32,
share: usize,
) -> SpciReturn {
let to_inner = to_locked.inner.get_mut_unchecked();
let from_inner = from_locked.inner.get_mut_unchecked();
// Disallow reflexive shares as this suggests an error in the VM.
if to_locked == from_locked {
return SpciReturn::InvalidParameters;
}
// Create a local pool so any freed memory can't be used by another thread.
// This is to ensure the original mapping can be restored if any stage of
// the process fails.
let local_page_pool: MPool = MPool::new_with_fallback(API_PAGE_POOL.get_ref());
// Obtain the single contiguous set of pages from the memory_region.
// TODO: Add support for multiple constituent regions.
let constituent =
&(*memory_region).constituents as *const _ as usize as *const SpciMemoryRegionConstituent;
let size = (*constituent).page_count as usize * PAGE_SIZE;
let begin = ipa_init((*constituent).address as usize);
let end = ipa_add(begin, size as usize);
// Check if the state transition is lawful for both VMs involved in the
// memory exchange, ensure that all constituents of a memory region being
// shared are at the same state.
let mut orig_from_mode = MaybeUninit::uninit();
let mut from_mode = MaybeUninit::uninit();
let mut to_mode = MaybeUninit::uninit();
let share = match share {
0x2 => SpciMemoryShare::Donate,
_ => return SpciReturn::InvalidParameters,
};
if !spci_msg_check_transition(
to_locked.deref(),
from_locked.deref(),
share,
orig_from_mode.get_mut(),
begin,
end,
memory_to_attributes,
from_mode.get_mut(),
to_mode.get_mut(),
) {
return SpciReturn::InvalidParameters;
}
let pa_begin = pa_from_ipa(begin);
let pa_end = pa_from_ipa(end);
// First update the mapping for the sender so there is not overlap with the
// recipient.
if from_inner
.ptable
.identity_map(pa_begin, pa_end, from_mode.assume_init(), &local_page_pool)
.is_err()
{
return SpciReturn::NoMemory;
}
// Complete the transfer by mapping the memory into the recipient.
if to_inner
.ptable
.identity_map(pa_begin, pa_end, to_mode.assume_init(), &local_page_pool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
from_inner.ptable.defrag(&local_page_pool);
assert!(from_inner
.ptable
.identity_map(
pa_begin,
pa_end,
orig_from_mode.assume_init(),
&local_page_pool
)
.is_err());
return SpciReturn::NoMemory;
}
SpciReturn::Success
}
/// Shares memory from the calling VM with another. The memory can be shared in
/// different modes.
///
/// TODO: the interface for sharing memory will need to be enhanced to allow
/// sharing with different modes e.g. read-only, informing the recipient
/// of the memory they have been given, opting to not wipe the memory and
/// possibly allowing multiple blocks to be transferred. What this will
/// look like is TBD.
fn share_memory(
vm_id: spci_vm_id_t,
addr: ipaddr_t,
size: usize,
share: HfShare,
current: &VCpu,
) -> Result<(), ()> {
let from: &Vm = unsafe { &*current.vm };
// Disallow reflexive shares as this suggests an error in the VM.
if vm_id == from.id {
return Err(());
}
// Ensure the target VM exists.
let to = unsafe { vm_find(vm_id) };
if to.is_null() {
return Err(());
}
let to = unsafe { &*to };
let begin = addr;
let end = ipa_add(addr, size);
// Fail if addresses are not page-aligned.
if !is_aligned(ipa_addr(begin), PAGE_SIZE) || !is_aligned(ipa_addr(end), PAGE_SIZE) {
return Err(());
}
let (from_mode, to_mode) = match share {
HfShare::Give => (
(Mode::INVALID | Mode::UNOWNED),
(Mode::R | Mode::W | Mode::X),
),
HfShare::Lend => (Mode::INVALID, (Mode::R | Mode::W | Mode::X | Mode::UNOWNED)),
HfShare::Share => (
(Mode::R | Mode::W | Mode::X | Mode::SHARED),
(Mode::R | Mode::W | Mode::X | Mode::UNOWNED | Mode::SHARED),
),
};
// Create a local pool so any freed memory can't be used by another thread.
// This is to ensure the original mapping can be restored if any stage of
// the process fails.
// TODO: So that's reason why Hafnium use local_page_pool! We need to verify
// this.
let local_page_pool = MPool::new_with_fallback(unsafe { API_PAGE_POOL.get_ref() });
let (mut from_inner, mut to_inner) = SpinLock::lock_both(&(*from).inner, &(*to).inner);
// Ensure that the memory range is mapped with the same mode so that
// changes can be reverted if the process fails.
// Also ensure the memory range is valid for the sender. If it isn't, the
// sender has either shared it with another VM already or has no claim to
// the memory.
let orig_from_mode = from_inner.ptable.get_mode(begin, end)?;
if orig_from_mode.contains(Mode::INVALID) {
return Err(());
}
// The sender must own the memory and have exclusive access to it in order
// to share it. Alternatively, it is giving memory back to the owning VM.
if orig_from_mode.contains(Mode::UNOWNED) {
let to_mode = to_inner.ptable.get_mode(begin, end)?;
if to_mode.contains(Mode::UNOWNED) {
return Err(());
}
if share != HfShare::Give {
return Err(());
}
} else if orig_from_mode.contains(Mode::SHARED) {
return Err(());
}
let pa_begin = pa_from_ipa(begin);
let pa_end = pa_from_ipa(end);
// First update the mapping for the sender so there is not overlap with the
// recipient.
from_inner
.ptable
.identity_map(pa_begin, pa_end, from_mode, &local_page_pool)?;
// Clear the memory so no VM or device can see the previous contents.
if clear_memory(pa_begin, pa_end, &local_page_pool).is_err() {
assert!(from_inner
.ptable
.identity_map(pa_begin, pa_end, orig_from_mode, &local_page_pool)
.is_ok());
return Err(());
}
// Complete the transfer by mapping the memory into the recipient.
if to_inner
.ptable
.identity_map(pa_begin, pa_end, to_mode, &local_page_pool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
from_inner.ptable.defrag(&local_page_pool);
// goto fail_return_to_sender;
assert!(from_inner
.ptable
.identity_map(pa_begin, pa_end, orig_from_mode, &local_page_pool)
.is_ok());
return Err(());
}
Ok(())
}
#[no_mangle]
pub unsafe extern "C" fn api_share_memory(
vm_id: spci_vm_id_t,
addr: ipaddr_t,
size: size_t,
share: usize,
current: *const VCpu,
) -> i64 {
// Convert the sharing request to memory management modes.
let share = match share {
0 => HfShare::Give,
1 => HfShare::Lend,
2 => HfShare::Share,
_ => {
// The input is untrusted so might not be a valid value.
return -1;
}
};
match share_memory(vm_id, addr, size, share, &*current) {
Ok(_) => 0,
Err(_) => -1,
}
}
/// Returns the version of the implemented SPCI specification.
#[no_mangle]
pub extern "C" fn api_spci_version() -> i32 {
// Ensure that both major and minor revision representation occupies at
// most 15 bits.
const_assert!(0x8000 > SPCI_VERSION_MAJOR);
const_assert!(0x10000 > SPCI_VERSION_MINOR);
(SPCI_VERSION_MAJOR << SPCI_VERSION_MAJOR_OFFSET) | SPCI_VERSION_MINOR
}
#[no_mangle]
pub unsafe extern "C" fn api_debug_log(c: c_char, current: *mut VCpu) -> i64 {
let vm = (*current).vm;
(*vm).debug_log(c);
0
}
Simplify code in api.rs
/*
* Copyright 2019 Jeehoon Kang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::ops::Deref;
use core::ptr;
use core::sync::atomic::Ordering;
use crate::abi::*;
use crate::addr::*;
use crate::arch::*;
use crate::cpu::*;
use crate::mm::*;
use crate::mpool::*;
use crate::page::*;
use crate::spci::*;
use crate::spinlock::*;
use crate::std::*;
use crate::types::*;
use crate::utils::*;
use crate::vm::*;
// To eliminate the risk of deadlocks, we define a partial order for the acquisition of locks held
// concurrently by the same physical CPU. Our current ordering requirements are as follows:
//
// vcpu::execution_lock -> vm::lock -> vcpu::interrupts_lock -> mm_stage1_lock -> dlog sl
//
// Locks of the same kind require the lock of lowest address to be locked first, see
// `sl_lock_both()`.
// Currently, a page is mapped for the send and receive buffers so the maximum request is the size
// of a page.
const_assert_eq!(hf_mailbox_size; HF_MAILBOX_SIZE, PAGE_SIZE);
/// A global page pool for sharing memories. Its mutability is needed only for
/// initialization.
static mut API_PAGE_POOL: MaybeUninit<MPool> = MaybeUninit::uninit();
/// Initialises the API page pool by taking ownership of the contents of the
/// given page pool.
/// TODO(HfO2): The ownership of `ppool` is actually moved from `one_time_init`
/// to here. Refactor this function like `Api::new(ppool: MPool) -> Api`. (#31)
#[no_mangle]
pub unsafe extern "C" fn api_init(ppool: *const MPool) {
API_PAGE_POOL = MaybeUninit::new(MPool::new_from(&*ppool));
}
/// Switches the physical CPU back to the corresponding vcpu of the primary VM.
///
/// This triggers the scheduling logic to run. Run in the context of secondary
/// VM to cause HF_VCPU_RUN to return and the primary VM to regain control of
/// the cpu.
unsafe fn switch_to_primary(
current: &mut VCpuExecutionLocked,
mut primary_ret: HfVCpuRunReturn,
secondary_state: VCpuStatus,
) -> *mut VCpu {
let primary = vm_find(HF_PRIMARY_VM_ID);
let next = vm_get_vcpu(
primary,
cpu_index(current.get_inner().cpu) as spci_vcpu_index_t,
);
// If the secondary is blocked but has a timer running, sleep until the
// timer fires rather than indefinitely.
match &mut primary_ret {
HfVCpuRunReturn::WaitForInterrupt { ns } | HfVCpuRunReturn::WaitForMessage { ns } => {
*ns = if arch_timer_enabled_current() {
arch_timer_remaining_ns_current()
} else {
HF_SLEEP_INDEFINITE
};
}
_ => {}
}
// Set the return value for the primary VM's call to HF_VCPU_RUN.
//
// The use of `get_mut_unchecked()` is safe because the currently running pCPU implicitly owns
// `next`. Notice that `next` is the vCPU of the primary VM that corresponds to the currently
// running pCPU.
(*next)
.inner
.get_mut_unchecked()
.regs
.set_retval(primary_ret.into_raw());
// Mark the current vcpu as waiting.
current.get_inner_mut().state = secondary_state;
next
}
/// Returns to the primary vm and signals that the vcpu still has work to do so.
#[no_mangle]
pub unsafe extern "C" fn api_preempt(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
switch_to_primary(&mut current, HfVCpuRunReturn::Preempted, VCpuStatus::Ready)
}
/// Puts the current vcpu in wait for interrupt mode, and returns to the primary
/// vm.
#[no_mangle]
pub unsafe extern "C" fn api_wait_for_interrupt(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
switch_to_primary(
&mut current,
HfVCpuRunReturn::WaitForInterrupt {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
},
VCpuStatus::BlockedInterrupt,
)
}
/// Puts the current vCPU in off mode, and returns to the primary VM.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_off(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
// Disable the timer, so the scheduler doesn't get told to call back
// based on it.
arch_timer_disable_current();
switch_to_primary(
&mut current,
HfVCpuRunReturn::WaitForInterrupt {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
},
VCpuStatus::Off,
)
}
/// Returns to the primary vm to allow this cpu to be used for other tasks as
/// the vcpu does not have work to do at this moment. The current vcpu is masked
/// as ready to be scheduled again. This SPCI function always returns
/// SpciReturn::Success.
#[no_mangle]
pub unsafe extern "C" fn api_spci_yield(current: *mut VCpu, next: *mut *mut VCpu) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// Noop on the primary as it makes the scheduling decisions.
return SpciReturn::Success;
}
*next = switch_to_primary(&mut current, HfVCpuRunReturn::Yield, VCpuStatus::Ready);
// SPCI_YIELD always returns SPCI_SUCCESS.
SpciReturn::Success
}
unsafe fn wake_up(current: &mut VCpuExecutionLocked, target_vcpu: &VCpu) -> *mut VCpu {
switch_to_primary(
current,
HfVCpuRunReturn::WakeUp {
vm_id: (*target_vcpu.vm).id,
vcpu: vcpu_index(target_vcpu),
},
VCpuStatus::Ready,
)
}
/// Switches to the primary so that it can switch to the target, or kick tit if
/// it is already running on a different physical CPU.
#[no_mangle]
pub unsafe extern "C" fn api_wake_up(current: *mut VCpu, target_vcpu: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
wake_up(&mut current, &*target_vcpu)
}
/// Aborts the vCPU and triggers its VM to abort fully.
#[no_mangle]
pub unsafe extern "C" fn api_abort(current: *mut VCpu) -> *mut VCpu {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
dlog!(
"Aborting VM {} vCPU {}\n",
(*current.get_vcpu().vm).id,
vcpu_index(current.get_vcpu())
);
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// TODO: what to do when the primary aborts?
spin_loop();
}
(*current.get_vcpu().vm)
.aborting
.store(true, Ordering::Relaxed);
// TODO: free resources once all vCPUs abort.
switch_to_primary(&mut current, HfVCpuRunReturn::Aborted, VCpuStatus::Aborted)
}
/// Returns the ID of the VM.
#[no_mangle]
pub unsafe extern "C" fn api_vm_get_id(current: *const VCpu) -> spci_vm_id_t {
(*(*current).vm).id
}
/// Returns the number of VMs configured to run.
#[no_mangle]
pub unsafe extern "C" fn api_vm_get_count() -> spci_vm_count_t {
vm_get_count()
}
/// Returns the number of vCPUs configured in the given VM, or 0 if there is no
/// such VM or the caller is not the primary VM.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_get_count(
vm_id: spci_vm_id_t,
current: *const VCpu,
) -> spci_vcpu_count_t {
let vm;
// Only the primary VM needs to know about vcpus for scheduling.
if (*(*current).vm).id != HF_PRIMARY_VM_ID {
return 0;
}
vm = vm_find(vm_id);
if vm.is_null() {
return 0;
}
(*vm).vcpu_count
}
/// This function is called by the architecture-specific context switching
/// function to indicate that register state for the given vcpu has been saved
/// and can therefore be used by other pcpus.
#[no_mangle]
pub unsafe extern "C" fn api_regs_state_saved(vcpu: *mut VCpu) {
(*vcpu).inner.unlock_unchecked();
}
/// Assuming that the arguments have already been checked by the caller, injects
/// a virtual interrupt of the given ID into the given target vCPU. This doesn't
/// cause the vCPU to actually be run immediately; it will be taken when the
/// vCPU is next run, which is up to the scheduler.
///
/// Returns:
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick the target vCPU.
/// TODO: this function was using `goto` originally and it is just
/// implemented as copy-paste in Rust.
unsafe fn internal_interrupt_inject(
target_vcpu: &VCpu,
intid: intid_t,
current: &mut VCpuExecutionLocked,
next: *mut *mut VCpu,
) -> i64 {
if target_vcpu.interrupts.lock().inject(intid).is_ok() {
if (*current.get_vcpu().vm).id == HF_PRIMARY_VM_ID {
// If the call came from the primary VM, let it know that it should
// run or kick the target vCPU.
return 1;
} else if current.get_vcpu() as *const _ != target_vcpu as *const _ && !next.is_null() {
*next = wake_up(current, target_vcpu);
}
}
0
}
/// Prepares the vcpu to run by updating its state and fetching whether a return
/// value needs to be forced onto the vCPU.
///
/// Returns:
/// - false if it fails to prepare `vcpu` to run.
/// - true if it succeeds to prepare `vcpu` to run. In this case,
/// `vcpu.execution_lock` has acquired.
unsafe fn vcpu_prepare_run(
current: &VCpuExecutionLocked,
vcpu: *mut VCpu,
run_ret: HfVCpuRunReturn,
) -> Result<VCpuExecutionLocked, HfVCpuRunReturn> {
let mut vcpu_inner = (*vcpu).inner.try_lock().map_err(|_| {
// vCPU is running or prepared to run on another pCPU.
//
// It's ok not to return the sleep duration here because the other
// physical CPU that is currently running this vCPU will return the
// sleep duration if needed. The default return value is
// HfVCpuRunReturn::WaitForInterrupt, so no need to set it
// explicitly.
run_ret
})?;
if (*(*vcpu).vm).aborting.load(Ordering::Relaxed) {
if vcpu_inner.state != VCpuStatus::Aborted {
dlog!(
"Aborting VM {} vCPU {}\n",
(*(*vcpu).vm).id,
vcpu_index(vcpu)
);
vcpu_inner.state = VCpuStatus::Aborted;
}
return Err(run_ret);
}
match vcpu_inner.state {
VCpuStatus::Off | VCpuStatus::Aborted => {
return Err(run_ret);
}
// A pending message allows the vCPU to run so the message can be
// delivered directly.
// The VM needs to be locked to deliver mailbox messages.
// The VM lock is not needed in the common case so it must only be taken
// when it is going to be needed. This ensures there are no inter-vCPU
// dependencies in the common run case meaning the sensitive context
// switch performance is consistent.
VCpuStatus::BlockedMailbox if (*(*vcpu).vm).inner.lock().try_read().is_ok() => {
vcpu_inner.regs.set_retval(SpciReturn::Success as uintreg_t);
}
// Allow virtual interrupts to be delivered.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt
if (*vcpu).interrupts.lock().is_interrupted() =>
{
// break;
}
// The timer expired so allow the interrupt to be delivered.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt
if vcpu_inner.regs.timer_pending() =>
{
// break;
}
// The vCPU is not ready to run, return the appropriate code to the
// primary which called vcpu_run.
VCpuStatus::BlockedMailbox | VCpuStatus::BlockedInterrupt => {
let run_ret = if !vcpu_inner.regs.timer_enabled() {
run_ret
} else {
let ns = vcpu_inner.regs.timer_remaining_ns();
if vcpu_inner.state == VCpuStatus::BlockedMailbox {
HfVCpuRunReturn::WaitForMessage { ns }
} else {
HfVCpuRunReturn::WaitForInterrupt { ns }
}
};
return Err(run_ret);
}
VCpuStatus::Ready => {
// break;
}
}
// It has been decided that the vCPU should be run.
vcpu_inner.cpu = current.get_inner().cpu;
// We want to keep the lock of vcpu.state because we're going to run.
mem::forget(vcpu_inner);
Ok(VCpuExecutionLocked::from_raw(vcpu))
}
/// Runs the given vcpu of the given vm.
#[no_mangle]
pub unsafe extern "C" fn api_vcpu_run(
vm_id: spci_vm_id_t,
vcpu_idx: spci_vcpu_index_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> u64 {
let current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let ret = HfVCpuRunReturn::WaitForInterrupt {
ns: HF_SLEEP_INDEFINITE,
};
// Only the primary VM can switch vcpus.
if (*current.get_vcpu().vm).id != HF_PRIMARY_VM_ID {
return ret.into_raw();
}
// Only the secondary VM vcpus can be run.
if vm_id == HF_PRIMARY_VM_ID {
return ret.into_raw();
}
// The requested VM must exist.
let vm = vm_find(vm_id);
if vm.is_null() {
return ret.into_raw();
}
// The requested vcpu must exist.
if vcpu_idx >= (*vm).vcpu_count {
return ret.into_raw();
}
// Update state if allowed.
let vcpu = vm_get_vcpu(vm, vcpu_idx);
let mut vcpu_locked = match vcpu_prepare_run(¤t, vcpu, ret) {
Ok(locked) => locked,
Err(ret) => return ret.into_raw(),
};
// Inject timer interrupt if timer has expired. It's safe to access
// vcpu->regs here because vcpu_prepare_run already made sure that
// regs_available was true (and then set it to false) before returning
// true.
if vcpu_locked.get_inner().regs.timer_pending() {
// Make virtual timer interrupt pending.
internal_interrupt_inject(
&*vcpu,
HF_VIRTUAL_TIMER_INTID,
&mut vcpu_locked,
ptr::null_mut(),
);
// Set the mask bit so the hardware interrupt doesn't fire again.
// Ideally we wouldn't do this because it affects what the secondary
// vcPU sees, but if we don't then we end up with a loop of the
// interrupt firing each time we try to return to the secondary vCPU.
vcpu_locked.get_inner_mut().regs.timer_mask();
}
// Switch to the vcpu.
*next = vcpu_locked.into_raw() as *const _ as *mut _;
// Set a placeholder return code to the scheduler. This will be overwritten
// when the switch back to the primary occurs.
HfVCpuRunReturn::Preempted.into_raw()
}
/// Determines the value to be returned by api_vm_configure and
/// api_mailbox_clear after they've succeeded. If a secondary VM is running and
/// there are waiters, it also switches back to the primary VM for it to wake
/// waiters up.
unsafe fn waiter_result(
vm_id: spci_vm_id_t,
vm_inner: &VmInner,
current: &mut VCpuExecutionLocked,
next: *mut *mut VCpu,
) -> i64 {
if vm_inner.is_waiter_list_empty() {
// No waiters, nothing else to do.
return 0;
}
if vm_id == HF_PRIMARY_VM_ID {
// The caller is the primary VM. Tell it to wake up waiters.
return 1;
}
// Switch back to the primary VM, informing it that there are waiters
// that need to be notified.
*next = switch_to_primary(current, HfVCpuRunReturn::NotifyWaiters, VCpuStatus::Ready);
0
}
/// Configures the VM to send/receive data through the specified pages. The
/// pages must not be shared.
///
/// Returns:
/// - -1 on failure.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick waiters. Waiters should be retrieved by calling
/// hf_mailbox_waiter_get.
#[no_mangle]
pub unsafe extern "C" fn api_vm_configure(
send: ipaddr_t,
recv: ipaddr_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = current.get_vcpu().vm;
// The hypervisor's memory map must be locked for the duration of this
// operation to ensure there will be sufficient memory to recover from
// any failures.
//
// TODO: the scope of the can be reduced but will require restructing
// to keep a single unlock point.
let mut vm_inner = (*vm).inner.lock();
if vm_inner
.configure(send, recv, API_PAGE_POOL.get_ref())
.is_err()
{
return -1;
}
// Tell caller about waiters, if any.
waiter_result((*vm).id, &vm_inner, &mut current, next)
}
/// Copies data from the sender's send buffer to the recipient's receive buffer
/// and notifies the recipient.
///
/// If the recipient's receive buffer is busy, it can optionally register the
/// caller to be notified when the recipient's receive buffer becomes available.
#[no_mangle]
pub unsafe extern "C" fn api_spci_msg_send(
attributes: SpciMsgSendAttributes,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let from = current.get_vcpu().vm;
// TODO: Refactor the control flow of this function, and make this variable
// immutable.
let mut ret;
let notify = attributes.contains(SpciMsgSendAttributes::NOTIFY);
// Check that the sender has configured its send buffer. Copy the message
// header. If the tx mailbox at from_msg is configured (i.e.
// from_msg != ptr::null()) then it can be safely accessed after releasing
// the lock since the tx mailbox address can only be configured once.
let from_msg = (*from).inner.lock().get_send_ptr();
if from_msg.is_null() {
return SpciReturn::InvalidParameters;
}
// Note that the payload is not copied when the message header is.
let mut from_msg_replica = ptr::read(from_msg);
// Ensure source VM id corresponds to the current VM.
if from_msg_replica.source_vm_id != (*from).id {
return SpciReturn::InvalidParameters;
}
let size = from_msg_replica.length as usize;
// Limit the size of transfer.
if size > SPCI_MSG_PAYLOAD_MAX {
return SpciReturn::InvalidParameters;
}
// Disallow reflexive requests as this suggests an error in the VM.
if from_msg_replica.target_vm_id == (*from).id {
return SpciReturn::InvalidParameters;
}
// Ensure the target VM exists.
let to = vm_find(from_msg_replica.target_vm_id);
if to.is_null() {
return SpciReturn::InvalidParameters;
}
// Hf needs to hold the lock on `to` before the mailbox state is checked.
// The lock on `to` must be held until the information is copied to `to` Rx
// buffer. Since in spci_msg_handle_architected_message we may call
// api_spci_share_memory which must hold the `from` lock, we must hold the
// `from` lock at this point to prevent a deadlock scenario.
let (mut to_inner, mut from_inner) = SpinLock::lock_both(&(*to).inner, &(*from).inner);
if !to_inner.is_empty() || !to_inner.is_configured() {
// Fail if the target isn't currently ready to receive data,
// setting up for notification if requested.
if notify {
let _ = from_inner.wait(&mut to_inner, (*to).id);
}
return SpciReturn::Busy;
}
let to_msg = to_inner.get_recv_ptr();
// Handle architected messages.
if !from_msg_replica.flags.contains(SpciMessageFlags::IMPDEF) {
// Buffer holding the internal copy of the shared memory regions.
// TODO: Buffer is temporarily in the stack.
let mut message_buffer: [u8; mem::size_of::<SpciArchitectedMessageHeader>()
+ mem::size_of::<SpciMemoryRegionConstituent>()
+ mem::size_of::<SpciMemoryRegion>()] = MaybeUninit::uninit().assume_init();
let architected_header = spci_get_architected_message_header(from_msg);
if from_msg_replica.length as usize > message_buffer.len() {
return SpciReturn::InvalidParameters;
}
if (from_msg_replica.length as usize) < mem::size_of::<SpciArchitectedMessageHeader>() {
return SpciReturn::InvalidParameters;
}
// Copy the architected message into an internal buffer.
memcpy_s(
message_buffer.as_mut_ptr() as _,
message_buffer.len(),
architected_header as _,
from_msg_replica.length as usize,
);
let architected_message_replica: *mut SpciArchitectedMessageHeader =
message_buffer.as_mut_ptr() as usize as *mut _;
// Note that message_buffer is passed as the third parameter to
// spci_msg_handle_architected_message. The execution flow commencing
// at spci_msg_handle_architected_message will make several accesses to
// fields in message_buffer. The memory area message_buffer must be
// exclusively owned by Hf so that TOCTOU issues do not arise.
// TODO(HfO2): This code looks unsafe. Port spci_architected_message.c
// and avoid creating VmLocked manually.
ret = spci_msg_handle_architected_message(
VmLocked::from_raw(to),
VmLocked::from_raw(from),
architected_message_replica,
&mut from_msg_replica,
to_msg,
);
if ret != SpciReturn::Success {
return ret;
}
} else {
// Copy data.
memcpy_s(
&mut (*to_msg).payload as *mut _ as usize as _,
SPCI_MSG_PAYLOAD_MAX,
// HfO2: below was &(*(*from).mailbox.send).payload, but we can
// safely assume it is equal to &(*from_msg).payload, even though
// from_msg was defined before entering critical section. That's
// because we do not allow vm to be configured more than once.
&(*from_msg).payload as *const _ as usize as _,
size,
);
*to_msg = from_msg_replica;
}
let primary_ret = HfVCpuRunReturn::Message { vm_id: (*to).id };
ret = SpciReturn::Success;
// Messages for the primary VM are delivered directly.
if (*to).id == HF_PRIMARY_VM_ID {
to_inner.set_read();
*next = switch_to_primary(&mut current, primary_ret, VCpuStatus::Ready);
return ret;
}
to_inner.set_received();
// Return to the primary VM directly or with a switch.
if (*from).id != HF_PRIMARY_VM_ID {
*next = switch_to_primary(&mut current, primary_ret, VCpuStatus::Ready);
}
ret
}
/// Receives a message from the mailbox. If one isn't available, this function
/// can optionally block the caller until one becomes available.
///
/// No new messages can be received until the mailbox has been cleared.
#[no_mangle]
pub unsafe extern "C" fn api_spci_msg_recv(
attributes: SpciMsgRecvAttributes,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> SpciReturn {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = &*current.get_vcpu().vm;
let block = attributes.contains(SpciMsgRecvAttributes::BLOCK);
// The primary VM will receive messages as a status code from running vcpus
// and must not call this function.
if vm.id == HF_PRIMARY_VM_ID {
return SpciReturn::Interrupted;
}
let mut vm_inner = vm.inner.lock();
// Return pending messages without blocking.
if vm_inner.try_read().is_ok() {
return SpciReturn::Success;
}
// No pending message so fail if not allowed to block.
if !block {
return SpciReturn::Retry;
}
// From this point onward this call can only be interrupted or a message received. If a message
// is received the return value will be set at that time to SPCI_SUCCESS.
//
// Block only if there are enabled and pending interrupts, to match behaviour of
// wait_for_interrupt.
if !current.get_vcpu().interrupts.lock().is_interrupted() {
// Switch back to primary vm to block.
*next = switch_to_primary(
&mut current,
HfVCpuRunReturn::WaitForMessage {
// `api_switch_to_primary` always initializes this variable.
ns: HF_SLEEP_INDEFINITE,
},
VCpuStatus::BlockedMailbox,
);
}
SpciReturn::Interrupted
}
/// Retrieves the next VM whose mailbox became writable. For a VM to be notified
/// by this function, the caller must have called api_mailbox_send before with
/// the notify argument set to true, and this call must have failed because the
/// mailbox was not available.
///
/// It should be called repeatedly to retrieve a list of VMs.
///
/// Returns -1 if no VM became writable, or the id of the VM whose mailbox
/// became writable.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_writable_get(current: *const VCpu) -> i64 {
let vm = (*current).vm;
let mut vm_inner = (*vm).inner.lock();
match vm_inner.dequeue_ready_list() {
Some(id) => i64::from(id),
None => -1,
}
}
/// Retrieves the next VM waiting to be notified that the mailbox of the
/// specified VM became writable. Only primary VMs are allowed to call this.
///
/// Returns -1 on failure or if there are no waiters; the VM id of the next
/// waiter otherwise.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_waiter_get(vm_id: spci_vm_id_t, current: *const VCpu) -> i64 {
// Only primary VMs are allowed to call this function.
if (*(*current).vm).id != HF_PRIMARY_VM_ID {
return -1;
}
let vm = vm_find(vm_id);
if vm.is_null() {
return -1;
}
// Check if there are outstanding notifications from given vm.
let entry = (*vm).inner.lock().fetch_waiter();
if entry.is_null() {
return -1;
}
// Enqueue notification to waiting VM.
let waiting_vm = (*entry).waiting_vm;
let mut vm_inner = (*waiting_vm).inner.lock();
if !(*entry).is_in_ready_list() {
vm_inner.enqueue_ready_list(&mut *entry);
}
i64::from((*waiting_vm).id)
}
/// Clears the caller's mailbox so that a new message can be received. The
/// caller must have copied out all data they wish to preserve as new messages
/// will overwrite the old and will arrive asynchronously.
///
/// Returns:
/// - -1 on failure, if the mailbox hasn't been read.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick waiters. Waiters should be retrieved by calling
/// hf_mailbox_waiter_get.
#[no_mangle]
pub unsafe extern "C" fn api_mailbox_clear(current: *mut VCpu, next: *mut *mut VCpu) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let vm = current.get_vcpu().vm;
let mut vm_inner = (*vm).inner.lock();
match vm_inner.get_state() {
MailboxState::Empty => 0,
MailboxState::Received => -1,
MailboxState::Read => {
vm_inner.set_empty();
waiter_result((*vm).id, &vm_inner, &mut current, next)
}
}
}
/// Enables or disables a given interrupt ID for the calling vCPU.
///
/// Returns 0 on success, or -1 if the intid is invalid.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_enable(
intid: intid_t,
enable: bool,
current: *mut VCpu,
) -> i64 {
if (*current).interrupts.lock().enable(intid, enable).is_ok() {
0
} else {
-1
}
}
/// Returns the ID of the next pending interrupt for the calling vCPU, and
/// acknowledges it (i.e. marks it as no longer pending). Returns
/// HF_INVALID_INTID if there are no pending interrupts.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_get(current: *mut VCpu) -> intid_t {
(*current).interrupts.lock().get()
}
/// Returns whether the current vCPU is allowed to inject an interrupt into the
/// given VM and vCPU.
#[inline]
fn is_injection_allowed(target_vm_id: spci_vm_id_t, current: &VCpu) -> bool {
let current_vm_id = unsafe { (*current.vm).id };
// The primary VM is allowed to inject interrupts into any VM. Secondary
// VMs are only allowed to inject interrupts into their own vCPUs.
current_vm_id == HF_PRIMARY_VM_ID || current_vm_id == target_vm_id
}
/// Injects a virtual interrupt of the given ID into the given target vCPU.
/// This doesn't cause the vCPU to actually be run immediately; it will be taken
/// when the vCPU is next run, which is up to the scheduler.
///
/// Returns:
/// - -1 on failure because the target VM or vCPU doesn't exist, the interrupt
/// ID is invalid, or the current VM is not allowed to inject interrupts to
/// the target VM.
/// - 0 on success if no further action is needed.
/// - 1 if it was called by the primary VM and the primary VM now needs to wake
/// up or kick the target vCPU.
#[no_mangle]
pub unsafe extern "C" fn api_interrupt_inject(
target_vm_id: spci_vm_id_t,
target_vcpu_idx: spci_vcpu_index_t,
intid: intid_t,
current: *mut VCpu,
next: *mut *mut VCpu,
) -> i64 {
let mut current = ManuallyDrop::new(VCpuExecutionLocked::from_raw(current));
let target_vm = vm_find(target_vm_id);
if intid >= HF_NUM_INTIDS {
return -1;
}
if target_vm.is_null() {
return -1;
}
if target_vcpu_idx >= (*target_vm).vcpu_count {
// The requested vcpu must exist.
return -1;
}
if !is_injection_allowed(target_vm_id, current.get_vcpu()) {
return -1;
}
let target_vcpu = vm_get_vcpu(target_vm, target_vcpu_idx);
dlog!(
"Injecting IRQ {} for VM {} VCPU {} from VM {} VCPU {}\n",
intid,
target_vm_id,
target_vcpu_idx,
(*current.get_vcpu().vm).id,
(*current.get_inner().cpu).id
);
internal_interrupt_inject(&*target_vcpu, intid, &mut current, next)
}
/// Clears a region of physical memory by overwriting it with zeros. The data is
/// flushed from the cache so the memory has been cleared across the system.
fn clear_memory(begin: paddr_t, end: paddr_t, ppool: &MPool) -> Result<(), ()> {
let mut hypervisor_ptable = HYPERVISOR_PAGE_TABLE.lock();
let size = pa_difference(begin, end);
let region = pa_addr(begin);
// TODO: change this to a cpu local single page window rather than a global
// mapping of the whole range. Such an approach will limit the
// changes to stage-1 tables and will allow only local invalidation.
if hypervisor_ptable
.identity_map(begin, end, Mode::W, ppool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
hypervisor_ptable.defrag(ppool);
return Err(());
}
unsafe {
memset_s(region as usize as _, size, 0, size);
arch_mm_write_back_dcache(region as usize, size);
}
hypervisor_ptable.unmap(begin, end, ppool).unwrap();
Ok(())
}
// TODO: Move function to spci_architectted_message.c. (How in Rust?)
/// Shares memory from the calling VM with another. The memory can be shared in
/// different modes.
///
/// This function requires the calling context to hold the <to> and <from>
/// locks.
///
/// Returns:
/// In case of error one of the following values is returned:
/// 1) SPCI_INVALID_PARAMETERS - The endpoint provided parameters were
/// erroneous;
/// 2) SPCI_NO_MEMORY - Hf did not have sufficient memory to complete
/// the request.
/// Success is indicated by SPCI_SUCCESS.
#[no_mangle]
pub unsafe extern "C" fn api_spci_share_memory(
to_locked: VmLocked,
from_locked: VmLocked,
memory_region: *mut SpciMemoryRegion,
memory_to_attributes: u32,
share: usize,
) -> SpciReturn {
let to_inner = to_locked.inner.get_mut_unchecked();
let from_inner = from_locked.inner.get_mut_unchecked();
// Disallow reflexive shares as this suggests an error in the VM.
if to_locked == from_locked {
return SpciReturn::InvalidParameters;
}
// Create a local pool so any freed memory can't be used by another thread.
// This is to ensure the original mapping can be restored if any stage of
// the process fails.
let local_page_pool: MPool = MPool::new_with_fallback(API_PAGE_POOL.get_ref());
// Obtain the single contiguous set of pages from the memory_region.
// TODO: Add support for multiple constituent regions.
let constituent =
&(*memory_region).constituents as *const _ as usize as *const SpciMemoryRegionConstituent;
let size = (*constituent).page_count as usize * PAGE_SIZE;
let begin = ipa_init((*constituent).address as usize);
let end = ipa_add(begin, size as usize);
// Check if the state transition is lawful for both VMs involved in the
// memory exchange, ensure that all constituents of a memory region being
// shared are at the same state.
let mut orig_from_mode = MaybeUninit::uninit();
let mut from_mode = MaybeUninit::uninit();
let mut to_mode = MaybeUninit::uninit();
let share = match share {
0x2 => SpciMemoryShare::Donate,
_ => return SpciReturn::InvalidParameters,
};
if !spci_msg_check_transition(
to_locked.deref(),
from_locked.deref(),
share,
orig_from_mode.get_mut(),
begin,
end,
memory_to_attributes,
from_mode.get_mut(),
to_mode.get_mut(),
) {
return SpciReturn::InvalidParameters;
}
let pa_begin = pa_from_ipa(begin);
let pa_end = pa_from_ipa(end);
// First update the mapping for the sender so there is not overlap with the
// recipient.
if from_inner
.ptable
.identity_map(pa_begin, pa_end, from_mode.assume_init(), &local_page_pool)
.is_err()
{
return SpciReturn::NoMemory;
}
// Complete the transfer by mapping the memory into the recipient.
if to_inner
.ptable
.identity_map(pa_begin, pa_end, to_mode.assume_init(), &local_page_pool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
from_inner.ptable.defrag(&local_page_pool);
assert!(from_inner
.ptable
.identity_map(
pa_begin,
pa_end,
orig_from_mode.assume_init(),
&local_page_pool
)
.is_err());
return SpciReturn::NoMemory;
}
SpciReturn::Success
}
/// Shares memory from the calling VM with another. The memory can be shared in
/// different modes.
///
/// TODO: the interface for sharing memory will need to be enhanced to allow
/// sharing with different modes e.g. read-only, informing the recipient
/// of the memory they have been given, opting to not wipe the memory and
/// possibly allowing multiple blocks to be transferred. What this will
/// look like is TBD.
fn share_memory(
vm_id: spci_vm_id_t,
addr: ipaddr_t,
size: usize,
share: HfShare,
current: &VCpu,
) -> Result<(), ()> {
let from: &Vm = unsafe { &*current.vm };
// Disallow reflexive shares as this suggests an error in the VM.
if vm_id == from.id {
return Err(());
}
// Ensure the target VM exists.
let to = unsafe { vm_find(vm_id) };
if to.is_null() {
return Err(());
}
let to = unsafe { &*to };
let begin = addr;
let end = ipa_add(addr, size);
// Fail if addresses are not page-aligned.
if !is_aligned(ipa_addr(begin), PAGE_SIZE) || !is_aligned(ipa_addr(end), PAGE_SIZE) {
return Err(());
}
let (from_mode, to_mode) = match share {
HfShare::Give => (
(Mode::INVALID | Mode::UNOWNED),
(Mode::R | Mode::W | Mode::X),
),
HfShare::Lend => (Mode::INVALID, (Mode::R | Mode::W | Mode::X | Mode::UNOWNED)),
HfShare::Share => (
(Mode::R | Mode::W | Mode::X | Mode::SHARED),
(Mode::R | Mode::W | Mode::X | Mode::UNOWNED | Mode::SHARED),
),
};
// Create a local pool so any freed memory can't be used by another thread.
// This is to ensure the original mapping can be restored if any stage of
// the process fails.
// TODO: So that's reason why Hafnium use local_page_pool! We need to verify
// this.
let local_page_pool = MPool::new_with_fallback(unsafe { API_PAGE_POOL.get_ref() });
let (mut from_inner, mut to_inner) = SpinLock::lock_both(&(*from).inner, &(*to).inner);
// Ensure that the memory range is mapped with the same mode so that
// changes can be reverted if the process fails.
// Also ensure the memory range is valid for the sender. If it isn't, the
// sender has either shared it with another VM already or has no claim to
// the memory.
let orig_from_mode = from_inner.ptable.get_mode(begin, end)?;
if orig_from_mode.contains(Mode::INVALID) {
return Err(());
}
// The sender must own the memory and have exclusive access to it in order
// to share it. Alternatively, it is giving memory back to the owning VM.
if orig_from_mode.contains(Mode::UNOWNED) {
let to_mode = to_inner.ptable.get_mode(begin, end)?;
if to_mode.contains(Mode::UNOWNED) {
return Err(());
}
if share != HfShare::Give {
return Err(());
}
} else if orig_from_mode.contains(Mode::SHARED) {
return Err(());
}
let pa_begin = pa_from_ipa(begin);
let pa_end = pa_from_ipa(end);
// First update the mapping for the sender so there is not overlap with the
// recipient.
from_inner
.ptable
.identity_map(pa_begin, pa_end, from_mode, &local_page_pool)?;
// Clear the memory so no VM or device can see the previous contents.
if clear_memory(pa_begin, pa_end, &local_page_pool).is_err() {
assert!(from_inner
.ptable
.identity_map(pa_begin, pa_end, orig_from_mode, &local_page_pool)
.is_ok());
return Err(());
}
// Complete the transfer by mapping the memory into the recipient.
if to_inner
.ptable
.identity_map(pa_begin, pa_end, to_mode, &local_page_pool)
.is_err()
{
// TODO: partial defrag of failed range.
// Recover any memory consumed in failed mapping.
from_inner.ptable.defrag(&local_page_pool);
// goto fail_return_to_sender;
assert!(from_inner
.ptable
.identity_map(pa_begin, pa_end, orig_from_mode, &local_page_pool)
.is_ok());
return Err(());
}
Ok(())
}
#[no_mangle]
pub unsafe extern "C" fn api_share_memory(
vm_id: spci_vm_id_t,
addr: ipaddr_t,
size: size_t,
share: usize,
current: *const VCpu,
) -> i64 {
// Convert the sharing request to memory management modes.
let share = match share {
0 => HfShare::Give,
1 => HfShare::Lend,
2 => HfShare::Share,
_ => {
// The input is untrusted so might not be a valid value.
return -1;
}
};
match share_memory(vm_id, addr, size, share, &*current) {
Ok(_) => 0,
Err(_) => -1,
}
}
/// Returns the version of the implemented SPCI specification.
#[no_mangle]
pub extern "C" fn api_spci_version() -> i32 {
// Ensure that both major and minor revision representation occupies at
// most 15 bits.
const_assert!(0x8000 > SPCI_VERSION_MAJOR);
const_assert!(0x10000 > SPCI_VERSION_MINOR);
(SPCI_VERSION_MAJOR << SPCI_VERSION_MAJOR_OFFSET) | SPCI_VERSION_MINOR
}
#[no_mangle]
pub unsafe extern "C" fn api_debug_log(c: c_char, current: *mut VCpu) -> i64 {
let vm = (*current).vm;
(*vm).debug_log(c);
0
}
|
/*
* Copyright 2019 Sanguk Park.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use core::convert::{TryFrom, TryInto};
use core::mem;
use core::ptr;
use core::slice;
use core::str;
use scopeguard::guard;
/// TODO(HfO2): port this function into `std.rs` (#48.)
extern "C" {
fn strcmp(a: *const u8, b: *const u8) -> i64;
}
#[derive(Clone)]
#[repr(C)]
pub struct fdt_node {
hdr: *const FdtHeader,
begin: *const u8,
end: *const u8,
strs: *const u8,
}
#[derive(Clone)]
pub struct FdtNode<'a> {
hdr: &'a FdtHeader,
data: &'a [u8],
strs: &'a [u8],
}
impl<'a> From<fdt_node> for FdtNode<'a> {
fn from(n: fdt_node) -> Self {
unsafe {
let hdr = &*n.hdr;
let data_size = u32::from_be(hdr.size_dt_struct) as usize;
let strs_size = u32::from_be(hdr.size_dt_strings) as usize;
Self {
hdr,
data: slice::from_raw_parts(n.begin, data_size),
strs: slice::from_raw_parts(n.strs, strs_size),
}
}
}
}
impl<'a> From<FdtNode<'a>> for fdt_node {
fn from(n: FdtNode<'a>) -> Self {
Self {
hdr: n.hdr,
begin: n.data.as_ptr(),
end: unsafe { n.data.as_ptr().add(n.data.len()) },
strs: n.strs.as_ptr(),
}
}
}
#[repr(C)]
pub struct FdtHeader {
magic: u32,
totalsize: u32,
off_dt_struct: u32,
off_dt_strings: u32,
off_mem_rsvmap: u32,
version: u32,
last_comp_version: u32,
boot_cpuid_phys: u32,
size_dt_strings: u32,
size_dt_struct: u32,
}
struct FdtReserveEntry {
address: u64,
size: u64,
}
#[derive(PartialEq, Clone, Copy)]
enum FdtToken {
BeginNode = 1,
EndNode = 2,
Prop = 3,
Nop = 4,
End = 9,
}
impl TryFrom<u32> for FdtToken {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
use FdtToken::*;
match value {
1 => Ok(BeginNode),
2 => Ok(EndNode),
3 => Ok(Prop),
4 => Ok(Nop),
9 => Ok(End),
_ => Err(()),
}
}
}
struct FdtTokenizer<'a> {
cur: &'a [u8],
strs: &'a [u8],
}
const FDT_VERSION: u32 = 17;
const FDT_MAGIC: u32 = 0xd00d_feed;
const FDT_TOKEN_ALIGNMENT: usize = mem::size_of::<u32>();
impl<'a> FdtTokenizer<'a> {
fn new(cur: &'a [u8], strs: &'a [u8]) -> Self {
Self { cur, strs }
}
fn align(&mut self) {
let modular = self.cur.as_ptr() as usize % FDT_TOKEN_ALIGNMENT;
let (_, cur) = self
.cur
.split_at((FDT_TOKEN_ALIGNMENT - modular) % FDT_TOKEN_ALIGNMENT);
self.cur = cur;
}
fn u32(&mut self) -> Option<u32> {
if self.cur.len() < mem::size_of::<u32>() {
return None;
}
let (first, rest) = self.cur.split_at(mem::size_of::<u32>());
let res = u32::from_be_bytes(first.try_into().unwrap());
self.cur = rest;
Some(res)
}
fn u32_pred<F>(&mut self, pred: F) -> Option<u32>
where
F: FnOnce(u32) -> bool,
{
if self.cur.len() < mem::size_of::<u32>() {
return None;
}
let (first, rest) = self.cur.split_at(mem::size_of::<u32>());
let res = u32::from_be_bytes(first.try_into().unwrap());
if !pred(res) {
return None;
}
self.cur = rest;
Some(res)
}
fn token(&mut self) -> Option<FdtToken> {
while let Some(v) = self.u32() {
let token = v.try_into().unwrap();
if token != FdtToken::Nop {
return Some(token);
}
}
None
}
fn token_expect(&mut self, expect: FdtToken) -> Option<FdtToken> {
while let Some(v) = self.u32_pred(|v| v == expect as u32) {
let token = v.try_into().unwrap();
if token != FdtToken::Nop {
return Some(token);
}
}
None
}
fn bytes(&mut self, size: usize) -> Option<&'a [u8]> {
if self.cur.len() < size {
return None;
}
let (first, rest) = self.cur.split_at(size);
self.cur = rest;
self.align();
Some(first)
}
fn str(&mut self) -> Option<&'a [u8]> {
let (i, _) = self.cur.iter().enumerate().find(|(_, p)| **p == 0)?;
// Found the end of the string.
let (first, rest) = self.cur.split_at(i + 1);
self.cur = rest;
self.align();
Some(first)
}
/// Move cursor to the end so that caller won't get any new tokens.
fn collapse(&mut self) {
self.cur = &self.cur[self.cur.len()..];
}
fn next_property(&mut self) -> Option<(*const u8, &'a [u8])> {
self.token_expect(FdtToken::Prop)?;
let mut this = guard(self, |this| {
this.collapse();
});
let size = this.u32()? as usize;
let nameoff = this.u32()? as usize;
let buf = this.bytes(size)?;
//TODO: Need to verify the strings.
let name = this.strs[nameoff..].as_ptr();
mem::forget(this);
Some((name, buf))
}
fn next_subnode(&mut self) -> Option<&'a [u8]> {
self.token_expect(FdtToken::BeginNode)?;
let name = some_or!(self.str(), {
self.collapse();
return None;
});
Some(name)
}
fn skip_properties(&mut self) {
while self.next_property().is_some() {}
}
fn skip_node(&mut self) -> Option<()> {
let mut pending = 1;
self.skip_properties();
while pending != 0 {
while let Some(_) = self.next_subnode() {
self.skip_properties();
pending += 1;
}
if self.token()? != FdtToken::EndNode {
self.collapse();
return None;
}
pending -= 1;
}
Some(())
}
}
impl<'a> FdtNode<'a> {
pub fn new_root(hdr: &'a FdtHeader) -> Option<Self> {
// Check the magic number before anything else.
if hdr.magic != u32::from_be(FDT_MAGIC) {
return None;
}
// Check the version.
let max_ver = u32::from_be(hdr.version);
let min_ver = u32::from_be(hdr.last_comp_version);
if FDT_VERSION < min_ver || FDT_VERSION > max_ver {
return None;
}
let hdr_ptr = hdr as *const _ as *const u8;
let data_begin = u32::from_be(hdr.off_dt_struct) as usize;
let data_size = u32::from_be(hdr.size_dt_struct) as usize;
let strs_begin = u32::from_be(hdr.off_dt_strings) as usize;
let strs_size = u32::from_be(hdr.size_dt_strings) as usize;
// TODO: Verify that it is all within the fdt.
// TODO: Verify strings as well.
Some(FdtNode {
hdr,
data: unsafe { slice::from_raw_parts(hdr_ptr.add(data_begin), data_size) },
strs: unsafe { slice::from_raw_parts(hdr_ptr.add(strs_begin), strs_size) },
})
}
pub fn read_property(&self, name: *const u8) -> Result<&'a [u8], ()> {
let mut t = FdtTokenizer::new(self.data, self.strs);
while let Some((prop_name, buf)) = t.next_property() {
if unsafe { strcmp(prop_name, name) } == 0 {
return Ok(buf);
}
}
Err(())
}
pub fn first_child(&mut self) -> Option<&'a [u8]> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_properties();
let child_name = t.next_subnode()?;
self.data = t.cur;
Some(child_name)
}
pub fn next_sibling(&mut self) -> Option<&'a [u8]> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_node()?;
let sibling_name = t.next_subnode()?;
self.data = t.cur;
Some(sibling_name)
}
pub fn find_child(&mut self, child: *const u8) -> Option<()> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_properties();
while let Some(name) = t.next_subnode() {
if unsafe { strcmp(name.as_ptr(), child) } == 0 {
self.data = t.cur;
return Some(());
}
t.skip_node();
}
None
}
}
impl FdtHeader {
pub unsafe fn dump(&self) {
unsafe fn asciz_to_utf8(ptr: *const u8) -> &'static str {
let len = (0..).find(|i| *ptr.add(*i) != 0).unwrap();
let bytes = slice::from_raw_parts(ptr, len);
str::from_utf8_unchecked(bytes)
}
// Traverse the whole thing.
let node = some_or!(FdtNode::new_root(self), {
dlog!("FDT failed validation.\n");
return;
});
let mut t = FdtTokenizer::new(node.data, node.strs);
let mut depth = 0;
loop {
while let Some(name) = t.next_subnode() {
dlog!(
"{:1$}New node: \"{2}\"\n",
"",
2 * depth,
str::from_utf8_unchecked(name)
);
depth += 1;
while let Some((name, buf)) = t.next_property() {
dlog!(
"{:1$}property: \"{2}\" (",
"",
2 * depth,
asciz_to_utf8(name)
);
for (i, byte) in buf.iter().enumerate() {
dlog!("{}{:02x}", if i == 0 { "" } else { " " }, *byte);
}
dlog!(")\n");
}
}
if t.token().filter(|t| *t != FdtToken::EndNode).is_none() {
return;
}
depth -= 1;
if depth == 0 {
break;
}
}
dlog!(
"fdt: off_mem_rsvmap={}\n",
u32::from_be(self.off_mem_rsvmap)
);
let mut entry = (self as *const _ as usize + u32::from_be(self.off_mem_rsvmap) as usize)
as *const FdtReserveEntry;
while (*entry).address != 0 || (*entry).size != 0 {
dlog!(
"Entry: {:p} (0x{:x} bytes)\n",
u64::from_be((*entry).address) as *const u8,
u64::from_be((*entry).size)
);
entry = entry.add(1);
}
}
pub unsafe fn add_mem_reservation(&mut self, addr: u64, len: u64) {
// TODO: Clean this up.
let begin =
(self as *const _ as usize as *mut u8).add(u32::from_be(self.off_mem_rsvmap) as usize);
let e = begin as *mut FdtReserveEntry;
let old_size = (u32::from_be(self.totalsize) - u32::from_be(self.off_mem_rsvmap)) as usize;
self.totalsize =
(u32::from_be(self.totalsize) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
self.off_dt_struct =
(u32::from_be(self.off_dt_struct) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
self.off_dt_strings =
(u32::from_be(self.off_dt_strings) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
ptr::copy(
begin,
begin.add(mem::size_of::<FdtReserveEntry>()),
old_size,
);
(*e).address = addr.to_be();
(*e).size = len.to_be();
}
pub fn total_size(&self) -> u32 {
u32::from_be(self.totalsize)
}
}
#[no_mangle]
pub unsafe extern "C" fn fdt_root_node(node: *mut fdt_node, hdr: *const FdtHeader) -> bool {
let n = some_or!(FdtNode::new_root(&*hdr), return false);
ptr::write(node, n.into());
true
}
#[no_mangle]
pub unsafe extern "C" fn fdt_find_child(c_node: *mut fdt_node, child: *const u8) -> bool {
let mut node = FdtNode::from((*c_node).clone());
let ret = node.find_child(child).is_some();
ptr::write(c_node, node.into());
ret
}
#[no_mangle]
pub unsafe extern "C" fn fdt_read_property(
node: *const fdt_node,
name: *const u8,
buf: *mut *const u8,
size: *mut u32,
) -> bool {
let prop_buf = ok_or!(
FdtNode::from((*node).clone()).read_property(name),
return false
);
ptr::write(buf, prop_buf.as_ptr());
ptr::write(size, prop_buf.len() as u32);
true
}
#[cfg(test)]
mod test {
use super::*;
static TEST_DTB: [u8; 12 * 27] = [
0xd0, 0x0d, 0xfe, 0xed, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x01,
0x08, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x00, 0x53, 0x6f, 0x6d, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x4e, 0x6f, 0x74, 0x68, 0x69,
0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79,
0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00,
0x00, 0x00, 0x2c, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00,
0x00, 0x01, 0x63, 0x70, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03,
0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x00,
0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x00, 0x23, 0x61, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x2d, 0x63, 0x65, 0x6c, 0x6c, 0x73, 0x00, 0x23, 0x73, 0x69, 0x7a,
0x65, 0x2d, 0x63, 0x65, 0x6c, 0x6c, 0x73, 0x00, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x5f,
0x74, 0x79, 0x70, 0x65, 0x00, 0x72, 0x65, 0x67, 0x00,
];
#[test]
fn total_size() {
let header = (&TEST_DTB[..]).as_ptr() as usize as *const FdtHeader;
assert_eq!(
unsafe { (*header).total_size() } as usize,
mem::size_of_val(&TEST_DTB)
);
}
}
`FdtNode::u32` now uses `FdtNode::bytes`.
/*
* Copyright 2019 Sanguk Park.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use core::convert::{TryFrom, TryInto};
use core::mem;
use core::ptr;
use core::slice;
use core::str;
use scopeguard::guard;
/// TODO(HfO2): port this function into `std.rs` (#48.)
extern "C" {
fn strcmp(a: *const u8, b: *const u8) -> i64;
}
#[derive(Clone)]
#[repr(C)]
pub struct fdt_node {
hdr: *const FdtHeader,
begin: *const u8,
end: *const u8,
strs: *const u8,
}
#[derive(Clone)]
pub struct FdtNode<'a> {
hdr: &'a FdtHeader,
data: &'a [u8],
strs: &'a [u8],
}
impl<'a> From<fdt_node> for FdtNode<'a> {
fn from(n: fdt_node) -> Self {
unsafe {
let hdr = &*n.hdr;
let data_size = u32::from_be(hdr.size_dt_struct) as usize;
let strs_size = u32::from_be(hdr.size_dt_strings) as usize;
Self {
hdr,
data: slice::from_raw_parts(n.begin, data_size),
strs: slice::from_raw_parts(n.strs, strs_size),
}
}
}
}
impl<'a> From<FdtNode<'a>> for fdt_node {
fn from(n: FdtNode<'a>) -> Self {
Self {
hdr: n.hdr,
begin: n.data.as_ptr(),
end: unsafe { n.data.as_ptr().add(n.data.len()) },
strs: n.strs.as_ptr(),
}
}
}
#[repr(C)]
pub struct FdtHeader {
magic: u32,
totalsize: u32,
off_dt_struct: u32,
off_dt_strings: u32,
off_mem_rsvmap: u32,
version: u32,
last_comp_version: u32,
boot_cpuid_phys: u32,
size_dt_strings: u32,
size_dt_struct: u32,
}
struct FdtReserveEntry {
address: u64,
size: u64,
}
#[derive(PartialEq, Clone, Copy)]
enum FdtToken {
BeginNode = 1,
EndNode = 2,
Prop = 3,
Nop = 4,
End = 9,
}
impl TryFrom<u32> for FdtToken {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
use FdtToken::*;
match value {
1 => Ok(BeginNode),
2 => Ok(EndNode),
3 => Ok(Prop),
4 => Ok(Nop),
9 => Ok(End),
_ => Err(()),
}
}
}
struct FdtTokenizer<'a> {
cur: &'a [u8],
strs: &'a [u8],
}
const FDT_VERSION: u32 = 17;
const FDT_MAGIC: u32 = 0xd00d_feed;
const FDT_TOKEN_ALIGNMENT: usize = mem::size_of::<u32>();
impl<'a> FdtTokenizer<'a> {
fn new(cur: &'a [u8], strs: &'a [u8]) -> Self {
Self { cur, strs }
}
fn align(&mut self) {
let modular = self.cur.as_ptr() as usize % FDT_TOKEN_ALIGNMENT;
let (_, cur) = self
.cur
.split_at((FDT_TOKEN_ALIGNMENT - modular) % FDT_TOKEN_ALIGNMENT);
self.cur = cur;
}
fn bytes(&mut self, size: usize) -> Option<&'a [u8]> {
if self.cur.len() < size {
return None;
}
let (first, rest) = self.cur.split_at(size);
self.cur = rest;
self.align();
Some(first)
}
fn bytes_filter<F>(&mut self, size: usize, pred: F) -> Option<&'a [u8]>
where
F: FnOnce(&'a [u8]) -> bool,
{
if self.cur.len() < size {
return None;
}
let (first, rest) = self.cur.split_at(size);
if !pred(first) {
return None;
}
self.cur = rest;
self.align();
Some(first)
}
fn u32(&mut self) -> Option<u32> {
let bytes = self.bytes(mem::size_of::<u32>())?;
Some(u32::from_be_bytes(bytes.try_into().unwrap()))
}
fn u32_expect(&mut self, expect: u32) -> Option<u32> {
let bytes = self.bytes_filter(mem::size_of::<u32>(), |b| b == expect.to_be_bytes())?;
Some(u32::from_be_bytes(bytes.try_into().unwrap()))
}
fn token(&mut self) -> Option<FdtToken> {
while let Some(v) = self.u32() {
let token = v.try_into().unwrap();
if token != FdtToken::Nop {
return Some(token);
}
}
None
}
fn token_expect(&mut self, expect: FdtToken) -> Option<FdtToken> {
while let Some(v) = self.u32_expect(expect as u32) {
let token = v.try_into().unwrap();
if token != FdtToken::Nop {
return Some(token);
}
}
None
}
fn str(&mut self) -> Option<&'a [u8]> {
let (i, _) = self.cur.iter().enumerate().find(|(_, p)| **p == 0)?;
// Found the end of the string.
let (first, rest) = self.cur.split_at(i + 1);
self.cur = rest;
self.align();
Some(first)
}
/// Move cursor to the end so that caller won't get any new tokens.
fn collapse(&mut self) {
self.cur = &self.cur[self.cur.len()..];
}
fn next_property(&mut self) -> Option<(*const u8, &'a [u8])> {
self.token_expect(FdtToken::Prop)?;
let mut this = guard(self, |this| {
this.collapse();
});
let size = this.u32()? as usize;
let nameoff = this.u32()? as usize;
let buf = this.bytes(size)?;
//TODO: Need to verify the strings.
let name = this.strs[nameoff..].as_ptr();
mem::forget(this);
Some((name, buf))
}
fn next_subnode(&mut self) -> Option<&'a [u8]> {
self.token_expect(FdtToken::BeginNode)?;
let name = some_or!(self.str(), {
self.collapse();
return None;
});
Some(name)
}
fn skip_properties(&mut self) {
while self.next_property().is_some() {}
}
fn skip_node(&mut self) -> Option<()> {
let mut pending = 1;
self.skip_properties();
while pending != 0 {
while let Some(_) = self.next_subnode() {
self.skip_properties();
pending += 1;
}
if self.token()? != FdtToken::EndNode {
self.collapse();
return None;
}
pending -= 1;
}
Some(())
}
}
impl<'a> FdtNode<'a> {
pub fn new_root(hdr: &'a FdtHeader) -> Option<Self> {
// Check the magic number before anything else.
if hdr.magic != u32::from_be(FDT_MAGIC) {
return None;
}
// Check the version.
let max_ver = u32::from_be(hdr.version);
let min_ver = u32::from_be(hdr.last_comp_version);
if FDT_VERSION < min_ver || FDT_VERSION > max_ver {
return None;
}
let hdr_ptr = hdr as *const _ as *const u8;
let data_begin = u32::from_be(hdr.off_dt_struct) as usize;
let data_size = u32::from_be(hdr.size_dt_struct) as usize;
let strs_begin = u32::from_be(hdr.off_dt_strings) as usize;
let strs_size = u32::from_be(hdr.size_dt_strings) as usize;
// TODO: Verify that it is all within the fdt.
// TODO: Verify strings as well.
Some(FdtNode {
hdr,
data: unsafe { slice::from_raw_parts(hdr_ptr.add(data_begin), data_size) },
strs: unsafe { slice::from_raw_parts(hdr_ptr.add(strs_begin), strs_size) },
})
}
pub fn read_property(&self, name: *const u8) -> Result<&'a [u8], ()> {
let mut t = FdtTokenizer::new(self.data, self.strs);
while let Some((prop_name, buf)) = t.next_property() {
if unsafe { strcmp(prop_name, name) } == 0 {
return Ok(buf);
}
}
Err(())
}
pub fn first_child(&mut self) -> Option<&'a [u8]> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_properties();
let child_name = t.next_subnode()?;
self.data = t.cur;
Some(child_name)
}
pub fn next_sibling(&mut self) -> Option<&'a [u8]> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_node()?;
let sibling_name = t.next_subnode()?;
self.data = t.cur;
Some(sibling_name)
}
pub fn find_child(&mut self, child: *const u8) -> Option<()> {
let mut t = FdtTokenizer::new(self.data, self.strs);
t.skip_properties();
while let Some(name) = t.next_subnode() {
if unsafe { strcmp(name.as_ptr(), child) } == 0 {
self.data = t.cur;
return Some(());
}
t.skip_node();
}
None
}
}
impl FdtHeader {
pub unsafe fn dump(&self) {
unsafe fn asciz_to_utf8(ptr: *const u8) -> &'static str {
let len = (0..).find(|i| *ptr.add(*i) != 0).unwrap();
let bytes = slice::from_raw_parts(ptr, len);
str::from_utf8_unchecked(bytes)
}
// Traverse the whole thing.
let node = some_or!(FdtNode::new_root(self), {
dlog!("FDT failed validation.\n");
return;
});
let mut t = FdtTokenizer::new(node.data, node.strs);
let mut depth = 0;
loop {
while let Some(name) = t.next_subnode() {
dlog!(
"{:1$}New node: \"{2}\"\n",
"",
2 * depth,
str::from_utf8_unchecked(name)
);
depth += 1;
while let Some((name, buf)) = t.next_property() {
dlog!(
"{:1$}property: \"{2}\" (",
"",
2 * depth,
asciz_to_utf8(name)
);
for (i, byte) in buf.iter().enumerate() {
dlog!("{}{:02x}", if i == 0 { "" } else { " " }, *byte);
}
dlog!(")\n");
}
}
if t.token().filter(|t| *t != FdtToken::EndNode).is_none() {
return;
}
depth -= 1;
if depth == 0 {
break;
}
}
dlog!(
"fdt: off_mem_rsvmap={}\n",
u32::from_be(self.off_mem_rsvmap)
);
let mut entry = (self as *const _ as usize + u32::from_be(self.off_mem_rsvmap) as usize)
as *const FdtReserveEntry;
while (*entry).address != 0 || (*entry).size != 0 {
dlog!(
"Entry: {:p} (0x{:x} bytes)\n",
u64::from_be((*entry).address) as *const u8,
u64::from_be((*entry).size)
);
entry = entry.add(1);
}
}
pub unsafe fn add_mem_reservation(&mut self, addr: u64, len: u64) {
// TODO: Clean this up.
let begin =
(self as *const _ as usize as *mut u8).add(u32::from_be(self.off_mem_rsvmap) as usize);
let e = begin as *mut FdtReserveEntry;
let old_size = (u32::from_be(self.totalsize) - u32::from_be(self.off_mem_rsvmap)) as usize;
self.totalsize =
(u32::from_be(self.totalsize) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
self.off_dt_struct =
(u32::from_be(self.off_dt_struct) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
self.off_dt_strings =
(u32::from_be(self.off_dt_strings) + mem::size_of::<FdtReserveEntry>() as u32).to_be();
ptr::copy(
begin,
begin.add(mem::size_of::<FdtReserveEntry>()),
old_size,
);
(*e).address = addr.to_be();
(*e).size = len.to_be();
}
pub fn total_size(&self) -> u32 {
u32::from_be(self.totalsize)
}
}
#[no_mangle]
pub unsafe extern "C" fn fdt_root_node(node: *mut fdt_node, hdr: *const FdtHeader) -> bool {
let n = some_or!(FdtNode::new_root(&*hdr), return false);
ptr::write(node, n.into());
true
}
#[no_mangle]
pub unsafe extern "C" fn fdt_find_child(c_node: *mut fdt_node, child: *const u8) -> bool {
let mut node = FdtNode::from((*c_node).clone());
let ret = node.find_child(child).is_some();
ptr::write(c_node, node.into());
ret
}
#[no_mangle]
pub unsafe extern "C" fn fdt_read_property(
node: *const fdt_node,
name: *const u8,
buf: *mut *const u8,
size: *mut u32,
) -> bool {
let prop_buf = ok_or!(
FdtNode::from((*node).clone()).read_property(name),
return false
);
ptr::write(buf, prop_buf.as_ptr());
ptr::write(size, prop_buf.len() as u32);
true
}
#[cfg(test)]
mod test {
use super::*;
static TEST_DTB: [u8; 12 * 27] = [
0xd0, 0x0d, 0xfe, 0xed, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x01,
0x08, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x00, 0x53, 0x6f, 0x6d, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x4e, 0x6f, 0x74, 0x68, 0x69,
0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79,
0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00,
0x00, 0x00, 0x2c, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00,
0x00, 0x01, 0x63, 0x70, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03,
0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x00,
0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x00, 0x23, 0x61, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x2d, 0x63, 0x65, 0x6c, 0x6c, 0x73, 0x00, 0x23, 0x73, 0x69, 0x7a,
0x65, 0x2d, 0x63, 0x65, 0x6c, 0x6c, 0x73, 0x00, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x5f,
0x74, 0x79, 0x70, 0x65, 0x00, 0x72, 0x65, 0x67, 0x00,
];
#[test]
fn total_size() {
let header = (&TEST_DTB[..]).as_ptr() as usize as *const FdtHeader;
assert_eq!(
unsafe { (*header).total_size() } as usize,
mem::size_of_val(&TEST_DTB)
);
}
}
|
// (c) 2016 Joost Yervante Damad <joost@productize.be>
use std::fmt;
use std::path::PathBuf;
// from parent
use ERes;
use err;
use read_file;
use footprint;
extern crate rustysexp;
use self::rustysexp::Sexp;
pub struct Layout {
pub version:i64,
pub elements:Vec<Element>,
}
#[derive(Clone)]
pub enum Element {
Module(footprint::Module),
Net(Net),
NetClass(NetClass),
Other(Sexp),
}
#[derive(Clone,PartialEq)]
pub struct Net {
pub num:i64,
pub name:String,
}
#[derive(Clone,PartialEq)]
pub struct NetClass {
pub name:String,
pub desc:String,
pub clearance:f64,
pub trace_width:f64,
pub via_dia:f64,
pub via_drill:f64,
pub uvia_dia:f64,
pub uvia_drill:f64,
pub nets:Vec<String>,
}
impl Layout {
fn new() -> Layout {
Layout {
version:0,
elements:vec![],
}
}
pub fn modify_module<F>(&mut self, reference:&String, fun:F) -> ERes<()>
where F:Fn(&mut footprint::Module) -> ()
{
for ref mut x in &mut self.elements[..] {
match **x {
Element::Module(ref mut m) => {
if m.is_reference(reference) {
return Ok(fun(m))
}
},
Element::Net(_) => (),
Element::NetClass(_) => (),
Element::Other(_) => (),
}
}
Err(format!("did not find module with reference {}", reference))
}
}
impl fmt::Display for Layout {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(writeln!(f, "(kicad_pcb (version {})", self.version));
for element in &self.elements[..] {
try!(writeln!(f, " {}", element));
try!(writeln!(f, ""));
}
writeln!(f, ")")
}
}
impl fmt::Display for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Element::Other(ref s) => write!(f, "{}", s),
Element::Module(ref s) => write!(f, "{}", s),
Element::Net(ref s) => write!(f, "{}", s),
Element::NetClass(ref s) => write!(f, "{}", s),
}
}
}
impl fmt::Display for Net {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if self.name.contains("(") || self.name.contains(")") || self.name.len()==0 {
write!(f, "(net {} \"{}\")", self.num, self.name)
} else {
write!(f, "(net {} {})", self.num, self.name)
}
}
}
impl fmt::Display for NetClass {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "(net_class {} \"{}\" ", self.name, self.desc));
try!(write!(f, "(clearance {}) ", self.clearance));
try!(write!(f, "(trace_width {}) ", self.trace_width));
try!(write!(f, "(via_dia {}) ", self.via_dia));
try!(write!(f, "(via_drill {}) ", self.via_drill));
try!(write!(f, "(uvia_dia {}) ", self.uvia_dia));
try!(write!(f, "(uvia_drill {}) ", self.uvia_drill));
for net in &self.nets {
if net.contains("(") || net.contains(")") {
try!(write!(f, "(add_net \"{}\")", net))
} else {
try!(write!(f, "(add_net {})", net))
}
}
write!(f, ")")
}
}
fn parse_version(e:&Sexp) -> ERes<i64> {
let l = try!(e.slice_atom("version"));
l[0].i()
}
fn parse_other(e:&Sexp) -> Element {
let e2 = e.clone();
Element::Other(e2)
}
fn parse_module(e:&Sexp) -> ERes<Element> {
let e2 = e.clone();
let m = try!(footprint::parse_module(e2));
Ok(Element::Module(m))
}
fn parse_net(e:&Sexp) -> ERes<Element> {
let l = try!(e.slice_atom("net"));
let num = try!(l[0].i());
let name = try!(l[1].string()).clone();
Ok(Element::Net(Net { name:name, num:num }))
}
fn parse_net_class(e:&Sexp) -> ERes<Element> {
fn parse(e:&Sexp, name:&str) -> ERes<f64> {
let l = try!(e.slice_atom(name));
l[0].f()
}
let l = try!(e.slice_atom("net_class"));
let name = try!(l[0].string()).clone();
let desc = try!(l[1].string()).clone();
let mut clearance = 0.1524;
let mut trace_width = 0.2032;
let mut via_dia = 0.675;
let mut via_drill = 0.25;
let mut uvia_dia = 0.508;
let mut uvia_drill = 0.127;
let mut nets = vec![];
for x in &l[2..] {
let list_name = try!(x.list_name());
let xn = &list_name[..];
match xn {
"add_net" => {
let l1 = try!(x.slice_atom("add_net"));
nets.push(try!(l1[0].string()).clone())
},
"clearance" => clearance = try!(parse(x, xn)),
"trace_width" => trace_width = try!(parse(x, xn)),
"via_dia" => via_dia = try!(parse(x, xn)),
"via_drill" => via_drill = try!(parse(x, xn)),
"uvia_dia" => uvia_dia = try!(parse(x, xn)),
"uvia_drill" => uvia_drill = try!(parse(x, xn)),
_ => return Err(format!("unknown net_class field {}", list_name))
}
}
let net_class = NetClass {
name:name, desc:desc, clearance:clearance, via_dia:via_dia,
via_drill:via_drill, uvia_dia:uvia_dia, uvia_drill:uvia_drill,
nets:nets, trace_width:trace_width,
};
Ok(Element::NetClass(net_class))
}
fn parse(s: &str) -> ERes<Layout> {
let exp = match rustysexp::parse_str(s) {
Ok(s) => s,
Err(x) => return Err(format!("ParseError: {}", x)),
};
let l1 = try!(exp.slice_atom("kicad_pcb"));
let mut layout = Layout::new();
for ref e in l1 {
match &try!(e.list_name())[..] {
"version" => layout.version = try!(parse_version(e)),
"module" => layout.elements.push(try!(parse_module(e))),
"net" => layout.elements.push(try!(parse_net(e))),
"net_class" => layout.elements.push(try!(parse_net_class(e))),
_ => layout.elements.push(parse_other(e)),
}
}
Ok(layout)
}
pub fn parse_str(s: &str) -> ERes<Layout> {
parse(s)
}
pub fn parse_file(filename: &PathBuf) -> ERes<Layout> {
let name = filename.to_str().unwrap();
let s = try!(match read_file(name) {
Ok(s) => Ok(s),
Err(x) => Err(format!("io error: {}", x))
});
parse(&s[..])
}
make Layout::new pub
// (c) 2016 Joost Yervante Damad <joost@productize.be>
use std::fmt;
use std::path::PathBuf;
// from parent
use ERes;
use err;
use read_file;
use footprint;
extern crate rustysexp;
use self::rustysexp::Sexp;
pub struct Layout {
pub version:i64,
pub elements:Vec<Element>,
}
#[derive(Clone)]
pub enum Element {
Module(footprint::Module),
Net(Net),
NetClass(NetClass),
Other(Sexp),
}
#[derive(Clone,PartialEq)]
pub struct Net {
pub num:i64,
pub name:String,
}
#[derive(Clone,PartialEq)]
pub struct NetClass {
pub name:String,
pub desc:String,
pub clearance:f64,
pub trace_width:f64,
pub via_dia:f64,
pub via_drill:f64,
pub uvia_dia:f64,
pub uvia_drill:f64,
pub nets:Vec<String>,
}
impl Layout {
pub fn new() -> Layout {
Layout {
version:0,
elements:vec![],
}
}
pub fn modify_module<F>(&mut self, reference:&String, fun:F) -> ERes<()>
where F:Fn(&mut footprint::Module) -> ()
{
for ref mut x in &mut self.elements[..] {
match **x {
Element::Module(ref mut m) => {
if m.is_reference(reference) {
return Ok(fun(m))
}
},
Element::Net(_) => (),
Element::NetClass(_) => (),
Element::Other(_) => (),
}
}
Err(format!("did not find module with reference {}", reference))
}
}
impl fmt::Display for Layout {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(writeln!(f, "(kicad_pcb (version {})", self.version));
for element in &self.elements[..] {
try!(writeln!(f, " {}", element));
try!(writeln!(f, ""));
}
writeln!(f, ")")
}
}
impl fmt::Display for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Element::Other(ref s) => write!(f, "{}", s),
Element::Module(ref s) => write!(f, "{}", s),
Element::Net(ref s) => write!(f, "{}", s),
Element::NetClass(ref s) => write!(f, "{}", s),
}
}
}
impl fmt::Display for Net {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if self.name.contains("(") || self.name.contains(")") || self.name.len()==0 {
write!(f, "(net {} \"{}\")", self.num, self.name)
} else {
write!(f, "(net {} {})", self.num, self.name)
}
}
}
impl fmt::Display for NetClass {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "(net_class {} \"{}\" ", self.name, self.desc));
try!(write!(f, "(clearance {}) ", self.clearance));
try!(write!(f, "(trace_width {}) ", self.trace_width));
try!(write!(f, "(via_dia {}) ", self.via_dia));
try!(write!(f, "(via_drill {}) ", self.via_drill));
try!(write!(f, "(uvia_dia {}) ", self.uvia_dia));
try!(write!(f, "(uvia_drill {}) ", self.uvia_drill));
for net in &self.nets {
if net.contains("(") || net.contains(")") {
try!(write!(f, "(add_net \"{}\")", net))
} else {
try!(write!(f, "(add_net {})", net))
}
}
write!(f, ")")
}
}
fn parse_version(e:&Sexp) -> ERes<i64> {
let l = try!(e.slice_atom("version"));
l[0].i()
}
fn parse_other(e:&Sexp) -> Element {
let e2 = e.clone();
Element::Other(e2)
}
fn parse_module(e:&Sexp) -> ERes<Element> {
let e2 = e.clone();
let m = try!(footprint::parse_module(e2));
Ok(Element::Module(m))
}
fn parse_net(e:&Sexp) -> ERes<Element> {
let l = try!(e.slice_atom("net"));
let num = try!(l[0].i());
let name = try!(l[1].string()).clone();
Ok(Element::Net(Net { name:name, num:num }))
}
fn parse_net_class(e:&Sexp) -> ERes<Element> {
fn parse(e:&Sexp, name:&str) -> ERes<f64> {
let l = try!(e.slice_atom(name));
l[0].f()
}
let l = try!(e.slice_atom("net_class"));
let name = try!(l[0].string()).clone();
let desc = try!(l[1].string()).clone();
let mut clearance = 0.1524;
let mut trace_width = 0.2032;
let mut via_dia = 0.675;
let mut via_drill = 0.25;
let mut uvia_dia = 0.508;
let mut uvia_drill = 0.127;
let mut nets = vec![];
for x in &l[2..] {
let list_name = try!(x.list_name());
let xn = &list_name[..];
match xn {
"add_net" => {
let l1 = try!(x.slice_atom("add_net"));
nets.push(try!(l1[0].string()).clone())
},
"clearance" => clearance = try!(parse(x, xn)),
"trace_width" => trace_width = try!(parse(x, xn)),
"via_dia" => via_dia = try!(parse(x, xn)),
"via_drill" => via_drill = try!(parse(x, xn)),
"uvia_dia" => uvia_dia = try!(parse(x, xn)),
"uvia_drill" => uvia_drill = try!(parse(x, xn)),
_ => return Err(format!("unknown net_class field {}", list_name))
}
}
let net_class = NetClass {
name:name, desc:desc, clearance:clearance, via_dia:via_dia,
via_drill:via_drill, uvia_dia:uvia_dia, uvia_drill:uvia_drill,
nets:nets, trace_width:trace_width,
};
Ok(Element::NetClass(net_class))
}
fn parse(s: &str) -> ERes<Layout> {
let exp = match rustysexp::parse_str(s) {
Ok(s) => s,
Err(x) => return Err(format!("ParseError: {}", x)),
};
let l1 = try!(exp.slice_atom("kicad_pcb"));
let mut layout = Layout::new();
for ref e in l1 {
match &try!(e.list_name())[..] {
"version" => layout.version = try!(parse_version(e)),
"module" => layout.elements.push(try!(parse_module(e))),
"net" => layout.elements.push(try!(parse_net(e))),
"net_class" => layout.elements.push(try!(parse_net_class(e))),
_ => layout.elements.push(parse_other(e)),
}
}
Ok(layout)
}
pub fn parse_str(s: &str) -> ERes<Layout> {
parse(s)
}
pub fn parse_file(filename: &PathBuf) -> ERes<Layout> {
let name = filename.to_str().unwrap();
let s = try!(match read_file(name) {
Ok(s) => Ok(s),
Err(x) => Err(format!("io error: {}", x))
});
parse(&s[..])
}
|
import std.os.libc;
import std._str;
import std._vec;
type stdio_reader = state obj {
fn getc() -> int;
fn ungetc(int i);
};
fn new_stdio_reader(str path) -> stdio_reader {
state obj stdio_FILE_reader(os.libc.FILE f) {
fn getc() -> int {
ret os.libc.fgetc(f);
}
fn ungetc(int i) {
os.libc.ungetc(i, f);
}
drop {
os.libc.fclose(f);
}
}
auto FILE = os.libc.fopen(_str.buf(path), _str.buf("r"));
check (FILE as uint != 0u);
ret stdio_FILE_reader(FILE);
}
type buf_reader = state obj {
fn read() -> vec[u8];
};
type buf_writer = state obj {
fn write(vec[u8] v);
};
fn default_bufsz() -> uint {
ret 4096u;
}
fn new_buf() -> vec[u8] {
ret _vec.alloc[u8](default_bufsz());
}
fn new_buf_reader(str path) -> buf_reader {
state obj fd_buf_reader(int fd, mutable vec[u8] buf) {
fn read() -> vec[u8] {
// Ensure our buf is singly-referenced.
if (_vec.rustrt.refcount[u8](buf) != 1u) {
buf = new_buf();
}
auto len = default_bufsz();
auto vbuf = _vec.buf[u8](buf);
auto count = os.libc.read(fd, vbuf, len);
if (count < 0) {
log "error filling buffer";
log sys.rustrt.last_os_error();
fail;
}
_vec.len_set[u8](buf, count as uint);
ret buf;
}
drop {
os.libc.close(fd);
}
}
auto fd = os.libc.open(_str.buf(path),
os.libc_constants.O_RDONLY() |
os.libc_constants.O_BINARY(),
0u);
if (fd < 0) {
log "error opening file for reading";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_reader(fd, new_buf());
}
tag fileflag {
append;
create;
truncate;
}
fn writefd(int fd, vec[u8] v) {
auto len = _vec.len[u8](v);
auto count = 0u;
auto vbuf;
while (count < len) {
vbuf = _vec.buf_off[u8](v, count);
auto nout = os.libc.write(fd, vbuf, len);
if (nout < 0) {
log "error dumping buffer";
log sys.rustrt.last_os_error();
fail;
}
count += nout as uint;
}
}
fn new_buf_writer(str path, vec[fileflag] flags) -> buf_writer {
state obj fd_buf_writer(int fd) {
fn write(vec[u8] v) {
writefd(fd, v);
}
drop {
os.libc.close(fd);
}
}
let int fflags =
os.libc_constants.O_WRONLY() |
os.libc_constants.O_BINARY();
for (fileflag f in flags) {
alt (f) {
case (append) { fflags |= os.libc_constants.O_APPEND(); }
case (create) { fflags |= os.libc_constants.O_CREAT(); }
case (truncate) { fflags |= os.libc_constants.O_TRUNC(); }
}
}
auto fd = os.libc.open(_str.buf(path),
fflags,
os.libc_constants.S_IRUSR() |
os.libc_constants.S_IWUSR());
if (fd < 0) {
log "error opening file for writing";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_writer(fd);
}
type writer =
state obj {
fn write_str(str s);
fn write_int(int n);
fn write_uint(uint n);
};
fn file_writer(str path,
vec[fileflag] flags)
-> writer
{
state obj fw(buf_writer out) {
fn write_str(str s) { out.write(_str.bytes(s)); }
fn write_int(int n) { out.write(_str.bytes(_int.to_str(n, 10u))); }
fn write_uint(uint n) { out.write(_str.bytes(_uint.to_str(n, 10u))); }
}
ret fw(new_buf_writer(path, flags));
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
Add stdout_writer and string_writer to std.io
For use by pretty-printer. string_writer API is a bit silly
right now, feel free to suggest a cleaner way to do this.
import std.os.libc;
import std._str;
import std._vec;
type stdio_reader = state obj {
fn getc() -> int;
fn ungetc(int i);
};
fn new_stdio_reader(str path) -> stdio_reader {
state obj stdio_FILE_reader(os.libc.FILE f) {
fn getc() -> int {
ret os.libc.fgetc(f);
}
fn ungetc(int i) {
os.libc.ungetc(i, f);
}
drop {
os.libc.fclose(f);
}
}
auto FILE = os.libc.fopen(_str.buf(path), _str.buf("r"));
check (FILE as uint != 0u);
ret stdio_FILE_reader(FILE);
}
type buf_reader = state obj {
fn read() -> vec[u8];
};
type buf_writer = state obj {
fn write(vec[u8] v);
};
fn default_bufsz() -> uint {
ret 4096u;
}
fn new_buf() -> vec[u8] {
ret _vec.alloc[u8](default_bufsz());
}
fn new_buf_reader(str path) -> buf_reader {
state obj fd_buf_reader(int fd, mutable vec[u8] buf) {
fn read() -> vec[u8] {
// Ensure our buf is singly-referenced.
if (_vec.rustrt.refcount[u8](buf) != 1u) {
buf = new_buf();
}
auto len = default_bufsz();
auto vbuf = _vec.buf[u8](buf);
auto count = os.libc.read(fd, vbuf, len);
if (count < 0) {
log "error filling buffer";
log sys.rustrt.last_os_error();
fail;
}
_vec.len_set[u8](buf, count as uint);
ret buf;
}
drop {
os.libc.close(fd);
}
}
auto fd = os.libc.open(_str.buf(path),
os.libc_constants.O_RDONLY() |
os.libc_constants.O_BINARY(),
0u);
if (fd < 0) {
log "error opening file for reading";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_reader(fd, new_buf());
}
tag fileflag {
append;
create;
truncate;
}
// FIXME move into fd_buf_writer
fn writefd(int fd, vec[u8] v) {
auto len = _vec.len[u8](v);
auto count = 0u;
auto vbuf;
while (count < len) {
vbuf = _vec.buf_off[u8](v, count);
auto nout = os.libc.write(fd, vbuf, len);
if (nout < 0) {
log "error dumping buffer";
log sys.rustrt.last_os_error();
fail;
}
count += nout as uint;
}
}
state obj fd_buf_writer(int fd, bool must_close) {
fn write(vec[u8] v) {
writefd(fd, v);
}
drop {
if (must_close) {os.libc.close(fd);}
}
}
fn file_buf_writer(str path, vec[fileflag] flags) -> buf_writer {
let int fflags =
os.libc_constants.O_WRONLY() |
os.libc_constants.O_BINARY();
for (fileflag f in flags) {
alt (f) {
case (append) { fflags |= os.libc_constants.O_APPEND(); }
case (create) { fflags |= os.libc_constants.O_CREAT(); }
case (truncate) { fflags |= os.libc_constants.O_TRUNC(); }
}
}
auto fd = os.libc.open(_str.buf(path),
fflags,
os.libc_constants.S_IRUSR() |
os.libc_constants.S_IWUSR());
if (fd < 0) {
log "error opening file for writing";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_writer(fd, true);
}
type writer =
state obj {
impure fn write_str(str s);
impure fn write_int(int n);
impure fn write_uint(uint n);
};
state obj new_writer(buf_writer out) {
impure fn write_str(str s) { out.write(_str.bytes(s)); }
impure fn write_int(int n) { out.write(_str.bytes(_int.to_str(n, 10u))); }
impure fn write_uint(uint n) { out.write(_str.bytes(_uint.to_str(n, 10u))); }
}
fn file_writer(str path, vec[fileflag] flags) -> writer {
ret new_writer(file_buf_writer(path, flags));
}
// FIXME it would be great if this could be a const named stdout
fn stdout_writer() -> writer {
ret new_writer(fd_buf_writer(1, false));
}
type str_writer =
state obj {
fn get_writer() -> writer;
fn get_str() -> str;
};
type str_buf = @rec(mutable str buf);
// TODO awkward! it's not possible to implement a writer with an extra method
fn string_writer() -> str_writer {
auto buf = @rec(mutable buf = "");
state obj str_writer_writer(str_buf buf) {
impure fn write_str(str s) { buf.buf += s; }
impure fn write_int(int n) { buf.buf += _int.to_str(n, 10u); }
impure fn write_uint(uint n) { buf.buf += _uint.to_str(n, 10u); }
}
state obj str_writer_wrap(writer wr, str_buf buf) {
fn get_writer() -> writer {ret wr;}
fn get_str() -> str {ret buf.buf;}
}
ret str_writer_wrap(str_writer_writer(buf), buf);
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
|
#![cfg(feature = "ds")]
extern crate rusoto_core;
extern crate rusoto_ds;
use rusoto_core::Region;
use rusoto_ds::{
DescribeDirectoriesRequest, DescribeTrustsRequest, DirectoryService, DirectoryServiceClient,
};
#[test]
fn should_describe_trusts() {
let client = DirectoryServiceClient::new(Region::UsEast1);
let request = DescribeTrustsRequest::default();
client.describe_trusts(request).sync().unwrap();
}
#[test]
fn should_describe_directories() {
let client = DirectoryServiceClient::new(Region::UsEast1);
let request = DescribeDirectoriesRequest::default();
client.describe_directories(request).sync().unwrap();
}
fix ds integration tests
#![cfg(feature = "ds")]
extern crate rusoto_core;
extern crate rusoto_ds;
use rusoto_core::Region;
use rusoto_ds::{
DescribeDirectoriesRequest, DescribeTrustsRequest, DirectoryService, DirectoryServiceClient,
};
#[test]
fn should_describe_trusts() {
let client = DirectoryServiceClient::new(Region::UsWest2);
let request = DescribeTrustsRequest::default();
client.describe_trusts(request).sync().unwrap();
}
#[test]
fn should_describe_directories() {
let client = DirectoryServiceClient::new(Region::UsWest2);
let request = DescribeDirectoriesRequest::default();
client.describe_directories(request).sync().unwrap();
}
|
//! # Logger
//!
//! Loggers are thread-safe and reference counted, so can be freely
//! passed around the code.
//!
//! Each logger is built with a set of key-values.
//!
//! Child loggers are build from existing loggers, and copy
//! all the key-values from their parents
//!
//! Loggers form hierarchies sharing a drain. Setting a drain on
//! any logger will change it on all loggers in given hierarchy.
use super::{OwnedKeyValue, Level, BorrowedKeyValue};
use std::sync::Arc;
use std::cell::RefCell;
use std::io;
use drain;
use chrono;
thread_local! {
static TL_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128))
}
// TODO: Implement custom clone, that starts with a new buffer
#[derive(Clone)]
/// Logger
pub struct Logger {
drain: Arc<drain::Drain>,
values: Vec<OwnedKeyValue>,
}
pub trait IntoMsg {
fn as_str(&self) -> &str;
}
/*
impl IntoMsg for str {
fn as_str(&self) -> &str {
self.as_str()
}
}*/
impl<'a> IntoMsg for &'a str {
fn as_str(&self) -> &str {
self
}
}
impl IntoMsg for String {
fn as_str(&self) -> &str {
(self as &String).as_str()
}
}
impl Logger {
/// Build a root logger
///
/// All children and their children and so on form one hierarchy
/// sharing a common drain.
///
/// Use `o!` macro to help build `values`
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let root = slog::Logger::new_root(o!("key1" => "value1", "key2" => "value2"), slog::drain::discard());
/// }
pub fn new_root<D : 'static+drain::Drain+Sized>(values: &[OwnedKeyValue], d : D) -> Logger {
Logger {
drain: Arc::new(d),
values: values.to_vec(),
}
}
/// Build a child logger
///
/// Child logger copies all existing values from the parent.
///
/// All children, their children and so on, form one hierarchy sharing
/// a common drain.
///
/// Use `o!` macro to help build `values`
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::drain::IntoLogger;
///
/// fn main() {
/// let root = slog::drain::discard().into_logger(o!("key1" => "value1", "key2" => "value2"));
/// let log = root.new(o!("key" => "value"));
/// }
pub fn new(&self, values: &[OwnedKeyValue]) -> Logger {
let mut new_values = self.values.clone();
new_values.extend_from_slice(values);
Logger {
drain: self.drain.clone(),
values: new_values,
}
}
/// Log one logging record
///
/// Use specific logging functions instead.
pub fn log(&self, lvl: Level, msg: &IntoMsg, values: &[BorrowedKeyValue]) {
let mut info = RecordInfo::new(lvl, msg);
// By default errors in loggers are ignored
TL_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
let _ = self.drain.log(&mut *buf, &mut info, self.values.as_slice(), values);
// TODO: Double check if this will not zero the old bytes as it costs time
buf.clear();
});
}
/// Log critical level record
///
/// Use `b!` macro to help build `values`
pub fn critical<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Critical, &msg, values);
}
/// Log error level record
///
/// Use `b!` macro to help build `values`
pub fn error<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Error, &msg, values);
}
/// Log warning level record
///
/// Use `b!` macro to help build `values`
pub fn warn<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Warning, &msg, values);
}
/// Log info level record
///
/// Use `b!` macro to help build `values`
pub fn info<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Info, &msg, values);
}
/// Log debug level record
///
/// Use `b!` macro to help build `values`
pub fn debug<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Debug, &msg, values);
}
/// Log trace level record
///
/// Use `b!` macro to help build `values`
pub fn trace<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Trace, &msg, values);
}
}
/// Common information about a logging record
pub struct RecordInfo<'a> {
ts: RefCell<Option<chrono::DateTime<chrono::UTC>>>,
/// Logging level
level: Level,
/// Message
msg: &'a IntoMsg,
}
impl<'a> RecordInfo<'a> {
/// Create a new `RecordInfo` with a current timestamp
pub fn new(level: Level, msg: &'a IntoMsg) -> Self {
RecordInfo {
ts: RefCell::new(None),
level: level,
msg: msg,
}
}
/// Timestamp
///
/// Lazily evaluated timestamp
pub fn ts(&self) -> chrono::DateTime<chrono::UTC> {
let mut ts = self.ts.borrow_mut();
match *ts {
None => {
let now = chrono::UTC::now();
*ts = Some(now);
now
},
Some(ts) => ts
}
}
/// Set timestamp
pub fn set_ts(&self, ts : chrono::DateTime<chrono::UTC>) {
*self.ts.borrow_mut() = Some(ts);
}
/// Get a log record message
pub fn msg(&self) -> &str {
self.msg.as_str()
}
/// Get record logging level
pub fn level(&self) -> Level {
self.level
}
}
Improve abstract of msg
//! # Logger
//!
//! Loggers are thread-safe and reference counted, so can be freely
//! passed around the code.
//!
//! Each logger is built with a set of key-values.
//!
//! Child loggers are build from existing loggers, and copy
//! all the key-values from their parents
//!
//! Loggers form hierarchies sharing a drain. Setting a drain on
//! any logger will change it on all loggers in given hierarchy.
use super::{OwnedKeyValue, Level, BorrowedKeyValue};
use std::sync::Arc;
use std::cell::RefCell;
use std::io;
use drain;
use chrono;
thread_local! {
static TL_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128))
}
// TODO: Implement custom clone, that starts with a new buffer
#[derive(Clone)]
/// Logger
pub struct Logger {
drain: Arc<drain::Drain>,
values: Vec<OwnedKeyValue>,
}
pub trait IntoMsg {
fn as_str(&self) -> &str;
}
impl<T : AsRef<str>> IntoMsg for T {
fn as_str(&self) -> &str {
self.as_ref()
}
}
impl Logger {
/// Build a root logger
///
/// All children and their children and so on form one hierarchy
/// sharing a common drain.
///
/// Use `o!` macro to help build `values`
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let root = slog::Logger::new_root(o!("key1" => "value1", "key2" => "value2"), slog::drain::discard());
/// }
pub fn new_root<D : 'static+drain::Drain+Sized>(values: &[OwnedKeyValue], d : D) -> Logger {
Logger {
drain: Arc::new(d),
values: values.to_vec(),
}
}
/// Build a child logger
///
/// Child logger copies all existing values from the parent.
///
/// All children, their children and so on, form one hierarchy sharing
/// a common drain.
///
/// Use `o!` macro to help build `values`
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::drain::IntoLogger;
///
/// fn main() {
/// let root = slog::drain::discard().into_logger(o!("key1" => "value1", "key2" => "value2"));
/// let log = root.new(o!("key" => "value"));
/// }
pub fn new(&self, values: &[OwnedKeyValue]) -> Logger {
let mut new_values = self.values.clone();
new_values.extend_from_slice(values);
Logger {
drain: self.drain.clone(),
values: new_values,
}
}
/// Log one logging record
///
/// Use specific logging functions instead.
pub fn log(&self, lvl: Level, msg: &IntoMsg, values: &[BorrowedKeyValue]) {
let mut info = RecordInfo::new(lvl, msg);
// By default errors in loggers are ignored
TL_BUF.with(|buf| {
let mut buf = buf.borrow_mut();
let _ = self.drain.log(&mut *buf, &mut info, self.values.as_slice(), values);
// TODO: Double check if this will not zero the old bytes as it costs time
buf.clear();
});
}
/// Log critical level record
///
/// Use `b!` macro to help build `values`
pub fn critical<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Critical, &msg, values);
}
/// Log error level record
///
/// Use `b!` macro to help build `values`
pub fn error<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Error, &msg, values);
}
/// Log warning level record
///
/// Use `b!` macro to help build `values`
pub fn warn<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Warning, &msg, values);
}
/// Log info level record
///
/// Use `b!` macro to help build `values`
pub fn info<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Info, &msg, values);
}
/// Log debug level record
///
/// Use `b!` macro to help build `values`
pub fn debug<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Debug, &msg, values);
}
/// Log trace level record
///
/// Use `b!` macro to help build `values`
pub fn trace<M : IntoMsg>(&self, msg: M, values: &[BorrowedKeyValue]) {
self.log(Level::Trace, &msg, values);
}
}
/// Common information about a logging record
pub struct RecordInfo<'a> {
ts: RefCell<Option<chrono::DateTime<chrono::UTC>>>,
/// Logging level
level: Level,
/// Message
msg: &'a IntoMsg,
}
impl<'a> RecordInfo<'a> {
/// Create a new `RecordInfo` with a current timestamp
pub fn new(level: Level, msg: &'a IntoMsg) -> Self {
RecordInfo {
ts: RefCell::new(None),
level: level,
msg: msg,
}
}
/// Timestamp
///
/// Lazily evaluated timestamp
pub fn ts(&self) -> chrono::DateTime<chrono::UTC> {
let mut ts = self.ts.borrow_mut();
match *ts {
None => {
let now = chrono::UTC::now();
*ts = Some(now);
now
},
Some(ts) => ts
}
}
/// Set timestamp
pub fn set_ts(&self, ts : chrono::DateTime<chrono::UTC>) {
*self.ts.borrow_mut() = Some(ts);
}
/// Get a log record message
pub fn msg(&self) -> &str {
self.msg.as_str()
}
/// Get record logging level
pub fn level(&self) -> Level {
self.level
}
}
|
// Copyright 2017 Dmytro Milinevskyi <dmilinevskyi@gmail.com>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate parking_lot;
use self::parking_lot::RwLock;
extern crate time;
extern crate crossbeam;
use self::crossbeam::sync::MsQueue;
use self::crossbeam::mem::CachePadded;
use std::mem;
use std::sync::{Arc, Once, ONCE_INIT};
use std::sync::atomic::{AtomicIsize, AtomicUsize, AtomicBool, Ordering,
ATOMIC_ISIZE_INIT, ATOMIC_USIZE_INIT, ATOMIC_BOOL_INIT};
use std::collections::BTreeMap;
use std::collections::Bound::{Included, Excluded, Unbounded};
use std::time::Duration;
use std::thread;
use std::fmt;
use std::env;
use levels::LogLevel;
use record::Record;
use record::imp::{SyncRecord, AsyncRecord, RecordMeta};
use line_range::{LineRangeBound, LineRange};
use formatters::Formatter;
use handlers::Handler;
static LOG_LEVEL: AtomicIsize = ATOMIC_ISIZE_INIT;
static HAS_SUBLOGGERS: AtomicBool = ATOMIC_BOOL_INIT;
static LOG_THREAD: AtomicBool = ATOMIC_BOOL_INIT;
static IS_INIT: AtomicBool = ATOMIC_BOOL_INIT;
lazy_static! {
static ref SENT: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
static ref RECEIVED: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
static ref QIDX: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
}
const QNUM: usize = 64;
/// A file-module separator.
///
/// This separator is used to join module and file paths.
#[macro_export]
macro_rules! wp_separator {
() => ('@')
}
struct LevelMeta {
level: LogLevel,
lranges: Vec<LineRange>,
}
type QVec = [MsQueue<AsyncRecord>; QNUM];
#[doc(hidden)]
pub struct RootLogger {
loggers: CachePadded<BTreeMap<String, LevelMeta>>,
formatter: Arc<Formatter>,
handlers: Vec<Handler>,
queue: Arc<QVec>,
}
impl RootLogger {
fn new(queue: Arc<QVec>) -> Self {
RootLogger {
loggers: CachePadded::new(BTreeMap::new()),
formatter: Arc::new(Box::new(::formatters::default::formatter)),
handlers: Vec::new(),
queue: queue,
}
}
fn reset(&mut self) {
self.loggers.clear();
self.formatter = Arc::new(Box::new(::formatters::default::formatter));
self.handlers.clear();
}
#[doc(hidden)]
pub fn reset_loggers(&mut self) {
self.loggers.clear()
}
#[doc(hidden)]
pub fn handler(&mut self, handler: Handler) {
self.handlers.push(handler);
}
#[doc(hidden)]
pub fn formatter(&mut self, formatter: Formatter) {
self.formatter = Arc::new(formatter);
}
fn remove_children(&mut self, path: &str) {
let mut trash = Vec::new();
{
let range = self.loggers.range::<str, _>((Excluded(path), Unbounded));
for (name, _) in range {
if !name.starts_with(path) {
break;
}
trash.push(name.to_string());
}
}
for item in trash {
self.loggers.remove(item.as_str());
}
}
#[doc(hidden)]
pub fn set_level(&mut self, level: LogLevel, path: &str, lranges: Vec<LineRange>) -> Result<(), String> {
if level == LogLevel::UNSUPPORTED {
return Err("Unsupported log level".to_string());
}
if !lranges.is_empty() {
if !path.ends_with("<anon>") && !path.ends_with(".rs") {
return Err("File path not specified".to_string());
}
if path.find(wp_separator!()).is_none() {
return Err("Module not specified".to_string());
}
}
let level = if lranges.is_empty() {
level
} else {
self.get_level(path, LineRangeBound::EOF.into())
};
self.remove_children(path);
let logger = LevelMeta {
level: level,
lranges: lranges,
};
self.loggers.insert(path.to_string(), logger);
global_set_loggers(true);
Ok(())
}
#[doc(hidden)]
#[inline(always)]
pub fn get_level(&self, path: &str, line: u32) -> LogLevel {
let range = self.loggers.range::<str, _>((Unbounded, Included(path)));
for (name, logger) in range.rev() {
if path.starts_with(name) {
if line == LineRangeBound::EOF.into() || logger.lranges.is_empty() {
return logger.level;
}
for range in &logger.lranges {
if line >= range.from && line <= range.to {
return range.level;
}
}
return logger.level;
}
}
global_get_level()
}
#[doc(hidden)]
pub fn log(&self, record: &'static RecordMeta, args: fmt::Arguments) {
let record = SyncRecord::new(record, time::get_time(), args, self.formatter.clone());
if !LOG_THREAD.load(Ordering::Relaxed) {
self.process(&record);
} else {
let record: AsyncRecord = record.into();
let qidx = QIDX.fetch_add(1, Ordering::Relaxed) % QNUM;
self.queue[qidx].push(record);
SENT.fetch_add(1, Ordering::Relaxed);
}
}
#[inline(always)]
fn process(&self, record: &Record) {
if self.handlers.is_empty() {
::handlers::stdout::emit(&record.formatted());
} else {
for h in &self.handlers {
h(record);
}
}
}
}
fn qempty() -> bool {
let sent = SENT.load(Ordering::Relaxed);
let received = RECEIVED.load(Ordering::Relaxed);
sent == received
}
#[doc(hidden)]
#[inline(always)]
pub fn root() -> Arc<RwLock<RootLogger>> {
static mut ROOT: *const Arc<RwLock<RootLogger>> = 0 as *const Arc<RwLock<RootLogger>>;
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
let mut queues: QVec = mem::uninitialized();
for queue in queues.iter_mut() {
let z = mem::replace(queue, MsQueue::new());
mem::forget(z);
}
let queues = Arc::new(queues);
assert!(IS_INIT.load(Ordering::Relaxed));
let root = Arc::new(RwLock::new(RootLogger::new(queues.clone())));
if LOG_THREAD.load(Ordering::Relaxed) {
let root = root.clone();
thread::spawn(move || {
loop {
for queue in queues.iter() {
if let Some(record) = queue.try_pop() {
{
let root = root.read();
root.process(&record);
}
RECEIVED.fetch_add(1, Ordering::Relaxed);
}
}
if qempty() {
thread::yield_now();
}
}
});
}
ROOT = mem::transmute(Box::new(root));
});
(*ROOT).clone()
}
}
/// Ensures that the logging queue is completely consumed by the log thread.
///
/// Normally this should be called in the very end of the program execution
/// to ensure that all log records are properly flushed.
pub fn sync() {
while !qempty() {
thread::sleep(Duration::from_millis(10));
}
}
#[doc(hidden)]
pub fn reset() {
sync();
let root = root();
let mut root = root.write();
global_set_level(LogLevel::WARN);
global_set_loggers(false);
root.reset();
}
fn __init(log_thread: bool) {
let log_thread = match env::var("WP_LOG_THREAD") {
Ok(ref val) => {
let val = &val.to_lowercase()[..1];
val == "y" || val == "1"
}
_ => log_thread,
};
LOG_THREAD.store(log_thread, Ordering::Relaxed);
// NOTE: it's not a real guard.
// The `init` function is supposed to be called once on init.
assert!(!IS_INIT.swap(true, Ordering::Relaxed));
reset();
}
/// Initializes the crate's kitchen.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// info!("Coucou!");
/// }
///
/// ```
pub fn init() {
__init(false);
}
/// Same as [init](fn.init.html) but enables the log thread.
///
/// Consider using [sync](fn.sync.html) to ensure that all log
/// records are properly flushed.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init_with_thread();
///
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// warn!("foo");
/// }
///
/// wp::sync();
///
/// assert_eq!(*out.lock().unwrap(), "foo".to_string());
/// }
///
/// ```
pub fn init_with_thread() {
__init(true);
}
#[doc(hidden)]
#[inline(always)]
pub fn global_get_level() -> LogLevel {
LogLevel::from(LOG_LEVEL.load(Ordering::Relaxed))
}
#[doc(hidden)]
pub fn global_set_level(level: LogLevel) {
LOG_LEVEL.store(level.into(), Ordering::Relaxed);
}
#[doc(hidden)]
#[inline(always)]
pub fn global_has_loggers() -> bool {
HAS_SUBLOGGERS.load(Ordering::Relaxed)
}
#[doc(hidden)]
pub fn global_set_loggers(value: bool) {
HAS_SUBLOGGERS.store(value, Ordering::Relaxed);
}
#[doc(hidden)]
#[macro_export]
macro_rules! __wp_write_root {
($func:ident($($arg:expr),*)) => {{
let root = $crate::logger::root();
$crate::logger::sync();
let mut root = root.write();
root.$func($($arg),*)
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __wp_read_root {
($func:ident($($arg:expr),*)) => {{
let root = $crate::logger::root();
let root = root.read();
root.$func($($arg),*)
}};
}
/// Sets the log level.
///
/// Sets global log level if called without the arguments or
/// according to the specified path otherwise.
///
/// Optionally the ranges of the lines within the file could
/// be given.
/// In this case the full path to the file must be provided.
///
/// See documentation for the [wp_get_level](macro.wp_get_level.html)
/// for more details on the log level hierarchy.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// let logger = "foo::bar";
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// wp_set_level!(wp::LogLevel::CRITICAL, logger).unwrap();
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::CRITICAL);
///
/// wp_set_level!(wp::LogLevel::WARN, this_file!(), [(line!() + 2, wp::EOF)]).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::CRITICAL, this_file!()).unwrap();
/// let ranges = vec![(wp::BOF.into(), line!() + 2), (line!() + 4, wp::EOF.into())];
/// wp_set_level!(wp::LogLevel::WARN, this_file!(), ranges).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
/// assert_eq!(wp_get_level!(), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::TRACE, this_file!(), [(wp::BOF, wp::EOF)]).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::TRACE);
/// }
///
/// ```
#[macro_export]
macro_rules! wp_set_level {
($level:expr, $logger:expr, [$(($from:expr, $to:expr)),*]) => {{
let mut lranges = Vec::new();
$(
let (from, to): (u32, u32) = ($from.into(), $to.into());
lranges.push((from, to));
)*;
wp_set_level!($level, $logger, lranges)
}};
($level:expr, $logger:expr, $lranges:expr) => {{
match $crate::line_range::prepare_ranges($level, &$lranges) {
Ok(lranges) => {
__wp_write_root!(set_level($level, $logger, lranges))
},
Err(err) => {
let err: Result<(), String> = Err(err);
err
},
}
}};
($level:expr, $logger:expr) => {{
__wp_write_root!(set_level($level, $logger, Vec::new()))
}};
($level:expr) => {{
$crate::logger::global_set_loggers(false);
__wp_write_root!(reset_loggers());
$crate::logger::global_set_level($level);
let ok: Result<(), String> = Ok(());
ok
}};
}
/// Gets the log level.
///
/// Returns global log level if called with `^` as an argument.
///
/// Returns log level according to the position (current path)
/// if called without any argument.
///
/// Returns log level for the requested path when it's passed as an argument.
///
/// The log levels are hierarchical.
///
/// It means that if, for example, there's a rule that states that the module `foo::bar`
/// has log level `WARN`, then all submodules inherit this log level.
/// At the same time another rule may override the inherited level.
/// For example, `foo::bar::qux@xyz.rs` has log level `DEBUG`.
///
/// If there's no exact match the rules of the parent are applied.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// let logger = "foo::bar";
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::WARN);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// wp_set_level!(wp::LogLevel::CRITICAL, logger).unwrap();
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::CRITICAL);
///
/// // Since the logs follow the hierarchy following statements are valid.
/// assert_eq!(wp_get_level!("foo::bar::qux"), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!("foo"), wp::LogLevel::INFO);
///
/// wp_set_level!(wp::LogLevel::CRITICAL, this_module!()).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::CRITICAL);
///
/// wp_set_level!(wp::LogLevel::DEBUG, this_file!()).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::DEBUG);
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(this_module!()), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!(this_file!()), wp::LogLevel::DEBUG);
/// }
///
/// ```
#[macro_export]
macro_rules! wp_get_level {
(^) => {{
$crate::logger::global_get_level()
}};
() => {{
if $crate::logger::global_has_loggers() {
let path = this_file!();
__wp_read_root!(get_level(path, line!()))
} else {
$crate::logger::global_get_level()
}
}};
($logger:expr) => {{
if $crate::logger::global_has_loggers() {
__wp_read_root!(get_level($logger, $crate::EOF.into()))
} else {
$crate::logger::global_get_level()
}
}};
}
/// Registers a log record handler.
///
/// The handler takes a log record as an argument and pushes it into a custom sink.
///
/// By default if no log handler is registered `woodpecker` emits
/// log records into `stdout`.
///
/// If at least one handler is registered than the `stdout` handler
/// must be registered explicitly if it's still desired.
///
/// See the definition of the [`Handler`](handlers/type.Handler.html) type for the details.
///
/// # Example
/// In this example string "foo" will be logged three times into `stdout`
/// but only one caught by the log handler.
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init();
///
/// warn!("foo");
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// wp_register_handler!(wp::handlers::stdout::handler());
/// warn!("foo");
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// warn!("foo");
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), "foo".to_string());
/// }
///
/// ```
#[macro_export]
macro_rules! wp_register_handler {
($handler:expr) => {{
__wp_write_root!(handler($handler));
}};
}
/// Sets a log record formatter.
///
/// A [default](formatters/default/fn.formatter.html) formatter is used if not set explicitly.
///
/// The formatter function takes a log record as an argument and returns a string
/// that will be used as a return value of [Record::formatted](record/struct.Record.html#method.formatted) function.
///
/// See the definition of the [Formatter](formatters/type.Formatter.html) type for the details.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init();
///
/// wp_set_formatter!(Box::new(|record| {
/// format!("{}:{}", record.level(), record.msg())
/// }));
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.formatted().deref());
/// }));
///
/// warn!("foo");
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), "WARN:foo".to_string());
/// }
///
/// ```
#[macro_export]
macro_rules! wp_set_formatter {
($formatter:expr) => {{
__wp_write_root!(formatter($formatter));
}};
}
/// The main log entry.
///
/// Prepares and emits a log record if requested log [level](levels/enum.LogLevel.html) is greater or equal
/// according to the log level.
///
/// If log level is not specified then the log is emitted unconditionally.
///
/// If, for example, the hierarchy rules deduce that the log level at the current position is
/// [WARN](levels/enum.LogLevel.html) then the logs for
/// the levels [WARN](levels/enum.LogLevel.html) and above([ERROR](levels/enum.LogLevel.html) and
/// [CRITICAL](levels/enum.LogLevel.html)) are emitted.
/// The logs for the levels below [WARN](levels/enum.LogLevel.html)
/// (such as [NOTICE](levels/enum.LogLevel.html), [INFO](levels/enum.LogLevel.html), etc.) are dropped.
///
/// See documentation for the [wp_get_level](macro.wp_get_level.html)
/// for more details on the log level hierarchy.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// let msg = "I'm always visible";
///
/// wp::init();
///
/// wp_set_level!(wp::LogLevel::CRITICAL).unwrap();
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// log!(">{}<", msg);
/// warn!("foo");
/// in_trace!({
/// log!("Not seen though");
/// });
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), format!(">{}<", msg));
/// }
///
/// ```
#[macro_export]
macro_rules! log {
($level:expr => $($arg:tt)*) => {{
use $crate::record::imp::RecordMeta;
static RECORD: RecordMeta = RecordMeta {
level: $level,
module: this_module!(),
file: file!(),
line: line!(),
};
if $crate::logger::global_has_loggers() {
let path = this_file!();
let root = $crate::logger::root();
let root = root.read();
if root.get_level(path, line!()) <= $level {
root.log(&RECORD, format_args!($($arg)*));
}
} else {
if $crate::logger::global_get_level() <= $level {
__wp_read_root!(log(&RECORD, format_args!($($arg)*)));
}
}
}};
($($arg:tt)*) => {{
use $crate::record::imp::RecordMeta;
static RECORD: RecordMeta = RecordMeta {
level: $crate::LogLevel::LOG,
module: this_module!(),
file: file!(),
line: line!(),
};
__wp_read_root!(log(&RECORD, format_args!($($arg)*)));
}};
}
/// Produces log record for the `trace` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! trace {
($($arg:tt)*) => {
log!($crate::LogLevel::TRACE => $($arg)*);
};
}
/// Executes the code only for the `trace` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_trace {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::TRACE {
$block;
}
}
}
/// Produces log record for the `debug` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! debug {
($($arg:tt)*) => {
log!($crate::LogLevel::DEBUG => $($arg)*);
};
}
/// Executes the code only for the `debug` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_debug {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::DEBUG {
$block;
}
}
}
/// Produces log for the `verbose` level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! verbose {
($($arg:tt)*) => {
log!($crate::LogLevel::VERBOSE => $($arg)*);
};
}
/// Executes the code only for the `verbose` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_verbose {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::VERBOSE {
$block;
}
}
}
/// Produces log record for the `info` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! info {
($($arg:tt)*) => {
log!($crate::LogLevel::INFO => $($arg)*);
};
}
/// Executes the code only for the `info` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_info {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::INFO {
$block;
}
}
}
/// Produces log record for the `notice` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! notice {
($($arg:tt)*) => {
log!($crate::LogLevel::NOTICE => $($arg)*);
};
}
/// Executes the code only for the `notice` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_notice {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::NOTICE {
$block;
}
}
}
/// Produces log record for the `warn` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! warn {
($($arg:tt)*) => {
log!($crate::LogLevel::WARN => $($arg)*);
};
}
/// Executes the code only for the `warn` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_warn {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::WARN {
$block;
}
}
}
/// Produces log record for the `error` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! error {
($($arg:tt)*) => {
log!($crate::LogLevel::ERROR => $($arg)*);
};
}
/// Executes the code only for the `error` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_error {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::ERROR {
$block;
}
}
}
/// Produces log record for the `critical` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! critical {
($($arg:tt)*) => {
log!($crate::LogLevel::CRITICAL => $($arg)*);
};
}
/// Executes the code only for the `critical` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_critical {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::CRITICAL {
$block;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use levels::LEVELS;
use std::sync::Mutex;
use std::ops::Deref;
use std::thread;
use std::panic;
// NOTE: the test must not run in //
fn run_test<T>(test: T) where T: FnOnce(Arc<Mutex<String>>) -> () + panic::UnwindSafe {
struct TContext {
lock: Mutex<u32>,
};
static mut CONTEXT: *const Arc<TContext> = 0 as *const Arc<TContext>;
static ONCE: Once = ONCE_INIT;
let context = unsafe {
ONCE.call_once(|| {
if cfg!(feature = "test-thread-log") {
init_with_thread();
} else {
init();
}
let context = Arc::new(TContext {
lock: Mutex::new(0),
});
CONTEXT = mem::transmute(Box::new(context));
});
(*CONTEXT).clone()
};
let lock = context.lock.lock().unwrap();
let result = panic::catch_unwind(|| {
reset();
let out = Arc::new(Mutex::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.lock().unwrap().push_str(record.formatted().deref());
}));
}
(test)(out.clone());
});
drop(lock);
if let Err(err) = result {
panic::resume_unwind(err);
}
}
#[test]
fn test_logger_default() {
run_test(|_| {
// Default level is WARN
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
wp_set_level!(LogLevel::INFO).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::INFO);
assert_eq!(wp_get_level!("foo"), LogLevel::INFO);
});
}
#[test]
fn test_logger_hierarchy() {
run_test(|_| {
wp_set_level!(LogLevel::CRITICAL, "foo::bar::qux").unwrap();
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo::bar::qux::xyz"), LogLevel::CRITICAL);
assert_eq!(wp_get_level!("foo::bar::qux"), LogLevel::CRITICAL);
assert_eq!(wp_get_level!("foo::bar"), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
});
}
#[test]
#[should_panic(expected = "File path not specified")]
fn test_set_level_range_0() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, this_module!(), [(LineRangeBound::BOF, 42u32)]).unwrap();
});
}
#[test]
#[should_panic(expected = "Module not specified")]
fn test_set_level_range_1() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, file!(), [(LineRangeBound::BOF, 42u32)]).unwrap();
});
}
#[test]
#[should_panic(expected = "Invalid range")]
fn test_set_level_range_2() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, this_file!(), [(42u32, 41u32)]).unwrap();
});
}
#[test]
fn test_set_level_range_3() {
run_test(|_| {
assert_eq!(wp_set_level!(LogLevel::TRACE, "foo", [(LineRangeBound::BOF, LineRangeBound::EOF)]), Ok(()));
assert_eq!(wp_set_level!(LogLevel::TRACE, this_file!(), [(LineRangeBound::BOF, 42u32)]), Ok(()));
});
}
#[test]
fn test_logger_basic() {
run_test(|buf| {
for l in LEVELS.iter() {
wp_set_level!(*l).unwrap();
assert_eq!(*l, wp_get_level!(^));
assert_eq!(*l, wp_get_level!());
for l in LEVELS.iter() {
match *l {
LogLevel::TRACE => trace!("msg"),
LogLevel::DEBUG => debug!("msg"),
LogLevel::VERBOSE => verbose!("msg"),
LogLevel::INFO => info!("msg"),
LogLevel::NOTICE => notice!("msg"),
LogLevel::WARN => warn!("msg"),
LogLevel::ERROR => error!("msg"),
LogLevel::CRITICAL => critical!("msg"),
LogLevel::LOG | LogLevel::UNSUPPORTED => panic!(),
}
sync();
let mut output = buf.lock().unwrap();
if *l >= wp_get_level!() {
assert!(output.as_str().contains("msg"));
assert!(output.as_str().contains(&l.to_string()));
} else {
assert!(output.is_empty());
}
output.clear();
}
}
for l in LEVELS.iter() {
wp_set_level!(*l).unwrap();
assert_eq!(*l, wp_get_level!());
log!(">>{}<<", "unconditional");
sync();
let mut output = buf.lock().unwrap();
assert!(output.as_str().contains(">>unconditional<<"));
output.clear();
}
wp_set_formatter!(Box::new(|record| {
format!(
"{}:{}",
record.level(),
record.msg(),
)
}));
let logger = "woodpecker";
wp_set_level!(LogLevel::WARN).unwrap();
wp_set_level!(LogLevel::VERBOSE, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
assert_eq!(wp_get_level!(logger), LogLevel::VERBOSE);
assert_eq!(wp_get_level!(), LogLevel::VERBOSE);
{
let mut output = buf.lock().unwrap();
output.clear();
drop(output);
verbose!("msg");
debug!("msg");
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "VERBOSE:msg");
}
wp_set_level!(LogLevel::CRITICAL).unwrap();
assert_eq!(wp_get_level!(), LogLevel::CRITICAL);
let logger = this_module!();
wp_set_level!(LogLevel::ERROR, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::CRITICAL);
assert_eq!(wp_get_level!(logger), LogLevel::ERROR);
assert_eq!(wp_get_level!(), LogLevel::ERROR);
let logger = this_file!();
wp_set_level!(LogLevel::NOTICE, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::CRITICAL);
assert_eq!(wp_get_level!(logger), LogLevel::NOTICE);
assert_eq!(wp_get_level!(), LogLevel::NOTICE);
{
let mut output = buf.lock().unwrap();
output.clear();
drop(output);
notice!("msg");
verbose!("msg");
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "NOTICE:msg");
}
});
}
#[test]
fn test_logger_in_log() {
run_test(|buf| {
wp_set_level!(LogLevel::WARN).unwrap();
wp_set_formatter!(Box::new(|record| {
(*record.msg()).clone()
}));
in_debug!({
log!("hidden");
});
in_warn!({
log!("visible");
});
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "visible");
});
}
#[test]
fn test_logger_handler() {
run_test(|buf| {
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.msg().deref());
out.write().push_str("|");
}));
wp_set_level!(LogLevel::INFO).unwrap();
info!("msg");
debug!("foo");
}
sync();
assert_eq!(buf.lock().unwrap().split("msg").count(), 2);
assert_eq!(*out.read(), "msg|".to_string());
});
}
#[test]
fn test_logger_formatter() {
run_test(|_| {
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.formatted().deref());
}));
wp_set_formatter!(Box::new(|record| {
format!(
"{}:{}|",
record.level(),
record.msg(),
)
}));
wp_set_level!(LogLevel::INFO).unwrap();
info!("msg");
debug!("foo");
}
sync();
assert_eq!(*out.read(), "INFO:msg|".to_string());
});
}
#[test]
fn test_logger_threads() {
run_test(|_| {
let thqty = 100;
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.formatted().deref());
}));
wp_set_formatter!(Box::new(move |record| {
format!(
"{}:{}",
record.level(),
record.msg(),
)
}));
let mut threads = Vec::new();
wp_set_level!(LogLevel::INFO).unwrap();
for idx in 0..thqty {
threads.push(thread::spawn(move || {
thread::yield_now();
if idx % 2 == 0 {
info!("{}", idx);
}
debug!("{}", idx);
}));
}
assert_eq!(thqty, threads.len());
for th in threads {
th.join().unwrap();
}
}
sync();
let sum = out.read().split("INFO:").
filter(|val| !val.is_empty()).
fold(0, |acc, ref val| {
acc + val.parse::<u32>().unwrap()
});
let expected = (0..100).filter(|x| x % 2 == 0).sum();
assert_eq!(sum, expected);
});
}
}
be less aggressive in the log thread
// Copyright 2017 Dmytro Milinevskyi <dmilinevskyi@gmail.com>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate parking_lot;
use self::parking_lot::RwLock;
extern crate time;
extern crate crossbeam;
use self::crossbeam::sync::MsQueue;
use self::crossbeam::mem::CachePadded;
use std::mem;
use std::sync::{Arc, Once, ONCE_INIT};
use std::sync::atomic::{AtomicIsize, AtomicUsize, AtomicBool, Ordering,
ATOMIC_ISIZE_INIT, ATOMIC_USIZE_INIT, ATOMIC_BOOL_INIT};
use std::collections::BTreeMap;
use std::collections::Bound::{Included, Excluded, Unbounded};
use std::time::{Duration, Instant};
use std::thread;
use std::fmt;
use std::env;
use levels::LogLevel;
use record::Record;
use record::imp::{SyncRecord, AsyncRecord, RecordMeta};
use line_range::{LineRangeBound, LineRange};
use formatters::Formatter;
use handlers::Handler;
static LOG_LEVEL: AtomicIsize = ATOMIC_ISIZE_INIT;
static HAS_SUBLOGGERS: AtomicBool = ATOMIC_BOOL_INIT;
static LOG_THREAD: AtomicBool = ATOMIC_BOOL_INIT;
static IS_INIT: AtomicBool = ATOMIC_BOOL_INIT;
lazy_static! {
static ref SENT: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
static ref RECEIVED: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
static ref QIDX: CachePadded<AtomicUsize> = CachePadded::new(ATOMIC_USIZE_INIT);
}
const QNUM: usize = 64;
/// A file-module separator.
///
/// This separator is used to join module and file paths.
#[macro_export]
macro_rules! wp_separator {
() => ('@')
}
struct LevelMeta {
level: LogLevel,
lranges: Vec<LineRange>,
}
type QVec = [MsQueue<AsyncRecord>; QNUM];
#[doc(hidden)]
pub struct RootLogger {
loggers: CachePadded<BTreeMap<String, LevelMeta>>,
formatter: Arc<Formatter>,
handlers: Vec<Handler>,
queue: Arc<QVec>,
}
impl RootLogger {
fn new(queue: Arc<QVec>) -> Self {
RootLogger {
loggers: CachePadded::new(BTreeMap::new()),
formatter: Arc::new(Box::new(::formatters::default::formatter)),
handlers: Vec::new(),
queue: queue,
}
}
fn reset(&mut self) {
self.loggers.clear();
self.formatter = Arc::new(Box::new(::formatters::default::formatter));
self.handlers.clear();
}
#[doc(hidden)]
pub fn reset_loggers(&mut self) {
self.loggers.clear()
}
#[doc(hidden)]
pub fn handler(&mut self, handler: Handler) {
self.handlers.push(handler);
}
#[doc(hidden)]
pub fn formatter(&mut self, formatter: Formatter) {
self.formatter = Arc::new(formatter);
}
fn remove_children(&mut self, path: &str) {
let mut trash = Vec::new();
{
let range = self.loggers.range::<str, _>((Excluded(path), Unbounded));
for (name, _) in range {
if !name.starts_with(path) {
break;
}
trash.push(name.to_string());
}
}
for item in trash {
self.loggers.remove(item.as_str());
}
}
#[doc(hidden)]
pub fn set_level(&mut self, level: LogLevel, path: &str, lranges: Vec<LineRange>) -> Result<(), String> {
if level == LogLevel::UNSUPPORTED {
return Err("Unsupported log level".to_string());
}
if !lranges.is_empty() {
if !path.ends_with("<anon>") && !path.ends_with(".rs") {
return Err("File path not specified".to_string());
}
if path.find(wp_separator!()).is_none() {
return Err("Module not specified".to_string());
}
}
let level = if lranges.is_empty() {
level
} else {
self.get_level(path, LineRangeBound::EOF.into())
};
self.remove_children(path);
let logger = LevelMeta {
level: level,
lranges: lranges,
};
self.loggers.insert(path.to_string(), logger);
global_set_loggers(true);
Ok(())
}
#[doc(hidden)]
#[inline(always)]
pub fn get_level(&self, path: &str, line: u32) -> LogLevel {
let range = self.loggers.range::<str, _>((Unbounded, Included(path)));
for (name, logger) in range.rev() {
if path.starts_with(name) {
if line == LineRangeBound::EOF.into() || logger.lranges.is_empty() {
return logger.level;
}
for range in &logger.lranges {
if line >= range.from && line <= range.to {
return range.level;
}
}
return logger.level;
}
}
global_get_level()
}
#[doc(hidden)]
pub fn log(&self, record: &'static RecordMeta, args: fmt::Arguments) {
let record = SyncRecord::new(record, time::get_time(), args, self.formatter.clone());
if !LOG_THREAD.load(Ordering::Relaxed) {
self.process(&record);
} else {
let record: AsyncRecord = record.into();
let qidx = QIDX.fetch_add(1, Ordering::Relaxed) % QNUM;
self.queue[qidx].push(record);
SENT.fetch_add(1, Ordering::Relaxed);
}
}
#[inline(always)]
fn process(&self, record: &Record) {
if self.handlers.is_empty() {
::handlers::stdout::emit(&record.formatted());
} else {
for h in &self.handlers {
h(record);
}
}
}
}
fn qempty() -> bool {
let sent = SENT.load(Ordering::Relaxed);
let received = RECEIVED.load(Ordering::Relaxed);
sent == received
}
fn lthread(root: Arc<RwLock<RootLogger>>, queues: Arc<QVec>) {
const BWAIT_MS: u64 = 10;
const RWAIT_MS: u64 = 500;
loop {
'wait: loop {
let now = Instant::now();
while qempty() {
thread::yield_now();
if now.elapsed() > Duration::from_millis(BWAIT_MS) {
thread::sleep(Duration::from_millis(RWAIT_MS));
continue 'wait;
}
}
break;
}
loop {
let mut received: usize = 0;
for queue in queues.iter() {
if queue.is_empty() {
thread::yield_now();
continue;
}
if let Some(record) = queue.try_pop() {
{
let root = root.read();
root.process(&record);
}
received += 1;
}
thread::yield_now();
}
RECEIVED.fetch_add(received, Ordering::Relaxed);
if received < QNUM {
break;
}
thread::yield_now();
}
}
}
#[doc(hidden)]
#[inline(always)]
pub fn root() -> Arc<RwLock<RootLogger>> {
static mut ROOT: *const Arc<RwLock<RootLogger>> = 0 as *const Arc<RwLock<RootLogger>>;
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
let mut queues: QVec = mem::uninitialized();
for queue in queues.iter_mut() {
let z = mem::replace(queue, MsQueue::new());
mem::forget(z);
}
let queues = Arc::new(queues);
assert!(IS_INIT.load(Ordering::Relaxed));
let root = Arc::new(RwLock::new(RootLogger::new(queues.clone())));
if LOG_THREAD.load(Ordering::Relaxed) {
let root = root.clone();
thread::spawn(move || {
lthread(root, queues);
});
}
ROOT = mem::transmute(Box::new(root));
});
(*ROOT).clone()
}
}
/// Ensures that the logging queue is completely consumed by the log thread.
///
/// Normally this should be called in the very end of the program execution
/// to ensure that all log records are properly flushed.
pub fn sync() {
while !qempty() {
thread::sleep(Duration::from_millis(10));
}
}
#[doc(hidden)]
pub fn reset() {
sync();
let root = root();
let mut root = root.write();
global_set_level(LogLevel::WARN);
global_set_loggers(false);
root.reset();
}
fn __init(log_thread: bool) {
let log_thread = match env::var("WP_LOG_THREAD") {
Ok(ref val) => {
let val = &val.to_lowercase()[..1];
val == "y" || val == "1"
}
_ => log_thread,
};
LOG_THREAD.store(log_thread, Ordering::Relaxed);
// NOTE: it's not a real guard.
// The `init` function is supposed to be called once on init.
assert!(!IS_INIT.swap(true, Ordering::Relaxed));
reset();
}
/// Initializes the crate's kitchen.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// info!("Coucou!");
/// }
///
/// ```
pub fn init() {
__init(false);
}
/// Same as [init](fn.init.html) but enables the log thread.
///
/// Consider using [sync](fn.sync.html) to ensure that all log
/// records are properly flushed.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init_with_thread();
///
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// warn!("foo");
/// }
///
/// wp::sync();
///
/// assert_eq!(*out.lock().unwrap(), "foo".to_string());
/// }
///
/// ```
pub fn init_with_thread() {
__init(true);
}
#[doc(hidden)]
#[inline(always)]
pub fn global_get_level() -> LogLevel {
LogLevel::from(LOG_LEVEL.load(Ordering::Relaxed))
}
#[doc(hidden)]
pub fn global_set_level(level: LogLevel) {
LOG_LEVEL.store(level.into(), Ordering::Relaxed);
}
#[doc(hidden)]
#[inline(always)]
pub fn global_has_loggers() -> bool {
HAS_SUBLOGGERS.load(Ordering::Relaxed)
}
#[doc(hidden)]
pub fn global_set_loggers(value: bool) {
HAS_SUBLOGGERS.store(value, Ordering::Relaxed);
}
#[doc(hidden)]
#[macro_export]
macro_rules! __wp_write_root {
($func:ident($($arg:expr),*)) => {{
let root = $crate::logger::root();
$crate::logger::sync();
let mut root = root.write();
root.$func($($arg),*)
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __wp_read_root {
($func:ident($($arg:expr),*)) => {{
let root = $crate::logger::root();
let root = root.read();
root.$func($($arg),*)
}};
}
/// Sets the log level.
///
/// Sets global log level if called without the arguments or
/// according to the specified path otherwise.
///
/// Optionally the ranges of the lines within the file could
/// be given.
/// In this case the full path to the file must be provided.
///
/// See documentation for the [wp_get_level](macro.wp_get_level.html)
/// for more details on the log level hierarchy.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// let logger = "foo::bar";
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// wp_set_level!(wp::LogLevel::CRITICAL, logger).unwrap();
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::CRITICAL);
///
/// wp_set_level!(wp::LogLevel::WARN, this_file!(), [(line!() + 2, wp::EOF)]).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::CRITICAL, this_file!()).unwrap();
/// let ranges = vec![(wp::BOF.into(), line!() + 2), (line!() + 4, wp::EOF.into())];
/// wp_set_level!(wp::LogLevel::WARN, this_file!(), ranges).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
/// assert_eq!(wp_get_level!(), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!(), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::TRACE, this_file!(), [(wp::BOF, wp::EOF)]).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::TRACE);
/// }
///
/// ```
#[macro_export]
macro_rules! wp_set_level {
($level:expr, $logger:expr, [$(($from:expr, $to:expr)),*]) => {{
let mut lranges = Vec::new();
$(
let (from, to): (u32, u32) = ($from.into(), $to.into());
lranges.push((from, to));
)*;
wp_set_level!($level, $logger, lranges)
}};
($level:expr, $logger:expr, $lranges:expr) => {{
match $crate::line_range::prepare_ranges($level, &$lranges) {
Ok(lranges) => {
__wp_write_root!(set_level($level, $logger, lranges))
},
Err(err) => {
let err: Result<(), String> = Err(err);
err
},
}
}};
($level:expr, $logger:expr) => {{
__wp_write_root!(set_level($level, $logger, Vec::new()))
}};
($level:expr) => {{
$crate::logger::global_set_loggers(false);
__wp_write_root!(reset_loggers());
$crate::logger::global_set_level($level);
let ok: Result<(), String> = Ok(());
ok
}};
}
/// Gets the log level.
///
/// Returns global log level if called with `^` as an argument.
///
/// Returns log level according to the position (current path)
/// if called without any argument.
///
/// Returns log level for the requested path when it's passed as an argument.
///
/// The log levels are hierarchical.
///
/// It means that if, for example, there's a rule that states that the module `foo::bar`
/// has log level `WARN`, then all submodules inherit this log level.
/// At the same time another rule may override the inherited level.
/// For example, `foo::bar::qux@xyz.rs` has log level `DEBUG`.
///
/// If there's no exact match the rules of the parent are applied.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// fn main() {
/// wp::init();
///
/// let logger = "foo::bar";
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::WARN);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::WARN);
///
/// wp_set_level!(wp::LogLevel::INFO).unwrap();
/// wp_set_level!(wp::LogLevel::CRITICAL, logger).unwrap();
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(logger), wp::LogLevel::CRITICAL);
///
/// // Since the logs follow the hierarchy following statements are valid.
/// assert_eq!(wp_get_level!("foo::bar::qux"), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!("foo"), wp::LogLevel::INFO);
///
/// wp_set_level!(wp::LogLevel::CRITICAL, this_module!()).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::CRITICAL);
///
/// wp_set_level!(wp::LogLevel::DEBUG, this_file!()).unwrap();
/// assert_eq!(wp_get_level!(), wp::LogLevel::DEBUG);
///
/// assert_eq!(wp_get_level!(^), wp::LogLevel::INFO);
/// assert_eq!(wp_get_level!(this_module!()), wp::LogLevel::CRITICAL);
/// assert_eq!(wp_get_level!(this_file!()), wp::LogLevel::DEBUG);
/// }
///
/// ```
#[macro_export]
macro_rules! wp_get_level {
(^) => {{
$crate::logger::global_get_level()
}};
() => {{
if $crate::logger::global_has_loggers() {
let path = this_file!();
__wp_read_root!(get_level(path, line!()))
} else {
$crate::logger::global_get_level()
}
}};
($logger:expr) => {{
if $crate::logger::global_has_loggers() {
__wp_read_root!(get_level($logger, $crate::EOF.into()))
} else {
$crate::logger::global_get_level()
}
}};
}
/// Registers a log record handler.
///
/// The handler takes a log record as an argument and pushes it into a custom sink.
///
/// By default if no log handler is registered `woodpecker` emits
/// log records into `stdout`.
///
/// If at least one handler is registered than the `stdout` handler
/// must be registered explicitly if it's still desired.
///
/// See the definition of the [`Handler`](handlers/type.Handler.html) type for the details.
///
/// # Example
/// In this example string "foo" will be logged three times into `stdout`
/// but only one caught by the log handler.
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init();
///
/// warn!("foo");
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// wp_register_handler!(wp::handlers::stdout::handler());
/// warn!("foo");
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// warn!("foo");
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), "foo".to_string());
/// }
///
/// ```
#[macro_export]
macro_rules! wp_register_handler {
($handler:expr) => {{
__wp_write_root!(handler($handler));
}};
}
/// Sets a log record formatter.
///
/// A [default](formatters/default/fn.formatter.html) formatter is used if not set explicitly.
///
/// The formatter function takes a log record as an argument and returns a string
/// that will be used as a return value of [Record::formatted](record/struct.Record.html#method.formatted) function.
///
/// See the definition of the [Formatter](formatters/type.Formatter.html) type for the details.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// wp::init();
///
/// wp_set_formatter!(Box::new(|record| {
/// format!("{}:{}", record.level(), record.msg())
/// }));
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.formatted().deref());
/// }));
///
/// warn!("foo");
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), "WARN:foo".to_string());
/// }
///
/// ```
#[macro_export]
macro_rules! wp_set_formatter {
($formatter:expr) => {{
__wp_write_root!(formatter($formatter));
}};
}
/// The main log entry.
///
/// Prepares and emits a log record if requested log [level](levels/enum.LogLevel.html) is greater or equal
/// according to the log level.
///
/// If log level is not specified then the log is emitted unconditionally.
///
/// If, for example, the hierarchy rules deduce that the log level at the current position is
/// [WARN](levels/enum.LogLevel.html) then the logs for
/// the levels [WARN](levels/enum.LogLevel.html) and above([ERROR](levels/enum.LogLevel.html) and
/// [CRITICAL](levels/enum.LogLevel.html)) are emitted.
/// The logs for the levels below [WARN](levels/enum.LogLevel.html)
/// (such as [NOTICE](levels/enum.LogLevel.html), [INFO](levels/enum.LogLevel.html), etc.) are dropped.
///
/// See documentation for the [wp_get_level](macro.wp_get_level.html)
/// for more details on the log level hierarchy.
///
/// # Example
///
/// ```rust
/// #[macro_use]
/// extern crate woodpecker;
/// use woodpecker as wp;
///
/// use std::sync::{Arc, Mutex};
/// use std::ops::Deref;
///
/// fn main() {
/// let msg = "I'm always visible";
///
/// wp::init();
///
/// wp_set_level!(wp::LogLevel::CRITICAL).unwrap();
/// let out = Arc::new(Mutex::new(String::new()));
/// {
/// let out = out.clone();
/// wp_register_handler!(Box::new(move |record| {
/// out.lock().unwrap().push_str(record.msg().deref());
/// }));
///
/// log!(">{}<", msg);
/// warn!("foo");
/// in_trace!({
/// log!("Not seen though");
/// });
/// }
/// if cfg!(feature = "test-thread-log") {
/// wp::sync();
/// }
/// assert_eq!(*out.lock().unwrap(), format!(">{}<", msg));
/// }
///
/// ```
#[macro_export]
macro_rules! log {
($level:expr => $($arg:tt)*) => {{
use $crate::record::imp::RecordMeta;
static RECORD: RecordMeta = RecordMeta {
level: $level,
module: this_module!(),
file: file!(),
line: line!(),
};
if $crate::logger::global_has_loggers() {
let path = this_file!();
let root = $crate::logger::root();
let root = root.read();
if root.get_level(path, line!()) <= $level {
root.log(&RECORD, format_args!($($arg)*));
}
} else {
if $crate::logger::global_get_level() <= $level {
__wp_read_root!(log(&RECORD, format_args!($($arg)*)));
}
}
}};
($($arg:tt)*) => {{
use $crate::record::imp::RecordMeta;
static RECORD: RecordMeta = RecordMeta {
level: $crate::LogLevel::LOG,
module: this_module!(),
file: file!(),
line: line!(),
};
__wp_read_root!(log(&RECORD, format_args!($($arg)*)));
}};
}
/// Produces log record for the `trace` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! trace {
($($arg:tt)*) => {
log!($crate::LogLevel::TRACE => $($arg)*);
};
}
/// Executes the code only for the `trace` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_trace {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::TRACE {
$block;
}
}
}
/// Produces log record for the `debug` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! debug {
($($arg:tt)*) => {
log!($crate::LogLevel::DEBUG => $($arg)*);
};
}
/// Executes the code only for the `debug` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_debug {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::DEBUG {
$block;
}
}
}
/// Produces log for the `verbose` level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! verbose {
($($arg:tt)*) => {
log!($crate::LogLevel::VERBOSE => $($arg)*);
};
}
/// Executes the code only for the `verbose` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_verbose {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::VERBOSE {
$block;
}
}
}
/// Produces log record for the `info` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! info {
($($arg:tt)*) => {
log!($crate::LogLevel::INFO => $($arg)*);
};
}
/// Executes the code only for the `info` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_info {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::INFO {
$block;
}
}
}
/// Produces log record for the `notice` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! notice {
($($arg:tt)*) => {
log!($crate::LogLevel::NOTICE => $($arg)*);
};
}
/// Executes the code only for the `notice` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_notice {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::NOTICE {
$block;
}
}
}
/// Produces log record for the `warn` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! warn {
($($arg:tt)*) => {
log!($crate::LogLevel::WARN => $($arg)*);
};
}
/// Executes the code only for the `warn` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_warn {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::WARN {
$block;
}
}
}
/// Produces log record for the `error` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! error {
($($arg:tt)*) => {
log!($crate::LogLevel::ERROR => $($arg)*);
};
}
/// Executes the code only for the `error` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_error {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::ERROR {
$block;
}
}
}
/// Produces log record for the `critical` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! critical {
($($arg:tt)*) => {
log!($crate::LogLevel::CRITICAL => $($arg)*);
};
}
/// Executes the code only for the `critical` log level.
///
/// See the [log](macro.log.html) macro for the details.
#[macro_export]
macro_rules! in_critical {
($block:block) => {
if wp_get_level!() <= $crate::LogLevel::CRITICAL {
$block;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use levels::LEVELS;
use std::sync::Mutex;
use std::ops::Deref;
use std::thread;
use std::panic;
// NOTE: the test must not run in //
fn run_test<T>(test: T) where T: FnOnce(Arc<Mutex<String>>) -> () + panic::UnwindSafe {
struct TContext {
lock: Mutex<u32>,
};
static mut CONTEXT: *const Arc<TContext> = 0 as *const Arc<TContext>;
static ONCE: Once = ONCE_INIT;
let context = unsafe {
ONCE.call_once(|| {
if cfg!(feature = "test-thread-log") {
init_with_thread();
} else {
init();
}
let context = Arc::new(TContext {
lock: Mutex::new(0),
});
CONTEXT = mem::transmute(Box::new(context));
});
(*CONTEXT).clone()
};
let lock = context.lock.lock().unwrap();
let result = panic::catch_unwind(|| {
reset();
let out = Arc::new(Mutex::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.lock().unwrap().push_str(record.formatted().deref());
}));
}
(test)(out.clone());
});
drop(lock);
if let Err(err) = result {
panic::resume_unwind(err);
}
}
#[test]
fn test_logger_default() {
run_test(|_| {
// Default level is WARN
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
wp_set_level!(LogLevel::INFO).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::INFO);
assert_eq!(wp_get_level!("foo"), LogLevel::INFO);
});
}
#[test]
fn test_logger_hierarchy() {
run_test(|_| {
wp_set_level!(LogLevel::CRITICAL, "foo::bar::qux").unwrap();
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo::bar::qux::xyz"), LogLevel::CRITICAL);
assert_eq!(wp_get_level!("foo::bar::qux"), LogLevel::CRITICAL);
assert_eq!(wp_get_level!("foo::bar"), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
});
}
#[test]
#[should_panic(expected = "File path not specified")]
fn test_set_level_range_0() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, this_module!(), [(LineRangeBound::BOF, 42u32)]).unwrap();
});
}
#[test]
#[should_panic(expected = "Module not specified")]
fn test_set_level_range_1() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, file!(), [(LineRangeBound::BOF, 42u32)]).unwrap();
});
}
#[test]
#[should_panic(expected = "Invalid range")]
fn test_set_level_range_2() {
run_test(|_| {
wp_set_level!(LogLevel::TRACE, this_file!(), [(42u32, 41u32)]).unwrap();
});
}
#[test]
fn test_set_level_range_3() {
run_test(|_| {
assert_eq!(wp_set_level!(LogLevel::TRACE, "foo", [(LineRangeBound::BOF, LineRangeBound::EOF)]), Ok(()));
assert_eq!(wp_set_level!(LogLevel::TRACE, this_file!(), [(LineRangeBound::BOF, 42u32)]), Ok(()));
});
}
#[test]
fn test_logger_basic() {
run_test(|buf| {
for l in LEVELS.iter() {
wp_set_level!(*l).unwrap();
assert_eq!(*l, wp_get_level!(^));
assert_eq!(*l, wp_get_level!());
for l in LEVELS.iter() {
match *l {
LogLevel::TRACE => trace!("msg"),
LogLevel::DEBUG => debug!("msg"),
LogLevel::VERBOSE => verbose!("msg"),
LogLevel::INFO => info!("msg"),
LogLevel::NOTICE => notice!("msg"),
LogLevel::WARN => warn!("msg"),
LogLevel::ERROR => error!("msg"),
LogLevel::CRITICAL => critical!("msg"),
LogLevel::LOG | LogLevel::UNSUPPORTED => panic!(),
}
sync();
let mut output = buf.lock().unwrap();
if *l >= wp_get_level!() {
assert!(output.as_str().contains("msg"));
assert!(output.as_str().contains(&l.to_string()));
} else {
assert!(output.is_empty());
}
output.clear();
}
}
for l in LEVELS.iter() {
wp_set_level!(*l).unwrap();
assert_eq!(*l, wp_get_level!());
log!(">>{}<<", "unconditional");
sync();
let mut output = buf.lock().unwrap();
assert!(output.as_str().contains(">>unconditional<<"));
output.clear();
}
wp_set_formatter!(Box::new(|record| {
format!(
"{}:{}",
record.level(),
record.msg(),
)
}));
let logger = "woodpecker";
wp_set_level!(LogLevel::WARN).unwrap();
wp_set_level!(LogLevel::VERBOSE, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::WARN);
assert_eq!(wp_get_level!("foo"), LogLevel::WARN);
assert_eq!(wp_get_level!(logger), LogLevel::VERBOSE);
assert_eq!(wp_get_level!(), LogLevel::VERBOSE);
{
let mut output = buf.lock().unwrap();
output.clear();
drop(output);
verbose!("msg");
debug!("msg");
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "VERBOSE:msg");
}
wp_set_level!(LogLevel::CRITICAL).unwrap();
assert_eq!(wp_get_level!(), LogLevel::CRITICAL);
let logger = this_module!();
wp_set_level!(LogLevel::ERROR, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::CRITICAL);
assert_eq!(wp_get_level!(logger), LogLevel::ERROR);
assert_eq!(wp_get_level!(), LogLevel::ERROR);
let logger = this_file!();
wp_set_level!(LogLevel::NOTICE, logger).unwrap();
assert_eq!(wp_get_level!(^), LogLevel::CRITICAL);
assert_eq!(wp_get_level!(logger), LogLevel::NOTICE);
assert_eq!(wp_get_level!(), LogLevel::NOTICE);
{
let mut output = buf.lock().unwrap();
output.clear();
drop(output);
notice!("msg");
verbose!("msg");
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "NOTICE:msg");
}
});
}
#[test]
fn test_logger_in_log() {
run_test(|buf| {
wp_set_level!(LogLevel::WARN).unwrap();
wp_set_formatter!(Box::new(|record| {
(*record.msg()).clone()
}));
in_debug!({
log!("hidden");
});
in_warn!({
log!("visible");
});
sync();
let output = buf.lock().unwrap();
assert_eq!(output.as_str(), "visible");
});
}
#[test]
fn test_logger_handler() {
run_test(|buf| {
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.msg().deref());
out.write().push_str("|");
}));
wp_set_level!(LogLevel::INFO).unwrap();
info!("msg");
debug!("foo");
}
sync();
assert_eq!(buf.lock().unwrap().split("msg").count(), 2);
assert_eq!(*out.read(), "msg|".to_string());
});
}
#[test]
fn test_logger_formatter() {
run_test(|_| {
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.formatted().deref());
}));
wp_set_formatter!(Box::new(|record| {
format!(
"{}:{}|",
record.level(),
record.msg(),
)
}));
wp_set_level!(LogLevel::INFO).unwrap();
info!("msg");
debug!("foo");
}
sync();
assert_eq!(*out.read(), "INFO:msg|".to_string());
});
}
#[test]
fn test_logger_threads() {
run_test(|_| {
let thqty = 100;
let out = Arc::new(RwLock::new(String::new()));
{
let out = out.clone();
wp_register_handler!(Box::new(move |record| {
out.write().push_str(record.formatted().deref());
}));
wp_set_formatter!(Box::new(move |record| {
format!(
"{}:{}",
record.level(),
record.msg(),
)
}));
let mut threads = Vec::new();
wp_set_level!(LogLevel::INFO).unwrap();
for idx in 0..thqty {
threads.push(thread::spawn(move || {
thread::yield_now();
if idx % 2 == 0 {
info!("{}", idx);
}
debug!("{}", idx);
}));
}
assert_eq!(thqty, threads.len());
for th in threads {
th.join().unwrap();
}
}
sync();
let sum = out.read().split("INFO:").
filter(|val| !val.is_empty()).
fold(0, |acc, ref val| {
acc + val.parse::<u32>().unwrap()
});
let expected = (0..100).filter(|x| x % 2 == 0).sum();
assert_eq!(sum, expected);
});
}
}
|
//! Macro combinators
//!
//! Macros are used to make combination easier,
//! since they often do not depend on the type
//! of the data they manipulate or return.
//!
//! There is a trick to make them easier to assemble,
//! combinators are defined like this:
//!
//! ```ignore
//! macro_rules! tag (
//! ($i:expr, $inp: expr) => (
//! {
//! ...
//! }
//! );
//! );
//! ```
//!
//! But when used in other combinators, are Used
//! like this:
//!
//! ```ignore
//! named!(my_function, tag!("abcd"));
//! ```
//!
//! Internally, other combinators will rewrite
//! that call to pass the input as first argument:
//!
//! ```ignore
//! macro_rules! named (
//! ($name:ident, $submac:ident!( $($args:tt)* )) => (
//! fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
//! $submac!(i, $($args)*)
//! }
//! );
//! );
//! ```
//!
//! If you want to call a combinator directly, you can
//! do it like this:
//!
//! ```ignore
//! let res = { tag!(input, "abcd"); }
//! ```
//!
//! Combinators must have a specific variant for
//! non-macro arguments. Example: passing a function
//! to filter! instead of another combinator.
//!
//! ```ignore
//! macro_rules! filter(
//! ($input:expr, $submac:ident!( $($args:tt)* )) => (
//! {
//! ...
//! }
//! );
//!
//! // wrap the function in a macro to pass it to the main implementation
//! ($input:expr, $f:expr) => (
//! filter!($input, call!($f));
//! );
//! );
//!
/// Wraps a parser in a closure
#[macro_export]
macro_rules! closure (
($ty:ty, $submac:ident!( $($args:tt)* )) => (
|i: $ty| { $submac!(i, $($args)*) }
);
($submac:ident!( $($args:tt)* )) => (
|i| { $submac!(i, $($args)*) }
);
);
/// Makes a function from a parser combination
///
/// The type can be set up if the compiler needs
/// more information
///
/// ```ignore
/// named!(my_function( &[u8] ) -> &[u8], tag!("abcd"));
/// // first type parameter is input, second is output
/// named!(my_function<&[u8], &[u8]>, tag!("abcd"));
/// // will have &[u8] as input type, &[u8] as output type
/// named!(my_function, tag!("abcd"));
/// // will use &[u8] as input type (use this if the compiler
/// // complains about lifetime issues
/// named!(my_function<&[u8]>, tag!("abcd"));
/// //prefix them with 'pub' to make the functions public
/// named!(pub my_function, tag!("abcd"));
/// ```
#[macro_export]
macro_rules! named (
($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: $i ) -> $crate::IResult<'a,$i,$o> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o> {
$submac!(i, $($args)*)
}
);
($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<'a, &'a [u8], $o> {
$submac!(i, $($args)*)
}
);
($name:ident<$life:item,$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<$life>( i: $i ) -> $crate::IResult<$life,$i, $o> {
$submac!(i, $($args)*)
}
);
($name:ident, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
$submac!(i, $($args)*)
}
);
(pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: $i ) -> $crate::IResult<'a,$i,$o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<'a, &'a [u8], $o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
$submac!(i, $($args)*)
}
);
);
/// Used to wrap common expressions and function as macros
#[macro_export]
macro_rules! call (
($i:expr, $fun:expr) => ( $fun( $i ) );
);
#[macro_export]
macro_rules! apply (
//($i:expr, $fun:ident( $($args:tt),*) ) => ($fun($i, $($args),*) );
($i:expr, $fun:expr, $arg:expr ) => ( $fun( $i, $arg ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr ) => ( $fun( $i, $arg, $arg2 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr ) => ( $fun( $i, $arg, $arg2, $arg3 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4, $arg5 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr, $arg6:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4, $arg5, $arg6 ) );
);
/// Prevents backtracking if the child parser fails
///
/// This parser will do an early return instead of sending
/// its result to the parent parser.
///
/// If another `error!` combinator is present in the parent
/// chain, the error will be wrapped and another early
/// return will be made.
///
/// This makes it easy to build report on which parser failed,
/// where it failed in the input, and the chain of parsers
/// that led it there.
///
/// Additionally, the error chain contains number identifiers
/// that can be matched to provide useful error messages.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use std::collections;
/// # use nom::IResult::Error;
/// # use nom::Err::{Position,NodePosition};
/// # fn main() {
/// named!(err_test, alt!(
/// tag!("abcd") |
/// preceded!(tag!("efgh"), error!(42,
/// chain!(
/// tag!("ijkl") ~
/// res: error!(128, tag!("mnop")) ,
/// || { res }
/// )
/// )
/// )
/// ));
/// let a = &b"efghblah"[..];
/// let b = &b"efghijklblah"[..];
/// let c = &b"efghijklmnop"[..];
///
/// let blah = &b"blah"[..];
///
/// let res_a = err_test(a);
/// let res_b = err_test(b);
/// let res_c = err_test(c);
/// assert_eq!(res_a, Error(NodePosition(42, blah, Box::new(Position(0, blah)))));
/// assert_eq!(res_b, Error(NodePosition(42, &b"ijklblah"[..], Box::new(NodePosition(128, blah, Box::new(Position(0, blah)))))));
/// # }
#[macro_export]
macro_rules! error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
let cl = || {
$submac!($i, $($args)*)
};
match cl() {
//match cl($i) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
return $crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
error!($i, $code, call!($f));
);
);
/// declares a byte array as a suite to recognize
///
/// consumes the recognized characters
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(x, tag!("abcd"));
/// let r = x(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tag (
($i:expr, $inp: expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
if bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(bytes.len()))
} else if &$i[0..bytes.len()] == bytes {
$crate::IResult::Done(&$i[bytes.len()..], &$i[0..bytes.len()])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Tag as u32, $i))
}
}
);
);
/// flat_map! combines a parser R -> IResult<R,S> and
/// a parser S -> IResult<S,T> to return another
/// parser R -> IResult<R,T>
#[macro_export]
macro_rules! flat_map(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)),
$crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2)
}
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
flat_map!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $g:expr) => (
flat_map!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
flat_map!($i, call!($f), $submac!($($args)*));
);
);
/// maps a function on the result of a parser
#[macro_export]
macro_rules! map(
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_impl!($i, $submac!($($args)*), $submac2!($($args2)*),);
);
($i:expr, $f:expr, $g:expr) => (
map_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_impl(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, $submac2!(o, $($args2)*))
}
}
);
);
/// maps a function returning a Result on the output of a parser
#[macro_export]
macro_rules! map_res (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_res_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_res_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_res_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_res_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_res_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Ok(output) => $crate::IResult::Done(i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::MapRes as u32, $i))
}
}
}
);
);
/// maps a function returning an Option on the output of a parser
#[macro_export]
macro_rules! map_opt (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_opt_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_opt_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_opt_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_opt_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_opt_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Some(output) => $crate::IResult::Done(i, output),
None => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::MapOpt as u32, $i))
}
}
}
);
);
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
#[macro_export]
macro_rules! expr_res (
($i:expr, $e:expr) => (
{
match $e {
Ok(output) => $crate::IResult::Done($i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::ExprRes as u32, $i))
}
}
);
);
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
///
/// Useful when doing computations in a chain
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorCode};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// chain!(input,
/// sz: be_u8 ~
/// length: expr_opt!(size.checked_add(sz)) ~ // checking for integer overflow (returns an Option)
/// data: take!(length) ,
/// ||{ data }
/// )
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorCode::ExprOpt as u32,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! expr_opt (
($i:expr, $e:expr) => (
{
match $e {
Some(output) => $crate::IResult::Done($i, output),
None => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::ExprOpt as u32, $i))
}
}
);
);
/// chains parsers and assemble the results through a closure
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// #[derive(PartialEq,Eq,Debug)]
/// struct B {
/// a: u8,
/// b: Option<u8>
/// }
///
/// named!(y, tag!("efgh"));
///
/// fn ret_int(i:&[u8]) -> IResult<&[u8], u8> { Done(i, 1) }
/// named!(ret_y<&[u8], u8>, map!(y, |_| 1)); // return 1 if the "efgh" tag is found
///
/// named!(z<&[u8], B>,
/// chain!(
/// tag!("abcd") ~
/// aa: ret_int ~ // the result of that parser will be used in the closure
/// tag!("abcd")? ~ // this parser is optional
/// bb: ret_y? , // the result of that parser is an option
/// ||{B{a: aa, b: bb}}
/// )
/// );
///
/// # fn main() {
/// // the first "abcd" tag is not present, we have an error
/// let r1 = z(&b"efgh"[..]);
/// assert_eq!(r1, Error(Position(0,&b"efgh"[..])));
///
/// // everything is present, everything is parsed
/// let r2 = z(&b"abcdabcdefgh"[..]);
/// assert_eq!(r2, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the second "abcd" tag is optional
/// let r3 = z(&b"abcdefgh"[..]);
/// assert_eq!(r3, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the result of ret_y is optional, as seen in the B structure
/// let r4 = z(&b"abcdabcdwxyz"[..]);
/// assert_eq!(r4, Done(&b"wxyz"[..], B{a: 1, b: None}));
/// # }
/// ```
#[macro_export]
macro_rules! chain (
($i:expr, $($rest:tt)*) => (
chaining_parser!($i, $($rest)*)
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! chaining_parser (
($i:expr, $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, call!($e) ~ $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,_) => {
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, call!($e) ? ~ $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
chaining_parser!(input, $($rest)*)
}
}
);
($i:expr, $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $field: call!($e) ~ $($rest)*);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let $field = o;
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, mut $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, mut $field: call!($e) ~ $($rest)*);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let mut $field = o;
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let ($field, input) = if let $crate::IResult::Done(i,o) = res {
(Some(o), i)
} else {
(None, $i)
};
chaining_parser!(input, $($rest)*)
}
}
);
($i:expr, mut $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, mut $field : call!($e) ? ~ $($rest)*);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let (mut $field, input) = if let $crate::IResult::Done(i,o) = res {
(Some(o), i)
} else {
(None, $i)
};
chaining_parser!(input, $($rest)*)
}
}
);
// ending the chain
($i:expr, $e:ident, $assemble:expr) => (
chaining_parser!($i, call!($e), $assemble);
);
($i:expr, $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $e:ident ?, $assemble:expr) => (
chaining_parser!($i, call!($e) ?, $assemble);
);
($i:expr, $submac:ident!( $($args:tt)* ) ?, $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
$crate::IResult::Done(input, $assemble())
}
}
);
($i:expr, $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $field: call!($e), $assemble);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, mut $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, mut $field: call!($e), $assemble);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let mut $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $field : call!($e) ? , $assemble);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Error(_) => {
let $field = None;
$crate::IResult::Done($i, $assemble())
},
$crate::IResult::Done(i,o) => {
let $field = Some(o);
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, mut $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $field : call!($e) ? , $assemble);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Error(_) => {
let mut $field = None;
$crate::IResult::Done($i, $assemble())
},
$crate::IResult::Done(i,o) => {
let mut $field = Some(o);
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $assemble:expr) => (
$crate::IResult::Done($i, $assemble())
)
);
/// try a list of parser, return the result of the first successful one
///
/// Incomplete results are ignored
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( test, alt!( tag!( "abcd" ) | tag!( "efgh" ) ) );
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], &b"abcd"[..]));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], &b"efgh"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! alt (
($i:expr, $($rest:tt)*) => (
{
alt_parser!($i, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! alt_parser (
($i:expr, $e:ident | $($rest:tt)*) => (
alt_parser!($i, call!($e) | $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
if let $crate::IResult::Done(i,o) = $submac!($i, $($args)*) {
$crate::IResult::Done(i,o)
} else {
alt_parser!($i, $($rest)*)
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
if let $crate::IResult::Done(i,o) = $subrule!($i, $($args)*) {
$crate::IResult::Done(i, $gen( o ))
} else {
alt_parser!($i, $($rest)+)
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_parser!($i, call!($e) => { $gen } | $($rest)*);
);
($i:expr, $e:ident => { $gen:expr }) => (
alt_parser!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
match $subrule!( $i, $($args)* ) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, $gen( o )),
}
);
($i:expr, $e:ident) => (
alt_parser!($i, call!($e));
);
($i:expr, $submac:ident!( $($args:tt)*)) => (
{
if let $crate::IResult::Done(i,o) = $submac!($i, $($args)*) {
$crate::IResult::Done(i,o)
} else {
alt_parser!($i)
}
}
);
($i:expr) => (
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Alt as u32,$i))
);
);
/// returns the longest list of bytes that do not appear in the provided array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( not_space, is_not!( " \t\r\n" ) );
///
/// let r = not_space(&b"abcdefgh\nijkl"[..]);
/// assert_eq!(r, Done(&b"\nijkl"[..], &b"abcdefgh"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! is_not(
($input:expr, $arr:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $arr;
let bytes = as_bytes(&expected);
let mut parsed = false;
let mut index = 0;
for idx in 0..$input.len() {
index = idx;
for &i in bytes.iter() {
if $input[idx] == i {
parsed = true;
break;
}
}
if parsed { break; }
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::IsNot as u32,$input))
} else {
$crate::IResult::Done(&$input[index..], &$input[0..index])
}
}
);
);
/// returns the longest list of bytes that appear in the provided array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(abcd, is_a!( "abcd" ));
///
/// let r1 = abcd(&b"aaaaefgh"[..]);
/// assert_eq!(r1, Done(&b"efgh"[..], &b"aaaa"[..]));
///
/// let r2 = abcd(&b"dcbaefgh"[..]);
/// assert_eq!(r2, Done(&b"efgh"[..], &b"dcba"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! is_a(
($input:expr, $arr:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $arr;
let bytes = as_bytes(&expected);
let mut index = 0;
for idx in 0..$input.len() {
index = idx;
let mut cont = false;
for &i in bytes.iter() {
if $input[idx] == i {
cont = true;
break;
}
}
if !cont { break; }
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::IsA as u32,$input))
} else {
$crate::IResult::Done(&$input[index..], &$input[0..index])
}
}
);
);
/// returns the longest list of bytes until the provided parser fails
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::is_alphanumeric;
/// # fn main() {
/// named!( alpha, filter!( is_alphanumeric ) );
///
/// let r = alpha(&b"abcd\nefgh"[..]);
/// assert_eq!(r, Done(&b"\nefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! filter(
($input:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut index = 0;
let mut found = false;
for idx in 0..$input.len() {
index = idx;
if !$submac!($input[idx], $($args)*) {
found = true;
break;
}
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Filter as u32,$input))
} else if found {
$crate::IResult::Done(&$input[index..], &$input[0..index])
} else {
$crate::IResult::Done(&b""[..], $input)
}
}
);
($input:expr, $f:expr) => (
filter!($input, call!($f));
);
);
/// make the underlying parser optional
///
/// returns an Option of the returned type
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( o<&[u8], Option<&[u8]> >, opt!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], None));
/// # }
/// ```
#[macro_export]
macro_rules! opt(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt!($i, call!($f));
);
);
/// make the underlying parser optional
///
/// returns a Result, with Err containing the parsing error
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::Err::Position;
/// # fn main() {
/// named!( o<&[u8], Result<&[u8], nom::Err> >, opt_res!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Ok(&b"abcd"[..])));
/// assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(0, b))));
/// # }
/// ```
#[macro_export]
macro_rules! opt_res (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Ok(o)),
$crate::IResult::Error(e) => $crate::IResult::Done($i, Err(e)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt_res!($i, call!($f));
);
);
/// Conditional combinator
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an Option of the return type of the child
/// parser.
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Done($i, None)
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond!($i, $cond, call!($f));
);
);
/// Conditional combinator with error
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an error if the condition is false
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::{Err,ErrorCode};
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond_reduce!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], &b"abcd"[..]));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond_reduce!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Error(Err::Position(ErrorCode::CondReduce as u32, &a[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond_reduce(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::CondReduce as u32, $i))
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond_reduce!($i, $cond, call!($f));
);
);
/// returns a result without consuming the input
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(ptag, peek!( tag!( "abcd" ) ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! peek(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(_,o) => $crate::IResult::Done($i, o),
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
peek!($i, call!(f));
);
);
/// allows access to the parser's result without affecting it
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use std::str;
/// # fn main() {
/// named!(ptag, tap!(res: tag!( "abcd" ) => { println!("recognized {}", str::from_utf8(res).unwrap()) } ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tap (
($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => {
let $name = o;
$e;
$crate::IResult::Done(i, $name)
},
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $name: ident: $f:expr => $e:expr) => (
tap!($i, $name: call!(f) => $e);
);
);
/// pair(X,Y), returns (x,y)
#[macro_export]
macro_rules! pair(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, (o1, o2))
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
pair!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
pair!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
pair!($i, call!($f), call!($g));
);
);
/// separated_pair(X,sep,Y) returns (x,y)
#[macro_export]
macro_rules! separated_pair(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
separated_pair1!(i1, o1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
separated_pair!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! separated_pair1(
($i:expr, $res1:ident, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
separated_pair2!(i2, $res1, $($rest)*)
}
}
}
);
($i:expr, $res1:ident, $g:expr, $($rest:tt)+) => (
separated_pair1!($i, $res1, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! separated_pair2(
($i:expr, $res1:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,o3) => {
$crate::IResult::Done(i3, ($res1, o3))
}
}
}
);
($i:expr, $res1:ident, $h:expr) => (
separated_pair2!($i, $res1, call!($h));
);
);
/// preceded(opening, X) returns X
#[macro_export]
macro_rules! preceded(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, o2)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
preceded!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
preceded!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
preceded!($i, call!($f), call!($g));
);
);
/// terminated(X, closing) returns X
#[macro_export]
macro_rules! terminated(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
$crate::IResult::Done(i2, o1)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
terminated!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
terminated!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
terminated!($i, call!($f), call!($g));
);
);
/// delimited(opening, X, closing) returns X
#[macro_export]
macro_rules! delimited(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
delimited1!(i1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
delimited!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! delimited1(
($i:expr, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
delimited2!(i2, o2, $($rest)*)
}
}
}
);
($i:expr, $g:expr, $($rest:tt)+) => (
delimited1!($i, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! delimited2(
($i:expr, $res2:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,_) => {
$crate::IResult::Done(i3, $res2)
}
}
}
);
($i:expr, $res2:ident, $h:expr) => (
delimited2!($i, $res2, call!($h));
);
);
/// separated_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
// get the first element
match $submac!($i, $($args2)*) {
$crate::IResult::Error(_) => $crate::IResult::Done($i, Vec::new()),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == $i.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::SeparatedList as u32,$i))
} else {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
loop {
// get the separator first
match $sep!(&$i[begin..], $($args)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i2,_) => {
if i2.len() == (&$i[begin..]).len() {
break;
}
begin += remaining - i2.len();
remaining = i2.len();
// get the element next
match $submac!(&$i[begin..], $($args2)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i3,o3) => {
if i3.len() == $i[begin..].len() {
break;
}
res.push(o3);
begin += remaining - i3.len();
remaining = i3.len();
},
}
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_list!($i, call!($f), call!($g));
);
);
/// separated_nonempty_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_nonempty_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
// get the first element
match $submac!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == $i.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::SeparatedNonEmptyList as u32,$i))
} else {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
loop {
// get the separator first
match $sep!(&$i[begin..], $($args)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i2,_) => {
if i2.len() == (&$i[begin..]).len() {
break;
}
begin += remaining - i2.len();
remaining = i2.len();
// get the element next
match $submac!(&$i[begin..], $($args2)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i3,o3) => {
if i3.len() == $i[begin..].len() {
break;
}
res.push(o3);
begin += remaining - i3.len();
remaining = i3.len();
},
}
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_nonempty_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_nonempty_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_nonempty_list!($i, call!($f), call!($g));
);
);
/// Applies the parser 0 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many0!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdef";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"ef"[..], res));
/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new()));
/// # }
/// ```
/// 0 or more
#[macro_export]
macro_rules! many0(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
if i.len() == $i[begin..].len() {
break;
}
res.push(o);
begin += remaining - i.len();
remaining = i.len();
},
_ => {
break;
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
);
($i:expr, $f:expr) => (
many0!($i, call!($f));
);
);
/// Applies the parser 1 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many1!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdef";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"ef"[..], res));
/// assert_eq!(multi(&b[..]), Error(Position(ErrorCode::Many1 as u32,&b[..])));
/// # }
/// ```
#[macro_export]
macro_rules! many1(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
if i.len() == $i[begin..].len() {
break;
}
res.push(o);
begin += remaining - i.len();
remaining = i.len();
},
_ => {
break;
}
}
}
if res.len() == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Many1 as u32,$i))
} else {
$crate::IResult::Done(&$i[begin..], res)
}
}
);
($i:expr, $f:expr) => (
many1!($i, call!($f));
);
);
/// Applies the child parser a specified number of times
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(counter< Vec<&[u8]> >, count!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count(
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
let mut cnt: usize = 0;
let mut err = false;
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $count {
break
}
},
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete(_) => {
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Count as u32,$i))
} else if cnt == $count {
$crate::IResult::Done(&$i[begin..], res)
} else {
$crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
);
($i:expr, $f:expr, $count: expr) => (
count!($i, call!($f), $count);
);
);
/// Applies the child parser a fixed number of times and returns a fixed size array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
/// // can omit the type specifier if returning slices
/// // named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = [&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count_fixed(
($i:expr, $typ:ty, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res: [$typ; $count] = unsafe{[::std::mem::uninitialized(); $count as usize]};
let mut cnt: usize = 0;
let mut err = false;
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
res[cnt] = o;
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $count {
break
}
},
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete(_) => {
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Count as u32,$i))
} else if cnt == $count {
$crate::IResult::Done(&$i[begin..], res)
} else {
$crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
);
($i:expr, $typ: ty, $f:ident, $count: expr) => (
count_fixed!($i, $typ, call!($f), $count);
);
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
count_fixed!($i, &[u8], $submac!($($args)*), $count);
);
($i:expr, $f:ident, $count: expr) => (
count_fixed!($i, &[u8], call!($f), $count);
);
);
/// generates a parser consuming the specified number of bytes
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// // Desmond parser
/// named!(take5, take!( 5 ) );
///
/// let a = b"abcdefgh";
///
/// assert_eq!(take5(&a[..]), Done(&b"fgh"[..], &b"abcde"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! take(
($i:expr, $count:expr) => (
{
let cnt = $count as usize;
if $i.len() < cnt {
$crate::IResult::Incomplete($crate::Needed::Size(cnt))
} else {
$crate::IResult::Done(&$i[cnt..],&$i[0..cnt])
}
}
);
);
/// same as take! but returning a &str
#[macro_export]
macro_rules! take_str (
( $i:expr, $size:expr ) => ( map_res!($i, take!($size), from_utf8) );
);
/// generates a parser consuming bytes until the specified byte sequence is found
#[macro_export]
macro_rules! take_until_and_consume(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + bytes.len() > $i.len() {
index = idx;
break;
}
if &$i[idx..idx + bytes.len()] == bytes {
parsed = true;
index = idx;
break;
}
}
if index + bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + bytes.len()))
} else {
if parsed {
$crate::IResult::Done(&$i[(index + bytes.len())..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilAndConsume as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + bytes.len() > $i.len() {
index = idx;
break;
}
if &$i[idx..idx+bytes.len()] == bytes {
parsed = true;
index = idx;
break;
}
}
if index + bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + bytes.len()))
} else {
if parsed {
$crate::IResult::Done(&$i[index..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntil as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until_either_and_consume(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + 1 > $i.len() {
index = idx;
break;
}
for &t in bytes.iter() {
if $i[idx] == t {
parsed = true;
index = idx;
break;
}
}
if parsed { break; }
}
if index + 1 > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + 1))
} else {
if parsed {
$crate::IResult::Done(&$i[(index+1)..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilEitherAndConsume as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until_either(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + 1 > $i.len() {
index = idx;
break;
}
for &t in bytes.iter() {
if $i[idx] == t {
parsed = true;
index = idx;
break;
}
}
if parsed { break; }
}
if index + 1 > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + 1))
} else {
if parsed {
$crate::IResult::Done(&$i[index..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilEither as u32,$i))
}
}
}
);
);
/// gets a number from the first parser, then applies the second parser that many times
#[macro_export]
macro_rules! length_value(
($i:expr, $f:expr, $g:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,nb) => {
let length_token = $i.len() - i1.len();
let mut begin = 0;
let mut remaining = i1.len();
let mut res = Vec::new();
let mut err = false;
let mut inc = $crate::Needed::Unknown;
loop {
if res.len() == nb as usize {
break;
}
match $g(&i1[begin..]) {
$crate::IResult::Done(i2,o2) => {
res.push(o2);
let parsed = remaining - i2.len();
begin += parsed;
remaining = i2.len();
},
$crate::IResult::Error(_) => {
err = true;
},
$crate::IResult::Incomplete(a) => {
inc = a;
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::LengthValue as u32,$i))
} else if res.len() < nb as usize {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(length) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + nb as usize * length))
}
} else {
$crate::IResult::Done(&i1[begin..], res)
}
}
}
}
);
($i:expr, $f:expr, $g:expr, $length:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,nb) => {
let length_token = $i.len() - i1.len();
let mut begin = 0;
let mut remaining = i1.len();
let mut res = Vec::new();
let mut err = false;
let mut inc = $crate::Needed::Unknown;
loop {
if res.len() == nb as usize {
break;
}
match $g(&i1[begin..]) {
$crate::IResult::Done(i2,o2) => {
res.push(o2);
let parsed = remaining - i2.len();
begin += parsed;
remaining = i2.len();
},
$crate::IResult::Error(_) => {
err = true;
},
$crate::IResult::Incomplete(a) => {
inc = a;
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::LengthValue as u32,$i))
} else if res.len() < nb as usize {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(_) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + nb as usize * $length))
}
} else {
$crate::IResult::Done(&i1[begin..], res)
}
}
}
}
);
);
#[cfg(test)]
mod tests {
use internal::{Needed,IResult,Err};
use internal::IResult::*;
use internal::Err::*;
use util::ErrorCode;
mod pub_named_mod {
named!(pub tst, tag!("abcd"));
}
#[test]
fn pub_named_test() {
let a = &b"abcd"[..];
let res = pub_named_mod::tst(a);
assert_eq!(res, Done(&b""[..], a));
}
#[test]
fn apply_test() {
fn sum2(a:u8, b:u8) -> u8 { a + b }
fn sum3(a:u8, b:u8, c:u8) -> u8 { a + b + c }
let a = apply!(1, sum2, 2);
let b = apply!(1, sum3, 2, 3);
assert_eq!(a, 3);
assert_eq!(b, 6);
}
#[test]
fn is_a() {
named!(a_or_b, is_a!(&b"ab"[..]));
let a = &b"abcd"[..];
assert_eq!(a_or_b(a), Done(&b"cd"[..], &b"ab"[..]));
let b = &b"bcde"[..];
assert_eq!(a_or_b(b), Done(&b"cde"[..], &b"b"[..]));
let c = &b"cdef"[..];
assert_eq!(a_or_b(c), Error(Position(ErrorCode::IsA as u32,c)));
let d = &b"bacdef"[..];
assert_eq!(a_or_b(d), Done(&b"cdef"[..], &b"ba"[..]));
}
#[derive(PartialEq,Eq,Debug)]
struct B {
a: u8,
b: u8
}
#[test]
fn chain2() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[test]
fn nested_chain() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
chain!(
tag!("abcd") ~
tag!("abcd")? ,
|| {}
) ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[derive(PartialEq,Eq,Debug)]
struct C {
a: u8,
b: Option<u8>
}
#[test]
fn chain_mut() {
fn ret_b1_2(i:&[u8]) -> IResult<&[u8], B> { Done(i,B{a:1,b:2}) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
tag!("efgh") ~
mut bb: ret_b1_2 ~
tag!("efgh") ,
||{
bb.b = 3;
bb
}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 3}));
}
#[test]
fn chain_opt() {
named!(y, tag!("efgh"));
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
named!(ret_y<&[u8], u8>, map!(y, |_| 2));
named!(f<&[u8],C>,
chain!(
tag!("abcd") ~
aa: ret_int1 ~
bb: ret_y? ,
||{C{a: aa, b: bb}}
)
);
let r = f(&b"abcdefghX"[..]);
assert_eq!(r, Done(&b"X"[..], C{a: 1, b: Some(2)}));
let r2 = f(&b"abcdWXYZ"[..]);
assert_eq!(r2, Done(&b"WXYZ"[..], C{a: 1, b: None}));
let r3 = f(&b"abcdX"[..]);
assert_eq!(r3, Incomplete(Needed::Size(4)));
}
use util::{error_to_list, add_error_pattern, print_error};
fn error_to_string(e: Err) -> &str {
let v:Vec<u32> = error_to_list(e);
// do it this way if you can use slice patterns
/*
match &v[..] {
[42, 0] => "missing `ijkl` tag",
[42, 128, 0] => "missing `mnop` tag after `ijkl`",
_ => "unrecognized error"
}
*/
if &v[..] == [42,0] {
"missing `ijkl` tag"
} else if &v[..] == [42, 128, 0] {
"missing `mnop` tag after `ijkl`"
} else {
"unrecognized error"
}
}
// do it this way if you can use box patterns
/*use std::str;
fn error_to_string(e:Err) -> String
match e {
NodePosition(42, i1, box Position(0, i2)) => {
format!("missing `ijkl` tag, found '{}' instead", str::from_utf8(i2).unwrap())
},
NodePosition(42, i1, box NodePosition(128, i2, box Position(0, i3))) => {
format!("missing `mnop` tag after `ijkl`, found '{}' instead", str::from_utf8(i3).unwrap())
},
_ => "unrecognized error".to_string()
}
}*/
use std::collections;
#[test]
fn err() {
named!(err_test, alt!(
tag!("abcd") |
preceded!(tag!("efgh"), error!(42,
chain!(
tag!("ijkl") ~
res: error!(128, tag!("mnop")) ,
|| { res }
)
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(42, blah, Box::new(Position(0, blah)))));
assert_eq!(res_b, Error(NodePosition(42, &b"ijklblah"[..], Box::new(NodePosition(128, blah, Box::new(Position(0, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
// Merr-like error matching
let mut err_map = collections::HashMap::new();
assert!(add_error_pattern(&mut err_map, err_test(&b"efghpouet"[..]), "missing `ijkl` tag"));
assert!(add_error_pattern(&mut err_map, err_test(&b"efghijklpouet"[..]), "missing `mnop` tag after `ijkl`"));
let res_a2 = res_a.clone();
match res_a {
Error(e) => {
let e2 = e.clone();
let e3 = e.clone();
assert_eq!(error_to_list(e), [42, 0]);
assert_eq!(error_to_string(e2), "missing `ijkl` tag");
assert_eq!(err_map.get(&error_to_list(e3)), Some(&"missing `ijkl` tag"));
},
_ => panic!()
};
let res_b2 = res_b.clone();
match res_b {
Error(e) => {
let e2 = e.clone();
let e3 = e.clone();
assert_eq!(error_to_list(e), [42, 128, 0]);
assert_eq!(error_to_string(e2), "missing `mnop` tag after `ijkl`");
assert_eq!(err_map.get(&error_to_list(e3)), Some(&"missing `mnop` tag after `ijkl`"));
},
_ => panic!()
};
print_error(a, res_a2);
print_error(b, res_b2);
}
#[test]
fn alt() {
fn work(input: &[u8]) -> IResult<&[u8],&[u8]> {
Done(&b""[..], input)
}
#[allow(unused_variables)]
fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8]> {
Error(Code(42))
}
fn work2(input: &[u8]) -> IResult<&[u8],&[u8]> {
Done(input, &b""[..])
}
named!(alt1, alt!(dont_work | dont_work));
named!(alt2, alt!(dont_work | work));
named!(alt3, alt!(dont_work | dont_work | work2 | dont_work));
let a = &b"abcd"[..];
assert_eq!(alt1(a), Error(Position(ErrorCode::Alt as u32, a)));
assert_eq!(alt2(a), Done(&b""[..], a));
assert_eq!(alt3(a), Done(a, &b""[..]));
named!(alt4, alt!(tag!("abcd") | tag!("efgh")));
let b = &b"efgh"[..];
assert_eq!(alt4(a), Done(&b""[..], a));
assert_eq!(alt4(b), Done(&b""[..], b));
}
#[test]
fn opt() {
named!(o<&[u8],Option<&[u8]> >, opt!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Some(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], None));
}
#[test]
fn opt_res() {
named!(o<&[u8], Result<&[u8], Err> >, opt_res!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Ok(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(0, b))));
}
#[test]
fn cond() {
let b = true;
let f = closure!(&'static [u8], cond!( b, tag!("abcd") ) );
let a = b"abcdef";
assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
let b2 = false;
let f2 = closure!(&'static [u8], cond!( b2, tag!("abcd") ) );
assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
}
#[test]
fn cond_wrapping() {
// Test that cond!() will wrap a given identifier in the call!() macro.
named!(silly, tag!("foo"));
let b = true;
let f = closure!(&'static [u8], cond!( b, silly ) );
assert_eq!(f(b"foobar"), Done(&b"bar"[..], Some(&b"foo"[..])));
}
#[test]
fn peek() {
named!(ptag<&[u8],&[u8]>, peek!(tag!("abcd")));
let r1 = ptag(&b"abcdefgh"[..]);
assert_eq!(r1, Done(&b"abcdefgh"[..], &b"abcd"[..]));
let r1 = ptag(&b"efgh"[..]);
assert_eq!(r1, Error(Position(0,&b"efgh"[..])));
}
#[test]
fn pair() {
named!(p<&[u8],(&[u8], &[u8])>, pair!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn separated_pair() {
named!(p<&[u8],(&[u8], &[u8])>, separated_pair!(tag!("abcd"), tag!(","), tag!("efgh")));
let r1 = p(&b"abcd,efghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn preceded() {
named!(p<&[u8], &[u8]>, preceded!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"efgh"[..]));
}
#[test]
fn terminated() {
named!(p<&[u8], &[u8]>, terminated!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"abcd"[..]));
}
#[test]
fn delimited() {
named!(p<&[u8], &[u8]>, delimited!(tag!("abcd"), tag!("efgh"), tag!("ij")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"kl"[..], &b"efgh"[..]));
}
#[test]
fn separated_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
}
#[test]
fn separated_nonempty_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(0,c)));
}
#[test]
fn many0() {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
}
#[test]
fn many1() {
named!(multi<&[u8],Vec<&[u8]> >, many1!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorCode::Many1 as u32,c)));
}
#[test]
fn infinite_many() {
fn tst(input: &[u8]) -> IResult<&[u8], &[u8]> {
println!("input: {:?}", input);
Error(Position(0,input))
}
// should not go into an infinite loop
named!(multi0<&[u8],Vec<&[u8]> >, many0!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi0(a), Done(a, Vec::new()));
named!(multi1<&[u8],Vec<&[u8]> >, many1!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi1(a), Error(Position(ErrorCode::Many1 as u32,a)));
}
#[test]
fn count() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 2;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
#[test]
fn count_fixed() {
named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
use nom::{le_u16,eof};
#[allow(dead_code)]
pub fn compile_count_fixed(input: &[u8]) -> IResult<&[u8], ()> {
chain!(input,
tag!("abcd") ~
count_fixed!( u16, le_u16, 4 ) ~
eof ,
|| { () }
)
}
#[test]
fn count_fixed_no_type() {
named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
use std::str::from_utf8;
#[test]
fn take_str_test() {
let a = b"omnomnom";
assert_eq!(take_str!(&a[..], 5), Done(&b"nom"[..], "omnom"));
assert_eq!(take_str!(&a[..], 9), Incomplete(Needed::Size(9)));
}
#[test]
fn take_until_test() {
named!(x, take_until_and_consume!("efgh"));
let r = x(&b"abcdabcdefghijkl"[..]);
assert_eq!(r, Done(&b"ijkl"[..], &b"abcdabcd"[..]));
println!("Done 1\n");
let r2 = x(&b"abcdabcdefgh"[..]);
assert_eq!(r2, Done(&b""[..], &b"abcdabcd"[..]));
println!("Done 2\n");
let r3 = x(&b"abcefg"[..]);
assert_eq!(r3, Incomplete(Needed::Size(7)));
}
use nom::{be_u8,be_u16};
#[test]
fn length_value_test() {
named!(tst1<&[u8], Vec<u16> >, length_value!(be_u8, be_u16));
named!(tst2<&[u8], Vec<u16> >, length_value!(be_u8, be_u16, 2));
let i1 = vec![0, 5, 6];
let i2 = vec![1, 5, 6, 3];
let i3 = vec![2, 5, 6, 3];
let i4 = vec![2, 5, 6, 3, 4, 5, 7];
let i5 = vec![3, 5, 6, 3, 4, 5];
let r1: Vec<u16> = Vec::new();
let r2: Vec<u16> = vec![1286];
let r4: Vec<u16> = vec![1286, 772];
assert_eq!(tst1(&i1), IResult::Done(&i1[1..], r1));
assert_eq!(tst1(&i2), IResult::Done(&i2[3..], r2));
assert_eq!(tst1(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst1(&i4), IResult::Done(&i4[5..], r4));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
let r6: Vec<u16> = Vec::new();
let r7: Vec<u16> = vec![1286];
let r9: Vec<u16> = vec![1286, 772];
assert_eq!(tst2(&i1), IResult::Done(&i1[1..], r6));
assert_eq!(tst2(&i2), IResult::Done(&i2[3..], r7));
assert_eq!(tst2(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst2(&i4), IResult::Done(&i4[5..], r9));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
}
}
fix filter's documentation
//! Macro combinators
//!
//! Macros are used to make combination easier,
//! since they often do not depend on the type
//! of the data they manipulate or return.
//!
//! There is a trick to make them easier to assemble,
//! combinators are defined like this:
//!
//! ```ignore
//! macro_rules! tag (
//! ($i:expr, $inp: expr) => (
//! {
//! ...
//! }
//! );
//! );
//! ```
//!
//! But when used in other combinators, are Used
//! like this:
//!
//! ```ignore
//! named!(my_function, tag!("abcd"));
//! ```
//!
//! Internally, other combinators will rewrite
//! that call to pass the input as first argument:
//!
//! ```ignore
//! macro_rules! named (
//! ($name:ident, $submac:ident!( $($args:tt)* )) => (
//! fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
//! $submac!(i, $($args)*)
//! }
//! );
//! );
//! ```
//!
//! If you want to call a combinator directly, you can
//! do it like this:
//!
//! ```ignore
//! let res = { tag!(input, "abcd"); }
//! ```
//!
//! Combinators must have a specific variant for
//! non-macro arguments. Example: passing a function
//! to filter! instead of another combinator.
//!
//! ```ignore
//! macro_rules! filter(
//! ($input:expr, $submac:ident!( $($args:tt)* )) => (
//! {
//! ...
//! }
//! );
//!
//! // wrap the function in a macro to pass it to the main implementation
//! ($input:expr, $f:expr) => (
//! filter!($input, call!($f));
//! );
//! );
//!
/// Wraps a parser in a closure
#[macro_export]
macro_rules! closure (
($ty:ty, $submac:ident!( $($args:tt)* )) => (
|i: $ty| { $submac!(i, $($args)*) }
);
($submac:ident!( $($args:tt)* )) => (
|i| { $submac!(i, $($args)*) }
);
);
/// Makes a function from a parser combination
///
/// The type can be set up if the compiler needs
/// more information
///
/// ```ignore
/// named!(my_function( &[u8] ) -> &[u8], tag!("abcd"));
/// // first type parameter is input, second is output
/// named!(my_function<&[u8], &[u8]>, tag!("abcd"));
/// // will have &[u8] as input type, &[u8] as output type
/// named!(my_function, tag!("abcd"));
/// // will use &[u8] as input type (use this if the compiler
/// // complains about lifetime issues
/// named!(my_function<&[u8]>, tag!("abcd"));
/// //prefix them with 'pub' to make the functions public
/// named!(pub my_function, tag!("abcd"));
/// ```
#[macro_export]
macro_rules! named (
($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: $i ) -> $crate::IResult<'a,$i,$o> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o> {
$submac!(i, $($args)*)
}
);
($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<'a, &'a [u8], $o> {
$submac!(i, $($args)*)
}
);
($name:ident<$life:item,$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<$life>( i: $i ) -> $crate::IResult<$life,$i, $o> {
$submac!(i, $($args)*)
}
);
($name:ident, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
$submac!(i, $($args)*)
}
);
(pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: $i ) -> $crate::IResult<'a,$i,$o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<'a, &'a [u8], $o> {
$submac!(i, $($args)*)
}
);
(pub $name:ident, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
$submac!(i, $($args)*)
}
);
);
/// Used to wrap common expressions and function as macros
#[macro_export]
macro_rules! call (
($i:expr, $fun:expr) => ( $fun( $i ) );
);
#[macro_export]
macro_rules! apply (
//($i:expr, $fun:ident( $($args:tt),*) ) => ($fun($i, $($args),*) );
($i:expr, $fun:expr, $arg:expr ) => ( $fun( $i, $arg ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr ) => ( $fun( $i, $arg, $arg2 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr ) => ( $fun( $i, $arg, $arg2, $arg3 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4, $arg5 ) );
($i:expr, $fun:expr, $arg:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr, $arg6:expr ) => ( $fun( $i, $arg, $arg2, $arg3, $arg4, $arg5, $arg6 ) );
);
/// Prevents backtracking if the child parser fails
///
/// This parser will do an early return instead of sending
/// its result to the parent parser.
///
/// If another `error!` combinator is present in the parent
/// chain, the error will be wrapped and another early
/// return will be made.
///
/// This makes it easy to build report on which parser failed,
/// where it failed in the input, and the chain of parsers
/// that led it there.
///
/// Additionally, the error chain contains number identifiers
/// that can be matched to provide useful error messages.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use std::collections;
/// # use nom::IResult::Error;
/// # use nom::Err::{Position,NodePosition};
/// # fn main() {
/// named!(err_test, alt!(
/// tag!("abcd") |
/// preceded!(tag!("efgh"), error!(42,
/// chain!(
/// tag!("ijkl") ~
/// res: error!(128, tag!("mnop")) ,
/// || { res }
/// )
/// )
/// )
/// ));
/// let a = &b"efghblah"[..];
/// let b = &b"efghijklblah"[..];
/// let c = &b"efghijklmnop"[..];
///
/// let blah = &b"blah"[..];
///
/// let res_a = err_test(a);
/// let res_b = err_test(b);
/// let res_c = err_test(c);
/// assert_eq!(res_a, Error(NodePosition(42, blah, Box::new(Position(0, blah)))));
/// assert_eq!(res_b, Error(NodePosition(42, &b"ijklblah"[..], Box::new(NodePosition(128, blah, Box::new(Position(0, blah)))))));
/// # }
#[macro_export]
macro_rules! error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
let cl = || {
$submac!($i, $($args)*)
};
match cl() {
//match cl($i) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
return $crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
error!($i, $code, call!($f));
);
);
/// declares a byte array as a suite to recognize
///
/// consumes the recognized characters
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(x, tag!("abcd"));
/// let r = x(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tag (
($i:expr, $inp: expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
if bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(bytes.len()))
} else if &$i[0..bytes.len()] == bytes {
$crate::IResult::Done(&$i[bytes.len()..], &$i[0..bytes.len()])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Tag as u32, $i))
}
}
);
);
/// flat_map! combines a parser R -> IResult<R,S> and
/// a parser S -> IResult<S,T> to return another
/// parser R -> IResult<R,T>
#[macro_export]
macro_rules! flat_map(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)),
$crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2)
}
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
flat_map!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $g:expr) => (
flat_map!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
flat_map!($i, call!($f), $submac!($($args)*));
);
);
/// maps a function on the result of a parser
#[macro_export]
macro_rules! map(
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_impl!($i, $submac!($($args)*), $submac2!($($args2)*),);
);
($i:expr, $f:expr, $g:expr) => (
map_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_impl(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, $submac2!(o, $($args2)*))
}
}
);
);
/// maps a function returning a Result on the output of a parser
#[macro_export]
macro_rules! map_res (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_res_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_res_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_res_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_res_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_res_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Ok(output) => $crate::IResult::Done(i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::MapRes as u32, $i))
}
}
}
);
);
/// maps a function returning an Option on the output of a parser
#[macro_export]
macro_rules! map_opt (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_opt_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_opt_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_opt_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_opt_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! map_opt_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Some(output) => $crate::IResult::Done(i, output),
None => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::MapOpt as u32, $i))
}
}
}
);
);
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
#[macro_export]
macro_rules! expr_res (
($i:expr, $e:expr) => (
{
match $e {
Ok(output) => $crate::IResult::Done($i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::ExprRes as u32, $i))
}
}
);
);
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
///
/// Useful when doing computations in a chain
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorCode};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// chain!(input,
/// sz: be_u8 ~
/// length: expr_opt!(size.checked_add(sz)) ~ // checking for integer overflow (returns an Option)
/// data: take!(length) ,
/// ||{ data }
/// )
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorCode::ExprOpt as u32,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! expr_opt (
($i:expr, $e:expr) => (
{
match $e {
Some(output) => $crate::IResult::Done($i, output),
None => $crate::IResult::Error($crate::Err::Position($crate::ErrorCode::ExprOpt as u32, $i))
}
}
);
);
/// chains parsers and assemble the results through a closure
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// #[derive(PartialEq,Eq,Debug)]
/// struct B {
/// a: u8,
/// b: Option<u8>
/// }
///
/// named!(y, tag!("efgh"));
///
/// fn ret_int(i:&[u8]) -> IResult<&[u8], u8> { Done(i, 1) }
/// named!(ret_y<&[u8], u8>, map!(y, |_| 1)); // return 1 if the "efgh" tag is found
///
/// named!(z<&[u8], B>,
/// chain!(
/// tag!("abcd") ~
/// aa: ret_int ~ // the result of that parser will be used in the closure
/// tag!("abcd")? ~ // this parser is optional
/// bb: ret_y? , // the result of that parser is an option
/// ||{B{a: aa, b: bb}}
/// )
/// );
///
/// # fn main() {
/// // the first "abcd" tag is not present, we have an error
/// let r1 = z(&b"efgh"[..]);
/// assert_eq!(r1, Error(Position(0,&b"efgh"[..])));
///
/// // everything is present, everything is parsed
/// let r2 = z(&b"abcdabcdefgh"[..]);
/// assert_eq!(r2, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the second "abcd" tag is optional
/// let r3 = z(&b"abcdefgh"[..]);
/// assert_eq!(r3, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the result of ret_y is optional, as seen in the B structure
/// let r4 = z(&b"abcdabcdwxyz"[..]);
/// assert_eq!(r4, Done(&b"wxyz"[..], B{a: 1, b: None}));
/// # }
/// ```
#[macro_export]
macro_rules! chain (
($i:expr, $($rest:tt)*) => (
chaining_parser!($i, $($rest)*)
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! chaining_parser (
($i:expr, $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, call!($e) ~ $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,_) => {
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, call!($e) ? ~ $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
chaining_parser!(input, $($rest)*)
}
}
);
($i:expr, $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $field: call!($e) ~ $($rest)*);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let $field = o;
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, mut $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, mut $field: call!($e) ~ $($rest)*);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let mut $field = o;
chaining_parser!(i, $($rest)*)
}
}
);
($i:expr, $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let ($field, input) = if let $crate::IResult::Done(i,o) = res {
(Some(o), i)
} else {
(None, $i)
};
chaining_parser!(input, $($rest)*)
}
}
);
($i:expr, mut $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, mut $field : call!($e) ? ~ $($rest)*);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let (mut $field, input) = if let $crate::IResult::Done(i,o) = res {
(Some(o), i)
} else {
(None, $i)
};
chaining_parser!(input, $($rest)*)
}
}
);
// ending the chain
($i:expr, $e:ident, $assemble:expr) => (
chaining_parser!($i, call!($e), $assemble);
);
($i:expr, $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $e:ident ?, $assemble:expr) => (
chaining_parser!($i, call!($e) ?, $assemble);
);
($i:expr, $submac:ident!( $($args:tt)* ) ?, $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
res => {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
$crate::IResult::Done(input, $assemble())
}
}
);
($i:expr, $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $field: call!($e), $assemble);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, mut $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, mut $field: call!($e), $assemble);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
let mut $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $field : call!($e) ? , $assemble);
);
($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Error(_) => {
let $field = None;
$crate::IResult::Done($i, $assemble())
},
$crate::IResult::Done(i,o) => {
let $field = Some(o);
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, mut $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $field : call!($e) ? , $assemble);
);
($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Error(_) => {
let mut $field = None;
$crate::IResult::Done($i, $assemble())
},
$crate::IResult::Done(i,o) => {
let mut $field = Some(o);
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $assemble:expr) => (
$crate::IResult::Done($i, $assemble())
)
);
/// try a list of parser, return the result of the first successful one
///
/// Incomplete results are ignored
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( test, alt!( tag!( "abcd" ) | tag!( "efgh" ) ) );
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], &b"abcd"[..]));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], &b"efgh"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! alt (
($i:expr, $($rest:tt)*) => (
{
alt_parser!($i, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! alt_parser (
($i:expr, $e:ident | $($rest:tt)*) => (
alt_parser!($i, call!($e) | $($rest)*);
);
($i:expr, $submac:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
if let $crate::IResult::Done(i,o) = $submac!($i, $($args)*) {
$crate::IResult::Done(i,o)
} else {
alt_parser!($i, $($rest)*)
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
if let $crate::IResult::Done(i,o) = $subrule!($i, $($args)*) {
$crate::IResult::Done(i, $gen( o ))
} else {
alt_parser!($i, $($rest)+)
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_parser!($i, call!($e) => { $gen } | $($rest)*);
);
($i:expr, $e:ident => { $gen:expr }) => (
alt_parser!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
match $subrule!( $i, $($args)* ) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, $gen( o )),
}
);
($i:expr, $e:ident) => (
alt_parser!($i, call!($e));
);
($i:expr, $submac:ident!( $($args:tt)*)) => (
{
if let $crate::IResult::Done(i,o) = $submac!($i, $($args)*) {
$crate::IResult::Done(i,o)
} else {
alt_parser!($i)
}
}
);
($i:expr) => (
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Alt as u32,$i))
);
);
/// returns the longest list of bytes that do not appear in the provided array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( not_space, is_not!( " \t\r\n" ) );
///
/// let r = not_space(&b"abcdefgh\nijkl"[..]);
/// assert_eq!(r, Done(&b"\nijkl"[..], &b"abcdefgh"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! is_not(
($input:expr, $arr:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $arr;
let bytes = as_bytes(&expected);
let mut parsed = false;
let mut index = 0;
for idx in 0..$input.len() {
index = idx;
for &i in bytes.iter() {
if $input[idx] == i {
parsed = true;
break;
}
}
if parsed { break; }
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::IsNot as u32,$input))
} else {
$crate::IResult::Done(&$input[index..], &$input[0..index])
}
}
);
);
/// returns the longest list of bytes that appear in the provided array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(abcd, is_a!( "abcd" ));
///
/// let r1 = abcd(&b"aaaaefgh"[..]);
/// assert_eq!(r1, Done(&b"efgh"[..], &b"aaaa"[..]));
///
/// let r2 = abcd(&b"dcbaefgh"[..]);
/// assert_eq!(r2, Done(&b"efgh"[..], &b"dcba"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! is_a(
($input:expr, $arr:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $arr;
let bytes = as_bytes(&expected);
let mut index = 0;
for idx in 0..$input.len() {
index = idx;
let mut cont = false;
for &i in bytes.iter() {
if $input[idx] == i {
cont = true;
break;
}
}
if !cont { break; }
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::IsA as u32,$input))
} else {
$crate::IResult::Done(&$input[index..], &$input[0..index])
}
}
);
);
/// returns the longest list of bytes until the provided function fails.
/// The argument is either a function `&[T] -> bool` or a macro returning a `bool`
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::is_alphanumeric;
/// # fn main() {
/// named!( alpha, filter!( is_alphanumeric ) );
///
/// let r = alpha(&b"abcd\nefgh"[..]);
/// assert_eq!(r, Done(&b"\nefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! filter(
($input:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut index = 0;
let mut found = false;
for idx in 0..$input.len() {
index = idx;
if !$submac!($input[idx], $($args)*) {
found = true;
break;
}
}
if index == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Filter as u32,$input))
} else if found {
$crate::IResult::Done(&$input[index..], &$input[0..index])
} else {
$crate::IResult::Done(&b""[..], $input)
}
}
);
($input:expr, $f:expr) => (
filter!($input, call!($f));
);
);
/// make the underlying parser optional
///
/// returns an Option of the returned type
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( o<&[u8], Option<&[u8]> >, opt!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], None));
/// # }
/// ```
#[macro_export]
macro_rules! opt(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt!($i, call!($f));
);
);
/// make the underlying parser optional
///
/// returns a Result, with Err containing the parsing error
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::Err::Position;
/// # fn main() {
/// named!( o<&[u8], Result<&[u8], nom::Err> >, opt_res!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Ok(&b"abcd"[..])));
/// assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(0, b))));
/// # }
/// ```
#[macro_export]
macro_rules! opt_res (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Ok(o)),
$crate::IResult::Error(e) => $crate::IResult::Done($i, Err(e)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt_res!($i, call!($f));
);
);
/// Conditional combinator
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an Option of the return type of the child
/// parser.
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Done($i, None)
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond!($i, $cond, call!($f));
);
);
/// Conditional combinator with error
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an error if the condition is false
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::{Err,ErrorCode};
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond_reduce!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], &b"abcd"[..]));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond_reduce!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Error(Err::Position(ErrorCode::CondReduce as u32, &a[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond_reduce(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::CondReduce as u32, $i))
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond_reduce!($i, $cond, call!($f));
);
);
/// returns a result without consuming the input
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(ptag, peek!( tag!( "abcd" ) ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! peek(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(_,o) => $crate::IResult::Done($i, o),
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
peek!($i, call!(f));
);
);
/// allows access to the parser's result without affecting it
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use std::str;
/// # fn main() {
/// named!(ptag, tap!(res: tag!( "abcd" ) => { println!("recognized {}", str::from_utf8(res).unwrap()) } ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tap (
($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => {
let $name = o;
$e;
$crate::IResult::Done(i, $name)
},
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $name: ident: $f:expr => $e:expr) => (
tap!($i, $name: call!(f) => $e);
);
);
/// pair(X,Y), returns (x,y)
#[macro_export]
macro_rules! pair(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, (o1, o2))
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
pair!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
pair!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
pair!($i, call!($f), call!($g));
);
);
/// separated_pair(X,sep,Y) returns (x,y)
#[macro_export]
macro_rules! separated_pair(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
separated_pair1!(i1, o1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
separated_pair!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! separated_pair1(
($i:expr, $res1:ident, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
separated_pair2!(i2, $res1, $($rest)*)
}
}
}
);
($i:expr, $res1:ident, $g:expr, $($rest:tt)+) => (
separated_pair1!($i, $res1, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! separated_pair2(
($i:expr, $res1:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,o3) => {
$crate::IResult::Done(i3, ($res1, o3))
}
}
}
);
($i:expr, $res1:ident, $h:expr) => (
separated_pair2!($i, $res1, call!($h));
);
);
/// preceded(opening, X) returns X
#[macro_export]
macro_rules! preceded(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, o2)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
preceded!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
preceded!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
preceded!($i, call!($f), call!($g));
);
);
/// terminated(X, closing) returns X
#[macro_export]
macro_rules! terminated(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
$crate::IResult::Done(i2, o1)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
terminated!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
terminated!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
terminated!($i, call!($f), call!($g));
);
);
/// delimited(opening, X, closing) returns X
#[macro_export]
macro_rules! delimited(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
delimited1!(i1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
delimited!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! delimited1(
($i:expr, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
delimited2!(i2, o2, $($rest)*)
}
}
}
);
($i:expr, $g:expr, $($rest:tt)+) => (
delimited1!($i, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[macro_export]
macro_rules! delimited2(
($i:expr, $res2:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,_) => {
$crate::IResult::Done(i3, $res2)
}
}
}
);
($i:expr, $res2:ident, $h:expr) => (
delimited2!($i, $res2, call!($h));
);
);
/// separated_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
// get the first element
match $submac!($i, $($args2)*) {
$crate::IResult::Error(_) => $crate::IResult::Done($i, Vec::new()),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == $i.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::SeparatedList as u32,$i))
} else {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
loop {
// get the separator first
match $sep!(&$i[begin..], $($args)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i2,_) => {
if i2.len() == (&$i[begin..]).len() {
break;
}
begin += remaining - i2.len();
remaining = i2.len();
// get the element next
match $submac!(&$i[begin..], $($args2)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i3,o3) => {
if i3.len() == $i[begin..].len() {
break;
}
res.push(o3);
begin += remaining - i3.len();
remaining = i3.len();
},
}
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_list!($i, call!($f), call!($g));
);
);
/// separated_nonempty_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_nonempty_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
// get the first element
match $submac!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == $i.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::SeparatedNonEmptyList as u32,$i))
} else {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
loop {
// get the separator first
match $sep!(&$i[begin..], $($args)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i2,_) => {
if i2.len() == (&$i[begin..]).len() {
break;
}
begin += remaining - i2.len();
remaining = i2.len();
// get the element next
match $submac!(&$i[begin..], $($args2)*) {
$crate::IResult::Error(_) => break,
$crate::IResult::Incomplete(_) => break,
$crate::IResult::Done(i3,o3) => {
if i3.len() == $i[begin..].len() {
break;
}
res.push(o3);
begin += remaining - i3.len();
remaining = i3.len();
},
}
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_nonempty_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_nonempty_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_nonempty_list!($i, call!($f), call!($g));
);
);
/// Applies the parser 0 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many0!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdef";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"ef"[..], res));
/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new()));
/// # }
/// ```
/// 0 or more
#[macro_export]
macro_rules! many0(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
if i.len() == $i[begin..].len() {
break;
}
res.push(o);
begin += remaining - i.len();
remaining = i.len();
},
_ => {
break;
}
}
}
$crate::IResult::Done(&$i[begin..], res)
}
);
($i:expr, $f:expr) => (
many0!($i, call!($f));
);
);
/// Applies the parser 1 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many1!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdef";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"ef"[..], res));
/// assert_eq!(multi(&b[..]), Error(Position(ErrorCode::Many1 as u32,&b[..])));
/// # }
/// ```
#[macro_export]
macro_rules! many1(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
if i.len() == $i[begin..].len() {
break;
}
res.push(o);
begin += remaining - i.len();
remaining = i.len();
},
_ => {
break;
}
}
}
if res.len() == 0 {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Many1 as u32,$i))
} else {
$crate::IResult::Done(&$i[begin..], res)
}
}
);
($i:expr, $f:expr) => (
many1!($i, call!($f));
);
);
/// Applies the child parser a specified number of times
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(counter< Vec<&[u8]> >, count!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count(
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
let mut cnt: usize = 0;
let mut err = false;
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
res.push(o);
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $count {
break
}
},
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete(_) => {
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Count as u32,$i))
} else if cnt == $count {
$crate::IResult::Done(&$i[begin..], res)
} else {
$crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
);
($i:expr, $f:expr, $count: expr) => (
count!($i, call!($f), $count);
);
);
/// Applies the child parser a fixed number of times and returns a fixed size array
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorCode;
/// # fn main() {
/// named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
/// // can omit the type specifier if returning slices
/// // named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = [&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count_fixed(
($i:expr, $typ:ty, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res: [$typ; $count] = unsafe{[::std::mem::uninitialized(); $count as usize]};
let mut cnt: usize = 0;
let mut err = false;
loop {
match $submac!(&$i[begin..], $($args)*) {
$crate::IResult::Done(i,o) => {
res[cnt] = o;
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $count {
break
}
},
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete(_) => {
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::Count as u32,$i))
} else if cnt == $count {
$crate::IResult::Done(&$i[begin..], res)
} else {
$crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
);
($i:expr, $typ: ty, $f:ident, $count: expr) => (
count_fixed!($i, $typ, call!($f), $count);
);
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
count_fixed!($i, &[u8], $submac!($($args)*), $count);
);
($i:expr, $f:ident, $count: expr) => (
count_fixed!($i, &[u8], call!($f), $count);
);
);
/// generates a parser consuming the specified number of bytes
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// // Desmond parser
/// named!(take5, take!( 5 ) );
///
/// let a = b"abcdefgh";
///
/// assert_eq!(take5(&a[..]), Done(&b"fgh"[..], &b"abcde"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! take(
($i:expr, $count:expr) => (
{
let cnt = $count as usize;
if $i.len() < cnt {
$crate::IResult::Incomplete($crate::Needed::Size(cnt))
} else {
$crate::IResult::Done(&$i[cnt..],&$i[0..cnt])
}
}
);
);
/// same as take! but returning a &str
#[macro_export]
macro_rules! take_str (
( $i:expr, $size:expr ) => ( map_res!($i, take!($size), from_utf8) );
);
/// generates a parser consuming bytes until the specified byte sequence is found
#[macro_export]
macro_rules! take_until_and_consume(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + bytes.len() > $i.len() {
index = idx;
break;
}
if &$i[idx..idx + bytes.len()] == bytes {
parsed = true;
index = idx;
break;
}
}
if index + bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + bytes.len()))
} else {
if parsed {
$crate::IResult::Done(&$i[(index + bytes.len())..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilAndConsume as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + bytes.len() > $i.len() {
index = idx;
break;
}
if &$i[idx..idx+bytes.len()] == bytes {
parsed = true;
index = idx;
break;
}
}
if index + bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + bytes.len()))
} else {
if parsed {
$crate::IResult::Done(&$i[index..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntil as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until_either_and_consume(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + 1 > $i.len() {
index = idx;
break;
}
for &t in bytes.iter() {
if $i[idx] == t {
parsed = true;
index = idx;
break;
}
}
if parsed { break; }
}
if index + 1 > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + 1))
} else {
if parsed {
$crate::IResult::Done(&$i[(index+1)..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilEitherAndConsume as u32,$i))
}
}
}
);
);
#[macro_export]
macro_rules! take_until_either(
($i:expr, $inp:expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let mut index = 0;
let mut parsed = false;
for idx in 0..$i.len() {
if idx + 1 > $i.len() {
index = idx;
break;
}
for &t in bytes.iter() {
if $i[idx] == t {
parsed = true;
index = idx;
break;
}
}
if parsed { break; }
}
if index + 1 > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(index + 1))
} else {
if parsed {
$crate::IResult::Done(&$i[index..], &$i[0..index])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::TakeUntilEither as u32,$i))
}
}
}
);
);
/// gets a number from the first parser, then applies the second parser that many times
#[macro_export]
macro_rules! length_value(
($i:expr, $f:expr, $g:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,nb) => {
let length_token = $i.len() - i1.len();
let mut begin = 0;
let mut remaining = i1.len();
let mut res = Vec::new();
let mut err = false;
let mut inc = $crate::Needed::Unknown;
loop {
if res.len() == nb as usize {
break;
}
match $g(&i1[begin..]) {
$crate::IResult::Done(i2,o2) => {
res.push(o2);
let parsed = remaining - i2.len();
begin += parsed;
remaining = i2.len();
},
$crate::IResult::Error(_) => {
err = true;
},
$crate::IResult::Incomplete(a) => {
inc = a;
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::LengthValue as u32,$i))
} else if res.len() < nb as usize {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(length) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + nb as usize * length))
}
} else {
$crate::IResult::Done(&i1[begin..], res)
}
}
}
}
);
($i:expr, $f:expr, $g:expr, $length:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,nb) => {
let length_token = $i.len() - i1.len();
let mut begin = 0;
let mut remaining = i1.len();
let mut res = Vec::new();
let mut err = false;
let mut inc = $crate::Needed::Unknown;
loop {
if res.len() == nb as usize {
break;
}
match $g(&i1[begin..]) {
$crate::IResult::Done(i2,o2) => {
res.push(o2);
let parsed = remaining - i2.len();
begin += parsed;
remaining = i2.len();
},
$crate::IResult::Error(_) => {
err = true;
},
$crate::IResult::Incomplete(a) => {
inc = a;
break;
}
}
}
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorCode::LengthValue as u32,$i))
} else if res.len() < nb as usize {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(_) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + nb as usize * $length))
}
} else {
$crate::IResult::Done(&i1[begin..], res)
}
}
}
}
);
);
#[cfg(test)]
mod tests {
use internal::{Needed,IResult,Err};
use internal::IResult::*;
use internal::Err::*;
use util::ErrorCode;
mod pub_named_mod {
named!(pub tst, tag!("abcd"));
}
#[test]
fn pub_named_test() {
let a = &b"abcd"[..];
let res = pub_named_mod::tst(a);
assert_eq!(res, Done(&b""[..], a));
}
#[test]
fn apply_test() {
fn sum2(a:u8, b:u8) -> u8 { a + b }
fn sum3(a:u8, b:u8, c:u8) -> u8 { a + b + c }
let a = apply!(1, sum2, 2);
let b = apply!(1, sum3, 2, 3);
assert_eq!(a, 3);
assert_eq!(b, 6);
}
#[test]
fn is_a() {
named!(a_or_b, is_a!(&b"ab"[..]));
let a = &b"abcd"[..];
assert_eq!(a_or_b(a), Done(&b"cd"[..], &b"ab"[..]));
let b = &b"bcde"[..];
assert_eq!(a_or_b(b), Done(&b"cde"[..], &b"b"[..]));
let c = &b"cdef"[..];
assert_eq!(a_or_b(c), Error(Position(ErrorCode::IsA as u32,c)));
let d = &b"bacdef"[..];
assert_eq!(a_or_b(d), Done(&b"cdef"[..], &b"ba"[..]));
}
#[derive(PartialEq,Eq,Debug)]
struct B {
a: u8,
b: u8
}
#[test]
fn chain2() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[test]
fn nested_chain() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
chain!(
tag!("abcd") ~
tag!("abcd")? ,
|| {}
) ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[derive(PartialEq,Eq,Debug)]
struct C {
a: u8,
b: Option<u8>
}
#[test]
fn chain_mut() {
fn ret_b1_2(i:&[u8]) -> IResult<&[u8], B> { Done(i,B{a:1,b:2}) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
tag!("efgh") ~
mut bb: ret_b1_2 ~
tag!("efgh") ,
||{
bb.b = 3;
bb
}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 3}));
}
#[test]
fn chain_opt() {
named!(y, tag!("efgh"));
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
named!(ret_y<&[u8], u8>, map!(y, |_| 2));
named!(f<&[u8],C>,
chain!(
tag!("abcd") ~
aa: ret_int1 ~
bb: ret_y? ,
||{C{a: aa, b: bb}}
)
);
let r = f(&b"abcdefghX"[..]);
assert_eq!(r, Done(&b"X"[..], C{a: 1, b: Some(2)}));
let r2 = f(&b"abcdWXYZ"[..]);
assert_eq!(r2, Done(&b"WXYZ"[..], C{a: 1, b: None}));
let r3 = f(&b"abcdX"[..]);
assert_eq!(r3, Incomplete(Needed::Size(4)));
}
use util::{error_to_list, add_error_pattern, print_error};
fn error_to_string(e: Err) -> &str {
let v:Vec<u32> = error_to_list(e);
// do it this way if you can use slice patterns
/*
match &v[..] {
[42, 0] => "missing `ijkl` tag",
[42, 128, 0] => "missing `mnop` tag after `ijkl`",
_ => "unrecognized error"
}
*/
if &v[..] == [42,0] {
"missing `ijkl` tag"
} else if &v[..] == [42, 128, 0] {
"missing `mnop` tag after `ijkl`"
} else {
"unrecognized error"
}
}
// do it this way if you can use box patterns
/*use std::str;
fn error_to_string(e:Err) -> String
match e {
NodePosition(42, i1, box Position(0, i2)) => {
format!("missing `ijkl` tag, found '{}' instead", str::from_utf8(i2).unwrap())
},
NodePosition(42, i1, box NodePosition(128, i2, box Position(0, i3))) => {
format!("missing `mnop` tag after `ijkl`, found '{}' instead", str::from_utf8(i3).unwrap())
},
_ => "unrecognized error".to_string()
}
}*/
use std::collections;
#[test]
fn err() {
named!(err_test, alt!(
tag!("abcd") |
preceded!(tag!("efgh"), error!(42,
chain!(
tag!("ijkl") ~
res: error!(128, tag!("mnop")) ,
|| { res }
)
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(42, blah, Box::new(Position(0, blah)))));
assert_eq!(res_b, Error(NodePosition(42, &b"ijklblah"[..], Box::new(NodePosition(128, blah, Box::new(Position(0, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
// Merr-like error matching
let mut err_map = collections::HashMap::new();
assert!(add_error_pattern(&mut err_map, err_test(&b"efghpouet"[..]), "missing `ijkl` tag"));
assert!(add_error_pattern(&mut err_map, err_test(&b"efghijklpouet"[..]), "missing `mnop` tag after `ijkl`"));
let res_a2 = res_a.clone();
match res_a {
Error(e) => {
let e2 = e.clone();
let e3 = e.clone();
assert_eq!(error_to_list(e), [42, 0]);
assert_eq!(error_to_string(e2), "missing `ijkl` tag");
assert_eq!(err_map.get(&error_to_list(e3)), Some(&"missing `ijkl` tag"));
},
_ => panic!()
};
let res_b2 = res_b.clone();
match res_b {
Error(e) => {
let e2 = e.clone();
let e3 = e.clone();
assert_eq!(error_to_list(e), [42, 128, 0]);
assert_eq!(error_to_string(e2), "missing `mnop` tag after `ijkl`");
assert_eq!(err_map.get(&error_to_list(e3)), Some(&"missing `mnop` tag after `ijkl`"));
},
_ => panic!()
};
print_error(a, res_a2);
print_error(b, res_b2);
}
#[test]
fn alt() {
fn work(input: &[u8]) -> IResult<&[u8],&[u8]> {
Done(&b""[..], input)
}
#[allow(unused_variables)]
fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8]> {
Error(Code(42))
}
fn work2(input: &[u8]) -> IResult<&[u8],&[u8]> {
Done(input, &b""[..])
}
named!(alt1, alt!(dont_work | dont_work));
named!(alt2, alt!(dont_work | work));
named!(alt3, alt!(dont_work | dont_work | work2 | dont_work));
let a = &b"abcd"[..];
assert_eq!(alt1(a), Error(Position(ErrorCode::Alt as u32, a)));
assert_eq!(alt2(a), Done(&b""[..], a));
assert_eq!(alt3(a), Done(a, &b""[..]));
named!(alt4, alt!(tag!("abcd") | tag!("efgh")));
let b = &b"efgh"[..];
assert_eq!(alt4(a), Done(&b""[..], a));
assert_eq!(alt4(b), Done(&b""[..], b));
}
#[test]
fn opt() {
named!(o<&[u8],Option<&[u8]> >, opt!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Some(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], None));
}
#[test]
fn opt_res() {
named!(o<&[u8], Result<&[u8], Err> >, opt_res!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Ok(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(0, b))));
}
#[test]
fn cond() {
let b = true;
let f = closure!(&'static [u8], cond!( b, tag!("abcd") ) );
let a = b"abcdef";
assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
let b2 = false;
let f2 = closure!(&'static [u8], cond!( b2, tag!("abcd") ) );
assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
}
#[test]
fn cond_wrapping() {
// Test that cond!() will wrap a given identifier in the call!() macro.
named!(silly, tag!("foo"));
let b = true;
let f = closure!(&'static [u8], cond!( b, silly ) );
assert_eq!(f(b"foobar"), Done(&b"bar"[..], Some(&b"foo"[..])));
}
#[test]
fn peek() {
named!(ptag<&[u8],&[u8]>, peek!(tag!("abcd")));
let r1 = ptag(&b"abcdefgh"[..]);
assert_eq!(r1, Done(&b"abcdefgh"[..], &b"abcd"[..]));
let r1 = ptag(&b"efgh"[..]);
assert_eq!(r1, Error(Position(0,&b"efgh"[..])));
}
#[test]
fn pair() {
named!(p<&[u8],(&[u8], &[u8])>, pair!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn separated_pair() {
named!(p<&[u8],(&[u8], &[u8])>, separated_pair!(tag!("abcd"), tag!(","), tag!("efgh")));
let r1 = p(&b"abcd,efghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn preceded() {
named!(p<&[u8], &[u8]>, preceded!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"efgh"[..]));
}
#[test]
fn terminated() {
named!(p<&[u8], &[u8]>, terminated!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"abcd"[..]));
}
#[test]
fn delimited() {
named!(p<&[u8], &[u8]>, delimited!(tag!("abcd"), tag!("efgh"), tag!("ij")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"kl"[..], &b"efgh"[..]));
}
#[test]
fn separated_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
}
#[test]
fn separated_nonempty_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(0,c)));
}
#[test]
fn many0() {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
}
#[test]
fn many1() {
named!(multi<&[u8],Vec<&[u8]> >, many1!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorCode::Many1 as u32,c)));
}
#[test]
fn infinite_many() {
fn tst(input: &[u8]) -> IResult<&[u8], &[u8]> {
println!("input: {:?}", input);
Error(Position(0,input))
}
// should not go into an infinite loop
named!(multi0<&[u8],Vec<&[u8]> >, many0!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi0(a), Done(a, Vec::new()));
named!(multi1<&[u8],Vec<&[u8]> >, many1!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi1(a), Error(Position(ErrorCode::Many1 as u32,a)));
}
#[test]
fn count() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 2;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
#[test]
fn count_fixed() {
named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
use nom::{le_u16,eof};
#[allow(dead_code)]
pub fn compile_count_fixed(input: &[u8]) -> IResult<&[u8], ()> {
chain!(input,
tag!("abcd") ~
count_fixed!( u16, le_u16, 4 ) ~
eof ,
|| { () }
)
}
#[test]
fn count_fixed_no_type() {
named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorCode::Count as u32, &b[..])));
}
use std::str::from_utf8;
#[test]
fn take_str_test() {
let a = b"omnomnom";
assert_eq!(take_str!(&a[..], 5), Done(&b"nom"[..], "omnom"));
assert_eq!(take_str!(&a[..], 9), Incomplete(Needed::Size(9)));
}
#[test]
fn take_until_test() {
named!(x, take_until_and_consume!("efgh"));
let r = x(&b"abcdabcdefghijkl"[..]);
assert_eq!(r, Done(&b"ijkl"[..], &b"abcdabcd"[..]));
println!("Done 1\n");
let r2 = x(&b"abcdabcdefgh"[..]);
assert_eq!(r2, Done(&b""[..], &b"abcdabcd"[..]));
println!("Done 2\n");
let r3 = x(&b"abcefg"[..]);
assert_eq!(r3, Incomplete(Needed::Size(7)));
}
use nom::{be_u8,be_u16};
#[test]
fn length_value_test() {
named!(tst1<&[u8], Vec<u16> >, length_value!(be_u8, be_u16));
named!(tst2<&[u8], Vec<u16> >, length_value!(be_u8, be_u16, 2));
let i1 = vec![0, 5, 6];
let i2 = vec![1, 5, 6, 3];
let i3 = vec![2, 5, 6, 3];
let i4 = vec![2, 5, 6, 3, 4, 5, 7];
let i5 = vec![3, 5, 6, 3, 4, 5];
let r1: Vec<u16> = Vec::new();
let r2: Vec<u16> = vec![1286];
let r4: Vec<u16> = vec![1286, 772];
assert_eq!(tst1(&i1), IResult::Done(&i1[1..], r1));
assert_eq!(tst1(&i2), IResult::Done(&i2[3..], r2));
assert_eq!(tst1(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst1(&i4), IResult::Done(&i4[5..], r4));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
let r6: Vec<u16> = Vec::new();
let r7: Vec<u16> = vec![1286];
let r9: Vec<u16> = vec![1286, 772];
assert_eq!(tst2(&i1), IResult::Done(&i1[1..], r6));
assert_eq!(tst2(&i2), IResult::Done(&i2[3..], r7));
assert_eq!(tst2(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst2(&i4), IResult::Done(&i4[5..], r9));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
}
}
|
// Vector/Point macros
macro_rules! n_pointvector {
(ops $lhs:ident; $rhs:ident {$($field:ident),*}) => {
impl<F: Float> ::std::ops::Add<$rhs<F>> for $lhs<F> {
type Output = $lhs<F>;
fn add(self, rhs: $rhs<F>) -> $lhs<F> {
$lhs {
$($field: self.$field + rhs.$field),*
}
}
}
impl<F: Float> ::std::ops::Sub<$rhs<F>> for $lhs<F> {
type Output = $lhs<F>;
fn sub(self, rhs: $rhs<F>) -> $lhs<F> {
$lhs {
$($field: self.$field - rhs.$field),*
}
}
}
};
(float ops $name:ident {$($field:ident),+}) => {
impl<F: Float> Mul<F> for $name<F> {
type Output = $name<F>;
fn mul(self, rhs: F) -> $name<F> {
$name {
$($field: self.$field * rhs),+
}
}
}
impl<F: Float> Div<F> for $name<F> {
type Output = $name<F>;
fn div(self, rhs: F) -> $name<F> {
$name {
$($field: self.$field / rhs),+
}
}
}
impl<F: Float> Neg for $name<F> {
type Output = $name<F>;
fn neg(self) -> $name<F> {
$name {
$($field: -self.$field),+
}
}
}
};
(struct $dims:expr; $name:ident {$($field:ident: $f_ty:ident),+} $sibling:ident) => {
#[derive(Debug, Clone, Copy)]
pub struct $name<F: Float> {
$(pub $field: F),+
}
impl<F: Float> $name<F> {
pub fn new($($field: F),+) -> $name<F> {
$name {
$($field: $field),+
}
}
}
impl<F: Float> ::std::convert::Into<[F; $dims]> for $name<F> {
fn into(self) -> [F; $dims] {
[$(self.$field),*]
}
}
impl<F: Float> ::std::convert::Into<($($f_ty),*)> for $name<F> {
fn into(self) -> ($($f_ty),*) {
($(self.$field),*)
}
}
impl<F: Float> ::std::convert::From<$sibling<F>> for $name<F> {
fn from(sib: $sibling<F>) -> $name<F> {
$name {
$($field: sib.$field),*
}
}
}
n_pointvector!(ops $name; $sibling {$($field),+});
n_pointvector!(ops $name; $name {$($field),+});
n_pointvector!(float ops $name {$($field),+});
};
($dims:expr; $p_name:ident, $v_name:ident {$($field:ident),+}) => {
n_pointvector!(struct $dims; $p_name {$($field: F),+} $v_name);
n_pointvector!(struct $dims; $v_name {$($field: F),+} $p_name);
impl<F: Float + FromPrimitive> $v_name<F> {
pub fn len(self) -> F {
($(self.$field.powi(2) +)+ F::from_f32(0.0).unwrap()).sqrt()
}
pub fn normalize(self) -> $v_name<F> {
self / self.len()
}
}
}
}
// Polynomial Macros
macro_rules! count {
($idc:tt) => (1);
($($element:tt),*) => {{$(count!($element) +)* 0}};
}
macro_rules! n_bezier {
($name:ident {
$($field:ident: $weight:expr),+
} derived {
$($dleft:ident - $dright:ident: $dweight:expr),+
}) => {
#[derive(Debug, Clone)]
pub struct $name<F> where F: ::num::Float + ::num::FromPrimitive {
$(pub $field: F),+
}
impl<F> $name<F> where F: ::num::Float + ::num::FromPrimitive {
pub fn new($($field: F),+) -> $name<F> {
$name {
$($field: $field),+
}
}
pub fn interp(&self, t: F) -> F {
$crate::check_t_bounds(t);
self.interp_unbounded(t)
}
pub fn interp_unbounded(&self, t: F) -> F {
let t1 = F::from_f32(1.0).unwrap() - t;
const COUNT: i32 = count!($($field),+) - 1;
let mut factor = COUNT + 1;
$(
factor -= 1;
let $field =
t1.powi(factor) *
t.powi(COUNT-factor) *
self.$field *
F::from_i32($weight).unwrap();
)+
$($field +)+ F::from_f32(0.0).unwrap()
}
pub fn slope(&self, t: F) -> F {
$crate::check_t_bounds(t);
self.slope_unbounded(t)
}
pub fn slope_unbounded(&self, t: F) -> F {
let t1 = F::from_f32(1.0).unwrap() - t;
const COUNT: i32 = count!($($dleft),+) - 1;
let mut factor = COUNT + 1;
$(
factor -= 1;
let $dleft =
t1.powi(factor) *
t.powi(COUNT-factor) *
(self.$dleft - self.$dright) *
F::from_i32($dweight * (COUNT + 1)).unwrap();
)+
$($dleft +)+ F::from_f32(0.0).unwrap()
}
}
impl<F> ::std::ops::Deref for $name<F> where F: ::num::Float + ::num::FromPrimitive {
type Target = [F];
fn deref(&self) -> &[F] {
use std::slice;
unsafe {
slice::from_raw_parts(self as *const $name<F> as *const F, count!($($field),+))
}
}
}
impl<F> ::std::ops::DerefMut for $name<F> where F: ::num::Float + ::num::FromPrimitive {
fn deref_mut(&mut self) -> &mut [F] {
use std::slice;
unsafe {
slice::from_raw_parts_mut(self as *mut $name<F> as *mut F, count!($($field),+))
}
}
}
}
}
macro_rules! bez_composite {
($name:ident<$poly:ident> {
$($field:ident: $($n_field:ident),+;)+
} -> <$point:ident; $vector:ident>;
$($dim:ident = $($dfield:ident),+;)+) =>
{
#[derive(Debug, Clone)]
pub struct $name<F: ::num::Float + ::num::FromPrimitive> {
$(pub $field: $point<F>),+
}
impl<F: ::num::Float + ::num::FromPrimitive> $name<F> {
pub fn new($($($n_field: F),+),+) -> $name<F> {
$name {
$($field: $point::new($($n_field),+)),+
}
}
pub fn interp(&self, t: F) -> $point<F> {
$crate::check_t_bounds(t);
self.interp_unbounded(t)
}
pub fn interp_unbounded(&self, t: F) -> $point<F> {
$(let $dim = $poly::new($(self.$dfield.$dim),+);)+
$point::new($($dim.interp_unbounded(t)),+)
}
pub fn slope(&self, t: F) -> $vector<F> {
$crate::check_t_bounds(t);
self.slope_unbounded(t)
}
pub fn slope_unbounded(&self, t: F) -> $vector<F> {
$(let $dim = $poly::new($(self.$dfield.$dim),+);)+
$vector::new($($dim.slope_unbounded(t)),+)
}
}
};
}
Added `Copy` implementations for bezier polynomials and curves.
// Vector/Point macros
macro_rules! n_pointvector {
(ops $lhs:ident; $rhs:ident {$($field:ident),*}) => {
impl<F: Float> ::std::ops::Add<$rhs<F>> for $lhs<F> {
type Output = $lhs<F>;
fn add(self, rhs: $rhs<F>) -> $lhs<F> {
$lhs {
$($field: self.$field + rhs.$field),*
}
}
}
impl<F: Float> ::std::ops::Sub<$rhs<F>> for $lhs<F> {
type Output = $lhs<F>;
fn sub(self, rhs: $rhs<F>) -> $lhs<F> {
$lhs {
$($field: self.$field - rhs.$field),*
}
}
}
};
(float ops $name:ident {$($field:ident),+}) => {
impl<F: Float> Mul<F> for $name<F> {
type Output = $name<F>;
fn mul(self, rhs: F) -> $name<F> {
$name {
$($field: self.$field * rhs),+
}
}
}
impl<F: Float> Div<F> for $name<F> {
type Output = $name<F>;
fn div(self, rhs: F) -> $name<F> {
$name {
$($field: self.$field / rhs),+
}
}
}
impl<F: Float> Neg for $name<F> {
type Output = $name<F>;
fn neg(self) -> $name<F> {
$name {
$($field: -self.$field),+
}
}
}
};
(struct $dims:expr; $name:ident {$($field:ident: $f_ty:ident),+} $sibling:ident) => {
#[derive(Debug, Clone, Copy)]
pub struct $name<F: Float> {
$(pub $field: F),+
}
impl<F: Float> $name<F> {
pub fn new($($field: F),+) -> $name<F> {
$name {
$($field: $field),+
}
}
}
impl<F: Float> ::std::convert::Into<[F; $dims]> for $name<F> {
fn into(self) -> [F; $dims] {
[$(self.$field),*]
}
}
impl<F: Float> ::std::convert::Into<($($f_ty),*)> for $name<F> {
fn into(self) -> ($($f_ty),*) {
($(self.$field),*)
}
}
impl<F: Float> ::std::convert::From<$sibling<F>> for $name<F> {
fn from(sib: $sibling<F>) -> $name<F> {
$name {
$($field: sib.$field),*
}
}
}
n_pointvector!(ops $name; $sibling {$($field),+});
n_pointvector!(ops $name; $name {$($field),+});
n_pointvector!(float ops $name {$($field),+});
};
($dims:expr; $p_name:ident, $v_name:ident {$($field:ident),+}) => {
n_pointvector!(struct $dims; $p_name {$($field: F),+} $v_name);
n_pointvector!(struct $dims; $v_name {$($field: F),+} $p_name);
impl<F: Float + FromPrimitive> $v_name<F> {
pub fn len(self) -> F {
($(self.$field.powi(2) +)+ F::from_f32(0.0).unwrap()).sqrt()
}
pub fn normalize(self) -> $v_name<F> {
self / self.len()
}
}
}
}
// Polynomial Macros
macro_rules! count {
($idc:tt) => (1);
($($element:tt),*) => {{$(count!($element) +)* 0}};
}
macro_rules! n_bezier {
($name:ident {
$($field:ident: $weight:expr),+
} derived {
$($dleft:ident - $dright:ident: $dweight:expr),+
}) => {
#[derive(Debug, Clone, Copy)]
pub struct $name<F> where F: ::num::Float + ::num::FromPrimitive {
$(pub $field: F),+
}
impl<F> $name<F> where F: ::num::Float + ::num::FromPrimitive {
pub fn new($($field: F),+) -> $name<F> {
$name {
$($field: $field),+
}
}
pub fn interp(&self, t: F) -> F {
$crate::check_t_bounds(t);
self.interp_unbounded(t)
}
pub fn interp_unbounded(&self, t: F) -> F {
let t1 = F::from_f32(1.0).unwrap() - t;
const COUNT: i32 = count!($($field),+) - 1;
let mut factor = COUNT + 1;
$(
factor -= 1;
let $field =
t1.powi(factor) *
t.powi(COUNT-factor) *
self.$field *
F::from_i32($weight).unwrap();
)+
$($field +)+ F::from_f32(0.0).unwrap()
}
pub fn slope(&self, t: F) -> F {
$crate::check_t_bounds(t);
self.slope_unbounded(t)
}
pub fn slope_unbounded(&self, t: F) -> F {
let t1 = F::from_f32(1.0).unwrap() - t;
const COUNT: i32 = count!($($dleft),+) - 1;
let mut factor = COUNT + 1;
$(
factor -= 1;
let $dleft =
t1.powi(factor) *
t.powi(COUNT-factor) *
(self.$dleft - self.$dright) *
F::from_i32($dweight * (COUNT + 1)).unwrap();
)+
$($dleft +)+ F::from_f32(0.0).unwrap()
}
}
impl<F> ::std::ops::Deref for $name<F> where F: ::num::Float + ::num::FromPrimitive {
type Target = [F];
fn deref(&self) -> &[F] {
use std::slice;
unsafe {
slice::from_raw_parts(self as *const $name<F> as *const F, count!($($field),+))
}
}
}
impl<F> ::std::ops::DerefMut for $name<F> where F: ::num::Float + ::num::FromPrimitive {
fn deref_mut(&mut self) -> &mut [F] {
use std::slice;
unsafe {
slice::from_raw_parts_mut(self as *mut $name<F> as *mut F, count!($($field),+))
}
}
}
}
}
macro_rules! bez_composite {
($name:ident<$poly:ident> {
$($field:ident: $($n_field:ident),+;)+
} -> <$point:ident; $vector:ident>;
$($dim:ident = $($dfield:ident),+;)+) =>
{
#[derive(Debug, Clone, Copy)]
pub struct $name<F: ::num::Float + ::num::FromPrimitive> {
$(pub $field: $point<F>),+
}
impl<F: ::num::Float + ::num::FromPrimitive> $name<F> {
pub fn new($($($n_field: F),+),+) -> $name<F> {
$name {
$($field: $point::new($($n_field),+)),+
}
}
pub fn interp(&self, t: F) -> $point<F> {
$crate::check_t_bounds(t);
self.interp_unbounded(t)
}
pub fn interp_unbounded(&self, t: F) -> $point<F> {
$(let $dim = $poly::new($(self.$dfield.$dim),+);)+
$point::new($($dim.interp_unbounded(t)),+)
}
pub fn slope(&self, t: F) -> $vector<F> {
$crate::check_t_bounds(t);
self.slope_unbounded(t)
}
pub fn slope_unbounded(&self, t: F) -> $vector<F> {
$(let $dim = $poly::new($(self.$dfield.$dim),+);)+
$vector::new($($dim.slope_unbounded(t)),+)
}
}
};
} |
/// Macro emulating `do`-notation for the parser monad, automatically threading the linear type.
///
/// ```ignore
/// parse!{input;
/// parser("parameter");
/// let value = other_parser();
///
/// ret do_something(value);
/// }
/// // is equivalent to:
/// parser(input, "parameter").bind(|i, _|
/// other_parser(i).bind(|i, value|
/// i.ret(do_something(value))))
/// ```
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate chomp;
/// # fn main() {
/// use chomp::{Input, Error};
/// use chomp::{take_while1, token};
///
/// let i = Input::new("Martin Wernstål\n".as_bytes());
///
/// #[derive(Debug, Eq, PartialEq)]
/// struct Name<'a> {
/// first: &'a [u8],
/// last: &'a [u8],
/// }
///
/// let r = parse!{i;
/// let first = take_while1(|c| c != b' ');
/// token(b' ');
/// let last = take_while1(|c| c != b'\n');
///
/// ret @ _, Error<_>: Name{
/// first: first,
/// last: last,
/// }
/// };
///
/// assert_eq!(r.unwrap(), Name{first: b"Martin", last: "Wernstål".as_bytes()});
/// # }
/// ```
///
/// ## Grammar
///
/// EBNF using `$ty`, `$expr`, `$ident` and `$pat` for the equivalent Rust macro patterns.
///
/// ```text
/// RET_TYPED = '@' $ty ',' $ty ':' $expr
/// RET_PLAIN = $expr
///
/// ERR_TYPED = '@' $ty ',' $ty ':' $expr
/// ERR_PLAIN = $expr
///
/// VAR = $ident ':' $ty | $pat
/// ACTION = INLINE_ACTION | NAMED_ACTION
/// INLINE_ACTION = $ident '->' $expr
/// NAMED_ACTION = $ident '(' ($expr ',')* ','? ')'
///
/// BIND = 'let' VAR '=' ACTION
/// THEN = ACTION
///
/// RET = 'ret' ( RET_TYPED | RET_PLAIN )
/// ERR = 'err' ( ERR_TYPED | ERR_PLAIN )
///
/// EXPR = ( BIND ';' | THEN ';' )* (RET | ERR | THEN)
/// ```
#[macro_export]
macro_rules! parse {
( $($t:tt)* ) => { __parse_internal!{ $($t)* } };
}
/// Actual implementation of the parse macro, hidden to make the documentation easier to read.
///
/// Patterns starting with @ symbolds are internal rules, used by other parts of the macro.
#[macro_export]
#[doc(hidden)]
macro_rules! __parse_internal {
// RET_TYPED = '@' $ty ',' $ty ':' $expr
( @RET($i:expr); @ $t_ty:ty , $e_ty:ty : $e:expr ) =>
{ $i.ret::<$t_ty, $e_ty>($e) };
// RET_PLAIN = $expr
( @RET($i:expr); $e:expr ) =>
{ $i.ret($e) };
// ERR_TYPED = '@' $ty ',' $ty ':' $expr
( @ERR($i:expr); @ $t_ty:ty , $e_ty:ty : $e:expr ) =>
{ $i.err::<$t_ty, $e_ty>($e) };
// ERR_PLAIN = $expr
( @ERR($i:expr); $e:expr ) =>
{ $i.err($e) };
// VAR = $ident ':' $ty | $pat
// pattern must be before ident
( @BIND($i:expr); $v:pat = $($t:tt)* ) =>
{ __parse_internal!{ @ACTION($i, $v ); $($t)* } };
( @BIND($i:expr); $v:ident : $v_ty:ty = $($t:tt)* ) =>
{ __parse_internal!{ @ACTION($i, $v:$v_ty); $($t)* } };
// ACTION = INLINE_ACTION | NAMED_ACTION
// INLINE_ACTION = $ident '->' $expr
// version with expression following, nonterminal:
( @ACTION($i:expr, $($v:tt)*); $m:ident -> $e:expr ; $($t:tt)*) =>
{ __parse_internal!{ @CONCAT({ let $m = $i; $e }, $($v)*); $($t)* } };
// terminal:
( @ACTION($i:expr, $($v:tt)*); $m:ident -> $e:expr ) =>
{ { let $m = $i; $e } };
// NAMED_ACTION = $ident '(' ($expr ',')* ','? ')'
// version with expression following, nonterminal:
( @ACTION($i:expr, $($v:tt)*); $f:ident ( $($p:expr),* $(,)*) ; $($t:tt)* ) =>
{ __parse_internal!{ @CONCAT($f($i, $($p),*), $($v)*); $($t)*} };
// terminal:
( @ACTION($i:expr, $($v:tt)*); $f:ident ( $($p:expr),* $(,)*) ) =>
{ $f($i, $($p),*) };
// Ties an expression together with the next, using the bind operator
// invoked from @ACTION and @BIND (via @ACTION)
// three variants are needed to coerce the tt-list into a parameter token
// an additional three variants are needed to handle tailing semicolons, if there is nothing
// else to expand, do not use bind
( @CONCAT($i:expr, _); ) =>
{ $i };
( @CONCAT($i:expr, _); $($tail:tt)+ ) =>
{ $i.bind(|i, _| __parse_internal!{ i; $($tail)* }) };
( @CONCAT($i:expr, $v:pat); ) =>
{ $i };
( @CONCAT($i:expr, $v:pat); $($tail:tt)+ ) =>
{ $i.bind(|i, $v| __parse_internal!{ i; $($tail)* }) };
( @CONCAT($i:expr, $v:ident : $v_ty:ty); ) =>
{ $i };
( @CONCAT($i:expr, $v:ident : $v_ty:ty); $($tail:tt)+ ) =>
{ $i.bind(|i, $v:$v_ty| __parse_internal!{ i; $($tail)* }) };
// EXPR = ( BIND ';' | THEN ';' )* (RET | ERR | THEN)
// TODO: Any way to prevent BIND from being the last?
// BIND = 'let' VAR '=' ACTION
( $i:expr ; let $($tail:tt)* ) =>
{ __parse_internal!{ @BIND($i); $($tail)+ } };
// RET = 'ret' ( RET_TYPED | RET_PLAIN )
( $i:expr ; ret $($tail:tt)+ ) =>
{ __parse_internal!{ @RET($i); $($tail)+ } };
// ERR = 'err' ( ERR_TYPED | ERR_PLAIN )
( $i:expr ; err $($tail:tt)+ ) =>
{ __parse_internal!{ @ERR($i); $($tail)+ } };
// THEN = ACTION
// needs to be last since it is the most general
( $i:expr ; $($tail:tt)+ ) =>
{ __parse_internal!{ @ACTION($i, _); $($tail)+ } };
// Terminals:
( $i:expr ; ) => { $i };
( $i:expr ) => { $i };
}
/// Macro wrapping an invocation to ``parse!`` in a closure, useful for creating parsers inline.
///
/// This makes it easier to eg. implement branching in the same ``parse!`` block:
///
/// ```
/// # #[macro_use] extern crate chomp;
/// # fn main() {
/// use chomp::{Input};
/// use chomp::{or, string};
///
/// let i = Input::new(b"ac");
///
/// let r = parse!{i;
/// or(parser!{string(b"ab")},
/// parser!{string(b"ac")})};
///
/// assert_eq!(r.unwrap(), b"ac");
/// # }
/// ```
#[macro_export]
macro_rules! parser {
( $($t:tt)* ) => { |i| parse!{i; $($t)* } }
}
#[cfg(test)]
mod test {
/// Simplified implementation of the emulated monad using linear types.
#[derive(Debug, Eq, PartialEq)]
struct Input(i64);
/// Simplified implementation of the emulated monad using linear types.
#[derive(Debug, Eq, PartialEq)]
enum Data<T, E> {
Value(i64, T),
Error(i64, E),
}
impl Input {
fn ret<T, E>(self, t: T) -> Data<T, E> {
Data::Value(self.0, t)
}
fn err<T, E>(self, e: E) -> Data<T, E> {
Data::Error(self.0, e)
}
}
impl<T, E> Data<T, E> {
fn bind<F, U, V = E>(self, f: F) -> Data<U, V>
where F: FnOnce(Input, T) -> Data<U, V>,
V: From<E> {
match self {
Data::Value(i, t) => f(Input(i), t).map_err(From::from),
Data::Error(i, e) => Data::Error(i, From::from(e)),
}
}
fn map_err<F, V>(self, f: F) -> Data<T, V>
where F: FnOnce(E) -> V {
match self {
Data::Value(i, t) => Data::Value(i, t),
Data::Error(i, e) => Data::Error(i, f(e)),
}
}
}
#[test]
fn empty() {
let i = 123;
let r = parse!{i};
assert_eq!(r, 123);
}
#[test]
fn empty_expr() {
let r = parse!{1 + 2};
assert_eq!(r, 3);
}
#[test]
fn ret() {
let i = Input(123);
// Type annotation necessary since ret leaves E free
let r: Data<_, ()> = parse!{i; ret "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn ret_typed() {
let i = Input(123);
let r = parse!{i; ret @ _, (): "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn ret_typed2() {
let i = Input(123);
let r = parse!{i; ret @ &str, (): "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn err() {
let i = Input(123);
// Type annotation necessary since err leaves T free
let r: Data<(), _> = parse!{i; err "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn err_typed() {
let i = Input(123);
let r = parse!{i; err @(), _: "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn err_typed2() {
let i = Input(123);
let r = parse!{i; err @(), &str: "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn action() {
fn doit(i: Input) -> Data<&'static str, ()> {
Data::Value(i.0, "doit")
}
let i = Input(123);
let r = parse!(i; doit());
assert_eq!(r, Data::Value(123, "doit"));
}
#[test]
fn action2() {
fn doit(i: Input, p: &str) -> Data<&str, ()> {
Data::Value(i.0, p)
}
let i = Input(123);
let r = parse!(i; doit("doit"));
assert_eq!(r, Data::Value(123, "doit"));
}
#[test]
fn action3() {
fn doit(i: Input, p: &str, u: u32) -> Data<(&str, u32), ()> {
Data::Value(i.0, (p, u))
}
let i = Input(123);
let r = parse!(i; doit("doit", 1337));
assert_eq!(r, Data::Value(123, ("doit", 1337)));
}
#[test]
fn two_actions() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, 1)
}
fn something(i: Input) -> Data<u32, ()> {
assert_eq!(i.0, 321);
Data::Value(123, 2)
}
let i = Input(123);
let r = parse!(i; doit(); something());
assert_eq!(r, Data::Value(123, 2));
}
#[test]
fn two_actions2() {
fn doit(i: Input, n: u32) -> Data<u32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, n)
}
fn something(i: Input, n: u32) -> Data<u32, ()> {
assert_eq!(i.0, 321);
Data::Value(123, n)
}
let i = Input(123);
let r = parse!(i; doit(22); something(33));
assert_eq!(r, Data::Value(123, 33));
}
#[test]
fn two_actions3() {
fn doit(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 123);
Data::Value(321, (n, x))
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 321);
Data::Value(123, (n, x))
}
let i = Input(123);
let r = parse!(i; doit(22, 1); something(33, 2));
assert_eq!(r, Data::Value(123, (33, 2)));
}
#[test]
fn tailing_semicolon() {
fn f(n: Input) -> Data<u32, ()> {
n.ret(3)
}
let r = parse!{Input(123); f(); };
assert_eq!(r, Data::Value(123, 3));
}
#[test]
fn action_ret() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!(i1; doit(2); ret 5);
let r2 = parse!(i2; doit(2); ret @ _, (): 5);
assert_eq!(r1, Data::Value(321, 5));
assert_eq!(r2, Data::Value(321, 5));
}
#[test]
fn action_ret2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; doit(2); something(4, 5); ret 5};
let r2 = parse!{i2; doit(2); something(4, 5); ret @ _, (): 5};
assert_eq!(r1, Data::Value(111, 5));
assert_eq!(r2, Data::Value(111, 5));
}
#[test]
fn bind() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); ret n + 2};
let r2 = parse!{i2; let n = doit(40); ret @ _, (): n + 2};
assert_eq!(r1, Data::Value(321, 42));
assert_eq!(r2, Data::Value(321, 42));
}
#[test]
fn bind2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 321);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); let x = something(n, 4); ret x + 6};
let r2 = parse!{i2; let n = doit(40); let x = something(n, 4);
ret @ _, (): x + 6};
assert_eq!(r1, Data::Value(111, 42));
assert_eq!(r2, Data::Value(111, 42));
}
#[test]
fn bind3() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; let n = doit(40); err n as u8 + 2};
let r2 = parse!{i2; let n = doit(40); err @ (), u8: n as u8 + 2};
assert_eq!(r1, Data::Error(321, 42));
assert_eq!(r2, Data::Error(321, 42));
}
#[test]
fn bind4() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, u8> {
assert_eq!(i.0, 321);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; let n = doit(40); let x = something(n, 4); err x as u8 + 6};
let r2 = parse!{i2; let n = doit(40); let x = something(n, 4);
err @ (), u8: x as u8 + 6};
assert_eq!(r1, Data::Error(111, 42));
assert_eq!(r2, Data::Error(111, 42));
}
#[test]
fn bind_then() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 111);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let x = something(6, 4); doit(x)};
let r2 = parse!{i2; let x = something(6, 4); doit(x)};
assert_eq!(r1, Data::Value(321, 2));
assert_eq!(r2, Data::Value(321, 2));
}
#[test]
fn bind_then2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 111);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let _x = something(6, 4); doit(3)};
let r2 = parse!{i2; let _x = something(6, 4); doit(3)};
assert_eq!(r1, Data::Value(321, 3));
assert_eq!(r2, Data::Value(321, 3));
}
#[test]
fn bind_type() {
fn doit<N>(i: Input, x: N) -> Data<N, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n: u64 = doit(42); ret n};
let r2 = parse!{i2; let n: u64 = doit(42); ret @ _, (): n};
assert_eq!(r1, Data::Value(321, 42u64));
assert_eq!(r2, Data::Value(321, 42u64));
}
#[test]
fn bind_pattern() {
fn something(i: Input, n: u32, x: u32) -> Data<(u32, u32), ()> {
assert_eq!(i.0, 123);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let (x, y) = something(2, 4); ret x + y};
let r2 = parse!{i2; let (x, y) = something(2, 4); ret @ _, (): x + y};
assert_eq!(r1, Data::Value(111, 6));
assert_eq!(r2, Data::Value(111, 6));
}
#[test]
fn bind_pattern2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<(i32, u32), ()> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); let (x, y) = something(n, 4);
ret x + y as i32};
let r2 = parse!{i2; let n = doit(40); let (x, y) = something(n, 4);
ret @ _, (): x + y as i32};
assert_eq!(r1, Data::Value(111, 44));
assert_eq!(r2, Data::Value(111, 44));
}
#[test]
fn action_err() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!(i1; doit(2); err 5);
let r2 = parse!(i2; doit(2); err @ (), u8: 5);
assert_eq!(r1, Data::Error(321, 5));
assert_eq!(r2, Data::Error(321, 5));
}
#[test]
fn action_err2() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), u8> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; doit(2); something(4, 5); err 5};
let r2 = parse!{i2; doit(2); something(4, 5); err @ (), u8: 5};
assert_eq!(r1, Data::Error(111, 5));
assert_eq!(r2, Data::Error(111, 5));
}
#[test]
fn inline_action() {
let i = Input(123);
let r = parse!{i;
s -> {
// Essentially just Input(123).ret(23):
assert_eq!(s, Input(123));
s.ret::<_, ()>(23)
}
};
assert_eq!(r, Data::Value(123, 23));
}
#[test]
fn inline_action2() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i, Input(123));
Data::Value(321, 2)
}
let i = Input(123);
let r = parse!{i;
doit();
s -> {
// Essentially just Input(123).ret(23):
assert_eq!(s, Input(321));
s.ret::<_, ()>(23)
}
};
assert_eq!(r, Data::Value(321, 23));
}
#[test]
fn inline_action3() {
let i = Input(123);
let r = parse!{i;
s -> s.ret::<u8, ()>(23)
};
assert_eq!(r, Data::Value(123, 23));
}
#[test]
fn inline_action_bind() {
let i = Input(123);
let r = parse!{i;
let v = s -> {
assert_eq!(s, Input(123));
s.ret(23)
};
ret @ u32, (): v + 2
};
assert_eq!(r, Data::Value(123, 25));
}
#[test]
fn inline_action_bind2() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i, Input(123));
Data::Value(321, 2)
}
let i = Input(123);
let r = parse!{i;
let n = doit();
let v = s -> {
assert_eq!(n, 2);
assert_eq!(s, Input(321));
s.ret(23 + n)
};
ret @ u32, (): v + 3
};
assert_eq!(r, Data::Value(321, 28));
}
// TODO: Compilefail tests for trailing bind
}
Macros: parse now intentionally fails parsing if the last statement is a bind
/// Macro emulating `do`-notation for the parser monad, automatically threading the linear type.
///
/// ```ignore
/// parse!{input;
/// parser("parameter");
/// let value = other_parser();
///
/// ret do_something(value);
/// }
/// // is equivalent to:
/// parser(input, "parameter").bind(|i, _|
/// other_parser(i).bind(|i, value|
/// i.ret(do_something(value))))
/// ```
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate chomp;
/// # fn main() {
/// use chomp::{Input, Error};
/// use chomp::{take_while1, token};
///
/// let i = Input::new("Martin Wernstål\n".as_bytes());
///
/// #[derive(Debug, Eq, PartialEq)]
/// struct Name<'a> {
/// first: &'a [u8],
/// last: &'a [u8],
/// }
///
/// let r = parse!{i;
/// let first = take_while1(|c| c != b' ');
/// token(b' ');
/// let last = take_while1(|c| c != b'\n');
///
/// ret @ _, Error<_>: Name{
/// first: first,
/// last: last,
/// }
/// };
///
/// assert_eq!(r.unwrap(), Name{first: b"Martin", last: "Wernstål".as_bytes()});
/// # }
/// ```
///
/// ## Grammar
///
/// EBNF using `$ty`, `$expr`, `$ident` and `$pat` for the equivalent Rust macro patterns.
///
/// ```text
/// RET_TYPED = '@' $ty ',' $ty ':' $expr
/// RET_PLAIN = $expr
///
/// ERR_TYPED = '@' $ty ',' $ty ':' $expr
/// ERR_PLAIN = $expr
///
/// VAR = $ident ':' $ty | $pat
/// ACTION = INLINE_ACTION | NAMED_ACTION
/// INLINE_ACTION = $ident '->' $expr
/// NAMED_ACTION = $ident '(' ($expr ',')* ','? ')'
///
/// BIND = 'let' VAR '=' ACTION
/// THEN = ACTION
///
/// RET = 'ret' ( RET_TYPED | RET_PLAIN )
/// ERR = 'err' ( ERR_TYPED | ERR_PLAIN )
///
/// EXPR = ( BIND ';' | THEN ';' )* (RET | ERR | THEN)
/// ```
#[macro_export]
macro_rules! parse {
( $($t:tt)* ) => { __parse_internal!{ $($t)* } };
}
/// Actual implementation of the parse macro, hidden to make the documentation easier to read.
///
/// Patterns starting with @ symbolds are internal rules, used by other parts of the macro.
#[macro_export]
#[doc(hidden)]
macro_rules! __parse_internal {
// RET_TYPED = '@' $ty ',' $ty ':' $expr
( @RET($i:expr); @ $t_ty:ty , $e_ty:ty : $e:expr ) =>
{ $i.ret::<$t_ty, $e_ty>($e) };
// RET_PLAIN = $expr
( @RET($i:expr); $e:expr ) =>
{ $i.ret($e) };
// ERR_TYPED = '@' $ty ',' $ty ':' $expr
( @ERR($i:expr); @ $t_ty:ty , $e_ty:ty : $e:expr ) =>
{ $i.err::<$t_ty, $e_ty>($e) };
// ERR_PLAIN = $expr
( @ERR($i:expr); $e:expr ) =>
{ $i.err($e) };
// VAR = $ident ':' $ty | $pat
// pattern must be before ident
// @ACTION_NONTERM will intentionally fail if there are no more tokens following the bind
( @BIND($i:expr); $v:pat = $($t:tt)* ) =>
{ __parse_internal!{ @ACTION_NONTERM($i, $v ); $($t)* } };
( @BIND($i:expr); $v:ident : $v_ty:ty = $($t:tt)* ) =>
{ __parse_internal!{ @ACTION_NONTERM($i, $v:$v_ty); $($t)* } };
// ACTION = INLINE_ACTION | NAMED_ACTION
// INLINE_ACTION = $ident '->' $expr
// version with expression following, nonterminal:
( @ACTION($i:expr, $($v:tt)*); $m:ident -> $e:expr ; $($t:tt)*) =>
{ __parse_internal!{ @CONCAT({ let $m = $i; $e }, $($v)*); $($t)* } };
// intentionally fail if there are no more tokens
( @ACTION_NONTERM($i:expr, $($v:tt)*); $m:ident -> $e:expr ; $($t:tt)*) =>
{ __parse_internal!{ @CONCAT({ let $m = $i; $e }, $($v)*); $($t)* } };
// terminal:
( @ACTION($i:expr, $($v:tt)*); $m:ident -> $e:expr ) =>
{ { let $m = $i; $e } };
// NAMED_ACTION = $ident '(' ($expr ',')* ','? ')'
// version with expression following, nonterminal:
( @ACTION($i:expr, $($v:tt)*); $f:ident ( $($p:expr),* $(,)*) ; $($t:tt)* ) =>
{ __parse_internal!{ @CONCAT($f($i, $($p),*), $($v)*); $($t)*} };
// intentionally fail if there are no more tokens
( @ACTION_NONTERM($i:expr, $($v:tt)*); $f:ident ( $($p:expr),* $(,)*) ; $($t:tt)* ) =>
{ __parse_internal!{ @CONCAT($f($i, $($p),*), $($v)*); $($t)*} };
// terminal:
( @ACTION($i:expr, $($v:tt)*); $f:ident ( $($p:expr),* $(,)*) ) =>
{ $f($i, $($p),*) };
// Ties an expression together with the next, using the bind operator
// invoked from @ACTION and @BIND (via @ACTION)
// three variants are needed to coerce the tt-list into a parameter token
// an additional three variants are needed to handle tailing semicolons, if there is nothing
// else to expand, do not use bind
( @CONCAT($i:expr, _); ) =>
{ $i };
( @CONCAT($i:expr, _); $($tail:tt)+ ) =>
{ $i.bind(|i, _| __parse_internal!{ i; $($tail)* }) };
( @CONCAT($i:expr, $v:pat); ) =>
{ $i };
( @CONCAT($i:expr, $v:pat); $($tail:tt)+ ) =>
{ $i.bind(|i, $v| __parse_internal!{ i; $($tail)* }) };
( @CONCAT($i:expr, $v:ident : $v_ty:ty); ) =>
{ $i };
( @CONCAT($i:expr, $v:ident : $v_ty:ty); $($tail:tt)+ ) =>
{ $i.bind(|i, $v:$v_ty| __parse_internal!{ i; $($tail)* }) };
// EXPR = ( BIND ';' | THEN ';' )* (RET | ERR | THEN)
// TODO: Any way to prevent BIND from being the last?
// BIND = 'let' VAR '=' ACTION
( $i:expr ; let $($tail:tt)* ) =>
{ __parse_internal!{ @BIND($i); $($tail)+ } };
// RET = 'ret' ( RET_TYPED | RET_PLAIN )
( $i:expr ; ret $($tail:tt)+ ) =>
{ __parse_internal!{ @RET($i); $($tail)+ } };
// ERR = 'err' ( ERR_TYPED | ERR_PLAIN )
( $i:expr ; err $($tail:tt)+ ) =>
{ __parse_internal!{ @ERR($i); $($tail)+ } };
// THEN = ACTION
// needs to be last since it is the most general
( $i:expr ; $($tail:tt)+ ) =>
{ __parse_internal!{ @ACTION($i, _); $($tail)+ } };
// Terminals:
( $i:expr ; ) => { $i };
( $i:expr ) => { $i };
}
/// Macro wrapping an invocation to ``parse!`` in a closure, useful for creating parsers inline.
///
/// This makes it easier to eg. implement branching in the same ``parse!`` block:
///
/// ```
/// # #[macro_use] extern crate chomp;
/// # fn main() {
/// use chomp::{Input};
/// use chomp::{or, string};
///
/// let i = Input::new(b"ac");
///
/// let r = parse!{i;
/// or(parser!{string(b"ab")},
/// parser!{string(b"ac")})};
///
/// assert_eq!(r.unwrap(), b"ac");
/// # }
/// ```
#[macro_export]
macro_rules! parser {
( $($t:tt)* ) => { |i| parse!{i; $($t)* } }
}
#[cfg(test)]
mod test {
/// Simplified implementation of the emulated monad using linear types.
#[derive(Debug, Eq, PartialEq)]
struct Input(i64);
/// Simplified implementation of the emulated monad using linear types.
#[derive(Debug, Eq, PartialEq)]
enum Data<T, E> {
Value(i64, T),
Error(i64, E),
}
impl Input {
fn ret<T, E>(self, t: T) -> Data<T, E> {
Data::Value(self.0, t)
}
fn err<T, E>(self, e: E) -> Data<T, E> {
Data::Error(self.0, e)
}
}
impl<T, E> Data<T, E> {
fn bind<F, U, V = E>(self, f: F) -> Data<U, V>
where F: FnOnce(Input, T) -> Data<U, V>,
V: From<E> {
match self {
Data::Value(i, t) => f(Input(i), t).map_err(From::from),
Data::Error(i, e) => Data::Error(i, From::from(e)),
}
}
fn map_err<F, V>(self, f: F) -> Data<T, V>
where F: FnOnce(E) -> V {
match self {
Data::Value(i, t) => Data::Value(i, t),
Data::Error(i, e) => Data::Error(i, f(e)),
}
}
}
#[test]
fn empty() {
let i = 123;
let r = parse!{i};
assert_eq!(r, 123);
}
#[test]
fn empty_expr() {
let r = parse!{1 + 2};
assert_eq!(r, 3);
}
#[test]
fn ret() {
let i = Input(123);
// Type annotation necessary since ret leaves E free
let r: Data<_, ()> = parse!{i; ret "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn ret_typed() {
let i = Input(123);
let r = parse!{i; ret @ _, (): "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn ret_typed2() {
let i = Input(123);
let r = parse!{i; ret @ &str, (): "foo"};
assert_eq!(r, Data::Value(123, "foo"));
}
#[test]
fn err() {
let i = Input(123);
// Type annotation necessary since err leaves T free
let r: Data<(), _> = parse!{i; err "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn err_typed() {
let i = Input(123);
let r = parse!{i; err @(), _: "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn err_typed2() {
let i = Input(123);
let r = parse!{i; err @(), &str: "foo"};
assert_eq!(r, Data::Error(123, "foo"));
}
#[test]
fn action() {
fn doit(i: Input) -> Data<&'static str, ()> {
Data::Value(i.0, "doit")
}
let i = Input(123);
let r = parse!(i; doit());
assert_eq!(r, Data::Value(123, "doit"));
}
#[test]
fn action2() {
fn doit(i: Input, p: &str) -> Data<&str, ()> {
Data::Value(i.0, p)
}
let i = Input(123);
let r = parse!(i; doit("doit"));
assert_eq!(r, Data::Value(123, "doit"));
}
#[test]
fn action3() {
fn doit(i: Input, p: &str, u: u32) -> Data<(&str, u32), ()> {
Data::Value(i.0, (p, u))
}
let i = Input(123);
let r = parse!(i; doit("doit", 1337));
assert_eq!(r, Data::Value(123, ("doit", 1337)));
}
#[test]
fn two_actions() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, 1)
}
fn something(i: Input) -> Data<u32, ()> {
assert_eq!(i.0, 321);
Data::Value(123, 2)
}
let i = Input(123);
let r = parse!(i; doit(); something());
assert_eq!(r, Data::Value(123, 2));
}
#[test]
fn two_actions2() {
fn doit(i: Input, n: u32) -> Data<u32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, n)
}
fn something(i: Input, n: u32) -> Data<u32, ()> {
assert_eq!(i.0, 321);
Data::Value(123, n)
}
let i = Input(123);
let r = parse!(i; doit(22); something(33));
assert_eq!(r, Data::Value(123, 33));
}
#[test]
fn two_actions3() {
fn doit(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 123);
Data::Value(321, (n, x))
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 321);
Data::Value(123, (n, x))
}
let i = Input(123);
let r = parse!(i; doit(22, 1); something(33, 2));
assert_eq!(r, Data::Value(123, (33, 2)));
}
#[test]
fn tailing_semicolon() {
fn f(n: Input) -> Data<u32, ()> {
n.ret(3)
}
let r = parse!{Input(123); f(); };
assert_eq!(r, Data::Value(123, 3));
}
#[test]
fn action_ret() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!(i1; doit(2); ret 5);
let r2 = parse!(i2; doit(2); ret @ _, (): 5);
assert_eq!(r1, Data::Value(321, 5));
assert_eq!(r2, Data::Value(321, 5));
}
#[test]
fn action_ret2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), ()> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; doit(2); something(4, 5); ret 5};
let r2 = parse!{i2; doit(2); something(4, 5); ret @ _, (): 5};
assert_eq!(r1, Data::Value(111, 5));
assert_eq!(r2, Data::Value(111, 5));
}
#[test]
fn bind() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); ret n + 2};
let r2 = parse!{i2; let n = doit(40); ret @ _, (): n + 2};
assert_eq!(r1, Data::Value(321, 42));
assert_eq!(r2, Data::Value(321, 42));
}
#[test]
fn bind2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 321);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); let x = something(n, 4); ret x + 6};
let r2 = parse!{i2; let n = doit(40); let x = something(n, 4);
ret @ _, (): x + 6};
assert_eq!(r1, Data::Value(111, 42));
assert_eq!(r2, Data::Value(111, 42));
}
#[test]
fn bind3() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; let n = doit(40); err n as u8 + 2};
let r2 = parse!{i2; let n = doit(40); err @ (), u8: n as u8 + 2};
assert_eq!(r1, Data::Error(321, 42));
assert_eq!(r2, Data::Error(321, 42));
}
#[test]
fn bind4() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, u8> {
assert_eq!(i.0, 321);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; let n = doit(40); let x = something(n, 4); err x as u8 + 6};
let r2 = parse!{i2; let n = doit(40); let x = something(n, 4);
err @ (), u8: x as u8 + 6};
assert_eq!(r1, Data::Error(111, 42));
assert_eq!(r2, Data::Error(111, 42));
}
#[test]
fn bind_then() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 111);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let x = something(6, 4); doit(x)};
let r2 = parse!{i2; let x = something(6, 4); doit(x)};
assert_eq!(r1, Data::Value(321, 2));
assert_eq!(r2, Data::Value(321, 2));
}
#[test]
fn bind_then2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 111);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(111, n - x as i32)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let _x = something(6, 4); doit(3)};
let r2 = parse!{i2; let _x = something(6, 4); doit(3)};
assert_eq!(r1, Data::Value(321, 3));
assert_eq!(r2, Data::Value(321, 3));
}
#[test]
fn bind_type() {
fn doit<N>(i: Input, x: N) -> Data<N, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n: u64 = doit(42); ret n};
let r2 = parse!{i2; let n: u64 = doit(42); ret @ _, (): n};
assert_eq!(r1, Data::Value(321, 42u64));
assert_eq!(r2, Data::Value(321, 42u64));
}
#[test]
fn bind_pattern() {
fn something(i: Input, n: u32, x: u32) -> Data<(u32, u32), ()> {
assert_eq!(i.0, 123);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let (x, y) = something(2, 4); ret x + y};
let r2 = parse!{i2; let (x, y) = something(2, 4); ret @ _, (): x + y};
assert_eq!(r1, Data::Value(111, 6));
assert_eq!(r2, Data::Value(111, 6));
}
#[test]
fn bind_pattern2() {
fn doit(i: Input, x: i32) -> Data<i32, ()> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: i32, x: u32) -> Data<(i32, u32), ()> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<_, ()> = parse!{i1; let n = doit(40); let (x, y) = something(n, 4);
ret x + y as i32};
let r2 = parse!{i2; let n = doit(40); let (x, y) = something(n, 4);
ret @ _, (): x + y as i32};
assert_eq!(r1, Data::Value(111, 44));
assert_eq!(r2, Data::Value(111, 44));
}
#[test]
fn action_err() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!(i1; doit(2); err 5);
let r2 = parse!(i2; doit(2); err @ (), u8: 5);
assert_eq!(r1, Data::Error(321, 5));
assert_eq!(r2, Data::Error(321, 5));
}
#[test]
fn action_err2() {
fn doit(i: Input, x: i32) -> Data<i32, u8> {
assert_eq!(i.0, 123);
Data::Value(321, x)
}
fn something(i: Input, n: u32, x: i32) -> Data<(u32, i32), u8> {
assert_eq!(i.0, 321);
Data::Value(111, (n, x))
}
let i1 = Input(123);
let i2 = Input(123);
let r1: Data<(), u8> = parse!{i1; doit(2); something(4, 5); err 5};
let r2 = parse!{i2; doit(2); something(4, 5); err @ (), u8: 5};
assert_eq!(r1, Data::Error(111, 5));
assert_eq!(r2, Data::Error(111, 5));
}
#[test]
fn inline_action() {
let i = Input(123);
let r = parse!{i;
s -> {
// Essentially just Input(123).ret(23):
assert_eq!(s, Input(123));
s.ret::<_, ()>(23)
}
};
assert_eq!(r, Data::Value(123, 23));
}
#[test]
fn inline_action2() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i, Input(123));
Data::Value(321, 2)
}
let i = Input(123);
let r = parse!{i;
doit();
s -> {
// Essentially just Input(123).ret(23):
assert_eq!(s, Input(321));
s.ret::<_, ()>(23)
}
};
assert_eq!(r, Data::Value(321, 23));
}
#[test]
fn inline_action3() {
let i = Input(123);
let r = parse!{i;
s -> s.ret::<u8, ()>(23)
};
assert_eq!(r, Data::Value(123, 23));
}
#[test]
fn inline_action_bind() {
let i = Input(123);
let r = parse!{i;
let v = s -> {
assert_eq!(s, Input(123));
s.ret(23)
};
ret @ u32, (): v + 2
};
assert_eq!(r, Data::Value(123, 25));
}
#[test]
fn inline_action_bind2() {
fn doit(i: Input) -> Data<u32, ()> {
assert_eq!(i, Input(123));
Data::Value(321, 2)
}
let i = Input(123);
let r = parse!{i;
let n = doit();
let v = s -> {
assert_eq!(n, 2);
assert_eq!(s, Input(321));
s.ret(23 + n)
};
ret @ u32, (): v + 3
};
assert_eq!(r, Data::Value(321, 28));
}
// TODO: Compilefail tests for trailing bind
}
|
//! Macro combinators
//!
//! Macros are used to make combination easier,
//! since they often do not depend on the type
//! of the data they manipulate or return.
//!
//! There is a trick to make them easier to assemble,
//! combinators are defined like this:
//!
//! ```ignore
//! macro_rules! tag (
//! ($i:expr, $inp: expr) => (
//! {
//! ...
//! }
//! );
//! );
//! ```
//!
//! But when used in other combinators, are Used
//! like this:
//!
//! ```ignore
//! named!(my_function, tag!("abcd"));
//! ```
//!
//! Internally, other combinators will rewrite
//! that call to pass the input as first argument:
//!
//! ```ignore
//! macro_rules! named (
//! ($name:ident, $submac:ident!( $($args:tt)* )) => (
//! fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
//! $submac!(i, $($args)*)
//! }
//! );
//! );
//! ```
//!
//! If you want to call a combinator directly, you can
//! do it like this:
//!
//! ```ignore
//! let res = { tag!(input, "abcd"); }
//! ```
//!
//! Combinators must have a specific variant for
//! non-macro arguments. Example: passing a function
//! to take_while! instead of another combinator.
//!
//! ```ignore
//! macro_rules! take_while(
//! ($input:expr, $submac:ident!( $($args:tt)* )) => (
//! {
//! ...
//! }
//! );
//!
//! // wrap the function in a macro to pass it to the main implementation
//! ($input:expr, $f:expr) => (
//! take_while!($input, call!($f));
//! );
//! );
//!
/// Wraps a parser in a closure
#[macro_export]
macro_rules! closure (
($ty:ty, $submac:ident!( $($args:tt)* )) => (
|i: $ty| { $submac!(i, $($args)*) }
);
($submac:ident!( $($args:tt)* )) => (
|i| { $submac!(i, $($args)*) }
);
);
/// Makes a function from a parser combination
///
/// The type can be set up if the compiler needs
/// more information
///
/// ```ignore
/// named!(my_function( &[u8] ) -> &[u8], tag!("abcd"));
/// // first type parameter is input, second is output
/// named!(my_function<&[u8], &[u8]>, tag!("abcd"));
/// // will have &[u8] as input type, &[u8] as output type
/// named!(my_function, tag!("abcd"));
/// // will use &[u8] as input type (use this if the compiler
/// // complains about lifetime issues
/// named!(my_function<&[u8]>, tag!("abcd"));
/// //prefix them with 'pub' to make the functions public
/// named!(pub my_function, tag!("abcd"));
/// ```
#[macro_export]
macro_rules! named (
($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i,$o,u32> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> {
$submac!(i, $($args)*)
}
);
($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<&'a [u8], $o, u32> {
$submac!(i, $($args)*)
}
);
($name:ident, $submac:ident!( $($args:tt)* )) => (
fn $name( i: &[u8] ) -> $crate::IResult<&[u8], &[u8], u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i,$o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: &[u8] ) -> $crate::IResult<&[u8], $o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<&[u8], &[u8], u32> {
$submac!(i, $($args)*)
}
);
);
/// Used to wrap common expressions and function as macros
#[macro_export]
macro_rules! call (
($i:expr, $fun:expr) => ( $fun( $i ) );
($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) );
);
/// emulate function currying: `apply!(my_function, arg1, arg2, ...)` becomes `my_function(input, arg1, arg2, ...)`
///
/// Supports up to 6 arguments
#[macro_export]
macro_rules! apply (
($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) );
);
/// Prevents backtracking if the child parser fails
///
/// This parser will do an early return instead of sending
/// its result to the parent parser.
///
/// If another `error!` combinator is present in the parent
/// chain, the error will be wrapped and another early
/// return will be made.
///
/// This makes it easy to build report on which parser failed,
/// where it failed in the input, and the chain of parsers
/// that led it there.
///
/// Additionally, the error chain contains number identifiers
/// that can be matched to provide useful error messages.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use std::collections;
/// # use nom::IResult::Error;
/// # use nom::Err::{Position,NodePosition};
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(err_test, alt!(
/// tag!("abcd") |
/// preceded!(tag!("efgh"), error!(ErrorKind::Custom(42),
/// chain!(
/// tag!("ijkl") ~
/// res: error!(ErrorKind::Custom(128), tag!("mnop")) ,
/// || { res }
/// )
/// )
/// )
/// ));
/// let a = &b"efghblah"[..];
/// let b = &b"efghijklblah"[..];
/// let c = &b"efghijklmnop"[..];
///
/// let blah = &b"blah"[..];
///
/// let res_a = err_test(a);
/// let res_b = err_test(b);
/// let res_c = err_test(c);
/// assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
/// assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..],
/// Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah))))))
/// );
/// # }
/// ```
///
#[macro_export]
macro_rules! error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
let cl = || {
$submac!($i, $($args)*)
};
match cl() {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
return $crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
error!($i, $code, call!($f));
);
);
/// Add an error if the child parser fails
///
/// While error! does an early return and avoids backtracking,
/// add_error! backtracks normally. It just provides more context
/// for an error
///
#[macro_export]
macro_rules! add_error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
$crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
add_error!($i, $code, call!($f));
);
);
/// translate parser result from IResult<I,O,u32> to IResult<I,O,E> woth a custom type
///
#[macro_export]
macro_rules! fix_error (
($i:expr, $t:ty, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
let err = match e {
$crate::Err::Code(ErrorKind::Custom(_)) |
$crate::Err::Node(ErrorKind::Custom(_), _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Code(e)
},
$crate::Err::Position(ErrorKind::Custom(_), p) |
$crate::Err::NodePosition(ErrorKind::Custom(_), p, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Position(e, p)
},
$crate::Err::Code(_) |
$crate::Err::Node(_, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Code(e)
},
$crate::Err::Position(_, p) |
$crate::Err::NodePosition(_, p, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Position(e, p)
},
};
$crate::IResult::Error(err)
}
}
}
);
($i:expr, $t:ty, $f:expr) => (
fix_error!($i, $t, call!($f));
);
);
/// replaces a `Incomplete` returned by the child parser
/// with an `Error`
///
#[macro_export]
macro_rules! complete (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(_) => {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Complete, $i))
},
}
}
);
($i:expr, $f:expr) => (
complete!($i, call!($f));
);
);
/// A bit like `std::try!`, this macro will return the remaining input and parsed value if the child parser returned `Done`,
/// and will do an early return for `Error` and `Incomplete`
/// this can provide more flexibility than `chain!` if needed
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorKind};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// let (i1, sz) = try_parse!(input, be_u8);
/// let (i2, length) = try_parse!(i1, expr_opt!(size.checked_add(sz)));
/// let (i3, data) = try_parse!(i2, take!(length));
/// return Done(i3, data);
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorKind::ExprOpt,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! try_parse (
($i:expr, $submac:ident!( $($args:tt)* )) => (
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => (i,o),
$crate::IResult::Error(e) => return $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => return $crate::IResult::Incomplete(i)
}
);
($i:expr, $f:expr) => (
try_parse!($i, call!($f))
);
);
/// `flat_map!(R -> IResult<R,S>, S -> IResult<S,T>) => R -> IResult<R, T>`
///
/// combines a parser R -> IResult<R,S> and
/// a parser S -> IResult<S,T> to return another
/// parser R -> IResult<R,T>
#[macro_export]
macro_rules! flat_map(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
$crate::IResult::Error(e) => {
let err = match e {
$crate::Err::Code(k) | $crate::Err::Node(k, _) | $crate::Err::Position(k, _) | $crate::Err::NodePosition(k, _, _) => {
$crate::Err::Position(k, $i)
}
};
$crate::IResult::Error(err)
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)),
$crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2)
}
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
flat_map!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $g:expr) => (
flat_map!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
flat_map!($i, call!($f), $submac!($($args)*));
);
);
/// `map!(I -> IResult<I,O>, O -> P) => I -> IResult<I, P>`
/// maps a function on the result of a parser
#[macro_export]
macro_rules! map(
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_impl(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, $submac2!(o, $($args2)*))
}
}
);
);
/// `map_res!(I -> IResult<I,O>, O -> Result<P>) => I -> IResult<I, P>`
/// maps a function returning a Result on the output of a parser
#[macro_export]
macro_rules! map_res (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_res_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_res_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_res_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_res_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_res_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Ok(output) => $crate::IResult::Done(i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::MapRes, $i))
}
}
}
);
);
/// `map_opt!(I -> IResult<I,O>, O -> Option<P>) => I -> IResult<I, P>`
/// maps a function returning an Option on the output of a parser
#[macro_export]
macro_rules! map_opt (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_opt_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_opt_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_opt_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_opt_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_opt_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
::std::option::Option::Some(output) => $crate::IResult::Done(i, output),
::std::option::Option::None => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::MapOpt, $i))
}
}
}
);
);
/// `value!(T, R -> IResult<R, S> ) => R -> IResult<R, T>`
///
/// or `value!(T) => R -> IResult<R, T>`
///
/// If the child parser was successful, return the value.
/// If no child parser is provided, always return the value
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(x<u8>, value!(42, delimited!(tag!("<!--"), take!(5), tag!("-->"))));
/// named!(y<u8>, delimited!(tag!("<!--"), value!(42), tag!("-->")));
/// let r = x(&b"<!-- abc --> aaa"[..]);
/// assert_eq!(r, Done(&b" aaa"[..], 42));
///
/// let r2 = y(&b"<!----> aaa"[..]);
/// assert_eq!(r2, Done(&b" aaa"[..], 42));
/// # }
/// ```
#[macro_export]
macro_rules! value (
($i:expr, $res:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::HexDisplay;
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $res)
},
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $res:expr, $f:expr) => (
value!($i, $res, call!($f))
);
($i:expr, $res:expr) => (
$crate::IResult::Done($i, $res)
);
);
/// `expr_res!(Result<E,O>) => I -> IResult<I, O>`
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
///
/// See expr_opt for an example
#[macro_export]
macro_rules! expr_res (
($i:expr, $e:expr) => (
{
match $e {
Ok(output) => $crate::IResult::Done($i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ExprRes, $i))
}
}
);
);
/// `expr_opt!(Option<O>) => I -> IResult<I, O>`
/// evaluate an expression that returns a Option<T> and returns a IResult::Done(I,T) if Ok
///
/// Useful when doing computations in a chain
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorKind};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// chain!(input,
/// sz: be_u8 ~
/// length: expr_opt!(size.checked_add(sz)) ~ // checking for integer overflow (returns an Option)
/// data: take!(length) ,
/// ||{ data }
/// )
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorKind::ExprOpt,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! expr_opt (
($i:expr, $e:expr) => (
{
match $e {
::std::option::Option::Some(output) => $crate::IResult::Done($i, output),
::std::option::Option::None => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ExprOpt, $i))
}
}
);
);
/// `chain!(I->IResult<I,A> ~ I->IResult<I,B> ~ ... I->IResult<I,X> , || { return O } ) => I -> IResult<I, O>`
/// chains parsers and assemble the results through a closure
/// the input type I must implement nom::InputLength
/// this combinator will count how much data is consumed by every child parser and take it into account if
/// there is not enough data
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// #[derive(PartialEq,Eq,Debug)]
/// struct B {
/// a: u8,
/// b: Option<u8>
/// }
///
/// named!(y, tag!("efgh"));
///
/// fn ret_int(i:&[u8]) -> IResult<&[u8], u8> { Done(i, 1) }
/// named!(ret_y<&[u8], u8>, map!(y, |_| 1)); // return 1 if the "efgh" tag is found
///
/// named!(z<&[u8], B>,
/// chain!(
/// tag!("abcd") ~ // the '~' character is used as separator
/// aa: ret_int ~ // the result of that parser will be used in the closure
/// tag!("abcd")? ~ // this parser is optional
/// bb: ret_y? , // the result of that parser is an option
/// // the last parser in the chain is followed by a ','
/// ||{B{a: aa, b: bb}}
/// )
/// );
///
/// # fn main() {
/// // the first "abcd" tag is not present, we have an error
/// let r1 = z(&b"efgh"[..]);
/// assert_eq!(r1, Error(Position(ErrorKind::Tag,&b"efgh"[..])));
///
/// // everything is present, everything is parsed
/// let r2 = z(&b"abcdabcdefgh"[..]);
/// assert_eq!(r2, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the second "abcd" tag is optional
/// let r3 = z(&b"abcdefgh"[..]);
/// assert_eq!(r3, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the result of ret_y is optional, as seen in the B structure
/// let r4 = z(&b"abcdabcdwxyz"[..]);
/// assert_eq!(r4, Done(&b"wxyz"[..], B{a: 1, b: None}));
/// # }
/// ```
#[macro_export]
macro_rules! chain (
($i:expr, $($rest:tt)*) => (
{
//use $crate::InputLength;
chaining_parser!($i, 0usize, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! chaining_parser (
($i:expr, $consumed:expr, $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,_) => {
chaining_parser!(i, $consumed + (($i).input_len() - i.input_len()), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
chaining_parser!(input, $consumed + (($i).input_len() - input.input_len()), $($rest)*)
}
}
});
($i:expr, $consumed:expr, $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, $field: call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let $field = o;
chaining_parser!(i, $consumed + (($i).input_len() - i.input_len()), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, mut $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, mut $field: call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let mut $field = o;
chaining_parser!(i, $consumed + ($i).input_len() - i.input_len(), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let ($field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o),i)
} else {
(::std::option::Option::None,$i)
};
chaining_parser!(input, $consumed + ($i).input_len() - input.input_len(), $($rest)*)
}
}
});
($i:expr, $consumed:expr, mut $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, mut $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let (mut $field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o),i)
} else {
(::std::option::Option::None,$i)
};
chaining_parser!(input, $consumed + ($i).input_len() - input.input_len(), $($rest)*)
}
}
});
// ending the chain
($i:expr, $consumed:expr, $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, call!($e), $assemble);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, $e:ident ?, $assemble:expr) => (
chaining_parser!($i, $consumed, call!($e) ?, $assemble);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ?, $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, $field: call!($e), $assemble);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, mut $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, mut $field: call!($e), $assemble);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let mut $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $consumed, $field : call!($e) ? , $assemble);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let ($field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o), i)
} else {
(::std::option::Option::None, $i)
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, mut $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $consumed, $field : call!($e) ? , $assemble);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let (mut $field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o), i)
} else {
(::std::option::Option::None, $i)
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, $assemble:expr) => (
$crate::IResult::Done($i, $assemble())
)
);
#[macro_export]
macro_rules! tuple (
($i:expr, $($rest:tt)*) => (
{
tuple_parser!($i, 0usize, (), $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! tuple_parser (
($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => (
tuple_parser!($i, $consumed, ($($parsed),*), call!($e), $($rest)*);
);
($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
tuple_parser!(i, $consumed + (($i).input_len() - i.input_len()), (o), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
tuple_parser!(i, $consumed + (($i).input_len() - i.input_len()), ($($parsed)* , o), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident) => (
tuple_parser!($i, $consumed, ($($parsed),*), call!($e));
);
($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
$crate::IResult::Done(i, (o))
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
$crate::IResult::Done(i, ($($parsed),* , o))
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:expr),*)) => (
{
$crate::IResult::Done($i, ($($parsed),*))
}
);
);
/// `alt!(I -> IResult<I,O> | I -> IResult<I,O> | ... | I -> IResult<I,O> ) => I -> IResult<I, O>`
/// try a list of parsers, return the result of the first successful one
///
/// If one of the parser returns Incomplete, alt will return Incomplete, to retry
/// once you get more input. Note that it is better for performance to know the
/// minimum size of data you need before you get into alt.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( test, alt!( tag!( "abcd" ) | tag!( "efgh" ) ) );
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], &b"abcd"[..]));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], &b"efgh"[..]));
/// # }
/// ```
///
/// There is another syntax for alt allowing a block to manipulate the result:
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// #[derive(Debug,PartialEq,Eq)]
/// enum Tagged {
/// Abcd,
/// Efgh,
/// Took(usize)
/// }
/// named!(test<Tagged>, alt!(
/// tag!("abcd") => { |_| Tagged::Abcd }
/// | tag!("efgh") => { |_| Tagged::Efgh }
/// | take!(5) => { |res: &[u8]| Tagged::Took(res.len()) } // the closure takes the result as argument if the parser is successful
/// ));
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], Tagged::Abcd));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], Tagged::Efgh));
/// let r3 = test(&b"mnopqrst"[..]);
/// assert_eq!(r3, Done(&b"rst"[..], Tagged::Took(5)));
/// # }
/// ```
///
/// **BE CAREFUL** there is a case where the behaviour of `alt!` can be confusing:
///
/// when the alternatives have different lengths, like this case:
///
/// ```ignore
/// named!( test, alt!( tag!( "abcd" ) | tag!( "ef" ) | tag!( "ghi" ) | tag!( "kl" ) ) );
/// ```
///
/// With this parser, if you pass `"abcd"` as input, the first alternative parses it correctly,
/// but if you pass `"efg"`, the first alternative will return `Incomplete`, since it needs an input
/// of 4 bytes. This behaviour of `alt!` is expected: if you get a partial input that isn't matched
/// by the first alternative, but would match if the input was complete, you want `alt!` to indicate
/// that it cannot decide with limited information.
///
/// There are two ways to fix this behaviour. The first one consists in ordering the alternatives
/// by size, like this:
///
/// ```ignore
/// named!( test, alt!( tag!( "ef" ) | tag!( "kl") | tag!( "ghi" ) | tag!( "abcd" ) ) );
/// ```
///
/// With this solution, the largest alternative will be tested last.
///
/// The other solution uses the `complete!` combinator, which transforms an `Incomplete` in an
/// `Error`. If one of the alternatives returns `Incomplete` but is wrapped by `complete!`,
/// `alt!` will try the next alternative. This is useful when you know that
/// you will not get partial input:
///
/// ```ignore
/// named!( test,
/// alt!(
/// complete!( tag!( "abcd" ) ) |
/// complete!( tag!( "ef" ) ) |
/// complete!( tag!( "ghi" ) ) |
/// complete!( tag!( "kl" ) )
/// )
/// );
/// ```
///
/// If you want the `complete!` combinator to be applied to all rules then use the convenience
/// `alt_complete!` macro (see below).
///
/// This behaviour of `alt!` can get especially confusing if multiple alternatives have different
/// sizes but a common prefix, like this:
///
/// ```ignore
/// named!( test, alt!( tag!( "abcd" ) | tag!( "ab" ) | tag!( "ef" ) ) );
/// ```
///
/// in that case, if you order by size, passing `"abcd"` as input will always be matched by the
/// smallest parser, so the solution using `complete!` is better suited.
///
/// You can also nest multiple `alt!`, like this:
///
/// ```ignore
/// named!( test,
/// alt!(
/// preceded!(
/// tag!("ab"),
/// alt!(
/// tag!( "cd" ) |
/// eof
/// )
/// )
/// | tag!( "ef" )
/// )
/// );
/// ```
///
/// `preceded!` will first parse `"ab"` then, if successful, try the alternatives "cd",
/// or empty input (End Of File). If none of them work, `preceded!` will fail and
/// "ef" will be tested.
///
#[macro_export]
macro_rules! alt (
($i:expr, $($rest:tt)*) => (
{
alt_parser!($i, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! alt_parser (
($i:expr, $e:ident | $($rest:tt)*) => (
alt_parser!($i, call!($e) | $($rest)*);
);
($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
let res = $subrule!($i, $($args)*);
match res {
$crate::IResult::Done(_,_) => res,
$crate::IResult::Incomplete(_) => res,
_ => alt_parser!($i, $($rest)*)
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i, $($rest)*)
}
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_parser!($i, call!($e) => { $gen } | $($rest)*);
);
($i:expr, $e:ident => { $gen:expr }) => (
alt_parser!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i)
}
}
}
);
($i:expr, $e:ident) => (
alt_parser!($i, call!($e));
);
($i:expr, $subrule:ident!( $($args:tt)*)) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,o),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i)
}
}
}
);
($i:expr) => (
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Alt,$i))
);
);
/// This is a combination of the `alt!` and `complete!` combinators. Rather
/// than returning `Incomplete` on partial input, `alt_complete!` will try the
/// next alternative in the chain. You should use this only if you know you
/// will not receive partial input for the rules you're trying to match (this
/// is almost always the case for parsing programming languages).
#[macro_export]
macro_rules! alt_complete (
// Recursive rules (must include `complete!` around the head)
($i:expr, $e:ident | $($rest:tt)*) => (
alt_complete!($i, complete!(call!($e)) | $($rest)*);
);
($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
let res = complete!($i, $subrule!($($args)*));
match res {
$crate::IResult::Done(_,_) => res,
_ => alt_complete!($i, $($rest)*),
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
match complete!($i, $subrule!($($args)*)) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
_ => alt_complete!($i, $($rest)*),
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_complete!($i, complete!(call!($e)) => { $gen } | $($rest)*);
);
// Tail (non-recursive) rules
($i:expr, $e:ident => { $gen:expr }) => (
alt_complete!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
alt_parser!($i, $subrule!($($args)*) => { $gen })
);
($i:expr, $e:ident) => (
alt_complete!($i, call!($e));
);
($i:expr, $subrule:ident!( $($args:tt)*)) => (
alt_parser!($i, $subrule!($($args)*))
);
);
/// `switch!(I -> IResult<I,P>, P => I -> IResult<I,O> | ... | P => I -> IResult<I,O> ) => I -> IResult<I, O>`
/// choose the next parser depending on the result of the first one, if successful,
/// and returns the result of the second parser
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::{Position, NodePosition};
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => tag!("XYZ") |
/// b"efgh" => tag!("123")
/// )
/// );
///
/// let a = b"abcdXYZ123";
/// let b = b"abcdef";
/// let c = b"efgh123";
/// let d = b"blah";
///
/// assert_eq!(sw(&a[..]), Done(&b"123"[..], &b"XYZ"[..]));
/// assert_eq!(sw(&b[..]), Error(NodePosition(ErrorKind::Switch, &b"abcdef"[..], Box::new(Position(ErrorKind::Tag, &b"ef"[..])))));
/// assert_eq!(sw(&c[..]), Done(&b""[..], &b"123"[..]));
/// assert_eq!(sw(&d[..]), Error(Position(ErrorKind::Switch, &b"blah"[..])));
/// # }
/// ```
///
/// Due to limitations in Rust macros, it is not possible to have simple functions on the right hand
/// side of pattern, like this:
///
/// ```ignore
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => tag!("XYZ") |
/// b"efgh" => tag!("123")
/// )
/// );
/// ```
///
/// If you want to pass your own functions instead, you can use the `call!` combinator as follows:
///
/// ```ignore
/// named!(xyz, tag!("XYZ"));
/// named!(num, tag!("123"));
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => call!(xyz) |
/// b"efgh" => call!(num)
/// )
/// );
/// ```
///
#[macro_export]
macro_rules! switch (
($i:expr, $submac:ident!( $($args:tt)*), $($rest:tt)*) => (
{
switch_impl!($i, $submac!($($args)*), $($rest)*)
}
);
($i:expr, $e:ident, $($rest:tt)*) => (
{
switch_impl!($i, call!($e), $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! switch_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error($crate::Err::NodePosition(
$crate::ErrorKind::Switch, $i, ::std::boxed::Box::new(e)
)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i, o) => {
match o {
$($p => match $subrule!(i, $($args2)*) {
$crate::IResult::Error(e) => $crate::IResult::Error($crate::Err::NodePosition(
$crate::ErrorKind::Switch, $i, ::std::boxed::Box::new(e)
)),
a => a,
}),*,
_ => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Switch,$i))
}
}
}
}
);
);
/// `opt!(I -> IResult<I,O>) => I -> IResult<I, Option<O>>`
/// make the underlying parser optional
///
/// returns an Option of the returned type. This parser returns `Some(result)` if the child parser
/// succeeds,`None` if it fails, and `Incomplete` if it did not have enough data to decide
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( o<&[u8], Option<&[u8]> >, opt!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], None));
/// # }
/// ```
#[macro_export]
macro_rules! opt(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, ::std::option::Option::None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt!($i, call!($f));
);
);
/// `opt_res!(I -> IResult<I,O>) => I -> IResult<I, Result<nom::Err,O>>`
/// make the underlying parser optional
///
/// returns a Result, with Err containing the parsing error
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!( o<&[u8], Result<&[u8], nom::Err<&[u8]> > >, opt_res!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Ok(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], Err(Position(ErrorKind::Tag, &b[..]))));
/// # }
/// ```
#[macro_export]
macro_rules! opt_res (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Ok(o)),
$crate::IResult::Error(e) => $crate::IResult::Done($i, Err(e)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt_res!($i, call!($f));
);
);
/// `cond!(bool, I -> IResult<I,O>) => I -> IResult<I, Option<O>>`
/// Conditional combinator
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an Option of the return type of the child
/// parser.
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::IResult;
/// # fn main() {
/// let b = true;
/// let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8],
/// cond!( b, tag!("abcd") ))
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
///
/// let b2 = false;
/// let f2:Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8],
/// cond!( b2, tag!("abcd") ))
/// );
/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, ::std::option::Option::None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Done($i, ::std::option::Option::None)
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond!($i, $cond, call!($f));
);
);
/// `cond_reduce!(bool, I -> IResult<I,O>) => I -> IResult<I, O>`
/// Conditional combinator with error
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an error if the condition is false
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::{Err,ErrorKind};
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond_reduce!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], &b"abcd"[..]));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond_reduce!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Error(Err::Position(ErrorKind::CondReduce, &a[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond_reduce(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::CondReduce, $i))
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond_reduce!($i, $cond, call!($f));
);
);
/// `peek!(I -> IResult<I,O>) => I -> IResult<I, O>`
/// returns a result without consuming the input
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(ptag, peek!( tag!( "abcd" ) ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! peek(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(_,o) => $crate::IResult::Done($i, o),
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
peek!($i, call!($f));
);
);
/// `tap!(name: I -> IResult<I,O> => { block }) => I -> IResult<I, O>`
/// allows access to the parser's result without affecting it
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use std::str;
/// # fn main() {
/// named!(ptag, tap!(res: tag!( "abcd" ) => { println!("recognized {}", str::from_utf8(res).unwrap()) } ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tap (
($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => {
let $name = o;
$e;
$crate::IResult::Done(i, $name)
},
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $name: ident: $f:expr => $e:expr) => (
tap!($i, $name: call!($f) => $e);
);
);
/// `pair!(I -> IResult<I,O>, I -> IResult<I,P>) => I -> IResult<I, (O,P)>`
/// pair(X,Y), returns (x,y)
///
#[macro_export]
macro_rules! pair(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, (o1, o2))
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
pair!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
pair!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
pair!($i, call!($f), call!($g));
);
);
/// `separated_pair!(I -> IResult<I,O>, I -> IResult<I, T>, I -> IResult<I,P>) => I -> IResult<I, (O,P)>`
/// separated_pair(X,sep,Y) returns (x,y)
#[macro_export]
macro_rules! separated_pair(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
separated_pair1!(i1, o1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
separated_pair!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! separated_pair1(
($i:expr, $res1:ident, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
separated_pair2!(i2, $res1, $($rest)*)
}
}
}
);
($i:expr, $res1:ident, $g:expr, $($rest:tt)+) => (
separated_pair1!($i, $res1, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! separated_pair2(
($i:expr, $res1:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,o3) => {
$crate::IResult::Done(i3, ($res1, o3))
}
}
}
);
($i:expr, $res1:ident, $h:expr) => (
separated_pair2!($i, $res1, call!($h));
);
);
/// `preceded!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, O>`
/// preceded(opening, X) returns X
#[macro_export]
macro_rules! preceded(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, o2)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
preceded!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
preceded!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
preceded!($i, call!($f), call!($g));
);
);
/// `terminated!(I -> IResult<I,O>, I -> IResult<I,T>) => I -> IResult<I, O>`
/// terminated(X, closing) returns X
#[macro_export]
macro_rules! terminated(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
$crate::IResult::Done(i2, o1)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
terminated!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
terminated!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
terminated!($i, call!($f), call!($g));
);
);
/// `delimited!(I -> IResult<I,T>, I -> IResult<I,O>, I -> IResult<I,U>) => I -> IResult<I, O>`
/// delimited(opening, X, closing) returns X
#[macro_export]
macro_rules! delimited(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
delimited1!(i1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
delimited!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! delimited1(
($i:expr, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
delimited2!(i2, o2, $($rest)*)
}
}
}
);
($i:expr, $g:expr, $($rest:tt)+) => (
delimited1!($i, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! delimited2(
($i:expr, $res2:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,_) => {
$crate::IResult::Done(i3, $res2)
}
}
}
);
($i:expr, $res2:ident, $h:expr) => (
delimited2!($i, $res2, call!($h));
);
);
/// `separated_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// separated_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut res = ::std::vec::Vec::new();
let mut input = $i;
// get the first element
match $submac!(input, $($args2)*) {
$crate::IResult::Error(_) => $crate::IResult::Done(input, ::std::vec::Vec::new()),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == input.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::SeparatedList,input))
} else {
res.push(o);
input = i;
loop {
// get the separator first
if let $crate::IResult::Done(i2,_) = $sep!(input, $($args)*) {
if i2.len() == input.len() {
break;
}
input = i2;
// get the element next
if let $crate::IResult::Done(i3,o3) = $submac!(input, $($args2)*) {
if i3.len() == input.len() {
break;
}
res.push(o3);
input = i3;
} else {
break;
}
} else {
break;
}
}
$crate::IResult::Done(input, res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_list!($i, call!($f), call!($g));
);
);
/// `separated_nonempty_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// separated_nonempty_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_nonempty_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut res = ::std::vec::Vec::new();
let mut input = $i;
// get the first element
match $submac!(input, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == input.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::SeparatedNonEmptyList,input))
} else {
res.push(o);
input = i;
loop {
if let $crate::IResult::Done(i2,_) = $sep!(input, $($args)*) {
if i2.len() == input.len() {
break;
}
input = i2;
if let $crate::IResult::Done(i3,o3) = $submac!(input, $($args2)*) {
if i3.len() == input.len() {
break;
}
res.push(o3);
input = i3;
} else {
break;
}
} else {
break;
}
}
$crate::IResult::Done(input, res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_nonempty_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_nonempty_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_nonempty_list!($i, call!($f), call!($g));
);
);
/// `many0!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser 0 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many0!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdefgh";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res));
/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new()));
/// # }
/// ```
/// 0 or more
#[macro_export]
macro_rules! many0(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
if ($i).input_len() == 0 {
$crate::IResult::Done($i, ::std::vec::Vec::new())
} else {
match $submac!($i, $($args)*) {
$crate::IResult::Error(_) => {
$crate::IResult::Done($i, ::std::vec::Vec::new())
},
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
if i1.input_len() == 0 {
$crate::IResult::Done(i1,vec![o1])
} else {
let mut res = ::std::vec::Vec::with_capacity(4);
res.push(o1);
let mut input = i1;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
match $submac!(input, $($args)*) {
$crate::IResult::Done(i, o) => {
// do not allow parsers that do not consume input (causes infinite loops)
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
}
$crate::IResult::Error(_) => {
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
}
if input.input_len() == 0 {
break;
}
}
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
}
}
}
);
($i:expr, $f:expr) => (
many0!($i, call!($f));
);
);
/// `many1!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser 1 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many1!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdefgh";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res));
/// assert_eq!(multi(&b[..]), Error(Position(ErrorKind::Many1,&b[..])));
/// # }
/// ```
#[macro_export]
macro_rules! many1(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Many1,$i)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
if i1.len() == 0 {
$crate::IResult::Done(i1,vec![o1])
} else {
let mut res = ::std::vec::Vec::with_capacity(4);
res.push(o1);
let mut input = i1;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
if input.input_len() == 0 {
break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Error(_) => {
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
$crate::IResult::Done(i, o) => {
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
}
}
}
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
}
}
);
($i:expr, $f:expr) => (
many1!($i, call!($f));
);
);
/// `many_m_n!(usize, usize, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser between m and n times (n included) and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many_m_n!(2, 4, tag!( "abcd" ) ) );
///
/// let a = b"abcdefgh";
/// let b = b"abcdabcdefgh";
/// let c = b"abcdabcdabcdabcdabcdefgh";
///
/// assert_eq!(multi(&a[..]),Error(Position(ErrorKind::ManyMN,&a[..])));
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&b[..]), Done(&b"efgh"[..], res));
/// let res2 = vec![&b"abcd"[..], &b"abcd"[..], &b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&c[..]), Done(&b"abcdefgh"[..], res2));
/// # }
/// ```
#[macro_export]
macro_rules! many_m_n(
($i:expr, $m:expr, $n: expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
let mut res = ::std::vec::Vec::with_capacity($m);
let mut input = $i;
let mut count: usize = 0;
let mut err = false;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
if count == $n { break }
match $submac!(input, $($args)*) {
$crate::IResult::Done(i, o) => {
// do not allow parsers that do not consume input (causes infinite loops)
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
count += 1;
}
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
}
if input.input_len() == 0 {
break;
}
}
if count < $m {
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ManyMN,$i))
} else {
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
} else {
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
);
($i:expr, $m:expr, $n: expr, $f:expr) => (
many_m_n!($i, $m, $n, call!($f));
);
);
/// `count!(I -> IResult<I,O>, nb) => I -> IResult<I, Vec<O>>`
/// Applies the child parser a specified number of times
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(counter< Vec<&[u8]> >, count!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count(
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let ret;
let mut input = $i;
let mut res = ::std::vec::Vec::with_capacity($count);
loop {
if res.len() == $count {
ret = $crate::IResult::Done(input, res); break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Done(i,o) => {
res.push(o);
input = i;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Count,$i)); break;
},
$crate::IResult::Incomplete(_) => {
ret = $crate::IResult::Incomplete($crate::Needed::Unknown); break;
}
}
}
ret
}
);
($i:expr, $f:expr, $count: expr) => (
count!($i, call!($f), $count);
);
);
/// `count_fixed!(O, I -> IResult<I,O>, nb) => I -> IResult<I, [O; nb]>`
/// Applies the child parser a fixed number of times and returns a fixed size array
/// The type must be specified and it must be `Copy`
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
/// // can omit the type specifier if returning slices
/// // named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = [&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count_fixed (
($i:expr, $typ:ty, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let ret;
let mut input = $i;
// `$typ` must be Copy, and thus having no destructor, this is panic safe
let mut res: [$typ; $count] = unsafe{[::std::mem::uninitialized(); $count as usize]};
let mut cnt: usize = 0;
loop {
if cnt == $count {
ret = $crate::IResult::Done(input, res); break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Done(i,o) => {
res[cnt] = o;
cnt += 1;
input = i;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Count,$i)); break;
},
$crate::IResult::Incomplete(_) => {
ret = $crate::IResult::Incomplete($crate::Needed::Unknown); break;
}
}
}
ret
}
);
($i:expr, $typ: ty, $f:ident, $count: expr) => (
count_fixed!($i, $typ, call!($f), $count);
);
);
/// `length_value!(I -> IResult<I, nb>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// gets a number from the first parser, then applies the second parser that many times
#[macro_export]
macro_rules! length_value(
($i:expr, $f:expr, $g:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(inum, onum) => {
let ret;
let length_token = $i.len() - inum.len();
let mut input = inum;
let mut res = ::std::vec::Vec::new();
loop {
if res.len() == onum as usize {
ret = $crate::IResult::Done(input, res); break;
}
match $g(input) {
$crate::IResult::Done(iparse, oparse) => {
res.push(oparse);
input = iparse;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::LengthValue,$i)); break;
},
$crate::IResult::Incomplete(a) => {
ret = match a {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(length) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + onum as usize * length))
};
break;
}
}
}
ret
}
}
}
);
($i:expr, $f:expr, $g:expr, $length:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(inum, onum) => {
let ret;
let length_token = $i.len() - inum.len();
let mut input = inum;
let mut res = ::std::vec::Vec::new();
loop {
if res.len() == onum as usize {
ret = $crate::IResult::Done(input, res); break;
}
match $g(input) {
$crate::IResult::Done(iparse, oparse) => {
res.push(oparse);
input = iparse;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::LengthValue,$i)); break;
},
$crate::IResult::Incomplete(a) => {
ret = match a {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(_) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + onum as usize * $length))
};
break;
}
}
}
ret
}
}
}
);
);
#[cfg(test)]
mod tests {
use internal::{Needed,IResult,Err};
use internal::IResult::*;
use internal::Err::*;
use util::ErrorKind;
// reproduce the tag and take macros, because of module import order
macro_rules! tag (
($i:expr, $inp: expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let res : $crate::IResult<&[u8],&[u8]> = if bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(bytes.len()))
} else if &$i[0..bytes.len()] == bytes {
$crate::IResult::Done(&$i[bytes.len()..], &$i[0..bytes.len()])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Tag, $i))
};
res
}
);
);
macro_rules! take(
($i:expr, $count:expr) => (
{
let cnt = $count as usize;
let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt {
$crate::IResult::Incomplete($crate::Needed::Size(cnt))
} else {
$crate::IResult::Done(&$i[cnt..],&$i[0..cnt])
};
res
}
);
);
mod pub_named_mod {
named!(pub tst, tag!("abcd"));
}
#[test]
fn pub_named_test() {
let a = &b"abcd"[..];
let res = pub_named_mod::tst(a);
assert_eq!(res, Done(&b""[..], a));
}
#[test]
fn apply_test() {
fn sum2(a:u8, b:u8) -> u8 { a + b }
fn sum3(a:u8, b:u8, c:u8) -> u8 { a + b + c }
let a = apply!(1, sum2, 2);
let b = apply!(1, sum3, 2, 3);
assert_eq!(a, 3);
assert_eq!(b, 6);
}
#[derive(PartialEq,Eq,Debug)]
struct B {
a: u8,
b: u8
}
#[test]
fn chain2() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[test]
fn nested_chain() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
chain!(
tag!("abcd") ~
tag!("abcd")? ,
|| {}
) ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[derive(PartialEq,Eq,Debug)]
struct C {
a: u8,
b: Option<u8>
}
#[test]
fn chain_mut() {
fn ret_b1_2(i:&[u8]) -> IResult<&[u8], B> { Done(i,B{a:1,b:2}) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
tag!("efgh") ~
mut bb: ret_b1_2 ~
tag!("efgh") ,
||{
bb.b = 3;
bb
}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 3}));
}
#[test]
fn chain_opt() {
named!(y, tag!("efgh"));
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
named!(ret_y<&[u8], u8>, map!(y, |_| 2));
named!(f<&[u8],C>,
chain!(
tag!("abcd") ~
aa: ret_int1 ~
bb: ret_y? ,
||{C{a: aa, b: bb}}
)
);
let r = f(&b"abcdefghX"[..]);
assert_eq!(r, Done(&b"X"[..], C{a: 1, b: Some(2)}));
let r2 = f(&b"abcdWXYZ"[..]);
assert_eq!(r2, Done(&b"WXYZ"[..], C{a: 1, b: None}));
let r3 = f(&b"abcdX"[..]);
assert_eq!(r3, Incomplete(Needed::Size(8)));
}
use util::{error_to_list, add_error_pattern, print_error};
fn error_to_string<P>(e: &Err<P>) -> &'static str {
let v:Vec<ErrorKind> = error_to_list(e);
// do it this way if you can use slice patterns
/*
match &v[..] {
[ErrorKind::Custom(42), ErrorKind::Tag] => "missing `ijkl` tag",
[ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] => "missing `mnop` tag after `ijkl`",
_ => "unrecognized error"
}
*/
if &v[..] == [ErrorKind::Custom(42),ErrorKind::Tag] {
"missing `ijkl` tag"
} else if &v[..] == [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] {
"missing `mnop` tag after `ijkl`"
} else {
"unrecognized error"
}
}
// do it this way if you can use box patterns
/*use std::str;
fn error_to_string(e:Err) -> String
match e {
NodePosition(ErrorKind::Custom(42), i1, box Position(ErrorKind::Tag, i2)) => {
format!("missing `ijkl` tag, found '{}' instead", str::from_utf8(i2).unwrap())
},
NodePosition(ErrorKind::Custom(42), i1, box NodePosition(ErrorKind::Custom(128), i2, box Position(ErrorKind::Tag, i3))) => {
format!("missing `mnop` tag after `ijkl`, found '{}' instead", str::from_utf8(i3).unwrap())
},
_ => "unrecognized error".to_string()
}
}*/
use std::collections;
#[test]
fn err() {
named!(err_test, alt!(
tag!("abcd") |
preceded!(tag!("efgh"), error!(ErrorKind::Custom(42),
chain!(
tag!("ijkl") ~
res: error!(ErrorKind::Custom(128), tag!("mnop")) ,
|| { res }
)
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..], Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
// Merr-like error matching
let mut err_map = collections::HashMap::new();
assert!(add_error_pattern(&mut err_map, err_test(&b"efghpouet"[..]), "missing `ijkl` tag"));
assert!(add_error_pattern(&mut err_map, err_test(&b"efghijklpouet"[..]), "missing `mnop` tag after `ijkl`"));
let res_a2 = res_a.clone();
match res_a {
Error(e) => {
assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Tag]);
assert_eq!(error_to_string(&e), "missing `ijkl` tag");
assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `ijkl` tag"));
},
_ => panic!()
};
let res_b2 = res_b.clone();
match res_b {
Error(e) => {
assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag]);
assert_eq!(error_to_string(&e), "missing `mnop` tag after `ijkl`");
assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `mnop` tag after `ijkl`"));
},
_ => panic!()
};
print_error(a, res_a2);
print_error(b, res_b2);
}
#[test]
fn add_err() {
named!(err_test,
preceded!(tag!("efgh"), add_error!(ErrorKind::Custom(42),
chain!(
tag!("ijkl") ~
res: add_error!(ErrorKind::Custom(128), tag!("mnop")) ,
|| { res }
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..], Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
}
#[test]
fn complete() {
named!(err_test,
chain!(
tag!("ijkl") ~
res: complete!(tag!("mnop")) ,
|| { res }
)
);
let a = &b"ijklmn"[..];
let res_a = err_test(a);
assert_eq!(res_a, Error(Position(ErrorKind::Complete, &b"mn"[..])));
}
#[test]
fn alt() {
fn work(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> {
Done(&b""[..], input)
}
#[allow(unused_variables)]
fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8],&'static str> {
Error(Code(ErrorKind::Custom("abcd")))
}
fn work2(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> {
Done(input, &b""[..])
}
fn alt1(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | dont_work)
}
fn alt2(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | work)
}
fn alt3(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | dont_work | work2 | dont_work)
}
//named!(alt1, alt!(dont_work | dont_work));
//named!(alt2, alt!(dont_work | work));
//named!(alt3, alt!(dont_work | dont_work | work2 | dont_work));
let a = &b"abcd"[..];
assert_eq!(alt1(a), Error(Position(ErrorKind::Alt, a)));
assert_eq!(alt2(a), Done(&b""[..], a));
assert_eq!(alt3(a), Done(a, &b""[..]));
named!(alt4, alt!(tag!("abcd") | tag!("efgh")));
let b = &b"efgh"[..];
assert_eq!(alt4(a), Done(&b""[..], a));
assert_eq!(alt4(b), Done(&b""[..], b));
// test the alternative syntax
named!(alt5<bool>, alt!(tag!("abcd") => { |_| false } | tag!("efgh") => { |_| true }));
assert_eq!(alt5(a), Done(&b""[..], false));
assert_eq!(alt5(b), Done(&b""[..], true));
}
#[test]
fn alt_incomplete() {
named!(alt1, alt!(tag!("a") | tag!("bc") | tag!("def")));
let a = &b""[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(1)));
let a = &b"b"[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(2)));
let a = &b"bcd"[..];
assert_eq!(alt1(a), Done(&b"d"[..], &b"bc"[..]));
let a = &b"cde"[..];
assert_eq!(alt1(a), Error(Position(ErrorKind::Alt, a)));
let a = &b"de"[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(3)));
let a = &b"defg"[..];
assert_eq!(alt1(a), Done(&b"g"[..], &b"def"[..]));
}
#[test]
fn alt_complete() {
named!(ac<&[u8], &[u8]>,
alt_complete!(tag!("abcd") | tag!("ef") | tag!("ghi") | tag!("kl"))
);
let a = &b""[..];
assert_eq!(ac(a), Incomplete(Needed::Size(2)));
let a = &b"ef"[..];
assert_eq!(ac(a), Done(&b""[..], &b"ef"[..]));
let a = &b"cde"[..];
assert_eq!(ac(a), Error(Position(ErrorKind::Alt, a)));
}
#[test]
fn switch() {
named!(sw,
switch!(take!(4),
b"abcd" => take!(2) |
b"efgh" => take!(4)
)
);
let a = &b"abcdefgh"[..];
assert_eq!(sw(a), Done(&b"gh"[..], &b"ef"[..]));
let b = &b"efghijkl"[..];
assert_eq!(sw(b), Done(&b""[..], &b"ijkl"[..]));
let c = &b"afghijkl"[..];
assert_eq!(sw(c), Error(Position(ErrorKind::Switch, &b"afghijkl"[..])));
}
#[test]
fn opt() {
named!(o<&[u8],Option<&[u8]> >, opt!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Some(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], None));
}
#[test]
fn opt_res() {
named!(o<&[u8], Result<&[u8], Err<&[u8]>> >, opt_res!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Ok(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(ErrorKind::Tag, b))));
}
#[test]
fn cond() {
let b = true;
let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b, tag!("abcd") ) ));
let a = b"abcdef";
assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
let b2 = false;
let f2: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b2, tag!("abcd") ) ));
//let f2 = closure!(&'static [u8], cond!( b2, tag!("abcd") ) );
assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
}
#[test]
fn cond_wrapping() {
// Test that cond!() will wrap a given identifier in the call!() macro.
named!(silly, tag!("foo"));
let b = true;
//let f = closure!(&'static [u8], cond!( b, silly ) );
let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b, silly ) ));
assert_eq!(f(b"foobar"), Done(&b"bar"[..], Some(&b"foo"[..])));
}
#[test]
fn peek() {
named!(ptag<&[u8],&[u8]>, peek!(tag!("abcd")));
let r1 = ptag(&b"abcdefgh"[..]);
assert_eq!(r1, Done(&b"abcdefgh"[..], &b"abcd"[..]));
let r1 = ptag(&b"efgh"[..]);
assert_eq!(r1, Error(Position(ErrorKind::Tag,&b"efgh"[..])));
}
#[test]
fn pair() {
named!(p<&[u8],(&[u8], &[u8])>, pair!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn separated_pair() {
named!(p<&[u8],(&[u8], &[u8])>, separated_pair!(tag!("abcd"), tag!(","), tag!("efgh")));
let r1 = p(&b"abcd,efghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn preceded() {
named!(p<&[u8], &[u8]>, preceded!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"efgh"[..]));
}
#[test]
fn terminated() {
named!(p<&[u8], &[u8]>, terminated!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"abcd"[..]));
}
#[test]
fn delimited() {
named!(p<&[u8], &[u8]>, delimited!(tag!("abcd"), tag!("efgh"), tag!("ij")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"kl"[..], &b"efgh"[..]));
}
#[test]
fn separated_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("abcd")));
named!(multi_empty<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let d = &b",,abc"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
let res3 = vec![&b""[..], &b""[..], &b""[..]];
//assert_eq!(multi_empty(d), Done(&b"abc"[..], res3));
}
#[test]
fn separated_nonempty_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorKind::Tag,c)));
}
#[test]
fn many0() {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdefgh"[..];
let c = &b"azerty"[..];
let d = &b"abcdab"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
assert_eq!(multi(d), Incomplete(Needed::Size(8)));
}
#[cfg(feature = "nightly")]
use test::Bencher;
#[cfg(feature = "nightly")]
#[bench]
fn many0_bench(b: &mut Bencher) {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
b.iter(|| {
multi(&b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"[..])
});
}
#[test]
fn many1() {
named!(multi<&[u8],Vec<&[u8]> >, many1!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdefgh"[..];
let c = &b"azerty"[..];
let d = &b"abcdab"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorKind::Many1,c)));
assert_eq!(multi(d), Incomplete(Needed::Size(8)));
}
#[test]
fn infinite_many() {
fn tst(input: &[u8]) -> IResult<&[u8], &[u8]> {
println!("input: {:?}", input);
Error(Position(ErrorKind::Custom(0),input))
}
// should not go into an infinite loop
named!(multi0<&[u8],Vec<&[u8]> >, many0!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi0(a), Done(a, Vec::new()));
named!(multi1<&[u8],Vec<&[u8]> >, many1!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi1(a), Error(Position(ErrorKind::Many1,a)));
}
#[test]
fn many_m_n() {
named!(multi<&[u8],Vec<&[u8]> >, many_m_n!(2, 4, tag!("Abcd")));
let a = &b"Abcdef"[..];
let b = &b"AbcdAbcdefgh"[..];
let c = &b"AbcdAbcdAbcdAbcdefgh"[..];
let d = &b"AbcdAbcdAbcdAbcdAbcdefgh"[..];
let e = &b"AbcdAb"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
let res3 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(c), Done(&b"efgh"[..], res3));
let res4 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(d), Done(&b"Abcdefgh"[..], res4));
assert_eq!(multi(e), Incomplete(Needed::Size(8)));
}
#[test]
fn count() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 2;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
#[test]
fn count_zero() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 0;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let res: Vec<&[u8]> = Vec::new();
assert_eq!(counter(&a[..]), Done(&b"abcdabcdabcdef"[..], res));
}
#[test]
fn count_fixed() {
//named!(counter< [&[u8]; 2], u32 >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
fn counter(input:&[u8]) -> IResult<&[u8], [&[u8]; 2], () > {
count_fixed!(input, &[u8], tag!( "abcd" ), 2 )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
use nom::{le_u16,eof};
#[allow(dead_code)]
pub fn compile_count_fixed(input: &[u8]) -> IResult<&[u8], ()> {
chain!(input,
tag!("abcd") ~
count_fixed!( u16, le_u16, 4 ) ~
eof ,
|| { () }
)
}
#[test]
fn count_fixed_no_type() {
//named!(counter< [&[u8]; 2], u32 >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
fn counter(input:&[u8]) -> IResult<&[u8], [&[u8]; 2], () > {
count_fixed!(input, &[u8], tag!( "abcd" ), 2 )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
use nom::{be_u8,be_u16};
#[test]
fn length_value_test() {
named!(tst1<&[u8], Vec<u16> >, length_value!(be_u8, be_u16));
named!(tst2<&[u8], Vec<u16> >, length_value!(be_u8, be_u16, 2));
let i1 = vec![0, 5, 6];
let i2 = vec![1, 5, 6, 3];
let i3 = vec![2, 5, 6, 3];
let i4 = vec![2, 5, 6, 3, 4, 5, 7];
let i5 = vec![3, 5, 6, 3, 4, 5];
let r1: Vec<u16> = Vec::new();
let r2: Vec<u16> = vec![1286];
let r4: Vec<u16> = vec![1286, 772];
assert_eq!(tst1(&i1), IResult::Done(&i1[1..], r1));
assert_eq!(tst1(&i2), IResult::Done(&i2[3..], r2));
assert_eq!(tst1(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst1(&i4), IResult::Done(&i4[5..], r4));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
let r6: Vec<u16> = Vec::new();
let r7: Vec<u16> = vec![1286];
let r9: Vec<u16> = vec![1286, 772];
assert_eq!(tst2(&i1), IResult::Done(&i1[1..], r6));
assert_eq!(tst2(&i2), IResult::Done(&i2[3..], r7));
assert_eq!(tst2(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst2(&i4), IResult::Done(&i4[5..], r9));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
}
#[test]
fn chain_incomplete() {
let res = chain!(&b"abcdefgh"[..],
a: take!(4) ~
b: take!(8),
||{(a,b )}
);
assert_eq!(res, IResult::Incomplete(Needed::Size(12)));
}
#[test]
fn tuple_test() {
named!(tpl<&[u8], (u16, &[u8], &[u8]) >,
tuple!(
be_u16 ,
take!(3),
tag!("fg")
)
);
assert_eq!(tpl(&b"abcdefgh"[..]), Done(&b"h"[..], (0x6162u16, &b"cde"[..], &b"fg"[..])));
assert_eq!(tpl(&b"abcd"[..]), Incomplete(Needed::Size(5)));
assert_eq!(tpl(&b"abcde"[..]), Incomplete(Needed::Size(7)));
let input = &b"abcdejk"[..];
assert_eq!(tpl(input), Error(Position(ErrorKind::Tag, &input[5..])));
}
}
separated_pair test overhaul
//! Macro combinators
//!
//! Macros are used to make combination easier,
//! since they often do not depend on the type
//! of the data they manipulate or return.
//!
//! There is a trick to make them easier to assemble,
//! combinators are defined like this:
//!
//! ```ignore
//! macro_rules! tag (
//! ($i:expr, $inp: expr) => (
//! {
//! ...
//! }
//! );
//! );
//! ```
//!
//! But when used in other combinators, are Used
//! like this:
//!
//! ```ignore
//! named!(my_function, tag!("abcd"));
//! ```
//!
//! Internally, other combinators will rewrite
//! that call to pass the input as first argument:
//!
//! ```ignore
//! macro_rules! named (
//! ($name:ident, $submac:ident!( $($args:tt)* )) => (
//! fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<'a,&[u8], &[u8]> {
//! $submac!(i, $($args)*)
//! }
//! );
//! );
//! ```
//!
//! If you want to call a combinator directly, you can
//! do it like this:
//!
//! ```ignore
//! let res = { tag!(input, "abcd"); }
//! ```
//!
//! Combinators must have a specific variant for
//! non-macro arguments. Example: passing a function
//! to take_while! instead of another combinator.
//!
//! ```ignore
//! macro_rules! take_while(
//! ($input:expr, $submac:ident!( $($args:tt)* )) => (
//! {
//! ...
//! }
//! );
//!
//! // wrap the function in a macro to pass it to the main implementation
//! ($input:expr, $f:expr) => (
//! take_while!($input, call!($f));
//! );
//! );
//!
/// Wraps a parser in a closure
#[macro_export]
macro_rules! closure (
($ty:ty, $submac:ident!( $($args:tt)* )) => (
|i: $ty| { $submac!(i, $($args)*) }
);
($submac:ident!( $($args:tt)* )) => (
|i| { $submac!(i, $($args)*) }
);
);
/// Makes a function from a parser combination
///
/// The type can be set up if the compiler needs
/// more information
///
/// ```ignore
/// named!(my_function( &[u8] ) -> &[u8], tag!("abcd"));
/// // first type parameter is input, second is output
/// named!(my_function<&[u8], &[u8]>, tag!("abcd"));
/// // will have &[u8] as input type, &[u8] as output type
/// named!(my_function, tag!("abcd"));
/// // will use &[u8] as input type (use this if the compiler
/// // complains about lifetime issues
/// named!(my_function<&[u8]>, tag!("abcd"));
/// //prefix them with 'pub' to make the functions public
/// named!(pub my_function, tag!("abcd"));
/// ```
#[macro_export]
macro_rules! named (
($name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i,$o,u32> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> {
$submac!(i, $($args)*)
}
);
($name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> {
$submac!(i, $($args)*)
}
);
($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
fn $name<'a>( i: &'a[u8] ) -> $crate::IResult<&'a [u8], $o, u32> {
$submac!(i, $($args)*)
}
);
($name:ident, $submac:ident!( $($args:tt)* )) => (
fn $name( i: &[u8] ) -> $crate::IResult<&[u8], &[u8], u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident( $i:ty ) -> $o:ty, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i,$o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty,$e:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o, $e> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$i:ty,$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: $i ) -> $crate::IResult<$i, $o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
pub fn $name( i: &[u8] ) -> $crate::IResult<&[u8], $o, u32> {
$submac!(i, $($args)*)
}
);
(pub $name:ident, $submac:ident!( $($args:tt)* )) => (
pub fn $name<'a>( i: &'a [u8] ) -> $crate::IResult<&[u8], &[u8], u32> {
$submac!(i, $($args)*)
}
);
);
/// Used to wrap common expressions and function as macros
#[macro_export]
macro_rules! call (
($i:expr, $fun:expr) => ( $fun( $i ) );
($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) );
);
/// emulate function currying: `apply!(my_function, arg1, arg2, ...)` becomes `my_function(input, arg1, arg2, ...)`
///
/// Supports up to 6 arguments
#[macro_export]
macro_rules! apply (
($i:expr, $fun:expr, $($args:expr),* ) => ( $fun( $i, $($args),* ) );
);
/// Prevents backtracking if the child parser fails
///
/// This parser will do an early return instead of sending
/// its result to the parent parser.
///
/// If another `error!` combinator is present in the parent
/// chain, the error will be wrapped and another early
/// return will be made.
///
/// This makes it easy to build report on which parser failed,
/// where it failed in the input, and the chain of parsers
/// that led it there.
///
/// Additionally, the error chain contains number identifiers
/// that can be matched to provide useful error messages.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use std::collections;
/// # use nom::IResult::Error;
/// # use nom::Err::{Position,NodePosition};
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(err_test, alt!(
/// tag!("abcd") |
/// preceded!(tag!("efgh"), error!(ErrorKind::Custom(42),
/// chain!(
/// tag!("ijkl") ~
/// res: error!(ErrorKind::Custom(128), tag!("mnop")) ,
/// || { res }
/// )
/// )
/// )
/// ));
/// let a = &b"efghblah"[..];
/// let b = &b"efghijklblah"[..];
/// let c = &b"efghijklmnop"[..];
///
/// let blah = &b"blah"[..];
///
/// let res_a = err_test(a);
/// let res_b = err_test(b);
/// let res_c = err_test(c);
/// assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
/// assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..],
/// Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah))))))
/// );
/// # }
/// ```
///
#[macro_export]
macro_rules! error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
let cl = || {
$submac!($i, $($args)*)
};
match cl() {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
return $crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
error!($i, $code, call!($f));
);
);
/// Add an error if the child parser fails
///
/// While error! does an early return and avoids backtracking,
/// add_error! backtracks normally. It just provides more context
/// for an error
///
#[macro_export]
macro_rules! add_error (
($i:expr, $code:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
$crate::IResult::Error($crate::Err::NodePosition($code, $i, Box::new(e)))
}
}
}
);
($i:expr, $code:expr, $f:expr) => (
add_error!($i, $code, call!($f));
);
);
/// translate parser result from IResult<I,O,u32> to IResult<I,O,E> woth a custom type
///
#[macro_export]
macro_rules! fix_error (
($i:expr, $t:ty, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => {
let err = match e {
$crate::Err::Code(ErrorKind::Custom(_)) |
$crate::Err::Node(ErrorKind::Custom(_), _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Code(e)
},
$crate::Err::Position(ErrorKind::Custom(_), p) |
$crate::Err::NodePosition(ErrorKind::Custom(_), p, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Position(e, p)
},
$crate::Err::Code(_) |
$crate::Err::Node(_, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Code(e)
},
$crate::Err::Position(_, p) |
$crate::Err::NodePosition(_, p, _) => {
let e: ErrorKind<$t> = ErrorKind::Fix;
$crate::Err::Position(e, p)
},
};
$crate::IResult::Error(err)
}
}
}
);
($i:expr, $t:ty, $f:expr) => (
fix_error!($i, $t, call!($f));
);
);
/// replaces a `Incomplete` returned by the child parser
/// with an `Error`
///
#[macro_export]
macro_rules! complete (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(_) => {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Complete, $i))
},
}
}
);
($i:expr, $f:expr) => (
complete!($i, call!($f));
);
);
/// A bit like `std::try!`, this macro will return the remaining input and parsed value if the child parser returned `Done`,
/// and will do an early return for `Error` and `Incomplete`
/// this can provide more flexibility than `chain!` if needed
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorKind};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// let (i1, sz) = try_parse!(input, be_u8);
/// let (i2, length) = try_parse!(i1, expr_opt!(size.checked_add(sz)));
/// let (i3, data) = try_parse!(i2, take!(length));
/// return Done(i3, data);
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorKind::ExprOpt,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! try_parse (
($i:expr, $submac:ident!( $($args:tt)* )) => (
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => (i,o),
$crate::IResult::Error(e) => return $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => return $crate::IResult::Incomplete(i)
}
);
($i:expr, $f:expr) => (
try_parse!($i, call!($f))
);
);
/// `flat_map!(R -> IResult<R,S>, S -> IResult<S,T>) => R -> IResult<R, T>`
///
/// combines a parser R -> IResult<R,S> and
/// a parser S -> IResult<S,T> to return another
/// parser R -> IResult<R,T>
#[macro_export]
macro_rules! flat_map(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
$crate::IResult::Error(e) => {
let err = match e {
$crate::Err::Code(k) | $crate::Err::Node(k, _) | $crate::Err::Position(k, _) | $crate::Err::NodePosition(k, _, _) => {
$crate::Err::Position(k, $i)
}
};
$crate::IResult::Error(err)
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(ref i2)) => $crate::IResult::Incomplete($crate::Needed::Size(*i2)),
$crate::IResult::Done(_, o2) => $crate::IResult::Done(i, o2)
}
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
flat_map!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $g:expr) => (
flat_map!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
flat_map!($i, call!($f), $submac!($($args)*));
);
);
/// `map!(I -> IResult<I,O>, O -> P) => I -> IResult<I, P>`
/// maps a function on the result of a parser
#[macro_export]
macro_rules! map(
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_impl(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => $crate::IResult::Done(i, $submac2!(o, $($args2)*))
}
}
);
);
/// `map_res!(I -> IResult<I,O>, O -> Result<P>) => I -> IResult<I, P>`
/// maps a function returning a Result on the output of a parser
#[macro_export]
macro_rules! map_res (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_res_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_res_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_res_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_res_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_res_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
Ok(output) => $crate::IResult::Done(i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::MapRes, $i))
}
}
}
);
);
/// `map_opt!(I -> IResult<I,O>, O -> Option<P>) => I -> IResult<I, P>`
/// maps a function returning an Option on the output of a parser
#[macro_export]
macro_rules! map_opt (
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
map_opt_impl!($i, $submac!($($args)*), call!($g));
);
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
map_opt_impl!($i, $submac!($($args)*), $submac2!($($args2)*));
);
($i:expr, $f:expr, $g:expr) => (
map_opt_impl!($i, call!($f), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
map_opt_impl!($i, call!($f), $submac!($($args)*));
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! map_opt_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size(i)),
$crate::IResult::Done(i, o) => match $submac2!(o, $($args2)*) {
::std::option::Option::Some(output) => $crate::IResult::Done(i, output),
::std::option::Option::None => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::MapOpt, $i))
}
}
}
);
);
/// `value!(T, R -> IResult<R, S> ) => R -> IResult<R, T>`
///
/// or `value!(T) => R -> IResult<R, T>`
///
/// If the child parser was successful, return the value.
/// If no child parser is provided, always return the value
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(x<u8>, value!(42, delimited!(tag!("<!--"), take!(5), tag!("-->"))));
/// named!(y<u8>, delimited!(tag!("<!--"), value!(42), tag!("-->")));
/// let r = x(&b"<!-- abc --> aaa"[..]);
/// assert_eq!(r, Done(&b" aaa"[..], 42));
///
/// let r2 = y(&b"<!----> aaa"[..]);
/// assert_eq!(r2, Done(&b" aaa"[..], 42));
/// # }
/// ```
#[macro_export]
macro_rules! value (
($i:expr, $res:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::HexDisplay;
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $res)
},
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $res:expr, $f:expr) => (
value!($i, $res, call!($f))
);
($i:expr, $res:expr) => (
$crate::IResult::Done($i, $res)
);
);
/// `expr_res!(Result<E,O>) => I -> IResult<I, O>`
/// evaluate an expression that returns a Result<T,E> and returns a IResult::Done(I,T) if Ok
///
/// See expr_opt for an example
#[macro_export]
macro_rules! expr_res (
($i:expr, $e:expr) => (
{
match $e {
Ok(output) => $crate::IResult::Done($i, output),
Err(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ExprRes, $i))
}
}
);
);
/// `expr_opt!(Option<O>) => I -> IResult<I, O>`
/// evaluate an expression that returns a Option<T> and returns a IResult::Done(I,T) if Ok
///
/// Useful when doing computations in a chain
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::{be_u8,ErrorKind};
///
/// fn take_add(input:&[u8], size: u8) -> IResult<&[u8],&[u8]> {
/// chain!(input,
/// sz: be_u8 ~
/// length: expr_opt!(size.checked_add(sz)) ~ // checking for integer overflow (returns an Option)
/// data: take!(length) ,
/// ||{ data }
/// )
/// }
/// # fn main() {
/// let arr1 = [1, 2, 3, 4, 5];
/// let r1 = take_add(&arr1[..], 1);
/// assert_eq!(r1, Done(&[4,5][..], &[2,3][..]));
///
/// let arr2 = [0xFE, 2, 3, 4, 5];
/// // size is overflowing
/// let r1 = take_add(&arr2[..], 42);
/// assert_eq!(r1, Error(Position(ErrorKind::ExprOpt,&[2,3,4,5][..])));
/// # }
/// ```
#[macro_export]
macro_rules! expr_opt (
($i:expr, $e:expr) => (
{
match $e {
::std::option::Option::Some(output) => $crate::IResult::Done($i, output),
::std::option::Option::None => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ExprOpt, $i))
}
}
);
);
/// `chain!(I->IResult<I,A> ~ I->IResult<I,B> ~ ... I->IResult<I,X> , || { return O } ) => I -> IResult<I, O>`
/// chains parsers and assemble the results through a closure
/// the input type I must implement nom::InputLength
/// this combinator will count how much data is consumed by every child parser and take it into account if
/// there is not enough data
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{self, Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// #[derive(PartialEq,Eq,Debug)]
/// struct B {
/// a: u8,
/// b: Option<u8>
/// }
///
/// named!(y, tag!("efgh"));
///
/// fn ret_int(i:&[u8]) -> IResult<&[u8], u8> { Done(i, 1) }
/// named!(ret_y<&[u8], u8>, map!(y, |_| 1)); // return 1 if the "efgh" tag is found
///
/// named!(z<&[u8], B>,
/// chain!(
/// tag!("abcd") ~ // the '~' character is used as separator
/// aa: ret_int ~ // the result of that parser will be used in the closure
/// tag!("abcd")? ~ // this parser is optional
/// bb: ret_y? , // the result of that parser is an option
/// // the last parser in the chain is followed by a ','
/// ||{B{a: aa, b: bb}}
/// )
/// );
///
/// # fn main() {
/// // the first "abcd" tag is not present, we have an error
/// let r1 = z(&b"efgh"[..]);
/// assert_eq!(r1, Error(Position(ErrorKind::Tag,&b"efgh"[..])));
///
/// // everything is present, everything is parsed
/// let r2 = z(&b"abcdabcdefgh"[..]);
/// assert_eq!(r2, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the second "abcd" tag is optional
/// let r3 = z(&b"abcdefgh"[..]);
/// assert_eq!(r3, Done(&b""[..], B{a: 1, b: Some(1)}));
///
/// // the result of ret_y is optional, as seen in the B structure
/// let r4 = z(&b"abcdabcdwxyz"[..]);
/// assert_eq!(r4, Done(&b"wxyz"[..], B{a: 1, b: None}));
/// # }
/// ```
#[macro_export]
macro_rules! chain (
($i:expr, $($rest:tt)*) => (
{
//use $crate::InputLength;
chaining_parser!($i, 0usize, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! chaining_parser (
($i:expr, $consumed:expr, $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,_) => {
chaining_parser!(i, $consumed + (($i).input_len() - i.input_len()), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
chaining_parser!(input, $consumed + (($i).input_len() - input.input_len()), $($rest)*)
}
}
});
($i:expr, $consumed:expr, $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, $field: call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let $field = o;
chaining_parser!(i, $consumed + (($i).input_len() - i.input_len()), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, mut $field:ident : $e:ident ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, mut $field: call!($e) ~ $($rest)*);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ~ $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let mut $field = o;
chaining_parser!(i, $consumed + ($i).input_len() - i.input_len(), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let ($field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o),i)
} else {
(::std::option::Option::None,$i)
};
chaining_parser!(input, $consumed + ($i).input_len() - input.input_len(), $($rest)*)
}
}
});
($i:expr, $consumed:expr, mut $field:ident : $e:ident ? ~ $($rest:tt)*) => (
chaining_parser!($i, $consumed, mut $field : call!($e) ? ~ $($rest)*);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? ~ $($rest:tt)*) => ({
{
use $crate::InputLength;
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let (mut $field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o),i)
} else {
(::std::option::Option::None,$i)
};
chaining_parser!(input, $consumed + ($i).input_len() - input.input_len(), $($rest)*)
}
}
});
// ending the chain
($i:expr, $consumed:expr, $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, call!($e), $assemble);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,_) => {
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, $e:ident ?, $assemble:expr) => (
chaining_parser!($i, $consumed, call!($e) ?, $assemble);
);
($i:expr, $consumed:expr, $submac:ident!( $($args:tt)* ) ?, $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let input = if let $crate::IResult::Done(i,_) = res {
i
} else {
$i
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, $field: call!($e), $assemble);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, mut $field:ident : $e:ident, $assemble:expr) => (
chaining_parser!($i, $consumed, mut $field: call!($e), $assemble);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ), $assemble:expr) => (
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
let mut $field = o;
$crate::IResult::Done(i, $assemble())
}
}
);
($i:expr, $consumed:expr, $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $consumed, $field : call!($e) ? , $assemble);
);
($i:expr, $consumed:expr, $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let ($field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o), i)
} else {
(::std::option::Option::None, $i)
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, mut $field:ident : $e:ident ? , $assemble:expr) => (
chaining_parser!($i, $consumed, $field : call!($e) ? , $assemble);
);
($i:expr, $consumed:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) ? , $assemble:expr) => ({
let res = $submac!($i, $($args)*);
if let $crate::IResult::Incomplete(inc) = res {
match inc {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(i) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
}
} else {
let (mut $field,input) = if let $crate::IResult::Done(i,o) = res {
(::std::option::Option::Some(o), i)
} else {
(::std::option::Option::None, $i)
};
$crate::IResult::Done(input, $assemble())
}
});
($i:expr, $consumed:expr, $assemble:expr) => (
$crate::IResult::Done($i, $assemble())
)
);
#[macro_export]
macro_rules! tuple (
($i:expr, $($rest:tt)*) => (
{
tuple_parser!($i, 0usize, (), $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! tuple_parser (
($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => (
tuple_parser!($i, $consumed, ($($parsed),*), call!($e), $($rest)*);
);
($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
tuple_parser!(i, $consumed + (($i).input_len() - i.input_len()), (o), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
tuple_parser!(i, $consumed + (($i).input_len() - i.input_len()), ($($parsed)* , o), $($rest)*)
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:tt),*), $e:ident) => (
tuple_parser!($i, $consumed, ($($parsed),*), call!($e));
);
($i:expr, $consumed:expr, (), $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
$crate::IResult::Done(i, (o))
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete($crate::Needed::Unknown) => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::IResult::Incomplete($crate::Needed::Size(i)) => $crate::IResult::Incomplete($crate::Needed::Size($consumed + i)),
$crate::IResult::Done(i,o) => {
$crate::IResult::Done(i, ($($parsed),* , o))
}
}
}
);
($i:expr, $consumed:expr, ($($parsed:expr),*)) => (
{
$crate::IResult::Done($i, ($($parsed),*))
}
);
);
/// `alt!(I -> IResult<I,O> | I -> IResult<I,O> | ... | I -> IResult<I,O> ) => I -> IResult<I, O>`
/// try a list of parsers, return the result of the first successful one
///
/// If one of the parser returns Incomplete, alt will return Incomplete, to retry
/// once you get more input. Note that it is better for performance to know the
/// minimum size of data you need before you get into alt.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( test, alt!( tag!( "abcd" ) | tag!( "efgh" ) ) );
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], &b"abcd"[..]));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], &b"efgh"[..]));
/// # }
/// ```
///
/// There is another syntax for alt allowing a block to manipulate the result:
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// #[derive(Debug,PartialEq,Eq)]
/// enum Tagged {
/// Abcd,
/// Efgh,
/// Took(usize)
/// }
/// named!(test<Tagged>, alt!(
/// tag!("abcd") => { |_| Tagged::Abcd }
/// | tag!("efgh") => { |_| Tagged::Efgh }
/// | take!(5) => { |res: &[u8]| Tagged::Took(res.len()) } // the closure takes the result as argument if the parser is successful
/// ));
/// let r1 = test(b"abcdefgh");
/// assert_eq!(r1, Done(&b"efgh"[..], Tagged::Abcd));
/// let r2 = test(&b"efghijkl"[..]);
/// assert_eq!(r2, Done(&b"ijkl"[..], Tagged::Efgh));
/// let r3 = test(&b"mnopqrst"[..]);
/// assert_eq!(r3, Done(&b"rst"[..], Tagged::Took(5)));
/// # }
/// ```
///
/// **BE CAREFUL** there is a case where the behaviour of `alt!` can be confusing:
///
/// when the alternatives have different lengths, like this case:
///
/// ```ignore
/// named!( test, alt!( tag!( "abcd" ) | tag!( "ef" ) | tag!( "ghi" ) | tag!( "kl" ) ) );
/// ```
///
/// With this parser, if you pass `"abcd"` as input, the first alternative parses it correctly,
/// but if you pass `"efg"`, the first alternative will return `Incomplete`, since it needs an input
/// of 4 bytes. This behaviour of `alt!` is expected: if you get a partial input that isn't matched
/// by the first alternative, but would match if the input was complete, you want `alt!` to indicate
/// that it cannot decide with limited information.
///
/// There are two ways to fix this behaviour. The first one consists in ordering the alternatives
/// by size, like this:
///
/// ```ignore
/// named!( test, alt!( tag!( "ef" ) | tag!( "kl") | tag!( "ghi" ) | tag!( "abcd" ) ) );
/// ```
///
/// With this solution, the largest alternative will be tested last.
///
/// The other solution uses the `complete!` combinator, which transforms an `Incomplete` in an
/// `Error`. If one of the alternatives returns `Incomplete` but is wrapped by `complete!`,
/// `alt!` will try the next alternative. This is useful when you know that
/// you will not get partial input:
///
/// ```ignore
/// named!( test,
/// alt!(
/// complete!( tag!( "abcd" ) ) |
/// complete!( tag!( "ef" ) ) |
/// complete!( tag!( "ghi" ) ) |
/// complete!( tag!( "kl" ) )
/// )
/// );
/// ```
///
/// If you want the `complete!` combinator to be applied to all rules then use the convenience
/// `alt_complete!` macro (see below).
///
/// This behaviour of `alt!` can get especially confusing if multiple alternatives have different
/// sizes but a common prefix, like this:
///
/// ```ignore
/// named!( test, alt!( tag!( "abcd" ) | tag!( "ab" ) | tag!( "ef" ) ) );
/// ```
///
/// in that case, if you order by size, passing `"abcd"` as input will always be matched by the
/// smallest parser, so the solution using `complete!` is better suited.
///
/// You can also nest multiple `alt!`, like this:
///
/// ```ignore
/// named!( test,
/// alt!(
/// preceded!(
/// tag!("ab"),
/// alt!(
/// tag!( "cd" ) |
/// eof
/// )
/// )
/// | tag!( "ef" )
/// )
/// );
/// ```
///
/// `preceded!` will first parse `"ab"` then, if successful, try the alternatives "cd",
/// or empty input (End Of File). If none of them work, `preceded!` will fail and
/// "ef" will be tested.
///
#[macro_export]
macro_rules! alt (
($i:expr, $($rest:tt)*) => (
{
alt_parser!($i, $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! alt_parser (
($i:expr, $e:ident | $($rest:tt)*) => (
alt_parser!($i, call!($e) | $($rest)*);
);
($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
let res = $subrule!($i, $($args)*);
match res {
$crate::IResult::Done(_,_) => res,
$crate::IResult::Incomplete(_) => res,
_ => alt_parser!($i, $($rest)*)
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i, $($rest)*)
}
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_parser!($i, call!($e) => { $gen } | $($rest)*);
);
($i:expr, $e:ident => { $gen:expr }) => (
alt_parser!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i)
}
}
}
);
($i:expr, $e:ident) => (
alt_parser!($i, call!($e));
);
($i:expr, $subrule:ident!( $($args:tt)*)) => (
{
match $subrule!( $i, $($args)* ) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,o),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Error(_) => {
alt_parser!($i)
}
}
}
);
($i:expr) => (
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Alt,$i))
);
);
/// This is a combination of the `alt!` and `complete!` combinators. Rather
/// than returning `Incomplete` on partial input, `alt_complete!` will try the
/// next alternative in the chain. You should use this only if you know you
/// will not receive partial input for the rules you're trying to match (this
/// is almost always the case for parsing programming languages).
#[macro_export]
macro_rules! alt_complete (
// Recursive rules (must include `complete!` around the head)
($i:expr, $e:ident | $($rest:tt)*) => (
alt_complete!($i, complete!(call!($e)) | $($rest)*);
);
($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => (
{
let res = complete!($i, $subrule!($($args)*));
match res {
$crate::IResult::Done(_,_) => res,
_ => alt_complete!($i, $($rest)*),
}
}
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => (
{
match complete!($i, $subrule!($($args)*)) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i,$gen(o)),
_ => alt_complete!($i, $($rest)*),
}
}
);
($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => (
alt_complete!($i, complete!(call!($e)) => { $gen } | $($rest)*);
);
// Tail (non-recursive) rules
($i:expr, $e:ident => { $gen:expr }) => (
alt_complete!($i, call!($e) => { $gen });
);
($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => (
alt_parser!($i, $subrule!($($args)*) => { $gen })
);
($i:expr, $e:ident) => (
alt_complete!($i, call!($e));
);
($i:expr, $subrule:ident!( $($args:tt)*)) => (
alt_parser!($i, $subrule!($($args)*))
);
);
/// `switch!(I -> IResult<I,P>, P => I -> IResult<I,O> | ... | P => I -> IResult<I,O> ) => I -> IResult<I, O>`
/// choose the next parser depending on the result of the first one, if successful,
/// and returns the result of the second parser
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::{Position, NodePosition};
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => tag!("XYZ") |
/// b"efgh" => tag!("123")
/// )
/// );
///
/// let a = b"abcdXYZ123";
/// let b = b"abcdef";
/// let c = b"efgh123";
/// let d = b"blah";
///
/// assert_eq!(sw(&a[..]), Done(&b"123"[..], &b"XYZ"[..]));
/// assert_eq!(sw(&b[..]), Error(NodePosition(ErrorKind::Switch, &b"abcdef"[..], Box::new(Position(ErrorKind::Tag, &b"ef"[..])))));
/// assert_eq!(sw(&c[..]), Done(&b""[..], &b"123"[..]));
/// assert_eq!(sw(&d[..]), Error(Position(ErrorKind::Switch, &b"blah"[..])));
/// # }
/// ```
///
/// Due to limitations in Rust macros, it is not possible to have simple functions on the right hand
/// side of pattern, like this:
///
/// ```ignore
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => tag!("XYZ") |
/// b"efgh" => tag!("123")
/// )
/// );
/// ```
///
/// If you want to pass your own functions instead, you can use the `call!` combinator as follows:
///
/// ```ignore
/// named!(xyz, tag!("XYZ"));
/// named!(num, tag!("123"));
/// named!(sw,
/// switch!(take!(4),
/// b"abcd" => call!(xyz) |
/// b"efgh" => call!(num)
/// )
/// );
/// ```
///
#[macro_export]
macro_rules! switch (
($i:expr, $submac:ident!( $($args:tt)*), $($rest:tt)*) => (
{
switch_impl!($i, $submac!($($args)*), $($rest)*)
}
);
($i:expr, $e:ident, $($rest:tt)*) => (
{
switch_impl!($i, call!($e), $($rest)*)
}
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! switch_impl (
($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(e) => $crate::IResult::Error($crate::Err::NodePosition(
$crate::ErrorKind::Switch, $i, ::std::boxed::Box::new(e)
)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i, o) => {
match o {
$($p => match $subrule!(i, $($args2)*) {
$crate::IResult::Error(e) => $crate::IResult::Error($crate::Err::NodePosition(
$crate::ErrorKind::Switch, $i, ::std::boxed::Box::new(e)
)),
a => a,
}),*,
_ => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Switch,$i))
}
}
}
}
);
);
/// `opt!(I -> IResult<I,O>) => I -> IResult<I, Option<O>>`
/// make the underlying parser optional
///
/// returns an Option of the returned type. This parser returns `Some(result)` if the child parser
/// succeeds,`None` if it fails, and `Incomplete` if it did not have enough data to decide
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!( o<&[u8], Option<&[u8]> >, opt!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], None));
/// # }
/// ```
#[macro_export]
macro_rules! opt(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, ::std::option::Option::None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt!($i, call!($f));
);
);
/// `opt_res!(I -> IResult<I,O>) => I -> IResult<I, Result<nom::Err,O>>`
/// make the underlying parser optional
///
/// returns a Result, with Err containing the parsing error
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!( o<&[u8], Result<&[u8], nom::Err<&[u8]> > >, opt_res!( tag!( "abcd" ) ) );
///
/// let a = b"abcdef";
/// let b = b"bcdefg";
/// assert_eq!(o(&a[..]), Done(&b"ef"[..], Ok(&b"abcd"[..])));
/// assert_eq!(o(&b[..]), Done(&b"bcdefg"[..], Err(Position(ErrorKind::Tag, &b[..]))));
/// # }
/// ```
#[macro_export]
macro_rules! opt_res (
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, Ok(o)),
$crate::IResult::Error(e) => $crate::IResult::Done($i, Err(e)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
opt_res!($i, call!($f));
);
);
/// `cond!(bool, I -> IResult<I,O>) => I -> IResult<I, Option<O>>`
/// Conditional combinator
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an Option of the return type of the child
/// parser.
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use nom::IResult;
/// # fn main() {
/// let b = true;
/// let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8],
/// cond!( b, tag!("abcd") ))
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
///
/// let b2 = false;
/// let f2:Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>>> = Box::new(closure!(&'static[u8],
/// cond!( b2, tag!("abcd") ))
/// );
/// assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)),
$crate::IResult::Error(_) => $crate::IResult::Done($i, ::std::option::Option::None),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Done($i, ::std::option::Option::None)
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond!($i, $cond, call!($f));
);
);
/// `cond_reduce!(bool, I -> IResult<I,O>) => I -> IResult<I, O>`
/// Conditional combinator with error
///
/// Wraps another parser and calls it if the
/// condition is met. This combinator returns
/// an error if the condition is false
///
/// This is especially useful if a parser depends
/// on the value return by a preceding parser in
/// a `chain!`.
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::{Err,ErrorKind};
/// # fn main() {
/// let b = true;
/// let f = closure!(&'static[u8],
/// cond_reduce!( b, tag!("abcd") )
/// );
///
/// let a = b"abcdef";
/// assert_eq!(f(&a[..]), Done(&b"ef"[..], &b"abcd"[..]));
///
/// let b2 = false;
/// let f2 = closure!(&'static[u8],
/// cond_reduce!( b2, tag!("abcd") )
/// );
/// assert_eq!(f2(&a[..]), Error(Err::Position(ErrorKind::CondReduce, &a[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! cond_reduce(
($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => (
{
if $cond {
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => $crate::IResult::Done(i, o),
$crate::IResult::Error(e) => $crate::IResult::Error(e),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::CondReduce, $i))
}
}
);
($i:expr, $cond:expr, $f:expr) => (
cond_reduce!($i, $cond, call!($f));
);
);
/// `peek!(I -> IResult<I,O>) => I -> IResult<I, O>`
/// returns a result without consuming the input
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(ptag, peek!( tag!( "abcd" ) ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"abcdefgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! peek(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(_,o) => $crate::IResult::Done($i, o),
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $f:expr) => (
peek!($i, call!($f));
);
);
/// `tap!(name: I -> IResult<I,O> => { block }) => I -> IResult<I, O>`
/// allows access to the parser's result without affecting it
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # use std::str;
/// # fn main() {
/// named!(ptag, tap!(res: tag!( "abcd" ) => { println!("recognized {}", str::from_utf8(res).unwrap()) } ) );
///
/// let r = ptag(&b"abcdefgh"[..]);
/// assert_eq!(r, Done(&b"efgh"[..], &b"abcd"[..]));
/// # }
/// ```
#[macro_export]
macro_rules! tap (
($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Done(i,o) => {
let $name = o;
$e;
$crate::IResult::Done(i, $name)
},
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i)
}
}
);
($i:expr, $name: ident: $f:expr => $e:expr) => (
tap!($i, $name: call!($f) => $e);
);
);
/// `pair!(I -> IResult<I,O>, I -> IResult<I,P>) => I -> IResult<I, (O,P)>`
/// pair(X,Y), returns (x,y)
///
#[macro_export]
macro_rules! pair(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, (o1, o2))
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
pair!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
pair!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
pair!($i, call!($f), call!($g));
);
);
/// `separated_pair!(I -> IResult<I,O>, I -> IResult<I, T>, I -> IResult<I,P>) => I -> IResult<I, (O,P)>`
/// separated_pair(X,sep,Y) returns (x,y)
#[macro_export]
macro_rules! separated_pair(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
separated_pair1!(i1, o1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
separated_pair!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! separated_pair1(
($i:expr, $res1:ident, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
separated_pair2!(i2, $res1, $($rest)*)
}
}
}
);
($i:expr, $res1:ident, $g:expr, $($rest:tt)+) => (
separated_pair1!($i, $res1, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! separated_pair2(
($i:expr, $res1:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,o3) => {
$crate::IResult::Done(i3, ($res1, o3))
}
}
}
);
($i:expr, $res1:ident, $h:expr) => (
separated_pair2!($i, $res1, call!($h));
);
);
/// `preceded!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, O>`
/// preceded(opening, X) returns X
#[macro_export]
macro_rules! preceded(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
$crate::IResult::Done(i2, o2)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
preceded!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
preceded!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
preceded!($i, call!($f), call!($g));
);
);
/// `terminated!(I -> IResult<I,O>, I -> IResult<I,T>) => I -> IResult<I, O>`
/// terminated(X, closing) returns X
#[macro_export]
macro_rules! terminated(
($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
match $submac2!(i1, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,_) => {
$crate::IResult::Done(i2, o1)
}
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
terminated!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
terminated!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
terminated!($i, call!($f), call!($g));
);
);
/// `delimited!(I -> IResult<I,T>, I -> IResult<I,O>, I -> IResult<I,U>) => I -> IResult<I, O>`
/// delimited(opening, X, closing) returns X
#[macro_export]
macro_rules! delimited(
($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => (
{
match $submac!($i, $($args)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,_) => {
delimited1!(i1, $($rest)*)
}
}
}
);
($i:expr, $f:expr, $($rest:tt)+) => (
delimited!($i, call!($f), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! delimited1(
($i:expr, $submac2:ident!( $($args2:tt)* ), $($rest:tt)+) => (
{
match $submac2!($i, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i2,o2) => {
delimited2!(i2, o2, $($rest)*)
}
}
}
);
($i:expr, $g:expr, $($rest:tt)+) => (
delimited1!($i, call!($g), $($rest)*);
);
);
/// Internal parser, do not use directly
#[doc(hidden)]
#[macro_export]
macro_rules! delimited2(
($i:expr, $res2:ident, $submac3:ident!( $($args3:tt)* )) => (
{
match $submac3!($i, $($args3)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i3,_) => {
$crate::IResult::Done(i3, $res2)
}
}
}
);
($i:expr, $res2:ident, $h:expr) => (
delimited2!($i, $res2, call!($h));
);
);
/// `separated_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// separated_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut res = ::std::vec::Vec::new();
let mut input = $i;
// get the first element
match $submac!(input, $($args2)*) {
$crate::IResult::Error(_) => $crate::IResult::Done(input, ::std::vec::Vec::new()),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == input.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::SeparatedList,input))
} else {
res.push(o);
input = i;
loop {
// get the separator first
if let $crate::IResult::Done(i2,_) = $sep!(input, $($args)*) {
if i2.len() == input.len() {
break;
}
input = i2;
// get the element next
if let $crate::IResult::Done(i3,o3) = $submac!(input, $($args2)*) {
if i3.len() == input.len() {
break;
}
res.push(o3);
input = i3;
} else {
break;
}
} else {
break;
}
}
$crate::IResult::Done(input, res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_list!($i, call!($f), call!($g));
);
);
/// `separated_nonempty_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// separated_nonempty_list(sep, X) returns Vec<X>
#[macro_export]
macro_rules! separated_nonempty_list(
($i:expr, $sep:ident!( $($args:tt)* ), $submac:ident!( $($args2:tt)* )) => (
{
let mut res = ::std::vec::Vec::new();
let mut input = $i;
// get the first element
match $submac!(input, $($args2)*) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i,o) => {
if i.len() == input.len() {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::SeparatedNonEmptyList,input))
} else {
res.push(o);
input = i;
loop {
if let $crate::IResult::Done(i2,_) = $sep!(input, $($args)*) {
if i2.len() == input.len() {
break;
}
input = i2;
if let $crate::IResult::Done(i3,o3) = $submac!(input, $($args2)*) {
if i3.len() == input.len() {
break;
}
res.push(o3);
input = i3;
} else {
break;
}
} else {
break;
}
}
$crate::IResult::Done(input, res)
}
},
}
}
);
($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => (
separated_nonempty_list!($i, $submac!($($args)*), call!($g));
);
($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => (
separated_nonempty_list!($i, call!($f), $submac!($($args)*));
);
($i:expr, $f:expr, $g:expr) => (
separated_nonempty_list!($i, call!($f), call!($g));
);
);
/// `many0!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser 0 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::Done;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many0!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdefgh";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res));
/// assert_eq!(multi(&b[..]), Done(&b"azerty"[..], Vec::new()));
/// # }
/// ```
/// 0 or more
#[macro_export]
macro_rules! many0(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
if ($i).input_len() == 0 {
$crate::IResult::Done($i, ::std::vec::Vec::new())
} else {
match $submac!($i, $($args)*) {
$crate::IResult::Error(_) => {
$crate::IResult::Done($i, ::std::vec::Vec::new())
},
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
if i1.input_len() == 0 {
$crate::IResult::Done(i1,vec![o1])
} else {
let mut res = ::std::vec::Vec::with_capacity(4);
res.push(o1);
let mut input = i1;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
match $submac!(input, $($args)*) {
$crate::IResult::Done(i, o) => {
// do not allow parsers that do not consume input (causes infinite loops)
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
}
$crate::IResult::Error(_) => {
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
}
if input.input_len() == 0 {
break;
}
}
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
}
}
}
);
($i:expr, $f:expr) => (
many0!($i, call!($f));
);
);
/// `many1!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser 1 or more times and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many1!( tag!( "abcd" ) ) );
///
/// let a = b"abcdabcdefgh";
/// let b = b"azerty";
///
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&a[..]), Done(&b"efgh"[..], res));
/// assert_eq!(multi(&b[..]), Error(Position(ErrorKind::Many1,&b[..])));
/// # }
/// ```
#[macro_export]
macro_rules! many1(
($i:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
match $submac!($i, $($args)*) {
$crate::IResult::Error(_) => $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Many1,$i)),
$crate::IResult::Incomplete(i) => $crate::IResult::Incomplete(i),
$crate::IResult::Done(i1,o1) => {
if i1.len() == 0 {
$crate::IResult::Done(i1,vec![o1])
} else {
let mut res = ::std::vec::Vec::with_capacity(4);
res.push(o1);
let mut input = i1;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
if input.input_len() == 0 {
break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Error(_) => {
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
$crate::IResult::Done(i, o) => {
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
}
}
}
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
}
}
);
($i:expr, $f:expr) => (
many1!($i, call!($f));
);
);
/// `many_m_n!(usize, usize, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// Applies the parser between m and n times (n included) and returns the list of results in a Vec
///
/// the embedded parser may return Incomplete
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done, Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(multi<&[u8], Vec<&[u8]> >, many_m_n!(2, 4, tag!( "abcd" ) ) );
///
/// let a = b"abcdefgh";
/// let b = b"abcdabcdefgh";
/// let c = b"abcdabcdabcdabcdabcdefgh";
///
/// assert_eq!(multi(&a[..]),Error(Position(ErrorKind::ManyMN,&a[..])));
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&b[..]), Done(&b"efgh"[..], res));
/// let res2 = vec![&b"abcd"[..], &b"abcd"[..], &b"abcd"[..], &b"abcd"[..]];
/// assert_eq!(multi(&c[..]), Done(&b"abcdefgh"[..], res2));
/// # }
/// ```
#[macro_export]
macro_rules! many_m_n(
($i:expr, $m:expr, $n: expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::InputLength;
let mut res = ::std::vec::Vec::with_capacity($m);
let mut input = $i;
let mut count: usize = 0;
let mut err = false;
let mut incomplete: ::std::option::Option<$crate::Needed> = ::std::option::Option::None;
loop {
if count == $n { break }
match $submac!(input, $($args)*) {
$crate::IResult::Done(i, o) => {
// do not allow parsers that do not consume input (causes infinite loops)
if i.input_len() == input.input_len() {
break;
}
res.push(o);
input = i;
count += 1;
}
$crate::IResult::Error(_) => {
err = true;
break;
},
$crate::IResult::Incomplete($crate::Needed::Unknown) => {
incomplete = ::std::option::Option::Some($crate::Needed::Unknown);
break;
},
$crate::IResult::Incomplete($crate::Needed::Size(i)) => {
incomplete = ::std::option::Option::Some($crate::Needed::Size(i + ($i).input_len() - input.input_len()));
break;
},
}
if input.input_len() == 0 {
break;
}
}
if count < $m {
if err {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::ManyMN,$i))
} else {
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Incomplete($crate::Needed::Unknown)
}
}
} else {
match incomplete {
::std::option::Option::Some(i) => $crate::IResult::Incomplete(i),
::std::option::Option::None => $crate::IResult::Done(input, res)
}
}
}
);
($i:expr, $m:expr, $n: expr, $f:expr) => (
many_m_n!($i, $m, $n, call!($f));
);
);
/// `count!(I -> IResult<I,O>, nb) => I -> IResult<I, Vec<O>>`
/// Applies the child parser a specified number of times
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(counter< Vec<&[u8]> >, count!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = vec![&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count(
($i:expr, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let ret;
let mut input = $i;
let mut res = ::std::vec::Vec::with_capacity($count);
loop {
if res.len() == $count {
ret = $crate::IResult::Done(input, res); break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Done(i,o) => {
res.push(o);
input = i;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Count,$i)); break;
},
$crate::IResult::Incomplete(_) => {
ret = $crate::IResult::Incomplete($crate::Needed::Unknown); break;
}
}
}
ret
}
);
($i:expr, $f:expr, $count: expr) => (
count!($i, call!($f), $count);
);
);
/// `count_fixed!(O, I -> IResult<I,O>, nb) => I -> IResult<I, [O; nb]>`
/// Applies the child parser a fixed number of times and returns a fixed size array
/// The type must be specified and it must be `Copy`
///
/// ```
/// # #[macro_use] extern crate nom;
/// # use nom::IResult::{Done,Error};
/// # use nom::Err::Position;
/// # use nom::ErrorKind;
/// # fn main() {
/// named!(counter< [&[u8]; 2] >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
/// // can omit the type specifier if returning slices
/// // named!(counter< [&[u8]; 2] >, count_fixed!( tag!( "abcd" ), 2 ) );
///
/// let a = b"abcdabcdabcdef";
/// let b = b"abcdefgh";
/// let res = [&b"abcd"[..], &b"abcd"[..]];
///
/// assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
/// assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
/// # }
/// ```
///
#[macro_export]
macro_rules! count_fixed (
($i:expr, $typ:ty, $submac:ident!( $($args:tt)* ), $count: expr) => (
{
let ret;
let mut input = $i;
// `$typ` must be Copy, and thus having no destructor, this is panic safe
let mut res: [$typ; $count] = unsafe{[::std::mem::uninitialized(); $count as usize]};
let mut cnt: usize = 0;
loop {
if cnt == $count {
ret = $crate::IResult::Done(input, res); break;
}
match $submac!(input, $($args)*) {
$crate::IResult::Done(i,o) => {
res[cnt] = o;
cnt += 1;
input = i;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Count,$i)); break;
},
$crate::IResult::Incomplete(_) => {
ret = $crate::IResult::Incomplete($crate::Needed::Unknown); break;
}
}
}
ret
}
);
($i:expr, $typ: ty, $f:ident, $count: expr) => (
count_fixed!($i, $typ, call!($f), $count);
);
);
/// `length_value!(I -> IResult<I, nb>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>>`
/// gets a number from the first parser, then applies the second parser that many times
#[macro_export]
macro_rules! length_value(
($i:expr, $f:expr, $g:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(inum, onum) => {
let ret;
let length_token = $i.len() - inum.len();
let mut input = inum;
let mut res = ::std::vec::Vec::new();
loop {
if res.len() == onum as usize {
ret = $crate::IResult::Done(input, res); break;
}
match $g(input) {
$crate::IResult::Done(iparse, oparse) => {
res.push(oparse);
input = iparse;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::LengthValue,$i)); break;
},
$crate::IResult::Incomplete(a) => {
ret = match a {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(length) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + onum as usize * length))
};
break;
}
}
}
ret
}
}
}
);
($i:expr, $f:expr, $g:expr, $length:expr) => (
{
match $f($i) {
$crate::IResult::Error(a) => $crate::IResult::Error(a),
$crate::IResult::Incomplete(x) => $crate::IResult::Incomplete(x),
$crate::IResult::Done(inum, onum) => {
let ret;
let length_token = $i.len() - inum.len();
let mut input = inum;
let mut res = ::std::vec::Vec::new();
loop {
if res.len() == onum as usize {
ret = $crate::IResult::Done(input, res); break;
}
match $g(input) {
$crate::IResult::Done(iparse, oparse) => {
res.push(oparse);
input = iparse;
},
$crate::IResult::Error(_) => {
ret = $crate::IResult::Error($crate::Err::Position($crate::ErrorKind::LengthValue,$i)); break;
},
$crate::IResult::Incomplete(a) => {
ret = match a {
$crate::Needed::Unknown => $crate::IResult::Incomplete($crate::Needed::Unknown),
$crate::Needed::Size(_) => $crate::IResult::Incomplete($crate::Needed::Size(length_token + onum as usize * $length))
};
break;
}
}
}
ret
}
}
}
);
);
#[cfg(test)]
mod tests {
use internal::{Needed,IResult,Err};
use internal::IResult::*;
use internal::Err::*;
use util::ErrorKind;
// reproduce the tag and take macros, because of module import order
macro_rules! tag (
($i:expr, $inp: expr) => (
{
#[inline(always)]
fn as_bytes<T: $crate::AsBytes>(b: &T) -> &[u8] {
b.as_bytes()
}
let expected = $inp;
let bytes = as_bytes(&expected);
let res : $crate::IResult<&[u8],&[u8]> = if bytes.len() > $i.len() {
$crate::IResult::Incomplete($crate::Needed::Size(bytes.len()))
} else if &$i[0..bytes.len()] == bytes {
$crate::IResult::Done(&$i[bytes.len()..], &$i[0..bytes.len()])
} else {
$crate::IResult::Error($crate::Err::Position($crate::ErrorKind::Tag, $i))
};
res
}
);
);
macro_rules! take(
($i:expr, $count:expr) => (
{
let cnt = $count as usize;
let res:$crate::IResult<&[u8],&[u8]> = if $i.len() < cnt {
$crate::IResult::Incomplete($crate::Needed::Size(cnt))
} else {
$crate::IResult::Done(&$i[cnt..],&$i[0..cnt])
};
res
}
);
);
mod pub_named_mod {
named!(pub tst, tag!("abcd"));
}
#[test]
fn pub_named_test() {
let a = &b"abcd"[..];
let res = pub_named_mod::tst(a);
assert_eq!(res, Done(&b""[..], a));
}
#[test]
fn apply_test() {
fn sum2(a:u8, b:u8) -> u8 { a + b }
fn sum3(a:u8, b:u8, c:u8) -> u8 { a + b + c }
let a = apply!(1, sum2, 2);
let b = apply!(1, sum3, 2, 3);
assert_eq!(a, 3);
assert_eq!(b, 6);
}
#[derive(PartialEq,Eq,Debug)]
struct B {
a: u8,
b: u8
}
#[test]
fn chain2() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[test]
fn nested_chain() {
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Done(i,2) };
named!(f<&[u8],B>,
chain!(
chain!(
tag!("abcd") ~
tag!("abcd")? ,
|| {}
) ~
aa: ret_int1 ~
tag!("efgh") ~
bb: ret_int2 ~
tag!("efgh") ,
||{B{a: aa, b: bb}}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 2}));
let r2 = f(&b"abcdefghefghX"[..]);
assert_eq!(r2, Done(&b"X"[..], B{a: 1, b: 2}));
}
#[derive(PartialEq,Eq,Debug)]
struct C {
a: u8,
b: Option<u8>
}
#[test]
fn chain_mut() {
fn ret_b1_2(i:&[u8]) -> IResult<&[u8], B> { Done(i,B{a:1,b:2}) };
named!(f<&[u8],B>,
chain!(
tag!("abcd") ~
tag!("abcd")? ~
tag!("efgh") ~
mut bb: ret_b1_2 ~
tag!("efgh") ,
||{
bb.b = 3;
bb
}
)
);
let r = f(&b"abcdabcdefghefghX"[..]);
assert_eq!(r, Done(&b"X"[..], B{a: 1, b: 3}));
}
#[test]
fn chain_opt() {
named!(y, tag!("efgh"));
fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Done(i,1) };
named!(ret_y<&[u8], u8>, map!(y, |_| 2));
named!(f<&[u8],C>,
chain!(
tag!("abcd") ~
aa: ret_int1 ~
bb: ret_y? ,
||{C{a: aa, b: bb}}
)
);
let r = f(&b"abcdefghX"[..]);
assert_eq!(r, Done(&b"X"[..], C{a: 1, b: Some(2)}));
let r2 = f(&b"abcdWXYZ"[..]);
assert_eq!(r2, Done(&b"WXYZ"[..], C{a: 1, b: None}));
let r3 = f(&b"abcdX"[..]);
assert_eq!(r3, Incomplete(Needed::Size(8)));
}
use util::{error_to_list, add_error_pattern, print_error};
fn error_to_string<P>(e: &Err<P>) -> &'static str {
let v:Vec<ErrorKind> = error_to_list(e);
// do it this way if you can use slice patterns
/*
match &v[..] {
[ErrorKind::Custom(42), ErrorKind::Tag] => "missing `ijkl` tag",
[ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] => "missing `mnop` tag after `ijkl`",
_ => "unrecognized error"
}
*/
if &v[..] == [ErrorKind::Custom(42),ErrorKind::Tag] {
"missing `ijkl` tag"
} else if &v[..] == [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag] {
"missing `mnop` tag after `ijkl`"
} else {
"unrecognized error"
}
}
// do it this way if you can use box patterns
/*use std::str;
fn error_to_string(e:Err) -> String
match e {
NodePosition(ErrorKind::Custom(42), i1, box Position(ErrorKind::Tag, i2)) => {
format!("missing `ijkl` tag, found '{}' instead", str::from_utf8(i2).unwrap())
},
NodePosition(ErrorKind::Custom(42), i1, box NodePosition(ErrorKind::Custom(128), i2, box Position(ErrorKind::Tag, i3))) => {
format!("missing `mnop` tag after `ijkl`, found '{}' instead", str::from_utf8(i3).unwrap())
},
_ => "unrecognized error".to_string()
}
}*/
use std::collections;
#[test]
fn err() {
named!(err_test, alt!(
tag!("abcd") |
preceded!(tag!("efgh"), error!(ErrorKind::Custom(42),
chain!(
tag!("ijkl") ~
res: error!(ErrorKind::Custom(128), tag!("mnop")) ,
|| { res }
)
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..], Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
// Merr-like error matching
let mut err_map = collections::HashMap::new();
assert!(add_error_pattern(&mut err_map, err_test(&b"efghpouet"[..]), "missing `ijkl` tag"));
assert!(add_error_pattern(&mut err_map, err_test(&b"efghijklpouet"[..]), "missing `mnop` tag after `ijkl`"));
let res_a2 = res_a.clone();
match res_a {
Error(e) => {
assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Tag]);
assert_eq!(error_to_string(&e), "missing `ijkl` tag");
assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `ijkl` tag"));
},
_ => panic!()
};
let res_b2 = res_b.clone();
match res_b {
Error(e) => {
assert_eq!(error_to_list(&e), [ErrorKind::Custom(42), ErrorKind::Custom(128), ErrorKind::Tag]);
assert_eq!(error_to_string(&e), "missing `mnop` tag after `ijkl`");
assert_eq!(err_map.get(&error_to_list(&e)), Some(&"missing `mnop` tag after `ijkl`"));
},
_ => panic!()
};
print_error(a, res_a2);
print_error(b, res_b2);
}
#[test]
fn add_err() {
named!(err_test,
preceded!(tag!("efgh"), add_error!(ErrorKind::Custom(42),
chain!(
tag!("ijkl") ~
res: add_error!(ErrorKind::Custom(128), tag!("mnop")) ,
|| { res }
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblah"[..];
let c = &b"efghijklmnop"[..];
let blah = &b"blah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
let res_c = err_test(c);
assert_eq!(res_a, Error(NodePosition(ErrorKind::Custom(42), blah, Box::new(Position(ErrorKind::Tag, blah)))));
assert_eq!(res_b, Error(NodePosition(ErrorKind::Custom(42), &b"ijklblah"[..], Box::new(NodePosition(ErrorKind::Custom(128), blah, Box::new(Position(ErrorKind::Tag, blah)))))));
assert_eq!(res_c, Done(&b""[..], &b"mnop"[..]));
}
#[test]
fn complete() {
named!(err_test,
chain!(
tag!("ijkl") ~
res: complete!(tag!("mnop")) ,
|| { res }
)
);
let a = &b"ijklmn"[..];
let res_a = err_test(a);
assert_eq!(res_a, Error(Position(ErrorKind::Complete, &b"mn"[..])));
}
#[test]
fn alt() {
fn work(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> {
Done(&b""[..], input)
}
#[allow(unused_variables)]
fn dont_work(input: &[u8]) -> IResult<&[u8],&[u8],&'static str> {
Error(Code(ErrorKind::Custom("abcd")))
}
fn work2(input: &[u8]) -> IResult<&[u8],&[u8], &'static str> {
Done(input, &b""[..])
}
fn alt1(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | dont_work)
}
fn alt2(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | work)
}
fn alt3(i:&[u8]) -> IResult<&[u8],&[u8], &'static str> {
alt!(i, dont_work | dont_work | work2 | dont_work)
}
//named!(alt1, alt!(dont_work | dont_work));
//named!(alt2, alt!(dont_work | work));
//named!(alt3, alt!(dont_work | dont_work | work2 | dont_work));
let a = &b"abcd"[..];
assert_eq!(alt1(a), Error(Position(ErrorKind::Alt, a)));
assert_eq!(alt2(a), Done(&b""[..], a));
assert_eq!(alt3(a), Done(a, &b""[..]));
named!(alt4, alt!(tag!("abcd") | tag!("efgh")));
let b = &b"efgh"[..];
assert_eq!(alt4(a), Done(&b""[..], a));
assert_eq!(alt4(b), Done(&b""[..], b));
// test the alternative syntax
named!(alt5<bool>, alt!(tag!("abcd") => { |_| false } | tag!("efgh") => { |_| true }));
assert_eq!(alt5(a), Done(&b""[..], false));
assert_eq!(alt5(b), Done(&b""[..], true));
}
#[test]
fn alt_incomplete() {
named!(alt1, alt!(tag!("a") | tag!("bc") | tag!("def")));
let a = &b""[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(1)));
let a = &b"b"[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(2)));
let a = &b"bcd"[..];
assert_eq!(alt1(a), Done(&b"d"[..], &b"bc"[..]));
let a = &b"cde"[..];
assert_eq!(alt1(a), Error(Position(ErrorKind::Alt, a)));
let a = &b"de"[..];
assert_eq!(alt1(a), Incomplete(Needed::Size(3)));
let a = &b"defg"[..];
assert_eq!(alt1(a), Done(&b"g"[..], &b"def"[..]));
}
#[test]
fn alt_complete() {
named!(ac<&[u8], &[u8]>,
alt_complete!(tag!("abcd") | tag!("ef") | tag!("ghi") | tag!("kl"))
);
let a = &b""[..];
assert_eq!(ac(a), Incomplete(Needed::Size(2)));
let a = &b"ef"[..];
assert_eq!(ac(a), Done(&b""[..], &b"ef"[..]));
let a = &b"cde"[..];
assert_eq!(ac(a), Error(Position(ErrorKind::Alt, a)));
}
#[test]
fn switch() {
named!(sw,
switch!(take!(4),
b"abcd" => take!(2) |
b"efgh" => take!(4)
)
);
let a = &b"abcdefgh"[..];
assert_eq!(sw(a), Done(&b"gh"[..], &b"ef"[..]));
let b = &b"efghijkl"[..];
assert_eq!(sw(b), Done(&b""[..], &b"ijkl"[..]));
let c = &b"afghijkl"[..];
assert_eq!(sw(c), Error(Position(ErrorKind::Switch, &b"afghijkl"[..])));
}
#[test]
fn opt() {
named!(o<&[u8],Option<&[u8]> >, opt!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Some(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], None));
}
#[test]
fn opt_res() {
named!(o<&[u8], Result<&[u8], Err<&[u8]>> >, opt_res!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"bcdefg"[..];
assert_eq!(o(a), Done(&b"ef"[..], Ok(&b"abcd"[..])));
assert_eq!(o(b), Done(&b"bcdefg"[..], Err(Position(ErrorKind::Tag, b))));
}
#[test]
fn cond() {
let b = true;
let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b, tag!("abcd") ) ));
let a = b"abcdef";
assert_eq!(f(&a[..]), Done(&b"ef"[..], Some(&b"abcd"[..])));
let b2 = false;
let f2: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b2, tag!("abcd") ) ));
//let f2 = closure!(&'static [u8], cond!( b2, tag!("abcd") ) );
assert_eq!(f2(&a[..]), Done(&b"abcdef"[..], None));
}
#[test]
fn cond_wrapping() {
// Test that cond!() will wrap a given identifier in the call!() macro.
named!(silly, tag!("foo"));
let b = true;
//let f = closure!(&'static [u8], cond!( b, silly ) );
let f: Box<Fn(&'static [u8]) -> IResult<&[u8],Option<&[u8]>, &str>> = Box::new(closure!(&'static [u8], cond!( b, silly ) ));
assert_eq!(f(b"foobar"), Done(&b"bar"[..], Some(&b"foo"[..])));
}
#[test]
fn peek() {
named!(ptag<&[u8],&[u8]>, peek!(tag!("abcd")));
let r1 = ptag(&b"abcdefgh"[..]);
assert_eq!(r1, Done(&b"abcdefgh"[..], &b"abcd"[..]));
let r1 = ptag(&b"efgh"[..]);
assert_eq!(r1, Error(Position(ErrorKind::Tag,&b"efgh"[..])));
}
#[test]
fn pair() {
named!(p<&[u8],(&[u8], &[u8])>, pair!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], (&b"abcd"[..], &b"efgh"[..])));
}
#[test]
fn separated_pair() {
named!( tag_abc, tag!("abc") );
named!( tag_def, tag!("def") );
named!( tag_separator, tag!(",") );
named!( sep_pair_abc_def<&[u8],(&[u8], &[u8])>, separated_pair!(tag_abc, tag_separator, tag_def) );
let done = &b"abc,defghijkl"[..];
let parsed_1 = &b"abc"[..];
let parsed_2 = &b"def"[..];
let rest = &b"ghijkl"[..];
let incomplete_1 = &b"ab"[..];
let incomplete_2 = &b"abc,d"[..];
let error = &b"xxx"[..];
let error_1 = &b"xxx,def"[..];
let error_2 = &b"abc,xxx"[..];
assert_eq!(sep_pair_abc_def(done), Done(rest, (parsed_1, parsed_2)));
assert_eq!(sep_pair_abc_def(incomplete_1), Incomplete(Needed::Size(3)));
assert_eq!(sep_pair_abc_def(incomplete_2), Incomplete(Needed::Size(3)));
assert_eq!(sep_pair_abc_def(error), Error(Position(ErrorKind::Tag, error)));
assert_eq!(sep_pair_abc_def(error_1), Error(Position(ErrorKind::Tag, error_1)));
assert_eq!(sep_pair_abc_def(error_2), Error(Position(ErrorKind::Tag, error)));
}
#[test]
fn preceded() {
named!(p<&[u8], &[u8]>, preceded!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"efgh"[..]));
}
#[test]
fn terminated() {
named!(p<&[u8], &[u8]>, terminated!(tag!("abcd"), tag!("efgh")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"ijkl"[..], &b"abcd"[..]));
}
#[test]
fn delimited() {
named!(p<&[u8], &[u8]>, delimited!(tag!("abcd"), tag!("efgh"), tag!("ij")));
let r1 = p(&b"abcdefghijkl"[..]);
assert_eq!(r1, Done(&b"kl"[..], &b"efgh"[..]));
}
#[test]
fn separated_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("abcd")));
named!(multi_empty<&[u8],Vec<&[u8]> >, separated_list!(tag!(","), tag!("")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let d = &b",,abc"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
let res3 = vec![&b""[..], &b""[..], &b""[..]];
//assert_eq!(multi_empty(d), Done(&b"abc"[..], res3));
}
#[test]
fn separated_nonempty_list() {
named!(multi<&[u8],Vec<&[u8]> >, separated_nonempty_list!(tag!(","), tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcd,abcdef"[..];
let c = &b"azerty"[..];
let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Done(&b"ef"[..], res1));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"ef"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorKind::Tag,c)));
}
#[test]
fn many0() {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdefgh"[..];
let c = &b"azerty"[..];
let d = &b"abcdab"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
assert_eq!(multi(c), Done(&b"azerty"[..], Vec::new()));
assert_eq!(multi(d), Incomplete(Needed::Size(8)));
}
#[cfg(feature = "nightly")]
use test::Bencher;
#[cfg(feature = "nightly")]
#[bench]
fn many0_bench(b: &mut Bencher) {
named!(multi<&[u8],Vec<&[u8]> >, many0!(tag!("abcd")));
b.iter(|| {
multi(&b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"[..])
});
}
#[test]
fn many1() {
named!(multi<&[u8],Vec<&[u8]> >, many1!(tag!("abcd")));
let a = &b"abcdef"[..];
let b = &b"abcdabcdefgh"[..];
let c = &b"azerty"[..];
let d = &b"abcdab"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
assert_eq!(multi(c), Error(Position(ErrorKind::Many1,c)));
assert_eq!(multi(d), Incomplete(Needed::Size(8)));
}
#[test]
fn infinite_many() {
fn tst(input: &[u8]) -> IResult<&[u8], &[u8]> {
println!("input: {:?}", input);
Error(Position(ErrorKind::Custom(0),input))
}
// should not go into an infinite loop
named!(multi0<&[u8],Vec<&[u8]> >, many0!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi0(a), Done(a, Vec::new()));
named!(multi1<&[u8],Vec<&[u8]> >, many1!(tst));
let a = &b"abcdef"[..];
assert_eq!(multi1(a), Error(Position(ErrorKind::Many1,a)));
}
#[test]
fn many_m_n() {
named!(multi<&[u8],Vec<&[u8]> >, many_m_n!(2, 4, tag!("Abcd")));
let a = &b"Abcdef"[..];
let b = &b"AbcdAbcdefgh"[..];
let c = &b"AbcdAbcdAbcdAbcdefgh"[..];
let d = &b"AbcdAbcdAbcdAbcdAbcdefgh"[..];
let e = &b"AbcdAb"[..];
//let res1 = vec![&b"abcd"[..]];
assert_eq!(multi(a), Incomplete(Needed::Size(8)));
let res2 = vec![&b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(b), Done(&b"efgh"[..], res2));
let res3 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(c), Done(&b"efgh"[..], res3));
let res4 = vec![&b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..], &b"Abcd"[..]];
assert_eq!(multi(d), Done(&b"Abcdefgh"[..], res4));
assert_eq!(multi(e), Incomplete(Needed::Size(8)));
}
#[test]
fn count() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 2;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = vec![&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
#[test]
fn count_zero() {
fn counter(input: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {
let size: usize = 0;
count!(input, tag!( "abcd" ), size )
}
let a = b"abcdabcdabcdef";
let res: Vec<&[u8]> = Vec::new();
assert_eq!(counter(&a[..]), Done(&b"abcdabcdabcdef"[..], res));
}
#[test]
fn count_fixed() {
//named!(counter< [&[u8]; 2], u32 >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
fn counter(input:&[u8]) -> IResult<&[u8], [&[u8]; 2], () > {
count_fixed!(input, &[u8], tag!( "abcd" ), 2 )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
use nom::{le_u16,eof};
#[allow(dead_code)]
pub fn compile_count_fixed(input: &[u8]) -> IResult<&[u8], ()> {
chain!(input,
tag!("abcd") ~
count_fixed!( u16, le_u16, 4 ) ~
eof ,
|| { () }
)
}
#[test]
fn count_fixed_no_type() {
//named!(counter< [&[u8]; 2], u32 >, count_fixed!( &[u8], tag!( "abcd" ), 2 ) );
fn counter(input:&[u8]) -> IResult<&[u8], [&[u8]; 2], () > {
count_fixed!(input, &[u8], tag!( "abcd" ), 2 )
}
let a = b"abcdabcdabcdef";
let b = b"abcdefgh";
let res = [&b"abcd"[..], &b"abcd"[..]];
assert_eq!(counter(&a[..]), Done(&b"abcdef"[..], res));
assert_eq!(counter(&b[..]), Error(Position(ErrorKind::Count, &b[..])));
}
use nom::{be_u8,be_u16};
#[test]
fn length_value_test() {
named!(tst1<&[u8], Vec<u16> >, length_value!(be_u8, be_u16));
named!(tst2<&[u8], Vec<u16> >, length_value!(be_u8, be_u16, 2));
let i1 = vec![0, 5, 6];
let i2 = vec![1, 5, 6, 3];
let i3 = vec![2, 5, 6, 3];
let i4 = vec![2, 5, 6, 3, 4, 5, 7];
let i5 = vec![3, 5, 6, 3, 4, 5];
let r1: Vec<u16> = Vec::new();
let r2: Vec<u16> = vec![1286];
let r4: Vec<u16> = vec![1286, 772];
assert_eq!(tst1(&i1), IResult::Done(&i1[1..], r1));
assert_eq!(tst1(&i2), IResult::Done(&i2[3..], r2));
assert_eq!(tst1(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst1(&i4), IResult::Done(&i4[5..], r4));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
let r6: Vec<u16> = Vec::new();
let r7: Vec<u16> = vec![1286];
let r9: Vec<u16> = vec![1286, 772];
assert_eq!(tst2(&i1), IResult::Done(&i1[1..], r6));
assert_eq!(tst2(&i2), IResult::Done(&i2[3..], r7));
assert_eq!(tst2(&i3), IResult::Incomplete(Needed::Size(5)));
assert_eq!(tst2(&i4), IResult::Done(&i4[5..], r9));
assert_eq!(tst1(&i5), IResult::Incomplete(Needed::Size(7)));
}
#[test]
fn chain_incomplete() {
let res = chain!(&b"abcdefgh"[..],
a: take!(4) ~
b: take!(8),
||{(a,b )}
);
assert_eq!(res, IResult::Incomplete(Needed::Size(12)));
}
#[test]
fn tuple_test() {
named!(tpl<&[u8], (u16, &[u8], &[u8]) >,
tuple!(
be_u16 ,
take!(3),
tag!("fg")
)
);
assert_eq!(tpl(&b"abcdefgh"[..]), Done(&b"h"[..], (0x6162u16, &b"cde"[..], &b"fg"[..])));
assert_eq!(tpl(&b"abcd"[..]), Incomplete(Needed::Size(5)));
assert_eq!(tpl(&b"abcde"[..]), Incomplete(Needed::Size(7)));
let input = &b"abcdejk"[..];
assert_eq!(tpl(input), Error(Position(ErrorKind::Tag, &input[5..])));
}
}
|
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian, BigEndian};
use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque, BTreeSet};
use std::{fmt, iter, ptr, mem, io};
use rustc::hir::def_id::DefId;
use rustc::ty::{self, BareFnTy, ClosureTy, ClosureSubsts, TyCtxt};
use rustc::ty::subst::Substs;
use rustc::ty::layout::{self, TargetDataLayout};
use syntax::abi::Abi;
use error::{EvalError, EvalResult};
use value::PrimVal;
////////////////////////////////////////////////////////////////////////////////
// Allocations and pointers
////////////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(pub u64);
impl fmt::Display for AllocId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug)]
pub struct Allocation {
/// The actual bytes of the allocation.
/// Note that the bytes of a pointer represent the offset of the pointer
pub bytes: Vec<u8>,
/// Maps from byte addresses to allocations.
/// Only the first byte of a pointer is inserted into the map.
pub relocations: BTreeMap<u64, AllocId>,
/// Denotes undefined memory. Reading from undefined memory is forbidden in miri
pub undef_mask: UndefMask,
/// The alignment of the allocation to detect unaligned reads.
pub align: u64,
/// Whether the allocation may be modified.
/// Use the `mark_static` method of `Memory` to ensure that an error occurs, if the memory of this
/// allocation is modified or deallocated in the future.
pub static_kind: StaticKind,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum StaticKind {
/// may be deallocated without breaking miri's invariants
NotStatic,
/// may be modified, but never deallocated
Mutable,
/// may neither be modified nor deallocated
Immutable,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Pointer {
pub alloc_id: AllocId,
pub offset: u64,
}
impl Pointer {
pub fn new(alloc_id: AllocId, offset: u64) -> Self {
Pointer { alloc_id, offset }
}
pub fn signed_offset(self, i: i64) -> Self {
// FIXME: is it possible to over/underflow here?
if i < 0 {
// trickery to ensure that i64::min_value() works fine
// this formula only works for true negative values, it panics for zero!
let n = u64::max_value() - (i as u64) + 1;
Pointer::new(self.alloc_id, self.offset - n)
} else {
self.offset(i as u64)
}
}
pub fn offset(self, i: u64) -> Self {
Pointer::new(self.alloc_id, self.offset + i)
}
pub fn points_to_zst(&self) -> bool {
self.alloc_id == ZST_ALLOC_ID
}
pub fn to_int<'tcx>(&self) -> EvalResult<'tcx, u64> {
match self.alloc_id {
NEVER_ALLOC_ID => Ok(self.offset),
_ => Err(EvalError::ReadPointerAsBytes),
}
}
pub fn from_int(i: u64) -> Self {
Pointer::new(NEVER_ALLOC_ID, i)
}
pub fn zst_ptr() -> Self {
Pointer::new(ZST_ALLOC_ID, 0)
}
pub fn never_ptr() -> Self {
Pointer::new(NEVER_ALLOC_ID, 0)
}
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
/// Identifies a specific monomorphized function
pub struct FunctionDefinition<'tcx> {
pub def_id: DefId,
pub substs: &'tcx Substs<'tcx>,
pub abi: Abi,
pub sig: &'tcx ty::FnSig<'tcx>,
}
/// Either a concrete function, or a glue function
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum Function<'tcx> {
/// A function or method created by compiling code
Concrete(FunctionDefinition<'tcx>),
/// Glue required to call a regular function through a Fn(Mut|Once) trait object
FnDefAsTraitObject(FunctionDefinition<'tcx>),
/// Glue required to call the actual drop impl's `drop` method.
/// Drop glue takes the `self` by value, while `Drop::drop` take `&mut self`
DropGlue(FunctionDefinition<'tcx>),
/// Glue required to treat the ptr part of a fat pointer
/// as a function pointer
FnPtrAsTraitObject(&'tcx ty::FnSig<'tcx>),
/// Glue for Closures
Closure(FunctionDefinition<'tcx>),
}
impl<'tcx> Function<'tcx> {
pub fn expect_concrete(self) -> EvalResult<'tcx, FunctionDefinition<'tcx>> {
match self {
Function::Concrete(fn_def) => Ok(fn_def),
other => Err(EvalError::ExpectedConcreteFunction(other)),
}
}
pub fn expect_drop_glue(self) -> EvalResult<'tcx, FunctionDefinition<'tcx>> {
match self {
Function::DropGlue(fn_def) => Ok(fn_def),
other => Err(EvalError::ExpectedDropGlue(other)),
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Top-level interpreter memory
////////////////////////////////////////////////////////////////////////////////
pub struct Memory<'a, 'tcx> {
/// Actual memory allocations (arbitrary bytes, may contain pointers into other allocations)
alloc_map: HashMap<AllocId, Allocation>,
/// Number of virtual bytes allocated
memory_usage: u64,
/// Maximum number of virtual bytes that may be allocated
memory_size: u64,
/// Function "allocations". They exist solely so pointers have something to point to, and
/// we can figure out what they point to.
functions: HashMap<AllocId, Function<'tcx>>,
/// Inverse map of `functions` so we don't allocate a new pointer every time we need one
function_alloc_cache: HashMap<Function<'tcx>, AllocId>,
next_id: AllocId,
pub layout: &'a TargetDataLayout,
/// List of memory regions containing packed structures
/// We mark memory as "packed" or "unaligned" for a single statement, and clear the marking afterwards.
/// In the case where no packed structs are present, it's just a single emptyness check of a set
/// instead of heavily influencing all memory access code as other solutions would.
///
/// One disadvantage of this solution is the fact that you can cast a pointer to a packed struct
/// to a pointer to a normal struct and if you access a field of both in the same MIR statement,
/// the normal struct access will succeed even though it shouldn't.
/// But even with mir optimizations, that situation is hard/impossible to produce.
packed: BTreeSet<Entry>,
}
const ZST_ALLOC_ID: AllocId = AllocId(0);
const NEVER_ALLOC_ID: AllocId = AllocId(1);
impl<'a, 'tcx> Memory<'a, 'tcx> {
pub fn new(layout: &'a TargetDataLayout, max_memory: u64) -> Self {
Memory {
alloc_map: HashMap::new(),
functions: HashMap::new(),
function_alloc_cache: HashMap::new(),
next_id: AllocId(2),
layout,
memory_size: max_memory,
memory_usage: 0,
packed: BTreeSet::new(),
}
}
pub fn allocations(&self) -> ::std::collections::hash_map::Iter<AllocId, Allocation> {
self.alloc_map.iter()
}
pub fn create_closure_ptr(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: ClosureSubsts<'tcx>, fn_ty: ClosureTy<'tcx>) -> Pointer {
// FIXME: this is a hack
let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {
unsafety: fn_ty.unsafety,
abi: fn_ty.abi,
sig: fn_ty.sig,
});
self.create_fn_alloc(Function::Closure(FunctionDefinition {
def_id,
substs: substs.substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_as_trait_glue(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::FnDefAsTraitObject(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_ptr_as_trait_glue(&mut self, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::FnPtrAsTraitObject(fn_ty.sig.skip_binder()))
}
pub fn create_drop_glue(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::DropGlue(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_ptr(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::Concrete(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
fn create_fn_alloc(&mut self, def: Function<'tcx>) -> Pointer {
if let Some(&alloc_id) = self.function_alloc_cache.get(&def) {
return Pointer::new(alloc_id, 0);
}
let id = self.next_id;
debug!("creating fn ptr: {}", id);
self.next_id.0 += 1;
self.functions.insert(id, def);
self.function_alloc_cache.insert(def, id);
Pointer::new(id, 0)
}
pub fn allocate(&mut self, size: u64, align: u64) -> EvalResult<'tcx, Pointer> {
if size == 0 {
return Ok(Pointer::zst_ptr());
}
assert!(align != 0);
if self.memory_size - self.memory_usage < size {
return Err(EvalError::OutOfMemory {
allocation_size: size,
memory_size: self.memory_size,
memory_usage: self.memory_usage,
});
}
self.memory_usage += size;
assert_eq!(size as usize as u64, size);
let alloc = Allocation {
bytes: vec![0; size as usize],
relocations: BTreeMap::new(),
undef_mask: UndefMask::new(size),
align,
static_kind: StaticKind::NotStatic,
};
let id = self.next_id;
self.next_id.0 += 1;
self.alloc_map.insert(id, alloc);
Ok(Pointer::new(id, 0))
}
// TODO(solson): Track which allocations were returned from __rust_allocate and report an error
// when reallocating/deallocating any others.
pub fn reallocate(&mut self, ptr: Pointer, new_size: u64, align: u64) -> EvalResult<'tcx, Pointer> {
// TODO(solson): Report error about non-__rust_allocate'd pointer.
if ptr.offset != 0 {
return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
}
if ptr.points_to_zst() {
return self.allocate(new_size, align);
}
if self.get(ptr.alloc_id).ok().map_or(false, |alloc| alloc.static_kind != StaticKind::NotStatic) {
return Err(EvalError::ReallocatedStaticMemory);
}
let size = self.get(ptr.alloc_id)?.bytes.len() as u64;
if new_size > size {
let amount = new_size - size;
self.memory_usage += amount;
let alloc = self.get_mut(ptr.alloc_id)?;
assert_eq!(amount as usize as u64, amount);
alloc.bytes.extend(iter::repeat(0).take(amount as usize));
alloc.undef_mask.grow(amount, false);
} else if size > new_size {
self.memory_usage -= size - new_size;
self.clear_relocations(ptr.offset(new_size), size - new_size)?;
let alloc = self.get_mut(ptr.alloc_id)?;
// `as usize` is fine here, since it is smaller than `size`, which came from a usize
alloc.bytes.truncate(new_size as usize);
alloc.bytes.shrink_to_fit();
alloc.undef_mask.truncate(new_size);
}
Ok(Pointer::new(ptr.alloc_id, 0))
}
// TODO(solson): See comment on `reallocate`.
pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<'tcx> {
if ptr.points_to_zst() {
return Ok(());
}
if ptr.offset != 0 {
// TODO(solson): Report error about non-__rust_allocate'd pointer.
return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
}
if self.get(ptr.alloc_id).ok().map_or(false, |alloc| alloc.static_kind != StaticKind::NotStatic) {
return Err(EvalError::DeallocatedStaticMemory);
}
if let Some(alloc) = self.alloc_map.remove(&ptr.alloc_id) {
self.memory_usage -= alloc.bytes.len() as u64;
} else {
debug!("deallocated a pointer twice: {}", ptr.alloc_id);
// TODO(solson): Report error about erroneous free. This is blocked on properly tracking
// already-dropped state since this if-statement is entered even in safe code without
// it.
}
debug!("deallocated : {}", ptr.alloc_id);
Ok(())
}
pub fn pointer_size(&self) -> u64 {
self.layout.pointer_size.bytes()
}
pub fn endianess(&self) -> layout::Endian {
self.layout.endian
}
pub fn check_align(&self, ptr: Pointer, align: u64, len: u64) -> EvalResult<'tcx> {
let alloc = self.get(ptr.alloc_id)?;
// check whether the memory was marked as packed
// we select all elements that have the correct alloc_id and are within
// the range given by the offset into the allocation and the length
let start = Entry {
alloc_id: ptr.alloc_id,
packed_start: 0,
packed_end: ptr.offset + len,
};
let end = Entry {
alloc_id: ptr.alloc_id,
packed_start: ptr.offset + len,
packed_end: 0,
};
for &Entry { packed_start, packed_end, .. } in self.packed.range(start..end) {
// if the region we are checking is covered by a region in `packed`
// ignore the actual alignment
if packed_start <= ptr.offset && (ptr.offset + len) <= packed_end {
return Ok(());
}
}
if alloc.align < align {
return Err(EvalError::AlignmentCheckFailed {
has: alloc.align,
required: align,
});
}
if ptr.offset % align == 0 {
Ok(())
} else {
Err(EvalError::AlignmentCheckFailed {
has: ptr.offset % align,
required: align,
})
}
}
pub(crate) fn mark_packed(&mut self, ptr: Pointer, len: u64) {
self.packed.insert(Entry {
alloc_id: ptr.alloc_id,
packed_start: ptr.offset,
packed_end: ptr.offset + len,
});
}
pub(crate) fn clear_packed(&mut self) {
self.packed.clear();
}
}
// The derived `Ord` impl sorts first by the first field, then, if the fields are the same
// by the second field, and if those are the same, too, then by the third field.
// This is exactly what we need for our purposes, since a range within an allocation
// will give us all `Entry`s that have that `AllocId`, and whose `packed_start` is <= than
// the one we're looking for, but not > the end of the range we're checking.
// At the same time the `packed_end` is irrelevant for the sorting and range searching, but used for the check.
// This kind of search breaks, if `packed_end < packed_start`, so don't do that!
#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct Entry {
alloc_id: AllocId,
packed_start: u64,
packed_end: u64,
}
/// Allocation accessors
impl<'a, 'tcx> Memory<'a, 'tcx> {
pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation> {
match self.alloc_map.get(&id) {
Some(alloc) => Ok(alloc),
None => match self.functions.get(&id) {
Some(_) => Err(EvalError::DerefFunctionPointer),
None if id == NEVER_ALLOC_ID || id == ZST_ALLOC_ID => Err(EvalError::InvalidMemoryAccess),
None => Err(EvalError::DanglingPointerDeref),
}
}
}
pub fn get_mut(&mut self, id: AllocId) -> EvalResult<'tcx, &mut Allocation> {
match self.alloc_map.get_mut(&id) {
Some(alloc) => match alloc.static_kind {
StaticKind::Mutable |
StaticKind::NotStatic => Ok(alloc),
StaticKind::Immutable => Err(EvalError::ModifiedConstantMemory),
},
None => match self.functions.get(&id) {
Some(_) => Err(EvalError::DerefFunctionPointer),
None if id == NEVER_ALLOC_ID || id == ZST_ALLOC_ID => Err(EvalError::InvalidMemoryAccess),
None => Err(EvalError::DanglingPointerDeref),
}
}
}
pub fn get_fn(&self, id: AllocId) -> EvalResult<'tcx, Function<'tcx>> {
debug!("reading fn ptr: {}", id);
match self.functions.get(&id) {
Some(&fndef) => Ok(fndef),
None => match self.alloc_map.get(&id) {
Some(_) => Err(EvalError::ExecuteMemory),
None => Err(EvalError::InvalidFunctionPointer),
}
}
}
/// For debugging, print an allocation and all allocations it points to, recursively.
pub fn dump_alloc(&self, id: AllocId) {
self.dump_allocs(vec![id]);
}
/// For debugging, print a list of allocations and all allocations they point to, recursively.
pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
use std::fmt::Write;
allocs.sort();
allocs.dedup();
let mut allocs_to_print = VecDeque::from(allocs);
let mut allocs_seen = HashSet::new();
while let Some(id) = allocs_to_print.pop_front() {
if id == ZST_ALLOC_ID || id == NEVER_ALLOC_ID { continue; }
let mut msg = format!("Alloc {:<5} ", format!("{}:", id));
let prefix_len = msg.len();
let mut relocations = vec![];
let alloc = match (self.alloc_map.get(&id), self.functions.get(&id)) {
(Some(a), None) => a,
(None, Some(&Function::Concrete(fn_def))) => {
trace!("{} {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::DropGlue(fn_def))) => {
trace!("{} drop glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::FnDefAsTraitObject(fn_def))) => {
trace!("{} fn as Fn glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::FnPtrAsTraitObject(fn_def))) => {
trace!("{} fn ptr as Fn glue (signature: {:?})", msg, fn_def);
continue;
},
(None, Some(&Function::Closure(fn_def))) => {
trace!("{} closure glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, None) => {
trace!("{} (deallocated)", msg);
continue;
},
(Some(_), Some(_)) => bug!("miri invariant broken: an allocation id exists that points to both a function and a memory location"),
};
for i in 0..(alloc.bytes.len() as u64) {
if let Some(&target_id) = alloc.relocations.get(&i) {
if allocs_seen.insert(target_id) {
allocs_to_print.push_back(target_id);
}
relocations.push((i, target_id));
}
if alloc.undef_mask.is_range_defined(i, i + 1) {
// this `as usize` is fine, since `i` came from a `usize`
write!(msg, "{:02x} ", alloc.bytes[i as usize]).unwrap();
} else {
msg.push_str("__ ");
}
}
let immutable = match alloc.static_kind {
StaticKind::Mutable => "(static mut)",
StaticKind::Immutable => "(immutable)",
StaticKind::NotStatic => "",
};
trace!("{}({} bytes){}", msg, alloc.bytes.len(), immutable);
if !relocations.is_empty() {
msg.clear();
write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
let mut pos = 0;
let relocation_width = (self.pointer_size() - 1) * 3;
for (i, target_id) in relocations {
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "{:1$}", "", ((i - pos) * 3) as usize).unwrap();
let target = match target_id {
ZST_ALLOC_ID => String::from("zst"),
NEVER_ALLOC_ID => String::from("int ptr"),
_ => format!("({})", target_id),
};
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
pos = i + self.pointer_size();
}
trace!("{}", msg);
}
}
}
}
fn dump_fn_def<'tcx>(fn_def: FunctionDefinition<'tcx>) -> String {
let name = ty::tls::with(|tcx| tcx.item_path_str(fn_def.def_id));
let abi = if fn_def.abi == Abi::Rust {
format!("")
} else {
format!("extern {} ", fn_def.abi)
};
format!("function pointer: {}: {}{}", name, abi, fn_def.sig)
}
/// Byte accessors
impl<'a, 'tcx> Memory<'a, 'tcx> {
fn get_bytes_unchecked(&self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
if size == 0 {
return Ok(&[]);
}
self.check_align(ptr, align, size)?;
let alloc = self.get(ptr.alloc_id)?;
let allocation_size = alloc.bytes.len() as u64;
if ptr.offset + size > allocation_size {
return Err(EvalError::PointerOutOfBounds { ptr, size, allocation_size });
}
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&alloc.bytes[offset..offset + size as usize])
}
fn get_bytes_unchecked_mut(&mut self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
if size == 0 {
return Ok(&mut []);
}
self.check_align(ptr, align, size)?;
let alloc = self.get_mut(ptr.alloc_id)?;
let allocation_size = alloc.bytes.len() as u64;
if ptr.offset + size > allocation_size {
return Err(EvalError::PointerOutOfBounds { ptr, size, allocation_size });
}
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&mut alloc.bytes[offset..offset + size as usize])
}
fn get_bytes(&self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
if size == 0 {
return Ok(&[]);
}
if self.relocations(ptr, size)?.count() != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
self.check_defined(ptr, size)?;
self.get_bytes_unchecked(ptr, size, align)
}
fn get_bytes_mut(&mut self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
if size == 0 {
return Ok(&mut []);
}
self.clear_relocations(ptr, size)?;
self.mark_definedness(ptr, size, true)?;
self.get_bytes_unchecked_mut(ptr, size, align)
}
}
/// Reading and writing
impl<'a, 'tcx> Memory<'a, 'tcx> {
/// mark an allocation as static, either mutable or not
pub fn mark_static(&mut self, alloc_id: AllocId, mutable: bool) -> EvalResult<'tcx> {
// do not use `self.get_mut(alloc_id)` here, because we might have already marked a
// sub-element or have circular pointers (e.g. `Rc`-cycles)
let relocations = match self.alloc_map.get_mut(&alloc_id) {
Some(&mut Allocation { ref mut relocations, static_kind: ref mut kind @ StaticKind::NotStatic, .. }) => {
*kind = if mutable {
StaticKind::Mutable
} else {
StaticKind::Immutable
};
// take out the relocations vector to free the borrow on self, so we can call
// mark recursively
mem::replace(relocations, Default::default())
},
None if alloc_id == NEVER_ALLOC_ID || alloc_id == ZST_ALLOC_ID => return Ok(()),
None if !self.functions.contains_key(&alloc_id) => return Err(EvalError::DanglingPointerDeref),
_ => return Ok(()),
};
// recurse into inner allocations
for &alloc in relocations.values() {
self.mark_static(alloc, mutable)?;
}
// put back the relocations
self.alloc_map.get_mut(&alloc_id).expect("checked above").relocations = relocations;
Ok(())
}
pub fn copy(&mut self, src: Pointer, dest: Pointer, size: u64, align: u64) -> EvalResult<'tcx> {
if size == 0 {
return Ok(());
}
self.check_relocation_edges(src, size)?;
let src_bytes = self.get_bytes_unchecked(src, size, align)?.as_ptr();
let dest_bytes = self.get_bytes_mut(dest, size, align)?.as_mut_ptr();
// SAFE: The above indexing would have panicked if there weren't at least `size` bytes
// behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
// `dest` could possibly overlap.
unsafe {
assert_eq!(size as usize as u64, size);
if src.alloc_id == dest.alloc_id {
ptr::copy(src_bytes, dest_bytes, size as usize);
} else {
ptr::copy_nonoverlapping(src_bytes, dest_bytes, size as usize);
}
}
self.copy_undef_mask(src, dest, size)?;
self.copy_relocations(src, dest, size)?;
Ok(())
}
pub fn read_c_str(&self, ptr: Pointer) -> EvalResult<'tcx, &[u8]> {
let alloc = self.get(ptr.alloc_id)?;
assert_eq!(ptr.offset as usize as u64, ptr.offset);
let offset = ptr.offset as usize;
match alloc.bytes[offset..].iter().position(|&c| c == 0) {
Some(size) => {
if self.relocations(ptr, (size + 1) as u64)?.count() != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
self.check_defined(ptr, (size + 1) as u64)?;
Ok(&alloc.bytes[offset..offset + size])
},
None => Err(EvalError::UnterminatedCString(ptr)),
}
}
pub fn read_bytes(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, &[u8]> {
self.get_bytes(ptr, size, 1)
}
pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<'tcx> {
let bytes = self.get_bytes_mut(ptr, src.len() as u64, 1)?;
bytes.clone_from_slice(src);
Ok(())
}
pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: u64) -> EvalResult<'tcx> {
let bytes = self.get_bytes_mut(ptr, count, 1)?;
for b in bytes { *b = val; }
Ok(())
}
pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<'tcx, Pointer> {
let size = self.pointer_size();
self.check_defined(ptr, size)?;
let endianess = self.endianess();
let bytes = self.get_bytes_unchecked(ptr, size, size)?;
let offset = read_target_uint(endianess, bytes).unwrap();
assert_eq!(offset as u64 as u128, offset);
let offset = offset as u64;
let alloc = self.get(ptr.alloc_id)?;
match alloc.relocations.get(&ptr.offset) {
Some(&alloc_id) => Ok(Pointer::new(alloc_id, offset)),
None => Ok(Pointer::from_int(offset)),
}
}
pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<'tcx> {
self.write_usize(dest, ptr.offset as u64)?;
self.get_mut(dest.alloc_id)?.relocations.insert(dest.offset, ptr.alloc_id);
Ok(())
}
pub fn write_primval(
&mut self,
dest: Pointer,
val: PrimVal,
size: u64,
) -> EvalResult<'tcx> {
match val {
PrimVal::Ptr(ptr) => {
assert_eq!(size, self.pointer_size());
self.write_ptr(dest, ptr)
}
PrimVal::Bytes(bytes) => {
// We need to mask here, or the byteorder crate can die when given a u64 larger
// than fits in an integer of the requested size.
let mask = match size {
1 => !0u8 as u128,
2 => !0u16 as u128,
4 => !0u32 as u128,
8 => !0u64 as u128,
16 => !0,
_ => bug!("unexpected PrimVal::Bytes size"),
};
self.write_uint(dest, bytes & mask, size)
}
PrimVal::Undef => self.mark_definedness(dest, size, false),
}
}
pub fn read_bool(&self, ptr: Pointer) -> EvalResult<'tcx, bool> {
let bytes = self.get_bytes(ptr, 1, self.layout.i1_align.abi())?;
match bytes[0] {
0 => Ok(false),
1 => Ok(true),
_ => Err(EvalError::InvalidBool),
}
}
pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<'tcx> {
let align = self.layout.i1_align.abi();
self.get_bytes_mut(ptr, 1, align)
.map(|bytes| bytes[0] = b as u8)
}
fn int_align(&self, size: u64) -> EvalResult<'tcx, u64> {
match size {
1 => Ok(self.layout.i8_align.abi()),
2 => Ok(self.layout.i16_align.abi()),
4 => Ok(self.layout.i32_align.abi()),
8 => Ok(self.layout.i64_align.abi()),
16 => Ok(self.layout.i128_align.abi()),
_ => bug!("bad integer size: {}", size),
}
}
pub fn read_int(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, i128> {
let align = self.int_align(size)?;
self.get_bytes(ptr, size, align).map(|b| read_target_int(self.endianess(), b).unwrap())
}
pub fn write_int(&mut self, ptr: Pointer, n: i128, size: u64) -> EvalResult<'tcx> {
let align = self.int_align(size)?;
let endianess = self.endianess();
let b = self.get_bytes_mut(ptr, size, align)?;
write_target_int(endianess, b, n).unwrap();
Ok(())
}
pub fn read_uint(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, u128> {
let align = self.int_align(size)?;
self.get_bytes(ptr, size, align).map(|b| read_target_uint(self.endianess(), b).unwrap())
}
pub fn write_uint(&mut self, ptr: Pointer, n: u128, size: u64) -> EvalResult<'tcx> {
let align = self.int_align(size)?;
let endianess = self.endianess();
let b = self.get_bytes_mut(ptr, size, align)?;
write_target_uint(endianess, b, n).unwrap();
Ok(())
}
pub fn read_isize(&self, ptr: Pointer) -> EvalResult<'tcx, i64> {
self.read_int(ptr, self.pointer_size()).map(|i| i as i64)
}
pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<'tcx> {
let size = self.pointer_size();
self.write_int(ptr, n as i128, size)
}
pub fn read_usize(&self, ptr: Pointer) -> EvalResult<'tcx, u64> {
self.read_uint(ptr, self.pointer_size()).map(|i| i as u64)
}
pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<'tcx> {
let size = self.pointer_size();
self.write_uint(ptr, n as u128, size)
}
pub fn write_f32(&mut self, ptr: Pointer, f: f32) -> EvalResult<'tcx> {
let endianess = self.endianess();
let align = self.layout.f32_align.abi();
let b = self.get_bytes_mut(ptr, 4, align)?;
write_target_f32(endianess, b, f).unwrap();
Ok(())
}
pub fn write_f64(&mut self, ptr: Pointer, f: f64) -> EvalResult<'tcx> {
let endianess = self.endianess();
let align = self.layout.f64_align.abi();
let b = self.get_bytes_mut(ptr, 8, align)?;
write_target_f64(endianess, b, f).unwrap();
Ok(())
}
pub fn read_f32(&self, ptr: Pointer) -> EvalResult<'tcx, f32> {
self.get_bytes(ptr, 4, self.layout.f32_align.abi())
.map(|b| read_target_f32(self.endianess(), b).unwrap())
}
pub fn read_f64(&self, ptr: Pointer) -> EvalResult<'tcx, f64> {
self.get_bytes(ptr, 8, self.layout.f64_align.abi())
.map(|b| read_target_f64(self.endianess(), b).unwrap())
}
}
/// Relocations
impl<'a, 'tcx> Memory<'a, 'tcx> {
fn relocations(&self, ptr: Pointer, size: u64)
-> EvalResult<'tcx, btree_map::Range<u64, AllocId>>
{
let start = ptr.offset.saturating_sub(self.pointer_size() - 1);
let end = ptr.offset + size;
Ok(self.get(ptr.alloc_id)?.relocations.range(start..end))
}
fn clear_relocations(&mut self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
// Find all relocations overlapping the given range.
let keys: Vec<_> = self.relocations(ptr, size)?.map(|(&k, _)| k).collect();
if keys.is_empty() { return Ok(()); }
// Find the start and end of the given range and its outermost relocations.
let start = ptr.offset;
let end = start + size;
let first = *keys.first().unwrap();
let last = *keys.last().unwrap() + self.pointer_size();
let alloc = self.get_mut(ptr.alloc_id)?;
// Mark parts of the outermost relocations as undefined if they partially fall outside the
// given range.
if first < start { alloc.undef_mask.set_range(first, start, false); }
if last > end { alloc.undef_mask.set_range(end, last, false); }
// Forget all the relocations.
for k in keys { alloc.relocations.remove(&k); }
Ok(())
}
fn check_relocation_edges(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
let overlapping_start = self.relocations(ptr, 0)?.count();
let overlapping_end = self.relocations(ptr.offset(size), 0)?.count();
if overlapping_start + overlapping_end != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
Ok(())
}
fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: u64) -> EvalResult<'tcx> {
let relocations: Vec<_> = self.relocations(src, size)?
.map(|(&offset, &alloc_id)| {
// Update relocation offsets for the new positions in the destination allocation.
(offset + dest.offset - src.offset, alloc_id)
})
.collect();
self.get_mut(dest.alloc_id)?.relocations.extend(relocations);
Ok(())
}
}
/// Undefined bytes
impl<'a, 'tcx> Memory<'a, 'tcx> {
// FIXME(solson): This is a very naive, slow version.
fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: u64) -> EvalResult<'tcx> {
// The bits have to be saved locally before writing to dest in case src and dest overlap.
assert_eq!(size as usize as u64, size);
let mut v = Vec::with_capacity(size as usize);
for i in 0..size {
let defined = self.get(src.alloc_id)?.undef_mask.get(src.offset + i);
v.push(defined);
}
for (i, defined) in v.into_iter().enumerate() {
self.get_mut(dest.alloc_id)?.undef_mask.set(dest.offset + i as u64, defined);
}
Ok(())
}
fn check_defined(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
let alloc = self.get(ptr.alloc_id)?;
if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
return Err(EvalError::ReadUndefBytes);
}
Ok(())
}
pub fn mark_definedness(
&mut self,
ptr: Pointer,
size: u64,
new_state: bool
) -> EvalResult<'tcx> {
if size == 0 {
return Ok(())
}
let mut alloc = self.get_mut(ptr.alloc_id)?;
alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
Ok(())
}
}
////////////////////////////////////////////////////////////////////////////////
// Methods to access integers in the target endianess
////////////////////////////////////////////////////////////////////////////////
fn write_target_uint(endianess: layout::Endian, mut target: &mut [u8], data: u128) -> Result<(), io::Error> {
let len = target.len();
match endianess {
layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
}
}
fn write_target_int(endianess: layout::Endian, mut target: &mut [u8], data: i128) -> Result<(), io::Error> {
let len = target.len();
match endianess {
layout::Endian::Little => target.write_int128::<LittleEndian>(data, len),
layout::Endian::Big => target.write_int128::<BigEndian>(data, len),
}
}
fn read_target_uint(endianess: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
match endianess {
layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
}
}
fn read_target_int(endianess: layout::Endian, mut source: &[u8]) -> Result<i128, io::Error> {
match endianess {
layout::Endian::Little => source.read_int128::<LittleEndian>(source.len()),
layout::Endian::Big => source.read_int128::<BigEndian>(source.len()),
}
}
////////////////////////////////////////////////////////////////////////////////
// Methods to access floats in the target endianess
////////////////////////////////////////////////////////////////////////////////
fn write_target_f32(endianess: layout::Endian, mut target: &mut [u8], data: f32) -> Result<(), io::Error> {
match endianess {
layout::Endian::Little => target.write_f32::<LittleEndian>(data),
layout::Endian::Big => target.write_f32::<BigEndian>(data),
}
}
fn write_target_f64(endianess: layout::Endian, mut target: &mut [u8], data: f64) -> Result<(), io::Error> {
match endianess {
layout::Endian::Little => target.write_f64::<LittleEndian>(data),
layout::Endian::Big => target.write_f64::<BigEndian>(data),
}
}
fn read_target_f32(endianess: layout::Endian, mut source: &[u8]) -> Result<f32, io::Error> {
match endianess {
layout::Endian::Little => source.read_f32::<LittleEndian>(),
layout::Endian::Big => source.read_f32::<BigEndian>(),
}
}
fn read_target_f64(endianess: layout::Endian, mut source: &[u8]) -> Result<f64, io::Error> {
match endianess {
layout::Endian::Little => source.read_f64::<LittleEndian>(),
layout::Endian::Big => source.read_f64::<BigEndian>(),
}
}
////////////////////////////////////////////////////////////////////////////////
// Undefined byte tracking
////////////////////////////////////////////////////////////////////////////////
type Block = u64;
const BLOCK_SIZE: u64 = 64;
#[derive(Clone, Debug)]
pub struct UndefMask {
blocks: Vec<Block>,
len: u64,
}
impl UndefMask {
fn new(size: u64) -> Self {
let mut m = UndefMask {
blocks: vec![],
len: 0,
};
m.grow(size, false);
m
}
/// Check whether the range `start..end` (end-exclusive) is entirely defined.
pub fn is_range_defined(&self, start: u64, end: u64) -> bool {
if end > self.len { return false; }
for i in start..end {
if !self.get(i) { return false; }
}
true
}
fn set_range(&mut self, start: u64, end: u64, new_state: bool) {
let len = self.len;
if end > len { self.grow(end - len, new_state); }
self.set_range_inbounds(start, end, new_state);
}
fn set_range_inbounds(&mut self, start: u64, end: u64, new_state: bool) {
for i in start..end { self.set(i, new_state); }
}
fn get(&self, i: u64) -> bool {
let (block, bit) = bit_index(i);
(self.blocks[block] & 1 << bit) != 0
}
fn set(&mut self, i: u64, new_state: bool) {
let (block, bit) = bit_index(i);
if new_state {
self.blocks[block] |= 1 << bit;
} else {
self.blocks[block] &= !(1 << bit);
}
}
fn grow(&mut self, amount: u64, new_state: bool) {
let unused_trailing_bits = self.blocks.len() as u64 * BLOCK_SIZE - self.len;
if amount > unused_trailing_bits {
let additional_blocks = amount / BLOCK_SIZE + 1;
assert_eq!(additional_blocks as usize as u64, additional_blocks);
self.blocks.extend(iter::repeat(0).take(additional_blocks as usize));
}
let start = self.len;
self.len += amount;
self.set_range_inbounds(start, start + amount, new_state);
}
fn truncate(&mut self, length: u64) {
self.len = length;
let truncate = self.len / BLOCK_SIZE + 1;
assert_eq!(truncate as usize as u64, truncate);
self.blocks.truncate(truncate as usize);
self.blocks.shrink_to_fit();
}
}
fn bit_index(bits: u64) -> (usize, usize) {
let a = bits / BLOCK_SIZE;
let b = bits % BLOCK_SIZE;
assert_eq!(a as usize as u64, a);
assert_eq!(b as usize as u64, b);
(a as usize, b as usize)
}
re-add spaces before static kind
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian, BigEndian};
use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque, BTreeSet};
use std::{fmt, iter, ptr, mem, io};
use rustc::hir::def_id::DefId;
use rustc::ty::{self, BareFnTy, ClosureTy, ClosureSubsts, TyCtxt};
use rustc::ty::subst::Substs;
use rustc::ty::layout::{self, TargetDataLayout};
use syntax::abi::Abi;
use error::{EvalError, EvalResult};
use value::PrimVal;
////////////////////////////////////////////////////////////////////////////////
// Allocations and pointers
////////////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(pub u64);
impl fmt::Display for AllocId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug)]
pub struct Allocation {
/// The actual bytes of the allocation.
/// Note that the bytes of a pointer represent the offset of the pointer
pub bytes: Vec<u8>,
/// Maps from byte addresses to allocations.
/// Only the first byte of a pointer is inserted into the map.
pub relocations: BTreeMap<u64, AllocId>,
/// Denotes undefined memory. Reading from undefined memory is forbidden in miri
pub undef_mask: UndefMask,
/// The alignment of the allocation to detect unaligned reads.
pub align: u64,
/// Whether the allocation may be modified.
/// Use the `mark_static` method of `Memory` to ensure that an error occurs, if the memory of this
/// allocation is modified or deallocated in the future.
pub static_kind: StaticKind,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum StaticKind {
/// may be deallocated without breaking miri's invariants
NotStatic,
/// may be modified, but never deallocated
Mutable,
/// may neither be modified nor deallocated
Immutable,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Pointer {
pub alloc_id: AllocId,
pub offset: u64,
}
impl Pointer {
pub fn new(alloc_id: AllocId, offset: u64) -> Self {
Pointer { alloc_id, offset }
}
pub fn signed_offset(self, i: i64) -> Self {
// FIXME: is it possible to over/underflow here?
if i < 0 {
// trickery to ensure that i64::min_value() works fine
// this formula only works for true negative values, it panics for zero!
let n = u64::max_value() - (i as u64) + 1;
Pointer::new(self.alloc_id, self.offset - n)
} else {
self.offset(i as u64)
}
}
pub fn offset(self, i: u64) -> Self {
Pointer::new(self.alloc_id, self.offset + i)
}
pub fn points_to_zst(&self) -> bool {
self.alloc_id == ZST_ALLOC_ID
}
pub fn to_int<'tcx>(&self) -> EvalResult<'tcx, u64> {
match self.alloc_id {
NEVER_ALLOC_ID => Ok(self.offset),
_ => Err(EvalError::ReadPointerAsBytes),
}
}
pub fn from_int(i: u64) -> Self {
Pointer::new(NEVER_ALLOC_ID, i)
}
pub fn zst_ptr() -> Self {
Pointer::new(ZST_ALLOC_ID, 0)
}
pub fn never_ptr() -> Self {
Pointer::new(NEVER_ALLOC_ID, 0)
}
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
/// Identifies a specific monomorphized function
pub struct FunctionDefinition<'tcx> {
pub def_id: DefId,
pub substs: &'tcx Substs<'tcx>,
pub abi: Abi,
pub sig: &'tcx ty::FnSig<'tcx>,
}
/// Either a concrete function, or a glue function
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum Function<'tcx> {
/// A function or method created by compiling code
Concrete(FunctionDefinition<'tcx>),
/// Glue required to call a regular function through a Fn(Mut|Once) trait object
FnDefAsTraitObject(FunctionDefinition<'tcx>),
/// Glue required to call the actual drop impl's `drop` method.
/// Drop glue takes the `self` by value, while `Drop::drop` take `&mut self`
DropGlue(FunctionDefinition<'tcx>),
/// Glue required to treat the ptr part of a fat pointer
/// as a function pointer
FnPtrAsTraitObject(&'tcx ty::FnSig<'tcx>),
/// Glue for Closures
Closure(FunctionDefinition<'tcx>),
}
impl<'tcx> Function<'tcx> {
pub fn expect_concrete(self) -> EvalResult<'tcx, FunctionDefinition<'tcx>> {
match self {
Function::Concrete(fn_def) => Ok(fn_def),
other => Err(EvalError::ExpectedConcreteFunction(other)),
}
}
pub fn expect_drop_glue(self) -> EvalResult<'tcx, FunctionDefinition<'tcx>> {
match self {
Function::DropGlue(fn_def) => Ok(fn_def),
other => Err(EvalError::ExpectedDropGlue(other)),
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Top-level interpreter memory
////////////////////////////////////////////////////////////////////////////////
pub struct Memory<'a, 'tcx> {
/// Actual memory allocations (arbitrary bytes, may contain pointers into other allocations)
alloc_map: HashMap<AllocId, Allocation>,
/// Number of virtual bytes allocated
memory_usage: u64,
/// Maximum number of virtual bytes that may be allocated
memory_size: u64,
/// Function "allocations". They exist solely so pointers have something to point to, and
/// we can figure out what they point to.
functions: HashMap<AllocId, Function<'tcx>>,
/// Inverse map of `functions` so we don't allocate a new pointer every time we need one
function_alloc_cache: HashMap<Function<'tcx>, AllocId>,
next_id: AllocId,
pub layout: &'a TargetDataLayout,
/// List of memory regions containing packed structures
/// We mark memory as "packed" or "unaligned" for a single statement, and clear the marking afterwards.
/// In the case where no packed structs are present, it's just a single emptyness check of a set
/// instead of heavily influencing all memory access code as other solutions would.
///
/// One disadvantage of this solution is the fact that you can cast a pointer to a packed struct
/// to a pointer to a normal struct and if you access a field of both in the same MIR statement,
/// the normal struct access will succeed even though it shouldn't.
/// But even with mir optimizations, that situation is hard/impossible to produce.
packed: BTreeSet<Entry>,
}
const ZST_ALLOC_ID: AllocId = AllocId(0);
const NEVER_ALLOC_ID: AllocId = AllocId(1);
impl<'a, 'tcx> Memory<'a, 'tcx> {
pub fn new(layout: &'a TargetDataLayout, max_memory: u64) -> Self {
Memory {
alloc_map: HashMap::new(),
functions: HashMap::new(),
function_alloc_cache: HashMap::new(),
next_id: AllocId(2),
layout,
memory_size: max_memory,
memory_usage: 0,
packed: BTreeSet::new(),
}
}
pub fn allocations(&self) -> ::std::collections::hash_map::Iter<AllocId, Allocation> {
self.alloc_map.iter()
}
pub fn create_closure_ptr(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: ClosureSubsts<'tcx>, fn_ty: ClosureTy<'tcx>) -> Pointer {
// FIXME: this is a hack
let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {
unsafety: fn_ty.unsafety,
abi: fn_ty.abi,
sig: fn_ty.sig,
});
self.create_fn_alloc(Function::Closure(FunctionDefinition {
def_id,
substs: substs.substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_as_trait_glue(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::FnDefAsTraitObject(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_ptr_as_trait_glue(&mut self, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::FnPtrAsTraitObject(fn_ty.sig.skip_binder()))
}
pub fn create_drop_glue(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::DropGlue(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
pub fn create_fn_ptr(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>, fn_ty: &'tcx BareFnTy<'tcx>) -> Pointer {
self.create_fn_alloc(Function::Concrete(FunctionDefinition {
def_id,
substs,
abi: fn_ty.abi,
// FIXME: why doesn't this compile?
//sig: tcx.erase_late_bound_regions(&fn_ty.sig),
sig: fn_ty.sig.skip_binder(),
}))
}
fn create_fn_alloc(&mut self, def: Function<'tcx>) -> Pointer {
if let Some(&alloc_id) = self.function_alloc_cache.get(&def) {
return Pointer::new(alloc_id, 0);
}
let id = self.next_id;
debug!("creating fn ptr: {}", id);
self.next_id.0 += 1;
self.functions.insert(id, def);
self.function_alloc_cache.insert(def, id);
Pointer::new(id, 0)
}
pub fn allocate(&mut self, size: u64, align: u64) -> EvalResult<'tcx, Pointer> {
if size == 0 {
return Ok(Pointer::zst_ptr());
}
assert!(align != 0);
if self.memory_size - self.memory_usage < size {
return Err(EvalError::OutOfMemory {
allocation_size: size,
memory_size: self.memory_size,
memory_usage: self.memory_usage,
});
}
self.memory_usage += size;
assert_eq!(size as usize as u64, size);
let alloc = Allocation {
bytes: vec![0; size as usize],
relocations: BTreeMap::new(),
undef_mask: UndefMask::new(size),
align,
static_kind: StaticKind::NotStatic,
};
let id = self.next_id;
self.next_id.0 += 1;
self.alloc_map.insert(id, alloc);
Ok(Pointer::new(id, 0))
}
// TODO(solson): Track which allocations were returned from __rust_allocate and report an error
// when reallocating/deallocating any others.
pub fn reallocate(&mut self, ptr: Pointer, new_size: u64, align: u64) -> EvalResult<'tcx, Pointer> {
// TODO(solson): Report error about non-__rust_allocate'd pointer.
if ptr.offset != 0 {
return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
}
if ptr.points_to_zst() {
return self.allocate(new_size, align);
}
if self.get(ptr.alloc_id).ok().map_or(false, |alloc| alloc.static_kind != StaticKind::NotStatic) {
return Err(EvalError::ReallocatedStaticMemory);
}
let size = self.get(ptr.alloc_id)?.bytes.len() as u64;
if new_size > size {
let amount = new_size - size;
self.memory_usage += amount;
let alloc = self.get_mut(ptr.alloc_id)?;
assert_eq!(amount as usize as u64, amount);
alloc.bytes.extend(iter::repeat(0).take(amount as usize));
alloc.undef_mask.grow(amount, false);
} else if size > new_size {
self.memory_usage -= size - new_size;
self.clear_relocations(ptr.offset(new_size), size - new_size)?;
let alloc = self.get_mut(ptr.alloc_id)?;
// `as usize` is fine here, since it is smaller than `size`, which came from a usize
alloc.bytes.truncate(new_size as usize);
alloc.bytes.shrink_to_fit();
alloc.undef_mask.truncate(new_size);
}
Ok(Pointer::new(ptr.alloc_id, 0))
}
// TODO(solson): See comment on `reallocate`.
pub fn deallocate(&mut self, ptr: Pointer) -> EvalResult<'tcx> {
if ptr.points_to_zst() {
return Ok(());
}
if ptr.offset != 0 {
// TODO(solson): Report error about non-__rust_allocate'd pointer.
return Err(EvalError::Unimplemented(format!("bad pointer offset: {}", ptr.offset)));
}
if self.get(ptr.alloc_id).ok().map_or(false, |alloc| alloc.static_kind != StaticKind::NotStatic) {
return Err(EvalError::DeallocatedStaticMemory);
}
if let Some(alloc) = self.alloc_map.remove(&ptr.alloc_id) {
self.memory_usage -= alloc.bytes.len() as u64;
} else {
debug!("deallocated a pointer twice: {}", ptr.alloc_id);
// TODO(solson): Report error about erroneous free. This is blocked on properly tracking
// already-dropped state since this if-statement is entered even in safe code without
// it.
}
debug!("deallocated : {}", ptr.alloc_id);
Ok(())
}
pub fn pointer_size(&self) -> u64 {
self.layout.pointer_size.bytes()
}
pub fn endianess(&self) -> layout::Endian {
self.layout.endian
}
pub fn check_align(&self, ptr: Pointer, align: u64, len: u64) -> EvalResult<'tcx> {
let alloc = self.get(ptr.alloc_id)?;
// check whether the memory was marked as packed
// we select all elements that have the correct alloc_id and are within
// the range given by the offset into the allocation and the length
let start = Entry {
alloc_id: ptr.alloc_id,
packed_start: 0,
packed_end: ptr.offset + len,
};
let end = Entry {
alloc_id: ptr.alloc_id,
packed_start: ptr.offset + len,
packed_end: 0,
};
for &Entry { packed_start, packed_end, .. } in self.packed.range(start..end) {
// if the region we are checking is covered by a region in `packed`
// ignore the actual alignment
if packed_start <= ptr.offset && (ptr.offset + len) <= packed_end {
return Ok(());
}
}
if alloc.align < align {
return Err(EvalError::AlignmentCheckFailed {
has: alloc.align,
required: align,
});
}
if ptr.offset % align == 0 {
Ok(())
} else {
Err(EvalError::AlignmentCheckFailed {
has: ptr.offset % align,
required: align,
})
}
}
pub(crate) fn mark_packed(&mut self, ptr: Pointer, len: u64) {
self.packed.insert(Entry {
alloc_id: ptr.alloc_id,
packed_start: ptr.offset,
packed_end: ptr.offset + len,
});
}
pub(crate) fn clear_packed(&mut self) {
self.packed.clear();
}
}
// The derived `Ord` impl sorts first by the first field, then, if the fields are the same
// by the second field, and if those are the same, too, then by the third field.
// This is exactly what we need for our purposes, since a range within an allocation
// will give us all `Entry`s that have that `AllocId`, and whose `packed_start` is <= than
// the one we're looking for, but not > the end of the range we're checking.
// At the same time the `packed_end` is irrelevant for the sorting and range searching, but used for the check.
// This kind of search breaks, if `packed_end < packed_start`, so don't do that!
#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct Entry {
alloc_id: AllocId,
packed_start: u64,
packed_end: u64,
}
/// Allocation accessors
impl<'a, 'tcx> Memory<'a, 'tcx> {
pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation> {
match self.alloc_map.get(&id) {
Some(alloc) => Ok(alloc),
None => match self.functions.get(&id) {
Some(_) => Err(EvalError::DerefFunctionPointer),
None if id == NEVER_ALLOC_ID || id == ZST_ALLOC_ID => Err(EvalError::InvalidMemoryAccess),
None => Err(EvalError::DanglingPointerDeref),
}
}
}
pub fn get_mut(&mut self, id: AllocId) -> EvalResult<'tcx, &mut Allocation> {
match self.alloc_map.get_mut(&id) {
Some(alloc) => match alloc.static_kind {
StaticKind::Mutable |
StaticKind::NotStatic => Ok(alloc),
StaticKind::Immutable => Err(EvalError::ModifiedConstantMemory),
},
None => match self.functions.get(&id) {
Some(_) => Err(EvalError::DerefFunctionPointer),
None if id == NEVER_ALLOC_ID || id == ZST_ALLOC_ID => Err(EvalError::InvalidMemoryAccess),
None => Err(EvalError::DanglingPointerDeref),
}
}
}
pub fn get_fn(&self, id: AllocId) -> EvalResult<'tcx, Function<'tcx>> {
debug!("reading fn ptr: {}", id);
match self.functions.get(&id) {
Some(&fndef) => Ok(fndef),
None => match self.alloc_map.get(&id) {
Some(_) => Err(EvalError::ExecuteMemory),
None => Err(EvalError::InvalidFunctionPointer),
}
}
}
/// For debugging, print an allocation and all allocations it points to, recursively.
pub fn dump_alloc(&self, id: AllocId) {
self.dump_allocs(vec![id]);
}
/// For debugging, print a list of allocations and all allocations they point to, recursively.
pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
use std::fmt::Write;
allocs.sort();
allocs.dedup();
let mut allocs_to_print = VecDeque::from(allocs);
let mut allocs_seen = HashSet::new();
while let Some(id) = allocs_to_print.pop_front() {
if id == ZST_ALLOC_ID || id == NEVER_ALLOC_ID { continue; }
let mut msg = format!("Alloc {:<5} ", format!("{}:", id));
let prefix_len = msg.len();
let mut relocations = vec![];
let alloc = match (self.alloc_map.get(&id), self.functions.get(&id)) {
(Some(a), None) => a,
(None, Some(&Function::Concrete(fn_def))) => {
trace!("{} {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::DropGlue(fn_def))) => {
trace!("{} drop glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::FnDefAsTraitObject(fn_def))) => {
trace!("{} fn as Fn glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, Some(&Function::FnPtrAsTraitObject(fn_def))) => {
trace!("{} fn ptr as Fn glue (signature: {:?})", msg, fn_def);
continue;
},
(None, Some(&Function::Closure(fn_def))) => {
trace!("{} closure glue for {}", msg, dump_fn_def(fn_def));
continue;
},
(None, None) => {
trace!("{} (deallocated)", msg);
continue;
},
(Some(_), Some(_)) => bug!("miri invariant broken: an allocation id exists that points to both a function and a memory location"),
};
for i in 0..(alloc.bytes.len() as u64) {
if let Some(&target_id) = alloc.relocations.get(&i) {
if allocs_seen.insert(target_id) {
allocs_to_print.push_back(target_id);
}
relocations.push((i, target_id));
}
if alloc.undef_mask.is_range_defined(i, i + 1) {
// this `as usize` is fine, since `i` came from a `usize`
write!(msg, "{:02x} ", alloc.bytes[i as usize]).unwrap();
} else {
msg.push_str("__ ");
}
}
let immutable = match alloc.static_kind {
StaticKind::Mutable => " (static mut)",
StaticKind::Immutable => " (immutable)",
StaticKind::NotStatic => "",
};
trace!("{}({} bytes){}", msg, alloc.bytes.len(), immutable);
if !relocations.is_empty() {
msg.clear();
write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
let mut pos = 0;
let relocation_width = (self.pointer_size() - 1) * 3;
for (i, target_id) in relocations {
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "{:1$}", "", ((i - pos) * 3) as usize).unwrap();
let target = match target_id {
ZST_ALLOC_ID => String::from("zst"),
NEVER_ALLOC_ID => String::from("int ptr"),
_ => format!("({})", target_id),
};
// this `as usize` is fine, since we can't print more chars than `usize::MAX`
write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
pos = i + self.pointer_size();
}
trace!("{}", msg);
}
}
}
}
fn dump_fn_def<'tcx>(fn_def: FunctionDefinition<'tcx>) -> String {
let name = ty::tls::with(|tcx| tcx.item_path_str(fn_def.def_id));
let abi = if fn_def.abi == Abi::Rust {
format!("")
} else {
format!("extern {} ", fn_def.abi)
};
format!("function pointer: {}: {}{}", name, abi, fn_def.sig)
}
/// Byte accessors
impl<'a, 'tcx> Memory<'a, 'tcx> {
fn get_bytes_unchecked(&self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
if size == 0 {
return Ok(&[]);
}
self.check_align(ptr, align, size)?;
let alloc = self.get(ptr.alloc_id)?;
let allocation_size = alloc.bytes.len() as u64;
if ptr.offset + size > allocation_size {
return Err(EvalError::PointerOutOfBounds { ptr, size, allocation_size });
}
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&alloc.bytes[offset..offset + size as usize])
}
fn get_bytes_unchecked_mut(&mut self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
if size == 0 {
return Ok(&mut []);
}
self.check_align(ptr, align, size)?;
let alloc = self.get_mut(ptr.alloc_id)?;
let allocation_size = alloc.bytes.len() as u64;
if ptr.offset + size > allocation_size {
return Err(EvalError::PointerOutOfBounds { ptr, size, allocation_size });
}
assert_eq!(ptr.offset as usize as u64, ptr.offset);
assert_eq!(size as usize as u64, size);
let offset = ptr.offset as usize;
Ok(&mut alloc.bytes[offset..offset + size as usize])
}
fn get_bytes(&self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &[u8]> {
if size == 0 {
return Ok(&[]);
}
if self.relocations(ptr, size)?.count() != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
self.check_defined(ptr, size)?;
self.get_bytes_unchecked(ptr, size, align)
}
fn get_bytes_mut(&mut self, ptr: Pointer, size: u64, align: u64) -> EvalResult<'tcx, &mut [u8]> {
if size == 0 {
return Ok(&mut []);
}
self.clear_relocations(ptr, size)?;
self.mark_definedness(ptr, size, true)?;
self.get_bytes_unchecked_mut(ptr, size, align)
}
}
/// Reading and writing
impl<'a, 'tcx> Memory<'a, 'tcx> {
/// mark an allocation as static, either mutable or not
pub fn mark_static(&mut self, alloc_id: AllocId, mutable: bool) -> EvalResult<'tcx> {
// do not use `self.get_mut(alloc_id)` here, because we might have already marked a
// sub-element or have circular pointers (e.g. `Rc`-cycles)
let relocations = match self.alloc_map.get_mut(&alloc_id) {
Some(&mut Allocation { ref mut relocations, static_kind: ref mut kind @ StaticKind::NotStatic, .. }) => {
*kind = if mutable {
StaticKind::Mutable
} else {
StaticKind::Immutable
};
// take out the relocations vector to free the borrow on self, so we can call
// mark recursively
mem::replace(relocations, Default::default())
},
None if alloc_id == NEVER_ALLOC_ID || alloc_id == ZST_ALLOC_ID => return Ok(()),
None if !self.functions.contains_key(&alloc_id) => return Err(EvalError::DanglingPointerDeref),
_ => return Ok(()),
};
// recurse into inner allocations
for &alloc in relocations.values() {
self.mark_static(alloc, mutable)?;
}
// put back the relocations
self.alloc_map.get_mut(&alloc_id).expect("checked above").relocations = relocations;
Ok(())
}
pub fn copy(&mut self, src: Pointer, dest: Pointer, size: u64, align: u64) -> EvalResult<'tcx> {
if size == 0 {
return Ok(());
}
self.check_relocation_edges(src, size)?;
let src_bytes = self.get_bytes_unchecked(src, size, align)?.as_ptr();
let dest_bytes = self.get_bytes_mut(dest, size, align)?.as_mut_ptr();
// SAFE: The above indexing would have panicked if there weren't at least `size` bytes
// behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
// `dest` could possibly overlap.
unsafe {
assert_eq!(size as usize as u64, size);
if src.alloc_id == dest.alloc_id {
ptr::copy(src_bytes, dest_bytes, size as usize);
} else {
ptr::copy_nonoverlapping(src_bytes, dest_bytes, size as usize);
}
}
self.copy_undef_mask(src, dest, size)?;
self.copy_relocations(src, dest, size)?;
Ok(())
}
pub fn read_c_str(&self, ptr: Pointer) -> EvalResult<'tcx, &[u8]> {
let alloc = self.get(ptr.alloc_id)?;
assert_eq!(ptr.offset as usize as u64, ptr.offset);
let offset = ptr.offset as usize;
match alloc.bytes[offset..].iter().position(|&c| c == 0) {
Some(size) => {
if self.relocations(ptr, (size + 1) as u64)?.count() != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
self.check_defined(ptr, (size + 1) as u64)?;
Ok(&alloc.bytes[offset..offset + size])
},
None => Err(EvalError::UnterminatedCString(ptr)),
}
}
pub fn read_bytes(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, &[u8]> {
self.get_bytes(ptr, size, 1)
}
pub fn write_bytes(&mut self, ptr: Pointer, src: &[u8]) -> EvalResult<'tcx> {
let bytes = self.get_bytes_mut(ptr, src.len() as u64, 1)?;
bytes.clone_from_slice(src);
Ok(())
}
pub fn write_repeat(&mut self, ptr: Pointer, val: u8, count: u64) -> EvalResult<'tcx> {
let bytes = self.get_bytes_mut(ptr, count, 1)?;
for b in bytes { *b = val; }
Ok(())
}
pub fn read_ptr(&self, ptr: Pointer) -> EvalResult<'tcx, Pointer> {
let size = self.pointer_size();
self.check_defined(ptr, size)?;
let endianess = self.endianess();
let bytes = self.get_bytes_unchecked(ptr, size, size)?;
let offset = read_target_uint(endianess, bytes).unwrap();
assert_eq!(offset as u64 as u128, offset);
let offset = offset as u64;
let alloc = self.get(ptr.alloc_id)?;
match alloc.relocations.get(&ptr.offset) {
Some(&alloc_id) => Ok(Pointer::new(alloc_id, offset)),
None => Ok(Pointer::from_int(offset)),
}
}
pub fn write_ptr(&mut self, dest: Pointer, ptr: Pointer) -> EvalResult<'tcx> {
self.write_usize(dest, ptr.offset as u64)?;
self.get_mut(dest.alloc_id)?.relocations.insert(dest.offset, ptr.alloc_id);
Ok(())
}
pub fn write_primval(
&mut self,
dest: Pointer,
val: PrimVal,
size: u64,
) -> EvalResult<'tcx> {
match val {
PrimVal::Ptr(ptr) => {
assert_eq!(size, self.pointer_size());
self.write_ptr(dest, ptr)
}
PrimVal::Bytes(bytes) => {
// We need to mask here, or the byteorder crate can die when given a u64 larger
// than fits in an integer of the requested size.
let mask = match size {
1 => !0u8 as u128,
2 => !0u16 as u128,
4 => !0u32 as u128,
8 => !0u64 as u128,
16 => !0,
_ => bug!("unexpected PrimVal::Bytes size"),
};
self.write_uint(dest, bytes & mask, size)
}
PrimVal::Undef => self.mark_definedness(dest, size, false),
}
}
pub fn read_bool(&self, ptr: Pointer) -> EvalResult<'tcx, bool> {
let bytes = self.get_bytes(ptr, 1, self.layout.i1_align.abi())?;
match bytes[0] {
0 => Ok(false),
1 => Ok(true),
_ => Err(EvalError::InvalidBool),
}
}
pub fn write_bool(&mut self, ptr: Pointer, b: bool) -> EvalResult<'tcx> {
let align = self.layout.i1_align.abi();
self.get_bytes_mut(ptr, 1, align)
.map(|bytes| bytes[0] = b as u8)
}
fn int_align(&self, size: u64) -> EvalResult<'tcx, u64> {
match size {
1 => Ok(self.layout.i8_align.abi()),
2 => Ok(self.layout.i16_align.abi()),
4 => Ok(self.layout.i32_align.abi()),
8 => Ok(self.layout.i64_align.abi()),
16 => Ok(self.layout.i128_align.abi()),
_ => bug!("bad integer size: {}", size),
}
}
pub fn read_int(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, i128> {
let align = self.int_align(size)?;
self.get_bytes(ptr, size, align).map(|b| read_target_int(self.endianess(), b).unwrap())
}
pub fn write_int(&mut self, ptr: Pointer, n: i128, size: u64) -> EvalResult<'tcx> {
let align = self.int_align(size)?;
let endianess = self.endianess();
let b = self.get_bytes_mut(ptr, size, align)?;
write_target_int(endianess, b, n).unwrap();
Ok(())
}
pub fn read_uint(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx, u128> {
let align = self.int_align(size)?;
self.get_bytes(ptr, size, align).map(|b| read_target_uint(self.endianess(), b).unwrap())
}
pub fn write_uint(&mut self, ptr: Pointer, n: u128, size: u64) -> EvalResult<'tcx> {
let align = self.int_align(size)?;
let endianess = self.endianess();
let b = self.get_bytes_mut(ptr, size, align)?;
write_target_uint(endianess, b, n).unwrap();
Ok(())
}
pub fn read_isize(&self, ptr: Pointer) -> EvalResult<'tcx, i64> {
self.read_int(ptr, self.pointer_size()).map(|i| i as i64)
}
pub fn write_isize(&mut self, ptr: Pointer, n: i64) -> EvalResult<'tcx> {
let size = self.pointer_size();
self.write_int(ptr, n as i128, size)
}
pub fn read_usize(&self, ptr: Pointer) -> EvalResult<'tcx, u64> {
self.read_uint(ptr, self.pointer_size()).map(|i| i as u64)
}
pub fn write_usize(&mut self, ptr: Pointer, n: u64) -> EvalResult<'tcx> {
let size = self.pointer_size();
self.write_uint(ptr, n as u128, size)
}
pub fn write_f32(&mut self, ptr: Pointer, f: f32) -> EvalResult<'tcx> {
let endianess = self.endianess();
let align = self.layout.f32_align.abi();
let b = self.get_bytes_mut(ptr, 4, align)?;
write_target_f32(endianess, b, f).unwrap();
Ok(())
}
pub fn write_f64(&mut self, ptr: Pointer, f: f64) -> EvalResult<'tcx> {
let endianess = self.endianess();
let align = self.layout.f64_align.abi();
let b = self.get_bytes_mut(ptr, 8, align)?;
write_target_f64(endianess, b, f).unwrap();
Ok(())
}
pub fn read_f32(&self, ptr: Pointer) -> EvalResult<'tcx, f32> {
self.get_bytes(ptr, 4, self.layout.f32_align.abi())
.map(|b| read_target_f32(self.endianess(), b).unwrap())
}
pub fn read_f64(&self, ptr: Pointer) -> EvalResult<'tcx, f64> {
self.get_bytes(ptr, 8, self.layout.f64_align.abi())
.map(|b| read_target_f64(self.endianess(), b).unwrap())
}
}
/// Relocations
impl<'a, 'tcx> Memory<'a, 'tcx> {
fn relocations(&self, ptr: Pointer, size: u64)
-> EvalResult<'tcx, btree_map::Range<u64, AllocId>>
{
let start = ptr.offset.saturating_sub(self.pointer_size() - 1);
let end = ptr.offset + size;
Ok(self.get(ptr.alloc_id)?.relocations.range(start..end))
}
fn clear_relocations(&mut self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
// Find all relocations overlapping the given range.
let keys: Vec<_> = self.relocations(ptr, size)?.map(|(&k, _)| k).collect();
if keys.is_empty() { return Ok(()); }
// Find the start and end of the given range and its outermost relocations.
let start = ptr.offset;
let end = start + size;
let first = *keys.first().unwrap();
let last = *keys.last().unwrap() + self.pointer_size();
let alloc = self.get_mut(ptr.alloc_id)?;
// Mark parts of the outermost relocations as undefined if they partially fall outside the
// given range.
if first < start { alloc.undef_mask.set_range(first, start, false); }
if last > end { alloc.undef_mask.set_range(end, last, false); }
// Forget all the relocations.
for k in keys { alloc.relocations.remove(&k); }
Ok(())
}
fn check_relocation_edges(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
let overlapping_start = self.relocations(ptr, 0)?.count();
let overlapping_end = self.relocations(ptr.offset(size), 0)?.count();
if overlapping_start + overlapping_end != 0 {
return Err(EvalError::ReadPointerAsBytes);
}
Ok(())
}
fn copy_relocations(&mut self, src: Pointer, dest: Pointer, size: u64) -> EvalResult<'tcx> {
let relocations: Vec<_> = self.relocations(src, size)?
.map(|(&offset, &alloc_id)| {
// Update relocation offsets for the new positions in the destination allocation.
(offset + dest.offset - src.offset, alloc_id)
})
.collect();
self.get_mut(dest.alloc_id)?.relocations.extend(relocations);
Ok(())
}
}
/// Undefined bytes
impl<'a, 'tcx> Memory<'a, 'tcx> {
// FIXME(solson): This is a very naive, slow version.
fn copy_undef_mask(&mut self, src: Pointer, dest: Pointer, size: u64) -> EvalResult<'tcx> {
// The bits have to be saved locally before writing to dest in case src and dest overlap.
assert_eq!(size as usize as u64, size);
let mut v = Vec::with_capacity(size as usize);
for i in 0..size {
let defined = self.get(src.alloc_id)?.undef_mask.get(src.offset + i);
v.push(defined);
}
for (i, defined) in v.into_iter().enumerate() {
self.get_mut(dest.alloc_id)?.undef_mask.set(dest.offset + i as u64, defined);
}
Ok(())
}
fn check_defined(&self, ptr: Pointer, size: u64) -> EvalResult<'tcx> {
let alloc = self.get(ptr.alloc_id)?;
if !alloc.undef_mask.is_range_defined(ptr.offset, ptr.offset + size) {
return Err(EvalError::ReadUndefBytes);
}
Ok(())
}
pub fn mark_definedness(
&mut self,
ptr: Pointer,
size: u64,
new_state: bool
) -> EvalResult<'tcx> {
if size == 0 {
return Ok(())
}
let mut alloc = self.get_mut(ptr.alloc_id)?;
alloc.undef_mask.set_range(ptr.offset, ptr.offset + size, new_state);
Ok(())
}
}
////////////////////////////////////////////////////////////////////////////////
// Methods to access integers in the target endianess
////////////////////////////////////////////////////////////////////////////////
fn write_target_uint(endianess: layout::Endian, mut target: &mut [u8], data: u128) -> Result<(), io::Error> {
let len = target.len();
match endianess {
layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
}
}
fn write_target_int(endianess: layout::Endian, mut target: &mut [u8], data: i128) -> Result<(), io::Error> {
let len = target.len();
match endianess {
layout::Endian::Little => target.write_int128::<LittleEndian>(data, len),
layout::Endian::Big => target.write_int128::<BigEndian>(data, len),
}
}
fn read_target_uint(endianess: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
match endianess {
layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
}
}
fn read_target_int(endianess: layout::Endian, mut source: &[u8]) -> Result<i128, io::Error> {
match endianess {
layout::Endian::Little => source.read_int128::<LittleEndian>(source.len()),
layout::Endian::Big => source.read_int128::<BigEndian>(source.len()),
}
}
////////////////////////////////////////////////////////////////////////////////
// Methods to access floats in the target endianess
////////////////////////////////////////////////////////////////////////////////
fn write_target_f32(endianess: layout::Endian, mut target: &mut [u8], data: f32) -> Result<(), io::Error> {
match endianess {
layout::Endian::Little => target.write_f32::<LittleEndian>(data),
layout::Endian::Big => target.write_f32::<BigEndian>(data),
}
}
fn write_target_f64(endianess: layout::Endian, mut target: &mut [u8], data: f64) -> Result<(), io::Error> {
match endianess {
layout::Endian::Little => target.write_f64::<LittleEndian>(data),
layout::Endian::Big => target.write_f64::<BigEndian>(data),
}
}
fn read_target_f32(endianess: layout::Endian, mut source: &[u8]) -> Result<f32, io::Error> {
match endianess {
layout::Endian::Little => source.read_f32::<LittleEndian>(),
layout::Endian::Big => source.read_f32::<BigEndian>(),
}
}
fn read_target_f64(endianess: layout::Endian, mut source: &[u8]) -> Result<f64, io::Error> {
match endianess {
layout::Endian::Little => source.read_f64::<LittleEndian>(),
layout::Endian::Big => source.read_f64::<BigEndian>(),
}
}
////////////////////////////////////////////////////////////////////////////////
// Undefined byte tracking
////////////////////////////////////////////////////////////////////////////////
type Block = u64;
const BLOCK_SIZE: u64 = 64;
#[derive(Clone, Debug)]
pub struct UndefMask {
blocks: Vec<Block>,
len: u64,
}
impl UndefMask {
fn new(size: u64) -> Self {
let mut m = UndefMask {
blocks: vec![],
len: 0,
};
m.grow(size, false);
m
}
/// Check whether the range `start..end` (end-exclusive) is entirely defined.
pub fn is_range_defined(&self, start: u64, end: u64) -> bool {
if end > self.len { return false; }
for i in start..end {
if !self.get(i) { return false; }
}
true
}
fn set_range(&mut self, start: u64, end: u64, new_state: bool) {
let len = self.len;
if end > len { self.grow(end - len, new_state); }
self.set_range_inbounds(start, end, new_state);
}
fn set_range_inbounds(&mut self, start: u64, end: u64, new_state: bool) {
for i in start..end { self.set(i, new_state); }
}
fn get(&self, i: u64) -> bool {
let (block, bit) = bit_index(i);
(self.blocks[block] & 1 << bit) != 0
}
fn set(&mut self, i: u64, new_state: bool) {
let (block, bit) = bit_index(i);
if new_state {
self.blocks[block] |= 1 << bit;
} else {
self.blocks[block] &= !(1 << bit);
}
}
fn grow(&mut self, amount: u64, new_state: bool) {
let unused_trailing_bits = self.blocks.len() as u64 * BLOCK_SIZE - self.len;
if amount > unused_trailing_bits {
let additional_blocks = amount / BLOCK_SIZE + 1;
assert_eq!(additional_blocks as usize as u64, additional_blocks);
self.blocks.extend(iter::repeat(0).take(additional_blocks as usize));
}
let start = self.len;
self.len += amount;
self.set_range_inbounds(start, start + amount, new_state);
}
fn truncate(&mut self, length: u64) {
self.len = length;
let truncate = self.len / BLOCK_SIZE + 1;
assert_eq!(truncate as usize as u64, truncate);
self.blocks.truncate(truncate as usize);
self.blocks.shrink_to_fit();
}
}
fn bit_index(bits: u64) -> (usize, usize) {
let a = bits / BLOCK_SIZE;
let b = bits % BLOCK_SIZE;
assert_eq!(a as usize as u64, a);
assert_eq!(b as usize as u64, b);
(a as usize, b as usize)
}
|
// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! `IMPL` Object wrapper implementation and `Object` binding.
use glib_sys;
use gobject_sys;
use std::cmp;
use std::fmt;
use std::hash;
use std::marker::PhantomData;
use std::mem;
use std::ops;
use std::ptr;
use quark::Quark;
use translate::*;
use types::StaticType;
use value::ToValue;
use BoolError;
use Closure;
use SignalHandlerId;
use Type;
use Value;
use get_thread_id;
#[doc(hidden)]
pub use gobject_sys::GObject;
#[doc(hidden)]
pub use gobject_sys::GObjectClass;
/// Implemented by types representing `glib::Object` and subclasses of it.
pub unsafe trait ObjectType:
UnsafeFrom<ObjectRef>
+ Into<ObjectRef>
+ StaticType
+ fmt::Debug
+ Clone
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ hash::Hash
+ for<'a> ToGlibPtr<'a, *mut <Self as ObjectType>::GlibType>
+ 'static
{
/// type of the FFI Instance structure.
type GlibType: 'static;
/// type of the FFI Class structure.
type GlibClassType: 'static;
/// type of the Rust Class structure.
type RustClassType: 'static;
fn as_object_ref(&self) -> &ObjectRef;
fn as_ptr(&self) -> *mut Self::GlibType;
}
/// Unsafe variant of the `From` trait.
pub trait UnsafeFrom<T> {
/// # Safety
///
/// It is the responsibility of the caller to ensure *all* invariants of
/// the `T` hold before this is called, and that subsequent to conversion
/// to assume nothing other than the invariants of the output. Implementors
/// of this must ensure that the invariants of the output type hold.
unsafe fn unsafe_from(t: T) -> Self;
}
/// Declares the "is a" relationship.
///
/// `Self` is said to implement `T`.
///
/// For instance, since originally `GtkWidget` is a subclass of `GObject` and
/// implements the `GtkBuildable` interface, `gtk::Widget` implements
/// `IsA<glib::Object>` and `IsA<gtk::Buildable>`.
///
///
/// The trait can only be implemented if the appropriate `ToGlibPtr`
/// implementations exist.
pub unsafe trait IsA<T: ObjectType>: ObjectType + AsRef<T> + 'static {}
/// Trait for mapping a class struct type to its corresponding instance type.
pub unsafe trait IsClassFor: Sized + 'static {
/// Corresponding Rust instance type for this class.
type Instance: ObjectType;
/// Get the type id for this class.
fn get_type(&self) -> Type {
unsafe {
let klass = self as *const _ as *const gobject_sys::GTypeClass;
from_glib((*klass).g_type)
}
}
/// Casts this class to a reference to a parent type's class.
fn upcast_ref<U: IsClassFor>(&self) -> &U
where
Self::Instance: IsA<U::Instance>,
U::Instance: ObjectType,
{
unsafe {
let klass = self as *const _ as *const U;
&*klass
}
}
/// Casts this class to a mutable reference to a parent type's class.
fn upcast_ref_mut<U: IsClassFor>(&mut self) -> &mut U
where
Self::Instance: IsA<U::Instance>,
U::Instance: ObjectType,
{
unsafe {
let klass = self as *mut _ as *mut U;
&mut *klass
}
}
/// Casts this class to a reference to a child type's class or
/// fails if this class is not implementing the child class.
fn downcast_ref<U: IsClassFor>(&self) -> Option<&U>
where
U::Instance: IsA<Self::Instance>,
Self::Instance: ObjectType,
{
if !self.get_type().is_a(&U::Instance::static_type()) {
return None;
}
unsafe {
let klass = self as *const _ as *const U;
Some(&*klass)
}
}
/// Casts this class to a mutable reference to a child type's class or
/// fails if this class is not implementing the child class.
fn downcast_ref_mut<U: IsClassFor>(&mut self) -> Option<&mut U>
where
U::Instance: IsA<Self::Instance>,
Self::Instance: ObjectType,
{
if !self.get_type().is_a(&U::Instance::static_type()) {
return None;
}
unsafe {
let klass = self as *mut _ as *mut U;
Some(&mut *klass)
}
}
/// Gets the class struct corresponding to `type_`.
///
/// This will return `None` if `type_` is not a subclass of `Self`.
fn from_type(type_: Type) -> Option<ClassRef<Self>> {
if !type_.is_a(&Self::Instance::static_type()) {
return None;
}
unsafe {
let ptr = gobject_sys::g_type_class_ref(type_.to_glib());
if ptr.is_null() {
None
} else {
Some(ClassRef(ptr::NonNull::new_unchecked(ptr as *mut Self)))
}
}
}
}
#[derive(Debug)]
pub struct ClassRef<T: IsClassFor>(ptr::NonNull<T>);
impl<T: IsClassFor> ops::Deref for ClassRef<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
impl<T: IsClassFor> Drop for ClassRef<T> {
fn drop(&mut self) {
unsafe {
gobject_sys::g_type_class_unref(self.0.as_ptr() as *mut _);
}
}
}
unsafe impl<T: IsClassFor> Send for ClassRef<T> {}
unsafe impl<T: IsClassFor> Sync for ClassRef<T> {}
/// Upcasting and downcasting support.
///
/// Provides conversions up and down the class hierarchy tree.
pub trait Cast: ObjectType {
/// Upcasts an object to a superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// ```
#[inline]
fn upcast<T: ObjectType>(self) -> T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast() }
}
/// Upcasts an object to a reference of its superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast_ref::<gtk::Widget>();
/// ```
#[inline]
fn upcast_ref<T: ObjectType>(&self) -> &T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast_ref() }
}
/// Tries to downcast to a subclass or interface implementor `T`.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn downcast<T: ObjectType>(self) -> Result<T, Self>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Ok(unsafe { self.unsafe_cast() })
} else {
Err(self)
}
}
/// Tries to downcast to a reference of its subclass or interface implementor `T`.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Some(unsafe { self.unsafe_cast_ref() })
} else {
None
}
}
/// Tries to cast to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking as to be performed at runtime.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast::<gtk::Widget>();
/// assert!(widget.is_ok());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn dynamic_cast<T: ObjectType>(self) -> Result<T, Self> {
if !self.is::<T>() {
Err(self)
} else {
Ok(unsafe { self.unsafe_cast() })
}
}
/// Tries to cast to reference to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking as to be performed at runtime.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast_ref::<gtk::Widget>();
/// assert!(widget.is_some());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn dynamic_cast_ref<T: ObjectType>(&self) -> Option<&T> {
if !self.is::<T>() {
None
} else {
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
Some(unsafe { self.unsafe_cast_ref() })
}
}
/// Casts to `T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
unsafe fn unsafe_cast<T: ObjectType>(self) -> T {
debug_assert!(self.is::<T>());
T::unsafe_from(self.into())
}
/// Casts to `&T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
unsafe fn unsafe_cast_ref<T: ObjectType>(&self) -> &T {
debug_assert!(self.is::<T>());
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
&*(self as *const Self as *const T)
}
}
impl<T: ObjectType> Cast for T {}
/// Marker trait for the statically known possibility of downcasting from `Self` to `T`.
pub trait CanDowncast<T> {}
impl<Super: IsA<Super>, Sub: IsA<Super>> CanDowncast<Sub> for Super {}
// Manual implementation of glib_shared_wrapper! because of special cases
pub struct ObjectRef {
inner: ptr::NonNull<GObject>,
}
impl Clone for ObjectRef {
fn clone(&self) -> Self {
unsafe {
ObjectRef {
inner: ptr::NonNull::new_unchecked(gobject_sys::g_object_ref(self.inner.as_ptr())),
}
}
}
}
impl Drop for ObjectRef {
fn drop(&mut self) {
unsafe {
gobject_sys::g_object_unref(self.inner.as_ptr());
}
}
}
impl fmt::Debug for ObjectRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let type_ = unsafe {
let klass = (*self.inner.as_ptr()).g_type_instance.g_class as *const ObjectClass;
(&*klass).get_type()
};
f.debug_struct("ObjectRef")
.field("inner", &self.inner)
.field("type", &type_)
.finish()
}
}
impl PartialOrd for ObjectRef {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.inner.partial_cmp(&other.inner)
}
}
impl Ord for ObjectRef {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.inner.cmp(&other.inner)
}
}
impl PartialEq for ObjectRef {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl Eq for ObjectRef {}
impl hash::Hash for ObjectRef {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.inner.hash(state)
}
}
#[doc(hidden)]
impl GlibPtrDefault for ObjectRef {
type GlibType = *mut GObject;
}
#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *mut GObject> for ObjectRef {
type Storage = &'a ObjectRef;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *mut GObject, Self> {
Stash(self.inner.as_ptr(), self)
}
#[inline]
fn to_glib_full(&self) -> *mut GObject {
unsafe { gobject_sys::g_object_ref(self.inner.as_ptr()) }
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *mut *mut GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut GObject, ObjectRef>>,
Option<Vec<*mut GObject>>,
);
fn to_glib_none_from_slice(t: &'a [ObjectRef]) -> (*mut *mut GObject, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(ptr::null_mut() as *mut GObject);
(v_ptr.as_ptr() as *mut *mut GObject, (v, Some(v_ptr)))
}
fn to_glib_container_from_slice(t: &'a [ObjectRef]) -> (*mut *mut GObject, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let v_ptr = unsafe {
let v_ptr = glib_sys::g_malloc0(mem::size_of::<*mut GObject>() * (t.len() + 1))
as *mut *mut GObject;
for (i, s) in v.iter().enumerate() {
ptr::write(v_ptr.add(i), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[ObjectRef]) -> *mut *mut GObject {
unsafe {
let v_ptr = glib_sys::g_malloc0(std::mem::size_of::<*mut GObject>() * (t.len() + 1))
as *mut *mut GObject;
for (i, s) in t.iter().enumerate() {
ptr::write(v_ptr.add(i), s.to_glib_full());
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *const *mut GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut GObject, ObjectRef>>,
Option<Vec<*mut GObject>>,
);
fn to_glib_none_from_slice(t: &'a [ObjectRef]) -> (*const *mut GObject, Self::Storage) {
let (ptr, stash) =
ToGlibContainerFromSlice::<'a, *mut *mut GObject>::to_glib_none_from_slice(t);
(ptr as *const *mut GObject, stash)
}
fn to_glib_container_from_slice(_: &'a [ObjectRef]) -> (*const *mut GObject, Self::Storage) {
// Can't have consumer free a *const pointer
unimplemented!()
}
fn to_glib_full_from_slice(_: &[ObjectRef]) -> *const *mut GObject {
// Can't have consumer free a *const pointer
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *mut GObject) -> Self {
assert!(!ptr.is_null());
// Attention: This takes ownership of floating references!
ObjectRef {
inner: ptr::NonNull::new_unchecked(gobject_sys::g_object_ref_sink(ptr)),
}
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*const GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *const GObject) -> Self {
// Attention: This takes ownership of floating references!
from_glib_none(ptr as *mut GObject)
}
}
#[doc(hidden)]
impl FromGlibPtrFull<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_full(ptr: *mut GObject) -> Self {
assert!(!ptr.is_null());
ObjectRef {
inner: ptr::NonNull::new_unchecked(ptr),
}
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *mut GObject) -> Borrowed<Self> {
assert!(!ptr.is_null());
Borrowed::new(ObjectRef {
inner: ptr::NonNull::new_unchecked(ptr),
})
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*const GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *const GObject) -> Borrowed<Self> {
from_glib_borrow(ptr as *mut GObject)
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut GObject, *mut *mut GObject> for ObjectRef {
unsafe fn from_glib_none_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
// Attention: This takes ownership of floating references!
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_none(ptr::read(ptr.add(i))));
}
res
}
unsafe fn from_glib_container_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
// Attention: This takes ownership of floating references!
let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
glib_sys::g_free(ptr as *mut _);
res
}
unsafe fn from_glib_full_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_full(ptr::read(ptr.add(i))));
}
glib_sys::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut GObject, *mut *mut GObject> for ObjectRef {
unsafe fn from_glib_none_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_container_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_full_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut GObject, *const *mut GObject> for ObjectRef {
unsafe fn from_glib_none_num_as_vec(ptr: *const *mut GObject, num: usize) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
unsafe fn from_glib_container_num_as_vec(_: *const *mut GObject, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_num_as_vec(_: *const *mut GObject, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut GObject, *const *mut GObject> for ObjectRef {
unsafe fn from_glib_none_as_vec(ptr: *const *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
unsafe fn from_glib_container_as_vec(_: *const *mut GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_as_vec(_: *const *mut GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! glib_weak_impl {
($name:ident) => {
#[doc(hidden)]
impl $crate::clone::Downgrade for $name {
type Weak = $crate::object::WeakRef<Self>;
fn downgrade(&self) -> Self::Weak {
<Self as $crate::object::ObjectExt>::downgrade(&self)
}
}
};
}
/// ObjectType implementations for Object types. See `glib_wrapper!`.
#[macro_export]
macro_rules! glib_object_wrapper {
(@generic_impl [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:path, @get_type $get_type_expr:expr) => {
$(#[$attr])*
// Always derive Hash/Ord (and below impl Debug, PartialEq, Eq, PartialOrd) for object
// types. Due to inheritance and up/downcasting we must implement these by pointer or
// otherwise they would potentially give differeny results for the same object depending on
// the type we currently know for it
#[derive(Clone, Hash, Ord)]
pub struct $name($crate::object::ObjectRef, ::std::marker::PhantomData<$ffi_name>);
#[doc(hidden)]
impl Into<$crate::object::ObjectRef> for $name {
fn into(self) -> $crate::object::ObjectRef {
self.0
}
}
#[doc(hidden)]
impl $crate::object::UnsafeFrom<$crate::object::ObjectRef> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn unsafe_from(t: $crate::object::ObjectRef) -> Self {
$name(t, ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::GlibPtrDefault for $name {
type GlibType = *mut $ffi_name;
}
#[doc(hidden)]
unsafe impl $crate::object::ObjectType for $name {
type GlibType = $ffi_name;
type GlibClassType = $ffi_class_name;
type RustClassType = $rust_class_name;
fn as_object_ref(&self) -> &$crate::object::ObjectRef {
&self.0
}
fn as_ptr(&self) -> *mut Self::GlibType {
self.0.to_glib_none().0 as *mut _
}
}
#[doc(hidden)]
impl AsRef<$crate::object::ObjectRef> for $name {
fn as_ref(&self) -> &$crate::object::ObjectRef {
&self.0
}
}
#[doc(hidden)]
impl AsRef<$name> for $name {
fn as_ref(&self) -> &$name {
self
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$name> for $name { }
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *const $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *const $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&self.0);
$crate::translate::Stash(stash.0 as *const _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *const $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&self.0) as *const _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *mut $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *mut $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&self.0);
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&self.0) as *mut _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *mut *mut $ffi_name> for $name {
type Storage = (Vec<$crate::translate::Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(::std::ptr::null_mut() as *mut $ffi_name);
(v_ptr.as_ptr() as *mut *mut $ffi_name, (v, Some(v_ptr)))
}
fn to_glib_container_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let v_ptr = unsafe {
let v_ptr = $crate::glib_sys::g_malloc0(::std::mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in v.iter().enumerate() {
::std::ptr::write(v_ptr.add(i), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[$name]) -> *mut *mut $ffi_name {
unsafe {
let v_ptr = $crate::glib_sys::g_malloc0(::std::mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in t.iter().enumerate() {
::std::ptr::write(v_ptr.add(i), $crate::translate::ToGlibPtr::to_glib_full(s));
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *const *mut $ffi_name> for $name {
type Storage = (Vec<$crate::translate::Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
let (ptr, stash) = $crate::translate::ToGlibContainerFromSlice::<'a, *mut *mut $ffi_name>::to_glib_none_from_slice(t);
(ptr as *const *mut $ffi_name, stash)
}
fn to_glib_container_from_slice(_: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
// Can't have consumer free a *const pointer
unimplemented!()
}
fn to_glib_full_from_slice(_: &[$name]) -> *const *mut $ffi_name {
// Can't have consumer free a *const pointer
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*const $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none(ptr: *const $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrFull<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_full(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrBorrow<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_borrow(ptr: *mut $ffi_name) -> $crate::translate::Borrowed<Self> {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$crate::translate::Borrowed::new(
$name(
$crate::translate::from_glib_borrow::<_, $crate::object::ObjectRef>(ptr as *mut _).into_inner(),
::std::marker::PhantomData,
)
)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrBorrow<*const $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_borrow(ptr: *const $ffi_name) -> $crate::translate::Borrowed<Self> {
$crate::translate::from_glib_borrow::<_, $name>(ptr as *mut $ffi_name)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_none(::std::ptr::read(ptr.add(i))));
}
res
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
let res = $crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
$crate::glib_sys::g_free(ptr as *mut _);
res
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_full(::std::ptr::read(ptr.add(i))));
}
$crate::glib_sys::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_num_as_vec(ptr: *const *mut $ffi_name, num: usize) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_as_vec(ptr: *const *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
impl $crate::types::StaticType for $name {
fn static_type() -> $crate::types::Type {
#[allow(unused_unsafe)]
unsafe { $crate::translate::from_glib($get_type_expr) }
}
}
impl<T: $crate::object::ObjectType> ::std::cmp::PartialEq<T> for $name {
#[inline]
fn eq(&self, other: &T) -> bool {
$crate::translate::ToGlibPtr::to_glib_none(&self.0).0 == $crate::translate::ToGlibPtr::to_glib_none($crate::object::ObjectType::as_object_ref(other)).0
}
}
impl ::std::cmp::Eq for $name { }
impl<T: $crate::object::ObjectType> ::std::cmp::PartialOrd<T> for $name {
#[inline]
fn partial_cmp(&self, other: &T) -> Option<::std::cmp::Ordering> {
$crate::translate::ToGlibPtr::to_glib_none(&self.0).0.partial_cmp(&$crate::translate::ToGlibPtr::to_glib_none($crate::object::ObjectType::as_object_ref(other)).0)
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(stringify!($name))
.field("inner", &self.0)
.finish()
}
}
#[doc(hidden)]
impl<'a> $crate::value::FromValueOptional<'a> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_value_optional(value: &$crate::Value) -> Option<Self> {
let obj = $crate::gobject_sys::g_value_get_object($crate::translate::ToGlibPtr::to_glib_none(value).0);
// Attention: Don't use from_glib_none() here because we don't want to steal any
// floating references that might be owned by someone else.
if !obj.is_null() {
$crate::gobject_sys::g_object_ref(obj);
}
// And take the reference to the object from above to pass it to the caller
Option::<$name>::from_glib_full(obj as *mut $ffi_name).map(|o| $crate::object::Cast::unsafe_cast(o))
}
}
#[doc(hidden)]
impl $crate::value::SetValue for $name {
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn set_value(value: &mut $crate::Value, this: &Self) {
$crate::gobject_sys::g_value_set_object($crate::translate::ToGlibPtrMut::to_glib_none_mut(value).0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(this).0 as *mut $crate::gobject_sys::GObject)
}
}
#[doc(hidden)]
impl $crate::value::SetValueOptional for $name {
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn set_value_optional(value: &mut $crate::Value, this: Option<&Self>) {
$crate::gobject_sys::g_value_set_object($crate::translate::ToGlibPtrMut::to_glib_none_mut(value).0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(&this).0 as *mut $crate::gobject_sys::GObject)
}
}
$crate::glib_weak_impl!($name);
};
(@munch_impls $name:ident, ) => { };
(@munch_impls $name:ident, $super_name:path) => {
unsafe impl $crate::object::IsA<$super_name> for $name { }
#[doc(hidden)]
impl AsRef<$super_name> for $name {
fn as_ref(&self) -> &$super_name {
$crate::object::Cast::upcast_ref(self)
}
}
};
(@munch_impls $name:ident, $super_name:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
// If there is no parent class, i.e. only glib::Object
(@munch_first_impl $name:ident, $rust_class_name:ident, ) => {
glib_object_wrapper!(@munch_impls $name, );
impl ::std::ops::Deref for $rust_class_name {
type Target = <$crate::object::Object as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
};
// If there is only one parent class
(@munch_first_impl $name:ident, $rust_class_name:ident, $super_name:path) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
impl ::std::ops::Deref for $rust_class_name {
type Target = <$super_name as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
};
// If there is more than one parent class
(@munch_first_impl $name:ident, $rust_class_name:ident, $super_name:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
impl ::std::ops::Deref for $rust_class_name {
type Target = <$super_name as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
(@class_impl $name:ident, $ffi_class_name:path, $rust_class_name:ident) => {
#[repr(C)]
#[derive(Debug)]
pub struct $rust_class_name($ffi_class_name);
unsafe impl $crate::object::IsClassFor for $rust_class_name {
type Instance = $name;
}
unsafe impl Send for $rust_class_name { }
unsafe impl Sync for $rust_class_name { }
};
// This case is only for glib::Object itself below. All other cases have glib::Object in its
// parent class list
(@object [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:ident, @get_type $get_type_expr:expr) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $ffi_class_name, $rust_class_name,
@get_type $get_type_expr);
glib_object_wrapper!(@class_impl $name, $ffi_class_name, $rust_class_name);
};
(@object [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:ident,
@get_type $get_type_expr:expr, @extends [$($extends:tt)*], @implements [$($implements:tt)*]) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $ffi_class_name, $rust_class_name,
@get_type $get_type_expr);
glib_object_wrapper!(@munch_first_impl $name, $rust_class_name, $($extends)*);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
glib_object_wrapper!(@class_impl $name, $ffi_class_name, $rust_class_name);
#[doc(hidden)]
impl AsRef<$crate::object::Object> for $name {
fn as_ref(&self) -> &$crate::object::Object {
$crate::object::Cast::upcast_ref(self)
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$crate::object::Object> for $name { }
};
(@interface [$($attr:meta)*] $name:ident, $ffi_name:path, @get_type $get_type_expr:expr, @requires [$($requires:tt)*]) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $crate::wrapper::Void, $crate::wrapper::Void,
@get_type $get_type_expr);
glib_object_wrapper!(@munch_impls $name, $($requires)*);
#[doc(hidden)]
impl AsRef<$crate::object::Object> for $name {
fn as_ref(&self) -> &$crate::object::Object {
$crate::object::Cast::upcast_ref(self)
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$crate::object::Object> for $name { }
};
}
glib_object_wrapper!(@object
[doc = "The base class in the object hierarchy."]
Object, GObject, GObjectClass, ObjectClass, @get_type gobject_sys::g_object_get_type()
);
impl Object {
pub fn new(type_: Type, properties: &[(&str, &dyn ToValue)]) -> Result<Object, BoolError> {
use std::ffi::CString;
if !type_.is_a(&Object::static_type()) {
return Err(glib_bool_error!("Can't instantiate non-GObject objects"));
}
let params = properties
.iter()
.map(|&(name, value)| (CString::new(name).unwrap(), value.to_value()))
.collect::<Vec<_>>();
let params_c = params
.iter()
.map(|&(ref name, ref value)| gobject_sys::GParameter {
name: name.as_ptr(),
value: unsafe { *value.to_glib_none().0 },
})
.collect::<Vec<_>>();
unsafe {
let ptr = gobject_sys::g_object_newv(
type_.to_glib(),
params_c.len() as u32,
mut_override(params_c.as_ptr()),
);
if ptr.is_null() {
Err(glib_bool_error!("Can't instantiate object"))
} else if type_.is_a(&InitiallyUnowned::static_type()) {
// Attention: This takes ownership of the floating reference
Ok(from_glib_none(ptr))
} else {
Ok(from_glib_full(ptr))
}
}
}
}
pub trait ObjectExt: ObjectType {
/// Returns `true` if the object is an instance of (can be cast to) `T`.
fn is<T: StaticType>(&self) -> bool;
fn get_type(&self) -> Type;
fn get_object_class(&self) -> &ObjectClass;
fn set_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
value: &dyn ToValue,
) -> Result<(), BoolError>;
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError>;
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> bool;
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type>;
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec>;
fn list_properties(&self) -> Vec<::ParamSpec>;
/// # Safety
///
/// This function doesn't store type information
unsafe fn set_qdata<QD: 'static>(&self, key: Quark, value: QD);
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn get_qdata<QD: 'static>(&self, key: Quark) -> Option<&QD>;
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn steal_qdata<QD: 'static>(&self, key: Quark) -> Option<QD>;
/// # Safety
///
/// This function doesn't store type information
unsafe fn set_data<QD: 'static>(&self, key: &str, value: QD);
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn get_data<QD: 'static>(&self, key: &str) -> Option<&QD>;
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn steal_data<QD: 'static>(&self, key: &str) -> Option<QD>;
fn block_signal(&self, handler_id: &SignalHandlerId);
fn unblock_signal(&self, handler_id: &SignalHandlerId);
fn stop_signal_emission(&self, signal_name: &str);
fn connect<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static;
fn connect_local<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + 'static;
#[allow(clippy::missing_safety_doc)]
unsafe fn connect_unsafe<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value>;
fn emit<'a, N: Into<&'a str>>(
&self,
signal_name: N,
args: &[&dyn ToValue],
) -> Result<Option<Value>, BoolError>;
fn disconnect(&self, handler_id: SignalHandlerId);
fn connect_notify<F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId;
#[allow(clippy::missing_safety_doc)]
unsafe fn connect_notify_unsafe<F: Fn(&Self, &::ParamSpec)>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId;
fn notify<'a, N: Into<&'a str>>(&self, property_name: N);
fn notify_by_pspec(&self, pspec: &::ParamSpec);
fn downgrade(&self) -> WeakRef<Self>;
fn bind_property<'a, O: ObjectType, N: Into<&'a str>, M: Into<&'a str>>(
&'a self,
source_property: N,
target: &'a O,
target_property: M,
) -> BindingBuilder<'a>;
fn ref_count(&self) -> u32;
}
impl<T: ObjectType> ObjectExt for T {
fn is<U: StaticType>(&self) -> bool {
self.get_type().is_a(&U::static_type())
}
fn get_type(&self) -> Type {
self.get_object_class().get_type()
}
fn get_object_class(&self) -> &ObjectClass {
unsafe {
let obj: *mut gobject_sys::GObject = self.as_object_ref().to_glib_none().0;
let klass = (*obj).g_type_instance.g_class as *const ObjectClass;
&*klass
}
}
fn set_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
value: &dyn ToValue,
) -> Result<(), BoolError> {
let property_name = property_name.into();
let mut property_value = value.to_value();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(glib_bool_error!("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::WRITABLE)
|| pspec.get_flags().contains(::ParamFlags::CONSTRUCT_ONLY)
{
return Err(glib_bool_error!("property is not writable"));
}
unsafe {
// While GLib actually allows all types that can somehow be transformed
// into the property type, we're more restrictive here to be consistent
// with Rust's type rules. We only allow the exact same type, or if the
// value type is a subtype of the property type
let valid_type: bool = from_glib(gobject_sys::g_type_check_value_holds(
mut_override(property_value.to_glib_none().0),
pspec.get_value_type().to_glib(),
));
// If it's not directly a valid type but an object type, we check if the
// actual type of the contained object is compatible and if so create
// a properly type Value. This can happen if the type field in the
// Value is set to a more generic type than the contained value
if !valid_type && property_value.type_().is_a(&Object::static_type()) {
match property_value.get::<Object>() {
Ok(Some(obj)) => {
if obj.get_type().is_a(&pspec.get_value_type()) {
property_value.0.g_type = pspec.get_value_type().to_glib();
} else {
return Err(glib_bool_error!(format!(
concat!(
"property can't be set from the given object type ",
"(expected: {:?}, got: {:?})",
),
pspec.get_value_type(),
obj.get_type(),
)));
}
}
Ok(None) => {
// If the value is None then the type is compatible too
property_value.0.g_type = pspec.get_value_type().to_glib();
}
Err(_) => unreachable!("property_value type conformity already checked"),
}
} else if !valid_type {
return Err(glib_bool_error!(format!(
"property can't be set from the given type (expected: {:?}, got: {:?})",
pspec.get_value_type(),
property_value.type_(),
)));
}
let changed: bool = from_glib(gobject_sys::g_param_value_validate(
pspec.to_glib_none().0,
property_value.to_glib_none_mut().0,
));
let change_allowed = pspec.get_flags().contains(::ParamFlags::LAX_VALIDATION);
if changed && !change_allowed {
return Err(glib_bool_error!(
"property can't be set from given value, it is invalid or out of range"
));
}
gobject_sys::g_object_set_property(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
property_value.to_glib_none().0,
);
}
Ok(())
}
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError> {
let property_name = property_name.into();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(glib_bool_error!("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::READABLE) {
return Err(glib_bool_error!("property is not readable"));
}
unsafe {
let mut value = Value::from_type(pspec.get_value_type());
gobject_sys::g_object_get_property(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
value.to_glib_none_mut().0,
);
// This can't really happen unless something goes wrong inside GObject
if value.type_() == ::Type::Invalid {
Err(glib_bool_error!("Failed to get property value"))
} else {
Ok(value)
}
}
}
unsafe fn set_qdata<QD: 'static>(&self, key: Quark, value: QD) {
unsafe extern "C" fn drop_value<QD>(ptr: glib_sys::gpointer) {
debug_assert!(!ptr.is_null());
let value: Box<QD> = Box::from_raw(ptr as *mut QD);
drop(value)
}
let ptr = Box::into_raw(Box::new(value)) as glib_sys::gpointer;
gobject_sys::g_object_set_qdata_full(
self.as_object_ref().to_glib_none().0,
key.to_glib(),
ptr,
Some(drop_value::<QD>),
);
}
unsafe fn get_qdata<QD: 'static>(&self, key: Quark) -> Option<&QD> {
let ptr = gobject_sys::g_object_get_qdata(
self.as_object_ref().to_glib_none().0,
key.to_glib(),
);
if ptr.is_null() {
None
} else {
Some(&*(ptr as *const QD))
}
}
unsafe fn steal_qdata<QD: 'static>(&self, key: Quark) -> Option<QD> {
let ptr = gobject_sys::g_object_steal_qdata(
self.as_object_ref().to_glib_none().0,
key.to_glib(),
);
if ptr.is_null() {
None
} else {
let value: Box<QD> = Box::from_raw(ptr as *mut QD);
Some(*value)
}
}
unsafe fn set_data<QD: 'static>(&self, key: &str, value: QD) {
self.set_qdata::<QD>(Quark::from_string(key), value)
}
unsafe fn get_data<QD: 'static>(&self, key: &str) -> Option<&QD> {
self.get_qdata::<QD>(Quark::from_string(key))
}
unsafe fn steal_data<QD: 'static>(&self, key: &str) -> Option<QD> {
self.steal_qdata::<QD>(Quark::from_string(key))
}
fn block_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_block(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn unblock_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_unblock(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn stop_signal_emission(&self, signal_name: &str) {
unsafe {
gobject_sys::g_signal_stop_emission_by_name(
self.as_object_ref().to_glib_none().0,
signal_name.to_glib_none().0,
);
}
}
fn disconnect(&self, handler_id: SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_disconnect(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn connect_notify<F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId {
unsafe { self.connect_notify_unsafe(name, f) }
}
unsafe fn connect_notify_unsafe<F: Fn(&Self, &::ParamSpec)>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_trampoline<P, F: Fn(&P, &::ParamSpec)>(
this: *mut gobject_sys::GObject,
param_spec: *mut gobject_sys::GParamSpec,
f: glib_sys::gpointer,
) where
P: ObjectType,
{
let f: &F = &*(f as *const F);
f(
Object::from_glib_borrow(this).unsafe_cast_ref(),
&from_glib_borrow(param_spec),
)
}
let signal_name = if let Some(name) = name {
format!("notify::{}\0", name)
} else {
"notify\0".into()
};
let f: Box<F> = Box::new(f);
::signal::connect_raw(
self.as_object_ref().to_glib_none().0,
signal_name.as_ptr() as *const _,
Some(mem::transmute::<_, unsafe extern "C" fn()>(
notify_trampoline::<Self, F> as *const (),
)),
Box::into_raw(f),
)
}
fn notify<'a, N: Into<&'a str>>(&self, property_name: N) {
let property_name = property_name.into();
unsafe {
gobject_sys::g_object_notify(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
);
}
}
fn notify_by_pspec(&self, pspec: &::ParamSpec) {
unsafe {
gobject_sys::g_object_notify_by_pspec(
self.as_object_ref().to_glib_none().0,
pspec.to_glib_none().0,
);
}
}
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> bool {
self.get_object_class().has_property(property_name, type_)
}
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type> {
self.get_object_class().get_property_type(property_name)
}
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec> {
self.get_object_class().find_property(property_name)
}
fn list_properties(&self) -> Vec<::ParamSpec> {
self.get_object_class().list_properties()
}
fn connect<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static,
{
unsafe { self.connect_unsafe(signal_name, after, callback) }
}
fn connect_local<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + 'static,
{
let callback = crate::ThreadGuard::new(callback);
unsafe {
self.connect_unsafe(signal_name, after, move |values| {
(callback.get_ref())(values)
})
}
}
unsafe fn connect_unsafe<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value>,
{
let signal_name: &str = signal_name.into();
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_sys::g_signal_parse_name(
signal_name.to_glib_none().0,
type_.to_glib(),
&mut signal_id,
&mut signal_detail,
true.to_glib(),
));
if !found {
return Err(glib_bool_error!("Signal not found"));
}
let mut details = mem::MaybeUninit::zeroed();
gobject_sys::g_signal_query(signal_id, details.as_mut_ptr());
let details = details.assume_init();
if details.signal_id != signal_id {
return Err(glib_bool_error!("Signal not found"));
}
// This is actually G_SIGNAL_TYPE_STATIC_SCOPE
let return_type: Type =
from_glib(details.return_type & (!gobject_sys::G_TYPE_FLAG_RESERVED_ID_BIT));
let closure = Closure::new_unsafe(move |values| {
let ret = callback(values);
if return_type == Type::Unit {
if let Some(ret) = ret {
panic!(
"Signal required no return value but got value of type {}",
ret.type_().name()
);
}
None
} else {
match ret {
Some(mut ret) => {
let valid_type: bool = from_glib(gobject_sys::g_type_check_value_holds(
mut_override(ret.to_glib_none().0),
return_type.to_glib(),
));
// If it's not directly a valid type but an object type, we check if the
// actual typed of the contained object is compatible and if so create
// a properly typed Value. This can happen if the type field in the
// Value is set to a more generic type than the contained value
if !valid_type && ret.type_().is_a(&Object::static_type()) {
match ret.get::<Object>() {
Ok(Some(obj)) => {
if obj.get_type().is_a(&return_type) {
ret.0.g_type = return_type.to_glib();
} else {
panic!("Signal required return value of type {} but got {} (actual {})",
return_type.name(), ret.type_().name(), obj.get_type().name());
}
}
Ok(None) => {
// If the value is None then the type is compatible too
ret.0.g_type = return_type.to_glib();
}
Err(_) => unreachable!("ret type conformity already checked"),
}
} else if !valid_type {
panic!(
"Signal required return value of type {} but got {}",
return_type.name(),
ret.type_().name()
);
}
Some(ret)
}
None => {
panic!(
"Signal required return value of type {} but got None",
return_type.name()
);
}
}
}
});
let handler = gobject_sys::g_signal_connect_closure_by_id(
self.as_object_ref().to_glib_none().0,
signal_id,
signal_detail,
closure.to_glib_none().0,
after.to_glib(),
);
if handler == 0 {
Err(glib_bool_error!("Failed to connect to signal"))
} else {
Ok(from_glib(handler))
}
}
fn emit<'a, N: Into<&'a str>>(
&self,
signal_name: N,
args: &[&dyn ToValue],
) -> Result<Option<Value>, BoolError> {
let signal_name: &str = signal_name.into();
unsafe {
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_sys::g_signal_parse_name(
signal_name.to_glib_none().0,
type_.to_glib(),
&mut signal_id,
&mut signal_detail,
true.to_glib(),
));
if !found {
return Err(glib_bool_error!("Signal not found"));
}
let mut details = mem::MaybeUninit::zeroed();
gobject_sys::g_signal_query(signal_id, details.as_mut_ptr());
let details = details.assume_init();
if details.signal_id != signal_id {
return Err(glib_bool_error!("Signal not found"));
}
if details.n_params != args.len() as u32 {
return Err(glib_bool_error!("Incompatible number of arguments"));
}
for (i, item) in args.iter().enumerate() {
let arg_type =
*(details.param_types.add(i)) & (!gobject_sys::G_TYPE_FLAG_RESERVED_ID_BIT);
if arg_type != item.to_value_type().to_glib() {
return Err(glib_bool_error!("Incompatible argument types"));
}
}
let mut v_args: Vec<Value>;
let mut s_args: [Value; 10] = mem::zeroed();
let self_v = {
let mut v = Value::uninitialized();
gobject_sys::g_value_init(v.to_glib_none_mut().0, self.get_type().to_glib());
gobject_sys::g_value_set_object(
v.to_glib_none_mut().0,
self.as_object_ref().to_glib_none().0,
);
v
};
let args = if args.len() < 10 {
s_args[0] = self_v;
for (i, arg) in args.iter().enumerate() {
s_args[i + 1] = arg.to_value();
}
&s_args[0..=args.len()]
} else {
v_args = Vec::with_capacity(args.len() + 1);
v_args.push(self_v);
for arg in args {
v_args.push(arg.to_value());
}
v_args.as_slice()
};
let mut return_value = Value::uninitialized();
if details.return_type != gobject_sys::G_TYPE_NONE {
gobject_sys::g_value_init(return_value.to_glib_none_mut().0, details.return_type);
}
gobject_sys::g_signal_emitv(
mut_override(args.as_ptr()) as *mut gobject_sys::GValue,
signal_id,
signal_detail,
return_value.to_glib_none_mut().0,
);
if return_value.type_() != Type::Unit && return_value.type_() != Type::Invalid {
Ok(Some(return_value))
} else {
Ok(None)
}
}
}
fn downgrade(&self) -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::zeroed()), PhantomData);
gobject_sys::g_weak_ref_init(
mut_override(&*w.0),
self.as_object_ref().to_glib_none().0,
);
w
}
}
fn bind_property<'a, O: ObjectType, N: Into<&'a str>, M: Into<&'a str>>(
&'a self,
source_property: N,
target: &'a O,
target_property: M,
) -> BindingBuilder<'a> {
let source_property = source_property.into();
let target_property = target_property.into();
BindingBuilder::new(self, source_property, target, target_property)
}
fn ref_count(&self) -> u32 {
let stash = self.as_object_ref().to_glib_none();
let ptr: *mut gobject_sys::GObject = stash.0;
unsafe { glib_sys::g_atomic_int_get(&(*ptr).ref_count as *const u32 as *const i32) as u32 }
}
}
impl ObjectClass {
pub fn has_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
type_: Option<Type>,
) -> bool {
let property_name = property_name.into();
let ptype = self.get_property_type(property_name);
match (ptype, type_) {
(None, _) => false,
(Some(_), None) => true,
(Some(ptype), Some(type_)) => ptype == type_,
}
}
pub fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type> {
self.find_property(property_name)
.map(|pspec| pspec.get_value_type())
}
pub fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec> {
let property_name = property_name.into();
unsafe {
let klass = self as *const _ as *const gobject_sys::GObjectClass;
from_glib_none(gobject_sys::g_object_class_find_property(
klass as *mut _,
property_name.to_glib_none().0,
))
}
}
pub fn list_properties(&self) -> Vec<::ParamSpec> {
unsafe {
let klass = self as *const _ as *const gobject_sys::GObjectClass;
let mut n_properties = 0;
let props =
gobject_sys::g_object_class_list_properties(klass as *mut _, &mut n_properties);
FromGlibContainer::from_glib_none_num(props, n_properties as usize)
}
}
}
glib_wrapper! {
pub struct InitiallyUnowned(Object<gobject_sys::GInitiallyUnowned, gobject_sys::GInitiallyUnownedClass, InitiallyUnownedClass>);
match fn {
get_type => || gobject_sys::g_initially_unowned_get_type(),
}
}
#[derive(Debug)]
pub struct WeakRef<T: ObjectType>(Box<gobject_sys::GWeakRef>, PhantomData<*const T>);
impl<T: ObjectType> WeakRef<T> {
pub fn new() -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::zeroed()), PhantomData);
gobject_sys::g_weak_ref_init(mut_override(&*w.0), ptr::null_mut());
w
}
}
pub fn upgrade(&self) -> Option<T> {
unsafe {
let ptr = gobject_sys::g_weak_ref_get(mut_override(&*self.0));
if ptr.is_null() {
None
} else {
let obj: Object = from_glib_full(ptr);
Some(T::unsafe_from(obj.into()))
}
}
}
}
impl<T: ObjectType> Drop for WeakRef<T> {
fn drop(&mut self) {
unsafe {
gobject_sys::g_weak_ref_clear(mut_override(&*self.0));
}
}
}
impl<T: ObjectType> Clone for WeakRef<T> {
fn clone(&self) -> Self {
unsafe {
let c = WeakRef(Box::new(mem::zeroed()), PhantomData);
let o = gobject_sys::g_weak_ref_get(mut_override(&*self.0));
gobject_sys::g_weak_ref_init(mut_override(&*c.0), o);
if !o.is_null() {
gobject_sys::g_object_unref(o);
}
c
}
}
}
impl<T: ObjectType> Default for WeakRef<T> {
fn default() -> Self {
Self::new()
}
}
unsafe impl<T: ObjectType + Sync + Sync> Sync for WeakRef<T> {}
unsafe impl<T: ObjectType + Send + Sync> Send for WeakRef<T> {}
/// A weak reference to the object it was created for that can be sent to
/// different threads even for object types that don't implement `Send`.
///
/// Trying to upgrade the weak reference from another thread than the one
/// where it was created on will panic but dropping or cloning can be done
/// safely from any thread.
#[derive(Debug)]
pub struct SendWeakRef<T: ObjectType>(WeakRef<T>, Option<usize>);
impl<T: ObjectType> SendWeakRef<T> {
pub fn new() -> SendWeakRef<T> {
SendWeakRef(WeakRef::new(), None)
}
pub fn into_weak_ref(self) -> WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
self.0
}
}
impl<T: ObjectType> ops::Deref for SendWeakRef<T> {
type Target = WeakRef<T>;
fn deref(&self) -> &WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
&self.0
}
}
// Deriving this gives the wrong trait bounds
impl<T: ObjectType> Clone for SendWeakRef<T> {
fn clone(&self) -> Self {
SendWeakRef(self.0.clone(), self.1)
}
}
impl<T: ObjectType> Default for SendWeakRef<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: ObjectType> From<WeakRef<T>> for SendWeakRef<T> {
fn from(v: WeakRef<T>) -> SendWeakRef<T> {
SendWeakRef(v, Some(get_thread_id()))
}
}
unsafe impl<T: ObjectType> Sync for SendWeakRef<T> {}
unsafe impl<T: ObjectType> Send for SendWeakRef<T> {}
#[derive(Debug)]
pub struct BindingBuilder<'a> {
source: &'a ObjectRef,
source_property: &'a str,
target: &'a ObjectRef,
target_property: &'a str,
flags: ::BindingFlags,
transform_to: Option<::Closure>,
transform_from: Option<::Closure>,
}
impl<'a> BindingBuilder<'a> {
fn new<S: ObjectType, T: ObjectType>(
source: &'a S,
source_property: &'a str,
target: &'a T,
target_property: &'a str,
) -> Self {
Self {
source: source.as_object_ref(),
source_property,
target: target.as_object_ref(),
target_property,
flags: ::BindingFlags::DEFAULT,
transform_to: None,
transform_from: None,
}
}
fn transform_closure<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
func: F,
) -> ::Closure {
::Closure::new(move |values| {
assert_eq!(values.len(), 3);
let binding = values[0].get::<::Binding>().unwrap_or_else(|_| {
panic!(
"Type mismatch with the first argument in the closure: expected: `Binding`, got: {:?}",
values[0].type_(),
)
})
.unwrap_or_else(|| {
panic!("Found `None` for the first argument in the closure, expected `Some`")
});
let from = unsafe {
let ptr = gobject_sys::g_value_get_boxed(mut_override(
&values[1] as *const Value as *const gobject_sys::GValue,
));
assert!(!ptr.is_null());
&*(ptr as *const gobject_sys::GValue as *const Value)
};
match func(&binding, &from) {
None => Some(false.to_value()),
Some(value) => {
unsafe {
gobject_sys::g_value_set_boxed(
mut_override(&values[2] as *const Value as *const gobject_sys::GValue),
&value as *const Value as *const _,
);
}
Some(true.to_value())
}
}
})
}
pub fn transform_from<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
self,
func: F,
) -> Self {
Self {
transform_from: Some(Self::transform_closure(func)),
..self
}
}
pub fn transform_to<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
self,
func: F,
) -> Self {
Self {
transform_to: Some(Self::transform_closure(func)),
..self
}
}
pub fn flags(self, flags: ::BindingFlags) -> Self {
Self { flags, ..self }
}
pub fn build(self) -> Option<::Binding> {
unsafe {
from_glib_none(gobject_sys::g_object_bind_property_with_closures(
self.source.to_glib_none().0,
self.source_property.to_glib_none().0,
self.target.to_glib_none().0,
self.target_property.to_glib_none().0,
self.flags.to_glib(),
self.transform_to.to_glib_none().0,
self.transform_from.to_glib_none().0,
))
}
}
}
reformat code
// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! `IMPL` Object wrapper implementation and `Object` binding.
use glib_sys;
use gobject_sys;
use quark::Quark;
use std::cmp;
use std::fmt;
use std::hash;
use std::marker::PhantomData;
use std::mem;
use std::ops;
use std::ptr;
use translate::*;
use types::StaticType;
use value::ToValue;
use BoolError;
use Closure;
use SignalHandlerId;
use Type;
use Value;
use get_thread_id;
#[doc(hidden)]
pub use gobject_sys::GObject;
#[doc(hidden)]
pub use gobject_sys::GObjectClass;
/// Implemented by types representing `glib::Object` and subclasses of it.
pub unsafe trait ObjectType:
UnsafeFrom<ObjectRef>
+ Into<ObjectRef>
+ StaticType
+ fmt::Debug
+ Clone
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ hash::Hash
+ for<'a> ToGlibPtr<'a, *mut <Self as ObjectType>::GlibType>
+ 'static
{
/// type of the FFI Instance structure.
type GlibType: 'static;
/// type of the FFI Class structure.
type GlibClassType: 'static;
/// type of the Rust Class structure.
type RustClassType: 'static;
fn as_object_ref(&self) -> &ObjectRef;
fn as_ptr(&self) -> *mut Self::GlibType;
}
/// Unsafe variant of the `From` trait.
pub trait UnsafeFrom<T> {
/// # Safety
///
/// It is the responsibility of the caller to ensure *all* invariants of
/// the `T` hold before this is called, and that subsequent to conversion
/// to assume nothing other than the invariants of the output. Implementors
/// of this must ensure that the invariants of the output type hold.
unsafe fn unsafe_from(t: T) -> Self;
}
/// Declares the "is a" relationship.
///
/// `Self` is said to implement `T`.
///
/// For instance, since originally `GtkWidget` is a subclass of `GObject` and
/// implements the `GtkBuildable` interface, `gtk::Widget` implements
/// `IsA<glib::Object>` and `IsA<gtk::Buildable>`.
///
///
/// The trait can only be implemented if the appropriate `ToGlibPtr`
/// implementations exist.
pub unsafe trait IsA<T: ObjectType>: ObjectType + AsRef<T> + 'static {}
/// Trait for mapping a class struct type to its corresponding instance type.
pub unsafe trait IsClassFor: Sized + 'static {
/// Corresponding Rust instance type for this class.
type Instance: ObjectType;
/// Get the type id for this class.
fn get_type(&self) -> Type {
unsafe {
let klass = self as *const _ as *const gobject_sys::GTypeClass;
from_glib((*klass).g_type)
}
}
/// Casts this class to a reference to a parent type's class.
fn upcast_ref<U: IsClassFor>(&self) -> &U
where
Self::Instance: IsA<U::Instance>,
U::Instance: ObjectType,
{
unsafe {
let klass = self as *const _ as *const U;
&*klass
}
}
/// Casts this class to a mutable reference to a parent type's class.
fn upcast_ref_mut<U: IsClassFor>(&mut self) -> &mut U
where
Self::Instance: IsA<U::Instance>,
U::Instance: ObjectType,
{
unsafe {
let klass = self as *mut _ as *mut U;
&mut *klass
}
}
/// Casts this class to a reference to a child type's class or
/// fails if this class is not implementing the child class.
fn downcast_ref<U: IsClassFor>(&self) -> Option<&U>
where
U::Instance: IsA<Self::Instance>,
Self::Instance: ObjectType,
{
if !self.get_type().is_a(&U::Instance::static_type()) {
return None;
}
unsafe {
let klass = self as *const _ as *const U;
Some(&*klass)
}
}
/// Casts this class to a mutable reference to a child type's class or
/// fails if this class is not implementing the child class.
fn downcast_ref_mut<U: IsClassFor>(&mut self) -> Option<&mut U>
where
U::Instance: IsA<Self::Instance>,
Self::Instance: ObjectType,
{
if !self.get_type().is_a(&U::Instance::static_type()) {
return None;
}
unsafe {
let klass = self as *mut _ as *mut U;
Some(&mut *klass)
}
}
/// Gets the class struct corresponding to `type_`.
///
/// This will return `None` if `type_` is not a subclass of `Self`.
fn from_type(type_: Type) -> Option<ClassRef<Self>> {
if !type_.is_a(&Self::Instance::static_type()) {
return None;
}
unsafe {
let ptr = gobject_sys::g_type_class_ref(type_.to_glib());
if ptr.is_null() {
None
} else {
Some(ClassRef(ptr::NonNull::new_unchecked(ptr as *mut Self)))
}
}
}
}
#[derive(Debug)]
pub struct ClassRef<T: IsClassFor>(ptr::NonNull<T>);
impl<T: IsClassFor> ops::Deref for ClassRef<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
impl<T: IsClassFor> Drop for ClassRef<T> {
fn drop(&mut self) {
unsafe {
gobject_sys::g_type_class_unref(self.0.as_ptr() as *mut _);
}
}
}
unsafe impl<T: IsClassFor> Send for ClassRef<T> {}
unsafe impl<T: IsClassFor> Sync for ClassRef<T> {}
/// Upcasting and downcasting support.
///
/// Provides conversions up and down the class hierarchy tree.
pub trait Cast: ObjectType {
/// Upcasts an object to a superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// ```
#[inline]
fn upcast<T: ObjectType>(self) -> T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast() }
}
/// Upcasts an object to a reference of its superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast_ref::<gtk::Widget>();
/// ```
#[inline]
fn upcast_ref<T: ObjectType>(&self) -> &T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast_ref() }
}
/// Tries to downcast to a subclass or interface implementor `T`.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn downcast<T: ObjectType>(self) -> Result<T, Self>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Ok(unsafe { self.unsafe_cast() })
} else {
Err(self)
}
}
/// Tries to downcast to a reference of its subclass or interface implementor `T`.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Some(unsafe { self.unsafe_cast_ref() })
} else {
None
}
}
/// Tries to cast to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking as to be performed at runtime.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast::<gtk::Widget>();
/// assert!(widget.is_ok());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn dynamic_cast<T: ObjectType>(self) -> Result<T, Self> {
if !self.is::<T>() {
Err(self)
} else {
Ok(unsafe { self.unsafe_cast() })
}
}
/// Tries to cast to reference to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking as to be performed at runtime.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast_ref::<gtk::Widget>();
/// assert!(widget.is_some());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn dynamic_cast_ref<T: ObjectType>(&self) -> Option<&T> {
if !self.is::<T>() {
None
} else {
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
Some(unsafe { self.unsafe_cast_ref() })
}
}
/// Casts to `T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
unsafe fn unsafe_cast<T: ObjectType>(self) -> T {
debug_assert!(self.is::<T>());
T::unsafe_from(self.into())
}
/// Casts to `&T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
unsafe fn unsafe_cast_ref<T: ObjectType>(&self) -> &T {
debug_assert!(self.is::<T>());
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
&*(self as *const Self as *const T)
}
}
impl<T: ObjectType> Cast for T {}
/// Marker trait for the statically known possibility of downcasting from `Self` to `T`.
pub trait CanDowncast<T> {}
impl<Super: IsA<Super>, Sub: IsA<Super>> CanDowncast<Sub> for Super {}
// Manual implementation of glib_shared_wrapper! because of special cases
pub struct ObjectRef {
inner: ptr::NonNull<GObject>,
}
impl Clone for ObjectRef {
fn clone(&self) -> Self {
unsafe {
ObjectRef {
inner: ptr::NonNull::new_unchecked(gobject_sys::g_object_ref(self.inner.as_ptr())),
}
}
}
}
impl Drop for ObjectRef {
fn drop(&mut self) {
unsafe {
gobject_sys::g_object_unref(self.inner.as_ptr());
}
}
}
impl fmt::Debug for ObjectRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let type_ = unsafe {
let klass = (*self.inner.as_ptr()).g_type_instance.g_class as *const ObjectClass;
(&*klass).get_type()
};
f.debug_struct("ObjectRef")
.field("inner", &self.inner)
.field("type", &type_)
.finish()
}
}
impl PartialOrd for ObjectRef {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.inner.partial_cmp(&other.inner)
}
}
impl Ord for ObjectRef {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.inner.cmp(&other.inner)
}
}
impl PartialEq for ObjectRef {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl Eq for ObjectRef {}
impl hash::Hash for ObjectRef {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.inner.hash(state)
}
}
#[doc(hidden)]
impl GlibPtrDefault for ObjectRef {
type GlibType = *mut GObject;
}
#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *mut GObject> for ObjectRef {
type Storage = &'a ObjectRef;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *mut GObject, Self> {
Stash(self.inner.as_ptr(), self)
}
#[inline]
fn to_glib_full(&self) -> *mut GObject {
unsafe { gobject_sys::g_object_ref(self.inner.as_ptr()) }
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *mut *mut GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut GObject, ObjectRef>>,
Option<Vec<*mut GObject>>,
);
fn to_glib_none_from_slice(t: &'a [ObjectRef]) -> (*mut *mut GObject, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(ptr::null_mut() as *mut GObject);
(v_ptr.as_ptr() as *mut *mut GObject, (v, Some(v_ptr)))
}
fn to_glib_container_from_slice(t: &'a [ObjectRef]) -> (*mut *mut GObject, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let v_ptr = unsafe {
let v_ptr = glib_sys::g_malloc0(mem::size_of::<*mut GObject>() * (t.len() + 1))
as *mut *mut GObject;
for (i, s) in v.iter().enumerate() {
ptr::write(v_ptr.add(i), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[ObjectRef]) -> *mut *mut GObject {
unsafe {
let v_ptr = glib_sys::g_malloc0(std::mem::size_of::<*mut GObject>() * (t.len() + 1))
as *mut *mut GObject;
for (i, s) in t.iter().enumerate() {
ptr::write(v_ptr.add(i), s.to_glib_full());
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *const *mut GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut GObject, ObjectRef>>,
Option<Vec<*mut GObject>>,
);
fn to_glib_none_from_slice(t: &'a [ObjectRef]) -> (*const *mut GObject, Self::Storage) {
let (ptr, stash) =
ToGlibContainerFromSlice::<'a, *mut *mut GObject>::to_glib_none_from_slice(t);
(ptr as *const *mut GObject, stash)
}
fn to_glib_container_from_slice(_: &'a [ObjectRef]) -> (*const *mut GObject, Self::Storage) {
// Can't have consumer free a *const pointer
unimplemented!()
}
fn to_glib_full_from_slice(_: &[ObjectRef]) -> *const *mut GObject {
// Can't have consumer free a *const pointer
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *mut GObject) -> Self {
assert!(!ptr.is_null());
// Attention: This takes ownership of floating references!
ObjectRef {
inner: ptr::NonNull::new_unchecked(gobject_sys::g_object_ref_sink(ptr)),
}
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*const GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *const GObject) -> Self {
// Attention: This takes ownership of floating references!
from_glib_none(ptr as *mut GObject)
}
}
#[doc(hidden)]
impl FromGlibPtrFull<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_full(ptr: *mut GObject) -> Self {
assert!(!ptr.is_null());
ObjectRef {
inner: ptr::NonNull::new_unchecked(ptr),
}
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*mut GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *mut GObject) -> Borrowed<Self> {
assert!(!ptr.is_null());
Borrowed::new(ObjectRef {
inner: ptr::NonNull::new_unchecked(ptr),
})
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*const GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *const GObject) -> Borrowed<Self> {
from_glib_borrow(ptr as *mut GObject)
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut GObject, *mut *mut GObject> for ObjectRef {
unsafe fn from_glib_none_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
// Attention: This takes ownership of floating references!
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_none(ptr::read(ptr.add(i))));
}
res
}
unsafe fn from_glib_container_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
// Attention: This takes ownership of floating references!
let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
glib_sys::g_free(ptr as *mut _);
res
}
unsafe fn from_glib_full_num_as_vec(ptr: *mut *mut GObject, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_full(ptr::read(ptr.add(i))));
}
glib_sys::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut GObject, *mut *mut GObject> for ObjectRef {
unsafe fn from_glib_none_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_container_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_full_as_vec(ptr: *mut *mut GObject) -> Vec<Self> {
FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut GObject, *const *mut GObject> for ObjectRef {
unsafe fn from_glib_none_num_as_vec(ptr: *const *mut GObject, num: usize) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
unsafe fn from_glib_container_num_as_vec(_: *const *mut GObject, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_num_as_vec(_: *const *mut GObject, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut GObject, *const *mut GObject> for ObjectRef {
unsafe fn from_glib_none_as_vec(ptr: *const *mut GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
unsafe fn from_glib_container_as_vec(_: *const *mut GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_as_vec(_: *const *mut GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! glib_weak_impl {
($name:ident) => {
#[doc(hidden)]
impl $crate::clone::Downgrade for $name {
type Weak = $crate::object::WeakRef<Self>;
fn downgrade(&self) -> Self::Weak {
<Self as $crate::object::ObjectExt>::downgrade(&self)
}
}
};
}
/// ObjectType implementations for Object types. See `glib_wrapper!`.
#[macro_export]
macro_rules! glib_object_wrapper {
(@generic_impl [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:path, @get_type $get_type_expr:expr) => {
$(#[$attr])*
// Always derive Hash/Ord (and below impl Debug, PartialEq, Eq, PartialOrd) for object
// types. Due to inheritance and up/downcasting we must implement these by pointer or
// otherwise they would potentially give differeny results for the same object depending on
// the type we currently know for it
#[derive(Clone, Hash, Ord)]
pub struct $name($crate::object::ObjectRef, ::std::marker::PhantomData<$ffi_name>);
#[doc(hidden)]
impl Into<$crate::object::ObjectRef> for $name {
fn into(self) -> $crate::object::ObjectRef {
self.0
}
}
#[doc(hidden)]
impl $crate::object::UnsafeFrom<$crate::object::ObjectRef> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn unsafe_from(t: $crate::object::ObjectRef) -> Self {
$name(t, ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::GlibPtrDefault for $name {
type GlibType = *mut $ffi_name;
}
#[doc(hidden)]
unsafe impl $crate::object::ObjectType for $name {
type GlibType = $ffi_name;
type GlibClassType = $ffi_class_name;
type RustClassType = $rust_class_name;
fn as_object_ref(&self) -> &$crate::object::ObjectRef {
&self.0
}
fn as_ptr(&self) -> *mut Self::GlibType {
self.0.to_glib_none().0 as *mut _
}
}
#[doc(hidden)]
impl AsRef<$crate::object::ObjectRef> for $name {
fn as_ref(&self) -> &$crate::object::ObjectRef {
&self.0
}
}
#[doc(hidden)]
impl AsRef<$name> for $name {
fn as_ref(&self) -> &$name {
self
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$name> for $name { }
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *const $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *const $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&self.0);
$crate::translate::Stash(stash.0 as *const _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *const $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&self.0) as *const _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *mut $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *mut $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&self.0);
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&self.0) as *mut _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *mut *mut $ffi_name> for $name {
type Storage = (Vec<$crate::translate::Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(::std::ptr::null_mut() as *mut $ffi_name);
(v_ptr.as_ptr() as *mut *mut $ffi_name, (v, Some(v_ptr)))
}
fn to_glib_container_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let v_ptr = unsafe {
let v_ptr = $crate::glib_sys::g_malloc0(::std::mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in v.iter().enumerate() {
::std::ptr::write(v_ptr.add(i), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[$name]) -> *mut *mut $ffi_name {
unsafe {
let v_ptr = $crate::glib_sys::g_malloc0(::std::mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in t.iter().enumerate() {
::std::ptr::write(v_ptr.add(i), $crate::translate::ToGlibPtr::to_glib_full(s));
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *const *mut $ffi_name> for $name {
type Storage = (Vec<$crate::translate::Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
let (ptr, stash) = $crate::translate::ToGlibContainerFromSlice::<'a, *mut *mut $ffi_name>::to_glib_none_from_slice(t);
(ptr as *const *mut $ffi_name, stash)
}
fn to_glib_container_from_slice(_: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
// Can't have consumer free a *const pointer
unimplemented!()
}
fn to_glib_full_from_slice(_: &[$name]) -> *const *mut $ffi_name {
// Can't have consumer free a *const pointer
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*const $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none(ptr: *const $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrFull<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_full(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrBorrow<*mut $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_borrow(ptr: *mut $ffi_name) -> $crate::translate::Borrowed<Self> {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$crate::translate::Borrowed::new(
$name(
$crate::translate::from_glib_borrow::<_, $crate::object::ObjectRef>(ptr as *mut _).into_inner(),
::std::marker::PhantomData,
)
)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrBorrow<*const $ffi_name> for $name {
#[inline]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_borrow(ptr: *const $ffi_name) -> $crate::translate::Borrowed<Self> {
$crate::translate::from_glib_borrow::<_, $name>(ptr as *mut $ffi_name)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_none(::std::ptr::read(ptr.add(i))));
}
res
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
let res = $crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
$crate::glib_sys::g_free(ptr as *mut _);
res
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_full(::std::ptr::read(ptr.add(i))));
}
$crate::glib_sys::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_num_as_vec(ptr: *const *mut $ffi_name, num: usize) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_none_as_vec(ptr: *const *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_container_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_glib_full_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
impl $crate::types::StaticType for $name {
fn static_type() -> $crate::types::Type {
#[allow(unused_unsafe)]
unsafe { $crate::translate::from_glib($get_type_expr) }
}
}
impl<T: $crate::object::ObjectType> ::std::cmp::PartialEq<T> for $name {
#[inline]
fn eq(&self, other: &T) -> bool {
$crate::translate::ToGlibPtr::to_glib_none(&self.0).0 == $crate::translate::ToGlibPtr::to_glib_none($crate::object::ObjectType::as_object_ref(other)).0
}
}
impl ::std::cmp::Eq for $name { }
impl<T: $crate::object::ObjectType> ::std::cmp::PartialOrd<T> for $name {
#[inline]
fn partial_cmp(&self, other: &T) -> Option<::std::cmp::Ordering> {
$crate::translate::ToGlibPtr::to_glib_none(&self.0).0.partial_cmp(&$crate::translate::ToGlibPtr::to_glib_none($crate::object::ObjectType::as_object_ref(other)).0)
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(stringify!($name))
.field("inner", &self.0)
.finish()
}
}
#[doc(hidden)]
impl<'a> $crate::value::FromValueOptional<'a> for $name {
#[allow(clippy::missing_safety_doc)]
unsafe fn from_value_optional(value: &$crate::Value) -> Option<Self> {
let obj = $crate::gobject_sys::g_value_get_object($crate::translate::ToGlibPtr::to_glib_none(value).0);
// Attention: Don't use from_glib_none() here because we don't want to steal any
// floating references that might be owned by someone else.
if !obj.is_null() {
$crate::gobject_sys::g_object_ref(obj);
}
// And take the reference to the object from above to pass it to the caller
Option::<$name>::from_glib_full(obj as *mut $ffi_name).map(|o| $crate::object::Cast::unsafe_cast(o))
}
}
#[doc(hidden)]
impl $crate::value::SetValue for $name {
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn set_value(value: &mut $crate::Value, this: &Self) {
$crate::gobject_sys::g_value_set_object($crate::translate::ToGlibPtrMut::to_glib_none_mut(value).0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(this).0 as *mut $crate::gobject_sys::GObject)
}
}
#[doc(hidden)]
impl $crate::value::SetValueOptional for $name {
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::missing_safety_doc)]
unsafe fn set_value_optional(value: &mut $crate::Value, this: Option<&Self>) {
$crate::gobject_sys::g_value_set_object($crate::translate::ToGlibPtrMut::to_glib_none_mut(value).0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(&this).0 as *mut $crate::gobject_sys::GObject)
}
}
$crate::glib_weak_impl!($name);
};
(@munch_impls $name:ident, ) => { };
(@munch_impls $name:ident, $super_name:path) => {
unsafe impl $crate::object::IsA<$super_name> for $name { }
#[doc(hidden)]
impl AsRef<$super_name> for $name {
fn as_ref(&self) -> &$super_name {
$crate::object::Cast::upcast_ref(self)
}
}
};
(@munch_impls $name:ident, $super_name:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
// If there is no parent class, i.e. only glib::Object
(@munch_first_impl $name:ident, $rust_class_name:ident, ) => {
glib_object_wrapper!(@munch_impls $name, );
impl ::std::ops::Deref for $rust_class_name {
type Target = <$crate::object::Object as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
};
// If there is only one parent class
(@munch_first_impl $name:ident, $rust_class_name:ident, $super_name:path) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
impl ::std::ops::Deref for $rust_class_name {
type Target = <$super_name as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
};
// If there is more than one parent class
(@munch_first_impl $name:ident, $rust_class_name:ident, $super_name:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
impl ::std::ops::Deref for $rust_class_name {
type Target = <$super_name as $crate::object::ObjectType>::RustClassType;
fn deref(&self) -> &Self::Target {
$crate::object::IsClassFor::upcast_ref(self)
}
}
impl ::std::ops::DerefMut for $rust_class_name {
fn deref_mut(&mut self) -> &mut Self::Target {
$crate::object::IsClassFor::upcast_ref_mut(self)
}
}
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
(@class_impl $name:ident, $ffi_class_name:path, $rust_class_name:ident) => {
#[repr(C)]
#[derive(Debug)]
pub struct $rust_class_name($ffi_class_name);
unsafe impl $crate::object::IsClassFor for $rust_class_name {
type Instance = $name;
}
unsafe impl Send for $rust_class_name { }
unsafe impl Sync for $rust_class_name { }
};
// This case is only for glib::Object itself below. All other cases have glib::Object in its
// parent class list
(@object [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:ident, @get_type $get_type_expr:expr) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $ffi_class_name, $rust_class_name,
@get_type $get_type_expr);
glib_object_wrapper!(@class_impl $name, $ffi_class_name, $rust_class_name);
};
(@object [$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, $rust_class_name:ident,
@get_type $get_type_expr:expr, @extends [$($extends:tt)*], @implements [$($implements:tt)*]) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $ffi_class_name, $rust_class_name,
@get_type $get_type_expr);
glib_object_wrapper!(@munch_first_impl $name, $rust_class_name, $($extends)*);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
glib_object_wrapper!(@class_impl $name, $ffi_class_name, $rust_class_name);
#[doc(hidden)]
impl AsRef<$crate::object::Object> for $name {
fn as_ref(&self) -> &$crate::object::Object {
$crate::object::Cast::upcast_ref(self)
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$crate::object::Object> for $name { }
};
(@interface [$($attr:meta)*] $name:ident, $ffi_name:path, @get_type $get_type_expr:expr, @requires [$($requires:tt)*]) => {
glib_object_wrapper!(@generic_impl [$($attr)*] $name, $ffi_name, $crate::wrapper::Void, $crate::wrapper::Void,
@get_type $get_type_expr);
glib_object_wrapper!(@munch_impls $name, $($requires)*);
#[doc(hidden)]
impl AsRef<$crate::object::Object> for $name {
fn as_ref(&self) -> &$crate::object::Object {
$crate::object::Cast::upcast_ref(self)
}
}
#[doc(hidden)]
unsafe impl $crate::object::IsA<$crate::object::Object> for $name { }
};
}
glib_object_wrapper!(@object
[doc = "The base class in the object hierarchy."]
Object, GObject, GObjectClass, ObjectClass, @get_type gobject_sys::g_object_get_type()
);
impl Object {
pub fn new(type_: Type, properties: &[(&str, &dyn ToValue)]) -> Result<Object, BoolError> {
use std::ffi::CString;
if !type_.is_a(&Object::static_type()) {
return Err(glib_bool_error!("Can't instantiate non-GObject objects"));
}
let params = properties
.iter()
.map(|&(name, value)| (CString::new(name).unwrap(), value.to_value()))
.collect::<Vec<_>>();
let params_c = params
.iter()
.map(|&(ref name, ref value)| gobject_sys::GParameter {
name: name.as_ptr(),
value: unsafe { *value.to_glib_none().0 },
})
.collect::<Vec<_>>();
unsafe {
let ptr = gobject_sys::g_object_newv(
type_.to_glib(),
params_c.len() as u32,
mut_override(params_c.as_ptr()),
);
if ptr.is_null() {
Err(glib_bool_error!("Can't instantiate object"))
} else if type_.is_a(&InitiallyUnowned::static_type()) {
// Attention: This takes ownership of the floating reference
Ok(from_glib_none(ptr))
} else {
Ok(from_glib_full(ptr))
}
}
}
}
pub trait ObjectExt: ObjectType {
/// Returns `true` if the object is an instance of (can be cast to) `T`.
fn is<T: StaticType>(&self) -> bool;
fn get_type(&self) -> Type;
fn get_object_class(&self) -> &ObjectClass;
fn set_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
value: &dyn ToValue,
) -> Result<(), BoolError>;
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError>;
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> bool;
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type>;
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec>;
fn list_properties(&self) -> Vec<::ParamSpec>;
/// # Safety
///
/// This function doesn't store type information
unsafe fn set_qdata<QD: 'static>(&self, key: Quark, value: QD);
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn get_qdata<QD: 'static>(&self, key: Quark) -> Option<&QD>;
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn steal_qdata<QD: 'static>(&self, key: Quark) -> Option<QD>;
/// # Safety
///
/// This function doesn't store type information
unsafe fn set_data<QD: 'static>(&self, key: &str, value: QD);
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn get_data<QD: 'static>(&self, key: &str) -> Option<&QD>;
/// # Safety
///
/// The caller is responsible for ensuring the returned value is of a suitable type
unsafe fn steal_data<QD: 'static>(&self, key: &str) -> Option<QD>;
fn block_signal(&self, handler_id: &SignalHandlerId);
fn unblock_signal(&self, handler_id: &SignalHandlerId);
fn stop_signal_emission(&self, signal_name: &str);
fn connect<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static;
fn connect_local<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + 'static;
#[allow(clippy::missing_safety_doc)]
unsafe fn connect_unsafe<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value>;
fn emit<'a, N: Into<&'a str>>(
&self,
signal_name: N,
args: &[&dyn ToValue],
) -> Result<Option<Value>, BoolError>;
fn disconnect(&self, handler_id: SignalHandlerId);
fn connect_notify<F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId;
#[allow(clippy::missing_safety_doc)]
unsafe fn connect_notify_unsafe<F: Fn(&Self, &::ParamSpec)>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId;
fn notify<'a, N: Into<&'a str>>(&self, property_name: N);
fn notify_by_pspec(&self, pspec: &::ParamSpec);
fn downgrade(&self) -> WeakRef<Self>;
fn bind_property<'a, O: ObjectType, N: Into<&'a str>, M: Into<&'a str>>(
&'a self,
source_property: N,
target: &'a O,
target_property: M,
) -> BindingBuilder<'a>;
fn ref_count(&self) -> u32;
}
impl<T: ObjectType> ObjectExt for T {
fn is<U: StaticType>(&self) -> bool {
self.get_type().is_a(&U::static_type())
}
fn get_type(&self) -> Type {
self.get_object_class().get_type()
}
fn get_object_class(&self) -> &ObjectClass {
unsafe {
let obj: *mut gobject_sys::GObject = self.as_object_ref().to_glib_none().0;
let klass = (*obj).g_type_instance.g_class as *const ObjectClass;
&*klass
}
}
fn set_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
value: &dyn ToValue,
) -> Result<(), BoolError> {
let property_name = property_name.into();
let mut property_value = value.to_value();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(glib_bool_error!("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::WRITABLE)
|| pspec.get_flags().contains(::ParamFlags::CONSTRUCT_ONLY)
{
return Err(glib_bool_error!("property is not writable"));
}
unsafe {
// While GLib actually allows all types that can somehow be transformed
// into the property type, we're more restrictive here to be consistent
// with Rust's type rules. We only allow the exact same type, or if the
// value type is a subtype of the property type
let valid_type: bool = from_glib(gobject_sys::g_type_check_value_holds(
mut_override(property_value.to_glib_none().0),
pspec.get_value_type().to_glib(),
));
// If it's not directly a valid type but an object type, we check if the
// actual type of the contained object is compatible and if so create
// a properly type Value. This can happen if the type field in the
// Value is set to a more generic type than the contained value
if !valid_type && property_value.type_().is_a(&Object::static_type()) {
match property_value.get::<Object>() {
Ok(Some(obj)) => {
if obj.get_type().is_a(&pspec.get_value_type()) {
property_value.0.g_type = pspec.get_value_type().to_glib();
} else {
return Err(glib_bool_error!(format!(
concat!(
"property can't be set from the given object type ",
"(expected: {:?}, got: {:?})",
),
pspec.get_value_type(),
obj.get_type(),
)));
}
}
Ok(None) => {
// If the value is None then the type is compatible too
property_value.0.g_type = pspec.get_value_type().to_glib();
}
Err(_) => unreachable!("property_value type conformity already checked"),
}
} else if !valid_type {
return Err(glib_bool_error!(format!(
"property can't be set from the given type (expected: {:?}, got: {:?})",
pspec.get_value_type(),
property_value.type_(),
)));
}
let changed: bool = from_glib(gobject_sys::g_param_value_validate(
pspec.to_glib_none().0,
property_value.to_glib_none_mut().0,
));
let change_allowed = pspec.get_flags().contains(::ParamFlags::LAX_VALIDATION);
if changed && !change_allowed {
return Err(glib_bool_error!(
"property can't be set from given value, it is invalid or out of range"
));
}
gobject_sys::g_object_set_property(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
property_value.to_glib_none().0,
);
}
Ok(())
}
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError> {
let property_name = property_name.into();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(glib_bool_error!("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::READABLE) {
return Err(glib_bool_error!("property is not readable"));
}
unsafe {
let mut value = Value::from_type(pspec.get_value_type());
gobject_sys::g_object_get_property(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
value.to_glib_none_mut().0,
);
// This can't really happen unless something goes wrong inside GObject
if value.type_() == ::Type::Invalid {
Err(glib_bool_error!("Failed to get property value"))
} else {
Ok(value)
}
}
}
unsafe fn set_qdata<QD: 'static>(&self, key: Quark, value: QD) {
unsafe extern "C" fn drop_value<QD>(ptr: glib_sys::gpointer) {
debug_assert!(!ptr.is_null());
let value: Box<QD> = Box::from_raw(ptr as *mut QD);
drop(value)
}
let ptr = Box::into_raw(Box::new(value)) as glib_sys::gpointer;
gobject_sys::g_object_set_qdata_full(
self.as_object_ref().to_glib_none().0,
key.to_glib(),
ptr,
Some(drop_value::<QD>),
);
}
unsafe fn get_qdata<QD: 'static>(&self, key: Quark) -> Option<&QD> {
let ptr =
gobject_sys::g_object_get_qdata(self.as_object_ref().to_glib_none().0, key.to_glib());
if ptr.is_null() {
None
} else {
Some(&*(ptr as *const QD))
}
}
unsafe fn steal_qdata<QD: 'static>(&self, key: Quark) -> Option<QD> {
let ptr =
gobject_sys::g_object_steal_qdata(self.as_object_ref().to_glib_none().0, key.to_glib());
if ptr.is_null() {
None
} else {
let value: Box<QD> = Box::from_raw(ptr as *mut QD);
Some(*value)
}
}
unsafe fn set_data<QD: 'static>(&self, key: &str, value: QD) {
self.set_qdata::<QD>(Quark::from_string(key), value)
}
unsafe fn get_data<QD: 'static>(&self, key: &str) -> Option<&QD> {
self.get_qdata::<QD>(Quark::from_string(key))
}
unsafe fn steal_data<QD: 'static>(&self, key: &str) -> Option<QD> {
self.steal_qdata::<QD>(Quark::from_string(key))
}
fn block_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_block(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn unblock_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_unblock(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn stop_signal_emission(&self, signal_name: &str) {
unsafe {
gobject_sys::g_signal_stop_emission_by_name(
self.as_object_ref().to_glib_none().0,
signal_name.to_glib_none().0,
);
}
}
fn disconnect(&self, handler_id: SignalHandlerId) {
unsafe {
gobject_sys::g_signal_handler_disconnect(
self.as_object_ref().to_glib_none().0,
handler_id.to_glib(),
);
}
}
fn connect_notify<F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId {
unsafe { self.connect_notify_unsafe(name, f) }
}
unsafe fn connect_notify_unsafe<F: Fn(&Self, &::ParamSpec)>(
&self,
name: Option<&str>,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_trampoline<P, F: Fn(&P, &::ParamSpec)>(
this: *mut gobject_sys::GObject,
param_spec: *mut gobject_sys::GParamSpec,
f: glib_sys::gpointer,
) where
P: ObjectType,
{
let f: &F = &*(f as *const F);
f(
Object::from_glib_borrow(this).unsafe_cast_ref(),
&from_glib_borrow(param_spec),
)
}
let signal_name = if let Some(name) = name {
format!("notify::{}\0", name)
} else {
"notify\0".into()
};
let f: Box<F> = Box::new(f);
::signal::connect_raw(
self.as_object_ref().to_glib_none().0,
signal_name.as_ptr() as *const _,
Some(mem::transmute::<_, unsafe extern "C" fn()>(
notify_trampoline::<Self, F> as *const (),
)),
Box::into_raw(f),
)
}
fn notify<'a, N: Into<&'a str>>(&self, property_name: N) {
let property_name = property_name.into();
unsafe {
gobject_sys::g_object_notify(
self.as_object_ref().to_glib_none().0,
property_name.to_glib_none().0,
);
}
}
fn notify_by_pspec(&self, pspec: &::ParamSpec) {
unsafe {
gobject_sys::g_object_notify_by_pspec(
self.as_object_ref().to_glib_none().0,
pspec.to_glib_none().0,
);
}
}
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> bool {
self.get_object_class().has_property(property_name, type_)
}
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type> {
self.get_object_class().get_property_type(property_name)
}
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec> {
self.get_object_class().find_property(property_name)
}
fn list_properties(&self) -> Vec<::ParamSpec> {
self.get_object_class().list_properties()
}
fn connect<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static,
{
unsafe { self.connect_unsafe(signal_name, after, callback) }
}
fn connect_local<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value> + 'static,
{
let callback = crate::ThreadGuard::new(callback);
unsafe {
self.connect_unsafe(signal_name, after, move |values| {
(callback.get_ref())(values)
})
}
}
unsafe fn connect_unsafe<'a, N, F>(
&self,
signal_name: N,
after: bool,
callback: F,
) -> Result<SignalHandlerId, BoolError>
where
N: Into<&'a str>,
F: Fn(&[Value]) -> Option<Value>,
{
let signal_name: &str = signal_name.into();
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_sys::g_signal_parse_name(
signal_name.to_glib_none().0,
type_.to_glib(),
&mut signal_id,
&mut signal_detail,
true.to_glib(),
));
if !found {
return Err(glib_bool_error!("Signal not found"));
}
let mut details = mem::MaybeUninit::zeroed();
gobject_sys::g_signal_query(signal_id, details.as_mut_ptr());
let details = details.assume_init();
if details.signal_id != signal_id {
return Err(glib_bool_error!("Signal not found"));
}
// This is actually G_SIGNAL_TYPE_STATIC_SCOPE
let return_type: Type =
from_glib(details.return_type & (!gobject_sys::G_TYPE_FLAG_RESERVED_ID_BIT));
let closure = Closure::new_unsafe(move |values| {
let ret = callback(values);
if return_type == Type::Unit {
if let Some(ret) = ret {
panic!(
"Signal required no return value but got value of type {}",
ret.type_().name()
);
}
None
} else {
match ret {
Some(mut ret) => {
let valid_type: bool = from_glib(gobject_sys::g_type_check_value_holds(
mut_override(ret.to_glib_none().0),
return_type.to_glib(),
));
// If it's not directly a valid type but an object type, we check if the
// actual typed of the contained object is compatible and if so create
// a properly typed Value. This can happen if the type field in the
// Value is set to a more generic type than the contained value
if !valid_type && ret.type_().is_a(&Object::static_type()) {
match ret.get::<Object>() {
Ok(Some(obj)) => {
if obj.get_type().is_a(&return_type) {
ret.0.g_type = return_type.to_glib();
} else {
panic!("Signal required return value of type {} but got {} (actual {})",
return_type.name(), ret.type_().name(), obj.get_type().name());
}
}
Ok(None) => {
// If the value is None then the type is compatible too
ret.0.g_type = return_type.to_glib();
}
Err(_) => unreachable!("ret type conformity already checked"),
}
} else if !valid_type {
panic!(
"Signal required return value of type {} but got {}",
return_type.name(),
ret.type_().name()
);
}
Some(ret)
}
None => {
panic!(
"Signal required return value of type {} but got None",
return_type.name()
);
}
}
}
});
let handler = gobject_sys::g_signal_connect_closure_by_id(
self.as_object_ref().to_glib_none().0,
signal_id,
signal_detail,
closure.to_glib_none().0,
after.to_glib(),
);
if handler == 0 {
Err(glib_bool_error!("Failed to connect to signal"))
} else {
Ok(from_glib(handler))
}
}
fn emit<'a, N: Into<&'a str>>(
&self,
signal_name: N,
args: &[&dyn ToValue],
) -> Result<Option<Value>, BoolError> {
let signal_name: &str = signal_name.into();
unsafe {
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_sys::g_signal_parse_name(
signal_name.to_glib_none().0,
type_.to_glib(),
&mut signal_id,
&mut signal_detail,
true.to_glib(),
));
if !found {
return Err(glib_bool_error!("Signal not found"));
}
let mut details = mem::MaybeUninit::zeroed();
gobject_sys::g_signal_query(signal_id, details.as_mut_ptr());
let details = details.assume_init();
if details.signal_id != signal_id {
return Err(glib_bool_error!("Signal not found"));
}
if details.n_params != args.len() as u32 {
return Err(glib_bool_error!("Incompatible number of arguments"));
}
for (i, item) in args.iter().enumerate() {
let arg_type =
*(details.param_types.add(i)) & (!gobject_sys::G_TYPE_FLAG_RESERVED_ID_BIT);
if arg_type != item.to_value_type().to_glib() {
return Err(glib_bool_error!("Incompatible argument types"));
}
}
let mut v_args: Vec<Value>;
let mut s_args: [Value; 10] = mem::zeroed();
let self_v = {
let mut v = Value::uninitialized();
gobject_sys::g_value_init(v.to_glib_none_mut().0, self.get_type().to_glib());
gobject_sys::g_value_set_object(
v.to_glib_none_mut().0,
self.as_object_ref().to_glib_none().0,
);
v
};
let args = if args.len() < 10 {
s_args[0] = self_v;
for (i, arg) in args.iter().enumerate() {
s_args[i + 1] = arg.to_value();
}
&s_args[0..=args.len()]
} else {
v_args = Vec::with_capacity(args.len() + 1);
v_args.push(self_v);
for arg in args {
v_args.push(arg.to_value());
}
v_args.as_slice()
};
let mut return_value = Value::uninitialized();
if details.return_type != gobject_sys::G_TYPE_NONE {
gobject_sys::g_value_init(return_value.to_glib_none_mut().0, details.return_type);
}
gobject_sys::g_signal_emitv(
mut_override(args.as_ptr()) as *mut gobject_sys::GValue,
signal_id,
signal_detail,
return_value.to_glib_none_mut().0,
);
if return_value.type_() != Type::Unit && return_value.type_() != Type::Invalid {
Ok(Some(return_value))
} else {
Ok(None)
}
}
}
fn downgrade(&self) -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::zeroed()), PhantomData);
gobject_sys::g_weak_ref_init(
mut_override(&*w.0),
self.as_object_ref().to_glib_none().0,
);
w
}
}
fn bind_property<'a, O: ObjectType, N: Into<&'a str>, M: Into<&'a str>>(
&'a self,
source_property: N,
target: &'a O,
target_property: M,
) -> BindingBuilder<'a> {
let source_property = source_property.into();
let target_property = target_property.into();
BindingBuilder::new(self, source_property, target, target_property)
}
fn ref_count(&self) -> u32 {
let stash = self.as_object_ref().to_glib_none();
let ptr: *mut gobject_sys::GObject = stash.0;
unsafe { glib_sys::g_atomic_int_get(&(*ptr).ref_count as *const u32 as *const i32) as u32 }
}
}
impl ObjectClass {
pub fn has_property<'a, N: Into<&'a str>>(
&self,
property_name: N,
type_: Option<Type>,
) -> bool {
let property_name = property_name.into();
let ptype = self.get_property_type(property_name);
match (ptype, type_) {
(None, _) => false,
(Some(_), None) => true,
(Some(ptype), Some(type_)) => ptype == type_,
}
}
pub fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type> {
self.find_property(property_name)
.map(|pspec| pspec.get_value_type())
}
pub fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec> {
let property_name = property_name.into();
unsafe {
let klass = self as *const _ as *const gobject_sys::GObjectClass;
from_glib_none(gobject_sys::g_object_class_find_property(
klass as *mut _,
property_name.to_glib_none().0,
))
}
}
pub fn list_properties(&self) -> Vec<::ParamSpec> {
unsafe {
let klass = self as *const _ as *const gobject_sys::GObjectClass;
let mut n_properties = 0;
let props =
gobject_sys::g_object_class_list_properties(klass as *mut _, &mut n_properties);
FromGlibContainer::from_glib_none_num(props, n_properties as usize)
}
}
}
glib_wrapper! {
pub struct InitiallyUnowned(Object<gobject_sys::GInitiallyUnowned, gobject_sys::GInitiallyUnownedClass, InitiallyUnownedClass>);
match fn {
get_type => || gobject_sys::g_initially_unowned_get_type(),
}
}
#[derive(Debug)]
pub struct WeakRef<T: ObjectType>(Box<gobject_sys::GWeakRef>, PhantomData<*const T>);
impl<T: ObjectType> WeakRef<T> {
pub fn new() -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::zeroed()), PhantomData);
gobject_sys::g_weak_ref_init(mut_override(&*w.0), ptr::null_mut());
w
}
}
pub fn upgrade(&self) -> Option<T> {
unsafe {
let ptr = gobject_sys::g_weak_ref_get(mut_override(&*self.0));
if ptr.is_null() {
None
} else {
let obj: Object = from_glib_full(ptr);
Some(T::unsafe_from(obj.into()))
}
}
}
}
impl<T: ObjectType> Drop for WeakRef<T> {
fn drop(&mut self) {
unsafe {
gobject_sys::g_weak_ref_clear(mut_override(&*self.0));
}
}
}
impl<T: ObjectType> Clone for WeakRef<T> {
fn clone(&self) -> Self {
unsafe {
let c = WeakRef(Box::new(mem::zeroed()), PhantomData);
let o = gobject_sys::g_weak_ref_get(mut_override(&*self.0));
gobject_sys::g_weak_ref_init(mut_override(&*c.0), o);
if !o.is_null() {
gobject_sys::g_object_unref(o);
}
c
}
}
}
impl<T: ObjectType> Default for WeakRef<T> {
fn default() -> Self {
Self::new()
}
}
unsafe impl<T: ObjectType + Sync + Sync> Sync for WeakRef<T> {}
unsafe impl<T: ObjectType + Send + Sync> Send for WeakRef<T> {}
/// A weak reference to the object it was created for that can be sent to
/// different threads even for object types that don't implement `Send`.
///
/// Trying to upgrade the weak reference from another thread than the one
/// where it was created on will panic but dropping or cloning can be done
/// safely from any thread.
#[derive(Debug)]
pub struct SendWeakRef<T: ObjectType>(WeakRef<T>, Option<usize>);
impl<T: ObjectType> SendWeakRef<T> {
pub fn new() -> SendWeakRef<T> {
SendWeakRef(WeakRef::new(), None)
}
pub fn into_weak_ref(self) -> WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
self.0
}
}
impl<T: ObjectType> ops::Deref for SendWeakRef<T> {
type Target = WeakRef<T>;
fn deref(&self) -> &WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
&self.0
}
}
// Deriving this gives the wrong trait bounds
impl<T: ObjectType> Clone for SendWeakRef<T> {
fn clone(&self) -> Self {
SendWeakRef(self.0.clone(), self.1)
}
}
impl<T: ObjectType> Default for SendWeakRef<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: ObjectType> From<WeakRef<T>> for SendWeakRef<T> {
fn from(v: WeakRef<T>) -> SendWeakRef<T> {
SendWeakRef(v, Some(get_thread_id()))
}
}
unsafe impl<T: ObjectType> Sync for SendWeakRef<T> {}
unsafe impl<T: ObjectType> Send for SendWeakRef<T> {}
#[derive(Debug)]
pub struct BindingBuilder<'a> {
source: &'a ObjectRef,
source_property: &'a str,
target: &'a ObjectRef,
target_property: &'a str,
flags: ::BindingFlags,
transform_to: Option<::Closure>,
transform_from: Option<::Closure>,
}
impl<'a> BindingBuilder<'a> {
fn new<S: ObjectType, T: ObjectType>(
source: &'a S,
source_property: &'a str,
target: &'a T,
target_property: &'a str,
) -> Self {
Self {
source: source.as_object_ref(),
source_property,
target: target.as_object_ref(),
target_property,
flags: ::BindingFlags::DEFAULT,
transform_to: None,
transform_from: None,
}
}
fn transform_closure<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
func: F,
) -> ::Closure {
::Closure::new(move |values| {
assert_eq!(values.len(), 3);
let binding = values[0].get::<::Binding>().unwrap_or_else(|_| {
panic!(
"Type mismatch with the first argument in the closure: expected: `Binding`, got: {:?}",
values[0].type_(),
)
})
.unwrap_or_else(|| {
panic!("Found `None` for the first argument in the closure, expected `Some`")
});
let from = unsafe {
let ptr = gobject_sys::g_value_get_boxed(mut_override(
&values[1] as *const Value as *const gobject_sys::GValue,
));
assert!(!ptr.is_null());
&*(ptr as *const gobject_sys::GValue as *const Value)
};
match func(&binding, &from) {
None => Some(false.to_value()),
Some(value) => {
unsafe {
gobject_sys::g_value_set_boxed(
mut_override(&values[2] as *const Value as *const gobject_sys::GValue),
&value as *const Value as *const _,
);
}
Some(true.to_value())
}
}
})
}
pub fn transform_from<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
self,
func: F,
) -> Self {
Self {
transform_from: Some(Self::transform_closure(func)),
..self
}
}
pub fn transform_to<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
self,
func: F,
) -> Self {
Self {
transform_to: Some(Self::transform_closure(func)),
..self
}
}
pub fn flags(self, flags: ::BindingFlags) -> Self {
Self { flags, ..self }
}
pub fn build(self) -> Option<::Binding> {
unsafe {
from_glib_none(gobject_sys::g_object_bind_property_with_closures(
self.source.to_glib_none().0,
self.source_property.to_glib_none().0,
self.target.to_glib_none().0,
self.target_property.to_glib_none().0,
self.flags.to_glib(),
self.transform_to.to_glib_none().0,
self.transform_from.to_glib_none().0,
))
}
}
}
|
use std::ascii::AsciiExt;
use std::num::from_str_radix;
use std::char::from_u32;
use super::{Document,Element,Text,Comment,ProcessingInstruction};
pub struct Parser;
struct ParsedElement<'a> {
name: &'a str,
attributes: Vec<ParsedAttribute<'a>>,
children: Vec<ParsedChild<'a>>,
}
struct ParsedAttribute<'a> {
name: &'a str,
value: &'a str,
}
struct ParsedText<'a> {
text: &'a str,
}
struct ParsedEntityRef<'a> {
text: &'a str,
}
struct ParsedDecimalCharRef<'a> {
text: &'a str,
}
struct ParsedHexCharRef<'a> {
text: &'a str,
}
enum ParsedReference<'a> {
EntityParsedReference(ParsedEntityRef<'a>),
DecimalCharParsedReference(ParsedDecimalCharRef<'a>),
HexCharParsedReference(ParsedHexCharRef<'a>),
}
struct ParsedComment<'a> {
text: &'a str,
}
struct ParsedProcessingInstruction<'a> {
target: &'a str,
value: Option<&'a str>,
}
enum ParsedRootChild<'a> {
CommentParsedRootChild(ParsedComment<'a>),
PIParsedRootChild(ParsedProcessingInstruction<'a>),
IgnoredParsedRootChild,
}
enum ParsedChild<'a> {
ElementParsedChild(ParsedElement<'a>),
TextParsedChild(ParsedText<'a>),
ReferenceParsedChild(ParsedReference<'a>),
CommentParsedChild(ParsedComment<'a>),
PIParsedChild(ParsedProcessingInstruction<'a>),
}
macro_rules! try_parse(
($e:expr) => ({
match $e {
None => return None,
Some(x) => x,
}
})
)
// Pattern: 0-or-1
macro_rules! optional_parse(
($f:expr, $start:expr) => ({
match $f {
None => (None, $start),
Some((value, next)) => (Some(value), next),
}
})
)
// Pattern: alternate
macro_rules! alternate_parse(
($start:expr, {}) => ( None );
($start:expr, {
[$p:expr -> $t:expr],
$([$p_rest:expr -> $t_rest:expr],)*
}) => (
match $p($start) {
Some((val, next)) => Some(($t(val), next)),
None => alternate_parse!($start, {$([$p_rest -> $t_rest],)*}),
}
);
)
impl Parser {
pub fn new() -> Parser {
Parser
}
fn parse_eq<'a>(&self, xml: &'a str) -> Option<((), &'a str)> {
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("="));
let (_, xml) = optional_parse!(xml.slice_space(), xml);
Some(((), xml))
}
fn parse_version_info<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_space());
let (_, xml) = try_parse!(xml.slice_literal("version"));
let (_, xml) = try_parse!(self.parse_eq(xml));
let (version, xml) = try_parse!(
self.parse_quoted_value(xml, |xml, _| xml.slice_version_num())
);
Some((version, xml))
}
fn parse_xml_declaration<'a>(&self, xml: &'a str) -> Option<((), &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<?xml"));
let (_version, xml) = try_parse!(self.parse_version_info(xml));
// let (encoding, xml) = optional_parse!(self.parse_encoding_declaration(xml));
// let (standalone, xml) = optional_parse!(self.parse_standalone_declaration(xml));
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("?>"));
Some(((), xml))
}
fn parse_space<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
xml.slice_space()
}
fn parse_misc<'a>(&self, xml: &'a str) -> Option<(ParsedRootChild<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_comment(xml) -> |c| CommentParsedRootChild(c)],
[|xml| self.parse_pi(xml) -> |p| PIParsedRootChild(p)],
[|xml| self.parse_space(xml) -> |_| IgnoredParsedRootChild],
})
}
fn parse_miscs<'a>(&self, xml: &'a str) -> (Vec<ParsedRootChild<'a>>, &'a str) {
let mut before_children = Vec::new();
// Pattern: zero-or-more
let mut start = xml;
loop {
let (child, after) = match self.parse_misc(start) {
Some(x) => x,
None => return (before_children, start),
};
before_children.push(child);
start = after;
}
}
fn parse_prolog<'a>(&self, xml: &'a str) -> (Vec<ParsedRootChild<'a>>, &'a str) {
let (_, xml) = optional_parse!(self.parse_xml_declaration(xml), xml);
self.parse_miscs(xml)
}
fn parse_one_quoted_value<'a, T>(&self,
xml: &'a str,
quote: &str,
f: |&'a str| -> Option<(T, &'a str)>)
-> Option<(T, &'a str)>
{
let (_, xml) = try_parse!(xml.slice_literal(quote));
let (value, xml) = try_parse!(f(xml));
let (_, xml) = try_parse!(xml.slice_literal(quote));
Some((value, xml))
}
fn parse_quoted_value<'a, T>(&self,
xml: &'a str,
f: |&'a str, &str| -> Option<(T, &'a str)>)
-> Option<(T, &'a str)>
{
alternate_parse!(xml, {
[|xml| self.parse_one_quoted_value(xml, "'", |xml| f(xml, "'")) -> |v| v],
[|xml| self.parse_one_quoted_value(xml, "\"", |xml| f(xml, "\"")) -> |v| v],
})
}
fn parse_attribute<'a>(&self, xml: &'a str) -> Option<(ParsedAttribute<'a>, &'a str)> {
let (name, xml) = match xml.slice_name() {
Some(x) => x,
None => return None,
};
let (_, xml) = try_parse!(self.parse_eq(xml));
// TODO: don't consume & or <
// TODO: support references
let (value, xml) = try_parse!(
self.parse_quoted_value(xml, |xml, quote| xml.slice_until(quote))
);
Some((ParsedAttribute{name: name, value: value}, xml))
}
fn parse_attributes<'a>(&self, xml: &'a str) -> (Vec<ParsedAttribute<'a>>, &'a str) {
let mut xml = xml;
let mut attrs = Vec::new();
// Pattern: zero-or-more
// On failure, return the end of the last successful parse
loop {
let (_, after_space) = match xml.slice_space() {
None => return (attrs, xml),
Some(x) => x,
};
xml = match self.parse_attribute(after_space) {
None => return (attrs, xml),
Some((attr, after_attr)) => {
attrs.push(attr);
after_attr
},
};
}
}
fn parse_empty_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<"));
let (name, xml) = try_parse!(xml.slice_name());
let (attrs, xml) = self.parse_attributes(xml);
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("/>"));
Some((ParsedElement{name: name, attributes: attrs, children: Vec::new()}, xml))
}
fn parse_element_start<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<"));
let (name, xml) = try_parse!(xml.slice_name());
let (attrs, xml) = self.parse_attributes(xml);
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal(">"));
Some((ParsedElement{name: name, attributes: attrs, children: Vec::new()}, xml))
}
fn parse_element_end<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("</"));
let (name, xml) = try_parse!(xml.slice_name());
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal(">"));
Some((name, xml))
}
fn parse_char_data<'a>(&self, xml: &'a str) -> Option<(ParsedText<'a>, &'a str)> {
let (text, xml) = try_parse!(xml.slice_char_data());
Some((ParsedText{text: text}, xml))
}
fn parse_cdata<'a>(&self, xml: &'a str) -> Option<(ParsedText<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<![CDATA["));
let (text, xml) = try_parse!(xml.slice_cdata());
let (_, xml) = try_parse!(xml.slice_literal("]]>"));
Some((ParsedText{text: text}, xml))
}
fn parse_entity_ref<'a>(&self, xml: &'a str) -> Option<(ParsedEntityRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&"));
let (name, xml) = try_parse!(xml.slice_name());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedEntityRef{text: name}, xml))
}
fn parse_decimal_char_ref<'a>(&self, xml: &'a str) -> Option<(ParsedDecimalCharRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&#"));
let (dec, xml) = try_parse!(xml.slice_decimal_chars());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedDecimalCharRef{text: dec}, xml))
}
fn parse_hex_char_ref<'a>(&self, xml: &'a str) -> Option<(ParsedHexCharRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&#x"));
let (hex, xml) = try_parse!(xml.slice_hex_chars());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedHexCharRef{text: hex}, xml))
}
fn parse_reference<'a>(&self, xml: &'a str) -> Option<(ParsedReference<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_entity_ref(xml) -> |e| EntityParsedReference(e)],
[|xml| self.parse_decimal_char_ref(xml) -> |d| DecimalCharParsedReference(d)],
[|xml| self.parse_hex_char_ref(xml) -> |h| HexCharParsedReference(h)],
})
}
fn parse_comment<'a>(&self, xml: &'a str) -> Option<(ParsedComment<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<!--"));
let (text, xml) = try_parse!(xml.slice_comment());
let (_, xml) = try_parse!(xml.slice_literal("-->"));
Some((ParsedComment{text: text}, xml))
}
fn parse_pi_value<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_space());
xml.slice_pi_value()
}
fn parse_pi<'a>(&self, xml: &'a str) -> Option<(ParsedProcessingInstruction<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<?"));
let (target, xml) = try_parse!(xml.slice_name());
let (value, xml) = optional_parse!(self.parse_pi_value(xml), xml);
let (_, xml) = try_parse!(xml.slice_literal("?>"));
if target.eq_ignore_ascii_case("xml") {
fail!("Can't use xml as a PI target");
}
Some((ParsedProcessingInstruction{target: target, value: value}, xml))
}
fn parse_content<'a>(&self, xml: &'a str) -> (Vec<ParsedChild<'a>>, &'a str) {
let mut children = Vec::new();
let (char_data, xml) = optional_parse!(self.parse_char_data(xml), xml);
char_data.map(|c| children.push(TextParsedChild(c)));
// Pattern: zero-or-more
let mut start = xml;
loop {
let xxx = alternate_parse!(start, {
[|xml| self.parse_element(xml) -> |e| ElementParsedChild(e)],
[|xml| self.parse_cdata(xml) -> |t| TextParsedChild(t)],
[|xml| self.parse_reference(xml) -> |r| ReferenceParsedChild(r)],
[|xml| self.parse_comment(xml) -> |c| CommentParsedChild(c)],
[|xml| self.parse_pi(xml) -> |p| PIParsedChild(p)],
});
let (child, after) = match xxx {
Some(x) => x,
None => return (children, start),
};
let (char_data, xml) = optional_parse!(self.parse_char_data(after), after);
children.push(child);
char_data.map(|c| children.push(TextParsedChild(c)));
start = xml;
}
}
fn parse_non_empty_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (mut element, xml) = try_parse!(self.parse_element_start(xml));
let (children, xml) = self.parse_content(xml);
let (name, xml) = try_parse!(self.parse_element_end(xml));
if element.name != name {
fail!("tags do not match!");
}
element.children = children;
Some((element, xml))
}
fn parse_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_empty_element(xml) -> |e| e],
[|xml| self.parse_non_empty_element(xml) -> |e| e],
})
}
fn hydrate_text(&self, doc: &Document, text_data: ParsedText) -> Text {
doc.new_text(text_data.text.to_string())
}
fn hydrate_reference(&self, doc: &Document, ref_data: ParsedReference) -> Text {
let val = match ref_data {
DecimalCharParsedReference(d) => {
let code: u32 = from_str_radix(d.text, 10).expect("Not valid decimal");
let c: char = from_u32(code).expect("Not a valid codepoint");
c.to_string()
},
HexCharParsedReference(h) => {
let code: u32 = from_str_radix(h.text, 16).expect("Not valid hex");
let c: char = from_u32(code).expect("Not a valid codepoint");
c.to_string()
},
EntityParsedReference(e) => {
match e.text {
"amp" => "&",
"lt" => "<",
"gt" => ">",
"apos" => "'",
"quot" => "\"",
_ => fail!("unknown entity"),
}.to_string()
}
};
doc.new_text(val)
}
fn hydrate_comment(&self, doc: &Document, comment_data: ParsedComment) -> Comment {
doc.new_comment(comment_data.text.to_string())
}
fn hydrate_pi(&self, doc: &Document, pi_data: ParsedProcessingInstruction) -> ProcessingInstruction {
doc.new_processing_instruction(pi_data.target.to_string(), pi_data.value.map(|v| v.to_string()))
}
fn hydrate_element(&self, doc: &Document, element_data: ParsedElement) -> Element {
let element = doc.new_element(element_data.name.to_string());
for attr in element_data.attributes.iter() {
element.set_attribute(attr.name.to_string(), attr.value.to_string());
}
for child in element_data.children.move_iter() {
match child {
ElementParsedChild(e) => element.append_child(self.hydrate_element(doc, e)),
TextParsedChild(t) => element.append_child(self.hydrate_text(doc, t)),
ReferenceParsedChild(r) => element.append_child(self.hydrate_reference(doc, r)),
CommentParsedChild(c) => element.append_child(self.hydrate_comment(doc, c)),
PIParsedChild(pi) => element.append_child(self.hydrate_pi(doc, pi)),
}
}
element
}
fn hydrate_misc(&self, doc: &Document, children: Vec<ParsedRootChild>) {
for child in children.move_iter() {
match child {
CommentParsedRootChild(c) =>
doc.root().append_child(self.hydrate_comment(doc, c)),
PIParsedRootChild(p) =>
doc.root().append_child(self.hydrate_pi(doc, p)),
IgnoredParsedRootChild => {},
}
}
}
fn hydrate_parsed_data(&self,
before_children: Vec<ParsedRootChild>,
element_data: ParsedElement,
after_children: Vec<ParsedRootChild>)
-> Document
{
let doc = Document::new();
let root = doc.root();
self.hydrate_misc(&doc, before_children);
root.append_child(self.hydrate_element(&doc, element_data));
self.hydrate_misc(&doc, after_children);
doc
}
pub fn parse(&self, xml: &str) -> Document {
let (before_children, xml) = self.parse_prolog(xml);
let (element, xml) = self.parse_element(xml).expect("no element");
let (after_children, _xml) = self.parse_miscs(xml);
self.hydrate_parsed_data(before_children, element, after_children)
}
}
trait XmlStr<'a> {
fn slice_at(&self, position: uint) -> (&'a str, &'a str);
fn slice_until(&self, s: &str) -> Option<(&'a str, &'a str)>;
fn slice_literal(&self, expected: &str) -> Option<(&'a str, &'a str)>;
fn slice_version_num(&self) -> Option<(&'a str, &'a str)>;
fn slice_char_data(&self) -> Option<(&'a str, &'a str)>;
fn slice_cdata(&self) -> Option<(&'a str, &'a str)>;
fn slice_decimal_chars(&self) -> Option<(&'a str, &'a str)>;
fn slice_hex_chars(&self) -> Option<(&'a str, &'a str)>;
fn slice_comment(&self) -> Option<(&'a str, &'a str)>;
fn slice_pi_value(&self) -> Option<(&'a str, &'a str)>;
fn slice_start_rest(&self, is_first: |char| -> bool, is_rest: |char| -> bool) -> Option<(&'a str, &'a str)>;
fn slice_name(&self) -> Option<(&'a str, &'a str)>;
fn slice_space(&self) -> Option<(&'a str, &'a str)>;
}
impl<'a> XmlStr<'a> for &'a str {
fn slice_at(&self, position: uint) -> (&'a str, &'a str) {
(self.slice_to(position), self.slice_from(position))
}
fn slice_until(&self, s: &str) -> Option<(&'a str, &'a str)> {
match self.find_str(s) {
Some(position) => Some(self.slice_at(position)),
None => None
}
}
fn slice_literal(&self, expected: &str) -> Option<(&'a str, &'a str)> {
if self.starts_with(expected) {
Some(self.slice_at(expected.len()))
} else {
None
}
}
fn slice_version_num(&self) -> Option<(&'a str, &'a str)> {
if self.starts_with("1.") {
let mut positions = self.char_indices().peekable();
positions.next();
positions.next();
// Need at least one character
match positions.peek() {
Some(&(_, c)) if c.is_decimal_char() => {},
_ => return None,
};
let mut positions = positions.skip_while(|&(_, c)| c.is_decimal_char());
match positions.next() {
Some((offset, _)) => Some(self.slice_at(offset)),
None => Some((self.clone(), "")),
}
} else {
None
}
}
fn slice_char_data(&self) -> Option<(&'a str, &'a str)> {
if self.starts_with("<") ||
self.starts_with("&") ||
self.starts_with("]]>")
{
return None
}
// Using a hex literal because emacs' rust-mode doesn't
// understand ] in a char literal. :-(
let mut positions = self.char_indices().skip_while(|&(_, c)| c != '<' && c != '&' && c != '\x5d');
loop {
match positions.next() {
None => return Some((self.clone(), "")),
Some((offset, c)) if c == '<' || c == '&' => return Some(self.slice_at(offset)),
Some((offset, _)) => {
let (head, tail) = self.slice_at(offset);
if tail.starts_with("]]>") {
return Some((head, tail))
} else {
// False alarm, resume scanning
continue;
}
},
}
}
}
fn slice_cdata(&self) -> Option<(&'a str, &'a str)> {
match self.find_str("]]>") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_decimal_chars(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_decimal_char(),
|c| c.is_decimal_char())
}
fn slice_hex_chars(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_hex_char(),
|c| c.is_hex_char())
}
fn slice_comment(&self) -> Option<(&'a str, &'a str)> {
// This deliberately does not include the >. -- is not allowed
// in a comment, so we can just test the end if it matches the
// complete close delimiter.
match self.find_str("--") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_pi_value(&self) -> Option<(&'a str, &'a str)> {
match self.find_str("?>") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_start_rest(&self,
is_first: |char| -> bool,
is_rest: |char| -> bool)
-> Option<(&'a str, &'a str)>
{
let mut positions = self.char_indices();
match positions.next() {
Some((_, c)) if is_first(c) => (),
Some((_, _)) => return None,
None => return None,
};
let mut positions = positions.skip_while(|&(_, c)| is_rest(c));
match positions.next() {
Some((offset, _)) => Some(self.slice_at(offset)),
None => Some((self.clone(), "")),
}
}
fn slice_name(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_name_start_char(), |c| c.is_name_char())
}
fn slice_space(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_space_char(), |c| c.is_space_char())
}
}
trait XmlChar {
fn is_name_start_char(&self) -> bool;
fn is_name_char(&self) -> bool;
fn is_space_char(&self) -> bool;
fn is_decimal_char(&self) -> bool;
fn is_hex_char(&self) -> bool;
}
impl XmlChar for char {
fn is_name_start_char(&self) -> bool {
match *self {
':' |
'A'..'Z' |
'_' |
'a'..'z' |
'\U000000C0'..'\U000000D6' |
'\U000000D8'..'\U000000F6' |
'\U000000F8'..'\U000002FF' |
'\U00000370'..'\U0000037D' |
'\U0000037F'..'\U00001FFF' |
'\U0000200C'..'\U0000200D' |
'\U00002070'..'\U0000218F' |
'\U00002C00'..'\U00002FEF' |
'\U00003001'..'\U0000D7FF' |
'\U0000F900'..'\U0000FDCF' |
'\U0000FDF0'..'\U0000FFFD' |
'\U00010000'..'\U000EFFFF' => true,
_ => false,
}
}
fn is_name_char(&self) -> bool {
if self.is_name_start_char() { return true; }
match *self {
'-' |
'.' |
'0'..'9' |
'\u00B7' |
'\u0300'..'\u036F' |
'\u203F'..'\u2040' => true,
_ => false
}
}
fn is_space_char(&self) -> bool {
match *self {
'\x20' |
'\x09' |
'\x0D' |
'\x0A' => true,
_ => false,
}
}
fn is_decimal_char(&self) -> bool {
match *self {
'0'..'9' => true,
_ => false,
}
}
fn is_hex_char(&self) -> bool {
match *self {
'0'..'9' |
'a'..'f' |
'A'..'F' => true,
_ => false,
}
}
}
#[test]
fn parses_a_document_with_a_prolog() {
let parser = Parser::new();
let doc = parser.parse("<?xml version='1.0' ?><hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn parses_a_document_with_a_prolog_with_double_quotes() {
let parser = Parser::new();
let doc = parser.parse("<?xml version=\"1.0\" ?><hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn parses_a_document_with_a_single_element() {
let parser = Parser::new();
let doc = parser.parse("<hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn parses_an_element_with_an_attribute() {
let parser = Parser::new();
let doc = parser.parse("<hello scope='world'/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
}
#[test]
fn parses_an_element_with_an_attribute_using_double_quotes() {
let parser = Parser::new();
let doc = parser.parse("<hello scope=\"world\"/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
}
#[test]
fn parses_an_element_with_multiple_attributes() {
let parser = Parser::new();
let doc = parser.parse("<hello scope=\"world\" happy='true'/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
assert_eq!(top.get_attribute("happy").unwrap().as_slice(), "true");
}
#[test]
fn parses_an_element_that_is_not_self_closing() {
let parser = Parser::new();
let doc = parser.parse("<hello></hello>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn parses_nested_elements() {
let parser = Parser::new();
let doc = parser.parse("<hello><world/></hello>");
let nested = doc.root().children()[0].element().unwrap().children()[0].element().unwrap();
assert_eq!(nested.name().as_slice(), "world");
}
#[test]
fn parses_multiply_nested_elements() {
let parser = Parser::new();
let doc = parser.parse("<hello><awesome><world/></awesome></hello>");
let hello = doc.root().children()[0].element().unwrap();
let awesome = hello.children()[0].element().unwrap();
let world = awesome.children()[0].element().unwrap();
assert_eq!(world.name().as_slice(), "world");
}
#[test]
fn parses_nested_elements_with_attributes() {
let parser = Parser::new();
let doc = parser.parse("<hello><world name='Earth'/></hello>");
let hello = doc.root().children()[0].element().unwrap();
let world = hello.children()[0].element().unwrap();
assert_eq!(world.get_attribute("name").unwrap().as_slice(), "Earth");
}
#[test]
fn parses_element_with_text() {
let parser = Parser::new();
let doc = parser.parse("<hello>world</hello>");
let hello = doc.root().children()[0].element().unwrap();
let text = hello.children()[0].text().unwrap();
assert_eq!(text.text().as_slice(), "world");
}
#[test]
fn parses_element_with_cdata() {
let parser = Parser::new();
let doc = parser.parse("<words><![CDATA[I have & and < !]]></words>");
let words = doc.root().children()[0].element().unwrap();
let text = words.children()[0].text().unwrap();
assert_eq!(text.text().as_slice(), "I have & and < !");
}
#[test]
fn parses_element_with_comment() {
let parser = Parser::new();
let doc = parser.parse("<hello><!-- A comment --></hello>");
let words = doc.root().children()[0].element().unwrap();
let comment = words.children()[0].comment().unwrap();
assert_eq!(comment.text().as_slice(), " A comment ");
}
#[test]
fn parses_comment_before_top_element() {
let parser = Parser::new();
let doc = parser.parse("<!-- A comment --><hello />");
let comment = doc.root().children()[0].comment().unwrap();
assert_eq!(comment.text().as_slice(), " A comment ");
}
#[test]
fn parses_multiple_comments_before_top_element() {
let parser = Parser::new();
let xml = r"
<!--Comment 1-->
<!--Comment 2-->
<hello />";
let doc = parser.parse(xml);
let comment1 = doc.root().children()[0].comment().unwrap();
let comment2 = doc.root().children()[1].comment().unwrap();
assert_eq!(comment1.text().as_slice(), "Comment 1");
assert_eq!(comment2.text().as_slice(), "Comment 2");
}
#[test]
fn parses_multiple_comments_after_top_element() {
let parser = Parser::new();
let xml = r"
<hello />
<!--Comment 1-->
<!--Comment 2-->";
let doc = parser.parse(xml);
let comment1 = doc.root().children()[1].comment().unwrap();
let comment2 = doc.root().children()[2].comment().unwrap();
assert_eq!(comment1.text().as_slice(), "Comment 1");
assert_eq!(comment2.text().as_slice(), "Comment 2");
}
#[test]
fn parses_element_with_processing_instruction() {
let parser = Parser::new();
let doc = parser.parse("<hello><?device?></hello>");
let hello = doc.root().children()[0].element().unwrap();
let pi = hello.children()[0].processing_instruction().unwrap();
assert_eq!(pi.target().as_slice(), "device");
assert_eq!(pi.value(), None);
}
#[test]
fn parses_top_level_processing_instructions() {
let parser = Parser::new();
let xml = r"
<?output printer?>
<hello />
<?validated?>";
let doc = parser.parse(xml);
let pi1 = doc.root().children()[0].processing_instruction().unwrap();
let pi2 = doc.root().children()[2].processing_instruction().unwrap();
assert_eq!(pi1.target().as_slice(), "output");
assert_eq!(pi1.value().unwrap().as_slice(), "printer");
assert_eq!(pi2.target().as_slice(), "validated");
assert_eq!(pi2.value(), None);
}
#[test]
fn parses_element_with_decimal_char_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>2 > 1</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "2 ");
assert_eq!(text2.text().as_slice(), ">");
assert_eq!(text3.text().as_slice(), " 1");
}
#[test]
fn parses_element_with_hexidecimal_char_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>1 < 2</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "1 ");
assert_eq!(text2.text().as_slice(), "<");
assert_eq!(text3.text().as_slice(), " 2");
}
#[test]
fn parses_element_with_entity_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>I <3 math</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "I ");
assert_eq!(text2.text().as_slice(), "<");
assert_eq!(text3.text().as_slice(), "3 math");
}
#[test]
fn parses_element_with_mixed_children() {
let parser = Parser::new();
let doc = parser.parse("<hello>to <a>the</a> world</hello>");
let hello = doc.root().children()[0].element().unwrap();
let text1 = hello.children()[0].text().unwrap();
let middle = hello.children()[1].element().unwrap();
let text2 = hello.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "to ");
assert_eq!(middle.name().as_slice(), "a");
assert_eq!(text2.text().as_slice(), " world");
}
#[test]
fn slice_char_data_leading_ampersand() {
assert_eq!("&".slice_char_data(), None);
}
#[test]
fn slice_char_data_leading_less_than() {
assert_eq!("<".slice_char_data(), None);
}
#[test]
fn slice_char_data_leading_cdata_end() {
assert_eq!("]]>".slice_char_data(), None);
}
#[test]
fn slice_char_data_until_ampersand() {
assert_eq!("hello&world".slice_char_data(), Some(("hello", "&world")));
}
#[test]
fn slice_char_data_until_less_than() {
assert_eq!("hello<world".slice_char_data(), Some(("hello", "<world")));
}
#[test]
fn slice_char_data_until_cdata_end() {
assert_eq!("hello]]>world".slice_char_data(), Some(("hello", "]]>world")));
}
#[test]
fn slice_char_data_includes_right_square() {
assert_eq!("hello]world".slice_char_data(), Some(("hello]world", "")));
}
Move parser tests to their own module
use std::ascii::AsciiExt;
use std::num::from_str_radix;
use std::char::from_u32;
use super::{Document,Element,Text,Comment,ProcessingInstruction};
pub struct Parser;
struct ParsedElement<'a> {
name: &'a str,
attributes: Vec<ParsedAttribute<'a>>,
children: Vec<ParsedChild<'a>>,
}
struct ParsedAttribute<'a> {
name: &'a str,
value: &'a str,
}
struct ParsedText<'a> {
text: &'a str,
}
struct ParsedEntityRef<'a> {
text: &'a str,
}
struct ParsedDecimalCharRef<'a> {
text: &'a str,
}
struct ParsedHexCharRef<'a> {
text: &'a str,
}
enum ParsedReference<'a> {
EntityParsedReference(ParsedEntityRef<'a>),
DecimalCharParsedReference(ParsedDecimalCharRef<'a>),
HexCharParsedReference(ParsedHexCharRef<'a>),
}
struct ParsedComment<'a> {
text: &'a str,
}
struct ParsedProcessingInstruction<'a> {
target: &'a str,
value: Option<&'a str>,
}
enum ParsedRootChild<'a> {
CommentParsedRootChild(ParsedComment<'a>),
PIParsedRootChild(ParsedProcessingInstruction<'a>),
IgnoredParsedRootChild,
}
enum ParsedChild<'a> {
ElementParsedChild(ParsedElement<'a>),
TextParsedChild(ParsedText<'a>),
ReferenceParsedChild(ParsedReference<'a>),
CommentParsedChild(ParsedComment<'a>),
PIParsedChild(ParsedProcessingInstruction<'a>),
}
macro_rules! try_parse(
($e:expr) => ({
match $e {
None => return None,
Some(x) => x,
}
})
)
// Pattern: 0-or-1
macro_rules! optional_parse(
($f:expr, $start:expr) => ({
match $f {
None => (None, $start),
Some((value, next)) => (Some(value), next),
}
})
)
// Pattern: alternate
macro_rules! alternate_parse(
($start:expr, {}) => ( None );
($start:expr, {
[$p:expr -> $t:expr],
$([$p_rest:expr -> $t_rest:expr],)*
}) => (
match $p($start) {
Some((val, next)) => Some(($t(val), next)),
None => alternate_parse!($start, {$([$p_rest -> $t_rest],)*}),
}
);
)
impl Parser {
pub fn new() -> Parser {
Parser
}
fn parse_eq<'a>(&self, xml: &'a str) -> Option<((), &'a str)> {
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("="));
let (_, xml) = optional_parse!(xml.slice_space(), xml);
Some(((), xml))
}
fn parse_version_info<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_space());
let (_, xml) = try_parse!(xml.slice_literal("version"));
let (_, xml) = try_parse!(self.parse_eq(xml));
let (version, xml) = try_parse!(
self.parse_quoted_value(xml, |xml, _| xml.slice_version_num())
);
Some((version, xml))
}
fn parse_xml_declaration<'a>(&self, xml: &'a str) -> Option<((), &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<?xml"));
let (_version, xml) = try_parse!(self.parse_version_info(xml));
// let (encoding, xml) = optional_parse!(self.parse_encoding_declaration(xml));
// let (standalone, xml) = optional_parse!(self.parse_standalone_declaration(xml));
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("?>"));
Some(((), xml))
}
fn parse_space<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
xml.slice_space()
}
fn parse_misc<'a>(&self, xml: &'a str) -> Option<(ParsedRootChild<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_comment(xml) -> |c| CommentParsedRootChild(c)],
[|xml| self.parse_pi(xml) -> |p| PIParsedRootChild(p)],
[|xml| self.parse_space(xml) -> |_| IgnoredParsedRootChild],
})
}
fn parse_miscs<'a>(&self, xml: &'a str) -> (Vec<ParsedRootChild<'a>>, &'a str) {
let mut before_children = Vec::new();
// Pattern: zero-or-more
let mut start = xml;
loop {
let (child, after) = match self.parse_misc(start) {
Some(x) => x,
None => return (before_children, start),
};
before_children.push(child);
start = after;
}
}
fn parse_prolog<'a>(&self, xml: &'a str) -> (Vec<ParsedRootChild<'a>>, &'a str) {
let (_, xml) = optional_parse!(self.parse_xml_declaration(xml), xml);
self.parse_miscs(xml)
}
fn parse_one_quoted_value<'a, T>(&self,
xml: &'a str,
quote: &str,
f: |&'a str| -> Option<(T, &'a str)>)
-> Option<(T, &'a str)>
{
let (_, xml) = try_parse!(xml.slice_literal(quote));
let (value, xml) = try_parse!(f(xml));
let (_, xml) = try_parse!(xml.slice_literal(quote));
Some((value, xml))
}
fn parse_quoted_value<'a, T>(&self,
xml: &'a str,
f: |&'a str, &str| -> Option<(T, &'a str)>)
-> Option<(T, &'a str)>
{
alternate_parse!(xml, {
[|xml| self.parse_one_quoted_value(xml, "'", |xml| f(xml, "'")) -> |v| v],
[|xml| self.parse_one_quoted_value(xml, "\"", |xml| f(xml, "\"")) -> |v| v],
})
}
fn parse_attribute<'a>(&self, xml: &'a str) -> Option<(ParsedAttribute<'a>, &'a str)> {
let (name, xml) = match xml.slice_name() {
Some(x) => x,
None => return None,
};
let (_, xml) = try_parse!(self.parse_eq(xml));
// TODO: don't consume & or <
// TODO: support references
let (value, xml) = try_parse!(
self.parse_quoted_value(xml, |xml, quote| xml.slice_until(quote))
);
Some((ParsedAttribute{name: name, value: value}, xml))
}
fn parse_attributes<'a>(&self, xml: &'a str) -> (Vec<ParsedAttribute<'a>>, &'a str) {
let mut xml = xml;
let mut attrs = Vec::new();
// Pattern: zero-or-more
// On failure, return the end of the last successful parse
loop {
let (_, after_space) = match xml.slice_space() {
None => return (attrs, xml),
Some(x) => x,
};
xml = match self.parse_attribute(after_space) {
None => return (attrs, xml),
Some((attr, after_attr)) => {
attrs.push(attr);
after_attr
},
};
}
}
fn parse_empty_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<"));
let (name, xml) = try_parse!(xml.slice_name());
let (attrs, xml) = self.parse_attributes(xml);
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal("/>"));
Some((ParsedElement{name: name, attributes: attrs, children: Vec::new()}, xml))
}
fn parse_element_start<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<"));
let (name, xml) = try_parse!(xml.slice_name());
let (attrs, xml) = self.parse_attributes(xml);
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal(">"));
Some((ParsedElement{name: name, attributes: attrs, children: Vec::new()}, xml))
}
fn parse_element_end<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("</"));
let (name, xml) = try_parse!(xml.slice_name());
let (_, xml) = optional_parse!(xml.slice_space(), xml);
let (_, xml) = try_parse!(xml.slice_literal(">"));
Some((name, xml))
}
fn parse_char_data<'a>(&self, xml: &'a str) -> Option<(ParsedText<'a>, &'a str)> {
let (text, xml) = try_parse!(xml.slice_char_data());
Some((ParsedText{text: text}, xml))
}
fn parse_cdata<'a>(&self, xml: &'a str) -> Option<(ParsedText<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<![CDATA["));
let (text, xml) = try_parse!(xml.slice_cdata());
let (_, xml) = try_parse!(xml.slice_literal("]]>"));
Some((ParsedText{text: text}, xml))
}
fn parse_entity_ref<'a>(&self, xml: &'a str) -> Option<(ParsedEntityRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&"));
let (name, xml) = try_parse!(xml.slice_name());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedEntityRef{text: name}, xml))
}
fn parse_decimal_char_ref<'a>(&self, xml: &'a str) -> Option<(ParsedDecimalCharRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&#"));
let (dec, xml) = try_parse!(xml.slice_decimal_chars());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedDecimalCharRef{text: dec}, xml))
}
fn parse_hex_char_ref<'a>(&self, xml: &'a str) -> Option<(ParsedHexCharRef<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("&#x"));
let (hex, xml) = try_parse!(xml.slice_hex_chars());
let (_, xml) = try_parse!(xml.slice_literal(";"));
Some((ParsedHexCharRef{text: hex}, xml))
}
fn parse_reference<'a>(&self, xml: &'a str) -> Option<(ParsedReference<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_entity_ref(xml) -> |e| EntityParsedReference(e)],
[|xml| self.parse_decimal_char_ref(xml) -> |d| DecimalCharParsedReference(d)],
[|xml| self.parse_hex_char_ref(xml) -> |h| HexCharParsedReference(h)],
})
}
fn parse_comment<'a>(&self, xml: &'a str) -> Option<(ParsedComment<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<!--"));
let (text, xml) = try_parse!(xml.slice_comment());
let (_, xml) = try_parse!(xml.slice_literal("-->"));
Some((ParsedComment{text: text}, xml))
}
fn parse_pi_value<'a>(&self, xml: &'a str) -> Option<(&'a str, &'a str)> {
let (_, xml) = try_parse!(xml.slice_space());
xml.slice_pi_value()
}
fn parse_pi<'a>(&self, xml: &'a str) -> Option<(ParsedProcessingInstruction<'a>, &'a str)> {
let (_, xml) = try_parse!(xml.slice_literal("<?"));
let (target, xml) = try_parse!(xml.slice_name());
let (value, xml) = optional_parse!(self.parse_pi_value(xml), xml);
let (_, xml) = try_parse!(xml.slice_literal("?>"));
if target.eq_ignore_ascii_case("xml") {
fail!("Can't use xml as a PI target");
}
Some((ParsedProcessingInstruction{target: target, value: value}, xml))
}
fn parse_content<'a>(&self, xml: &'a str) -> (Vec<ParsedChild<'a>>, &'a str) {
let mut children = Vec::new();
let (char_data, xml) = optional_parse!(self.parse_char_data(xml), xml);
char_data.map(|c| children.push(TextParsedChild(c)));
// Pattern: zero-or-more
let mut start = xml;
loop {
let xxx = alternate_parse!(start, {
[|xml| self.parse_element(xml) -> |e| ElementParsedChild(e)],
[|xml| self.parse_cdata(xml) -> |t| TextParsedChild(t)],
[|xml| self.parse_reference(xml) -> |r| ReferenceParsedChild(r)],
[|xml| self.parse_comment(xml) -> |c| CommentParsedChild(c)],
[|xml| self.parse_pi(xml) -> |p| PIParsedChild(p)],
});
let (child, after) = match xxx {
Some(x) => x,
None => return (children, start),
};
let (char_data, xml) = optional_parse!(self.parse_char_data(after), after);
children.push(child);
char_data.map(|c| children.push(TextParsedChild(c)));
start = xml;
}
}
fn parse_non_empty_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
let (mut element, xml) = try_parse!(self.parse_element_start(xml));
let (children, xml) = self.parse_content(xml);
let (name, xml) = try_parse!(self.parse_element_end(xml));
if element.name != name {
fail!("tags do not match!");
}
element.children = children;
Some((element, xml))
}
fn parse_element<'a>(&self, xml: &'a str) -> Option<(ParsedElement<'a>, &'a str)> {
alternate_parse!(xml, {
[|xml| self.parse_empty_element(xml) -> |e| e],
[|xml| self.parse_non_empty_element(xml) -> |e| e],
})
}
fn hydrate_text(&self, doc: &Document, text_data: ParsedText) -> Text {
doc.new_text(text_data.text.to_string())
}
fn hydrate_reference(&self, doc: &Document, ref_data: ParsedReference) -> Text {
let val = match ref_data {
DecimalCharParsedReference(d) => {
let code: u32 = from_str_radix(d.text, 10).expect("Not valid decimal");
let c: char = from_u32(code).expect("Not a valid codepoint");
c.to_string()
},
HexCharParsedReference(h) => {
let code: u32 = from_str_radix(h.text, 16).expect("Not valid hex");
let c: char = from_u32(code).expect("Not a valid codepoint");
c.to_string()
},
EntityParsedReference(e) => {
match e.text {
"amp" => "&",
"lt" => "<",
"gt" => ">",
"apos" => "'",
"quot" => "\"",
_ => fail!("unknown entity"),
}.to_string()
}
};
doc.new_text(val)
}
fn hydrate_comment(&self, doc: &Document, comment_data: ParsedComment) -> Comment {
doc.new_comment(comment_data.text.to_string())
}
fn hydrate_pi(&self, doc: &Document, pi_data: ParsedProcessingInstruction) -> ProcessingInstruction {
doc.new_processing_instruction(pi_data.target.to_string(), pi_data.value.map(|v| v.to_string()))
}
fn hydrate_element(&self, doc: &Document, element_data: ParsedElement) -> Element {
let element = doc.new_element(element_data.name.to_string());
for attr in element_data.attributes.iter() {
element.set_attribute(attr.name.to_string(), attr.value.to_string());
}
for child in element_data.children.move_iter() {
match child {
ElementParsedChild(e) => element.append_child(self.hydrate_element(doc, e)),
TextParsedChild(t) => element.append_child(self.hydrate_text(doc, t)),
ReferenceParsedChild(r) => element.append_child(self.hydrate_reference(doc, r)),
CommentParsedChild(c) => element.append_child(self.hydrate_comment(doc, c)),
PIParsedChild(pi) => element.append_child(self.hydrate_pi(doc, pi)),
}
}
element
}
fn hydrate_misc(&self, doc: &Document, children: Vec<ParsedRootChild>) {
for child in children.move_iter() {
match child {
CommentParsedRootChild(c) =>
doc.root().append_child(self.hydrate_comment(doc, c)),
PIParsedRootChild(p) =>
doc.root().append_child(self.hydrate_pi(doc, p)),
IgnoredParsedRootChild => {},
}
}
}
fn hydrate_parsed_data(&self,
before_children: Vec<ParsedRootChild>,
element_data: ParsedElement,
after_children: Vec<ParsedRootChild>)
-> Document
{
let doc = Document::new();
let root = doc.root();
self.hydrate_misc(&doc, before_children);
root.append_child(self.hydrate_element(&doc, element_data));
self.hydrate_misc(&doc, after_children);
doc
}
pub fn parse(&self, xml: &str) -> Document {
let (before_children, xml) = self.parse_prolog(xml);
let (element, xml) = self.parse_element(xml).expect("no element");
let (after_children, _xml) = self.parse_miscs(xml);
self.hydrate_parsed_data(before_children, element, after_children)
}
}
trait XmlStr<'a> {
fn slice_at(&self, position: uint) -> (&'a str, &'a str);
fn slice_until(&self, s: &str) -> Option<(&'a str, &'a str)>;
fn slice_literal(&self, expected: &str) -> Option<(&'a str, &'a str)>;
fn slice_version_num(&self) -> Option<(&'a str, &'a str)>;
fn slice_char_data(&self) -> Option<(&'a str, &'a str)>;
fn slice_cdata(&self) -> Option<(&'a str, &'a str)>;
fn slice_decimal_chars(&self) -> Option<(&'a str, &'a str)>;
fn slice_hex_chars(&self) -> Option<(&'a str, &'a str)>;
fn slice_comment(&self) -> Option<(&'a str, &'a str)>;
fn slice_pi_value(&self) -> Option<(&'a str, &'a str)>;
fn slice_start_rest(&self, is_first: |char| -> bool, is_rest: |char| -> bool) -> Option<(&'a str, &'a str)>;
fn slice_name(&self) -> Option<(&'a str, &'a str)>;
fn slice_space(&self) -> Option<(&'a str, &'a str)>;
}
impl<'a> XmlStr<'a> for &'a str {
fn slice_at(&self, position: uint) -> (&'a str, &'a str) {
(self.slice_to(position), self.slice_from(position))
}
fn slice_until(&self, s: &str) -> Option<(&'a str, &'a str)> {
match self.find_str(s) {
Some(position) => Some(self.slice_at(position)),
None => None
}
}
fn slice_literal(&self, expected: &str) -> Option<(&'a str, &'a str)> {
if self.starts_with(expected) {
Some(self.slice_at(expected.len()))
} else {
None
}
}
fn slice_version_num(&self) -> Option<(&'a str, &'a str)> {
if self.starts_with("1.") {
let mut positions = self.char_indices().peekable();
positions.next();
positions.next();
// Need at least one character
match positions.peek() {
Some(&(_, c)) if c.is_decimal_char() => {},
_ => return None,
};
let mut positions = positions.skip_while(|&(_, c)| c.is_decimal_char());
match positions.next() {
Some((offset, _)) => Some(self.slice_at(offset)),
None => Some((self.clone(), "")),
}
} else {
None
}
}
fn slice_char_data(&self) -> Option<(&'a str, &'a str)> {
if self.starts_with("<") ||
self.starts_with("&") ||
self.starts_with("]]>")
{
return None
}
// Using a hex literal because emacs' rust-mode doesn't
// understand ] in a char literal. :-(
let mut positions = self.char_indices().skip_while(|&(_, c)| c != '<' && c != '&' && c != '\x5d');
loop {
match positions.next() {
None => return Some((self.clone(), "")),
Some((offset, c)) if c == '<' || c == '&' => return Some(self.slice_at(offset)),
Some((offset, _)) => {
let (head, tail) = self.slice_at(offset);
if tail.starts_with("]]>") {
return Some((head, tail))
} else {
// False alarm, resume scanning
continue;
}
},
}
}
}
fn slice_cdata(&self) -> Option<(&'a str, &'a str)> {
match self.find_str("]]>") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_decimal_chars(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_decimal_char(),
|c| c.is_decimal_char())
}
fn slice_hex_chars(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_hex_char(),
|c| c.is_hex_char())
}
fn slice_comment(&self) -> Option<(&'a str, &'a str)> {
// This deliberately does not include the >. -- is not allowed
// in a comment, so we can just test the end if it matches the
// complete close delimiter.
match self.find_str("--") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_pi_value(&self) -> Option<(&'a str, &'a str)> {
match self.find_str("?>") {
None => None,
Some(offset) => Some(self.slice_at(offset)),
}
}
fn slice_start_rest(&self,
is_first: |char| -> bool,
is_rest: |char| -> bool)
-> Option<(&'a str, &'a str)>
{
let mut positions = self.char_indices();
match positions.next() {
Some((_, c)) if is_first(c) => (),
Some((_, _)) => return None,
None => return None,
};
let mut positions = positions.skip_while(|&(_, c)| is_rest(c));
match positions.next() {
Some((offset, _)) => Some(self.slice_at(offset)),
None => Some((self.clone(), "")),
}
}
fn slice_name(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_name_start_char(), |c| c.is_name_char())
}
fn slice_space(&self) -> Option<(&'a str, &'a str)> {
self.slice_start_rest(|c| c.is_space_char(), |c| c.is_space_char())
}
}
trait XmlChar {
fn is_name_start_char(&self) -> bool;
fn is_name_char(&self) -> bool;
fn is_space_char(&self) -> bool;
fn is_decimal_char(&self) -> bool;
fn is_hex_char(&self) -> bool;
}
impl XmlChar for char {
fn is_name_start_char(&self) -> bool {
match *self {
':' |
'A'..'Z' |
'_' |
'a'..'z' |
'\U000000C0'..'\U000000D6' |
'\U000000D8'..'\U000000F6' |
'\U000000F8'..'\U000002FF' |
'\U00000370'..'\U0000037D' |
'\U0000037F'..'\U00001FFF' |
'\U0000200C'..'\U0000200D' |
'\U00002070'..'\U0000218F' |
'\U00002C00'..'\U00002FEF' |
'\U00003001'..'\U0000D7FF' |
'\U0000F900'..'\U0000FDCF' |
'\U0000FDF0'..'\U0000FFFD' |
'\U00010000'..'\U000EFFFF' => true,
_ => false,
}
}
fn is_name_char(&self) -> bool {
if self.is_name_start_char() { return true; }
match *self {
'-' |
'.' |
'0'..'9' |
'\u00B7' |
'\u0300'..'\u036F' |
'\u203F'..'\u2040' => true,
_ => false
}
}
fn is_space_char(&self) -> bool {
match *self {
'\x20' |
'\x09' |
'\x0D' |
'\x0A' => true,
_ => false,
}
}
fn is_decimal_char(&self) -> bool {
match *self {
'0'..'9' => true,
_ => false,
}
}
fn is_hex_char(&self) -> bool {
match *self {
'0'..'9' |
'a'..'f' |
'A'..'F' => true,
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::Parser;
#[test]
fn a_document_with_a_prolog() {
let parser = Parser::new();
let doc = parser.parse("<?xml version='1.0' ?><hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn a_document_with_a_prolog_with_double_quotes() {
let parser = Parser::new();
let doc = parser.parse("<?xml version=\"1.0\" ?><hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn a_document_with_a_single_element() {
let parser = Parser::new();
let doc = parser.parse("<hello />");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn an_element_with_an_attribute() {
let parser = Parser::new();
let doc = parser.parse("<hello scope='world'/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
}
#[test]
fn an_element_with_an_attribute_using_double_quotes() {
let parser = Parser::new();
let doc = parser.parse("<hello scope=\"world\"/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
}
#[test]
fn an_element_with_multiple_attributes() {
let parser = Parser::new();
let doc = parser.parse("<hello scope=\"world\" happy='true'/>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.get_attribute("scope").unwrap().as_slice(), "world");
assert_eq!(top.get_attribute("happy").unwrap().as_slice(), "true");
}
#[test]
fn an_element_that_is_not_self_closing() {
let parser = Parser::new();
let doc = parser.parse("<hello></hello>");
let top = doc.root().children()[0].element().unwrap();
assert_eq!(top.name().as_slice(), "hello");
}
#[test]
fn nested_elements() {
let parser = Parser::new();
let doc = parser.parse("<hello><world/></hello>");
let nested = doc.root().children()[0].element().unwrap().children()[0].element().unwrap();
assert_eq!(nested.name().as_slice(), "world");
}
#[test]
fn multiply_nested_elements() {
let parser = Parser::new();
let doc = parser.parse("<hello><awesome><world/></awesome></hello>");
let hello = doc.root().children()[0].element().unwrap();
let awesome = hello.children()[0].element().unwrap();
let world = awesome.children()[0].element().unwrap();
assert_eq!(world.name().as_slice(), "world");
}
#[test]
fn nested_elements_with_attributes() {
let parser = Parser::new();
let doc = parser.parse("<hello><world name='Earth'/></hello>");
let hello = doc.root().children()[0].element().unwrap();
let world = hello.children()[0].element().unwrap();
assert_eq!(world.get_attribute("name").unwrap().as_slice(), "Earth");
}
#[test]
fn element_with_text() {
let parser = Parser::new();
let doc = parser.parse("<hello>world</hello>");
let hello = doc.root().children()[0].element().unwrap();
let text = hello.children()[0].text().unwrap();
assert_eq!(text.text().as_slice(), "world");
}
#[test]
fn element_with_cdata() {
let parser = Parser::new();
let doc = parser.parse("<words><![CDATA[I have & and < !]]></words>");
let words = doc.root().children()[0].element().unwrap();
let text = words.children()[0].text().unwrap();
assert_eq!(text.text().as_slice(), "I have & and < !");
}
#[test]
fn element_with_comment() {
let parser = Parser::new();
let doc = parser.parse("<hello><!-- A comment --></hello>");
let words = doc.root().children()[0].element().unwrap();
let comment = words.children()[0].comment().unwrap();
assert_eq!(comment.text().as_slice(), " A comment ");
}
#[test]
fn comment_before_top_element() {
let parser = Parser::new();
let doc = parser.parse("<!-- A comment --><hello />");
let comment = doc.root().children()[0].comment().unwrap();
assert_eq!(comment.text().as_slice(), " A comment ");
}
#[test]
fn multiple_comments_before_top_element() {
let parser = Parser::new();
let xml = r"
<!--Comment 1-->
<!--Comment 2-->
<hello />";
let doc = parser.parse(xml);
let comment1 = doc.root().children()[0].comment().unwrap();
let comment2 = doc.root().children()[1].comment().unwrap();
assert_eq!(comment1.text().as_slice(), "Comment 1");
assert_eq!(comment2.text().as_slice(), "Comment 2");
}
#[test]
fn multiple_comments_after_top_element() {
let parser = Parser::new();
let xml = r"
<hello />
<!--Comment 1-->
<!--Comment 2-->";
let doc = parser.parse(xml);
let comment1 = doc.root().children()[1].comment().unwrap();
let comment2 = doc.root().children()[2].comment().unwrap();
assert_eq!(comment1.text().as_slice(), "Comment 1");
assert_eq!(comment2.text().as_slice(), "Comment 2");
}
#[test]
fn element_with_processing_instruction() {
let parser = Parser::new();
let doc = parser.parse("<hello><?device?></hello>");
let hello = doc.root().children()[0].element().unwrap();
let pi = hello.children()[0].processing_instruction().unwrap();
assert_eq!(pi.target().as_slice(), "device");
assert_eq!(pi.value(), None);
}
#[test]
fn top_level_processing_instructions() {
let parser = Parser::new();
let xml = r"
<?output printer?>
<hello />
<?validated?>";
let doc = parser.parse(xml);
let pi1 = doc.root().children()[0].processing_instruction().unwrap();
let pi2 = doc.root().children()[2].processing_instruction().unwrap();
assert_eq!(pi1.target().as_slice(), "output");
assert_eq!(pi1.value().unwrap().as_slice(), "printer");
assert_eq!(pi2.target().as_slice(), "validated");
assert_eq!(pi2.value(), None);
}
#[test]
fn element_with_decimal_char_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>2 > 1</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "2 ");
assert_eq!(text2.text().as_slice(), ">");
assert_eq!(text3.text().as_slice(), " 1");
}
#[test]
fn element_with_hexidecimal_char_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>1 < 2</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "1 ");
assert_eq!(text2.text().as_slice(), "<");
assert_eq!(text3.text().as_slice(), " 2");
}
#[test]
fn element_with_entity_reference() {
let parser = Parser::new();
let doc = parser.parse("<math>I <3 math</math>");
let math = doc.root().children()[0].element().unwrap();
let text1 = math.children()[0].text().unwrap();
let text2 = math.children()[1].text().unwrap();
let text3 = math.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "I ");
assert_eq!(text2.text().as_slice(), "<");
assert_eq!(text3.text().as_slice(), "3 math");
}
#[test]
fn element_with_mixed_children() {
let parser = Parser::new();
let doc = parser.parse("<hello>to <a>the</a> world</hello>");
let hello = doc.root().children()[0].element().unwrap();
let text1 = hello.children()[0].text().unwrap();
let middle = hello.children()[1].element().unwrap();
let text2 = hello.children()[2].text().unwrap();
assert_eq!(text1.text().as_slice(), "to ");
assert_eq!(middle.name().as_slice(), "a");
assert_eq!(text2.text().as_slice(), " world");
}
mod xmlstr {
use super::super::XmlStr;
#[test]
fn slice_char_data_leading_ampersand() {
assert_eq!("&".slice_char_data(), None);
}
#[test]
fn slice_char_data_leading_less_than() {
assert_eq!("<".slice_char_data(), None);
}
#[test]
fn slice_char_data_leading_cdata_end() {
assert_eq!("]]>".slice_char_data(), None);
}
#[test]
fn slice_char_data_until_ampersand() {
assert_eq!("hello&world".slice_char_data(), Some(("hello", "&world")));
}
#[test]
fn slice_char_data_until_less_than() {
assert_eq!("hello<world".slice_char_data(), Some(("hello", "<world")));
}
#[test]
fn slice_char_data_until_cdata_end() {
assert_eq!("hello]]>world".slice_char_data(), Some(("hello", "]]>world")));
}
#[test]
fn slice_char_data_includes_right_square() {
assert_eq!("hello]world".slice_char_data(), Some(("hello]world", "")));
}
}
}
|
use lexer::*;
use spec::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Category {
Integer,
Real,
Boolean,
Procedure,
Program,
Sentinel,
Undefined
}
#[derive(Debug)]
pub struct Identifier {
name: String,
category: Category
}
pub struct Parser {
scanner: Scanner,
symbol: Symbol,
stack: Vec<Identifier>,
// temporary buffer to store identifiers before pushing to stack
// used to bind the types
identifiers_buffer: Vec<Identifier>,
// temporary buffer to store the acceptable types of a category
acceptable_categories: Vec<Category>,
expression : Vec<Symbol>
}
impl Parser {
pub fn new() -> Parser {
Parser {
scanner: Scanner::new(),
stack: Vec::new(),
acceptable_categories: Vec::new(),
identifiers_buffer: Vec::new(),
expression : Vec::new(),
symbol: Symbol {
token: Token::Empty,
category: Type::Eof,
line: 0 }
}
}
pub fn build_ast(&mut self, p: &str) -> bool {
self.scanner.build_token(p);
self.set_next_symbol();
self.parse_program()
}
/*
programa →
program id;
declarações_variáveis
declarações_de_subprogramas
comando_composto
.
*/
fn parse_program(&mut self) -> bool {
// program
if self.symbol.token == Token::Program {
// pushing
self.stack.push(
Identifier {
name: "$".to_string(),
category: Category::Sentinel
});
self.set_next_symbol();
// id
if self.symbol.category == Type::Identifier {
//TODO: encapsular
// pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Program
});
self.set_next_symbol();
//;
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
// declarações_variáveis
self.parse_declare_var();
// declarações_de_subprogramas
self.parse_declare_subprograms();
//comando_composto
self.parse_compound_command();
// .
if self.symbol.token == Token::Period {
true
} else {
panic!("Expected delimiter `.` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected delimiter `;` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
} else {
panic!("Expected keyword `program` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
/*
declarações_variáveis →
var lista_declarações_variáveis | ε
*/
fn parse_declare_var(&mut self) {
// var
if self.symbol.token == Token::Var {
self.set_next_symbol();
// lista_declarações_variáveis
self.parse_list_declare_var(false); //nao pode ser vazio
}
}
/*
lista_declarações_variáveis →
lista_de_identificadores: tipo; lista_declarações_variáveis'
*/
fn parse_list_declare_var(&mut self, ep_closure: bool) {
// lista_de_identificadores
self.parse_list_identfiers(ep_closure);
// :
if self.symbol.token == Token::Colon {
self.set_next_symbol();
// tipo
self.parse_types();
// ;
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
// lista_declarações_variáveis'
self.parse_list_declare_var(true); //pode ser vazio
}
} else if !ep_closure {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
/*
lista_de_identificadores →
id lista_de_identificadores'
*/
fn parse_list_identfiers(&mut self, ep_closure: bool) {
// id
if self.symbol.category == Type::Identifier {
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!() };
if !self.search_scope(&name) {
// pushing
self.identifiers_buffer.push(
Identifier {
name: name,
category: Category::Undefined
});
self.set_next_symbol();
} else {
panic!("Identifier `{}` already declared", name);
}
// lista_de_identificadores'
self.parse_list_identfiers_recursive();
} else if !ep_closure {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
}
/*
lista_de_identificadores' →
, id lista_de_identificadores'
| ε
*/
fn parse_list_identfiers_recursive(&mut self) {
// ,
if self.symbol.token == Token::Comma {
self.set_next_symbol();
// id
if self.symbol.category == Type::Identifier {
// pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Integer
});
self.set_next_symbol();
// lista_de_identificadores'
self.parse_list_identfiers_recursive();
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
}
}
/*
tipo →
integer | real | boolean
*/
fn parse_types(&mut self) {
//integer | real | boolean
if self.symbol.token == Token::Integer || self.symbol.token == Token::Real || self.symbol.token == Token::Boolean {
self.bind_type_and_erase();
self.set_next_symbol();
} else {
panic!("Expected type `boolean` or `integer` or `real` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_declare_subprograms(&mut self) {
if self.symbol.token == Token::Procedure {
self.parse_declare_subprogram(true);
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_declare_subprograms();
}
}
}
fn parse_declare_subprogram(&mut self, ep_closure: bool) {
if self.symbol.token == Token::Procedure {
self.set_next_symbol();
if self.symbol.category == Type::Identifier {
//pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Procedure
}
);
self.stack.push(
Identifier {
name: "$".to_string(),
category: Category::Sentinel
}
);
self.set_next_symbol();
self.parse_args();
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_declare_var();
self.parse_declare_subprograms();
self.parse_compound_command();
}
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
} else if !ep_closure {
panic!("Expected keyword `procedure` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_args(&mut self) {
if self.symbol.token == Token::LParentheses {
self.set_next_symbol();
self.parse_list_params();
if self.symbol.token == Token::RParentheses {
self.set_next_symbol();
} else {
panic!("Expected delimiter `)` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_list_params(&mut self) {
self.parse_list_identfiers(false);
if self.symbol.token == Token::Colon {
self.set_next_symbol();
self.parse_types();
self.parse_list_params_recursive();
} else {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_list_params_recursive(&mut self) {
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_list_identfiers(false);
if self.symbol.token == Token::Colon {
self.set_next_symbol();
self.parse_types();
self.parse_list_params_recursive();
} else {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_compound_command(&mut self) {
if self.symbol.token == Token::Begin {
self.set_next_symbol();
self.parse_list_command(true);
if self.symbol.token == Token::End {
self.clear_scope();
self.set_next_symbol();
} else {
panic!("Expected keyword `end` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected keyword `begin` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_list_command(&mut self, ep_closure: bool) {
self.parse_command(ep_closure);
self.parse_list_command_recursive();
}
fn parse_list_command_recursive(&mut self) {
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_command(true);
self.parse_list_command_recursive();
}
}
fn parse_command(&mut self, ep_closure: bool) {
if self.symbol.category == Type::Identifier {
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
};
let category = self.search_stack(&name);
if category != Category::Undefined {
self.acceptable_types(category); //refresh the acceptable_categories vector
self.set_next_symbol();
if self.symbol.token == Token::Assign {
self.set_next_symbol();
self.parse_expr();
self.evaluate_expr();
} else {
self.parse_active_procedure();
}
} else {
panic!("Identifier `{}` not declared => line {}", name, self.symbol.line);
}
} else if self.symbol.token == Token::Begin {
self.parse_compound_command();
} else if self.symbol.token == Token::If {
self.set_next_symbol();
self.parse_expr();
self.acceptable_types(Category::Boolean);
self.evaluate_expr();
if self.symbol.token == Token::Then {
self.set_next_symbol();
self.parse_command(false);
self.parse_else();
} else {
panic!("Expected keyword `then` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else if self.symbol.token == Token::While {
self.set_next_symbol();
self.parse_expr();
self.acceptable_types(Category::Boolean);
self.evaluate_expr();
if self.symbol.token == Token::Do {
self.set_next_symbol();
self.parse_command(false);
} else {
panic!("Expected keyword `do` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else if !ep_closure {
panic!("Expected identifier found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_active_procedure(&mut self) {
if self.symbol.token == Token::LParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_list_expr();
if self.symbol.token == Token::RParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
} else {
panic!("Expected delimiter `)` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_else(&mut self) {
if self.symbol.token == Token::Else {
self.set_next_symbol();
self.parse_command(false);
}
}
fn parse_list_expr(&mut self) {
self.parse_expr();
self.parse_list_expr_recursive();
}
fn parse_list_expr_recursive(&mut self) {
if self.symbol.token == Token::Comma {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_expr();
self.parse_list_expr_recursive();
}
}
fn parse_expr(&mut self) {
self.parse_simple_expr();
if self.symbol.category == Type::RelOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_simple_expr();
}
}
fn parse_simple_expr(&mut self) {
if self.symbol.token == Token::Add || self.symbol.token == Token::Sub {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_term();
self.parse_simple_expr_recursive();
} else {
self.parse_term();
self.parse_simple_expr_recursive();
}
}
fn parse_simple_expr_recursive(&mut self) {
if self.symbol.category == Type::AddOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_term();
self.parse_simple_expr_recursive();
}
}
fn parse_term(&mut self) {
self.parse_factor();
self.parse_term_recursive();
}
fn parse_term_recursive(&mut self) {
if self.symbol.category == Type::MulOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_factor();
self.parse_term_recursive();
}
}
fn parse_factor(&mut self) {
if self.symbol.category == Type::Identifier {
self.expression.push(self.symbol.clone());
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!() };
if self.search_stack(&name) != Category::Undefined {
self.set_next_symbol();
} else {
panic!("Identifier `{}` not declared => line {}", name, self.symbol.line);
}
self.parse_active_procedure();
} else if self.symbol.token == Token::LParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_expr();
if self.symbol.token == Token::RParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
}
} else if self.symbol.category == Type::RealLiteral || self.symbol.category == Type::IntLiteral ||
self.symbol.token == Token::True || self.symbol.token == Token::False ||
self.symbol.token == Token::Not {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
} else {
panic!("Expected Factor `id` or `real` or `integer` or `true` or false` or `(` or `not` found `{}` => line {}",
self.symbol.token, self.symbol.line)
}
}
fn bind_type_and_erase(&mut self){
let cat: Category = match self.symbol.token {
Token::Integer => Category::Integer,
Token::Real => Category::Real,
Token::Boolean => Category::Boolean,
_ => unimplemented!() };
while !self.identifiers_buffer.is_empty() {
let mut tmp = self.identifiers_buffer.pop().unwrap();
tmp.category = cat;
self.stack.push(tmp);
}
}
fn acceptable_types(&mut self, category: Category){
self.acceptable_categories = match category {
Category::Integer => vec![Category::Integer, Category::Real],
Category::Real => vec![Category::Real, Category::Integer],
Category::Boolean => vec![Category::Boolean],
Category::Procedure => vec![Category::Undefined],
_ => unimplemented!()
};
}
fn search_scope(&self, id: &String) -> bool {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == "$" {
return false;
}
if self.stack[x].name == *id {
return true;
}
}
false
}
fn search_stack(&self, id: &String) -> Category {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == *id {
return self.stack[x].category;
}
}
Category::Undefined
}
fn clear_scope(&mut self) {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == "$" {
self.stack.pop();
break;
} else {
self.stack.pop();
}
}
}
fn evaluate_expr(&mut self) {
// atomic expression
if self.expression.len() == 1 {
let syml = self.expression.pop().unwrap();
let cat = self.match_token_category(syml);
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
} else if self.acceptable_categories[0] == Category::Integer || self.acceptable_categories[0] == Category::Real {
for e in self.expression.iter() {
if e.category == Type::RelOperator {
panic!("Type `{:?}` doesn't support operator relational `{}` => line {}", self.acceptable_categories[0], e.token, e.line);
} else if e.category == Type::AddOperator || e.category == Type::MulOperator || e.token == Token::Not {
match e.token {
Token::Not | Token::And | Token::Or => panic!("Type `{:?}` doesn't support operator logical `{}` => line {}", self.acceptable_categories[0], e.token, e.line),
_ => continue
}
} else {
let cat = self.match_token_category(e.clone());
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
}
}
} else if self.acceptable_categories[0] == Category::Boolean {
let mut type_stack: Vec<Symbol> = Vec::new();
let mut op_stack: Vec<Symbol> = Vec::new();
let mut flag_next = false;
let mut flag_operation = false;
for e in self.expression.iter() {
//(
if e.token == Token::LParentheses && !op_stack.is_empty(){
flag_next = true;
}
// )
if e.token == Token::RParentheses {
if !op_stack.is_empty() {
let mut op1 = type_stack.pop().unwrap();
let mut op2 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}`", Category::Real, Type::BoolLiteral);
}
if op2.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}`", Category::Real, Type::BoolLiteral);
}
type_stack.push(op1.clone());
}
}
}
//literals
if e.category == Type::IntLiteral || e.category == Type::RealLiteral || e.category == Type::BoolLiteral{
if flag_next || !flag_operation {
type_stack.push(e.clone());
} else {
let mut op1 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, op1.line);
}
if e.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, e.line);
}
type_stack.push(op1.clone());
flag_operation = false;
}
}
}
//identifier
if e.category == Type::Identifier {
//test before push
let mut string = match e.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
};
let mut category = self.search_stack(&string);
match category {
Category::Procedure | Category::Program | Category::Sentinel | Category::Undefined =>
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", self.acceptable_categories[0], category, e.line),
_=> continue
};
if flag_next || !flag_operation {
type_stack.push(e.clone());
} else {
let mut op1 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, op1.line);
}
if e.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, e.line);
}
type_stack.push(op1.clone());
}
}
}
//operator
if e.category == Type::AddOperator || e.category == Type::MulOperator || e.category == Type::RelOperator{
op_stack.push(e.clone());
flag_operation = true;
if flag_next {
flag_next = false;
}
}
} //end of loop
let cat = self.match_token_category(type_stack[0].clone());
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
}
self.expression.clear();
}
fn match_token_category(&self, sym: Symbol) -> Category {
match sym.token {
Token::LitStr(ref s) => self.search_stack(s),
Token::True | Token::False => Category::Boolean,
Token::LitReal(r) => Category::Real,
Token::LitInt(i) => Category::Integer,
_ => unimplemented!()
}
}
#[inline]
fn set_next_symbol(&mut self) {
self.symbol = self.scanner.next_symbol();
}
}
#[test]
fn test_expr_boolean(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program16.txt");
for ex in p1.expression.iter() {
println!("{:?}", ex);
}
assert!(res);
}
#[test]
fn test_expr(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
for ex in p1.expression.iter() {
println!("{:?}", ex);
}
assert!(res);
}
#[test]
fn test_stack(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
for id in p1.stack.iter() {
println!("{:?}", id);
}
assert!(res);
}
#[test]
fn test_parser_program6() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
assert!(res);
}
#[test]
fn test_parser_program7() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program7.txt");
assert!(res);
}
#[test]
fn test_parser_program9() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program9.txt");
assert!(res);
}
#[test]
fn test_parser_program10() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program10.txt");
assert!(res);
}
#[test]
fn test_parser_program11() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program11.txt");
assert!(res);
}
#[test]
fn test_parser_program12() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program12.txt");
assert!(res);
}
#[test]
fn test_parser_program13() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program13.txt");
assert!(res);
}
#[test]
fn test_parser_program14() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program14.txt");
assert!(res);
}
#[test]
fn test_parser_program15() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program15.txt");
assert!(res);
}
Fix | Parentêses na expressão aritmética
use lexer::*;
use spec::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Category {
Integer,
Real,
Boolean,
Procedure,
Program,
Sentinel,
Undefined
}
#[derive(Debug)]
pub struct Identifier {
name: String,
category: Category
}
pub struct Parser {
scanner: Scanner,
symbol: Symbol,
stack: Vec<Identifier>,
// temporary buffer to store identifiers before pushing to stack
// used to bind the types
identifiers_buffer: Vec<Identifier>,
// temporary buffer to store the acceptable types of a category
acceptable_categories: Vec<Category>,
expression : Vec<Symbol>
}
impl Parser {
pub fn new() -> Parser {
Parser {
scanner: Scanner::new(),
stack: Vec::new(),
acceptable_categories: Vec::new(),
identifiers_buffer: Vec::new(),
expression : Vec::new(),
symbol: Symbol {
token: Token::Empty,
category: Type::Eof,
line: 0 }
}
}
pub fn build_ast(&mut self, p: &str) -> bool {
self.scanner.build_token(p);
self.set_next_symbol();
self.parse_program()
}
/*
programa →
program id;
declarações_variáveis
declarações_de_subprogramas
comando_composto
.
*/
fn parse_program(&mut self) -> bool {
// program
if self.symbol.token == Token::Program {
// pushing
self.stack.push(
Identifier {
name: "$".to_string(),
category: Category::Sentinel
});
self.set_next_symbol();
// id
if self.symbol.category == Type::Identifier {
//TODO: encapsular
// pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Program
});
self.set_next_symbol();
//;
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
// declarações_variáveis
self.parse_declare_var();
// declarações_de_subprogramas
self.parse_declare_subprograms();
//comando_composto
self.parse_compound_command();
// .
if self.symbol.token == Token::Period {
true
} else {
panic!("Expected delimiter `.` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected delimiter `;` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
} else {
panic!("Expected keyword `program` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
/*
declarações_variáveis →
var lista_declarações_variáveis | ε
*/
fn parse_declare_var(&mut self) {
// var
if self.symbol.token == Token::Var {
self.set_next_symbol();
// lista_declarações_variáveis
self.parse_list_declare_var(false); //nao pode ser vazio
}
}
/*
lista_declarações_variáveis →
lista_de_identificadores: tipo; lista_declarações_variáveis'
*/
fn parse_list_declare_var(&mut self, ep_closure: bool) {
// lista_de_identificadores
self.parse_list_identfiers(ep_closure);
// :
if self.symbol.token == Token::Colon {
self.set_next_symbol();
// tipo
self.parse_types();
// ;
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
// lista_declarações_variáveis'
self.parse_list_declare_var(true); //pode ser vazio
}
} else if !ep_closure {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
/*
lista_de_identificadores →
id lista_de_identificadores'
*/
fn parse_list_identfiers(&mut self, ep_closure: bool) {
// id
if self.symbol.category == Type::Identifier {
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!() };
if !self.search_scope(&name) {
// pushing
self.identifiers_buffer.push(
Identifier {
name: name,
category: Category::Undefined
});
self.set_next_symbol();
} else {
panic!("Identifier `{}` already declared", name);
}
// lista_de_identificadores'
self.parse_list_identfiers_recursive();
} else if !ep_closure {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
}
/*
lista_de_identificadores' →
, id lista_de_identificadores'
| ε
*/
fn parse_list_identfiers_recursive(&mut self) {
// ,
if self.symbol.token == Token::Comma {
self.set_next_symbol();
// id
if self.symbol.category == Type::Identifier {
// pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Integer
});
self.set_next_symbol();
// lista_de_identificadores'
self.parse_list_identfiers_recursive();
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
}
}
/*
tipo →
integer | real | boolean
*/
fn parse_types(&mut self) {
//integer | real | boolean
if self.symbol.token == Token::Integer || self.symbol.token == Token::Real || self.symbol.token == Token::Boolean {
self.bind_type_and_erase();
self.set_next_symbol();
} else {
panic!("Expected type `boolean` or `integer` or `real` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_declare_subprograms(&mut self) {
if self.symbol.token == Token::Procedure {
self.parse_declare_subprogram(true);
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_declare_subprograms();
}
}
}
fn parse_declare_subprogram(&mut self, ep_closure: bool) {
if self.symbol.token == Token::Procedure {
self.set_next_symbol();
if self.symbol.category == Type::Identifier {
//pushing
self.stack.push(
Identifier {
name: match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
},
category: Category::Procedure
}
);
self.stack.push(
Identifier {
name: "$".to_string(),
category: Category::Sentinel
}
);
self.set_next_symbol();
self.parse_args();
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_declare_var();
self.parse_declare_subprograms();
self.parse_compound_command();
}
} else {
panic!("Expected identifier found `{:?}` => line {}", self.symbol.category, self.symbol.line);
}
} else if !ep_closure {
panic!("Expected keyword `procedure` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_args(&mut self) {
if self.symbol.token == Token::LParentheses {
self.set_next_symbol();
self.parse_list_params();
if self.symbol.token == Token::RParentheses {
self.set_next_symbol();
} else {
panic!("Expected delimiter `)` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_list_params(&mut self) {
self.parse_list_identfiers(false);
if self.symbol.token == Token::Colon {
self.set_next_symbol();
self.parse_types();
self.parse_list_params_recursive();
} else {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_list_params_recursive(&mut self) {
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_list_identfiers(false);
if self.symbol.token == Token::Colon {
self.set_next_symbol();
self.parse_types();
self.parse_list_params_recursive();
} else {
panic!("Expected delimiter `:` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_compound_command(&mut self) {
if self.symbol.token == Token::Begin {
self.set_next_symbol();
self.parse_list_command(true);
if self.symbol.token == Token::End {
self.clear_scope();
self.set_next_symbol();
} else {
panic!("Expected keyword `end` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else {
panic!("Expected keyword `begin` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_list_command(&mut self, ep_closure: bool) {
self.parse_command(ep_closure);
self.parse_list_command_recursive();
}
fn parse_list_command_recursive(&mut self) {
if self.symbol.token == Token::Semicolon {
self.set_next_symbol();
self.parse_command(true);
self.parse_list_command_recursive();
}
}
fn parse_command(&mut self, ep_closure: bool) {
if self.symbol.category == Type::Identifier {
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
};
let category = self.search_stack(&name);
if category != Category::Undefined {
self.acceptable_types(category); //refresh the acceptable_categories vector
self.set_next_symbol();
if self.symbol.token == Token::Assign {
self.set_next_symbol();
self.parse_expr();
self.evaluate_expr();
} else {
self.parse_active_procedure();
}
} else {
panic!("Identifier `{}` not declared => line {}", name, self.symbol.line);
}
} else if self.symbol.token == Token::Begin {
self.parse_compound_command();
} else if self.symbol.token == Token::If {
self.set_next_symbol();
self.parse_expr();
self.acceptable_types(Category::Boolean);
self.evaluate_expr();
if self.symbol.token == Token::Then {
self.set_next_symbol();
self.parse_command(false);
self.parse_else();
} else {
panic!("Expected keyword `then` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else if self.symbol.token == Token::While {
self.set_next_symbol();
self.parse_expr();
self.acceptable_types(Category::Boolean);
self.evaluate_expr();
if self.symbol.token == Token::Do {
self.set_next_symbol();
self.parse_command(false);
} else {
panic!("Expected keyword `do` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
} else if !ep_closure {
panic!("Expected identifier found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
fn parse_active_procedure(&mut self) {
if self.symbol.token == Token::LParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_list_expr();
if self.symbol.token == Token::RParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
} else {
panic!("Expected delimiter `)` found `{}` => line {}", self.symbol.token, self.symbol.line);
}
}
}
fn parse_else(&mut self) {
if self.symbol.token == Token::Else {
self.set_next_symbol();
self.parse_command(false);
}
}
fn parse_list_expr(&mut self) {
self.parse_expr();
self.parse_list_expr_recursive();
}
fn parse_list_expr_recursive(&mut self) {
if self.symbol.token == Token::Comma {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_expr();
self.parse_list_expr_recursive();
}
}
fn parse_expr(&mut self) {
self.parse_simple_expr();
if self.symbol.category == Type::RelOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_simple_expr();
}
}
fn parse_simple_expr(&mut self) {
if self.symbol.token == Token::Add || self.symbol.token == Token::Sub {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_term();
self.parse_simple_expr_recursive();
} else {
self.parse_term();
self.parse_simple_expr_recursive();
}
}
fn parse_simple_expr_recursive(&mut self) {
if self.symbol.category == Type::AddOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_term();
self.parse_simple_expr_recursive();
}
}
fn parse_term(&mut self) {
self.parse_factor();
self.parse_term_recursive();
}
fn parse_term_recursive(&mut self) {
if self.symbol.category == Type::MulOperator {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_factor();
self.parse_term_recursive();
}
}
fn parse_factor(&mut self) {
if self.symbol.category == Type::Identifier {
self.expression.push(self.symbol.clone());
let name: String = match self.symbol.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!() };
if self.search_stack(&name) != Category::Undefined {
self.set_next_symbol();
} else {
panic!("Identifier `{}` not declared => line {}", name, self.symbol.line);
}
self.parse_active_procedure();
} else if self.symbol.token == Token::LParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
self.parse_expr();
if self.symbol.token == Token::RParentheses {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
}
} else if self.symbol.category == Type::RealLiteral || self.symbol.category == Type::IntLiteral ||
self.symbol.token == Token::True || self.symbol.token == Token::False ||
self.symbol.token == Token::Not {
self.expression.push(self.symbol.clone());
self.set_next_symbol();
} else {
panic!("Expected Factor `id` or `real` or `integer` or `true` or false` or `(` or `not` found `{}` => line {}",
self.symbol.token, self.symbol.line)
}
}
fn bind_type_and_erase(&mut self){
let cat: Category = match self.symbol.token {
Token::Integer => Category::Integer,
Token::Real => Category::Real,
Token::Boolean => Category::Boolean,
_ => unimplemented!() };
while !self.identifiers_buffer.is_empty() {
let mut tmp = self.identifiers_buffer.pop().unwrap();
tmp.category = cat;
self.stack.push(tmp);
}
}
fn acceptable_types(&mut self, category: Category){
self.acceptable_categories = match category {
Category::Integer => vec![Category::Integer, Category::Real],
Category::Real => vec![Category::Real, Category::Integer],
Category::Boolean => vec![Category::Boolean],
Category::Procedure => vec![Category::Undefined],
_ => unimplemented!()
};
}
fn search_scope(&self, id: &String) -> bool {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == "$" {
return false;
}
if self.stack[x].name == *id {
return true;
}
}
false
}
fn search_stack(&self, id: &String) -> Category {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == *id {
return self.stack[x].category;
}
}
Category::Undefined
}
fn clear_scope(&mut self) {
let len = self.stack.len();
for x in (0..len).rev() {
if self.stack[x].name == "$" {
self.stack.pop();
break;
} else {
self.stack.pop();
}
}
}
fn evaluate_expr(&mut self) {
// atomic expression
if self.expression.len() == 1 {
let syml = self.expression.pop().unwrap();
let cat = self.match_token_category(syml);
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
} else if self.acceptable_categories[0] == Category::Integer || self.acceptable_categories[0] == Category::Real {
for e in self.expression.iter() {
if e.category == Type::RelOperator {
panic!("Type `{:?}` doesn't support operator relational `{}` => line {}", self.acceptable_categories[0], e.token, e.line);
} else if e.category == Type::AddOperator || e.category == Type::MulOperator || e.token == Token::Not {
match e.token {
Token::Not | Token::And | Token::Or => panic!("Type `{:?}` doesn't support operator logical `{}` => line {}", self.acceptable_categories[0], e.token, e.line),
_ => continue
}
} else if e.token == Token::LParentheses || e.token == Token::RParentheses {
continue;
} else {
let cat = self.match_token_category(e.clone());
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
}
}
} else if self.acceptable_categories[0] == Category::Boolean {
let mut type_stack: Vec<Symbol> = Vec::new();
let mut op_stack: Vec<Symbol> = Vec::new();
let mut flag_next = false;
let mut flag_operation = false;
for e in self.expression.iter() {
//(
if e.token == Token::LParentheses && !op_stack.is_empty(){
flag_next = true;
}
// )
if e.token == Token::RParentheses {
if !op_stack.is_empty() {
let mut op1 = type_stack.pop().unwrap();
let mut op2 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}`", Category::Real, Type::BoolLiteral);
}
if op2.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}`", Category::Real, Type::BoolLiteral);
}
type_stack.push(op1.clone());
}
}
}
//literals
if e.category == Type::IntLiteral || e.category == Type::RealLiteral || e.category == Type::BoolLiteral{
if flag_next || !flag_operation {
type_stack.push(e.clone());
} else {
let mut op1 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, op1.line);
}
if e.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, e.line);
}
type_stack.push(op1.clone());
flag_operation = false;
}
}
}
//identifier
if e.category == Type::Identifier {
//test before push
let mut string = match e.token {
Token::LitStr(ref s) => s.to_string(),
_ => unimplemented!()
};
let mut category = self.search_stack(&string);
match category {
Category::Procedure | Category::Program | Category::Sentinel | Category::Undefined =>
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", self.acceptable_categories[0], category, e.line),
_=> continue
};
if flag_next || !flag_operation {
type_stack.push(e.clone());
} else {
let mut op1 = type_stack.pop().unwrap();
let mut operator = op_stack.pop().unwrap();
if operator.category == Type::RelOperator {
type_stack.push(Symbol{
token : Token::True,
category : Type::BoolLiteral,
line : 0
});
} else {
if op1.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, op1.line);
}
if e.category == Type::BoolLiteral {
panic!("Mismatched types expected `{:?}` found `{:?}` => line {}", Category::Real, Type::BoolLiteral, e.line);
}
type_stack.push(op1.clone());
}
}
}
//operator
if e.category == Type::AddOperator || e.category == Type::MulOperator || e.category == Type::RelOperator{
op_stack.push(e.clone());
flag_operation = true;
if flag_next {
flag_next = false;
}
}
} //end of loop
let cat = self.match_token_category(type_stack[0].clone());
if !self.acceptable_categories.contains(&cat) {
panic!("Mismatched types expected `{:?}` found `{:?}`", self.acceptable_categories[0], cat);
}
}
self.expression.clear();
}
fn match_token_category(&self, sym: Symbol) -> Category {
match sym.token {
Token::LitStr(ref s) => self.search_stack(s),
Token::True | Token::False => Category::Boolean,
Token::LitReal(r) => Category::Real,
Token::LitInt(i) => Category::Integer,
_ => unimplemented!()
}
}
#[inline]
fn set_next_symbol(&mut self) {
self.symbol = self.scanner.next_symbol();
}
}
#[test]
fn test_expr_boolean(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program16.txt");
for ex in p1.expression.iter() {
println!("{:?}", ex);
}
assert!(res);
}
#[test]
fn test_expr(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
for ex in p1.expression.iter() {
println!("{:?}", ex);
}
assert!(res);
}
#[test]
fn test_stack(){
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
for id in p1.stack.iter() {
println!("{:?}", id);
}
assert!(res);
}
#[test]
fn test_parser_program6() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program6.txt");
assert!(res);
}
#[test]
fn test_parser_program7() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program7.txt");
assert!(res);
}
#[test]
fn test_parser_program9() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program9.txt");
assert!(res);
}
#[test]
fn test_parser_program10() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program10.txt");
assert!(res);
}
#[test]
fn test_parser_program11() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program11.txt");
assert!(res);
}
#[test]
fn test_parser_program12() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program12.txt");
assert!(res);
}
#[test]
fn test_parser_program13() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program13.txt");
assert!(res);
}
#[test]
fn test_parser_program14() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program14.txt");
assert!(res);
}
#[test]
fn test_parser_program15() {
let mut p1: Parser = Parser::new();
let res = p1.build_ast("files/program15.txt");
assert!(res);
}
|
use pair::Pair;
use error::NcclError;
use token::{Token, TokenKind};
#[derive(Debug)]
pub struct Parser {
current: usize,
path: Vec<String>,
indent: usize,
tokens: Vec<Token>,
pair: Pair,
line: u64,
}
impl Parser {
pub fn new(tokens: Vec<Token>) -> Self {
Parser {
current: 0,
path: vec![],
indent: 0,
tokens: tokens,
pair: Pair::new("__top_level__"),
line: 1,
}
}
pub fn new_with(tokens: Vec<Token>, pair: Pair) -> Self {
let mut r = Parser {
current: 0,
path: vec![],
indent: 0,
tokens: tokens,
pair: Pair::new("__top_level__"),
line: 1
};
r.pair.add_pair(pair);
r
}
// faked you out with that Scanner, didn't I?
// you thought this was going to be recursive descent. YOU WERE WRONG!
pub fn parse(mut self) -> Result<Pair, Vec<NcclError>> {
let mut i = 0;
while i < self.tokens.len() {
match self.tokens[i].kind {
TokenKind::Value => { // add to path respective of self.index
if self.indent <= self.path.len() {
let mut new = self.path[0..self.indent].to_owned();
new.push(self.tokens[i].lexeme.clone());
self.path = new;
} else {
self.path.push(self.tokens[i].lexeme.clone());
}
self.pair.add_slice(&self.path);
if i + 2 <= self.tokens.len() && self.tokens[i + 2].kind == TokenKind::Value {
self.path.clear();
self.indent = 0;
}
},
TokenKind::Indent => { // set new self.index
let mut indent = 0;
while self.tokens[i].kind == TokenKind::Indent {
indent += 1;
i += 1;
}
i -= 1;
self.indent = indent;
},
TokenKind::Newline => { // reset self.index
self.indent = 0;
self.line += 1;
},
TokenKind::EOF => break,
}
i += 1;
}
Ok(self.pair)
}
}
make parse_file_with work
use pair::Pair;
use error::NcclError;
use token::{Token, TokenKind};
#[derive(Debug)]
pub struct Parser {
current: usize,
path: Vec<String>,
indent: usize,
tokens: Vec<Token>,
pair: Pair,
line: u64,
}
impl Parser {
pub fn new(tokens: Vec<Token>) -> Self {
Parser {
current: 0,
path: vec![],
indent: 0,
tokens: tokens,
pair: Pair::new("__top_level__"),
line: 1,
}
}
pub fn new_with(tokens: Vec<Token>, pair: Pair) -> Self {
Parser {
current: 0,
path: vec![],
indent: 0,
tokens: tokens,
pair: pair,
line: 1
}
}
// faked you out with that Scanner, didn't I?
// you thought this was going to be recursive descent. YOU WERE WRONG!
pub fn parse(mut self) -> Result<Pair, Vec<NcclError>> {
let mut i = 0;
while i < self.tokens.len() {
match self.tokens[i].kind {
TokenKind::Value => { // add to path respective of self.index
if self.indent <= self.path.len() {
let mut new = self.path[0..self.indent].to_owned();
new.push(self.tokens[i].lexeme.clone());
self.path = new;
} else {
self.path.push(self.tokens[i].lexeme.clone());
}
self.pair.add_slice(&self.path);
if i + 2 <= self.tokens.len() && self.tokens[i + 2].kind == TokenKind::Value {
self.path.clear();
self.indent = 0;
}
},
TokenKind::Indent => { // set new self.index
let mut indent = 0;
while self.tokens[i].kind == TokenKind::Indent {
indent += 1;
i += 1;
}
i -= 1;
self.indent = indent;
},
TokenKind::Newline => { // reset self.index
self.indent = 0;
self.line += 1;
},
TokenKind::EOF => break,
}
i += 1;
}
Ok(self.pair)
}
}
|
use std::str::from_utf8;
use std::result::Result;
use nom::{IResult,eof};
/*
* Core structs
*/
#[derive(Debug,PartialEq,Eq)]
pub struct TarEntry<'a> {
pub header: PosixHeader<'a>,
pub contents: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixHeader<'a> {
pub name: &'a str,
pub mode: &'a str,
pub uid: u64,
pub gid: u64,
pub size: u64,
pub mtime: u64,
pub chksum: &'a str,
pub typeflag: TypeFlag,
pub linkname: &'a str,
pub ustar: ExtraHeader<'a>
}
/* TODO: support vendor specific + sparse */
#[derive(Debug,PartialEq,Eq,Clone,Copy)]
pub enum TypeFlag {
NormalFile,
HardLink,
SymbolicLink,
CharacterSpecial,
BlockSpecial,
Directory,
FIFO,
ContiguousFile,
PaxInterexchangeFormat,
PaxExtendedAttributes,
VendorSpecific
}
#[derive(Debug,PartialEq,Eq)]
pub enum ExtraHeader<'a> {
UStar(UStarHeader<'a>),
Padding
}
#[derive(Debug,PartialEq,Eq)]
pub struct UStarHeader<'a> {
pub magic: &'a str,
pub version: &'a str,
pub uname: &'a str,
pub gname: &'a str,
pub devmajor: u64,
pub devminor: u64,
pub extra: UStarExtraHeader<'a>
}
#[derive(Debug,PartialEq,Eq)]
pub enum UStarExtraHeader<'a> {
PosixUStar(PosixUStarHeader<'a>),
Pax(PaxHeader<'a>)
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixUStarHeader<'a> {
pub prefix: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PaxHeader<'a> {
pub atime: u64,
pub ctime: u64,
pub offset: u64,
pub longnames: &'a str,
pub sparse: [Sparse; 4],
pub isextended: bool,
pub realsize: u64
}
#[derive(Debug,PartialEq,Eq,Clone,Copy)]
pub struct Sparse {
pub offset: u64,
pub numbytes: u64
}
#[derive(Debug,PartialEq,Eq)]
pub struct Padding;
/*
* Useful macros
*/
macro_rules! take_str_eat_garbage (
( $i:expr, $size:expr ) => (
chain!($i,
s: map_res!(take_until!("\0"), from_utf8) ~
take!($size - s.len()),
||{
s
}
)
);
);
named!(parse_str4<&[u8], &str>, take_str_eat_garbage!(4));
named!(parse_str8<&[u8], &str>, take_str_eat_garbage!(8));
named!(parse_str32<&[u8], &str>, take_str_eat_garbage!(32));
named!(parse_str100<&[u8], &str>, take_str_eat_garbage!(100));
named!(parse_str155<&[u8], &str>, take_str_eat_garbage!(155));
/*
* Octal string parsing
*/
pub fn octal_to_u64(s: &str) -> Result<u64, &'static str> {
let mut u = 0;
for c in s.chars() {
if c < '0' || c > '7' {
return Err("invalid octal string received");
}
u *= 8;
u += (c as u64) - ('0' as u64);
}
Ok(u)
}
fn parse_octal(i: &[u8], n: usize) -> IResult<&[u8], u64> {
map_res!(i, take_str_eat_garbage!(n), octal_to_u64)
}
named!(parse_octal8<&[u8], u64>, apply!(parse_octal, 8));
named!(parse_octal12<&[u8], u64>, apply!(parse_octal, 12));
/*
* TypeFlag parsing
*/
fn char_to_type_flag(c: char) -> TypeFlag {
match c {
'0' | '\0' => TypeFlag::NormalFile,
'1' => TypeFlag::HardLink,
'2' => TypeFlag::SymbolicLink,
'3' => TypeFlag::CharacterSpecial,
'4' => TypeFlag::BlockSpecial,
'5' => TypeFlag::Directory,
'6' => TypeFlag::FIFO,
'7' => TypeFlag::ContiguousFile,
'g' => TypeFlag::PaxInterexchangeFormat,
'x' => TypeFlag::PaxExtendedAttributes,
'A' ... 'Z' => TypeFlag::VendorSpecific,
_ => TypeFlag::NormalFile
}
}
fn bytes_to_type_flag(i: &[u8]) -> Result<TypeFlag, &'static str> {
Ok(char_to_type_flag(i[0] as char))
}
named!(parse_type_flag<&[u8], TypeFlag>, map_res!(take!(1), bytes_to_type_flag));
/*
* Sparse parsing
*/
fn parse_one_sparse(i: &[u8]) -> IResult<&[u8], Sparse> {
chain!(i,
offset: parse_octal12 ~
numbytes: parse_octal12,
||{
Sparse {
offset: offset,
numbytes: numbytes
}
}
)
}
fn parse_sparse(i: &[u8]) -> IResult<&[u8], [Sparse; 4]> {
count!(i, parse_one_sparse, Sparse, 4)
}
/*
* Boolean parsing
*/
fn to_bool(i: &[u8]) -> Result<bool, &'static str> {
Ok(i[0] != 0)
}
named!(parse_bool<&[u8], bool>, map_res!(take!(1), to_bool));
/*
* UStar PAX extended parsing
*/
fn parse_ustar00_extra_pax(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
atime: parse_octal12 ~
ctime: parse_octal12 ~
offset: parse_octal12 ~
longnames: parse_str4 ~
take!(1) ~
sparse: parse_sparse ~
isextended: parse_bool ~
realsize: parse_octal12 ~
take!(17), /* padding to 512 */
||{
UStarExtraHeader::Pax(PaxHeader {
atime: atime,
ctime: ctime,
offset: offset,
longnames: longnames,
sparse: sparse,
isextended: isextended,
realsize: realsize
})
}
)
}
/*
* UStar Posix parsing
*/
fn parse_ustar00_extra_posix(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
prefix: parse_str155 ~
take!(12),
||{
UStarExtraHeader::PosixUStar(PosixUStarHeader {
prefix: prefix
})
}
)
}
fn parse_ustar00_extra(i: &[u8], flag: TypeFlag) -> IResult<&[u8], UStarExtraHeader> {
match flag {
TypeFlag::PaxInterexchangeFormat => parse_ustar00_extra_pax(i),
_ => parse_ustar00_extra_posix(i)
}
}
fn parse_ustar00(i: &[u8], flag: TypeFlag) -> IResult<&[u8], ExtraHeader> {
chain!(i,
tag!("00") ~
uname: parse_str32 ~
gname: parse_str32 ~
devmajor: parse_octal8 ~
devminor: parse_octal8 ~
extra: apply!(parse_ustar00_extra, flag),
||{
ExtraHeader::UStar(UStarHeader {
magic: "ustar\0",
version: "00",
uname: uname,
gname: gname,
devmajor: devmajor,
devminor: devminor,
extra: extra
})
}
)
}
fn parse_ustar(i: &[u8], flag: TypeFlag) -> IResult<&[u8], ExtraHeader> {
chain!(i,
tag!("ustar\0") ~
ustar: apply!(parse_ustar00, flag),
||{
ustar
}
)
}
/*
* Posix tar archive header parsing
*/
fn parse_posix(i: &[u8]) -> IResult<&[u8], ExtraHeader> {
chain!(i,
take!(255), /* padding to 512 */
||{
ExtraHeader::Padding
}
)
}
fn parse_header(i: &[u8]) -> IResult<&[u8], PosixHeader> {
chain!(i,
name: parse_str100 ~
mode: parse_str8 ~
uid: parse_octal8 ~
gid: parse_octal8 ~
size: parse_octal12 ~
mtime: parse_octal12 ~
chksum: parse_str8 ~
typeflag: parse_type_flag ~
linkname: parse_str100 ~
ustar: alt!(apply!(parse_ustar, typeflag) | parse_posix),
||{
PosixHeader {
name: name,
mode: mode,
uid: uid,
gid: gid,
size: size,
mtime: mtime,
chksum: chksum,
typeflag: typeflag,
linkname: linkname,
ustar: ustar
}
}
)
}
/*
* Contents parsing
*/
fn parse_contents(i: &[u8], size: u64) -> IResult<&[u8], &str> {
let trailing = size % 512;
let padding = match trailing {
0 => 0,
t => 512 - t
};
chain!(i,
contents: take_str!(size as usize) ~
take!(padding as usize),
||{
contents
}
)
}
/*
* Tar entry header + contents parsing
*/
fn parse_entry(i: &[u8]) -> IResult<&[u8], TarEntry> {
chain!(i,
header: parse_header ~
contents: apply!(parse_contents, header.size),
||{
TarEntry {
header: header,
contents: contents
}
}
)
}
/*
* Tar archive parsing
*/
fn filter_entries(entries: Vec<TarEntry>) -> Result<Vec<TarEntry>, &'static str> {
/* Filter out empty entries */
Ok(entries.into_iter().filter(|e| e.header.name != "").collect::<Vec<TarEntry>>())
}
pub fn parse_tar(i: &[u8]) -> IResult<&[u8], Vec<TarEntry>> {
chain!(i,
entries: map_res!(many0!(parse_entry), filter_entries) ~
eof,
||{
entries
}
)
}
/*
* Tests
*/
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
use nom::IResult;
#[test]
fn octal_to_u64_ok_test() {
assert_eq!(octal_to_u64("756"), Ok(494));
assert_eq!(octal_to_u64(""), Ok(0));
}
#[test]
fn octal_to_u64_error_test() {
assert_eq!(octal_to_u64("1238"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("a"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("A"), Err("invalid octal string received"));
}
#[test]
fn take_str_eat_garbage_test() {
let s = b"foobar\0\0\0\0baz";
let baz = b"baz";
assert_eq!(take_str_eat_garbage!(&s[..], 10), IResult::Done(&baz[..], "foobar"));
}
}
work on extra sparse
Signed-off-by: Marc-Antoine Perennou <07f76cf0511c79b361712839686f3cee8c75791c@Perennou.com>
use std::str::from_utf8;
use std::result::Result;
use nom::{IResult,eof};
/*
* Core structs
*/
#[derive(Debug,PartialEq,Eq)]
pub struct TarEntry<'a> {
pub header: PosixHeader<'a>,
pub contents: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixHeader<'a> {
pub name: &'a str,
pub mode: &'a str,
pub uid: u64,
pub gid: u64,
pub size: u64,
pub mtime: u64,
pub chksum: &'a str,
pub typeflag: TypeFlag,
pub linkname: &'a str,
pub ustar: ExtraHeader<'a>
}
/* TODO: support vendor specific + sparse */
#[derive(Debug,PartialEq,Eq,Clone,Copy)]
pub enum TypeFlag {
NormalFile,
HardLink,
SymbolicLink,
CharacterSpecial,
BlockSpecial,
Directory,
FIFO,
ContiguousFile,
PaxInterexchangeFormat,
PaxExtendedAttributes,
VendorSpecific
}
#[derive(Debug,PartialEq,Eq)]
pub enum ExtraHeader<'a> {
UStar(UStarHeader<'a>),
Padding
}
#[derive(Debug,PartialEq,Eq)]
pub struct UStarHeader<'a> {
pub magic: &'a str,
pub version: &'a str,
pub uname: &'a str,
pub gname: &'a str,
pub devmajor: u64,
pub devminor: u64,
pub extra: UStarExtraHeader<'a>
}
#[derive(Debug,PartialEq,Eq)]
pub enum UStarExtraHeader<'a> {
PosixUStar(PosixUStarHeader<'a>),
Pax(PaxHeader<'a>)
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixUStarHeader<'a> {
pub prefix: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PaxHeader<'a> {
pub atime: u64,
pub ctime: u64,
pub offset: u64,
pub longnames: &'a str,
pub sparse: [Sparse; 4],
pub isextended: bool,
pub realsize: u64,
pub extra_sparses: Vec<Sparse>
}
#[derive(Debug,PartialEq,Eq,Clone,Copy)]
pub struct Sparse {
pub offset: u64,
pub numbytes: u64
}
#[derive(Debug,PartialEq,Eq)]
pub struct Padding;
/*
* Useful macros
*/
macro_rules! take_str_eat_garbage (
( $i:expr, $size:expr ) => (
chain!($i,
s: map_res!(take_until!("\0"), from_utf8) ~
take!($size - s.len()),
||{
s
}
)
);
);
named!(parse_str4<&[u8], &str>, take_str_eat_garbage!(4));
named!(parse_str8<&[u8], &str>, take_str_eat_garbage!(8));
named!(parse_str32<&[u8], &str>, take_str_eat_garbage!(32));
named!(parse_str100<&[u8], &str>, take_str_eat_garbage!(100));
named!(parse_str155<&[u8], &str>, take_str_eat_garbage!(155));
/*
* Octal string parsing
*/
pub fn octal_to_u64(s: &str) -> Result<u64, &'static str> {
let mut u = 0;
for c in s.chars() {
if c < '0' || c > '7' {
return Err("invalid octal string received");
}
u *= 8;
u += (c as u64) - ('0' as u64);
}
Ok(u)
}
fn parse_octal(i: &[u8], n: usize) -> IResult<&[u8], u64> {
map_res!(i, take_str_eat_garbage!(n), octal_to_u64)
}
named!(parse_octal8<&[u8], u64>, apply!(parse_octal, 8));
named!(parse_octal12<&[u8], u64>, apply!(parse_octal, 12));
/*
* TypeFlag parsing
*/
fn char_to_type_flag(c: char) -> TypeFlag {
match c {
'0' | '\0' => TypeFlag::NormalFile,
'1' => TypeFlag::HardLink,
'2' => TypeFlag::SymbolicLink,
'3' => TypeFlag::CharacterSpecial,
'4' => TypeFlag::BlockSpecial,
'5' => TypeFlag::Directory,
'6' => TypeFlag::FIFO,
'7' => TypeFlag::ContiguousFile,
'g' => TypeFlag::PaxInterexchangeFormat,
'x' => TypeFlag::PaxExtendedAttributes,
'A' ... 'Z' => TypeFlag::VendorSpecific,
_ => TypeFlag::NormalFile
}
}
fn bytes_to_type_flag(i: &[u8]) -> Result<TypeFlag, &'static str> {
Ok(char_to_type_flag(i[0] as char))
}
named!(parse_type_flag<&[u8], TypeFlag>, map_res!(take!(1), bytes_to_type_flag));
/*
* Sparse parsing
*/
fn parse_one_sparse(i: &[u8]) -> IResult<&[u8], Sparse> {
chain!(i,
offset: parse_octal12 ~
numbytes: parse_octal12,
||{
Sparse {
offset: offset,
numbytes: numbytes
}
}
)
}
fn parse_sparse(i: &[u8]) -> IResult<&[u8], [Sparse; 4]> {
count!(i, parse_one_sparse, Sparse, 4)
}
fn add_to_vec(extra: [Sparse; 21], sparses: &mut Vec<Sparse>) -> Result<&'static str, &'static str> {
for sparse in &extra[..] {
if sparse.offset == 0 {
break;
} else {
sparses.push(*sparse);
}
}
Ok("")
}
fn parse_extra_sparses<'a>(i: &'a [u8], isextended: bool, sparses: &'a mut Vec<Sparse>) -> IResult<'a, &'a [u8], &'a mut Vec<Sparse>> {
if isextended {
chain!(i,
map_res!(count!(parse_one_sparse, Sparse, 21), apply!(add_to_vec, sparses)) ~
extended: parse_bool ~
take!(7) /* padding to 512 */ ~
extra_sparses: apply!(parse_extra_sparses, extended, sparses),
||{
extra_sparses
}
)
} else {
IResult::Done(i, sparses)
}
}
/*
* Boolean parsing
*/
fn to_bool(i: &[u8]) -> Result<bool, &'static str> {
Ok(i[0] != 0)
}
named!(parse_bool<&[u8], bool>, map_res!(take!(1), to_bool));
/*
* UStar PAX extended parsing
*/
fn parse_ustar00_extra_pax(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
let sparses : Vec<Sparse> = Vec::new();
chain!(i,
atime: parse_octal12 ~
ctime: parse_octal12 ~
offset: parse_octal12 ~
longnames: parse_str4 ~
take!(1) ~
sparse: parse_sparse ~
isextended: parse_bool ~
realsize: parse_octal12 ~
take!(17) ~ /* padding to 512 */
apply!(parse_extra_sparses, isextended, &mut sparses),
||{
UStarExtraHeader::Pax(PaxHeader {
atime: atime,
ctime: ctime,
offset: offset,
longnames: longnames,
sparse: sparse,
isextended: isextended,
realsize: realsize,
extra_sparses: sparses
})
}
)
}
/*
* UStar Posix parsing
*/
fn parse_ustar00_extra_posix(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
prefix: parse_str155 ~
take!(12),
||{
UStarExtraHeader::PosixUStar(PosixUStarHeader {
prefix: prefix
})
}
)
}
fn parse_ustar00_extra(i: &[u8], flag: TypeFlag) -> IResult<&[u8], UStarExtraHeader> {
match flag {
TypeFlag::PaxInterexchangeFormat => parse_ustar00_extra_pax(i),
_ => parse_ustar00_extra_posix(i)
}
}
fn parse_ustar00(i: &[u8], flag: TypeFlag) -> IResult<&[u8], ExtraHeader> {
chain!(i,
tag!("00") ~
uname: parse_str32 ~
gname: parse_str32 ~
devmajor: parse_octal8 ~
devminor: parse_octal8 ~
extra: apply!(parse_ustar00_extra, flag),
||{
ExtraHeader::UStar(UStarHeader {
magic: "ustar\0",
version: "00",
uname: uname,
gname: gname,
devmajor: devmajor,
devminor: devminor,
extra: extra
})
}
)
}
fn parse_ustar(i: &[u8], flag: TypeFlag) -> IResult<&[u8], ExtraHeader> {
chain!(i,
tag!("ustar\0") ~
ustar: apply!(parse_ustar00, flag),
||{
ustar
}
)
}
/*
* Posix tar archive header parsing
*/
fn parse_posix(i: &[u8]) -> IResult<&[u8], ExtraHeader> {
chain!(i,
take!(255), /* padding to 512 */
||{
ExtraHeader::Padding
}
)
}
fn parse_header(i: &[u8]) -> IResult<&[u8], PosixHeader> {
chain!(i,
name: parse_str100 ~
mode: parse_str8 ~
uid: parse_octal8 ~
gid: parse_octal8 ~
size: parse_octal12 ~
mtime: parse_octal12 ~
chksum: parse_str8 ~
typeflag: parse_type_flag ~
linkname: parse_str100 ~
ustar: alt!(apply!(parse_ustar, typeflag) | parse_posix),
||{
PosixHeader {
name: name,
mode: mode,
uid: uid,
gid: gid,
size: size,
mtime: mtime,
chksum: chksum,
typeflag: typeflag,
linkname: linkname,
ustar: ustar
}
}
)
}
/*
* Contents parsing
*/
fn parse_contents(i: &[u8], size: u64) -> IResult<&[u8], &str> {
let trailing = size % 512;
let padding = match trailing {
0 => 0,
t => 512 - t
};
chain!(i,
contents: take_str!(size as usize) ~
take!(padding as usize),
||{
contents
}
)
}
/*
* Tar entry header + contents parsing
*/
fn parse_entry(i: &[u8]) -> IResult<&[u8], TarEntry> {
chain!(i,
header: parse_header ~
contents: apply!(parse_contents, header.size),
||{
TarEntry {
header: header,
contents: contents
}
}
)
}
/*
* Tar archive parsing
*/
fn filter_entries(entries: Vec<TarEntry>) -> Result<Vec<TarEntry>, &'static str> {
/* Filter out empty entries */
Ok(entries.into_iter().filter(|e| e.header.name != "").collect::<Vec<TarEntry>>())
}
pub fn parse_tar(i: &[u8]) -> IResult<&[u8], Vec<TarEntry>> {
chain!(i,
entries: map_res!(many0!(parse_entry), filter_entries) ~
eof,
||{
entries
}
)
}
/*
* Tests
*/
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
use nom::IResult;
#[test]
fn octal_to_u64_ok_test() {
assert_eq!(octal_to_u64("756"), Ok(494));
assert_eq!(octal_to_u64(""), Ok(0));
}
#[test]
fn octal_to_u64_error_test() {
assert_eq!(octal_to_u64("1238"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("a"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("A"), Err("invalid octal string received"));
}
#[test]
fn take_str_eat_garbage_test() {
let s = b"foobar\0\0\0\0baz";
let baz = b"baz";
assert_eq!(take_str_eat_garbage!(&s[..], 10), IResult::Done(&baz[..], "foobar"));
}
}
|
use std::error::Error;
use {Ident, Value};
#[deriving(PartialEq, Show)]
/// Possible errors encountered when parsing EDN.
pub enum ParserError {
/// The parser reached the end of the input unexpectedly.
Eof,
/// The parser found a token invalid for this position.
InvalidToken(char)
}
impl Error for ParserError {
fn description(&self) -> &str { "EDN parser error" }
}
pub type ParserResult = Result<Value, ParserError>;
pub struct Parser<T: Iterator<char>> {
inp: T,
ch: Option<char>
}
impl<T: Iterator<char>> Parser<T> {
pub fn new(mut inp: T) -> Parser<T> {
let ch = inp.next();
Parser {
inp: inp,
ch: ch
}
}
fn is_eof(&self) -> bool {
self.ch.is_none()
}
fn bump(&mut self) {
self.ch = self.inp.next()
}
fn consume_ws(&mut self) {
loop {
if self.is_eof() { break }
let ch = self.ch.unwrap();
// The EDN "spec" is very vague about what constitutes whitespace, but
// tools.reader.edn uses Java's Character.isWhitespace method which has
// identical semantics to Rust's char::is_whitespace method (*cough*
// hopefully).
// FIXME: verify that ^^^
if ch.is_whitespace() || ch == ',' {
self.bump();
} else {
break
}
}
}
fn at_symbol(&self) -> bool {
if let Some(ch) = self.ch {
is_ident_start_ch(ch)
} else {
false
}
}
fn at_keyword(&self) -> bool {
if let Some(':') = self.ch { true } else { false }
}
fn parse_ident(&mut self) -> Result<Ident, ParserError> {
if self.is_eof() { return Err(ParserError::Eof) }
let mut ident = String::with_capacity(16);
let mut prefix = None;
let ch = self.ch.unwrap();
// It's important that parse_symbol respects the symbol starting character
// restrictions itself, because parse_ident is also needed for parsing
// keywords (which don't have those restrictions).
if !is_ident_ch(ch) { return Err(ParserError::InvalidToken(ch)) }
loop {
if self.is_eof() { break; }
let ch = self.ch.unwrap();
if ch == '/' {
prefix = Some(ident);
ident = String::with_capacity(16);
self.bump();
continue;
}
if !is_ident_ch(ch) { break; }
ident.push(self.ch.unwrap());
self.bump();
}
if ident.len() == 0 { return Err(ParserError::InvalidToken('/')) }
Ok(Ident {
name: ident,
prefix: prefix
})
}
fn parse_symbol(&mut self) -> ParserResult {
let ident = try!(self.parse_ident());
if ident.prefix.is_none() {
Ok(match &*ident.name {
"nil" => Value::Nil,
"true" => Value::Bool(true),
"false" => Value::Bool(false),
_ => Value::Symbol(ident)
})
} else {
Ok(Value::Symbol(ident))
}
}
fn parse_keyword(&mut self) -> ParserResult {
self.bump();
Ok(Value::Keyword(try!(self.parse_ident())))
}
pub fn parse_value(&mut self) -> ParserResult {
self.consume_ws();
if self.is_eof() { return Err(ParserError::Eof) }
if self.at_symbol() { return self.parse_symbol() }
if self.at_keyword() { return self.parse_keyword() }
unimplemented!()
}
}
fn is_ident_start_ch(ch: char) -> bool {
match ch {
'a'...'z' | 'A'...'Z' => true,
'*' | '!' | '_' | '?' | '$' | '%' | '&' | '=' | '<' | '>' => true,
'-' | '+' | '.' => true, // can also start a number literal, watch out!
_ => false
}
}
fn is_ident_ch(ch: char) -> bool {
is_ident_start_ch(ch) || ch == ':' || ch == '#' || (ch >= '0' && ch <= '9')
}
#[cfg(test)]
mod test {
use {Ident, Value};
use super::*;
macro_rules! assert_val {
($str:expr, $val:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert_eq!(parser.parse_value(), Ok($val))
})
}
macro_rules! assert_err {
($str:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert!(parser.parse_value().is_err())
});
($str:expr, $val:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert_eq!(parser.parse_value(), Err($val))
})
}
#[test]
fn test_parse_eof() {
assert_err!("", ParserError::Eof);
assert_err!(" ", ParserError::Eof);
assert_err!(",", ParserError::Eof);
}
#[test]
fn test_parse_nil() {
assert_val!("nil", Value::Nil);
assert_val!("nil ", Value::Nil);
}
#[test]
fn test_parse_bool() {
assert_val!("true", Value::Bool(true));
assert_val!("false", Value::Bool(false));
assert_val!("false,", Value::Bool(false));
}
#[test]
fn test_parse_symbol() {
assert_val!("foo", Value::Symbol(Ident::simple("foo")));
assert_val!("foo#", Value::Symbol(Ident::simple("foo#")));
assert_val!("foo9", Value::Symbol(Ident::simple("foo9")));
assert_val!("-foo", Value::Symbol(Ident::simple("-foo")));
assert_val!("foo/bar", Value::Symbol(Ident::prefixed("bar", "foo")));
assert_err!("foo/", ParserError::InvalidToken('/'));
// FIXME: the parser doesn't handle this correctly right now
// assert_err!("/bar", ParserError::InvalidToken('/'));
// tools.reader.edn parses this as a symbol
// assert_val!("ᛰ", Value::Symbol(Ident::simple("ᛰ")));
}
#[test]
fn test_parse_keyword() {
assert_err!(":", ParserError::Eof);
assert_err!(": foo", ParserError::InvalidToken(' '));
assert_val!(":foo", Value::Keyword(Ident::simple("foo")));
assert_val!(":-foo", Value::Keyword(Ident::simple("-foo")));
assert_val!(":1234", Value::Keyword(Ident::simple("1234")));
assert_val!(":12aaa", Value::Keyword(Ident::simple("12aaa")));
}
}
Parse string literals
use std::error::Error;
use {Ident, Value};
#[deriving(PartialEq, Show)]
/// Possible errors encountered when parsing EDN.
pub enum ParserError {
/// The parser reached the end of the input unexpectedly.
Eof,
/// The parser read an unknown string escape
InvalidEscape,
/// The parser found a token invalid for this position.
InvalidToken(char)
}
impl Error for ParserError {
fn description(&self) -> &str { "EDN parser error" }
}
pub type ParserResult = Result<Value, ParserError>;
pub struct Parser<T: Iterator<char>> {
inp: T,
ch: Option<char>
}
impl<T: Iterator<char>> Parser<T> {
pub fn new(mut inp: T) -> Parser<T> {
let ch = inp.next();
Parser {
inp: inp,
ch: ch
}
}
fn is_eof(&self) -> bool {
self.ch.is_none()
}
fn bump(&mut self) {
self.ch = self.inp.next()
}
fn consume_ws(&mut self) {
loop {
if self.is_eof() { break }
let ch = self.ch.unwrap();
// The EDN "spec" is very vague about what constitutes whitespace, but
// tools.reader.edn uses Java's Character.isWhitespace method which has
// identical semantics to Rust's char::is_whitespace method (*cough*
// hopefully).
// FIXME: verify that ^^^
if ch.is_whitespace() || ch == ',' {
self.bump();
} else {
break
}
}
}
fn at_symbol(&self) -> bool {
if let Some(ch) = self.ch {
is_ident_start_ch(ch)
} else {
false
}
}
fn at_keyword(&self) -> bool {
if let Some(':') = self.ch { true } else { false }
}
fn parse_ident(&mut self) -> Result<Ident, ParserError> {
if self.is_eof() { return Err(ParserError::Eof) }
let mut ident = String::with_capacity(16);
let mut prefix = None;
let ch = self.ch.unwrap();
// It's important that parse_symbol respects the symbol starting character
// restrictions itself, because parse_ident is also needed for parsing
// keywords (which don't have those restrictions).
if !is_ident_ch(ch) { return Err(ParserError::InvalidToken(ch)) }
loop {
if self.is_eof() { break; }
let ch = self.ch.unwrap();
if ch == '/' {
prefix = Some(ident);
ident = String::with_capacity(16);
self.bump();
continue;
}
if !is_ident_ch(ch) { break; }
ident.push(self.ch.unwrap());
self.bump();
}
if ident.len() == 0 { return Err(ParserError::InvalidToken('/')) }
Ok(Ident {
name: ident,
prefix: prefix
})
}
fn parse_string_escape(&mut self) -> Result<char, ParserError> {
self.bump();
if self.is_eof() { return Err(ParserError::Eof) }
let ch = self.ch.unwrap();
match ch {
't' => Ok('\t'),
'r' => Ok('\r'),
'n' => Ok('\n'),
'\\' => Ok('\\'),
'"' => Ok('"'),
_ => Err(ParserError::InvalidEscape)
}
}
fn parse_string(&mut self) -> ParserResult {
let mut out = String::with_capacity(32);
loop {
self.bump();
if self.is_eof() { return Err(ParserError::Eof) }
let ch = self.ch.unwrap();
if ch == '"' { break }
if ch == '\\' {
out.push(try!(self.parse_string_escape()));
continue;
}
out.push(self.ch.unwrap())
}
Ok(Value::String(out))
}
fn parse_symbol(&mut self) -> ParserResult {
let ident = try!(self.parse_ident());
if ident.prefix.is_none() {
Ok(match &*ident.name {
"nil" => Value::Nil,
"true" => Value::Bool(true),
"false" => Value::Bool(false),
_ => Value::Symbol(ident)
})
} else {
Ok(Value::Symbol(ident))
}
}
fn parse_keyword(&mut self) -> ParserResult {
self.bump();
Ok(Value::Keyword(try!(self.parse_ident())))
}
pub fn parse_value(&mut self) -> ParserResult {
self.consume_ws();
if self.is_eof() { return Err(ParserError::Eof) }
let ch = self.ch.unwrap();
if ch == '"' { return self.parse_string() }
if self.at_symbol() { return self.parse_symbol() }
if self.at_keyword() { return self.parse_keyword() }
unimplemented!()
}
}
fn is_ident_start_ch(ch: char) -> bool {
match ch {
'a'...'z' | 'A'...'Z' => true,
'*' | '!' | '_' | '?' | '$' | '%' | '&' | '=' | '<' | '>' => true,
'-' | '+' | '.' => true, // can also start a number literal, watch out!
_ => false
}
}
fn is_ident_ch(ch: char) -> bool {
is_ident_start_ch(ch) || ch == ':' || ch == '#' || (ch >= '0' && ch <= '9')
}
#[cfg(test)]
mod test {
use {Ident, Value};
use super::*;
macro_rules! assert_val {
($str:expr, $val:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert_eq!(parser.parse_value(), Ok($val))
})
}
macro_rules! assert_err {
($str:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert!(parser.parse_value().is_err())
});
($str:expr, $val:expr) => ({
let inp = $str.into_string();
let mut parser = Parser::new(inp.chars());
assert_eq!(parser.parse_value(), Err($val))
})
}
#[test]
fn test_parse_eof() {
assert_err!("", ParserError::Eof);
assert_err!(" ", ParserError::Eof);
assert_err!(",", ParserError::Eof);
}
#[test]
fn test_parse_nil() {
assert_val!("nil", Value::Nil);
assert_val!("nil ", Value::Nil);
}
#[test]
fn test_parse_bool() {
assert_val!("true", Value::Bool(true));
assert_val!("false", Value::Bool(false));
assert_val!("false,", Value::Bool(false));
}
#[test]
fn test_parse_str() {
assert_err!(r#" "foo "#, ParserError::Eof);
assert_val!(r#" "" "#, Value::String("".into_string()));
assert_val!(r#" "foo" "#, Value::String("foo".into_string()));
assert_val!(r#" "\n" "#, Value::String("\n".into_string()));
assert_val!(r#" "\"" "#, Value::String("\"".into_string()));
// multi-line
assert_val!(" \"foo\nbar\" ", Value::String("foo\nbar".into_string()));
}
#[test]
fn test_parse_symbol() {
assert_val!("foo", Value::Symbol(Ident::simple("foo")));
assert_val!("foo#", Value::Symbol(Ident::simple("foo#")));
assert_val!("foo9", Value::Symbol(Ident::simple("foo9")));
assert_val!("-foo", Value::Symbol(Ident::simple("-foo")));
assert_val!("foo/bar", Value::Symbol(Ident::prefixed("bar", "foo")));
assert_err!("foo/", ParserError::InvalidToken('/'));
// FIXME: the parser doesn't handle this correctly right now
// assert_err!("/bar", ParserError::InvalidToken('/'));
// tools.reader.edn parses this as a symbol
// assert_val!("ᛰ", Value::Symbol(Ident::simple("ᛰ")));
}
#[test]
fn test_parse_keyword() {
assert_err!(":", ParserError::Eof);
assert_err!(": foo", ParserError::InvalidToken(' '));
assert_val!(":foo", Value::Keyword(Ident::simple("foo")));
assert_val!(":-foo", Value::Keyword(Ident::simple("-foo")));
assert_val!(":1234", Value::Keyword(Ident::simple("1234")));
assert_val!(":12aaa", Value::Keyword(Ident::simple("12aaa")));
}
}
|
use notify::op;
use std::path::{Path, PathBuf};
use std::time::{SystemTime};
/// Info about a path and its corresponding `notify` event
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct PathOp {
pub path: PathBuf,
pub op: Option<op::Op>,
pub cookie: Option<u32>,
pub time: SystemTime,
}
impl PathOp {
pub fn new(path: &Path, op: Option<op::Op>, cookie: Option<u32>) -> PathOp {
PathOp {
path: path.to_path_buf(),
op: op,
cookie: cookie,
time: SystemTime::now(),
}
}
pub fn is_create(op_: op::Op) -> bool {
op_.contains(op::CREATE)
}
pub fn is_remove(op_: op::Op) -> bool {
op_.contains(op::REMOVE)
}
pub fn is_rename(op_: op::Op) -> bool {
op_.contains(op::RENAME)
}
pub fn is_write(op_: op::Op) -> bool {
let mut write_or_close_write = op::WRITE;
write_or_close_write.toggle(op::CLOSE_WRITE);
op_.intersects(write_or_close_write)
}
pub fn is_meta(op_: op::Op) -> bool {
op_.contains(op::CHMOD)
}
}
[pathop] Revert changes adding a time field
use notify::op;
use std::path::{Path, PathBuf};
/// Info about a path and its corresponding `notify` event
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct PathOp {
pub path: PathBuf,
pub op: Option<op::Op>,
pub cookie: Option<u32>,
}
impl PathOp {
pub fn new(path: &Path, op: Option<op::Op>, cookie: Option<u32>) -> PathOp {
PathOp {
path: path.to_path_buf(),
op: op,
cookie: cookie,
}
}
pub fn is_create(op_: op::Op) -> bool {
op_.contains(op::CREATE)
}
pub fn is_remove(op_: op::Op) -> bool {
op_.contains(op::REMOVE)
}
pub fn is_rename(op_: op::Op) -> bool {
op_.contains(op::RENAME)
}
pub fn is_write(op_: op::Op) -> bool {
let mut write_or_close_write = op::WRITE;
write_or_close_write.toggle(op::CLOSE_WRITE);
op_.intersects(write_or_close_write)
}
pub fn is_meta(op_: op::Op) -> bool {
op_.contains(op::CHMOD)
}
}
|
//! Pragma helpers
use std::ops::Deref;
use crate::error::Error;
use crate::ffi;
use crate::types::{ToSql, ToSqlOutput, ValueRef};
use crate::{Connection, DatabaseName, Result, Row, NO_PARAMS};
pub struct Sql {
buf: String,
}
impl Sql {
pub fn new() -> Sql {
Sql { buf: String::new() }
}
pub fn push_pragma(
&mut self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
) -> Result<()> {
self.push_keyword("PRAGMA")?;
self.push_space();
if let Some(schema_name) = schema_name {
self.push_schema_name(schema_name);
self.push_dot();
}
self.push_keyword(pragma_name)
}
pub fn push_keyword(&mut self, keyword: &str) -> Result<()> {
if !keyword.is_empty() && is_identifier(keyword) {
self.buf.push_str(keyword);
Ok(())
} else {
Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Invalid keyword \"{}\"", keyword)),
))
}
}
pub fn push_schema_name(&mut self, schema_name: DatabaseName<'_>) {
match schema_name {
DatabaseName::Main => self.buf.push_str("main"),
DatabaseName::Temp => self.buf.push_str("temp"),
DatabaseName::Attached(s) => self.push_identifier(s),
};
}
pub fn push_identifier(&mut self, s: &str) {
if is_identifier(s) {
self.buf.push_str(s);
} else {
self.wrap_and_escape(s, '"');
}
}
pub fn push_value(&mut self, value: &dyn ToSql) -> Result<()> {
let value = value.to_sql()?;
let value = match value {
ToSqlOutput::Borrowed(v) => v,
ToSqlOutput::Owned(ref v) => ValueRef::from(v),
#[cfg(feature = "blob")]
ToSqlOutput::ZeroBlob(_) => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
#[cfg(feature = "array")]
ToSqlOutput::Array(_) => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
};
match value {
ValueRef::Integer(i) => {
self.push_int(i);
}
ValueRef::Real(r) => {
self.push_real(r);
}
ValueRef::Text(s) => {
self.push_string_literal(s);
}
_ => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
};
Ok(())
}
pub fn push_string_literal(&mut self, s: &str) {
self.wrap_and_escape(s, '\'');
}
pub fn push_int(&mut self, i: i64) {
self.buf.push_str(&i.to_string());
}
pub fn push_real(&mut self, f: f64) {
self.buf.push_str(&f.to_string());
}
pub fn push_space(&mut self) {
self.buf.push(' ');
}
pub fn push_dot(&mut self) {
self.buf.push('.');
}
pub fn push_equal_sign(&mut self) {
self.buf.push('=');
}
pub fn open_brace(&mut self) {
self.buf.push('(');
}
pub fn close_brace(&mut self) {
self.buf.push(')');
}
pub fn as_str(&self) -> &str {
&self.buf
}
fn wrap_and_escape(&mut self, s: &str, quote: char) {
self.buf.push(quote);
let chars = s.chars();
for ch in chars {
// escape `quote` by doubling it
if ch == quote {
self.buf.push(ch);
}
self.buf.push(ch)
}
self.buf.push(quote);
}
}
impl Deref for Sql {
type Target = str;
fn deref(&self) -> &str {
self.as_str()
}
}
impl Connection {
/// Query the current value of `pragma_name`.
///
/// Some pragmas will return multiple rows/values which cannot be retrieved
/// with this method.
pub fn pragma_query_value<T, F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
f: F,
) -> Result<T>
where
F: FnOnce(Row<'_, '_>) -> Result<T>,
{
let mut query = Sql::new();
query.push_pragma(schema_name, pragma_name)?;
let mut stmt = self.prepare(&query)?;
let mut rows = stmt.query(NO_PARAMS)?;
if let Some(result_row) = rows.next() {
let row = result_row?;
f(row)
} else {
Err(Error::QueryReturnedNoRows)
}
}
/// Query the current rows/values of `pragma_name`.
pub fn pragma_query<F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
mut f: F,
) -> Result<()>
where
F: FnMut(&Row<'_, '_>) -> Result<()>,
{
let mut query = Sql::new();
query.push_pragma(schema_name, pragma_name)?;
let mut stmt = self.prepare(&query)?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(result_row) = rows.next() {
let row = result_row?;
f(&row)?;
}
Ok(())
}
/// Query the current value(s) of `pragma_name` associated to
/// `pragma_value`.
///
/// This method can be used with query-only pragmas which need an argument
/// (e.g. `table_info('one_tbl')`) or pragmas which return the updated value
/// (e.g. `journal_mode`).
pub fn pragma<F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
mut f: F,
) -> Result<()>
where
F: FnMut(&Row<'_, '_>) -> Result<()>,
{
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.open_brace();
sql.push_value(pragma_value)?;
sql.close_brace();
let mut stmt = self.prepare(&sql)?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(result_row) = rows.next() {
let row = result_row?;
f(&row)?;
}
Ok(())
}
/// Set a new value to `pragma_name`.
///
/// Some pragmas will return the updated value which cannot be retrieved
/// with this method.
pub fn pragma_update(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
) -> Result<()> {
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.push_equal_sign();
sql.push_value(pragma_value)?;
self.execute_batch(&sql)
}
/// Set a new value to `pragma_name` and return the updated value.
///
/// Only few pragmas automatically return the updated value.
pub fn pragma_update_and_check<F, T>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
f: F,
) -> Result<T>
where
F: FnOnce(Row<'_, '_>) -> Result<T>,
{
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.push_equal_sign();
sql.push_value(pragma_value)?;
let mut stmt = self.prepare(&sql)?;
let mut rows = stmt.query(NO_PARAMS)?;
if let Some(result_row) = rows.next() {
let row = result_row?;
f(row)
} else {
Err(Error::QueryReturnedNoRows)
}
}
}
fn is_identifier(s: &str) -> bool {
let chars = s.char_indices();
for (i, ch) in chars {
if i == 0 {
if !is_identifier_start(ch) {
return false;
}
} else if !is_identifier_continue(ch) {
return false;
}
}
true
}
fn is_identifier_start(c: char) -> bool {
(c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z') || c > '\x7F'
}
fn is_identifier_continue(c: char) -> bool {
c == '$'
|| (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'Z')
|| c == '_'
|| (c >= 'a' && c <= 'z')
|| c > '\x7F'
}
#[cfg(test)]
mod test {
use super::Sql;
use crate::pragma;
use crate::{Connection, DatabaseName};
#[test]
fn pragma_query_value() {
let db = Connection::open_in_memory().unwrap();
let user_version: i32 = db
.pragma_query_value(None, "user_version", |row| row.get_checked(0))
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma_query_no_schema() {
let db = Connection::open_in_memory().unwrap();
let mut user_version = -1;
db.pragma_query(None, "user_version", |row| {
user_version = row.get_checked(0)?;
Ok(())
})
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma_query_with_schema() {
let db = Connection::open_in_memory().unwrap();
let mut user_version = -1;
db.pragma_query(Some(DatabaseName::Main), "user_version", |row| {
user_version = row.get_checked(0)?;
Ok(())
})
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma() {
let db = Connection::open_in_memory().unwrap();
let mut columns = Vec::new();
db.pragma(None, "table_info", &"sqlite_master", |row| {
let column: String = row.get_checked(1)?;
columns.push(column);
Ok(())
})
.unwrap();
assert_eq!(5, columns.len());
}
#[test]
fn pragma_update() {
let db = Connection::open_in_memory().unwrap();
db.pragma_update(None, "user_version", &1).unwrap();
}
#[test]
fn pragma_update_and_check() {
let db = Connection::open_in_memory().unwrap();
let journal_mode: String = db
.pragma_update_and_check(None, "journal_mode", &"OFF", |row| row.get_checked(0))
.unwrap();
assert_eq!("off", &journal_mode);
}
#[test]
fn is_identifier() {
assert!(pragma::is_identifier("full"));
assert!(pragma::is_identifier("r2d2"));
assert!(!pragma::is_identifier("sp ce"));
assert!(!pragma::is_identifier("semi;colon"));
}
#[test]
fn double_quote() {
let mut sql = Sql::new();
sql.push_schema_name(DatabaseName::Attached(r#"schema";--"#));
assert_eq!(r#""schema"";--""#, sql.as_str());
}
#[test]
fn wrap_and_escape() {
let mut sql = Sql::new();
sql.push_string_literal("value'; --");
assert_eq!("'value''; --'", sql.as_str());
}
}
Suggest users to use PRAGMA function instead
//! Pragma helpers
use std::ops::Deref;
use crate::error::Error;
use crate::ffi;
use crate::types::{ToSql, ToSqlOutput, ValueRef};
use crate::{Connection, DatabaseName, Result, Row, NO_PARAMS};
pub struct Sql {
buf: String,
}
impl Sql {
pub fn new() -> Sql {
Sql { buf: String::new() }
}
pub fn push_pragma(
&mut self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
) -> Result<()> {
self.push_keyword("PRAGMA")?;
self.push_space();
if let Some(schema_name) = schema_name {
self.push_schema_name(schema_name);
self.push_dot();
}
self.push_keyword(pragma_name)
}
pub fn push_keyword(&mut self, keyword: &str) -> Result<()> {
if !keyword.is_empty() && is_identifier(keyword) {
self.buf.push_str(keyword);
Ok(())
} else {
Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Invalid keyword \"{}\"", keyword)),
))
}
}
pub fn push_schema_name(&mut self, schema_name: DatabaseName<'_>) {
match schema_name {
DatabaseName::Main => self.buf.push_str("main"),
DatabaseName::Temp => self.buf.push_str("temp"),
DatabaseName::Attached(s) => self.push_identifier(s),
};
}
pub fn push_identifier(&mut self, s: &str) {
if is_identifier(s) {
self.buf.push_str(s);
} else {
self.wrap_and_escape(s, '"');
}
}
pub fn push_value(&mut self, value: &dyn ToSql) -> Result<()> {
let value = value.to_sql()?;
let value = match value {
ToSqlOutput::Borrowed(v) => v,
ToSqlOutput::Owned(ref v) => ValueRef::from(v),
#[cfg(feature = "blob")]
ToSqlOutput::ZeroBlob(_) => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
#[cfg(feature = "array")]
ToSqlOutput::Array(_) => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
};
match value {
ValueRef::Integer(i) => {
self.push_int(i);
}
ValueRef::Real(r) => {
self.push_real(r);
}
ValueRef::Text(s) => {
self.push_string_literal(s);
}
_ => {
return Err(Error::SqliteFailure(
ffi::Error::new(ffi::SQLITE_MISUSE),
Some(format!("Unsupported value \"{:?}\"", value)),
));
}
};
Ok(())
}
pub fn push_string_literal(&mut self, s: &str) {
self.wrap_and_escape(s, '\'');
}
pub fn push_int(&mut self, i: i64) {
self.buf.push_str(&i.to_string());
}
pub fn push_real(&mut self, f: f64) {
self.buf.push_str(&f.to_string());
}
pub fn push_space(&mut self) {
self.buf.push(' ');
}
pub fn push_dot(&mut self) {
self.buf.push('.');
}
pub fn push_equal_sign(&mut self) {
self.buf.push('=');
}
pub fn open_brace(&mut self) {
self.buf.push('(');
}
pub fn close_brace(&mut self) {
self.buf.push(')');
}
pub fn as_str(&self) -> &str {
&self.buf
}
fn wrap_and_escape(&mut self, s: &str, quote: char) {
self.buf.push(quote);
let chars = s.chars();
for ch in chars {
// escape `quote` by doubling it
if ch == quote {
self.buf.push(ch);
}
self.buf.push(ch)
}
self.buf.push(quote);
}
}
impl Deref for Sql {
type Target = str;
fn deref(&self) -> &str {
self.as_str()
}
}
impl Connection {
/// Query the current value of `pragma_name`.
///
/// Some pragmas will return multiple rows/values which cannot be retrieved
/// with this method.
///
/// Prefer [PRAGMA function](https://sqlite.org/pragma.html#pragfunc) introduced in SQLite 3.20:
/// `SELECT user_version FROM pragma_user_version;`
pub fn pragma_query_value<T, F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
f: F,
) -> Result<T>
where
F: FnOnce(Row<'_, '_>) -> Result<T>,
{
let mut query = Sql::new();
query.push_pragma(schema_name, pragma_name)?;
let mut stmt = self.prepare(&query)?;
let mut rows = stmt.query(NO_PARAMS)?;
if let Some(result_row) = rows.next() {
let row = result_row?;
f(row)
} else {
Err(Error::QueryReturnedNoRows)
}
}
/// Query the current rows/values of `pragma_name`.
///
/// Prefer [PRAGMA function](https://sqlite.org/pragma.html#pragfunc) introduced in SQLite 3.20:
/// `SELECT * FROM pragma_collation_list;`
pub fn pragma_query<F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
mut f: F,
) -> Result<()>
where
F: FnMut(&Row<'_, '_>) -> Result<()>,
{
let mut query = Sql::new();
query.push_pragma(schema_name, pragma_name)?;
let mut stmt = self.prepare(&query)?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(result_row) = rows.next() {
let row = result_row?;
f(&row)?;
}
Ok(())
}
/// Query the current value(s) of `pragma_name` associated to
/// `pragma_value`.
///
/// This method can be used with query-only pragmas which need an argument
/// (e.g. `table_info('one_tbl')`) or pragmas which returns value(s)
/// (e.g. `integrity_check`).
///
/// Prefer [PRAGMA function](https://sqlite.org/pragma.html#pragfunc) introduced in SQLite 3.20:
/// `SELECT * FROM pragma_table_info(?);`
pub fn pragma<F>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
mut f: F,
) -> Result<()>
where
F: FnMut(&Row<'_, '_>) -> Result<()>,
{
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.open_brace();
sql.push_value(pragma_value)?;
sql.close_brace();
let mut stmt = self.prepare(&sql)?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(result_row) = rows.next() {
let row = result_row?;
f(&row)?;
}
Ok(())
}
/// Set a new value to `pragma_name`.
///
/// Some pragmas will return the updated value which cannot be retrieved
/// with this method.
pub fn pragma_update(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
) -> Result<()> {
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.push_equal_sign();
sql.push_value(pragma_value)?;
self.execute_batch(&sql)
}
/// Set a new value to `pragma_name` and return the updated value.
///
/// Only few pragmas automatically return the updated value.
pub fn pragma_update_and_check<F, T>(
&self,
schema_name: Option<DatabaseName<'_>>,
pragma_name: &str,
pragma_value: &dyn ToSql,
f: F,
) -> Result<T>
where
F: FnOnce(Row<'_, '_>) -> Result<T>,
{
let mut sql = Sql::new();
sql.push_pragma(schema_name, pragma_name)?;
// The argument is may be either in parentheses
// or it may be separated from the pragma name by an equal sign.
// The two syntaxes yield identical results.
sql.push_equal_sign();
sql.push_value(pragma_value)?;
let mut stmt = self.prepare(&sql)?;
let mut rows = stmt.query(NO_PARAMS)?;
if let Some(result_row) = rows.next() {
let row = result_row?;
f(row)
} else {
Err(Error::QueryReturnedNoRows)
}
}
}
fn is_identifier(s: &str) -> bool {
let chars = s.char_indices();
for (i, ch) in chars {
if i == 0 {
if !is_identifier_start(ch) {
return false;
}
} else if !is_identifier_continue(ch) {
return false;
}
}
true
}
fn is_identifier_start(c: char) -> bool {
(c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z') || c > '\x7F'
}
fn is_identifier_continue(c: char) -> bool {
c == '$'
|| (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'Z')
|| c == '_'
|| (c >= 'a' && c <= 'z')
|| c > '\x7F'
}
#[cfg(test)]
mod test {
use super::Sql;
use crate::pragma;
use crate::{Connection, DatabaseName, NO_PARAMS};
#[test]
fn pragma_query_value() {
let db = Connection::open_in_memory().unwrap();
let user_version: i32 = db
.pragma_query_value(None, "user_version", |row| row.get_checked(0))
.unwrap();
assert_eq!(0, user_version);
}
#[test]
#[cfg(feature = "bundled")]
fn pragma_func_query_value() {
let db = Connection::open_in_memory().unwrap();
let user_version: i32 = db
.query_row(
"SELECT user_version FROM pragma_user_version",
NO_PARAMS,
|row| row.get(0),
)
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma_query_no_schema() {
let db = Connection::open_in_memory().unwrap();
let mut user_version = -1;
db.pragma_query(None, "user_version", |row| {
user_version = row.get_checked(0)?;
Ok(())
})
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma_query_with_schema() {
let db = Connection::open_in_memory().unwrap();
let mut user_version = -1;
db.pragma_query(Some(DatabaseName::Main), "user_version", |row| {
user_version = row.get_checked(0)?;
Ok(())
})
.unwrap();
assert_eq!(0, user_version);
}
#[test]
fn pragma() {
let db = Connection::open_in_memory().unwrap();
let mut columns = Vec::new();
db.pragma(None, "table_info", &"sqlite_master", |row| {
let column: String = row.get_checked(1)?;
columns.push(column);
Ok(())
})
.unwrap();
assert_eq!(5, columns.len());
}
#[test]
#[cfg(feature = "bundled")]
fn pragma_func() {
let db = Connection::open_in_memory().unwrap();
let mut table_info = db.prepare("SELECT * FROM pragma_table_info(?)").unwrap();
let mut columns = Vec::new();
let mut rows = table_info.query(&["sqlite_master"]).unwrap();
while let Some(row) = rows.next() {
let row = row.unwrap();
let column: String = row.get(1);
columns.push(column);
}
assert_eq!(5, columns.len());
}
#[test]
fn pragma_update() {
let db = Connection::open_in_memory().unwrap();
db.pragma_update(None, "user_version", &1).unwrap();
}
#[test]
fn pragma_update_and_check() {
let db = Connection::open_in_memory().unwrap();
let journal_mode: String = db
.pragma_update_and_check(None, "journal_mode", &"OFF", |row| row.get_checked(0))
.unwrap();
assert_eq!("off", &journal_mode);
}
#[test]
fn is_identifier() {
assert!(pragma::is_identifier("full"));
assert!(pragma::is_identifier("r2d2"));
assert!(!pragma::is_identifier("sp ce"));
assert!(!pragma::is_identifier("semi;colon"));
}
#[test]
fn double_quote() {
let mut sql = Sql::new();
sql.push_schema_name(DatabaseName::Attached(r#"schema";--"#));
assert_eq!(r#""schema"";--""#, sql.as_str());
}
#[test]
fn wrap_and_escape() {
let mut sql = Sql::new();
sql.push_string_literal("value'; --");
assert_eq!("'value''; --'", sql.as_str());
}
}
|
// This file is part of sokoban-rs
// Copyright 2015 Sébastien Watteau
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::Rect;
use sdl2::render::{Canvas, Texture};
use sdl2::ttf::{Font, Sdl2TtfContext};
use sdl2::video::Window;
use std::cmp;
use std::path::Path;
use game::{Direction, Level, Position};
/// The Drawer struct is responsible for drawing the game onto the screen.
pub struct Drawer<'a> {
/// The active tileset
tileset: TileSetSwitch<'a>,
/// The font used to display text
font: Font<'a, 'a>,
/// The size of the screen in pixels
screen_size: (u32, u32),
/// The height of the status bar
bar_height: u32,
/// The color of the status bar
bar_color: Color,
/// The color of the text in the status bar
bar_text_color: Color,
}
/// Represents a location for text in the status bar
enum StatusBarLocation {
FlushLeft,
FlushRight,
}
impl<'a> Drawer<'a> {
/// Creates a new Drawer instance.
pub fn new(
canvas: &mut Canvas<Window>,
big: &'a Texture,
small: &'a Texture,
ttf_context: &'a Sdl2TtfContext,
) -> Drawer<'a> {
let font = {
let ttf = Path::new("assets/font/RujisHandwritingFontv.2.0.ttf");
ttf_context.load_font(&ttf, 20).unwrap()
};
let screen_size = canvas.window().drawable_size();
let tileset = TileSetSwitch::new(big, small);
Drawer {
tileset: tileset,
font: font,
screen_size: screen_size,
bar_height: 32,
bar_color: Color::RGBA(20, 20, 20, 255),
bar_text_color: Color::RGBA(255, 192, 0, 255),
}
}
/// Draws a level onto the screen.
pub fn draw(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
self.tileset.set_extents(level.extents());
// Draw a full-size image onto an off-screen buffer
let fullsize = self.tileset.select().get_rendering_size(level.extents());
let creator = canvas.texture_creator();
let mut texture = creator
.create_texture_target(PixelFormatEnum::RGBA8888, fullsize.0, fullsize.1)
.expect("Could not get texture target for off-screen rendering");
canvas
.with_texture_canvas(&mut texture, |cv| {
self.draw_fullsize(cv, level);
})
.unwrap();
// Copy onto the screen with appropriate scaling
let final_rect = self.get_centered_image_rect(self.get_scaled_rendering_size(&level));
canvas.clear();
let original_rect = Some(Rect::new(0, 0, fullsize.0, fullsize.1));
canvas.copy(&texture, original_rect, final_rect).unwrap();
self.draw_status_bar(canvas, &level);
canvas.present();
}
/// Draws a full-size image of the given level onto the current render target.
fn draw_fullsize(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
let (cols, rows) = level.extents();
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
for r in 0..rows {
for c in 0..cols {
let pos = Position::new(r, c);
let (x, y) = self.tileset.select().get_coordinates(&pos);
// First draw the floor tiles
if level.is_square(&pos) {
self.draw_tile(canvas, Tile::Square, x, y);
} else {
self.draw_tile(canvas, Tile::Floor, x, y);
}
// Add the shadows
let flags = get_shadow_flags(&level, &pos);
for f in &[
ShadowFlags::N_EDGE,
ShadowFlags::S_EDGE,
ShadowFlags::E_EDGE,
ShadowFlags::W_EDGE,
ShadowFlags::NE_CORNER,
ShadowFlags::NW_CORNER,
ShadowFlags::SE_CORNER,
ShadowFlags::SW_CORNER,
] {
if flags.contains(*f) {
self.draw_tile(canvas, Tile::Shadow(*f), x, y);
}
}
// Draw the other items
let z = y - self.tileset.select().tile_offset();
if level.is_wall(&pos) {
self.draw_tile(canvas, Tile::Wall, x, z);
}
if level.is_box(&pos) {
self.draw_tile(canvas, Tile::Rock, x, z);
}
if level.is_player(&pos) {
self.draw_tile(canvas, Tile::Player, x, z);
}
}
}
}
/// Draws the status bar
fn draw_status_bar(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
let prev_color = canvas.draw_color();
canvas.set_draw_color(self.bar_color);
let rect = Rect::new(
0,
(self.screen_size.1 - self.bar_height) as i32,
self.screen_size.0,
self.bar_height,
);
canvas.fill_rect(rect).unwrap();
canvas.set_draw_color(prev_color);
// Draw the number of moves
let s = format!("# moves: {}", level.get_steps());
self.draw_status_text(canvas, &s, StatusBarLocation::FlushLeft);
// Draw the level's title
self.draw_status_text(canvas, level.title(), StatusBarLocation::FlushRight);
}
/// Draws text in the status bar
fn draw_status_text(
&mut self,
canvas: &mut Canvas<Window>,
text: &str,
location: StatusBarLocation,
) {
let surface = self.font.render(text).blended(self.bar_text_color).unwrap();
let creator = canvas.texture_creator();
let texture = creator.create_texture_from_surface(&surface).unwrap();
let margin = 4;
let (w, h) = {
let q = texture.query();
(q.width, q.height)
};
let (x, y) = match location {
StatusBarLocation::FlushLeft => {
(margin as i32, (self.screen_size.1 - margin - h) as i32)
}
StatusBarLocation::FlushRight => (
(self.screen_size.0 - margin - w) as i32,
(self.screen_size.1 - margin - h) as i32,
),
};
canvas
.copy(&texture, None, Some(Rect::new(x, y, w, h)))
.unwrap();
}
/// Draws a tile at the given coordinates.
fn draw_tile(&mut self, canvas: &mut Canvas<Window>, tile: Tile, x: i32, y: i32) {
let (col, row) = self.tileset.select().location(tile).unwrap_or_else(|| {
panic!("No image for this tile: {:?}", tile);
});
let tile_rect = self.tileset.select().get_tile_rect(col, row);
let target_rect = Some(Rect::new(
x,
y,
self.tileset.select().tile_width(),
self.tileset.select().tile_height(),
));
canvas
.copy(self.tileset.select().texture(), tile_rect, target_rect)
.unwrap();
}
/// Returns the size of the drawing scaled to fit onto the screen.
fn get_scaled_rendering_size(&self, level: &Level) -> (u32, u32) {
let render_size = self.tileset.select().get_rendering_size(level.extents());
let width_ratio = (self.screen_size.0 as f64) / (render_size.0 as f64);
let h = self.screen_size.1 - self.bar_height;
let height_ratio = (h as f64) / (render_size.1 as f64);
let ratio = f64::min(1.0, f64::min(width_ratio, height_ratio));
let scale = |sz: u32| (ratio * (sz as f64)).floor() as u32;
(scale(render_size.0), scale(render_size.1))
}
/// Returns the Rect of an image of given dimensions so that it's centered on the screen.
fn get_centered_image_rect(&self, img_size: (u32, u32)) -> Option<Rect> {
let x = (self.screen_size.0 - img_size.0) as i32 / 2;
let y = (self.screen_size.1 - self.bar_height - img_size.1) as i32 / 2;
Some(Rect::new(x, y, img_size.0, img_size.1))
}
}
/// Represents a kind of tile.
#[derive(Copy, Clone, Debug)]
enum Tile {
/// Standard floor tile
Floor,
/// Wall tile
Wall,
/// Rock tile
Rock,
/// Target square tile
Square,
/// Player tile
Player,
/// Shadow tile
Shadow(ShadowFlags),
}
/// Holds information about a tileset.
trait TileSet {
/// Returns the associated texture
fn texture(&self) -> &Texture;
/// Returns the width of a tile.
fn tile_width(&self) -> u32;
/// Returns the height of a tile.
fn tile_height(&self) -> u32;
/// Returns the effective height of a tile (used for stacking)
fn tile_effective_height(&self) -> u32;
/// Returns the offset need to draw items on the floor.
fn tile_offset(&self) -> i32;
/// Returns the location of the tile in the tileset texture.
fn location(&self, tile: Tile) -> Option<(u32, u32)> {
match tile {
Tile::Floor => Some((0, 0)),
Tile::Wall => Some((0, 2)),
Tile::Rock => Some((2, 0)),
Tile::Square => Some((1, 0)),
Tile::Player => Some((3, 0)),
Tile::Shadow(ShadowFlags::N_EDGE) => Some((4, 0)),
Tile::Shadow(ShadowFlags::S_EDGE) => Some((5, 0)),
Tile::Shadow(ShadowFlags::E_EDGE) => Some((0, 1)),
Tile::Shadow(ShadowFlags::W_EDGE) => Some((1, 1)),
Tile::Shadow(ShadowFlags::NE_CORNER) => Some((2, 1)),
Tile::Shadow(ShadowFlags::NW_CORNER) => Some((3, 1)),
Tile::Shadow(ShadowFlags::SE_CORNER) => Some((4, 1)),
Tile::Shadow(ShadowFlags::SW_CORNER) => Some((5, 1)),
Tile::Shadow(ShadowFlags { .. }) => None,
}
}
/// Returns the top-left corner coordinates of the tile corresponding
/// to the given position.
fn get_coordinates(&self, pos: &Position) -> (i32, i32) {
let x = self.tile_width() as i32 * pos.column();
let y = self.tile_effective_height() as i32 * pos.row();
(x, y)
}
/// Returns the full size needed to draw a level of the given dimensions.
fn get_rendering_size(&self, extents: (i32, i32)) -> (u32, u32) {
let width = extents.0 as u32 * self.tile_width();
let height = if extents.1 > 0 {
self.tile_height() + (extents.1 - 1) as u32 * self.tile_effective_height()
} else {
0
};
(width, height)
}
/// Returns the Rect of the tile located at the given row and column in the texture.
fn get_tile_rect(&self, col: u32, row: u32) -> Option<Rect> {
let (w, h) = (self.tile_width(), self.tile_height());
let x = (col * w) as i32;
let y = (row * h) as i32;
Some(Rect::new(x, y, w, h))
}
}
// A macro to generate the tilesets
macro_rules! decl_tileset {
($name:ident, $path:expr, $width:expr, $height:expr, $effective_height:expr, $offset:expr) => {
struct $name<'a> {
texture: &'a Texture<'a>,
}
impl<'a> $name<'a> {
pub fn new(texture: &'a Texture) -> Self {
$name { texture: texture }
}
}
impl<'a> TileSet for $name<'a> {
fn texture(&self) -> &Texture {
&self.texture
}
fn tile_width(&self) -> u32 {
$width
}
fn tile_height(&self) -> u32 {
$height
}
fn tile_effective_height(&self) -> u32 {
$effective_height
}
fn tile_offset(&self) -> i32 {
$offset
}
}
};
}
decl_tileset!(BigTileSet, "assets/image/tileset.png", 101, 171, 83, 40);
decl_tileset!(
SmallTileSet,
"assets/image/tileset-small.png",
50,
85,
41,
20
);
/// Enables switching between two tilesets.
struct TileSetSwitch<'a> {
/// The limit value for switching
limit: i32,
/// The extents of the current level
extents: (i32, i32),
/// The small tileset
tileset_small: SmallTileSet<'a>,
/// The big tileset
tileset_big: BigTileSet<'a>,
}
impl<'a> TileSetSwitch<'a> {
/// Creates a new instance.
pub fn new(big: &'a Texture, small: &'a Texture) -> Self {
TileSetSwitch {
limit: 40,
extents: (0, 0),
tileset_big: BigTileSet::new(big),
tileset_small: SmallTileSet::new(small),
}
}
/// Updates the switch with the given extents.
pub fn set_extents(&mut self, extents: (i32, i32)) {
self.extents = extents;
}
pub fn select(&self) -> &TileSet {
if cmp::max(self.extents.0, self.extents.1) > self.limit {
&self.tileset_small
} else {
&self.tileset_big
}
}
}
bitflags!(
/// Represents the different kind of shadows that can be cast
/// onto a floor tile.
struct ShadowFlags: i32 {
/// North edge
const N_EDGE = 0x1;
/// South edge
const S_EDGE = 0x2;
/// East edge
const E_EDGE = 0x4;
/// West edge
const W_EDGE = 0x8;
/// North East corner
const NE_CORNER = 0x10;
/// North West corner
const NW_CORNER = 0x20;
/// South East corner
const SE_CORNER = 0x40;
/// South West corner
const SW_CORNER = 0x80;
}
);
/// Returns the shadow flags for a particular position in the given level.
fn get_shadow_flags(level: &Level, pos: &Position) -> ShadowFlags {
let north = pos.neighbor(Direction::Up);
let south = pos.neighbor(Direction::Down);
let west = pos.neighbor(Direction::Left);
let east = pos.neighbor(Direction::Right);
let mut flags = ShadowFlags::empty();
if level.is_wall(&north) {
flags = flags | ShadowFlags::N_EDGE;
}
if level.is_wall(&south) {
flags = flags | ShadowFlags::S_EDGE;
}
if level.is_wall(&west) {
flags = flags | ShadowFlags::W_EDGE;
}
if level.is_wall(&east) {
flags = flags | ShadowFlags::E_EDGE;
}
if level.is_wall(&north.neighbor(Direction::Right))
&& !flags.intersects(ShadowFlags::N_EDGE | ShadowFlags::E_EDGE)
{
flags = flags | ShadowFlags::NE_CORNER;
}
if level.is_wall(&north.neighbor(Direction::Left))
&& !flags.intersects(ShadowFlags::N_EDGE | ShadowFlags::W_EDGE)
{
flags = flags | ShadowFlags::NW_CORNER;
}
if level.is_wall(&south.neighbor(Direction::Right))
&& !flags.intersects(ShadowFlags::S_EDGE | ShadowFlags::E_EDGE)
{
flags = flags | ShadowFlags::SE_CORNER;
}
if level.is_wall(&south.neighbor(Direction::Left))
&& !flags.intersects(ShadowFlags::S_EDGE | ShadowFlags::W_EDGE)
{
flags = flags | ShadowFlags::SW_CORNER;
}
flags
}
Added tileset helper function
// This file is part of sokoban-rs
// Copyright 2015 Sébastien Watteau
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::Rect;
use sdl2::render::{Canvas, Texture};
use sdl2::ttf::{Font, Sdl2TtfContext};
use sdl2::video::Window;
use std::cmp;
use std::path::Path;
use game::{Direction, Level, Position};
/// The Drawer struct is responsible for drawing the game onto the screen.
pub struct Drawer<'a> {
/// The active tileset
tileset: TileSetSwitch<'a>,
/// The font used to display text
font: Font<'a, 'a>,
/// The size of the screen in pixels
screen_size: (u32, u32),
/// The height of the status bar
bar_height: u32,
/// The color of the status bar
bar_color: Color,
/// The color of the text in the status bar
bar_text_color: Color,
}
/// Represents a location for text in the status bar
enum StatusBarLocation {
FlushLeft,
FlushRight,
}
impl<'a> Drawer<'a> {
/// Creates a new Drawer instance.
pub fn new(
canvas: &mut Canvas<Window>,
big: &'a Texture,
small: &'a Texture,
ttf_context: &'a Sdl2TtfContext,
) -> Drawer<'a> {
let font = {
let ttf = Path::new("assets/font/RujisHandwritingFontv.2.0.ttf");
ttf_context.load_font(&ttf, 20).unwrap()
};
let screen_size = canvas.window().drawable_size();
let tileset = TileSetSwitch::new(big, small);
Drawer {
tileset: tileset,
font: font,
screen_size: screen_size,
bar_height: 32,
bar_color: Color::RGBA(20, 20, 20, 255),
bar_text_color: Color::RGBA(255, 192, 0, 255),
}
}
/// Draws a level onto the screen.
pub fn draw(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
self.tileset.set_extents(level.extents());
// Draw a full-size image onto an off-screen buffer
let fullsize = self.tileset().get_rendering_size(level.extents());
let creator = canvas.texture_creator();
let mut texture = creator
.create_texture_target(PixelFormatEnum::RGBA8888, fullsize.0, fullsize.1)
.expect("Could not get texture target for off-screen rendering");
canvas
.with_texture_canvas(&mut texture, |cv| {
self.draw_fullsize(cv, level);
})
.unwrap();
// Copy onto the screen with appropriate scaling
let final_rect = self.get_centered_image_rect(self.get_scaled_rendering_size(&level));
canvas.clear();
let original_rect = Some(Rect::new(0, 0, fullsize.0, fullsize.1));
canvas.copy(&texture, original_rect, final_rect).unwrap();
self.draw_status_bar(canvas, &level);
canvas.present();
}
/// Draws a full-size image of the given level onto the current render target.
fn draw_fullsize(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
let (cols, rows) = level.extents();
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
for r in 0..rows {
for c in 0..cols {
let pos = Position::new(r, c);
let (x, y) = self.tileset().get_coordinates(&pos);
// First draw the floor tiles
if level.is_square(&pos) {
self.draw_tile(canvas, Tile::Square, x, y);
} else {
self.draw_tile(canvas, Tile::Floor, x, y);
}
// Add the shadows
let flags = get_shadow_flags(&level, &pos);
for f in &[
ShadowFlags::N_EDGE,
ShadowFlags::S_EDGE,
ShadowFlags::E_EDGE,
ShadowFlags::W_EDGE,
ShadowFlags::NE_CORNER,
ShadowFlags::NW_CORNER,
ShadowFlags::SE_CORNER,
ShadowFlags::SW_CORNER,
] {
if flags.contains(*f) {
self.draw_tile(canvas, Tile::Shadow(*f), x, y);
}
}
// Draw the other items
let z = y - self.tileset().tile_offset();
if level.is_wall(&pos) {
self.draw_tile(canvas, Tile::Wall, x, z);
}
if level.is_box(&pos) {
self.draw_tile(canvas, Tile::Rock, x, z);
}
if level.is_player(&pos) {
self.draw_tile(canvas, Tile::Player, x, z);
}
}
}
}
/// Draws the status bar
fn draw_status_bar(&mut self, canvas: &mut Canvas<Window>, level: &Level) {
let prev_color = canvas.draw_color();
canvas.set_draw_color(self.bar_color);
let rect = Rect::new(
0,
(self.screen_size.1 - self.bar_height) as i32,
self.screen_size.0,
self.bar_height,
);
canvas.fill_rect(rect).unwrap();
canvas.set_draw_color(prev_color);
// Draw the number of moves
let s = format!("# moves: {}", level.get_steps());
self.draw_status_text(canvas, &s, StatusBarLocation::FlushLeft);
// Draw the level's title
self.draw_status_text(canvas, level.title(), StatusBarLocation::FlushRight);
}
/// Draws text in the status bar
fn draw_status_text(
&mut self,
canvas: &mut Canvas<Window>,
text: &str,
location: StatusBarLocation,
) {
let surface = self.font.render(text).blended(self.bar_text_color).unwrap();
let creator = canvas.texture_creator();
let texture = creator.create_texture_from_surface(&surface).unwrap();
let margin = 4;
let (w, h) = {
let q = texture.query();
(q.width, q.height)
};
let (x, y) = match location {
StatusBarLocation::FlushLeft => {
(margin as i32, (self.screen_size.1 - margin - h) as i32)
}
StatusBarLocation::FlushRight => (
(self.screen_size.0 - margin - w) as i32,
(self.screen_size.1 - margin - h) as i32,
),
};
canvas
.copy(&texture, None, Some(Rect::new(x, y, w, h)))
.unwrap();
}
/// Draws a tile at the given coordinates.
fn draw_tile(&mut self, canvas: &mut Canvas<Window>, tile: Tile, x: i32, y: i32) {
let (col, row) = self.tileset().location(tile).unwrap_or_else(|| {
panic!("No image for this tile: {:?}", tile);
});
let tile_rect = self.tileset().get_tile_rect(col, row);
let target_rect = Some(Rect::new(
x,
y,
self.tileset().tile_width(),
self.tileset().tile_height(),
));
canvas
.copy(self.tileset().texture(), tile_rect, target_rect)
.unwrap();
}
/// Returns the size of the drawing scaled to fit onto the screen.
fn get_scaled_rendering_size(&self, level: &Level) -> (u32, u32) {
let render_size = self.tileset().get_rendering_size(level.extents());
let width_ratio = (self.screen_size.0 as f64) / (render_size.0 as f64);
let h = self.screen_size.1 - self.bar_height;
let height_ratio = (h as f64) / (render_size.1 as f64);
let ratio = f64::min(1.0, f64::min(width_ratio, height_ratio));
let scale = |sz: u32| (ratio * (sz as f64)).floor() as u32;
(scale(render_size.0), scale(render_size.1))
}
/// Returns the Rect of an image of given dimensions so that it's centered on the screen.
fn get_centered_image_rect(&self, img_size: (u32, u32)) -> Option<Rect> {
let x = (self.screen_size.0 - img_size.0) as i32 / 2;
let y = (self.screen_size.1 - self.bar_height - img_size.1) as i32 / 2;
Some(Rect::new(x, y, img_size.0, img_size.1))
}
fn tileset(&self) -> &TileSet {
self.tileset.select()
}
}
/// Represents a kind of tile.
#[derive(Copy, Clone, Debug)]
enum Tile {
/// Standard floor tile
Floor,
/// Wall tile
Wall,
/// Rock tile
Rock,
/// Target square tile
Square,
/// Player tile
Player,
/// Shadow tile
Shadow(ShadowFlags),
}
/// Holds information about a tileset.
trait TileSet {
/// Returns the associated texture
fn texture(&self) -> &Texture;
/// Returns the width of a tile.
fn tile_width(&self) -> u32;
/// Returns the height of a tile.
fn tile_height(&self) -> u32;
/// Returns the effective height of a tile (used for stacking)
fn tile_effective_height(&self) -> u32;
/// Returns the offset need to draw items on the floor.
fn tile_offset(&self) -> i32;
/// Returns the location of the tile in the tileset texture.
fn location(&self, tile: Tile) -> Option<(u32, u32)> {
match tile {
Tile::Floor => Some((0, 0)),
Tile::Wall => Some((0, 2)),
Tile::Rock => Some((2, 0)),
Tile::Square => Some((1, 0)),
Tile::Player => Some((3, 0)),
Tile::Shadow(ShadowFlags::N_EDGE) => Some((4, 0)),
Tile::Shadow(ShadowFlags::S_EDGE) => Some((5, 0)),
Tile::Shadow(ShadowFlags::E_EDGE) => Some((0, 1)),
Tile::Shadow(ShadowFlags::W_EDGE) => Some((1, 1)),
Tile::Shadow(ShadowFlags::NE_CORNER) => Some((2, 1)),
Tile::Shadow(ShadowFlags::NW_CORNER) => Some((3, 1)),
Tile::Shadow(ShadowFlags::SE_CORNER) => Some((4, 1)),
Tile::Shadow(ShadowFlags::SW_CORNER) => Some((5, 1)),
Tile::Shadow(ShadowFlags { .. }) => None,
}
}
/// Returns the top-left corner coordinates of the tile corresponding
/// to the given position.
fn get_coordinates(&self, pos: &Position) -> (i32, i32) {
let x = self.tile_width() as i32 * pos.column();
let y = self.tile_effective_height() as i32 * pos.row();
(x, y)
}
/// Returns the full size needed to draw a level of the given dimensions.
fn get_rendering_size(&self, extents: (i32, i32)) -> (u32, u32) {
let width = extents.0 as u32 * self.tile_width();
let height = if extents.1 > 0 {
self.tile_height() + (extents.1 - 1) as u32 * self.tile_effective_height()
} else {
0
};
(width, height)
}
/// Returns the Rect of the tile located at the given row and column in the texture.
fn get_tile_rect(&self, col: u32, row: u32) -> Option<Rect> {
let (w, h) = (self.tile_width(), self.tile_height());
let x = (col * w) as i32;
let y = (row * h) as i32;
Some(Rect::new(x, y, w, h))
}
}
// A macro to generate the tilesets
macro_rules! decl_tileset {
($name:ident, $path:expr, $width:expr, $height:expr, $effective_height:expr, $offset:expr) => {
struct $name<'a> {
texture: &'a Texture<'a>,
}
impl<'a> $name<'a> {
pub fn new(texture: &'a Texture) -> Self {
$name { texture: texture }
}
}
impl<'a> TileSet for $name<'a> {
fn texture(&self) -> &Texture {
&self.texture
}
fn tile_width(&self) -> u32 {
$width
}
fn tile_height(&self) -> u32 {
$height
}
fn tile_effective_height(&self) -> u32 {
$effective_height
}
fn tile_offset(&self) -> i32 {
$offset
}
}
};
}
decl_tileset!(BigTileSet, "assets/image/tileset.png", 101, 171, 83, 40);
decl_tileset!(
SmallTileSet,
"assets/image/tileset-small.png",
50,
85,
41,
20
);
/// Enables switching between two tilesets.
struct TileSetSwitch<'a> {
/// The limit value for switching
limit: i32,
/// The extents of the current level
extents: (i32, i32),
/// The small tileset
tileset_small: SmallTileSet<'a>,
/// The big tileset
tileset_big: BigTileSet<'a>,
}
impl<'a> TileSetSwitch<'a> {
/// Creates a new instance.
pub fn new(big: &'a Texture, small: &'a Texture) -> Self {
TileSetSwitch {
limit: 40,
extents: (0, 0),
tileset_big: BigTileSet::new(big),
tileset_small: SmallTileSet::new(small),
}
}
/// Updates the switch with the given extents.
pub fn set_extents(&mut self, extents: (i32, i32)) {
self.extents = extents;
}
pub fn select(&self) -> &TileSet {
if cmp::max(self.extents.0, self.extents.1) > self.limit {
&self.tileset_small
} else {
&self.tileset_big
}
}
}
bitflags!(
/// Represents the different kind of shadows that can be cast
/// onto a floor tile.
struct ShadowFlags: i32 {
/// North edge
const N_EDGE = 0x1;
/// South edge
const S_EDGE = 0x2;
/// East edge
const E_EDGE = 0x4;
/// West edge
const W_EDGE = 0x8;
/// North East corner
const NE_CORNER = 0x10;
/// North West corner
const NW_CORNER = 0x20;
/// South East corner
const SE_CORNER = 0x40;
/// South West corner
const SW_CORNER = 0x80;
}
);
/// Returns the shadow flags for a particular position in the given level.
fn get_shadow_flags(level: &Level, pos: &Position) -> ShadowFlags {
let north = pos.neighbor(Direction::Up);
let south = pos.neighbor(Direction::Down);
let west = pos.neighbor(Direction::Left);
let east = pos.neighbor(Direction::Right);
let mut flags = ShadowFlags::empty();
if level.is_wall(&north) {
flags = flags | ShadowFlags::N_EDGE;
}
if level.is_wall(&south) {
flags = flags | ShadowFlags::S_EDGE;
}
if level.is_wall(&west) {
flags = flags | ShadowFlags::W_EDGE;
}
if level.is_wall(&east) {
flags = flags | ShadowFlags::E_EDGE;
}
if level.is_wall(&north.neighbor(Direction::Right))
&& !flags.intersects(ShadowFlags::N_EDGE | ShadowFlags::E_EDGE)
{
flags = flags | ShadowFlags::NE_CORNER;
}
if level.is_wall(&north.neighbor(Direction::Left))
&& !flags.intersects(ShadowFlags::N_EDGE | ShadowFlags::W_EDGE)
{
flags = flags | ShadowFlags::NW_CORNER;
}
if level.is_wall(&south.neighbor(Direction::Right))
&& !flags.intersects(ShadowFlags::S_EDGE | ShadowFlags::E_EDGE)
{
flags = flags | ShadowFlags::SE_CORNER;
}
if level.is_wall(&south.neighbor(Direction::Left))
&& !flags.intersects(ShadowFlags::S_EDGE | ShadowFlags::W_EDGE)
{
flags = flags | ShadowFlags::SW_CORNER;
}
flags
}
|
extern crate termion;
use termion::raw::*;
use termion::clear;
use termion::color;
use termion::input::MouseTerminal;
use actor::*;
use floor::*;
use world::*;
use primitive::*;
use std::io::{Write, stdout};
use std::sync::*;
use std::thread;
use std::time::Duration;
fn render_floor<W : Write>(screen : &mut W, floor: &Floor) {
for row in &floor.tiles {
let mut line = String::new();
for tile in row {
if let Some(ref wall) = tile.wall {
line.push_str(wall);
} else {
line.push_str(" "); // U-2027
//line.push_str("‧"); // U-2027
}
}
write!(screen, "{}\n\r", line).unwrap(); // U-2502
}
}
fn goto_cursor_coord(coord : &Coord) -> termion::cursor::Goto {
// Coordinate translation naively assumes floor is being rendered at 1,1
termion::cursor::Goto(coord.col+1, coord.row+1)
}
pub fn render_loop(world_mutex : Arc<Mutex<World>>, stop : Arc<Mutex<bool>>, dirty_coord_rx : mpsc::Receiver<Coord>) {
let mut screen = MouseTerminal::from(stdout().into_raw_mode().unwrap());
// Hide the cursor, clear the screen
write!(screen, "{}{}", termion::cursor::Hide, termion::clear::All).unwrap();
{
write!(screen, "{}", termion::cursor::Goto(1, 1)).unwrap();
let world = world_mutex.lock().unwrap();
render_floor(&mut screen, &world.floor);
}
// Render Loop
loop {
// Time to stop?
{
let stop = stop.lock().unwrap();
if *stop {
break;
}
}
let world = world_mutex.lock().unwrap();
// Redraw any dirty world coordinates
while let Ok(coord) = dirty_coord_rx.try_recv() {
write!(screen, "{}{}", goto_cursor_coord(&coord), world.floor.get_symbol(&coord)).unwrap();
}
// Render Player
write!(screen, "{}", goto_cursor_coord(&world.player.coord())).unwrap();
write!(screen, "{}", &world.player.symbol()).unwrap();
// Render Monsters
for monster in &world.monsters {
write!(screen, "{}", goto_cursor_coord(monster.coord())).unwrap();
write!(screen, "{}", monster.symbol()).unwrap();
}
// Bottom text
write!(screen, "{}", termion::cursor::Goto(1, (world.floor.rows+1) as u16)).unwrap();
write!(screen, "{}\n\r\n\r", world.floor.name).unwrap(); // Dungeon Name
for msg in &world.messages {
write!(screen, "{}{}", color::Fg(color::LightWhite), msg).unwrap();
write!(screen, "{}{}\n\r", color::Fg(color::Reset), clear::UntilNewline).unwrap();
}
screen.flush().unwrap();
// Don't render too hot.
thread::sleep(Duration::from_millis(50));
}
// Nice cleanup: Move cursor below the world, so we can see how we finished
{
let world = world_mutex.lock().unwrap();
write!(screen, "{}", goto_cursor_coord(&Coord { col: 0, row: (world.floor.rows+7) as u16})).unwrap();
}
print!("{}", termion::cursor::Show);
screen.flush().unwrap();
}
simplify
extern crate termion;
use termion::raw::*;
use termion::clear;
use termion::color;
use termion::input::MouseTerminal;
use actor::*;
use floor::*;
use world::*;
use primitive::*;
use std::io::{Write, stdout};
use std::sync::*;
use std::thread;
use std::time::Duration;
fn render_floor<W : Write>(screen : &mut W, floor: &Floor) {
for row in &floor.tiles {
let mut line = String::new();
for tile in row {
if let Some(ref wall) = tile.wall {
line.push_str(wall);
} else {
line.push_str(" "); // U-2027
//line.push_str("‧"); // U-2027
}
}
write!(screen, "{}\n\r", line).unwrap(); // U-2502
}
}
fn goto_cursor_coord(coord : Coord) -> termion::cursor::Goto {
// Coordinate translation naively assumes floor is being rendered at 1,1
termion::cursor::Goto(coord.col+1, coord.row+1)
}
pub fn render_loop(world_mutex : Arc<Mutex<World>>, stop : Arc<Mutex<bool>>, dirty_coord_rx : mpsc::Receiver<Coord>) {
let mut screen = MouseTerminal::from(stdout().into_raw_mode().unwrap());
// Hide the cursor, clear the screen
write!(screen, "{}{}", termion::cursor::Hide, termion::clear::All).unwrap();
{
write!(screen, "{}", termion::cursor::Goto(1, 1)).unwrap();
let world = world_mutex.lock().unwrap();
render_floor(&mut screen, &world.floor);
}
// Render Loop
loop {
// Time to stop?
{
let stop = stop.lock().unwrap();
if *stop {
break;
}
}
let world = world_mutex.lock().unwrap();
// Redraw any dirty world coordinates
while let Ok(coord) = dirty_coord_rx.try_recv() {
write!(screen, "{}{}", goto_cursor_coord(coord), world.floor.get_symbol(&coord)).unwrap();
}
// Render Player
write!(screen, "{}", goto_cursor_coord(world.player.coord())).unwrap();
write!(screen, "{}", &world.player.symbol()).unwrap();
// Render Monsters
for monster in &world.monsters {
write!(screen, "{}", goto_cursor_coord(monster.coord())).unwrap();
write!(screen, "{}", monster.symbol()).unwrap();
}
// Bottom text
write!(screen, "{}", termion::cursor::Goto(1, (world.floor.rows+1) as u16)).unwrap();
write!(screen, "{}\n\r\n\r", world.floor.name).unwrap(); // Dungeon Name
for msg in &world.messages {
write!(screen, "{}{}", color::Fg(color::LightWhite), msg).unwrap();
write!(screen, "{}{}\n\r", color::Fg(color::Reset), clear::UntilNewline).unwrap();
}
screen.flush().unwrap();
// Don't render too hot.
thread::sleep(Duration::from_millis(50));
}
// Nice cleanup: Move cursor below the world, so we can see how we finished
{
let world = world_mutex.lock().unwrap();
write!(screen, "{}", goto_cursor_coord(Coord { col: 0, row: (world.floor.rows+7) as u16})).unwrap();
}
print!("{}", termion::cursor::Show);
screen.flush().unwrap();
}
|
use std::fmt;
use std::io;
use std::borrow::Cow;
use std::str::Utf8Error;
use std::result::Result as StdResult;
use std::error::Error as StdError;
use std::convert::{From, Into};
use httparse;
use mio;
#[cfg(feature="ssl")]
use openssl::ssl::{Error as SslError, HandshakeError as SslHandshakeError};
#[cfg(feature="ssl")]
type HandshakeError = SslHandshakeError<mio::tcp::TcpStream>;
use communication::Command;
pub type Result<T> = StdResult<T, Error>;
/// The type of an error, which may indicate other kinds of errors as the underlying cause.
#[derive(Debug)]
pub enum Kind {
/// Indicates an internal application error.
/// The WebSocket will automatically attempt to send an Error (1011) close code.
Internal,
/// Indicates a state where some size limit has been exceeded, such as an inability to accept
/// any more new connections.
/// If a Connection is active, the WebSocket will automatically attempt to send
/// a Size (1009) close code.
Capacity,
/// Indicates a violation of the WebSocket protocol.
/// The WebSocket will automatically attempt to send a Protocol (1002) close code, or if
/// this error occurs during a handshake, an HTTP 400 response will be generated.
Protocol,
/// Indicates that the WebSocket received data that should be utf8 encoded but was not.
/// The WebSocket will automatically attempt to send a Invalid Frame Payload Data (1007) close
/// code.
Encoding(Utf8Error),
/// Indicates an underlying IO Error.
/// This kind of error will result in a WebSocket Connection disconnecting.
Io(io::Error),
/// Indicates a failure to parse an HTTP message.
/// This kind of error should only occur during a WebSocket Handshake, and a HTTP 500 response
/// will be generated.
Http(httparse::Error),
/// Indicates a failure to send a signal on the internal EventLoop channel. This means that
/// the WebSocket is overloaded. In order to avoid this error, it is important to set
/// `Settings::max_connections` and `Settings:queue_size` high enough to handle the load.
/// If encountered, retuning from a handler method and waiting for the EventLoop to consume
/// the queue may relieve the situation.
Queue(mio::channel::SendError<Command>),
/// Indicates a failure to schedule a timeout on the EventLoop.
Timer(mio::timer::TimerError),
/// Indicates a failure to perform SSL encryption.
#[cfg(feature="ssl")]
Ssl(SslError),
/// Indicates a failure to perform SSL encryption.
#[cfg(feature="ssl")]
SslHandshake(HandshakeError),
/// A custom error kind for use by applications. This error kind involves extra overhead
/// because it will allocate the memory on the heap. The WebSocket ignores such errors by
/// default, simply passing them to the Connection Handler.
Custom(Box<StdError + Send + Sync>),
}
/// A struct indicating the kind of error that has occurred and any precise details of that error.
pub struct Error {
pub kind: Kind,
pub details: Cow<'static, str>,
}
impl Error {
pub fn new<I>(kind: Kind, details: I) -> Error
where I: Into<Cow<'static, str>>
{
Error {
kind: kind,
details: details.into(),
}
}
pub fn into_box(self) -> Box<StdError> {
match self.kind {
Kind::Custom(err) => err,
_ => Box::new(self),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.details.len() > 0 {
write!(f, "WS Error <{:?}>: {}", self.kind, self.details)
} else {
write!(f, "WS Error <{:?}>", self.kind)
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.details.len() > 0 {
write!(f, "{}: {}", self.description(), self.details)
} else {
write!(f, "{}", self.description())
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
match self.kind {
Kind::Internal => "Internal Application Error",
Kind::Capacity => "WebSocket at Capacity",
Kind::Protocol => "WebSocket Protocol Error",
Kind::Encoding(ref err) => err.description(),
Kind::Io(ref err) => err.description(),
Kind::Http(_) => "Unable to parse HTTP",
#[cfg(feature="ssl")]
Kind::Ssl(ref err) => err.description(),
#[cfg(feature="ssl")]
Kind::SslHandshake(ref err) => err.description(),
Kind::Queue(_) => "Unable to send signal on event loop",
Kind::Timer(_) => "Unable to schedule timeout on event loop",
Kind::Custom(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&StdError> {
match self.kind {
Kind::Encoding(ref err) => Some(err),
Kind::Io(ref err) => Some(err),
#[cfg(feature="ssl")]
Kind::Ssl(ref err) => Some(err),
#[cfg(feature="ssl")]
Kind::SslHandshake(ref err) => err.cause(),
Kind::Custom(ref err) => Some(err.as_ref()),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::new(Kind::Io(err), "")
}
}
impl From<httparse::Error> for Error {
fn from(err: httparse::Error) -> Error {
let details = match err {
httparse::Error::HeaderName => "Invalid byte in header name.",
httparse::Error::HeaderValue => "Invalid byte in header value.",
httparse::Error::NewLine => "Invalid byte in new line.",
httparse::Error::Status => "Invalid byte in Response status.",
httparse::Error::Token => "Invalid byte where token is required.",
httparse::Error::TooManyHeaders => "Parsed more headers than provided buffer can contain.",
httparse::Error::Version => "Invalid byte in HTTP version.",
};
Error::new(Kind::Http(err), details)
}
}
impl From<mio::channel::SendError<Command>> for Error {
fn from(err: mio::channel::SendError<Command>) -> Error {
match err {
mio::channel::SendError::Io(err) => Error::from(err),
_ => Error::new(Kind::Queue(err), "")
}
}
}
impl From<mio::timer::TimerError> for Error {
fn from(err: mio::timer::TimerError) -> Error {
match err {
_ => Error::new(Kind::Timer(err), "")
}
}
}
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Error {
Error::new(Kind::Encoding(err), "")
}
}
#[cfg(feature="ssl")]
impl From<SslError> for Error {
fn from(err: SslError) -> Error {
Error::new(Kind::Ssl(err), "")
}
}
#[cfg(feature="ssl")]
impl From<HandshakeError> for Error {
fn from(err: HandshakeError) -> Error {
Error::new(Kind::SslHandshake(err), "")
}
}
impl<B> From<Box<B>> for Error
where B: StdError + Send + Sync + 'static
{
fn from(err: Box<B>) -> Error {
Error::new(Kind::Custom(err), "")
}
}
Updating docs for ErrorKind::Internal
use std::fmt;
use std::io;
use std::borrow::Cow;
use std::str::Utf8Error;
use std::result::Result as StdResult;
use std::error::Error as StdError;
use std::convert::{From, Into};
use httparse;
use mio;
#[cfg(feature="ssl")]
use openssl::ssl::{Error as SslError, HandshakeError as SslHandshakeError};
#[cfg(feature="ssl")]
type HandshakeError = SslHandshakeError<mio::tcp::TcpStream>;
use communication::Command;
pub type Result<T> = StdResult<T, Error>;
/// The type of an error, which may indicate other kinds of errors as the underlying cause.
#[derive(Debug)]
pub enum Kind {
/// Indicates an internal application error.
/// If panic_on_internal is true, which is the default, then the application will panic.
/// Otherwise the WebSocket will automatically attempt to send an Error (1011) close code.
Internal,
/// Indicates a state where some size limit has been exceeded, such as an inability to accept
/// any more new connections.
/// If a Connection is active, the WebSocket will automatically attempt to send
/// a Size (1009) close code.
Capacity,
/// Indicates a violation of the WebSocket protocol.
/// The WebSocket will automatically attempt to send a Protocol (1002) close code, or if
/// this error occurs during a handshake, an HTTP 400 response will be generated.
Protocol,
/// Indicates that the WebSocket received data that should be utf8 encoded but was not.
/// The WebSocket will automatically attempt to send a Invalid Frame Payload Data (1007) close
/// code.
Encoding(Utf8Error),
/// Indicates an underlying IO Error.
/// This kind of error will result in a WebSocket Connection disconnecting.
Io(io::Error),
/// Indicates a failure to parse an HTTP message.
/// This kind of error should only occur during a WebSocket Handshake, and a HTTP 500 response
/// will be generated.
Http(httparse::Error),
/// Indicates a failure to send a signal on the internal EventLoop channel. This means that
/// the WebSocket is overloaded. In order to avoid this error, it is important to set
/// `Settings::max_connections` and `Settings:queue_size` high enough to handle the load.
/// If encountered, retuning from a handler method and waiting for the EventLoop to consume
/// the queue may relieve the situation.
Queue(mio::channel::SendError<Command>),
/// Indicates a failure to schedule a timeout on the EventLoop.
Timer(mio::timer::TimerError),
/// Indicates a failure to perform SSL encryption.
#[cfg(feature="ssl")]
Ssl(SslError),
/// Indicates a failure to perform SSL encryption.
#[cfg(feature="ssl")]
SslHandshake(HandshakeError),
/// A custom error kind for use by applications. This error kind involves extra overhead
/// because it will allocate the memory on the heap. The WebSocket ignores such errors by
/// default, simply passing them to the Connection Handler.
Custom(Box<StdError + Send + Sync>),
}
/// A struct indicating the kind of error that has occurred and any precise details of that error.
pub struct Error {
pub kind: Kind,
pub details: Cow<'static, str>,
}
impl Error {
pub fn new<I>(kind: Kind, details: I) -> Error
where I: Into<Cow<'static, str>>
{
Error {
kind: kind,
details: details.into(),
}
}
pub fn into_box(self) -> Box<StdError> {
match self.kind {
Kind::Custom(err) => err,
_ => Box::new(self),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.details.len() > 0 {
write!(f, "WS Error <{:?}>: {}", self.kind, self.details)
} else {
write!(f, "WS Error <{:?}>", self.kind)
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.details.len() > 0 {
write!(f, "{}: {}", self.description(), self.details)
} else {
write!(f, "{}", self.description())
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
match self.kind {
Kind::Internal => "Internal Application Error",
Kind::Capacity => "WebSocket at Capacity",
Kind::Protocol => "WebSocket Protocol Error",
Kind::Encoding(ref err) => err.description(),
Kind::Io(ref err) => err.description(),
Kind::Http(_) => "Unable to parse HTTP",
#[cfg(feature="ssl")]
Kind::Ssl(ref err) => err.description(),
#[cfg(feature="ssl")]
Kind::SslHandshake(ref err) => err.description(),
Kind::Queue(_) => "Unable to send signal on event loop",
Kind::Timer(_) => "Unable to schedule timeout on event loop",
Kind::Custom(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&StdError> {
match self.kind {
Kind::Encoding(ref err) => Some(err),
Kind::Io(ref err) => Some(err),
#[cfg(feature="ssl")]
Kind::Ssl(ref err) => Some(err),
#[cfg(feature="ssl")]
Kind::SslHandshake(ref err) => err.cause(),
Kind::Custom(ref err) => Some(err.as_ref()),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::new(Kind::Io(err), "")
}
}
impl From<httparse::Error> for Error {
fn from(err: httparse::Error) -> Error {
let details = match err {
httparse::Error::HeaderName => "Invalid byte in header name.",
httparse::Error::HeaderValue => "Invalid byte in header value.",
httparse::Error::NewLine => "Invalid byte in new line.",
httparse::Error::Status => "Invalid byte in Response status.",
httparse::Error::Token => "Invalid byte where token is required.",
httparse::Error::TooManyHeaders => "Parsed more headers than provided buffer can contain.",
httparse::Error::Version => "Invalid byte in HTTP version.",
};
Error::new(Kind::Http(err), details)
}
}
impl From<mio::channel::SendError<Command>> for Error {
fn from(err: mio::channel::SendError<Command>) -> Error {
match err {
mio::channel::SendError::Io(err) => Error::from(err),
_ => Error::new(Kind::Queue(err), "")
}
}
}
impl From<mio::timer::TimerError> for Error {
fn from(err: mio::timer::TimerError) -> Error {
match err {
_ => Error::new(Kind::Timer(err), "")
}
}
}
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Error {
Error::new(Kind::Encoding(err), "")
}
}
#[cfg(feature="ssl")]
impl From<SslError> for Error {
fn from(err: SslError) -> Error {
Error::new(Kind::Ssl(err), "")
}
}
#[cfg(feature="ssl")]
impl From<HandshakeError> for Error {
fn from(err: HandshakeError) -> Error {
Error::new(Kind::SslHandshake(err), "")
}
}
impl<B> From<Box<B>> for Error
where B: StdError + Send + Sync + 'static
{
fn from(err: Box<B>) -> Error {
Error::new(Kind::Custom(err), "")
}
}
|
use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant};
use iron::{Request, Response, Handler, IronResult, Error, IronError, Set};
use iron::{status, method};
use iron::response::modifiers::Status;
use iron::typemap::Assoc;
use recognizer::Router as Recognizer;
use recognizer::{Match, Params};
/// `Router` provides an interface for creating complex routes as middleware
/// for the Iron framework.
pub struct Router {
// The routers, specialized by method.
routers: HashMap<method::Method, Recognizer<Box<Handler + Send + Sync>>>,
error: Option<Box<Handler + Send + Sync>>
}
#[deriving(Show)]
/// The error thrown by router if there is no matching route.
pub struct NoRoute;
impl Error for NoRoute {
fn name(&self) -> &'static str { "No Route" }
}
impl Router {
/// `new` constructs a new, blank `Router`.
pub fn new() -> Router { Router { routers: HashMap::new(), error: None } }
/// Add a new route to a `Router`, matching both a method and glob pattern.
///
/// `route` supports glob patterns: `*` for a single wildcard segment and
/// `:param` for matching storing that segment of the request url in the `Params`
/// object, which is stored in the request `extensions`.
///
/// For instance, to route `Get` requests on any route matching
/// `/users/:userid/:friend` and store `userid` and `friend` in
/// the exposed Params object:
///
/// ```ignore
/// router.route(iron::method::Method::Get, "/users/:userid/:friendid", controller);
/// ```
///
/// The controller provided to route can be any `Handler`, which allows
/// extreme flexibility when handling routes. For instance, you could provide
/// a `Chain`, a `Handler`, which contains an authorization middleware and
/// a controller function, so that you can confirm that the request is
/// authorized for this route before handling it.
pub fn route<H: Handler, S: Str>(&mut self, method: method::Method, glob: S, handler: H) -> &mut Router {
match self.routers.entry(method) {
Vacant(entry) => entry.set(Recognizer::new()),
Occupied(entry) => entry.into_mut()
}.add(glob.as_slice(), box handler as Box<Handler + Send + Sync>);
self
}
/// Like route, but specialized to the `Get` method.
pub fn get<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Get, glob, handler)
}
/// Like route, but specialized to the `Post` method.
pub fn post<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Post, glob, handler)
}
/// Like route, but specialized to the `Put` method.
pub fn put<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Put, glob, handler)
}
/// Like route, but specialized to the `Delete` method.
pub fn delete<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Delete, glob, handler)
}
/// Like route, but specialized to the `Head` method.
pub fn head<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Head, glob, handler)
}
/// Like route, but specialized to the `Patch` method.
pub fn patch<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Patch, glob, handler)
}
/// Like route, but specialized to the `Options` method.
pub fn options<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Options, glob, handler)
}
/// Add a Handler to be used for this Router's `catch` method.
pub fn error<H: Handler>(&mut self, handler: H) -> &mut Router {
self.error = Some(box handler as Box<Handler + Send + Sync>);
self
}
fn recognize<'a>(&'a self, method: &method::Method, path: &str)
-> Option<Match<&'a Box<Handler + Send + Sync>>> {
self.routers.get(method).and_then(|router| router.recognize(path).ok())
}
}
impl Assoc<Params> for Router {}
impl Handler for Router {
fn call(&self, req: &mut Request) -> IronResult<Response> {
let matched = match self.recognize(&req.method, req.url.path.connect("/").as_slice()) {
Some(matched) => matched,
// No match.
None => return Err(box NoRoute as IronError)
};
req.extensions.insert::<Router, Params>(matched.params);
matched.handler.call(req)
}
fn catch(&self, req: &mut Request, err: IronError) -> (Response, IronResult<()>) {
match self.error {
Some(ref error_handler) => error_handler.catch(req, err),
// Error that is not caught by anything!
None => (Response::new().set(Status(status::InternalServerError)), Err(err))
}
}
}
(fix) Use std::error interop with iron::Error.
use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant};
use std::error::Error;
use iron::{Request, Response, Handler, IronResult, IronError, Set};
use iron::{status, method};
use iron::response::modifiers::Status;
use iron::typemap::Assoc;
use recognizer::Router as Recognizer;
use recognizer::{Match, Params};
/// `Router` provides an interface for creating complex routes as middleware
/// for the Iron framework.
pub struct Router {
// The routers, specialized by method.
routers: HashMap<method::Method, Recognizer<Box<Handler + Send + Sync>>>,
error: Option<Box<Handler + Send + Sync>>
}
#[deriving(Show)]
/// The error thrown by router if there is no matching route.
pub struct NoRoute;
impl Error for NoRoute {
fn description(&self) -> &str { "No Route" }
}
impl Router {
/// `new` constructs a new, blank `Router`.
pub fn new() -> Router { Router { routers: HashMap::new(), error: None } }
/// Add a new route to a `Router`, matching both a method and glob pattern.
///
/// `route` supports glob patterns: `*` for a single wildcard segment and
/// `:param` for matching storing that segment of the request url in the `Params`
/// object, which is stored in the request `extensions`.
///
/// For instance, to route `Get` requests on any route matching
/// `/users/:userid/:friend` and store `userid` and `friend` in
/// the exposed Params object:
///
/// ```ignore
/// router.route(iron::method::Method::Get, "/users/:userid/:friendid", controller);
/// ```
///
/// The controller provided to route can be any `Handler`, which allows
/// extreme flexibility when handling routes. For instance, you could provide
/// a `Chain`, a `Handler`, which contains an authorization middleware and
/// a controller function, so that you can confirm that the request is
/// authorized for this route before handling it.
pub fn route<H: Handler, S: Str>(&mut self, method: method::Method, glob: S, handler: H) -> &mut Router {
match self.routers.entry(method) {
Vacant(entry) => entry.set(Recognizer::new()),
Occupied(entry) => entry.into_mut()
}.add(glob.as_slice(), box handler as Box<Handler + Send + Sync>);
self
}
/// Like route, but specialized to the `Get` method.
pub fn get<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Get, glob, handler)
}
/// Like route, but specialized to the `Post` method.
pub fn post<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Post, glob, handler)
}
/// Like route, but specialized to the `Put` method.
pub fn put<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Put, glob, handler)
}
/// Like route, but specialized to the `Delete` method.
pub fn delete<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Delete, glob, handler)
}
/// Like route, but specialized to the `Head` method.
pub fn head<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Head, glob, handler)
}
/// Like route, but specialized to the `Patch` method.
pub fn patch<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Patch, glob, handler)
}
/// Like route, but specialized to the `Options` method.
pub fn options<H: Handler, S: Str>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Options, glob, handler)
}
/// Add a Handler to be used for this Router's `catch` method.
pub fn error<H: Handler>(&mut self, handler: H) -> &mut Router {
self.error = Some(box handler as Box<Handler + Send + Sync>);
self
}
fn recognize<'a>(&'a self, method: &method::Method, path: &str)
-> Option<Match<&'a Box<Handler + Send + Sync>>> {
self.routers.get(method).and_then(|router| router.recognize(path).ok())
}
}
impl Assoc<Params> for Router {}
impl Handler for Router {
fn call(&self, req: &mut Request) -> IronResult<Response> {
let matched = match self.recognize(&req.method, req.url.path.connect("/").as_slice()) {
Some(matched) => matched,
// No match.
None => return Err(box NoRoute as IronError)
};
req.extensions.insert::<Router, Params>(matched.params);
matched.handler.call(req)
}
fn catch(&self, req: &mut Request, err: IronError) -> (Response, IronResult<()>) {
match self.error {
Some(ref error_handler) => error_handler.catch(req, err),
// Error that is not caught by anything!
None => (Response::new().set(Status(status::InternalServerError)), Err(err))
}
}
}
|
//! Serial interface
//!
//! You can use the `Serial` interface with these USART instances
//!
//! # USART1
//!
//! - TX = PA9
//! - RX = PA10
//! - Interrupt = USART1
//!
//! # USART2
//!
//! - TX = PA2
//! - RX = PA3
//! - Interrupt = USART2
//!
//! # USART3
//!
//! - TX = PB10
//! - RX = PB11
//! - Interrupt = USART3
use core::any::{Any, TypeId};
use core::marker::Unsize;
use core::ops::Deref;
use core::ptr;
use cast::u16;
use hal;
use nb;
use static_ref::Ref;
use stm32f103xx::{AFIO, DMA1, GPIOA, GPIOB, RCC, USART1, USART2, USART3, gpioa, usart1};
use dma::{self, Buffer, Dma1Channel4, Dma1Channel5};
/// Specialized `Result` type
pub type Result<T> = ::core::result::Result<T, nb::Error<Error>>;
/// IMPLEMENTATION DETAIL
pub unsafe trait Usart: Deref<Target = usart1::RegisterBlock> {
/// IMPLEMENTATION DETAIL
type GPIO: Deref<Target = gpioa::RegisterBlock>;
/// IMPLEMENTATION DETAIL
type Ticks: Into<u32>;
}
unsafe impl Usart for USART1 {
type GPIO = GPIOA;
type Ticks = ::apb2::Ticks;
}
unsafe impl Usart for USART2 {
type GPIO = GPIOA;
type Ticks = ::apb1::Ticks;
}
unsafe impl Usart for USART3 {
type GPIO = GPIOB;
type Ticks = ::apb1::Ticks;
}
/// An error
#[derive(Debug)]
pub enum Error {
/// De-synchronization, excessive noise or a break character detected
Framing,
/// Noise detected in the received frame
Noise,
/// RX buffer overrun
Overrun,
#[doc(hidden)]
_Extensible,
}
/// Interrupt event
pub enum Event {
/// RX buffer Not Empty (new data available)
Rxne,
/// Transmission Complete
Tc,
/// TX buffer Empty (more data can be send)
Txe,
}
/// Serial interface
///
/// # Interrupts
///
/// - RXNE
pub struct Serial<'a, U>(pub &'a U) where U: Any + Usart;
impl<'a, U> Clone for Serial<'a, U>
where U: Any + Usart
{
fn clone(&self) -> Self {
*self
}
}
impl<'a, U> Copy for Serial<'a, U> where U: Any + Usart {}
impl<'a, U> Serial<'a, U>
where U: Any + Usart
{
/// Initializes the serial interface with a baud rate of `baut_rate` bits
/// per second
///
/// The serial interface will be configured to use 8 bits of data, 1 stop
/// bit, no hardware control and to omit parity checking
pub fn init<B>(&self,
baud_rate: B,
afio: &AFIO,
dma1: Option<&DMA1>,
gpio: &U::GPIO,
rcc: &RCC)
where B: Into<U::Ticks>
{
self._init(baud_rate.into(), afio, dma1, gpio, rcc)
}
fn _init(&self,
baud_rate: U::Ticks,
afio: &AFIO,
dma1: Option<&DMA1>,
gpio: &U::GPIO,
rcc: &RCC) {
let usart = self.0;
// power up peripherals
if dma1.is_some() {
rcc.ahbenr.modify(|_, w| w.dma1en().enabled());
}
if usart.get_type_id() == TypeId::of::<USART1>() {
rcc.apb2enr
.modify(|_, w| {
w.afioen()
.enabled()
.iopaen()
.enabled()
.usart1en()
.enabled()
});
} else if usart.get_type_id() == TypeId::of::<USART2>() {
rcc.apb1enr.modify(|_, w| w.usart2en().enabled());
rcc.apb2enr
.modify(|_, w| w.afioen().enabled().iopaen().enabled());
} else if usart.get_type_id() == TypeId::of::<USART3>() {
rcc.apb1enr.modify(|_, w| w.usart3en().enabled());
rcc.apb2enr
.modify(|_, w| w.afioen().enabled().iopben().enabled());
}
if usart.get_type_id() == TypeId::of::<USART1>() {
// PA9 = TX, PA10 = RX
afio.mapr.modify(|_, w| w.usart1_remap().clear());
gpio.crh
.modify(|_, w| {
w.mode9()
.output()
.cnf9()
.alt_push()
.mode10()
.input()
.cnf10()
.bits(0b01)
});
} else if usart.get_type_id() == TypeId::of::<USART2>() {
// PA2 = TX, PA3 = RX
afio.mapr.modify(|_, w| w.usart2_remap().clear());
gpio.crl
.modify(|_, w| {
w.mode2()
.output()
.cnf2()
.alt_push()
.mode3()
.input()
.cnf3()
.bits(0b01)
});
} else if usart.get_type_id() == TypeId::of::<USART3>() {
// PB10 = TX, PB11 = RX
afio.mapr
.modify(|_, w| unsafe { w.usart3_remap().bits(0b00) });
gpio.crh
.modify(|_, w| {
w.mode10()
.output()
.cnf10()
.alt_push()
.mode11()
.input()
.cnf11()
.bits(0b01)
});
}
if let Some(dma1) = dma1 {
if usart.get_type_id() == TypeId::of::<USART1>() {
// TX DMA transfer
// mem2mem: Memory to memory mode disabled
// pl: Medium priority
// msize: Memory size = 8 bits
// psize: Peripheral size = 8 bits
// minc: Memory increment mode enabled
// pinc: Peripheral increment mode disabled
// circ: Circular mode disabled
// dir: Transfer from memory to peripheral
// tceie: Transfer complete interrupt enabled
// en: Disabled
dma1.ccr4
.write(|w| unsafe {
w.mem2mem()
.clear()
.pl()
.bits(0b01)
.msize()
.bits(0b00)
.psize()
.bits(0b00)
.minc()
.set()
.circ()
.clear()
.pinc()
.clear()
.dir()
.set()
.tcie()
.set()
.en()
.clear()
});
// RX DMA transfer
// mem2mem: Memory to memory mode disabled
// pl: Medium priority
// msize: Memory size = 8 bits
// psize: Peripheral size = 8 bits
// minc: Memory increment mode enabled
// pinc: Peripheral increment mode disabled
// circ: Circular mode disabled
// dir: Transfer from peripheral to memory
// tceie: Transfer complete interrupt enabled
// en: Disabled
dma1.ccr5
.write(|w| unsafe {
w.mem2mem()
.clear()
.pl()
.bits(0b01)
.msize()
.bits(0b00)
.psize()
.bits(0b00)
.minc()
.set()
.circ()
.clear()
.pinc()
.clear()
.dir()
.clear()
.tcie()
.set()
.en()
.clear()
});
} else {
// TODO enable DMA for USART{2,3}
unimplemented!()
}
}
// 8N1
usart.cr2.write(|w| unsafe { w.stop().bits(0b00) });
// baud rate
let brr = baud_rate.into();
assert!(brr >= 16, "impossible baud rate");
usart.brr.write(|w| unsafe { w.bits(brr) });
// disable hardware flow control
// enable DMA TX and RX transfers
usart
.cr3
.write(|w| {
w.rtse()
.clear()
.ctse()
.clear()
.dmat()
.set()
.dmar()
.set()
});
// enable TX, RX; disable parity checking
usart
.cr1
.write(|w| {
w.ue()
.set()
.re()
.set()
.te()
.set()
.m()
.clear()
.pce()
.clear()
.rxneie()
.clear()
});
}
/// Starts listening for an interrupt `event`
pub fn listen(&self, event: Event) {
let usart = self.0;
match event {
Event::Rxne => usart.cr1.modify(|_, w| w.rxneie().set()),
Event::Tc => usart.cr1.modify(|_, w| w.tcie().set()),
Event::Txe => usart.cr1.modify(|_, w| w.txeie().set()),
}
}
/// Stops listening for an interrupt `event`
pub fn unlisten(&self, event: Event) {
let usart = self.0;
match event {
Event::Rxne => usart.cr1.modify(|_, w| w.rxneie().clear()),
Event::Tc => usart.cr1.modify(|_, w| w.tcie().clear()),
Event::Txe => usart.cr1.modify(|_, w| w.txeie().clear()),
}
}
}
impl<'a, U> hal::Serial for Serial<'a, U>
where U: Any + Usart
{
type Error = Error;
fn read(&self) -> Result<u8> {
let usart1 = self.0;
let sr = usart1.sr.read();
if sr.ore().is_set() {
Err(nb::Error::Other(Error::Overrun))
} else if sr.ne().is_set() {
Err(nb::Error::Other(Error::Noise))
} else if sr.fe().is_set() {
Err(nb::Error::Other(Error::Framing))
} else if sr.rxne().is_set() {
// NOTE(read_volatile) the register is 9 bits big but we'll only
// work with the first 8 bits
Ok(unsafe { ptr::read_volatile(&usart1.dr as *const _ as *const u8) })
} else {
Err(nb::Error::WouldBlock)
}
}
fn write(&self, byte: u8) -> Result<()> {
let usart1 = self.0;
let sr = usart1.sr.read();
if sr.ore().is_set() {
Err(nb::Error::Other(Error::Overrun))
} else if sr.ne().is_set() {
Err(nb::Error::Other(Error::Noise))
} else if sr.fe().is_set() {
Err(nb::Error::Other(Error::Framing))
} else if sr.txe().is_set() {
// NOTE(write_volatile) see NOTE in the `read` method
unsafe { ptr::write_volatile(&usart1.dr as *const _ as *mut u8, byte) }
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl<'a> Serial<'a, USART1> {
/// Starts a DMA transfer to receive serial data into a `buffer`
///
/// This will mutably lock the `buffer` preventing borrowing its contents
/// The `buffer` can be `release`d after the DMA transfer finishes
// TODO support circular mode + half transfer interrupt as a double
// buffering mode
pub fn read_exact<B>(&self,
dma1: &DMA1,
buffer: Ref<Buffer<B, Dma1Channel5>>)
-> ::core::result::Result<(), dma::Error>
where B: Unsize<[u8]>
{
let usart1 = self.0;
if dma1.ccr5.read().en().is_set() {
return Err(dma::Error::InUse);
}
let buffer: &mut [u8] = buffer.lock_mut();
dma1.cndtr5
.write(|w| unsafe { w.ndt().bits(u16(buffer.len()).unwrap()) });
dma1.cpar5
.write(|w| unsafe { w.bits(&usart1.dr as *const _ as u32) });
dma1.cmar5
.write(|w| unsafe { w.bits(buffer.as_ptr() as u32) });
dma1.ccr5.modify(|_, w| w.en().set());
Ok(())
}
/// Starts a DMA transfer to send `buffer` through this serial port
///
/// This will immutably lock the `buffer` preventing mutably borrowing its
/// contents. The `buffer` can be `release`d after the DMA transfer finishes
pub fn write_all<B>(&self,
dma1: &DMA1,
buffer: Ref<Buffer<B, Dma1Channel4>>)
-> ::core::result::Result<(), dma::Error>
where B: Unsize<[u8]>
{
let usart1 = self.0;
if dma1.ccr4.read().en().is_set() {
return Err(dma::Error::InUse);
}
let buffer: &[u8] = buffer.lock();
dma1.cndtr4
.write(|w| unsafe { w.ndt().bits(u16(buffer.len()).unwrap()) });
dma1.cpar4
.write(|w| unsafe { w.bits(&usart1.dr as *const _ as u32) });
dma1.cmar4
.write(|w| unsafe { w.bits(buffer.as_ptr() as u32) });
dma1.ccr4.modify(|_, w| w.en().set());
Ok(())
}
}
Add serial
use core::any::{Any, TypeId};
use core::marker::Unsize;
use core::ops::Deref;
use core::ptr;
use cast::u16;
use hal;
use hal::serial::Write;
use nb;
use time::U32Ext;
// use static_ref::Ref;
use stm32f411::{usart1, USART1, USART2, USART6};
/// Specialized `Result` type
pub type Result<T> = ::core::result::Result<T, nb::Error<Error>>;
/// IMPLEMENTATION DETAIL
pub unsafe trait Usart: Deref<Target = usart1::RegisterBlock> {
/// IMPLEMENTATION DETAIL
type Ticks: Into<u32>;
}
unsafe impl Usart for USART1 {
type Ticks = ::apb2::Ticks;
}
unsafe impl Usart for USART2 {
type Ticks = ::apb1::Ticks;
}
unsafe impl Usart for USART6 {
type Ticks = ::apb1::Ticks;
}
/// An error
#[derive(Debug)]
pub enum Error {
/// De-synchronization, excessive noise or a break character detected
Framing,
/// Noise detected in the received frame
Noise,
/// RX buffer overrun
Overrun,
#[doc(hidden)]
_Extensible,
}
/// Interrupt event
pub enum Event {
/// RX buffer Not Empty (new data available)
Rxne,
/// Transmission Complete
Tc,
/// TX buffer Empty (more data can be send)
Txe,
}
/// Serial interface
///
/// # Interrupts
///
/// - RXNE
pub struct Serial<'a, U>(pub &'a U) where U: Any + Usart;
impl<'a, U> Clone for Serial<'a, U>
where U: Any + Usart
{
fn clone(&self) -> Self {
*self
}
}
impl<'a, U> Copy for Serial<'a, U> where U: Any + Usart {}
impl<'a, U> Serial<'a, U>
where U: Any + Usart
{
/// Initializes the serial interface with a baud rate of `baut_rate` bits
/// per second
///
/// The serial interface will be configured to use 8 bits of data, 1 stop
/// bit, no hardware control and to omit parity checking
pub fn init<B>(&self, baud_rate: B)
where B: Into<U::Ticks>
{
self.set_baud_rate(baud_rate);
self.enable();
}
pub fn set_baud_rate<B>(&self, baud_rate: B)
where B: Into<U::Ticks>
{
let ticks = baud_rate.into();
let baud = ticks.into();
self.0.brr.write(|w| unsafe { w.bits(baud) });
}
pub fn enable(&self) {
self.0.cr1.modify(|_, w|
w.ue().set_bit()
.te().set_bit()
.re().set_bit());
}
pub fn disable(&self) {
self.0.cr1.modify(|_, w| w.ue().clear_bit());
}
}
impl<'a, U> hal::serial::Read<u8> for Serial<'a, U>
where
U: Any + Usart,
{
type Error = Error;
fn read(&self) -> Result<u8> {
let usart = self.0;
let sr = usart.sr.read();
if sr.ore().bit_is_set() {
Err(nb::Error::Other(Error::Overrun))
} else if sr.nf().bit_is_set() {
Err(nb::Error::Other(Error::Noise))
} else if sr.fe().bit_is_set() {
Err(nb::Error::Other(Error::Framing))
} else if sr.rxne().bit_is_set() {
// NOTE(read_volatile) the register is 9 bits big but we'll only
// work with the first 8 bits
Ok(unsafe {
ptr::read_volatile(&usart.dr as *const _ as *const u8)
})
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl<'a, U> Write<u8> for Serial<'a, U>
where
U: Any + Usart,
{
type Error = Error;
fn write(&self, byte: u8) -> Result<()> {
let usart = self.0;
let sr = usart.sr.read();
if sr.ore().bit_is_set() {
Err(nb::Error::Other(Error::Overrun))
} else if sr.nf().bit_is_set() {
Err(nb::Error::Other(Error::Noise))
} else if sr.fe().bit_is_set() {
Err(nb::Error::Other(Error::Framing))
} else if sr.txe().bit_is_set() {
// NOTE(write_volatile) see NOTE in the `read` method
unsafe {
ptr::write_volatile(&usart.dr as *const _ as *mut u8, byte)
}
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl<'a, U> hal::serial::Write<&'a [u8]> for Serial<'a, U>
where
U: Any + Usart,
{
type Error = Error;
fn write<'b>(&self, buffer: &'b [u8]) -> Result<()> {
for byte in buffer {
let status = block!(self.write(*byte));
match status {
Err(e) => return Err(nb::Error::Other(e)),
_ => {}
}
}
Ok(())
}
}
impl<'a, U> hal::serial::Write<&'a str> for Serial<'a, U>
where
U: Any + Usart,
{
type Error = Error;
fn write<'b>(&self, string: &'a str) -> Result<()> {
self.write(string.as_bytes())
}
}
/*
impl<'a> Serial<'a, USART1> {
/// Starts a DMA transfer to receive serial data into a `buffer`
///
/// This will mutably lock the `buffer` preventing borrowing its contents
/// The `buffer` can be `release`d after the DMA transfer finishes
// TODO support circular mode + half transfer interrupt as a double
// buffering mode
pub fn read_exact<B>(&self,
dma1: &DMA1,
buffer: Ref<Buffer<B, Dma1Channel5>>)
-> ::core::result::Result<(), dma::Error>
where B: Unsize<[u8]>
{
let usart1 = self.0;
if dma1.ccr5.read().en().is_set() {
return Err(dma::Error::InUse);
}
let buffer: &mut [u8] = buffer.lock_mut();
dma1.cndtr5
.write(|w| unsafe { w.ndt().bits(u16(buffer.len()).unwrap()) });
dma1.cpar5
.write(|w| unsafe { w.bits(&usart1.dr as *const _ as u32) });
dma1.cmar5
.write(|w| unsafe { w.bits(buffer.as_ptr() as u32) });
dma1.ccr5.modify(|_, w| w.en().set());
Ok(())
}
/// Starts a DMA transfer to send `buffer` through this serial port
///
/// This will immutably lock the `buffer` preventing mutably borrowing its
/// contents. The `buffer` can be `release`d after the DMA transfer finishes
pub fn write_all<B>(&self,
dma1: &DMA1,
buffer: Ref<Buffer<B, Dma1Channel4>>)
-> ::core::result::Result<(), dma::Error>
where B: Unsize<[u8]>
{
let usart1 = self.0;
if dma1.ccr4.read().en().is_set() {
return Err(dma::Error::InUse);
}
let buffer: &[u8] = buffer.lock();
dma1.cndtr4
.write(|w| unsafe { w.ndt().bits(u16(buffer.len()).unwrap()) });
dma1.cpar4
.write(|w| unsafe { w.bits(&usart1.dr as *const _ as u32) });
dma1.cmar4
.write(|w| unsafe { w.bits(buffer.as_ptr() as u32) });
dma1.ccr4.modify(|_, w| w.en().set());
Ok(())
}
}
*/ |
//! Provides the server and handles the incomming requests
//! All ports are handled by the same function
// System modules:
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::thread::spawn;
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::io::Result;
use time::now;
// Internal modules:
use configuration::Configuration;
fn handle_client(stream: &mut TcpStream, remote_addr: &SocketAddr, all_data_file: &Arc<Mutex<String>>) -> Result<()> {
info!("Client socket address: {}", remote_addr);
let local_addr = try!(stream.local_addr());
let local_port = match local_addr {
SocketAddr::V4(local_addr) => local_addr.port(),
SocketAddr::V6(local_addr) => local_addr.port()
};
info!("Port: {}", local_port);
let mut buffer = Vec::new();
let len = try!(stream.read_to_end(&mut buffer));
info!("Number of bytes received: {}", len);
info!("Bytes: {:?}", buffer);
match all_data_file.lock() {
Ok(all_data_file) => {
let mut file_handle = BufWriter::new(try!(OpenOptions::new().write(true).create(true).append(true).open(&*all_data_file)));
let tm = now();
let tm = tm.strftime("%Y.%m.%d - %H:%M:%S").unwrap();
try!(write!(file_handle, "<measure>\n"));
try!(write!(file_handle, "<port>{}</port>\n", local_port));
try!(write!(file_handle, "<date_time>{}</date_time>\n", &tm));
try!(write!(file_handle, "<data>\n"));
try!(write!(file_handle, "{:?}\n", buffer));
try!(write!(file_handle, "</data>\n"));
try!(write!(file_handle, "</measure>\n"));
},
Err(e) => info!("Mutex (poison) error: {}", e)
}
Ok(())
}
pub fn start_service(config: Configuration) {
let mut listeners = Vec::new();
for port in config.ports {
let listener = TcpListener::bind(("0.0.0.0", port));
if let Ok(listener) = listener {
listeners.push(listener);
}
}
let all_data_file = Arc::new(Mutex::new(config.all_data_file.clone()));
for listener in listeners {
let all_data_file = all_data_file.clone();
spawn(move|| {
loop {
let result = listener.accept();
if let Ok(result) = result {
let (mut stream, addr) = result;
if let Err(io_error) = handle_client(&mut stream, &addr, &all_data_file) {
info!("IOError: {}", io_error);
}
}
}
});
}
}
add support for a second (monthly) file, some comments about refactoring
//! Provides the server and handles the incomming requests
//! All ports are handled by the same function
// System modules:
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::thread::spawn;
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::io::Result;
use time::now;
// Internal modules:
use configuration::Configuration;
fn handle_client(stream: &mut TcpStream, remote_addr: &SocketAddr,
all_data_file: &Arc<Mutex<String>>, monthly_data_folder: &Arc<Mutex<String>>) -> Result<()> {
info!("Client socket address: {}", remote_addr);
let local_addr = try!(stream.local_addr());
let local_port = match local_addr {
SocketAddr::V4(local_addr) => local_addr.port(),
SocketAddr::V6(local_addr) => local_addr.port()
};
info!("Port: {}", local_port);
let mut buffer = Vec::new();
let len = try!(stream.read_to_end(&mut buffer));
info!("Number of bytes received: {}", len);
info!("Bytes: {:?}", buffer);
// TODO: refactor to utility function
// TODO: use str::from_utf8(buf) if data is sent in clear text
// Otherwise parse binary data to floats
match all_data_file.lock() {
Ok(all_data_file) => {
let mut file_handle = BufWriter::new(try!(OpenOptions::new()
.write(true).create(true).append(true).open(&*all_data_file)));
let tm = now();
let current_date_time = tm.strftime("%Y.%m.%d - %H:%M:%S").unwrap();
try!(write!(file_handle, "<measure>\n"));
try!(write!(file_handle, "<port>{}</port>\n", local_port));
try!(write!(file_handle, "<date_time>{}</date_time>\n", ¤t_date_time));
try!(write!(file_handle, "<data>\n"));
try!(write!(file_handle, "{:?}\n", buffer));
try!(write!(file_handle, "</data>\n"));
try!(write!(file_handle, "</measure>\n\n"));
},
Err(e) => info!("Mutex (poison) error (all_data_file): {}", e)
}
match monthly_data_folder.lock() {
Ok(monthly_data_folder) => {
let tm = now();
let current_year = tm.strftime("%Y").unwrap();
let current_month = tm.strftime("%m").unwrap();
// TODO: create separate folder for year and month
let file_name = format!("{}/{}_{}.txt", *monthly_data_folder, current_year, current_month);
let mut file_handle = BufWriter::new(try!(OpenOptions::new()
.write(true).create(true).append(true).open(file_name)));
let current_date_time = tm.strftime("%Y.%m.%d - %H:%M:%S").unwrap();
try!(write!(file_handle, "<measure>\n"));
try!(write!(file_handle, "<port>{}</port>\n", local_port));
try!(write!(file_handle, "<date_time>{}</date_time>\n", ¤t_date_time));
try!(write!(file_handle, "<data>\n"));
try!(write!(file_handle, "{:?}\n", buffer));
try!(write!(file_handle, "</data>\n"));
try!(write!(file_handle, "</measure>\n\n"));
},
Err(e) => info!("Mutex (poison) error (monthly_data_folder): {}", e)
}
Ok(())
}
pub fn start_service(config: Configuration) {
let mut listeners = Vec::new();
for port in config.ports {
let listener = TcpListener::bind(("0.0.0.0", port));
if let Ok(listener) = listener {
listeners.push(listener);
}
}
let all_data_file = Arc::new(Mutex::new(config.all_data_file.clone()));
let monthly_data_folder = Arc::new(Mutex::new(config.monthly_data_folder.clone()));
for listener in listeners {
let all_data_file = all_data_file.clone();
let monthly_data_folder = monthly_data_folder.clone();
spawn(move|| {
loop {
let result = listener.accept();
if let Ok(result) = result {
let (mut stream, addr) = result;
if let Err(io_error) = handle_client(&mut stream, &addr,
&all_data_file, &monthly_data_folder) {
info!("IOError: {}", io_error);
}
}
}
});
}
}
|
use grain_capnp::{PowerboxCapability, UiView, UiSession};
use web_session_capnp::{WebSession};
use collections::hashmap::HashMap;
use capnp::capability::{ClientHook, FromServer};
use capnp::AnyPointer;
use capnp_rpc::rpc::{RpcConnectionState, SturdyRefRestorer};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
pub struct UiViewImpl;
impl PowerboxCapability::Server for UiViewImpl {
fn get_powerbox_info(&mut self, context : PowerboxCapability::GetPowerboxInfoContext) {
context.done()
}
}
impl UiView::Server for UiViewImpl {
fn get_view_info(&mut self, context : UiView::GetViewInfoContext) {
context.done()
}
fn new_session(&mut self, mut context : UiView::NewSessionContext) {
println!("asked for a new session!");
let (_, results) = context.get();
let client : WebSession::Client = FromServer::new(None::<LocalClient>, ~WebSessionImpl::new());
// we need to do this dance to upcast.
results.set_session(UiSession::Client { client : client.client});
context.done()
}
}
pub struct WebSessionImpl {
db : sqlite3::Database,
}
impl WebSessionImpl {
pub fn new() -> WebSessionImpl {
WebSessionImpl {
db : sqlite3::open("/var/data.db").unwrap(),
}
}
}
impl UiSession::Server for WebSessionImpl {
}
static main_css : &'static str =
"body { font-family: Helvetica, Sans, Arial;
font-size: medium;
margin-left: auto;
margin-right: auto;
width: 600px;
text-align: center;
}
.word {
text-align: center;
font-size: 500%;
}
";
static header : &'static str =
r#"<head><title> acronymy </title><link rel="stylesheet" type="text/css" href="main.css" >
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>"#;
fn html_body(body :&str) -> ~str {
format!("<html>{}<body>{}</body></html>", header, body)
}
struct Path {
path : ~str,
query : HashMap<~str, ~str>,
}
impl Path {
fn new() -> Path {
Path { path : ~"", query : HashMap::new() }
}
}
fn parse_path(path : &str) -> Path {
let mut result = Path::new();
let v : ~[&str] = path.splitn('?', 2).collect();
if v.len() == 0 {
return result;
}
result.path = v[0].into_owned();
if v.len() == 1 {
return result;
}
for attr in v[1].split('&') {
let a : ~[&str] = attr.splitn('=', 2).collect();
if a.len() == 2 {
result.query.insert(a[0].into_owned(),
a[1].into_owned());
}
}
return result;
}
impl WebSessionImpl {
fn is_word(&mut self, word : &str) -> sqlite3::SqliteResult<bool> {
let cursor = try!(self.db.prepare(
format!("SELECT * FROM Words WHERE Word = \"{}\";", word),
&None));
println!("got the cursor");
return Ok(try!(cursor.step_row()).is_some());
}
}
impl WebSession::Server for WebSessionImpl {
fn get(&mut self, mut context : WebSession::GetContext) {
println!("GET");
let (params, results) = context.get();
let raw_path = params.get_path();
let content = results.init_content();
content.set_mime_type("text/html");
let path = parse_path(raw_path);
println!("path = {}", raw_path);
println!("{}, {}", path.path, path.query);
if raw_path == "main.css" {
content.get_body().set_bytes(main_css.as_bytes())
} else if path.path.as_slice() == "define" {
let word : ~str = path.query.get(&~"word").clone();
// TODO check that `word` is actually a word.
match self.is_word(word) {
Err(e) => fail!("is_word error: {}", e),
Ok(false) => {
content.get_body().set_bytes(
html_body(
"<div> that's not a word </div>
<form action=\"define\" method=\"get\">
<input name=\"word\"/><button>go</button></form>").as_bytes());
return context.done();
}
Ok(true) => {}
}
content.get_body().set_bytes(
html_body(
format!(
"<div class=\"word\">{word}</div>
<form action=\"define\" method=\"get\">
<input name=\"word\" value=\"{word}\" type=\"hidden\"/>
<input name=\"definition\"/><button>define</button></form>",
word=word)).as_bytes());
} else {
content.get_body().set_bytes(
html_body(
"<form action=\"define\" method=\"get\">
<input name=\"word\"/><button>go</button></form>").as_bytes());
}
context.done()
}
fn post(&mut self, context : WebSession::PostContext) {
println!("POST");
context.done()
}
fn put(&mut self, context : WebSession::PutContext) {
println!("PUT");
context.done()
}
fn delete(&mut self, context : WebSession::DeleteContext) {
println!("DELETE");
context.done()
}
fn open_web_socket(&mut self, context : WebSession::OpenWebSocketContext) {
println!("OPEN WEB SOCKET");
context.done()
}
}
pub struct FdStream {
inner : ~::std::rt::rtio::RtioFileStream:Send,
}
impl FdStream {
pub fn new(fd : ::libc::c_int) -> ::std::io::IoResult<FdStream> {
::std::rt::rtio::LocalIo::maybe_raise(|io| {
Ok (FdStream { inner : io.fs_from_raw_fd(fd, ::std::rt::rtio::DontClose) })
})
}
}
impl Reader for FdStream {
fn read(&mut self, buf : &mut [u8]) -> ::std::io::IoResult<uint> {
self.inner.read(buf).map(|i| i as uint)
}
}
impl Writer for FdStream {
fn write(&mut self, buf : &[u8]) -> ::std::io::IoResult<()> {
self.inner.write(buf)
}
}
pub struct Restorer;
impl SturdyRefRestorer for Restorer {
fn restore(&self, obj_id : AnyPointer::Reader) -> Option<~ClientHook:Send> {
if obj_id.is_null() {
let client : UiView::Client = FromServer::new(None::<LocalClient>, ~UiViewImpl);
Some(client.client.hook)
} else {
None
}
}
}
pub fn main() -> ::std::io::IoResult<()> {
let ifs = try!(FdStream::new(3));
let ofs = try!(FdStream::new(3));
let connection_state = RpcConnectionState::new();
connection_state.run(ifs, ofs, Restorer);
Ok(())
}
print the error message too
use grain_capnp::{PowerboxCapability, UiView, UiSession};
use web_session_capnp::{WebSession};
use collections::hashmap::HashMap;
use capnp::capability::{ClientHook, FromServer};
use capnp::AnyPointer;
use capnp_rpc::rpc::{RpcConnectionState, SturdyRefRestorer};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
pub struct UiViewImpl;
impl PowerboxCapability::Server for UiViewImpl {
fn get_powerbox_info(&mut self, context : PowerboxCapability::GetPowerboxInfoContext) {
context.done()
}
}
impl UiView::Server for UiViewImpl {
fn get_view_info(&mut self, context : UiView::GetViewInfoContext) {
context.done()
}
fn new_session(&mut self, mut context : UiView::NewSessionContext) {
println!("asked for a new session!");
let (_, results) = context.get();
let client : WebSession::Client = FromServer::new(None::<LocalClient>, ~WebSessionImpl::new());
// we need to do this dance to upcast.
results.set_session(UiSession::Client { client : client.client});
context.done()
}
}
pub struct WebSessionImpl {
db : sqlite3::Database,
}
impl WebSessionImpl {
pub fn new() -> WebSessionImpl {
WebSessionImpl {
db : sqlite3::open("/var/data.db").unwrap(),
}
}
}
impl UiSession::Server for WebSessionImpl {
}
static main_css : &'static str =
"body { font-family: Helvetica, Sans, Arial;
font-size: medium;
margin-left: auto;
margin-right: auto;
width: 600px;
text-align: center;
}
.word {
text-align: center;
font-size: 500%;
}
";
static header : &'static str =
r#"<head><title> acronymy </title><link rel="stylesheet" type="text/css" href="main.css" >
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>"#;
fn html_body(body :&str) -> ~str {
format!("<html>{}<body>{}</body></html>", header, body)
}
struct Path {
path : ~str,
query : HashMap<~str, ~str>,
}
impl Path {
fn new() -> Path {
Path { path : ~"", query : HashMap::new() }
}
}
fn parse_path(path : &str) -> Path {
let mut result = Path::new();
let v : ~[&str] = path.splitn('?', 2).collect();
if v.len() == 0 {
return result;
}
result.path = v[0].into_owned();
if v.len() == 1 {
return result;
}
for attr in v[1].split('&') {
let a : ~[&str] = attr.splitn('=', 2).collect();
if a.len() == 2 {
result.query.insert(a[0].into_owned(),
a[1].into_owned());
}
}
return result;
}
impl WebSessionImpl {
fn is_word(&mut self, word : &str) -> sqlite3::SqliteResult<bool> {
let cursor = try!(self.db.prepare(
format!("SELECT * FROM Words WHERE Word = \"{}\";", word),
&None));
println!("got the cursor");
return Ok(try!(cursor.step_row()).is_some());
}
}
impl WebSession::Server for WebSessionImpl {
fn get(&mut self, mut context : WebSession::GetContext) {
println!("GET");
let (params, results) = context.get();
let raw_path = params.get_path();
let content = results.init_content();
content.set_mime_type("text/html");
let path = parse_path(raw_path);
println!("path = {}", raw_path);
println!("{}, {}", path.path, path.query);
if raw_path == "main.css" {
content.get_body().set_bytes(main_css.as_bytes())
} else if path.path.as_slice() == "define" {
let word : ~str = path.query.get(&~"word").clone();
// TODO check that `word` is actually a word.
match self.is_word(word) {
Err(e) => fail!("is_word error: {}, {:?}", e, self.db.get_errmsg()),
Ok(false) => {
content.get_body().set_bytes(
html_body(
"<div> that's not a word </div>
<form action=\"define\" method=\"get\">
<input name=\"word\"/><button>go</button></form>").as_bytes());
return context.done();
}
Ok(true) => {}
}
content.get_body().set_bytes(
html_body(
format!(
"<div class=\"word\">{word}</div>
<form action=\"define\" method=\"get\">
<input name=\"word\" value=\"{word}\" type=\"hidden\"/>
<input name=\"definition\"/><button>define</button></form>",
word=word)).as_bytes());
} else {
content.get_body().set_bytes(
html_body(
"<form action=\"define\" method=\"get\">
<input name=\"word\"/><button>go</button></form>").as_bytes());
}
context.done()
}
fn post(&mut self, context : WebSession::PostContext) {
println!("POST");
context.done()
}
fn put(&mut self, context : WebSession::PutContext) {
println!("PUT");
context.done()
}
fn delete(&mut self, context : WebSession::DeleteContext) {
println!("DELETE");
context.done()
}
fn open_web_socket(&mut self, context : WebSession::OpenWebSocketContext) {
println!("OPEN WEB SOCKET");
context.done()
}
}
pub struct FdStream {
inner : ~::std::rt::rtio::RtioFileStream:Send,
}
impl FdStream {
pub fn new(fd : ::libc::c_int) -> ::std::io::IoResult<FdStream> {
::std::rt::rtio::LocalIo::maybe_raise(|io| {
Ok (FdStream { inner : io.fs_from_raw_fd(fd, ::std::rt::rtio::DontClose) })
})
}
}
impl Reader for FdStream {
fn read(&mut self, buf : &mut [u8]) -> ::std::io::IoResult<uint> {
self.inner.read(buf).map(|i| i as uint)
}
}
impl Writer for FdStream {
fn write(&mut self, buf : &[u8]) -> ::std::io::IoResult<()> {
self.inner.write(buf)
}
}
pub struct Restorer;
impl SturdyRefRestorer for Restorer {
fn restore(&self, obj_id : AnyPointer::Reader) -> Option<~ClientHook:Send> {
if obj_id.is_null() {
let client : UiView::Client = FromServer::new(None::<LocalClient>, ~UiViewImpl);
Some(client.client.hook)
} else {
None
}
}
}
pub fn main() -> ::std::io::IoResult<()> {
let ifs = try!(FdStream::new(3));
let ofs = try!(FdStream::new(3));
let connection_state = RpcConnectionState::new();
connection_state.run(ifs, ofs, Restorer);
Ok(())
}
|
//! Provides the server and handles the incomming requests
//! All ports are handled by the same function
// System modules:
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::thread::spawn;
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use std::io;
use time;
use mysql;
use mysql::{OptsBuilder, Pool, Value};
use mysql::conn::QueryResult;
use std::process;
// Internal modules:
use configuration::{Configuration, HEADER_LENGTH};
use data_parser::{parse_text_data, parse_binary_data, StationDataType};
quick_error! {
#[derive(Debug)]
pub enum StoreDataError {
IOError(error: io::Error) { from() }
MySQLError(error: mysql::Error) { from() }
TimeParseError(error: time::ParseError) { from() }
}
}
pub fn init_db(config: &Configuration) -> Pool {
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some(config.hostname.as_ref()))
.db_name(Some(config.db_name.as_ref()))
.user(Some(config.username.as_ref()))
.pass(Some(config.password.as_ref()));
match Pool::new(db_builder) {
Ok(db_pool) => db_pool,
Err(e) => {
info!("Database error: {}", e);
process::exit(1);
}
}
}
pub fn store_to_db<'a>(db_pool: &Pool, station_name: &str, data: &StationDataType) -> Result<Option<QueryResult<'a>>, StoreDataError> {
let datetime_format = "%Y-%m-%d %H:%M:%S";
match data {
&StationDataType::SimpleData(timestamp_tm, voltage1, voltage2, wind_dir) => {
let timestamp = try!(timestamp_tm.strftime(&datetime_format));
let result = try!(db_pool.prep_exec("INSERT INTO battery_data (
timestamp,
station,
battery_voltage,
li_battery_voltage,
wind_dir
) VALUES (
:timestamp,
:station,
:battery_voltage,
:li_battery_voltage,
:wind_dir
)", (
Value::from(timestamp.to_string()),
Value::from(station_name),
Value::from(voltage1),
Value::from(voltage2),
Value::from(wind_dir)
)));
return Ok(Some(result));
},
&StationDataType::MultipleData(ref full_data_set) => {
let timestamp = try!(full_data_set.timestamp.strftime(&datetime_format));
let result = try!(db_pool.prep_exec("INSERT INTO multiple_data (
timestamp,
station,
air_temperature,
air_relative_humidity,
solar_radiation,
soil_water_content,
soil_temperature,
wind_speed,
wind_max,
wind_direction,
precipitation,
air_pressure
) VALUES (
:timestamp,
:station,
:air_temperature,
:air_relative_humidity,
:solar_radiation,
:soil_water_content,
:soil_temperature,
:wind_speed,
:wind_max,
:wind_direction,
:precipitation,
:air_pressure
)", (
Value::from(timestamp.to_string()),
Value::from(station_name),
Value::from(full_data_set.air_temperature),
Value::from(full_data_set.air_relative_humidity),
Value::from(full_data_set.solar_radiation),
Value::from(full_data_set.soil_water_content),
Value::from(full_data_set.soil_temperature),
Value::from(full_data_set.wind_speed),
Value::from(full_data_set.wind_max),
Value::from(full_data_set.wind_direction),
Value::from(full_data_set.precipitation),
Value::from(full_data_set.air_pressure)
)));
return Ok(Some(result));
}
}
}
fn port_to_station(port: u16) -> String{
match port {
2100 => "Nahuelbuta".to_string(),
2101 => "Santa_Gracia".to_string(),
2102 => "Pan_de_Azucar".to_string(),
2103 => "La_Campana".to_string(),
2104 => "Wanne_Tuebingen".to_string(),
2001 => "test1".to_string(),
2200 => "test2".to_string(),
_ => "unknown".to_string()
}
}
fn handle_client<'a>(stream: &mut TcpStream, remote_addr: &SocketAddr,
db_pool: &Arc<Mutex<Pool>>) -> Result<Option<QueryResult<'a>>, StoreDataError> {
info!("Client socket address: {}", remote_addr);
let local_addr = try!(stream.local_addr());
let local_port = match local_addr {
SocketAddr::V4(local_addr) => local_addr.port(),
SocketAddr::V6(local_addr) => local_addr.port()
};
info!("Port: {}", local_port);
let mut buffer = Vec::new();
let len = try!(stream.read_to_end(&mut buffer));
info!("[{}] Number of bytes received: {}", local_port, len);
if buffer.len() > HEADER_LENGTH {
let station_name = port_to_station(local_port);
let (_, buffer_right) = buffer.split_at(HEADER_LENGTH);
// let str_header = String::from_utf8_lossy(buffer_left);
// let str_data = String::from_utf8_lossy(buffer_right);
// info!("Header: {:?}", buffer_left);
info!("[{}] Data: {:?}", local_port, buffer_right);
// info!("Header (ASCII) ({}): '{}'", &station_name, str_header);
// info!("Data (ASCII) ({}): '{}'", &station_name, str_data);
// Quick hack for now, remove later when everything is binary
if local_port == 2101 || local_port == 2103 || local_port == 2001 {
info!("Parse text data");
match parse_text_data(&buffer_right) {
Ok(parsed_data) => {
info!("Data parsed correctly");
match db_pool.lock() {
Ok(db_pool) => {
try!(store_to_db(&db_pool, &station_name, &parsed_data));
},
Err(e) => info!("Mutex (poison) error (db_pool): {}", e)
}
},
Err(e) => {
info!("Could not parse data: {}", e);
}
}
} else {
info!("Parse binary data");
for (counter, parsed_data) in parse_binary_data(&buffer_right).iter().enumerate() {
match *parsed_data {
Ok(ref parsed_data) => {
info!("Data parsed correctly ({})", counter);
match db_pool.lock() {
Ok(db_pool) => {
try!(store_to_db(&db_pool, &station_name, &parsed_data));
},
Err(e) => info!("Mutex (poison) error (db_pool): {}", e)
}
},
Err(ref e) => {
info!("Could not parse data: {}", e);
}
}
}
}
} else if buffer.len() < HEADER_LENGTH {
info!("[{}] Invalid header (less than {} bytes received)!", local_port, HEADER_LENGTH);
info!("[{}] Bytes: {:?}", local_port, buffer);
// info!("Bytes (ASCII): '{}'", String::from_utf8_lossy(&buffer));
} else { // buffer.len() == HEADER_LENGTH -> no data, only header
info!("[{}] No data received, just header.", local_port);
info!("[{}] Bytes: {:?}", local_port, buffer);
// info!("Bytes (ASCII): '{}'", String::from_utf8_lossy(&buffer));
}
info!("handle_client finished");
Ok(None)
}
pub fn start_service(config: &Configuration) {
let mut listeners = Vec::new();
for port in &config.ports {
match TcpListener::bind(("0.0.0.0", *port)) {
Ok(listener) => {
info!("Create listener for port {}", port);
listeners.push(listener);
},
Err(e) => {
info!("Network error: {}", e);
process::exit(1);
}
}
}
let db_pool = Arc::new(Mutex::new(init_db(&config)));
for listener in listeners {
let cloned_pool = db_pool.clone();
spawn(move|| {
loop {
let result = listener.accept();
if let Ok(result) = result {
let (mut stream, addr) = result;
match handle_client(&mut stream, &addr, &cloned_pool) {
Ok(None) => {},
Ok(Some(query_result)) => { info!("Database insert successfull: {}, {}",
query_result.affected_rows(), query_result.last_insert_id()) },
Err(StoreDataError::MySQLError(db_error)) => { info!("DB Error: {}", db_error) },
Err(StoreDataError::IOError(io_error)) => { info!("IO Error: {}", io_error) },
Err(StoreDataError::TimeParseError(time_error)) => { info!("Time parse Error: {}", time_error) }
}
}
}
});
}
}
#[cfg(test)]
mod tests {
use std::net::TcpStream;
use std::time::Duration;
use std::thread::sleep;
use std::io::Write;
use time::{strptime};
use mysql::{Value, Pool, OptsBuilder};
use chrono::naive::datetime::NaiveDateTime;
use flexi_logger::{detailed_format, init, LogConfig};
use configuration::Configuration;
use data_parser::{StationDataType, WeatherStationData};
use super::{store_to_db, port_to_station, start_service};
#[test]
fn test_port_to_station() {
assert_eq!(port_to_station(2100), "Nahuelbuta");
assert_eq!(port_to_station(2101), "Santa_Gracia");
assert_eq!(port_to_station(2102), "Pan_de_Azucar");
assert_eq!(port_to_station(2103), "La_Campana");
assert_eq!(port_to_station(2104), "Wanne_Tuebingen");
assert_eq!(port_to_station(2105), "unknown");
}
#[test]
fn test_store_to_db1() {
// let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
let query_result = store_to_db(&pool, "test_store1", &StationDataType::SimpleData(strptime("2016-06-12 12:13:14",
"%Y-%m-%d %H:%M:%S").unwrap(), 12.73, 0.0, 0.0));
let query_result = query_result.unwrap().unwrap();
let affected_rows = query_result.affected_rows();
assert_eq!(affected_rows, 1);
let last_insert_id = query_result.last_insert_id();
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE id = (:id)", (Value::from(last_insert_id),)).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_id: u64 = row_item.get(0).unwrap();
assert_eq!(row_id, last_insert_id);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-06-12 12:13:14", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test_store1");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 12.73);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test_store1'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_store_to_db2() {
// let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
let query_result = store_to_db(&pool, "test_store2", &StationDataType::MultipleData(WeatherStationData{
timestamp: strptime("2016-06-15 15:16:17", "%Y-%m-%d %H:%M:%S").unwrap(),
air_temperature: 18.15,
air_relative_humidity: 65.31,
solar_radiation: 620.4,
soil_water_content: 0.056,
soil_temperature: 16.25,
wind_speed: 4.713,
wind_max: 9.5,
wind_direction: 257.9,
precipitation: 1.232,
air_pressure: 981.4
}));
let query_result = query_result.unwrap().unwrap();
let affected_rows = query_result.affected_rows();
assert_eq!(affected_rows, 1);
let last_insert_id = query_result.last_insert_id();
let select_result = pool.prep_exec("SELECT * FROM multiple_data WHERE id = (:id)", (Value::from(last_insert_id),)).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 13);
let row_id: u64 = row_item.get(0).unwrap();
assert_eq!(row_id, last_insert_id);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-06-15 15:16:17", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test_store2");
let row_air_temperature: f64 = row_item.get(3).unwrap();
assert_eq!(row_air_temperature, 18.15);
let row_air_relative_humidity: f64 = row_item.get(4).unwrap();
assert_eq!(row_air_relative_humidity, 65.31);
let row_solar_radiation: f64 = row_item.get(5).unwrap();
assert_eq!(row_solar_radiation, 620.4 );
let row_soil_water_content: f64 = row_item.get(6).unwrap();
assert_eq!(row_soil_water_content, 0.056);
let row_soil_temperature: f64 = row_item.get(7).unwrap();
assert_eq!(row_soil_temperature, 16.25);
let row_wind_speed: f64 = row_item.get(8).unwrap();
assert_eq!(row_wind_speed, 4.713);
let row_wind_max: f64 = row_item.get(9).unwrap();
assert_eq!(row_wind_max, 9.5);
let row_wind_direction: f64 = row_item.get(10).unwrap();
assert_eq!(row_wind_direction, 257.9);
let row_precipitation: f64 = row_item.get(11).unwrap();
assert_eq!(row_precipitation, 1.232);
let row_air_pressure: f64 = row_item.get(12).unwrap();
assert_eq!(row_air_pressure, 981.4);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM multiple_data WHERE station = 'test_store2'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_server1() {
let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let config = Configuration {
ports: vec![2001],
log_level: "info".to_string(),
hostname: "localhost".to_string(),
db_name: "test_weatherstation".to_string(),
username: "test".to_string(),
password: "test".to_string(),
binary_filename: None,
binary_station_name: None
};
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
info!("DB connection successfull!");
// Make sure that there is no old data laying around
let _ = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test1'", ()).unwrap();
start_service(&config);
info!("Wait for server...");
// Wait for the server to start up.
sleep(Duration::new(1, 0));
info!("Wait end!");
{
// Connect to local server
let mut stream = TcpStream::connect("127.0.0.1:2001").unwrap();
let result = stream.write_fmt(format_args!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"2016-04-17 17:29:22\",7.53,0"));
assert!(result.is_ok());
} // Socket gets closed here!
info!("Wait for client...");
// Wait for the client to submit the data.
// Wait for the server to parse and process the data.
sleep(Duration::new(1, 0));
info!("Wait end!");
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE station = 'test1'", ()).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-04-17 17:29:22", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test1");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 7.53);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test1'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_server2() {
let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let config = Configuration {
ports: vec![2200],
log_level: "info".to_string(),
hostname: "localhost".to_string(),
db_name: "test_weatherstation".to_string(),
username: "test".to_string(),
password: "test".to_string(),
binary_filename: None,
binary_station_name: None
};
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
info!("DB connection successfull!");
// Make sure that there is no old data laying around
let _ = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test2'", ()).unwrap();
start_service(&config);
info!("Wait for server...");
// Wait for the server to start up.
sleep(Duration::new(1, 0));
info!("Wait end!");
{
// Connect to local server
let mut stream = TcpStream::connect("127.0.0.1:2200").unwrap();
let result = stream.write(&vec![0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,12,0,141,64,50,0,0,0,0,68,252,96,0,0,0]);
assert!(result.is_ok());
} // Socket gets closed here!
info!("Wait for client...");
// Wait for the client to submit the data.
// Wait for the server to parse and process the data.
sleep(Duration::new(1, 0));
info!("Wait end!");
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE station = 'test2'", ()).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-09-19 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test2");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 12.76);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test2'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
// Test server:
// echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"2016-07-06 00:00:00",12.71,0 | nc localhost 2001
// echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"2016-07-06 12:00:00",13.86,9.98,356.3,0.055,14.12,1.248,2.6,121.7,0,979 | nc localhost 2001
}
show station name, start counter with 1
//! Provides the server and handles the incomming requests
//! All ports are handled by the same function
// System modules:
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::thread::spawn;
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use std::io;
use time;
use mysql;
use mysql::{OptsBuilder, Pool, Value};
use mysql::conn::QueryResult;
use std::process;
// Internal modules:
use configuration::{Configuration, HEADER_LENGTH};
use data_parser::{parse_text_data, parse_binary_data, StationDataType};
quick_error! {
#[derive(Debug)]
pub enum StoreDataError {
IOError(error: io::Error) { from() }
MySQLError(error: mysql::Error) { from() }
TimeParseError(error: time::ParseError) { from() }
}
}
pub fn init_db(config: &Configuration) -> Pool {
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some(config.hostname.as_ref()))
.db_name(Some(config.db_name.as_ref()))
.user(Some(config.username.as_ref()))
.pass(Some(config.password.as_ref()));
match Pool::new(db_builder) {
Ok(db_pool) => db_pool,
Err(e) => {
info!("Database error: {}", e);
process::exit(1);
}
}
}
pub fn store_to_db<'a>(db_pool: &Pool, station_name: &str, data: &StationDataType) -> Result<Option<QueryResult<'a>>, StoreDataError> {
let datetime_format = "%Y-%m-%d %H:%M:%S";
match data {
&StationDataType::SimpleData(timestamp_tm, voltage1, voltage2, wind_dir) => {
let timestamp = try!(timestamp_tm.strftime(&datetime_format));
let result = try!(db_pool.prep_exec("INSERT INTO battery_data (
timestamp,
station,
battery_voltage,
li_battery_voltage,
wind_dir
) VALUES (
:timestamp,
:station,
:battery_voltage,
:li_battery_voltage,
:wind_dir
)", (
Value::from(timestamp.to_string()),
Value::from(station_name),
Value::from(voltage1),
Value::from(voltage2),
Value::from(wind_dir)
)));
return Ok(Some(result));
},
&StationDataType::MultipleData(ref full_data_set) => {
let timestamp = try!(full_data_set.timestamp.strftime(&datetime_format));
let result = try!(db_pool.prep_exec("INSERT INTO multiple_data (
timestamp,
station,
air_temperature,
air_relative_humidity,
solar_radiation,
soil_water_content,
soil_temperature,
wind_speed,
wind_max,
wind_direction,
precipitation,
air_pressure
) VALUES (
:timestamp,
:station,
:air_temperature,
:air_relative_humidity,
:solar_radiation,
:soil_water_content,
:soil_temperature,
:wind_speed,
:wind_max,
:wind_direction,
:precipitation,
:air_pressure
)", (
Value::from(timestamp.to_string()),
Value::from(station_name),
Value::from(full_data_set.air_temperature),
Value::from(full_data_set.air_relative_humidity),
Value::from(full_data_set.solar_radiation),
Value::from(full_data_set.soil_water_content),
Value::from(full_data_set.soil_temperature),
Value::from(full_data_set.wind_speed),
Value::from(full_data_set.wind_max),
Value::from(full_data_set.wind_direction),
Value::from(full_data_set.precipitation),
Value::from(full_data_set.air_pressure)
)));
return Ok(Some(result));
}
}
}
fn port_to_station(port: u16) -> String{
match port {
2100 => "Nahuelbuta".to_string(),
2101 => "Santa_Gracia".to_string(),
2102 => "Pan_de_Azucar".to_string(),
2103 => "La_Campana".to_string(),
2104 => "Wanne_Tuebingen".to_string(),
2001 => "test1".to_string(),
2200 => "test2".to_string(),
_ => "unknown".to_string()
}
}
fn handle_client<'a>(stream: &mut TcpStream, remote_addr: &SocketAddr,
db_pool: &Arc<Mutex<Pool>>) -> Result<Option<QueryResult<'a>>, StoreDataError> {
info!("Client socket address: {}", remote_addr);
let local_addr = try!(stream.local_addr());
let local_port = match local_addr {
SocketAddr::V4(local_addr) => local_addr.port(),
SocketAddr::V6(local_addr) => local_addr.port()
};
info!("Port: {}", local_port);
let mut buffer = Vec::new();
let len = try!(stream.read_to_end(&mut buffer));
info!("[{}] Number of bytes received: {}", local_port, len);
if buffer.len() > HEADER_LENGTH {
let station_name = port_to_station(local_port);
let (_, buffer_right) = buffer.split_at(HEADER_LENGTH);
// let str_header = String::from_utf8_lossy(buffer_left);
// let str_data = String::from_utf8_lossy(buffer_right);
// info!("Header: {:?}", buffer_left);
info!("[{}] Data: {:?}", local_port, buffer_right);
// info!("Header (ASCII) ({}): '{}'", &station_name, str_header);
// info!("Data (ASCII) ({}): '{}'", &station_name, str_data);
// Quick hack for now, remove later when everything is binary
if local_port == 2101 || local_port == 2103 || local_port == 2001 {
info!("Parse text data for {}", &station_name);
match parse_text_data(&buffer_right) {
Ok(parsed_data) => {
info!("Data parsed correctly");
match db_pool.lock() {
Ok(db_pool) => {
try!(store_to_db(&db_pool, &station_name, &parsed_data));
},
Err(e) => info!("Mutex (poison) error (db_pool): {}", e)
}
},
Err(e) => {
info!("Could not parse data: {}", e);
}
}
} else {
info!("Parse binary data for {}", &station_name);
for (counter, parsed_data) in parse_binary_data(&buffer_right).iter().enumerate() {
match *parsed_data {
Ok(ref parsed_data) => {
info!("Data parsed correctly ({})", counter + 1);
match db_pool.lock() {
Ok(db_pool) => {
try!(store_to_db(&db_pool, &station_name, &parsed_data));
},
Err(e) => info!("Mutex (poison) error (db_pool): {}", e)
}
},
Err(ref e) => {
info!("Could not parse data: {}", e);
}
}
}
}
} else if buffer.len() < HEADER_LENGTH {
info!("[{}] Invalid header (less than {} bytes received)!", local_port, HEADER_LENGTH);
info!("[{}] Bytes: {:?}", local_port, buffer);
// info!("Bytes (ASCII): '{}'", String::from_utf8_lossy(&buffer));
} else { // buffer.len() == HEADER_LENGTH -> no data, only header
info!("[{}] No data received, just header.", local_port);
info!("[{}] Bytes: {:?}", local_port, buffer);
// info!("Bytes (ASCII): '{}'", String::from_utf8_lossy(&buffer));
}
info!("handle_client finished");
Ok(None)
}
pub fn start_service(config: &Configuration) {
let mut listeners = Vec::new();
for port in &config.ports {
match TcpListener::bind(("0.0.0.0", *port)) {
Ok(listener) => {
info!("Create listener for port {}", port);
listeners.push(listener);
},
Err(e) => {
info!("Network error: {}", e);
process::exit(1);
}
}
}
let db_pool = Arc::new(Mutex::new(init_db(&config)));
for listener in listeners {
let cloned_pool = db_pool.clone();
spawn(move|| {
loop {
let result = listener.accept();
if let Ok(result) = result {
let (mut stream, addr) = result;
match handle_client(&mut stream, &addr, &cloned_pool) {
Ok(None) => {},
Ok(Some(query_result)) => { info!("Database insert successfull: {}, {}",
query_result.affected_rows(), query_result.last_insert_id()) },
Err(StoreDataError::MySQLError(db_error)) => { info!("DB Error: {}", db_error) },
Err(StoreDataError::IOError(io_error)) => { info!("IO Error: {}", io_error) },
Err(StoreDataError::TimeParseError(time_error)) => { info!("Time parse Error: {}", time_error) }
}
}
}
});
}
}
#[cfg(test)]
mod tests {
use std::net::TcpStream;
use std::time::Duration;
use std::thread::sleep;
use std::io::Write;
use time::{strptime};
use mysql::{Value, Pool, OptsBuilder};
use chrono::naive::datetime::NaiveDateTime;
use flexi_logger::{detailed_format, init, LogConfig};
use configuration::Configuration;
use data_parser::{StationDataType, WeatherStationData};
use super::{store_to_db, port_to_station, start_service};
#[test]
fn test_port_to_station() {
assert_eq!(port_to_station(2100), "Nahuelbuta");
assert_eq!(port_to_station(2101), "Santa_Gracia");
assert_eq!(port_to_station(2102), "Pan_de_Azucar");
assert_eq!(port_to_station(2103), "La_Campana");
assert_eq!(port_to_station(2104), "Wanne_Tuebingen");
assert_eq!(port_to_station(2105), "unknown");
}
#[test]
fn test_store_to_db1() {
// let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
let query_result = store_to_db(&pool, "test_store1", &StationDataType::SimpleData(strptime("2016-06-12 12:13:14",
"%Y-%m-%d %H:%M:%S").unwrap(), 12.73, 0.0, 0.0));
let query_result = query_result.unwrap().unwrap();
let affected_rows = query_result.affected_rows();
assert_eq!(affected_rows, 1);
let last_insert_id = query_result.last_insert_id();
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE id = (:id)", (Value::from(last_insert_id),)).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_id: u64 = row_item.get(0).unwrap();
assert_eq!(row_id, last_insert_id);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-06-12 12:13:14", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test_store1");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 12.73);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test_store1'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_store_to_db2() {
// let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
let query_result = store_to_db(&pool, "test_store2", &StationDataType::MultipleData(WeatherStationData{
timestamp: strptime("2016-06-15 15:16:17", "%Y-%m-%d %H:%M:%S").unwrap(),
air_temperature: 18.15,
air_relative_humidity: 65.31,
solar_radiation: 620.4,
soil_water_content: 0.056,
soil_temperature: 16.25,
wind_speed: 4.713,
wind_max: 9.5,
wind_direction: 257.9,
precipitation: 1.232,
air_pressure: 981.4
}));
let query_result = query_result.unwrap().unwrap();
let affected_rows = query_result.affected_rows();
assert_eq!(affected_rows, 1);
let last_insert_id = query_result.last_insert_id();
let select_result = pool.prep_exec("SELECT * FROM multiple_data WHERE id = (:id)", (Value::from(last_insert_id),)).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 13);
let row_id: u64 = row_item.get(0).unwrap();
assert_eq!(row_id, last_insert_id);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-06-15 15:16:17", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test_store2");
let row_air_temperature: f64 = row_item.get(3).unwrap();
assert_eq!(row_air_temperature, 18.15);
let row_air_relative_humidity: f64 = row_item.get(4).unwrap();
assert_eq!(row_air_relative_humidity, 65.31);
let row_solar_radiation: f64 = row_item.get(5).unwrap();
assert_eq!(row_solar_radiation, 620.4 );
let row_soil_water_content: f64 = row_item.get(6).unwrap();
assert_eq!(row_soil_water_content, 0.056);
let row_soil_temperature: f64 = row_item.get(7).unwrap();
assert_eq!(row_soil_temperature, 16.25);
let row_wind_speed: f64 = row_item.get(8).unwrap();
assert_eq!(row_wind_speed, 4.713);
let row_wind_max: f64 = row_item.get(9).unwrap();
assert_eq!(row_wind_max, 9.5);
let row_wind_direction: f64 = row_item.get(10).unwrap();
assert_eq!(row_wind_direction, 257.9);
let row_precipitation: f64 = row_item.get(11).unwrap();
assert_eq!(row_precipitation, 1.232);
let row_air_pressure: f64 = row_item.get(12).unwrap();
assert_eq!(row_air_pressure, 981.4);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM multiple_data WHERE station = 'test_store2'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_server1() {
let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let config = Configuration {
ports: vec![2001],
log_level: "info".to_string(),
hostname: "localhost".to_string(),
db_name: "test_weatherstation".to_string(),
username: "test".to_string(),
password: "test".to_string(),
binary_filename: None,
binary_station_name: None
};
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
info!("DB connection successfull!");
// Make sure that there is no old data laying around
let _ = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test1'", ()).unwrap();
start_service(&config);
info!("Wait for server...");
// Wait for the server to start up.
sleep(Duration::new(1, 0));
info!("Wait end!");
{
// Connect to local server
let mut stream = TcpStream::connect("127.0.0.1:2001").unwrap();
let result = stream.write_fmt(format_args!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"2016-04-17 17:29:22\",7.53,0"));
assert!(result.is_ok());
} // Socket gets closed here!
info!("Wait for client...");
// Wait for the client to submit the data.
// Wait for the server to parse and process the data.
sleep(Duration::new(1, 0));
info!("Wait end!");
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE station = 'test1'", ()).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-04-17 17:29:22", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test1");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 7.53);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test1'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
#[test]
fn test_server2() {
let _ = init(LogConfig { log_to_file: true, format: detailed_format, .. LogConfig::new() }, Some("info".to_string()));
let config = Configuration {
ports: vec![2200],
log_level: "info".to_string(),
hostname: "localhost".to_string(),
db_name: "test_weatherstation".to_string(),
username: "test".to_string(),
password: "test".to_string(),
binary_filename: None,
binary_station_name: None
};
let mut db_builder = OptsBuilder::new();
db_builder.ip_or_hostname(Some("localhost"))
.tcp_port(3306)
.user(Some("test"))
.pass(Some("test"))
.db_name(Some("test_weatherstation"));
let pool = Pool::new(db_builder).unwrap();
info!("DB connection successfull!");
// Make sure that there is no old data laying around
let _ = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test2'", ()).unwrap();
start_service(&config);
info!("Wait for server...");
// Wait for the server to start up.
sleep(Duration::new(1, 0));
info!("Wait end!");
{
// Connect to local server
let mut stream = TcpStream::connect("127.0.0.1:2200").unwrap();
let result = stream.write(&vec![0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,12,0,141,64,50,0,0,0,0,68,252,96,0,0,0]);
assert!(result.is_ok());
} // Socket gets closed here!
info!("Wait for client...");
// Wait for the client to submit the data.
// Wait for the server to parse and process the data.
sleep(Duration::new(1, 0));
info!("Wait end!");
let select_result = pool.prep_exec("SELECT * FROM battery_data WHERE station = 'test2'", ()).unwrap();
let mut count = 0;
for opt_item in select_result {
let mut row_item = opt_item.unwrap();
assert_eq!(row_item.len(), 6);
let row_timestamp: NaiveDateTime = row_item.get(1).unwrap();
assert_eq!(row_timestamp, NaiveDateTime::parse_from_str("2016-09-19 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap());
let row_station: String = row_item.get(2).unwrap();
assert_eq!(row_station, "test2");
let row_voltage: f64 = row_item.get(3).unwrap();
assert_eq!(row_voltage, 12.76);
count = count + 1;
}
assert_eq!(count, 1);
let delete_result = pool.prep_exec("DELETE FROM battery_data WHERE station = 'test2'", ()).unwrap();
assert_eq!(delete_result.affected_rows(), 1);
}
// Test server:
// echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"2016-07-06 00:00:00",12.71,0 | nc localhost 2001
// echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"2016-07-06 12:00:00",13.86,9.98,356.3,0.055,14.12,1.248,2.6,121.7,0,979 | nc localhost 2001
}
|
// Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// For tokio_io::codec::length_delimited::Framed;
#![allow(deprecated)]
use crate::cache::{storage_from_config, Storage};
use crate::compiler::{
get_compiler_info, CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher,
CompilerKind, DistType, MissType,
};
#[cfg(feature = "dist-client")]
use crate::config;
use crate::config::Config;
use crate::dist;
use crate::dist::Client as DistClient;
use crate::jobserver::Client;
use crate::mock_command::{CommandCreatorSync, ProcessCommandCreator};
use crate::protocol::{Compile, CompileFinished, CompileResponse, Request, Response};
use crate::util;
use filetime::FileTime;
use futures::sync::mpsc;
use futures::task::{self, Task};
use futures::{future, stream, Async, AsyncSink, Future, Poll, Sink, StartSend, Stream};
use futures_cpupool::CpuPool;
use number_prefix::{binary_prefix, Prefixed, Standalone};
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::metadata;
use std::io::{self, Write};
#[cfg(feature = "dist-client")]
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use std::rc::Rc;
use std::sync::Arc;
#[cfg(feature = "dist-client")]
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use std::u64;
use tokio::runtime::current_thread::Runtime;
use tokio_io::codec::length_delimited;
use tokio_io::codec::length_delimited::Framed;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_serde_bincode::{ReadBincode, WriteBincode};
use tokio_tcp::TcpListener;
use tokio_timer::{Delay, Timeout};
use tower::Service;
use crate::errors::*;
/// If the server is idle for this many seconds, shut down.
const DEFAULT_IDLE_TIMEOUT: u64 = 600;
/// If the dist client couldn't be created, retry creation at this number
/// of seconds from now (or later)
#[cfg(feature = "dist-client")]
const DIST_CLIENT_RECREATE_TIMEOUT: Duration = Duration::from_secs(30);
/// Result of background server startup.
#[derive(Debug, Serialize, Deserialize)]
pub enum ServerStartup {
/// Server started successfully on `port`.
Ok { port: u16 },
/// Timed out waiting for server startup.
TimedOut,
/// Server encountered an error.
Err { reason: String },
}
/// Get the time the server should idle for before shutting down.
fn get_idle_timeout() -> u64 {
// A value of 0 disables idle shutdown entirely.
env::var("SCCACHE_IDLE_TIMEOUT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_IDLE_TIMEOUT)
}
fn notify_server_startup_internal<W: Write>(mut w: W, status: ServerStartup) -> Result<()> {
util::write_length_prefixed_bincode(&mut w, status)
}
#[cfg(unix)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use std::os::unix::net::UnixStream;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
debug!("notify_server_startup({:?})", status);
let stream = UnixStream::connect(name)?;
notify_server_startup_internal(stream, status)
}
#[cfg(windows)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use std::fs::OpenOptions;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
let pipe = OpenOptions::new().write(true).read(true).open(name)?;
notify_server_startup_internal(pipe, status)
}
#[cfg(unix)]
fn get_signal(status: ExitStatus) -> i32 {
use std::os::unix::prelude::*;
status.signal().expect("must have signal")
}
#[cfg(windows)]
fn get_signal(_status: ExitStatus) -> i32 {
panic!("no signals on windows")
}
pub struct DistClientContainer {
// The actual dist client state
#[cfg(feature = "dist-client")]
state: Mutex<DistClientState>,
}
#[cfg(feature = "dist-client")]
struct DistClientConfig {
// Reusable items tied to an SccacheServer instance
pool: CpuPool,
// From the static dist configuration
scheduler_url: Option<config::HTTPUrl>,
auth: config::DistAuth,
cache_dir: PathBuf,
toolchain_cache_size: u64,
toolchains: Vec<config::DistToolchainConfig>,
rewrite_includes_only: bool,
}
#[cfg(feature = "dist-client")]
enum DistClientState {
#[cfg(feature = "dist-client")]
Some(DistClientConfig, Arc<dyn dist::Client>),
#[cfg(feature = "dist-client")]
FailWithMessage(DistClientConfig, String),
#[cfg(feature = "dist-client")]
RetryCreateAt(DistClientConfig, Instant),
Disabled,
}
#[cfg(not(feature = "dist-client"))]
impl DistClientContainer {
#[cfg(not(feature = "dist-client"))]
fn new(config: &Config, _: &CpuPool) -> Self {
if let Some(_) = config.dist.scheduler_url {
warn!("Scheduler address configured but dist feature disabled, disabling distributed sccache")
}
Self {}
}
pub fn new_disabled() -> Self {
Self {}
}
pub fn reset_state(&self) {}
pub fn get_status(&self) -> DistInfo {
DistInfo::Disabled("dist-client feature not selected".to_string())
}
fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
Ok(None)
}
}
#[cfg(feature = "dist-client")]
impl DistClientContainer {
fn new(config: &Config, pool: &CpuPool) -> Self {
let config = DistClientConfig {
pool: pool.clone(),
scheduler_url: config.dist.scheduler_url.clone(),
auth: config.dist.auth.clone(),
cache_dir: config.dist.cache_dir.clone(),
toolchain_cache_size: config.dist.toolchain_cache_size,
toolchains: config.dist.toolchains.clone(),
rewrite_includes_only: config.dist.rewrite_includes_only,
};
let state = Self::create_state(config);
Self {
state: Mutex::new(state),
}
}
pub fn new_disabled() -> Self {
Self {
state: Mutex::new(DistClientState::Disabled),
}
}
pub fn reset_state(&self) {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
match mem::replace(state, DistClientState::Disabled) {
DistClientState::Some(cfg, _)
| DistClientState::FailWithMessage(cfg, _)
| DistClientState::RetryCreateAt(cfg, _) => {
warn!("State reset. Will recreate");
*state =
DistClientState::RetryCreateAt(cfg, Instant::now() - Duration::from_secs(1));
}
DistClientState::Disabled => (),
}
}
pub fn get_status(&self) -> DistInfo {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
match state {
DistClientState::Disabled => DistInfo::Disabled("disabled".to_string()),
DistClientState::FailWithMessage(cfg, _) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, auth not configured".to_string(),
),
DistClientState::RetryCreateAt(cfg, _) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, not connected, will retry".to_string(),
),
DistClientState::Some(cfg, client) => match client.do_get_status().wait() {
Ok(res) => DistInfo::SchedulerStatus(cfg.scheduler_url.clone(), res),
Err(_) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"could not communicate with scheduler".to_string(),
),
},
}
}
fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
Self::maybe_recreate_state(state);
let res = match state {
DistClientState::Some(_, dc) => Ok(Some(dc.clone())),
DistClientState::Disabled | DistClientState::RetryCreateAt(_, _) => Ok(None),
DistClientState::FailWithMessage(_, msg) => Err(Error::from(msg.clone())),
};
match res {
Err(_) => {
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::FailWithMessage(config, _) => config,
_ => unreachable!(),
};
// The client is most likely mis-configured, make sure we
// re-create on our next attempt.
*state =
DistClientState::RetryCreateAt(config, Instant::now() - Duration::from_secs(1));
}
_ => (),
};
res
}
fn maybe_recreate_state(state: &mut DistClientState) {
if let DistClientState::RetryCreateAt(_, instant) = *state {
if instant > Instant::now() {
return;
}
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::RetryCreateAt(config, _) => config,
_ => unreachable!(),
};
info!("Attempting to recreate the dist client");
*state = Self::create_state(config)
}
}
// Attempt to recreate the dist client
fn create_state(config: DistClientConfig) -> DistClientState {
macro_rules! try_or_retry_later {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
use error_chain::ChainedError;
error!("{}", e.display_chain());
return DistClientState::RetryCreateAt(
config,
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
);
}
}
}};
}
macro_rules! try_or_fail_with_message {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
use error_chain::ChainedError;
let errmsg = e.display_chain();
error!("{}", errmsg);
return DistClientState::FailWithMessage(config, errmsg.to_string());
}
}
}};
}
// TODO: NLL would avoid this clone
match config.scheduler_url.clone() {
Some(addr) => {
let url = addr.to_url();
info!("Enabling distributed sccache to {}", url);
let auth_token = match &config.auth {
config::DistAuth::Token { token } => Ok(token.to_owned()),
config::DistAuth::Oauth2CodeGrantPKCE {
client_id: _,
auth_url,
token_url: _,
}
| config::DistAuth::Oauth2Implicit {
client_id: _,
auth_url,
} => Self::get_cached_config_auth_token(auth_url),
};
let auth_token = try_or_fail_with_message!(auth_token.chain_err(|| {
"could not load client auth token, run |sccache --dist-auth|"
}));
// TODO: NLL would let us move this inside the previous match
let dist_client = dist::http::Client::new(
&config.pool,
url,
&config.cache_dir.join("client"),
config.toolchain_cache_size,
&config.toolchains,
auth_token,
config.rewrite_includes_only,
);
let dist_client = try_or_retry_later!(
dist_client.chain_err(|| "failure during dist client creation")
);
match dist_client.do_get_status().wait() {
Ok(res) => {
info!(
"Successfully created dist client with {:?} cores across {:?} servers",
res.num_cpus, res.num_servers
);
DistClientState::Some(config, Arc::new(dist_client))
}
Err(_) => {
warn!("Scheduler address configured, but could not communicate with scheduler");
DistClientState::RetryCreateAt(
config,
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
)
}
}
}
None => {
info!("No scheduler address configured, disabling distributed sccache");
DistClientState::Disabled
}
}
}
fn get_cached_config_auth_token(auth_url: &str) -> Result<String> {
let cached_config = config::CachedConfig::reload()?;
cached_config
.with(|c| c.dist.auth_tokens.get(auth_url).map(String::to_owned))
.ok_or_else(|| {
Error::from(format!(
"token for url {} not present in cached config",
auth_url
))
})
}
}
/// Start an sccache server, listening on `port`.
///
/// Spins an event loop handling client connections until a client
/// requests a shutdown.
pub fn start_server(config: &Config, port: u16) -> Result<()> {
info!("start_server: port: {}", port);
let client = unsafe { Client::new() };
let runtime = Runtime::new()?;
let pool = CpuPool::new(std::cmp::max(20, 2 * num_cpus::get()));
let dist_client = DistClientContainer::new(config, &pool);
let storage = storage_from_config(config, &pool);
let res = SccacheServer::<ProcessCommandCreator>::new(
port,
pool,
runtime,
client,
dist_client,
storage,
);
let notify = env::var_os("SCCACHE_STARTUP_NOTIFY");
match res {
Ok(srv) => {
let port = srv.port();
info!("server started, listening on port {}", port);
notify_server_startup(¬ify, ServerStartup::Ok { port })?;
srv.run(future::empty::<(), ()>())?;
Ok(())
}
Err(e) => {
error!("failed to start server: {}", e);
let reason = e.to_string();
notify_server_startup(¬ify, ServerStartup::Err { reason })?;
Err(e)
}
}
}
pub struct SccacheServer<C: CommandCreatorSync> {
runtime: Runtime,
listener: TcpListener,
rx: mpsc::Receiver<ServerMessage>,
timeout: Duration,
service: SccacheService<C>,
wait: WaitUntilZero,
}
impl<C: CommandCreatorSync> SccacheServer<C> {
pub fn new(
port: u16,
pool: CpuPool,
runtime: Runtime,
client: Client,
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
) -> Result<SccacheServer<C>> {
let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port);
let listener = TcpListener::bind(&SocketAddr::V4(addr))?;
// Prepare the service which we'll use to service all incoming TCP
// connections.
let (tx, rx) = mpsc::channel(1);
let (wait, info) = WaitUntilZero::new();
let service = SccacheService::new(dist_client, storage, &client, pool, tx, info);
Ok(SccacheServer {
runtime: runtime,
listener: listener,
rx: rx,
service: service,
timeout: Duration::from_secs(get_idle_timeout()),
wait: wait,
})
}
/// Configures how long this server will be idle before shutting down.
#[allow(dead_code)]
pub fn set_idle_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
/// Set the storage this server will use.
#[allow(dead_code)]
pub fn set_storage(&mut self, storage: Arc<dyn Storage>) {
self.service.storage = storage;
}
/// Returns a reference to a thread pool to run work on
#[allow(dead_code)]
pub fn pool(&self) -> &CpuPool {
&self.service.pool
}
/// Returns a reference to the command creator this server will use
#[allow(dead_code)]
pub fn command_creator(&self) -> &C {
&self.service.creator
}
/// Returns the port that this server is bound to
#[allow(dead_code)]
pub fn port(&self) -> u16 {
self.listener.local_addr().unwrap().port()
}
/// Runs this server to completion.
///
/// If the `shutdown` future resolves then the server will be shut down,
/// otherwise the server may naturally shut down if it becomes idle for too
/// long anyway.
pub fn run<F>(self, shutdown: F) -> io::Result<()>
where
F: Future,
{
self._run(Box::new(shutdown.then(|_| Ok(()))))
}
fn _run<'a>(self, shutdown: Box<dyn Future<Item = (), Error = ()> + 'a>) -> io::Result<()> {
let SccacheServer {
mut runtime,
listener,
rx,
service,
timeout,
wait,
} = self;
// Create our "server future" which will simply handle all incoming
// connections in separate tasks.
let server = listener.incoming().for_each(move |socket| {
trace!("incoming connection");
tokio::runtime::current_thread::TaskExecutor::current()
.spawn_local(Box::new(service.clone().bind(socket).map_err(|err| {
error!("{}", err);
})))
.unwrap();
Ok(())
});
// Right now there's a whole bunch of ways to shut down this server for
// various purposes. These include:
//
// 1. The `shutdown` future above.
// 2. An RPC indicating the server should shut down
// 3. A period of inactivity (no requests serviced)
//
// These are all encapsulated wih the future that we're creating below.
// The `ShutdownOrInactive` indicates the RPC or the period of
// inactivity, and this is then select'd with the `shutdown` future
// passed to this function.
let shutdown = shutdown.map(|a| {
info!("shutting down due to explicit signal");
a
});
let mut futures = vec![
Box::new(server) as Box<dyn Future<Item = _, Error = _>>,
Box::new(
shutdown
.map_err(|()| io::Error::new(io::ErrorKind::Other, "shutdown signal failed")),
),
];
let shutdown_idle = ShutdownOrInactive {
rx: rx,
timeout: if timeout != Duration::new(0, 0) {
Some(Delay::new(Instant::now() + timeout))
} else {
None
},
timeout_dur: timeout,
};
futures.push(Box::new(shutdown_idle.map(|a| {
info!("shutting down due to being idle or request");
a
})));
let server = future::select_all(futures);
runtime.block_on(server).map_err(|p| p.0)?;
info!(
"moving into the shutdown phase now, waiting at most 10 seconds \
for all client requests to complete"
);
// Once our server has shut down either due to inactivity or a manual
// request we still need to give a bit of time for all active
// connections to finish. This `wait` future will resolve once all
// instances of `SccacheService` have been dropped.
//
// Note that we cap the amount of time this can take, however, as we
// don't want to wait *too* long.
runtime
.block_on(Timeout::new(wait, Duration::new(10, 0)))
.map_err(|e| {
if e.is_inner() {
e.into_inner().unwrap()
} else {
io::Error::new(io::ErrorKind::Other, e)
}
})?;
info!("ok, fully shutting down now");
Ok(())
}
}
/// Service implementation for sccache
#[derive(Clone)]
struct SccacheService<C: CommandCreatorSync> {
/// Server statistics.
stats: Rc<RefCell<ServerStats>>,
/// Distributed sccache client
dist_client: Rc<DistClientContainer>,
/// Cache storage.
storage: Arc<dyn Storage>,
/// A cache of known compiler info.
compilers: Rc<
RefCell<
HashMap<PathBuf, Option<(Box<dyn Compiler<C>>, FileTime, Option<(PathBuf, FileTime)>)>>,
>,
>,
/// Thread pool to execute work in
pool: CpuPool,
/// An object for creating commands.
///
/// This is mostly useful for unit testing, where we
/// can mock this out.
creator: C,
/// Message channel used to learn about requests received by this server.
///
/// Note that messages sent along this channel will keep the server alive
/// (reset the idle timer) and this channel can also be used to shut down
/// the entire server immediately via a message.
tx: mpsc::Sender<ServerMessage>,
/// Information tracking how many services (connected clients) are active.
info: ActiveInfo,
}
type SccacheRequest = Message<Request, Body<()>>;
type SccacheResponse = Message<Response, Body<Response>>;
/// Messages sent from all services to the main event loop indicating activity.
///
/// Whenever a request is receive a `Request` message is sent which will reset
/// the idle shutdown timer, and otherwise a `Shutdown` message indicates that
/// a server shutdown was requested via an RPC.
pub enum ServerMessage {
/// A message sent whenever a request is received.
Request,
/// Message sent whenever a shutdown request is received.
Shutdown,
}
impl<C> Service<SccacheRequest> for SccacheService<C>
where
C: CommandCreatorSync + 'static,
{
type Response = SccacheResponse;
type Error = Error;
type Future = SFuture<Self::Response>;
fn call(&mut self, req: SccacheRequest) -> Self::Future {
trace!("handle_client");
// Opportunistically let channel know that we've received a request. We
// ignore failures here as well as backpressure as it's not imperative
// that every message is received.
drop(self.tx.clone().start_send(ServerMessage::Request));
let res: SFuture<Response> = match req.into_inner() {
Request::Compile(compile) => {
debug!("handle_client: compile");
self.stats.borrow_mut().compile_requests += 1;
return self.handle_compile(compile);
}
Request::GetStats => {
debug!("handle_client: get_stats");
Box::new(self.get_info().map(Response::Stats))
}
Request::DistStatus => {
debug!("handle_client: dist_status");
Box::new(self.get_dist_status().map(Response::DistStatus))
}
Request::ZeroStats => {
debug!("handle_client: zero_stats");
self.zero_stats();
Box::new(self.get_info().map(Response::Stats))
}
Request::Shutdown => {
debug!("handle_client: shutdown");
let future = self
.tx
.clone()
.send(ServerMessage::Shutdown)
.then(|_| Ok(()));
let info_future = self.get_info();
return Box::new(
future
.join(info_future)
.map(move |(_, info)| Message::WithoutBody(Response::ShuttingDown(info))),
);
}
};
Box::new(res.map(Message::WithoutBody))
}
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
}
impl<C> SccacheService<C>
where
C: CommandCreatorSync,
{
pub fn new(
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
client: &Client,
pool: CpuPool,
tx: mpsc::Sender<ServerMessage>,
info: ActiveInfo,
) -> SccacheService<C> {
SccacheService {
stats: Rc::new(RefCell::new(ServerStats::default())),
dist_client: Rc::new(dist_client),
storage,
compilers: Rc::new(RefCell::new(HashMap::new())),
pool,
creator: C::new(client),
tx,
info,
}
}
fn bind<T>(mut self, socket: T) -> impl Future<Item = (), Error = Error>
where
T: AsyncRead + AsyncWrite + 'static,
{
let mut builder = length_delimited::Builder::new();
if let Ok(max_frame_length_str) = env::var("SCCACHE_MAX_FRAME_LENGTH") {
if let Ok(max_frame_length) = max_frame_length_str.parse::<usize>() {
builder.max_frame_length(max_frame_length);
} else {
warn!("Content of SCCACHE_MAX_FRAME_LENGTH is not a valid number, using default");
}
}
let io = builder.new_framed(socket);
let (sink, stream) = SccacheTransport {
inner: WriteBincode::new(ReadBincode::new(io)),
}
.split();
let sink = sink.sink_from_err::<Error>();
stream
.from_err::<Error>()
.and_then(move |input| self.call(input))
.and_then(|message| {
let f: Box<dyn Stream<Item = _, Error = _>> = match message {
Message::WithoutBody(message) => Box::new(stream::once(Ok(Frame::Message {
message,
body: false,
}))),
Message::WithBody(message, body) => Box::new(
stream::once(Ok(Frame::Message {
message,
body: true,
}))
.chain(body.map(|chunk| Frame::Body { chunk: Some(chunk) }))
.chain(stream::once(Ok(Frame::Body { chunk: None }))),
),
};
Ok(f.from_err::<Error>())
})
.flatten()
.forward(sink)
.map(|_| ())
}
/// Get dist status.
fn get_dist_status(&self) -> SFuture<DistInfo> {
f_ok(self.dist_client.get_status())
}
/// Get info and stats about the cache.
fn get_info(&self) -> SFuture<ServerInfo> {
let stats = self.stats.borrow().clone();
let cache_location = self.storage.location();
Box::new(
self.storage
.current_size()
.join(self.storage.max_size())
.map(move |(cache_size, max_cache_size)| ServerInfo {
stats,
cache_location,
cache_size,
max_cache_size,
}),
)
}
/// Zero stats about the cache.
fn zero_stats(&self) {
*self.stats.borrow_mut() = ServerStats::default();
}
/// Handle a compile request from a client.
///
/// This will handle a compile request entirely, generating a response with
/// the inital information and an optional body which will eventually
/// contain the results of the compilation.
fn handle_compile(&self, compile: Compile) -> SFuture<SccacheResponse> {
let exe = compile.exe;
let cmd = compile.args;
let cwd = compile.cwd;
let env_vars = compile.env_vars;
let me = self.clone();
Box::new(
self.compiler_info(exe.into(), &env_vars)
.map(move |info| me.check_compiler(info, cmd, cwd.into(), env_vars)),
)
}
/// Look up compiler info from the cache for the compiler `path`.
/// If not cached, determine the compiler type and cache the result.
fn compiler_info(
&self,
path: PathBuf,
env: &[(OsString, OsString)],
) -> SFuture<Result<Box<dyn Compiler<C>>>> {
trace!("compiler_info");
let mtime = ftry!(metadata(&path).map(|attr| FileTime::from_last_modification_time(&attr)));
let dist_info = match self.dist_client.get_client() {
Ok(Some(ref client)) => {
if let Some(archive) = client.get_custom_toolchain(&path) {
match metadata(&archive)
.map(|attr| FileTime::from_last_modification_time(&attr))
{
Ok(mtime) => Some((archive, mtime)),
_ => None,
}
} else {
None
}
}
_ => None,
};
//TODO: properly handle rustup overrides. Currently this will
// cache based on the rustup rustc path, ignoring overrides.
// https://github.com/mozilla/sccache/issues/87
let result = match self.compilers.borrow().get(&path) {
// It's a hit only if the mtime and dist archive data matches.
Some(&Some((ref c, ref cached_mtime, ref cached_dist_info))) => {
if *cached_mtime == mtime && *cached_dist_info == dist_info {
Some(c.clone())
} else {
None
}
}
_ => None,
};
match result {
Some(info) => {
trace!("compiler_info cache hit");
f_ok(Ok(info))
}
None => {
trace!("compiler_info cache miss");
// Check the compiler type and return the result when
// finished. This generally involves invoking the compiler,
// so do it asynchronously.
let me = self.clone();
let info = get_compiler_info(
&self.creator,
&path,
env,
&self.pool,
dist_info.clone().map(|(p, _)| p),
);
Box::new(info.then(move |info| {
let map_info = match info {
Ok(ref c) => Some((c.clone(), mtime, dist_info)),
Err(_) => None,
};
me.compilers.borrow_mut().insert(path, map_info);
Ok(info)
}))
}
}
}
/// Check that we can handle and cache `cmd` when run with `compiler`.
/// If so, run `start_compile_task` to execute it.
fn check_compiler(
&self,
compiler: Result<Box<dyn Compiler<C>>>,
cmd: Vec<OsString>,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
) -> SccacheResponse {
let mut stats = self.stats.borrow_mut();
match compiler {
Err(e) => {
debug!("check_compiler: Unsupported compiler: {}", e.to_string());
stats.requests_unsupported_compiler += 1;
return Message::WithoutBody(Response::Compile(
CompileResponse::UnsupportedCompiler(OsString::from(e.to_string())),
));
}
Ok(c) => {
debug!("check_compiler: Supported compiler");
// Now check that we can handle this compiler with
// the provided commandline.
match c.parse_arguments(&cmd, &cwd) {
CompilerArguments::Ok(hasher) => {
debug!("parse_arguments: Ok: {:?}", cmd);
stats.requests_executed += 1;
let (tx, rx) = Body::pair();
self.start_compile_task(c, hasher, cmd, cwd, env_vars, tx);
let res = CompileResponse::CompileStarted;
return Message::WithBody(Response::Compile(res), rx);
}
CompilerArguments::CannotCache(why, extra_info) => {
if let Some(extra_info) = extra_info {
debug!(
"parse_arguments: CannotCache({}, {}): {:?}",
why, extra_info, cmd
)
} else {
debug!("parse_arguments: CannotCache({}): {:?}", why, cmd)
}
stats.requests_not_cacheable += 1;
*stats.not_cached.entry(why.to_string()).or_insert(0) += 1;
}
CompilerArguments::NotCompilation => {
debug!("parse_arguments: NotCompilation: {:?}", cmd);
stats.requests_not_compile += 1;
}
}
}
}
let res = CompileResponse::UnhandledCompile;
Message::WithoutBody(Response::Compile(res))
}
/// Given compiler arguments `arguments`, look up
/// a compile result in the cache or execute the compilation and store
/// the result in the cache.
fn start_compile_task(
&self,
compiler: Box<dyn Compiler<C>>,
hasher: Box<dyn CompilerHasher<C>>,
arguments: Vec<OsString>,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
tx: mpsc::Sender<Result<Response>>,
) {
let force_recache = env_vars
.iter()
.any(|&(ref k, ref _v)| k.as_os_str() == OsStr::new("SCCACHE_RECACHE"));
let cache_control = if force_recache {
CacheControl::ForceRecache
} else {
CacheControl::Default
};
let out_pretty = hasher.output_pretty().into_owned();
let color_mode = hasher.color_mode();
let result = hasher.get_cached_or_compile(
self.dist_client.get_client(),
self.creator.clone(),
self.storage.clone(),
arguments,
cwd,
env_vars,
cache_control,
self.pool.clone(),
);
let me = self.clone();
let kind = compiler.kind();
let task = result.then(move |result| {
let mut cache_write = None;
let mut stats = me.stats.borrow_mut();
let mut res = CompileFinished::default();
res.color_mode = color_mode;
match result {
Ok((compiled, out)) => {
match compiled {
CompileResult::Error => {
stats.cache_errors.increment(&kind);
}
CompileResult::CacheHit(duration) => {
stats.cache_hits.increment(&kind);
stats.cache_read_hit_duration += duration;
}
CompileResult::CacheMiss(miss_type, dist_type, duration, future) => {
match dist_type {
DistType::NoDist => {}
DistType::Ok(id) => {
let server = id.addr().to_string();
let server_count =
stats.dist_compiles.entry(server).or_insert(0);
*server_count += 1;
}
DistType::Error => stats.dist_errors += 1,
}
match miss_type {
MissType::Normal => {}
MissType::ForcedRecache => {
stats.forced_recaches += 1;
}
MissType::TimedOut => {
stats.cache_timeouts += 1;
}
MissType::CacheReadError => {
stats.cache_errors.increment(&kind);
}
}
stats.cache_misses.increment(&kind);
stats.cache_read_miss_duration += duration;
cache_write = Some(future);
}
CompileResult::NotCacheable => {
stats.cache_misses.increment(&kind);
stats.non_cacheable_compilations += 1;
}
CompileResult::CompileFailed => {
stats.compile_fails += 1;
}
};
let Output {
status,
stdout,
stderr,
} = out;
trace!("CompileFinished retcode: {}", status);
match status.code() {
Some(code) => res.retcode = Some(code),
None => res.signal = Some(get_signal(status)),
};
res.stdout = stdout;
res.stderr = stderr;
}
Err(Error(ErrorKind::ProcessError(output), _)) => {
debug!("Compilation failed: {:?}", output);
stats.compile_fails += 1;
match output.status.code() {
Some(code) => res.retcode = Some(code),
None => res.signal = Some(get_signal(output.status)),
};
res.stdout = output.stdout;
res.stderr = output.stderr;
}
Err(Error(ErrorKind::HttpClientError(msg), _)) => {
me.dist_client.reset_state();
let errmsg = format!("[{:?}] http error status: {}", out_pretty, msg);
error!("{}", errmsg);
res.retcode = Some(1);
res.stderr = errmsg.as_bytes().to_vec();
}
Err(err) => {
use std::fmt::Write;
error!("[{:?}] fatal error: {}", out_pretty, err);
let mut error = format!("sccache: encountered fatal error\n");
drop(writeln!(error, "sccache: error : {}", err));
for e in err.iter() {
error!("[{:?}] \t{}", out_pretty, e);
drop(writeln!(error, "sccache: cause: {}", e));
}
stats.cache_errors.increment(&kind);
//TODO: figure out a better way to communicate this?
res.retcode = Some(-2);
res.stderr = error.into_bytes();
}
};
let send = tx.send(Ok(Response::CompileFinished(res)));
let me = me.clone();
let cache_write = cache_write.then(move |result| {
match result {
Err(e) => {
debug!("Error executing cache write: {}", e);
me.stats.borrow_mut().cache_write_errors += 1;
}
//TODO: save cache stats!
Ok(Some(info)) => {
debug!(
"[{}]: Cache write finished in {}",
info.object_file_pretty,
util::fmt_duration_as_secs(&info.duration)
);
me.stats.borrow_mut().cache_writes += 1;
me.stats.borrow_mut().cache_write_duration += info.duration;
}
Ok(None) => {}
}
Ok(())
});
send.join(cache_write).then(|_| Ok(()))
});
tokio::runtime::current_thread::TaskExecutor::current()
.spawn_local(Box::new(task))
.unwrap();
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PerLanguageCount {
counts: HashMap<String, u64>,
}
impl PerLanguageCount {
fn increment(&mut self, kind: &CompilerKind) {
let key = kind.lang_kind().clone();
let count = match self.counts.get(&key) {
Some(v) => v + 1,
None => 1,
};
self.counts.insert(key, count);
}
pub fn all(&self) -> u64 {
self.counts.values().sum()
}
pub fn get(&self, key: &str) -> Option<&u64> {
self.counts.get(key)
}
pub fn new() -> PerLanguageCount {
PerLanguageCount {
counts: HashMap::new(),
}
}
}
/// Statistics about the server.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ServerStats {
/// The count of client compile requests.
pub compile_requests: u64,
/// The count of client requests that used an unsupported compiler.
pub requests_unsupported_compiler: u64,
/// The count of client requests that were not compilation.
pub requests_not_compile: u64,
/// The count of client requests that were not cacheable.
pub requests_not_cacheable: u64,
/// The count of client requests that were executed.
pub requests_executed: u64,
/// The count of errors handling compile requests (per language).
pub cache_errors: PerLanguageCount,
/// The count of cache hits for handled compile requests (per language).
pub cache_hits: PerLanguageCount,
/// The count of cache misses for handled compile requests (per language).
pub cache_misses: PerLanguageCount,
/// The count of cache misses because the cache took too long to respond.
pub cache_timeouts: u64,
/// The count of errors reading cache entries.
pub cache_read_errors: u64,
/// The count of compilations which were successful but couldn't be cached.
pub non_cacheable_compilations: u64,
/// The count of compilations which forcibly ignored the cache.
pub forced_recaches: u64,
/// The count of errors writing to cache.
pub cache_write_errors: u64,
/// The number of successful cache writes.
pub cache_writes: u64,
/// The total time spent writing cache entries.
pub cache_write_duration: Duration,
/// The total time spent reading cache hits.
pub cache_read_hit_duration: Duration,
/// The total time spent reading cache misses.
pub cache_read_miss_duration: Duration,
/// The count of compilation failures.
pub compile_fails: u64,
/// Counts of reasons why compiles were not cached.
pub not_cached: HashMap<String, usize>,
/// The count of compilations that were successfully distributed indexed
/// by the server that ran those compilations.
pub dist_compiles: HashMap<String, usize>,
/// The count of compilations that were distributed but failed and had to be re-run locally
pub dist_errors: u64,
}
/// Info and stats about the server.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ServerInfo {
pub stats: ServerStats,
pub cache_location: String,
pub cache_size: Option<u64>,
pub max_cache_size: Option<u64>,
}
/// Status of the dist client.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum DistInfo {
Disabled(String),
#[cfg(feature = "dist-client")]
NotConnected(Option<config::HTTPUrl>, String),
#[cfg(feature = "dist-client")]
SchedulerStatus(Option<config::HTTPUrl>, dist::SchedulerStatusResult),
}
impl Default for ServerStats {
fn default() -> ServerStats {
ServerStats {
compile_requests: u64::default(),
requests_unsupported_compiler: u64::default(),
requests_not_compile: u64::default(),
requests_not_cacheable: u64::default(),
requests_executed: u64::default(),
cache_errors: PerLanguageCount::new(),
cache_hits: PerLanguageCount::new(),
cache_misses: PerLanguageCount::new(),
cache_timeouts: u64::default(),
cache_read_errors: u64::default(),
non_cacheable_compilations: u64::default(),
forced_recaches: u64::default(),
cache_write_errors: u64::default(),
cache_writes: u64::default(),
cache_write_duration: Duration::new(0, 0),
cache_read_hit_duration: Duration::new(0, 0),
cache_read_miss_duration: Duration::new(0, 0),
compile_fails: u64::default(),
not_cached: HashMap::new(),
dist_compiles: HashMap::new(),
dist_errors: u64::default(),
}
}
}
impl ServerStats {
/// Print stats to stdout in a human-readable format.
///
/// Return the formatted width of each of the (name, value) columns.
fn print(&self) -> (usize, usize) {
macro_rules! set_stat {
($vec:ident, $var:expr, $name:expr) => {{
// name, value, suffix length
$vec.push(($name.to_string(), $var.to_string(), 0));
}};
}
macro_rules! set_lang_stat {
($vec:ident, $var:expr, $name:expr) => {{
$vec.push(($name.to_string(), $var.all().to_string(), 0));
let mut sorted_stats: Vec<_> = $var.counts.iter().collect();
sorted_stats.sort_by_key(|v| v.0);
for (lang, count) in sorted_stats.iter() {
$vec.push((format!("{} ({})", $name, lang), count.to_string(), 0));
}
}};
}
macro_rules! set_duration_stat {
($vec:ident, $dur:expr, $num:expr, $name:expr) => {{
let s = if $num > 0 {
$dur / $num as u32
} else {
Default::default()
};
// name, value, suffix length
$vec.push(($name.to_string(), util::fmt_duration_as_secs(&s), 2));
}};
}
let mut stats_vec = vec![];
//TODO: this would be nice to replace with a custom derive implementation.
set_stat!(stats_vec, self.compile_requests, "Compile requests");
set_stat!(
stats_vec,
self.requests_executed,
"Compile requests executed"
);
set_lang_stat!(stats_vec, self.cache_hits, "Cache hits");
set_lang_stat!(stats_vec, self.cache_misses, "Cache misses");
set_stat!(stats_vec, self.cache_timeouts, "Cache timeouts");
set_stat!(stats_vec, self.cache_read_errors, "Cache read errors");
set_stat!(stats_vec, self.forced_recaches, "Forced recaches");
set_stat!(stats_vec, self.cache_write_errors, "Cache write errors");
set_stat!(stats_vec, self.compile_fails, "Compilation failures");
set_lang_stat!(stats_vec, self.cache_errors, "Cache errors");
set_stat!(
stats_vec,
self.non_cacheable_compilations,
"Non-cacheable compilations"
);
set_stat!(
stats_vec,
self.requests_not_cacheable,
"Non-cacheable calls"
);
set_stat!(
stats_vec,
self.requests_not_compile,
"Non-compilation calls"
);
set_stat!(
stats_vec,
self.requests_unsupported_compiler,
"Unsupported compiler calls"
);
set_duration_stat!(
stats_vec,
self.cache_write_duration,
self.cache_writes,
"Average cache write"
);
set_duration_stat!(
stats_vec,
self.cache_read_miss_duration,
self.cache_misses.all(),
"Average cache read miss"
);
set_duration_stat!(
stats_vec,
self.cache_read_hit_duration,
self.cache_hits.all(),
"Average cache read hit"
);
set_stat!(
stats_vec,
self.dist_errors,
"Failed distributed compilations"
);
let name_width = stats_vec
.iter()
.map(|&(ref n, _, _)| n.len())
.max()
.unwrap();
let stat_width = stats_vec
.iter()
.map(|&(_, ref s, _)| s.len())
.max()
.unwrap();
for (name, stat, suffix_len) in stats_vec {
println!(
"{:<name_width$} {:>stat_width$}",
name,
stat,
name_width = name_width,
stat_width = stat_width + suffix_len
);
}
if self.dist_compiles.len() > 0 {
println!("\nSuccessful distributed compiles");
let mut counts: Vec<_> = self.dist_compiles.iter().collect();
counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse());
for (reason, count) in counts {
println!(
" {:<name_width$} {:>stat_width$}",
reason,
count,
name_width = name_width - 2,
stat_width = stat_width
);
}
}
if !self.not_cached.is_empty() {
println!("\nNon-cacheable reasons:");
let mut counts: Vec<_> = self.not_cached.iter().collect();
counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse());
for (reason, count) in counts {
println!(
"{:<name_width$} {:>stat_width$}",
reason,
count,
name_width = name_width,
stat_width = stat_width
);
}
println!("");
}
(name_width, stat_width)
}
}
impl ServerInfo {
/// Print info to stdout in a human-readable format.
pub fn print(&self) {
let (name_width, stat_width) = self.stats.print();
println!(
"{:<name_width$} {}",
"Cache location",
self.cache_location,
name_width = name_width
);
for &(name, val) in &[
("Cache size", &self.cache_size),
("Max cache size", &self.max_cache_size),
] {
if let &Some(val) = val {
let (val, suffix) = match binary_prefix(val as f64) {
Standalone(bytes) => (bytes.to_string(), "bytes".to_string()),
Prefixed(prefix, n) => (format!("{:.0}", n), format!("{}B", prefix)),
};
println!(
"{:<name_width$} {:>stat_width$} {}",
name,
val,
suffix,
name_width = name_width,
stat_width = stat_width
);
}
}
}
}
enum Frame<R, R1> {
Body { chunk: Option<R1> },
Message { message: R, body: bool },
}
struct Body<R> {
receiver: mpsc::Receiver<Result<R>>,
}
impl<R> Body<R> {
fn pair() -> (mpsc::Sender<Result<R>>, Self) {
let (tx, rx) = mpsc::channel(0);
(tx, Body { receiver: rx })
}
}
impl<R> Stream for Body<R> {
type Item = R;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.receiver.poll().unwrap() {
Async::Ready(Some(Ok(item))) => Ok(Async::Ready(Some(item))),
Async::Ready(Some(Err(err))) => Err(err),
Async::Ready(None) => Ok(Async::Ready(None)),
Async::NotReady => Ok(Async::NotReady),
}
}
}
enum Message<R, B> {
WithBody(R, B),
WithoutBody(R),
}
impl<R, B> Message<R, B> {
fn into_inner(self) -> R {
match self {
Message::WithBody(r, _) => r,
Message::WithoutBody(r) => r,
}
}
}
/// Implementation of `Stream + Sink` that tokio-proto is expecting
///
/// This type is composed of a few layers:
///
/// * First there's `I`, the I/O object implementing `AsyncRead` and
/// `AsyncWrite`
/// * Next that's framed using the `length_delimited` module in tokio-io giving
/// us a `Sink` and `Stream` of `BytesMut`.
/// * Next that sink/stream is wrapped in `ReadBincode` which will cause the
/// `Stream` implementation to switch from `BytesMut` to `Request` by parsing
/// the bytes bincode.
/// * Finally that sink/stream is wrapped in `WriteBincode` which will cause the
/// `Sink` implementation to switch from `BytesMut` to `Response` meaning that
/// all `Response` types pushed in will be converted to `BytesMut` and pushed
/// below.
struct SccacheTransport<I: AsyncRead + AsyncWrite> {
inner: WriteBincode<ReadBincode<Framed<I>, Request>, Response>,
}
impl<I: AsyncRead + AsyncWrite> Stream for SccacheTransport<I> {
type Item = Message<Request, Body<()>>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
let msg = try_ready!(self.inner.poll().map_err(|e| {
error!("SccacheTransport::poll failed: {}", e);
io::Error::new(io::ErrorKind::Other, e)
}));
Ok(msg.map(|m| Message::WithoutBody(m)).into())
}
}
impl<I: AsyncRead + AsyncWrite> Sink for SccacheTransport<I> {
type SinkItem = Frame<Response, Response>;
type SinkError = io::Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, io::Error> {
match item {
Frame::Message { message, body } => match self.inner.start_send(message)? {
AsyncSink::Ready => Ok(AsyncSink::Ready),
AsyncSink::NotReady(message) => Ok(AsyncSink::NotReady(Frame::Message {
message: message,
body: body,
})),
},
Frame::Body { chunk: Some(chunk) } => match self.inner.start_send(chunk)? {
AsyncSink::Ready => Ok(AsyncSink::Ready),
AsyncSink::NotReady(chunk) => {
Ok(AsyncSink::NotReady(Frame::Body { chunk: Some(chunk) }))
}
},
Frame::Body { chunk: None } => Ok(AsyncSink::Ready),
}
}
fn poll_complete(&mut self) -> Poll<(), io::Error> {
self.inner.poll_complete()
}
fn close(&mut self) -> Poll<(), io::Error> {
self.inner.close()
}
}
struct ShutdownOrInactive {
rx: mpsc::Receiver<ServerMessage>,
timeout: Option<Delay>,
timeout_dur: Duration,
}
impl Future for ShutdownOrInactive {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
loop {
match self.rx.poll().unwrap() {
Async::NotReady => break,
// Shutdown received!
Async::Ready(Some(ServerMessage::Shutdown)) => return Ok(().into()),
Async::Ready(Some(ServerMessage::Request)) => {
if self.timeout_dur != Duration::new(0, 0) {
self.timeout = Some(Delay::new(Instant::now() + self.timeout_dur));
}
}
// All services have shut down, in theory this isn't possible...
Async::Ready(None) => return Ok(().into()),
}
}
match self.timeout {
None => Ok(Async::NotReady),
Some(ref mut timeout) => timeout
.poll()
.map_err(|err| io::Error::new(io::ErrorKind::Other, err)),
}
}
}
/// Helper future which tracks the `ActiveInfo` below. This future will resolve
/// once all instances of `ActiveInfo` have been dropped.
struct WaitUntilZero {
info: Rc<RefCell<Info>>,
}
struct ActiveInfo {
info: Rc<RefCell<Info>>,
}
struct Info {
active: usize,
blocker: Option<Task>,
}
impl WaitUntilZero {
fn new() -> (WaitUntilZero, ActiveInfo) {
let info = Rc::new(RefCell::new(Info {
active: 1,
blocker: None,
}));
(
WaitUntilZero { info: info.clone() },
ActiveInfo { info: info },
)
}
}
impl Clone for ActiveInfo {
fn clone(&self) -> ActiveInfo {
self.info.borrow_mut().active += 1;
ActiveInfo {
info: self.info.clone(),
}
}
}
impl Drop for ActiveInfo {
fn drop(&mut self) {
let mut info = self.info.borrow_mut();
info.active -= 1;
if info.active == 0 {
if let Some(task) = info.blocker.take() {
task.notify();
}
}
}
}
impl Future for WaitUntilZero {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
let mut info = self.info.borrow_mut();
if info.active == 0 {
Ok(().into())
} else {
info.blocker = Some(task::current());
Ok(Async::NotReady)
}
}
}
increase SccacheServer shutdown wait timeout
This is a bit of a hack. The integration tests under `src/test/`,
specifically `test_server_compile` have started timing out at some point
after the Windows builds were broken. It's not obvious to me why it
should be this particular test, and not other tests. But we're running
on Windows, and presumably running on some kind of VM in CI, so it seems
worth bumping up the timeout here.
// Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// For tokio_io::codec::length_delimited::Framed;
#![allow(deprecated)]
use crate::cache::{storage_from_config, Storage};
use crate::compiler::{
get_compiler_info, CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher,
CompilerKind, DistType, MissType,
};
#[cfg(feature = "dist-client")]
use crate::config;
use crate::config::Config;
use crate::dist;
use crate::dist::Client as DistClient;
use crate::jobserver::Client;
use crate::mock_command::{CommandCreatorSync, ProcessCommandCreator};
use crate::protocol::{Compile, CompileFinished, CompileResponse, Request, Response};
use crate::util;
use filetime::FileTime;
use futures::sync::mpsc;
use futures::task::{self, Task};
use futures::{future, stream, Async, AsyncSink, Future, Poll, Sink, StartSend, Stream};
use futures_cpupool::CpuPool;
use number_prefix::{binary_prefix, Prefixed, Standalone};
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::metadata;
use std::io::{self, Write};
#[cfg(feature = "dist-client")]
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use std::rc::Rc;
use std::sync::Arc;
#[cfg(feature = "dist-client")]
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use std::u64;
use tokio::runtime::current_thread::Runtime;
use tokio_io::codec::length_delimited;
use tokio_io::codec::length_delimited::Framed;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_serde_bincode::{ReadBincode, WriteBincode};
use tokio_tcp::TcpListener;
use tokio_timer::{Delay, Timeout};
use tower::Service;
use crate::errors::*;
/// If the server is idle for this many seconds, shut down.
const DEFAULT_IDLE_TIMEOUT: u64 = 600;
/// If the dist client couldn't be created, retry creation at this number
/// of seconds from now (or later)
#[cfg(feature = "dist-client")]
const DIST_CLIENT_RECREATE_TIMEOUT: Duration = Duration::from_secs(30);
/// Result of background server startup.
#[derive(Debug, Serialize, Deserialize)]
pub enum ServerStartup {
/// Server started successfully on `port`.
Ok { port: u16 },
/// Timed out waiting for server startup.
TimedOut,
/// Server encountered an error.
Err { reason: String },
}
/// Get the time the server should idle for before shutting down.
fn get_idle_timeout() -> u64 {
// A value of 0 disables idle shutdown entirely.
env::var("SCCACHE_IDLE_TIMEOUT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_IDLE_TIMEOUT)
}
fn notify_server_startup_internal<W: Write>(mut w: W, status: ServerStartup) -> Result<()> {
util::write_length_prefixed_bincode(&mut w, status)
}
#[cfg(unix)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use std::os::unix::net::UnixStream;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
debug!("notify_server_startup({:?})", status);
let stream = UnixStream::connect(name)?;
notify_server_startup_internal(stream, status)
}
#[cfg(windows)]
fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> {
use std::fs::OpenOptions;
let name = match *name {
Some(ref s) => s,
None => return Ok(()),
};
let pipe = OpenOptions::new().write(true).read(true).open(name)?;
notify_server_startup_internal(pipe, status)
}
#[cfg(unix)]
fn get_signal(status: ExitStatus) -> i32 {
use std::os::unix::prelude::*;
status.signal().expect("must have signal")
}
#[cfg(windows)]
fn get_signal(_status: ExitStatus) -> i32 {
panic!("no signals on windows")
}
pub struct DistClientContainer {
// The actual dist client state
#[cfg(feature = "dist-client")]
state: Mutex<DistClientState>,
}
#[cfg(feature = "dist-client")]
struct DistClientConfig {
// Reusable items tied to an SccacheServer instance
pool: CpuPool,
// From the static dist configuration
scheduler_url: Option<config::HTTPUrl>,
auth: config::DistAuth,
cache_dir: PathBuf,
toolchain_cache_size: u64,
toolchains: Vec<config::DistToolchainConfig>,
rewrite_includes_only: bool,
}
#[cfg(feature = "dist-client")]
enum DistClientState {
#[cfg(feature = "dist-client")]
Some(DistClientConfig, Arc<dyn dist::Client>),
#[cfg(feature = "dist-client")]
FailWithMessage(DistClientConfig, String),
#[cfg(feature = "dist-client")]
RetryCreateAt(DistClientConfig, Instant),
Disabled,
}
#[cfg(not(feature = "dist-client"))]
impl DistClientContainer {
#[cfg(not(feature = "dist-client"))]
fn new(config: &Config, _: &CpuPool) -> Self {
if let Some(_) = config.dist.scheduler_url {
warn!("Scheduler address configured but dist feature disabled, disabling distributed sccache")
}
Self {}
}
pub fn new_disabled() -> Self {
Self {}
}
pub fn reset_state(&self) {}
pub fn get_status(&self) -> DistInfo {
DistInfo::Disabled("dist-client feature not selected".to_string())
}
fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
Ok(None)
}
}
#[cfg(feature = "dist-client")]
impl DistClientContainer {
fn new(config: &Config, pool: &CpuPool) -> Self {
let config = DistClientConfig {
pool: pool.clone(),
scheduler_url: config.dist.scheduler_url.clone(),
auth: config.dist.auth.clone(),
cache_dir: config.dist.cache_dir.clone(),
toolchain_cache_size: config.dist.toolchain_cache_size,
toolchains: config.dist.toolchains.clone(),
rewrite_includes_only: config.dist.rewrite_includes_only,
};
let state = Self::create_state(config);
Self {
state: Mutex::new(state),
}
}
pub fn new_disabled() -> Self {
Self {
state: Mutex::new(DistClientState::Disabled),
}
}
pub fn reset_state(&self) {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
match mem::replace(state, DistClientState::Disabled) {
DistClientState::Some(cfg, _)
| DistClientState::FailWithMessage(cfg, _)
| DistClientState::RetryCreateAt(cfg, _) => {
warn!("State reset. Will recreate");
*state =
DistClientState::RetryCreateAt(cfg, Instant::now() - Duration::from_secs(1));
}
DistClientState::Disabled => (),
}
}
pub fn get_status(&self) -> DistInfo {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
match state {
DistClientState::Disabled => DistInfo::Disabled("disabled".to_string()),
DistClientState::FailWithMessage(cfg, _) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, auth not configured".to_string(),
),
DistClientState::RetryCreateAt(cfg, _) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"enabled, not connected, will retry".to_string(),
),
DistClientState::Some(cfg, client) => match client.do_get_status().wait() {
Ok(res) => DistInfo::SchedulerStatus(cfg.scheduler_url.clone(), res),
Err(_) => DistInfo::NotConnected(
cfg.scheduler_url.clone(),
"could not communicate with scheduler".to_string(),
),
},
}
}
fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> {
let mut guard = self.state.lock();
let state = guard.as_mut().unwrap();
let state: &mut DistClientState = &mut **state;
Self::maybe_recreate_state(state);
let res = match state {
DistClientState::Some(_, dc) => Ok(Some(dc.clone())),
DistClientState::Disabled | DistClientState::RetryCreateAt(_, _) => Ok(None),
DistClientState::FailWithMessage(_, msg) => Err(Error::from(msg.clone())),
};
match res {
Err(_) => {
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::FailWithMessage(config, _) => config,
_ => unreachable!(),
};
// The client is most likely mis-configured, make sure we
// re-create on our next attempt.
*state =
DistClientState::RetryCreateAt(config, Instant::now() - Duration::from_secs(1));
}
_ => (),
};
res
}
fn maybe_recreate_state(state: &mut DistClientState) {
if let DistClientState::RetryCreateAt(_, instant) = *state {
if instant > Instant::now() {
return;
}
let config = match mem::replace(state, DistClientState::Disabled) {
DistClientState::RetryCreateAt(config, _) => config,
_ => unreachable!(),
};
info!("Attempting to recreate the dist client");
*state = Self::create_state(config)
}
}
// Attempt to recreate the dist client
fn create_state(config: DistClientConfig) -> DistClientState {
macro_rules! try_or_retry_later {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
use error_chain::ChainedError;
error!("{}", e.display_chain());
return DistClientState::RetryCreateAt(
config,
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
);
}
}
}};
}
macro_rules! try_or_fail_with_message {
($v:expr) => {{
match $v {
Ok(v) => v,
Err(e) => {
use error_chain::ChainedError;
let errmsg = e.display_chain();
error!("{}", errmsg);
return DistClientState::FailWithMessage(config, errmsg.to_string());
}
}
}};
}
// TODO: NLL would avoid this clone
match config.scheduler_url.clone() {
Some(addr) => {
let url = addr.to_url();
info!("Enabling distributed sccache to {}", url);
let auth_token = match &config.auth {
config::DistAuth::Token { token } => Ok(token.to_owned()),
config::DistAuth::Oauth2CodeGrantPKCE {
client_id: _,
auth_url,
token_url: _,
}
| config::DistAuth::Oauth2Implicit {
client_id: _,
auth_url,
} => Self::get_cached_config_auth_token(auth_url),
};
let auth_token = try_or_fail_with_message!(auth_token.chain_err(|| {
"could not load client auth token, run |sccache --dist-auth|"
}));
// TODO: NLL would let us move this inside the previous match
let dist_client = dist::http::Client::new(
&config.pool,
url,
&config.cache_dir.join("client"),
config.toolchain_cache_size,
&config.toolchains,
auth_token,
config.rewrite_includes_only,
);
let dist_client = try_or_retry_later!(
dist_client.chain_err(|| "failure during dist client creation")
);
match dist_client.do_get_status().wait() {
Ok(res) => {
info!(
"Successfully created dist client with {:?} cores across {:?} servers",
res.num_cpus, res.num_servers
);
DistClientState::Some(config, Arc::new(dist_client))
}
Err(_) => {
warn!("Scheduler address configured, but could not communicate with scheduler");
DistClientState::RetryCreateAt(
config,
Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT,
)
}
}
}
None => {
info!("No scheduler address configured, disabling distributed sccache");
DistClientState::Disabled
}
}
}
fn get_cached_config_auth_token(auth_url: &str) -> Result<String> {
let cached_config = config::CachedConfig::reload()?;
cached_config
.with(|c| c.dist.auth_tokens.get(auth_url).map(String::to_owned))
.ok_or_else(|| {
Error::from(format!(
"token for url {} not present in cached config",
auth_url
))
})
}
}
/// Start an sccache server, listening on `port`.
///
/// Spins an event loop handling client connections until a client
/// requests a shutdown.
pub fn start_server(config: &Config, port: u16) -> Result<()> {
info!("start_server: port: {}", port);
let client = unsafe { Client::new() };
let runtime = Runtime::new()?;
let pool = CpuPool::new(std::cmp::max(20, 2 * num_cpus::get()));
let dist_client = DistClientContainer::new(config, &pool);
let storage = storage_from_config(config, &pool);
let res = SccacheServer::<ProcessCommandCreator>::new(
port,
pool,
runtime,
client,
dist_client,
storage,
);
let notify = env::var_os("SCCACHE_STARTUP_NOTIFY");
match res {
Ok(srv) => {
let port = srv.port();
info!("server started, listening on port {}", port);
notify_server_startup(¬ify, ServerStartup::Ok { port })?;
srv.run(future::empty::<(), ()>())?;
Ok(())
}
Err(e) => {
error!("failed to start server: {}", e);
let reason = e.to_string();
notify_server_startup(¬ify, ServerStartup::Err { reason })?;
Err(e)
}
}
}
pub struct SccacheServer<C: CommandCreatorSync> {
runtime: Runtime,
listener: TcpListener,
rx: mpsc::Receiver<ServerMessage>,
timeout: Duration,
service: SccacheService<C>,
wait: WaitUntilZero,
}
impl<C: CommandCreatorSync> SccacheServer<C> {
pub fn new(
port: u16,
pool: CpuPool,
runtime: Runtime,
client: Client,
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
) -> Result<SccacheServer<C>> {
let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port);
let listener = TcpListener::bind(&SocketAddr::V4(addr))?;
// Prepare the service which we'll use to service all incoming TCP
// connections.
let (tx, rx) = mpsc::channel(1);
let (wait, info) = WaitUntilZero::new();
let service = SccacheService::new(dist_client, storage, &client, pool, tx, info);
Ok(SccacheServer {
runtime: runtime,
listener: listener,
rx: rx,
service: service,
timeout: Duration::from_secs(get_idle_timeout()),
wait: wait,
})
}
/// Configures how long this server will be idle before shutting down.
#[allow(dead_code)]
pub fn set_idle_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
/// Set the storage this server will use.
#[allow(dead_code)]
pub fn set_storage(&mut self, storage: Arc<dyn Storage>) {
self.service.storage = storage;
}
/// Returns a reference to a thread pool to run work on
#[allow(dead_code)]
pub fn pool(&self) -> &CpuPool {
&self.service.pool
}
/// Returns a reference to the command creator this server will use
#[allow(dead_code)]
pub fn command_creator(&self) -> &C {
&self.service.creator
}
/// Returns the port that this server is bound to
#[allow(dead_code)]
pub fn port(&self) -> u16 {
self.listener.local_addr().unwrap().port()
}
/// Runs this server to completion.
///
/// If the `shutdown` future resolves then the server will be shut down,
/// otherwise the server may naturally shut down if it becomes idle for too
/// long anyway.
pub fn run<F>(self, shutdown: F) -> io::Result<()>
where
F: Future,
{
self._run(Box::new(shutdown.then(|_| Ok(()))))
}
fn _run<'a>(self, shutdown: Box<dyn Future<Item = (), Error = ()> + 'a>) -> io::Result<()> {
let SccacheServer {
mut runtime,
listener,
rx,
service,
timeout,
wait,
} = self;
// Create our "server future" which will simply handle all incoming
// connections in separate tasks.
let server = listener.incoming().for_each(move |socket| {
trace!("incoming connection");
tokio::runtime::current_thread::TaskExecutor::current()
.spawn_local(Box::new(service.clone().bind(socket).map_err(|err| {
error!("{}", err);
})))
.unwrap();
Ok(())
});
// Right now there's a whole bunch of ways to shut down this server for
// various purposes. These include:
//
// 1. The `shutdown` future above.
// 2. An RPC indicating the server should shut down
// 3. A period of inactivity (no requests serviced)
//
// These are all encapsulated wih the future that we're creating below.
// The `ShutdownOrInactive` indicates the RPC or the period of
// inactivity, and this is then select'd with the `shutdown` future
// passed to this function.
let shutdown = shutdown.map(|a| {
info!("shutting down due to explicit signal");
a
});
let mut futures = vec![
Box::new(server) as Box<dyn Future<Item = _, Error = _>>,
Box::new(
shutdown
.map_err(|()| io::Error::new(io::ErrorKind::Other, "shutdown signal failed")),
),
];
let shutdown_idle = ShutdownOrInactive {
rx: rx,
timeout: if timeout != Duration::new(0, 0) {
Some(Delay::new(Instant::now() + timeout))
} else {
None
},
timeout_dur: timeout,
};
futures.push(Box::new(shutdown_idle.map(|a| {
info!("shutting down due to being idle or request");
a
})));
let server = future::select_all(futures);
runtime.block_on(server).map_err(|p| p.0)?;
info!(
"moving into the shutdown phase now, waiting at most 10 seconds \
for all client requests to complete"
);
// Once our server has shut down either due to inactivity or a manual
// request we still need to give a bit of time for all active
// connections to finish. This `wait` future will resolve once all
// instances of `SccacheService` have been dropped.
//
// Note that we cap the amount of time this can take, however, as we
// don't want to wait *too* long.
runtime
.block_on(Timeout::new(wait, Duration::new(30, 0)))
.map_err(|e| {
if e.is_inner() {
e.into_inner().unwrap()
} else {
io::Error::new(io::ErrorKind::Other, e)
}
})?;
info!("ok, fully shutting down now");
Ok(())
}
}
/// Service implementation for sccache
#[derive(Clone)]
struct SccacheService<C: CommandCreatorSync> {
/// Server statistics.
stats: Rc<RefCell<ServerStats>>,
/// Distributed sccache client
dist_client: Rc<DistClientContainer>,
/// Cache storage.
storage: Arc<dyn Storage>,
/// A cache of known compiler info.
compilers: Rc<
RefCell<
HashMap<PathBuf, Option<(Box<dyn Compiler<C>>, FileTime, Option<(PathBuf, FileTime)>)>>,
>,
>,
/// Thread pool to execute work in
pool: CpuPool,
/// An object for creating commands.
///
/// This is mostly useful for unit testing, where we
/// can mock this out.
creator: C,
/// Message channel used to learn about requests received by this server.
///
/// Note that messages sent along this channel will keep the server alive
/// (reset the idle timer) and this channel can also be used to shut down
/// the entire server immediately via a message.
tx: mpsc::Sender<ServerMessage>,
/// Information tracking how many services (connected clients) are active.
info: ActiveInfo,
}
type SccacheRequest = Message<Request, Body<()>>;
type SccacheResponse = Message<Response, Body<Response>>;
/// Messages sent from all services to the main event loop indicating activity.
///
/// Whenever a request is receive a `Request` message is sent which will reset
/// the idle shutdown timer, and otherwise a `Shutdown` message indicates that
/// a server shutdown was requested via an RPC.
pub enum ServerMessage {
/// A message sent whenever a request is received.
Request,
/// Message sent whenever a shutdown request is received.
Shutdown,
}
impl<C> Service<SccacheRequest> for SccacheService<C>
where
C: CommandCreatorSync + 'static,
{
type Response = SccacheResponse;
type Error = Error;
type Future = SFuture<Self::Response>;
fn call(&mut self, req: SccacheRequest) -> Self::Future {
trace!("handle_client");
// Opportunistically let channel know that we've received a request. We
// ignore failures here as well as backpressure as it's not imperative
// that every message is received.
drop(self.tx.clone().start_send(ServerMessage::Request));
let res: SFuture<Response> = match req.into_inner() {
Request::Compile(compile) => {
debug!("handle_client: compile");
self.stats.borrow_mut().compile_requests += 1;
return self.handle_compile(compile);
}
Request::GetStats => {
debug!("handle_client: get_stats");
Box::new(self.get_info().map(Response::Stats))
}
Request::DistStatus => {
debug!("handle_client: dist_status");
Box::new(self.get_dist_status().map(Response::DistStatus))
}
Request::ZeroStats => {
debug!("handle_client: zero_stats");
self.zero_stats();
Box::new(self.get_info().map(Response::Stats))
}
Request::Shutdown => {
debug!("handle_client: shutdown");
let future = self
.tx
.clone()
.send(ServerMessage::Shutdown)
.then(|_| Ok(()));
let info_future = self.get_info();
return Box::new(
future
.join(info_future)
.map(move |(_, info)| Message::WithoutBody(Response::ShuttingDown(info))),
);
}
};
Box::new(res.map(Message::WithoutBody))
}
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
}
impl<C> SccacheService<C>
where
C: CommandCreatorSync,
{
pub fn new(
dist_client: DistClientContainer,
storage: Arc<dyn Storage>,
client: &Client,
pool: CpuPool,
tx: mpsc::Sender<ServerMessage>,
info: ActiveInfo,
) -> SccacheService<C> {
SccacheService {
stats: Rc::new(RefCell::new(ServerStats::default())),
dist_client: Rc::new(dist_client),
storage,
compilers: Rc::new(RefCell::new(HashMap::new())),
pool,
creator: C::new(client),
tx,
info,
}
}
fn bind<T>(mut self, socket: T) -> impl Future<Item = (), Error = Error>
where
T: AsyncRead + AsyncWrite + 'static,
{
let mut builder = length_delimited::Builder::new();
if let Ok(max_frame_length_str) = env::var("SCCACHE_MAX_FRAME_LENGTH") {
if let Ok(max_frame_length) = max_frame_length_str.parse::<usize>() {
builder.max_frame_length(max_frame_length);
} else {
warn!("Content of SCCACHE_MAX_FRAME_LENGTH is not a valid number, using default");
}
}
let io = builder.new_framed(socket);
let (sink, stream) = SccacheTransport {
inner: WriteBincode::new(ReadBincode::new(io)),
}
.split();
let sink = sink.sink_from_err::<Error>();
stream
.from_err::<Error>()
.and_then(move |input| self.call(input))
.and_then(|message| {
let f: Box<dyn Stream<Item = _, Error = _>> = match message {
Message::WithoutBody(message) => Box::new(stream::once(Ok(Frame::Message {
message,
body: false,
}))),
Message::WithBody(message, body) => Box::new(
stream::once(Ok(Frame::Message {
message,
body: true,
}))
.chain(body.map(|chunk| Frame::Body { chunk: Some(chunk) }))
.chain(stream::once(Ok(Frame::Body { chunk: None }))),
),
};
Ok(f.from_err::<Error>())
})
.flatten()
.forward(sink)
.map(|_| ())
}
/// Get dist status.
fn get_dist_status(&self) -> SFuture<DistInfo> {
f_ok(self.dist_client.get_status())
}
/// Get info and stats about the cache.
fn get_info(&self) -> SFuture<ServerInfo> {
let stats = self.stats.borrow().clone();
let cache_location = self.storage.location();
Box::new(
self.storage
.current_size()
.join(self.storage.max_size())
.map(move |(cache_size, max_cache_size)| ServerInfo {
stats,
cache_location,
cache_size,
max_cache_size,
}),
)
}
/// Zero stats about the cache.
fn zero_stats(&self) {
*self.stats.borrow_mut() = ServerStats::default();
}
/// Handle a compile request from a client.
///
/// This will handle a compile request entirely, generating a response with
/// the inital information and an optional body which will eventually
/// contain the results of the compilation.
fn handle_compile(&self, compile: Compile) -> SFuture<SccacheResponse> {
let exe = compile.exe;
let cmd = compile.args;
let cwd = compile.cwd;
let env_vars = compile.env_vars;
let me = self.clone();
Box::new(
self.compiler_info(exe.into(), &env_vars)
.map(move |info| me.check_compiler(info, cmd, cwd.into(), env_vars)),
)
}
/// Look up compiler info from the cache for the compiler `path`.
/// If not cached, determine the compiler type and cache the result.
fn compiler_info(
&self,
path: PathBuf,
env: &[(OsString, OsString)],
) -> SFuture<Result<Box<dyn Compiler<C>>>> {
trace!("compiler_info");
let mtime = ftry!(metadata(&path).map(|attr| FileTime::from_last_modification_time(&attr)));
let dist_info = match self.dist_client.get_client() {
Ok(Some(ref client)) => {
if let Some(archive) = client.get_custom_toolchain(&path) {
match metadata(&archive)
.map(|attr| FileTime::from_last_modification_time(&attr))
{
Ok(mtime) => Some((archive, mtime)),
_ => None,
}
} else {
None
}
}
_ => None,
};
//TODO: properly handle rustup overrides. Currently this will
// cache based on the rustup rustc path, ignoring overrides.
// https://github.com/mozilla/sccache/issues/87
let result = match self.compilers.borrow().get(&path) {
// It's a hit only if the mtime and dist archive data matches.
Some(&Some((ref c, ref cached_mtime, ref cached_dist_info))) => {
if *cached_mtime == mtime && *cached_dist_info == dist_info {
Some(c.clone())
} else {
None
}
}
_ => None,
};
match result {
Some(info) => {
trace!("compiler_info cache hit");
f_ok(Ok(info))
}
None => {
trace!("compiler_info cache miss");
// Check the compiler type and return the result when
// finished. This generally involves invoking the compiler,
// so do it asynchronously.
let me = self.clone();
let info = get_compiler_info(
&self.creator,
&path,
env,
&self.pool,
dist_info.clone().map(|(p, _)| p),
);
Box::new(info.then(move |info| {
let map_info = match info {
Ok(ref c) => Some((c.clone(), mtime, dist_info)),
Err(_) => None,
};
me.compilers.borrow_mut().insert(path, map_info);
Ok(info)
}))
}
}
}
/// Check that we can handle and cache `cmd` when run with `compiler`.
/// If so, run `start_compile_task` to execute it.
fn check_compiler(
&self,
compiler: Result<Box<dyn Compiler<C>>>,
cmd: Vec<OsString>,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
) -> SccacheResponse {
let mut stats = self.stats.borrow_mut();
match compiler {
Err(e) => {
debug!("check_compiler: Unsupported compiler: {}", e.to_string());
stats.requests_unsupported_compiler += 1;
return Message::WithoutBody(Response::Compile(
CompileResponse::UnsupportedCompiler(OsString::from(e.to_string())),
));
}
Ok(c) => {
debug!("check_compiler: Supported compiler");
// Now check that we can handle this compiler with
// the provided commandline.
match c.parse_arguments(&cmd, &cwd) {
CompilerArguments::Ok(hasher) => {
debug!("parse_arguments: Ok: {:?}", cmd);
stats.requests_executed += 1;
let (tx, rx) = Body::pair();
self.start_compile_task(c, hasher, cmd, cwd, env_vars, tx);
let res = CompileResponse::CompileStarted;
return Message::WithBody(Response::Compile(res), rx);
}
CompilerArguments::CannotCache(why, extra_info) => {
if let Some(extra_info) = extra_info {
debug!(
"parse_arguments: CannotCache({}, {}): {:?}",
why, extra_info, cmd
)
} else {
debug!("parse_arguments: CannotCache({}): {:?}", why, cmd)
}
stats.requests_not_cacheable += 1;
*stats.not_cached.entry(why.to_string()).or_insert(0) += 1;
}
CompilerArguments::NotCompilation => {
debug!("parse_arguments: NotCompilation: {:?}", cmd);
stats.requests_not_compile += 1;
}
}
}
}
let res = CompileResponse::UnhandledCompile;
Message::WithoutBody(Response::Compile(res))
}
/// Given compiler arguments `arguments`, look up
/// a compile result in the cache or execute the compilation and store
/// the result in the cache.
fn start_compile_task(
&self,
compiler: Box<dyn Compiler<C>>,
hasher: Box<dyn CompilerHasher<C>>,
arguments: Vec<OsString>,
cwd: PathBuf,
env_vars: Vec<(OsString, OsString)>,
tx: mpsc::Sender<Result<Response>>,
) {
let force_recache = env_vars
.iter()
.any(|&(ref k, ref _v)| k.as_os_str() == OsStr::new("SCCACHE_RECACHE"));
let cache_control = if force_recache {
CacheControl::ForceRecache
} else {
CacheControl::Default
};
let out_pretty = hasher.output_pretty().into_owned();
let color_mode = hasher.color_mode();
let result = hasher.get_cached_or_compile(
self.dist_client.get_client(),
self.creator.clone(),
self.storage.clone(),
arguments,
cwd,
env_vars,
cache_control,
self.pool.clone(),
);
let me = self.clone();
let kind = compiler.kind();
let task = result.then(move |result| {
let mut cache_write = None;
let mut stats = me.stats.borrow_mut();
let mut res = CompileFinished::default();
res.color_mode = color_mode;
match result {
Ok((compiled, out)) => {
match compiled {
CompileResult::Error => {
stats.cache_errors.increment(&kind);
}
CompileResult::CacheHit(duration) => {
stats.cache_hits.increment(&kind);
stats.cache_read_hit_duration += duration;
}
CompileResult::CacheMiss(miss_type, dist_type, duration, future) => {
match dist_type {
DistType::NoDist => {}
DistType::Ok(id) => {
let server = id.addr().to_string();
let server_count =
stats.dist_compiles.entry(server).or_insert(0);
*server_count += 1;
}
DistType::Error => stats.dist_errors += 1,
}
match miss_type {
MissType::Normal => {}
MissType::ForcedRecache => {
stats.forced_recaches += 1;
}
MissType::TimedOut => {
stats.cache_timeouts += 1;
}
MissType::CacheReadError => {
stats.cache_errors.increment(&kind);
}
}
stats.cache_misses.increment(&kind);
stats.cache_read_miss_duration += duration;
cache_write = Some(future);
}
CompileResult::NotCacheable => {
stats.cache_misses.increment(&kind);
stats.non_cacheable_compilations += 1;
}
CompileResult::CompileFailed => {
stats.compile_fails += 1;
}
};
let Output {
status,
stdout,
stderr,
} = out;
trace!("CompileFinished retcode: {}", status);
match status.code() {
Some(code) => res.retcode = Some(code),
None => res.signal = Some(get_signal(status)),
};
res.stdout = stdout;
res.stderr = stderr;
}
Err(Error(ErrorKind::ProcessError(output), _)) => {
debug!("Compilation failed: {:?}", output);
stats.compile_fails += 1;
match output.status.code() {
Some(code) => res.retcode = Some(code),
None => res.signal = Some(get_signal(output.status)),
};
res.stdout = output.stdout;
res.stderr = output.stderr;
}
Err(Error(ErrorKind::HttpClientError(msg), _)) => {
me.dist_client.reset_state();
let errmsg = format!("[{:?}] http error status: {}", out_pretty, msg);
error!("{}", errmsg);
res.retcode = Some(1);
res.stderr = errmsg.as_bytes().to_vec();
}
Err(err) => {
use std::fmt::Write;
error!("[{:?}] fatal error: {}", out_pretty, err);
let mut error = format!("sccache: encountered fatal error\n");
drop(writeln!(error, "sccache: error : {}", err));
for e in err.iter() {
error!("[{:?}] \t{}", out_pretty, e);
drop(writeln!(error, "sccache: cause: {}", e));
}
stats.cache_errors.increment(&kind);
//TODO: figure out a better way to communicate this?
res.retcode = Some(-2);
res.stderr = error.into_bytes();
}
};
let send = tx.send(Ok(Response::CompileFinished(res)));
let me = me.clone();
let cache_write = cache_write.then(move |result| {
match result {
Err(e) => {
debug!("Error executing cache write: {}", e);
me.stats.borrow_mut().cache_write_errors += 1;
}
//TODO: save cache stats!
Ok(Some(info)) => {
debug!(
"[{}]: Cache write finished in {}",
info.object_file_pretty,
util::fmt_duration_as_secs(&info.duration)
);
me.stats.borrow_mut().cache_writes += 1;
me.stats.borrow_mut().cache_write_duration += info.duration;
}
Ok(None) => {}
}
Ok(())
});
send.join(cache_write).then(|_| Ok(()))
});
tokio::runtime::current_thread::TaskExecutor::current()
.spawn_local(Box::new(task))
.unwrap();
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PerLanguageCount {
counts: HashMap<String, u64>,
}
impl PerLanguageCount {
fn increment(&mut self, kind: &CompilerKind) {
let key = kind.lang_kind().clone();
let count = match self.counts.get(&key) {
Some(v) => v + 1,
None => 1,
};
self.counts.insert(key, count);
}
pub fn all(&self) -> u64 {
self.counts.values().sum()
}
pub fn get(&self, key: &str) -> Option<&u64> {
self.counts.get(key)
}
pub fn new() -> PerLanguageCount {
PerLanguageCount {
counts: HashMap::new(),
}
}
}
/// Statistics about the server.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ServerStats {
/// The count of client compile requests.
pub compile_requests: u64,
/// The count of client requests that used an unsupported compiler.
pub requests_unsupported_compiler: u64,
/// The count of client requests that were not compilation.
pub requests_not_compile: u64,
/// The count of client requests that were not cacheable.
pub requests_not_cacheable: u64,
/// The count of client requests that were executed.
pub requests_executed: u64,
/// The count of errors handling compile requests (per language).
pub cache_errors: PerLanguageCount,
/// The count of cache hits for handled compile requests (per language).
pub cache_hits: PerLanguageCount,
/// The count of cache misses for handled compile requests (per language).
pub cache_misses: PerLanguageCount,
/// The count of cache misses because the cache took too long to respond.
pub cache_timeouts: u64,
/// The count of errors reading cache entries.
pub cache_read_errors: u64,
/// The count of compilations which were successful but couldn't be cached.
pub non_cacheable_compilations: u64,
/// The count of compilations which forcibly ignored the cache.
pub forced_recaches: u64,
/// The count of errors writing to cache.
pub cache_write_errors: u64,
/// The number of successful cache writes.
pub cache_writes: u64,
/// The total time spent writing cache entries.
pub cache_write_duration: Duration,
/// The total time spent reading cache hits.
pub cache_read_hit_duration: Duration,
/// The total time spent reading cache misses.
pub cache_read_miss_duration: Duration,
/// The count of compilation failures.
pub compile_fails: u64,
/// Counts of reasons why compiles were not cached.
pub not_cached: HashMap<String, usize>,
/// The count of compilations that were successfully distributed indexed
/// by the server that ran those compilations.
pub dist_compiles: HashMap<String, usize>,
/// The count of compilations that were distributed but failed and had to be re-run locally
pub dist_errors: u64,
}
/// Info and stats about the server.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ServerInfo {
pub stats: ServerStats,
pub cache_location: String,
pub cache_size: Option<u64>,
pub max_cache_size: Option<u64>,
}
/// Status of the dist client.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum DistInfo {
Disabled(String),
#[cfg(feature = "dist-client")]
NotConnected(Option<config::HTTPUrl>, String),
#[cfg(feature = "dist-client")]
SchedulerStatus(Option<config::HTTPUrl>, dist::SchedulerStatusResult),
}
impl Default for ServerStats {
fn default() -> ServerStats {
ServerStats {
compile_requests: u64::default(),
requests_unsupported_compiler: u64::default(),
requests_not_compile: u64::default(),
requests_not_cacheable: u64::default(),
requests_executed: u64::default(),
cache_errors: PerLanguageCount::new(),
cache_hits: PerLanguageCount::new(),
cache_misses: PerLanguageCount::new(),
cache_timeouts: u64::default(),
cache_read_errors: u64::default(),
non_cacheable_compilations: u64::default(),
forced_recaches: u64::default(),
cache_write_errors: u64::default(),
cache_writes: u64::default(),
cache_write_duration: Duration::new(0, 0),
cache_read_hit_duration: Duration::new(0, 0),
cache_read_miss_duration: Duration::new(0, 0),
compile_fails: u64::default(),
not_cached: HashMap::new(),
dist_compiles: HashMap::new(),
dist_errors: u64::default(),
}
}
}
impl ServerStats {
/// Print stats to stdout in a human-readable format.
///
/// Return the formatted width of each of the (name, value) columns.
fn print(&self) -> (usize, usize) {
macro_rules! set_stat {
($vec:ident, $var:expr, $name:expr) => {{
// name, value, suffix length
$vec.push(($name.to_string(), $var.to_string(), 0));
}};
}
macro_rules! set_lang_stat {
($vec:ident, $var:expr, $name:expr) => {{
$vec.push(($name.to_string(), $var.all().to_string(), 0));
let mut sorted_stats: Vec<_> = $var.counts.iter().collect();
sorted_stats.sort_by_key(|v| v.0);
for (lang, count) in sorted_stats.iter() {
$vec.push((format!("{} ({})", $name, lang), count.to_string(), 0));
}
}};
}
macro_rules! set_duration_stat {
($vec:ident, $dur:expr, $num:expr, $name:expr) => {{
let s = if $num > 0 {
$dur / $num as u32
} else {
Default::default()
};
// name, value, suffix length
$vec.push(($name.to_string(), util::fmt_duration_as_secs(&s), 2));
}};
}
let mut stats_vec = vec![];
//TODO: this would be nice to replace with a custom derive implementation.
set_stat!(stats_vec, self.compile_requests, "Compile requests");
set_stat!(
stats_vec,
self.requests_executed,
"Compile requests executed"
);
set_lang_stat!(stats_vec, self.cache_hits, "Cache hits");
set_lang_stat!(stats_vec, self.cache_misses, "Cache misses");
set_stat!(stats_vec, self.cache_timeouts, "Cache timeouts");
set_stat!(stats_vec, self.cache_read_errors, "Cache read errors");
set_stat!(stats_vec, self.forced_recaches, "Forced recaches");
set_stat!(stats_vec, self.cache_write_errors, "Cache write errors");
set_stat!(stats_vec, self.compile_fails, "Compilation failures");
set_lang_stat!(stats_vec, self.cache_errors, "Cache errors");
set_stat!(
stats_vec,
self.non_cacheable_compilations,
"Non-cacheable compilations"
);
set_stat!(
stats_vec,
self.requests_not_cacheable,
"Non-cacheable calls"
);
set_stat!(
stats_vec,
self.requests_not_compile,
"Non-compilation calls"
);
set_stat!(
stats_vec,
self.requests_unsupported_compiler,
"Unsupported compiler calls"
);
set_duration_stat!(
stats_vec,
self.cache_write_duration,
self.cache_writes,
"Average cache write"
);
set_duration_stat!(
stats_vec,
self.cache_read_miss_duration,
self.cache_misses.all(),
"Average cache read miss"
);
set_duration_stat!(
stats_vec,
self.cache_read_hit_duration,
self.cache_hits.all(),
"Average cache read hit"
);
set_stat!(
stats_vec,
self.dist_errors,
"Failed distributed compilations"
);
let name_width = stats_vec
.iter()
.map(|&(ref n, _, _)| n.len())
.max()
.unwrap();
let stat_width = stats_vec
.iter()
.map(|&(_, ref s, _)| s.len())
.max()
.unwrap();
for (name, stat, suffix_len) in stats_vec {
println!(
"{:<name_width$} {:>stat_width$}",
name,
stat,
name_width = name_width,
stat_width = stat_width + suffix_len
);
}
if self.dist_compiles.len() > 0 {
println!("\nSuccessful distributed compiles");
let mut counts: Vec<_> = self.dist_compiles.iter().collect();
counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse());
for (reason, count) in counts {
println!(
" {:<name_width$} {:>stat_width$}",
reason,
count,
name_width = name_width - 2,
stat_width = stat_width
);
}
}
if !self.not_cached.is_empty() {
println!("\nNon-cacheable reasons:");
let mut counts: Vec<_> = self.not_cached.iter().collect();
counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse());
for (reason, count) in counts {
println!(
"{:<name_width$} {:>stat_width$}",
reason,
count,
name_width = name_width,
stat_width = stat_width
);
}
println!("");
}
(name_width, stat_width)
}
}
impl ServerInfo {
/// Print info to stdout in a human-readable format.
pub fn print(&self) {
let (name_width, stat_width) = self.stats.print();
println!(
"{:<name_width$} {}",
"Cache location",
self.cache_location,
name_width = name_width
);
for &(name, val) in &[
("Cache size", &self.cache_size),
("Max cache size", &self.max_cache_size),
] {
if let &Some(val) = val {
let (val, suffix) = match binary_prefix(val as f64) {
Standalone(bytes) => (bytes.to_string(), "bytes".to_string()),
Prefixed(prefix, n) => (format!("{:.0}", n), format!("{}B", prefix)),
};
println!(
"{:<name_width$} {:>stat_width$} {}",
name,
val,
suffix,
name_width = name_width,
stat_width = stat_width
);
}
}
}
}
enum Frame<R, R1> {
Body { chunk: Option<R1> },
Message { message: R, body: bool },
}
struct Body<R> {
receiver: mpsc::Receiver<Result<R>>,
}
impl<R> Body<R> {
fn pair() -> (mpsc::Sender<Result<R>>, Self) {
let (tx, rx) = mpsc::channel(0);
(tx, Body { receiver: rx })
}
}
impl<R> Stream for Body<R> {
type Item = R;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.receiver.poll().unwrap() {
Async::Ready(Some(Ok(item))) => Ok(Async::Ready(Some(item))),
Async::Ready(Some(Err(err))) => Err(err),
Async::Ready(None) => Ok(Async::Ready(None)),
Async::NotReady => Ok(Async::NotReady),
}
}
}
enum Message<R, B> {
WithBody(R, B),
WithoutBody(R),
}
impl<R, B> Message<R, B> {
fn into_inner(self) -> R {
match self {
Message::WithBody(r, _) => r,
Message::WithoutBody(r) => r,
}
}
}
/// Implementation of `Stream + Sink` that tokio-proto is expecting
///
/// This type is composed of a few layers:
///
/// * First there's `I`, the I/O object implementing `AsyncRead` and
/// `AsyncWrite`
/// * Next that's framed using the `length_delimited` module in tokio-io giving
/// us a `Sink` and `Stream` of `BytesMut`.
/// * Next that sink/stream is wrapped in `ReadBincode` which will cause the
/// `Stream` implementation to switch from `BytesMut` to `Request` by parsing
/// the bytes bincode.
/// * Finally that sink/stream is wrapped in `WriteBincode` which will cause the
/// `Sink` implementation to switch from `BytesMut` to `Response` meaning that
/// all `Response` types pushed in will be converted to `BytesMut` and pushed
/// below.
struct SccacheTransport<I: AsyncRead + AsyncWrite> {
inner: WriteBincode<ReadBincode<Framed<I>, Request>, Response>,
}
impl<I: AsyncRead + AsyncWrite> Stream for SccacheTransport<I> {
type Item = Message<Request, Body<()>>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
let msg = try_ready!(self.inner.poll().map_err(|e| {
error!("SccacheTransport::poll failed: {}", e);
io::Error::new(io::ErrorKind::Other, e)
}));
Ok(msg.map(|m| Message::WithoutBody(m)).into())
}
}
impl<I: AsyncRead + AsyncWrite> Sink for SccacheTransport<I> {
type SinkItem = Frame<Response, Response>;
type SinkError = io::Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, io::Error> {
match item {
Frame::Message { message, body } => match self.inner.start_send(message)? {
AsyncSink::Ready => Ok(AsyncSink::Ready),
AsyncSink::NotReady(message) => Ok(AsyncSink::NotReady(Frame::Message {
message: message,
body: body,
})),
},
Frame::Body { chunk: Some(chunk) } => match self.inner.start_send(chunk)? {
AsyncSink::Ready => Ok(AsyncSink::Ready),
AsyncSink::NotReady(chunk) => {
Ok(AsyncSink::NotReady(Frame::Body { chunk: Some(chunk) }))
}
},
Frame::Body { chunk: None } => Ok(AsyncSink::Ready),
}
}
fn poll_complete(&mut self) -> Poll<(), io::Error> {
self.inner.poll_complete()
}
fn close(&mut self) -> Poll<(), io::Error> {
self.inner.close()
}
}
struct ShutdownOrInactive {
rx: mpsc::Receiver<ServerMessage>,
timeout: Option<Delay>,
timeout_dur: Duration,
}
impl Future for ShutdownOrInactive {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
loop {
match self.rx.poll().unwrap() {
Async::NotReady => break,
// Shutdown received!
Async::Ready(Some(ServerMessage::Shutdown)) => return Ok(().into()),
Async::Ready(Some(ServerMessage::Request)) => {
if self.timeout_dur != Duration::new(0, 0) {
self.timeout = Some(Delay::new(Instant::now() + self.timeout_dur));
}
}
// All services have shut down, in theory this isn't possible...
Async::Ready(None) => return Ok(().into()),
}
}
match self.timeout {
None => Ok(Async::NotReady),
Some(ref mut timeout) => timeout
.poll()
.map_err(|err| io::Error::new(io::ErrorKind::Other, err)),
}
}
}
/// Helper future which tracks the `ActiveInfo` below. This future will resolve
/// once all instances of `ActiveInfo` have been dropped.
struct WaitUntilZero {
info: Rc<RefCell<Info>>,
}
struct ActiveInfo {
info: Rc<RefCell<Info>>,
}
struct Info {
active: usize,
blocker: Option<Task>,
}
impl WaitUntilZero {
fn new() -> (WaitUntilZero, ActiveInfo) {
let info = Rc::new(RefCell::new(Info {
active: 1,
blocker: None,
}));
(
WaitUntilZero { info: info.clone() },
ActiveInfo { info: info },
)
}
}
impl Clone for ActiveInfo {
fn clone(&self) -> ActiveInfo {
self.info.borrow_mut().active += 1;
ActiveInfo {
info: self.info.clone(),
}
}
}
impl Drop for ActiveInfo {
fn drop(&mut self) {
let mut info = self.info.borrow_mut();
info.active -= 1;
if info.active == 0 {
if let Some(task) = info.blocker.take() {
task.notify();
}
}
}
}
impl Future for WaitUntilZero {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<(), io::Error> {
let mut info = self.info.borrow_mut();
if info.active == 0 {
Ok(().into())
} else {
info.blocker = Some(task::current());
Ok(Async::NotReady)
}
}
}
|
// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL was not
// distributed with this file, You can obtain one at
// http://mozilla.org/MPL/2.0/.
use std::thread;
use std::io::Error;
use std::time::Duration;
use std::ops::{Deref, DerefMut};
use std::cell::UnsafeCell;
use std::sync::{Arc, Mutex};
use std::net::{TcpStream, TcpListener};
use std::os::unix::io::{RawFd, AsRawFd, IntoRawFd};
use libc;
use errno::errno;
use threadpool::ThreadPool;
use openssl::ssl::{SslStream, SslContext};
use ss::nonblocking::plain::Plain;
use ss::nonblocking::secure::Secure;
use ss::{Socket, Stream, SRecv, SSend, TcpOptions, SocketOptions};
use simple_slab::Slab;
use stats;
use types::*;
use config::Config;
// We need to be able to access our resource pool from several methods
//static mut thread_pool: *mut ThreadPool = 0 as *mut ThreadPool;
// SslContext
static mut ssl_context: *mut SslContext = 0 as *mut SslContext;
// When added to epoll, these will be the conditions of kernel notification:
//
// EPOLLIN - Data is available in kerndl buffer.
// EPOLLRDHUP - Peer closed connection.
// EPOLLPRI - Urgent data for read available.
// EPOLLET - Register in EdgeTrigger mode.
// EPOLLONESHOT - After an event is pulled out with epoll_wait(2) the associated
// file descriptor is internally disabled and no other events will
// be reported by the epoll interface.
const EVENTS: u32 = libc::EPOLLIN |
libc::EPOLLRDHUP |
libc::EPOLLPRI |
libc::EPOLLET |
libc::EPOLLONESHOT;
#[derive(Clone, PartialEq, Eq)]
enum IoEvent {
/// Waiting for an updte from epoll
Waiting,
/// Epoll has reported data is waiting to be read from socket.
DataAvailable,
/// Error/Disconnect/Etc has occured and socket needs removed from server.
ShouldClose
}
#[derive(Clone, PartialEq, Eq)]
enum IoState {
/// New connection, needs added to epoll instance.
New,
/// Socket has no data avialable for reading, but is armed and in the
/// epoll instance's interest list.
Waiting,
/// Socket is currently in use (reading).
InUse,
/// All I/O operations have been exhausted and socket is ready to be
/// re-inserted into the epoll instance's interest list.
ReArm
}
struct Connection {
/// Underlying file descriptor.
fd: RawFd,
/// Last reported event fired from epoll.
event: Mutex<IoEvent>,
/// Current I/O state for socket.
state: Mutex<IoState>,
/// Socket (Stream implemented trait-object).
stream: UnsafeCell<Stream>
}
unsafe impl Send for Connection {}
unsafe impl Sync for Connection {}
struct MutSlab {
inner: UnsafeCell<Slab<Arc<Connection>>>
}
unsafe impl Send for MutSlab {}
unsafe impl Sync for MutSlab {}
/// Memory region for all concurrent connections.
type ConnectionSlab = Arc<MutSlab>;
/// Protected memory region for newly accepted connections.
type NewConnectionSlab = Arc<Mutex<Slab<Connection>>>;
/// Starts the server with the passed config options
pub fn begin(cfg: Config, event_handler: Box<EventHandler>) {
// Wrap handler in something we can share between threads
let handler = Handler(Box::into_raw(event_handler));
// Create our new connections slab
let new_connection_slab = Arc::new(Mutex::new(Slab::<Connection>::new(10)));
// Create our connection slab
let mut_slab = MutSlab {
inner: UnsafeCell::new(Slab::<Arc<Connection>>::new(cfg.pre_allocated))
};
let connection_slab = Arc::new(mut_slab);
// Start the event loop
let threads = cfg.max_threads;
let handler_clone = handler.clone();
let new_connections = new_connection_slab.clone();
unsafe {
thread::Builder::new()
.name("Event Loop".to_string())
.spawn(move || {
event_loop(new_connections, connection_slab, handler_clone, threads)
})
.unwrap();
}
// Start the TcpListener loop
let listener_thread = unsafe {
thread::Builder::new()
.name("TcpListener Loop".to_string())
.spawn(move || { listener_loop(cfg, new_connection_slab) })
.unwrap()
};
let _ = listener_thread.join();
}
unsafe fn listener_loop(cfg: Config, new_connections: NewConnectionSlab) {
let listener_result = TcpListener::bind((&cfg.addr[..], cfg.port));
if listener_result.is_err() {
let err = listener_result.unwrap_err();
error!("Creating TcpListener: {}", err);
panic!();
}
let listener = listener_result.unwrap();
setup_listener_options(&listener);
for accept_attempt in listener.incoming() {
match accept_attempt {
Ok(tcp_stream) => handle_new_connection(tcp_stream, &new_connections),
Err(e) => error!("Accepting connection: {}", e)
};
}
drop(listener);
}
fn setup_listener_options(listener: &TcpListener) {
let fd = listener.as_raw_fd();
let mut socket = Socket::new(fd);
let _ = socket.set_reuseaddr(true);
}
unsafe fn handle_new_connection(tcp_stream: TcpStream, new_connections: &NewConnectionSlab) {
// Take ownership of tcp_stream's underlying file descriptor
let fd = tcp_stream.into_raw_fd();
trace!("New connection with fd: {}", fd);
// Create a socket and set various options
let mut socket = Socket::new(fd);
let _ = socket.set_nonblocking();
let _ = socket.set_tcp_nodelay(true);
let _ = socket.set_keepalive(true);
// Create a "Plain Text" Stream
let plain_text = Plain::new(socket);
let stream = Stream::new(Box::new(plain_text));
// Create a connection structure
let connection = Connection {
fd: fd,
event: Mutex::new(IoEvent::Waiting),
state: Mutex::new(IoState::New),
stream: UnsafeCell::new(stream)
};
// Insert it into the NewConnectionSlab
let mut guard = match (*new_connections).lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let slab = guard.deref_mut();
slab.insert(connection);
}
/// Main event loop
unsafe fn event_loop(new_connections: NewConnectionSlab,
connection_slab: ConnectionSlab,
handler: Handler,
threads: usize)
{
// Maximum number of events returned from epoll_wait
const MAX_EVENTS: usize = 100;
const MAX_WAIT: i32 = 100; // Milliseconds
// Attempt to create an epoll instance
let result = libc::epoll_create(0);
if result < 0 {
let err = Error::from_raw_os_error(result as i32);
error!("Error closing fd: {}", err);
panic!();
}
// Epoll instance
let epfd = result;
// ThreadPool with user specified number of threads
let thread_pool = ThreadPool::new(threads);
// Start the I/O Sentinel
let conn_slab_clone = connection_slab.clone();
let t_pool_clone = thread_pool.clone();
let handler_clone = handler.clone();
thread::Builder::new()
.name("I/O Sentinel".to_string())
.spawn(move || { io_sentinel(conn_slab_clone, t_pool_clone, handler_clone) })
.unwrap();
// Scratch space for epoll returned events
let mut event_buffer = Vec::<libc::epoll_event>::with_capacity(MAX_EVENTS);
event_buffer.set_len(MAX_EVENTS);
loop {
// Remove any connections in the IoState::ShouldClose state.
remove_stale_connections(&connection_slab, &thread_pool, &handler);
// Insert any newly received connections into the connection_slab
insert_new_connections(&new_connections, &connection_slab);
// Adjust states/re-arm connections before going back into epoll_wait
prepare_connections_for_epoll_wait(epfd, &connection_slab);
// Check for any new events
match libc::epoll_wait(epfd, &mut event_buffer[..], MAX_WAIT) {
Ok(num_events) => {
update_io_events(&connection_slab, &event_buffer[0..num_events]);
}
Err(e) => {
error!("During epoll::wait(): {}", e);
panic!()
}
};
}
}
/// Traverses through the connection slab and creates a list of connections that need dropped,
/// then traverses that list, drops them, and informs the handler of client drop.
unsafe fn remove_stale_connections(connection_slab: &ConnectionSlab,
thread_pool: &ThreadPool,
handler: &Handler)
{
let slab_ptr = (*connection_slab).inner.get();
let max_removals = (*slab_ptr).len();
let mut offsets = Vec::<usize>::with_capacity(max_removals);
for x in 0..max_removals {
match (*slab_ptr)[x] {
Some(ref arc_connection) => {
// Assuming spin locks would be a solid choice here, but not
// currently a direct API from stdlib. Possibly could use the
// `try_lock()` function from Mutex with a timer and loop, but that
// just seems a bit trickier to get right than what I'm willing to
// devote during this loop.
let event_state: IoEvent;
{ // Mutex lock
let guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
event_state = (*guard).clone();
} // Mutex unlock
if event_state == IoEvent::ShouldClose {
offsets.push(x);
}
}
None => { }
}
}
for offset in offsets {
let arc_connection = (*slab_ptr).remove(offset).unwrap();
// Inform kernel we're done
close_connection(&arc_connection);
// Inform the consumer connection is no longer valid
let fd = (*arc_connection).fd;
let handler_clone = (*handler).clone();
thread_pool.execute(move || {
let Handler(ptr) = handler_clone;
(*ptr).on_stream_closed(fd);
});
}
}
/// Closes the connection's underlying file descriptor
unsafe fn close_connection(connection: &Arc<Connection>) {
let fd = (*connection).fd;
trace!("Closing fd: {}", fd);
let result = libc::close(fd);
if result < 0 {
let err = Error::from_raw_os_error(result as i32);
error!("Error closing fd: {}", err);
}
}
/// Transfers Connections from the new_connections slab to the "main" connection_slab.
unsafe fn insert_new_connections(new_connections: &NewConnectionSlab,
connection_slab: &ConnectionSlab)
{
let mut guard = match new_connections.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let new_slab = guard.deref_mut();
let num_connections = new_slab.len();
let arc_main_slab = (*connection_slab).inner.get();
for _ in 0..num_connections {
let connection = new_slab.remove(0).unwrap();
(*arc_main_slab).insert(Arc::new(connection));
}
}
/// Traverses the "main" connection_slab looking for connections in IoState::New or IoState::ReArm
/// It then either adds the new connection to epoll's interest list, or re-arms the fd with a
/// new event mask.
unsafe fn prepare_connections_for_epoll_wait(epfd: RawFd, connection_slab: &ConnectionSlab)
{
// Unwrap/dereference our Slab from Arc<Unsafe<T>>
let slab_ptr = (*connection_slab).inner.get();
// Iterate over our connections and add them to epoll if they are new,
// or re-arm them epoll if they are finished with I/O operations
for ref arc_connection in (*slab_ptr).iter_mut() {
let mut guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut io_state = guard.deref_mut();
if *io_state == IoState::New {
add_connection_to_epoll(epfd, arc_connection);
*io_state = IoState::Waiting;
} else if *io_state == IoState::ReArm {
//rearm_connection_in_epoll(epfd, arc_connection);
remove_connection_from_epoll(epfd, arc_connection);
add_connection_to_epoll(epfd, arc_connection);
*io_state = IoState::Waiting;
}
}
}
/// Adds a new connection to the epoll interest list.
unsafe fn add_connection_to_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_ADD,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Adding fd to epoll: {}", err);
// Update state to IoEvent::ShouldClose
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut event_state = guard.deref_mut();
*event_state = IoEvent::ShouldClose;
}
}
/// Re-arms a connection in the epoll interest list with the event mask.
unsafe fn rearm_connection_in_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_MOD,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Re-arming fd in epoll: {}", err);
// Update state to IoEvent::ShouldClose
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut event_state = guard.deref_mut();
*event_state = IoEvent::ShouldClose;
}
}
/// Removes a connection in the epoll interest list.
unsafe fn remove_connection_from_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_DEL,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Removing fd from epoll: {}", err);
}
}
/// Traverses the ConnectionSlab and updates any connection's state reported changed by epoll.
unsafe fn update_io_events(connection_slab: &ConnectionSlab, events: &[libc::epoll_event]) {
const READ_EVENT: u32 = libc::EPOLLIN;
for event in events.iter() {
// Locate the connection this event is for
let fd = event.data as RawFd;
trace!("I/O event for fd: {}", fd);
let find_result = find_connection_from_fd(fd, connection_slab);
if find_result.is_err() {
error!("Finding fd: {} in connection_slab", fd);
continue;
}
let arc_connection = find_result.unwrap();
// Event type branch
let data_available = (event.events & READ_EVENT) > 0;
// If we've properly handled race conditions correctly and state ordering,
// the only thing we care about here are connections that are currently
// in the IoEvent::Waiting state.
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_event = guard.deref_mut();
if data_available {
if *io_event == IoEvent::Waiting {
*io_event = IoEvent::DataAvailable;
}
} else {
*io_event = IoEvent::ShouldClose;
}
}
}
/// Given a fd and ConnectionSlab, returns the Connection associated with fd.
unsafe fn find_connection_from_fd(fd: RawFd,
connection_slab: &ConnectionSlab)
-> Result<Arc<Connection>, ()>
{
let slab_ptr = (*connection_slab).inner.get();
for ref arc_connection in (*slab_ptr).iter() {
if (*arc_connection).fd == fd {
return Ok((*arc_connection).clone());
}
}
Err(())
}
unsafe fn io_sentinel(connection_slab: ConnectionSlab, thread_pool: ThreadPool, handler: Handler) {
// We want to wake up with the same interval consitency as the epoll_wait loop.
// Plus a few ms for hopeful non-interference from mutex contention.
let _100ms = 1000000 * 100;
let wait_interval = Duration::new(0, _100ms);
loop {
thread::sleep(wait_interval);
// Go through the connection_slab and process any connections that
// are in the IoEvent::DataAvailable state.
let slab_ptr = (*connection_slab).inner.get();
for ref arc_connection in (*slab_ptr).iter() {
let mut event_guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let event_state = event_guard.deref_mut();
if *event_state == IoEvent::DataAvailable {
let mut state_guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_state = state_guard.deref_mut();
if *io_state == IoState::Waiting {
// Update state so other threads do not interfere
// with this connection.
*io_state = IoState::InUse;
let conn_clone = (*arc_connection).clone();
let handler_clone = handler.clone();
thread_pool.execute(move || {
handle_data_available(conn_clone, handler_clone);
});
}
}
}
}
}
unsafe fn handle_data_available(arc_connection: Arc<Connection>, handler: Handler) {
// Get a pointer into UnsafeCell<Stream>
let stream_ptr = (*arc_connection).stream.get();
trace!("Read event for fd: {}", (*stream_ptr).as_raw_fd());
// Attempt recv
let recv_result = (*stream_ptr).recv();
if recv_result.is_err() {
let err = recv_result.unwrap_err();
error!("During recv: {}", err);
// Update the state so that the next iteration over the ConnectionSlab
// will remove this connection.
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let event_state = guard.deref_mut();
*event_state == IoEvent::ShouldClose;
return;
}
// Update the state so that the next iteration over the ConnectionSlab
// will re-arm this connection in epoll
let mut guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_state = guard.deref_mut();
*io_state == IoState::ReArm;
// Grab the queue of all messages received during the last call
let mut msg_queue = (*stream_ptr).drain_rx_queue();
for msg in msg_queue.drain(..) {
let stream = (*stream_ptr).clone();
let Handler(handler_ptr) = handler;
trace!("Consumer handoff: {}", String::from_utf8(msg.clone()).unwrap());
(*handler_ptr).on_data_received(stream, msg);
}
}
Remote machine compiling
// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL was not
// distributed with this file, You can obtain one at
// http://mozilla.org/MPL/2.0/.
use std::thread;
use std::io::Error;
use std::time::Duration;
use std::ops::{Deref, DerefMut};
use std::cell::UnsafeCell;
use std::sync::{Arc, Mutex};
use std::net::{TcpStream, TcpListener};
use std::os::unix::io::{RawFd, AsRawFd, IntoRawFd};
use libc;
use errno::errno;
use threadpool::ThreadPool;
use openssl::ssl::{SslStream, SslContext};
use ss::nonblocking::plain::Plain;
use ss::nonblocking::secure::Secure;
use ss::{Socket, Stream, SRecv, SSend, TcpOptions, SocketOptions};
use simple_slab::Slab;
use stats;
use types::*;
use config::Config;
// We need to be able to access our resource pool from several methods
//static mut thread_pool: *mut ThreadPool = 0 as *mut ThreadPool;
// SslContext
static mut ssl_context: *mut SslContext = 0 as *mut SslContext;
// When added to epoll, these will be the conditions of kernel notification:
//
// EPOLLIN - Data is available in kerndl buffer.
// EPOLLRDHUP - Peer closed connection.
// EPOLLPRI - Urgent data for read available.
// EPOLLET - Register in EdgeTrigger mode.
// EPOLLONESHOT - After an event is pulled out with epoll_wait(2) the associated
// file descriptor is internally disabled and no other events will
// be reported by the epoll interface.
const EVENTS: u32 = libc::EPOLLIN |
libc::EPOLLRDHUP |
libc::EPOLLPRI |
libc::EPOLLET |
libc::EPOLLONESHOT;
#[derive(Clone, PartialEq, Eq)]
enum IoEvent {
/// Waiting for an updte from epoll
Waiting,
/// Epoll has reported data is waiting to be read from socket.
DataAvailable,
/// Error/Disconnect/Etc has occured and socket needs removed from server.
ShouldClose
}
#[derive(Clone, PartialEq, Eq)]
enum IoState {
/// New connection, needs added to epoll instance.
New,
/// Socket has no data avialable for reading, but is armed and in the
/// epoll instance's interest list.
Waiting,
/// Socket is currently in use (reading).
InUse,
/// All I/O operations have been exhausted and socket is ready to be
/// re-inserted into the epoll instance's interest list.
ReArm
}
struct Connection {
/// Underlying file descriptor.
fd: RawFd,
/// Last reported event fired from epoll.
event: Mutex<IoEvent>,
/// Current I/O state for socket.
state: Mutex<IoState>,
/// Socket (Stream implemented trait-object).
stream: UnsafeCell<Stream>
}
unsafe impl Send for Connection {}
unsafe impl Sync for Connection {}
struct MutSlab {
inner: UnsafeCell<Slab<Arc<Connection>>>
}
unsafe impl Send for MutSlab {}
unsafe impl Sync for MutSlab {}
/// Memory region for all concurrent connections.
type ConnectionSlab = Arc<MutSlab>;
/// Protected memory region for newly accepted connections.
type NewConnectionSlab = Arc<Mutex<Slab<Connection>>>;
/// Starts the server with the passed config options
pub fn begin(cfg: Config, event_handler: Box<EventHandler>) {
// Wrap handler in something we can share between threads
let handler = Handler(Box::into_raw(event_handler));
// Create our new connections slab
let new_connection_slab = Arc::new(Mutex::new(Slab::<Connection>::new(10)));
// Create our connection slab
let mut_slab = MutSlab {
inner: UnsafeCell::new(Slab::<Arc<Connection>>::new(cfg.pre_allocated))
};
let connection_slab = Arc::new(mut_slab);
// Start the event loop
let threads = cfg.max_threads;
let handler_clone = handler.clone();
let new_connections = new_connection_slab.clone();
unsafe {
thread::Builder::new()
.name("Event Loop".to_string())
.spawn(move || {
event_loop(new_connections, connection_slab, handler_clone, threads)
})
.unwrap();
}
// Start the TcpListener loop
let listener_thread = unsafe {
thread::Builder::new()
.name("TcpListener Loop".to_string())
.spawn(move || { listener_loop(cfg, new_connection_slab) })
.unwrap()
};
let _ = listener_thread.join();
}
unsafe fn listener_loop(cfg: Config, new_connections: NewConnectionSlab) {
let listener_result = TcpListener::bind((&cfg.addr[..], cfg.port));
if listener_result.is_err() {
let err = listener_result.unwrap_err();
error!("Creating TcpListener: {}", err);
panic!();
}
let listener = listener_result.unwrap();
setup_listener_options(&listener);
for accept_attempt in listener.incoming() {
match accept_attempt {
Ok(tcp_stream) => handle_new_connection(tcp_stream, &new_connections),
Err(e) => error!("Accepting connection: {}", e)
};
}
drop(listener);
}
fn setup_listener_options(listener: &TcpListener) {
let fd = listener.as_raw_fd();
let mut socket = Socket::new(fd);
let _ = socket.set_reuseaddr(true);
}
unsafe fn handle_new_connection(tcp_stream: TcpStream, new_connections: &NewConnectionSlab) {
// Take ownership of tcp_stream's underlying file descriptor
let fd = tcp_stream.into_raw_fd();
trace!("New connection with fd: {}", fd);
// Create a socket and set various options
let mut socket = Socket::new(fd);
let _ = socket.set_nonblocking();
let _ = socket.set_tcp_nodelay(true);
let _ = socket.set_keepalive(true);
// Create a "Plain Text" Stream
let plain_text = Plain::new(socket);
let stream = Stream::new(Box::new(plain_text));
// Create a connection structure
let connection = Connection {
fd: fd,
event: Mutex::new(IoEvent::Waiting),
state: Mutex::new(IoState::New),
stream: UnsafeCell::new(stream)
};
// Insert it into the NewConnectionSlab
let mut guard = match (*new_connections).lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let slab = guard.deref_mut();
slab.insert(connection);
}
/// Main event loop
unsafe fn event_loop(new_connections: NewConnectionSlab,
connection_slab: ConnectionSlab,
handler: Handler,
threads: usize)
{
// Maximum number of events returned from epoll_wait
const MAX_EVENTS: usize = 100;
const MAX_WAIT: i32 = 100; // Milliseconds
// Attempt to create an epoll instance
let result = libc::epoll_create(0);
if result < 0 {
let err = Error::from_raw_os_error(result as i32);
error!("Error closing fd: {}", err);
panic!();
}
// Epoll instance
let epfd = result;
// ThreadPool with user specified number of threads
let thread_pool = ThreadPool::new(threads);
// Start the I/O Sentinel
let conn_slab_clone = connection_slab.clone();
let t_pool_clone = thread_pool.clone();
let handler_clone = handler.clone();
thread::Builder::new()
.name("I/O Sentinel".to_string())
.spawn(move || { io_sentinel(conn_slab_clone, t_pool_clone, handler_clone) })
.unwrap();
// Scratch space for epoll returned events
let mut event_buffer = Vec::<libc::epoll_event>::with_capacity(MAX_EVENTS);
event_buffer.set_len(MAX_EVENTS);
loop {
// Remove any connections in the IoState::ShouldClose state.
remove_stale_connections(&connection_slab, &thread_pool, &handler);
// Insert any newly received connections into the connection_slab
insert_new_connections(&new_connections, &connection_slab);
// Adjust states/re-arm connections before going back into epoll_wait
prepare_connections_for_epoll_wait(epfd, &connection_slab);
// Check for any new events
match libc::epoll_wait(epfd, &mut event_buffer[..], MAX_WAIT) {
Ok(num_events) => {
update_io_events(&connection_slab, &event_buffer[0..num_events]);
}
Err(e) => {
error!("During epoll::wait(): {}", e);
panic!()
}
};
}
}
/// Traverses through the connection slab and creates a list of connections that need dropped,
/// then traverses that list, drops them, and informs the handler of client drop.
unsafe fn remove_stale_connections(connection_slab: &ConnectionSlab,
thread_pool: &ThreadPool,
handler: &Handler)
{
let slab_ptr = (*connection_slab).inner.get();
let max_removals = (*slab_ptr).len();
let mut offsets = Vec::<usize>::with_capacity(max_removals);
for x in 0..max_removals {
match (*slab_ptr)[x] {
Some(ref arc_connection) => {
// Assuming spin locks would be a solid choice here, but not
// currently a direct API from stdlib. Possibly could use the
// `try_lock()` function from Mutex with a timer and loop, but that
// just seems a bit trickier to get right than what I'm willing to
// devote during this loop.
let event_state: IoEvent;
{ // Mutex lock
let guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
event_state = (*guard).clone();
} // Mutex unlock
if event_state == IoEvent::ShouldClose {
offsets.push(x);
}
}
None => { }
}
}
for offset in offsets {
let arc_connection = (*slab_ptr).remove(offset).unwrap();
// Inform kernel we're done
close_connection(&arc_connection);
// Inform the consumer connection is no longer valid
let fd = (*arc_connection).fd;
let handler_clone = (*handler).clone();
thread_pool.execute(move || {
let Handler(ptr) = handler_clone;
(*ptr).on_stream_closed(fd);
});
}
}
/// Closes the connection's underlying file descriptor
unsafe fn close_connection(connection: &Arc<Connection>) {
let fd = (*connection).fd;
trace!("Closing fd: {}", fd);
let result = libc::close(fd);
if result < 0 {
let err = Error::from_raw_os_error(result as i32);
error!("Error closing fd: {}", err);
}
}
/// Transfers Connections from the new_connections slab to the "main" connection_slab.
unsafe fn insert_new_connections(new_connections: &NewConnectionSlab,
connection_slab: &ConnectionSlab)
{
let mut guard = match new_connections.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let new_slab = guard.deref_mut();
let num_connections = new_slab.len();
let arc_main_slab = (*connection_slab).inner.get();
for _ in 0..num_connections {
let connection = new_slab.remove(0).unwrap();
(*arc_main_slab).insert(Arc::new(connection));
}
}
/// Traverses the "main" connection_slab looking for connections in IoState::New or IoState::ReArm
/// It then either adds the new connection to epoll's interest list, or re-arms the fd with a
/// new event mask.
unsafe fn prepare_connections_for_epoll_wait(epfd: RawFd, connection_slab: &ConnectionSlab)
{
// Unwrap/dereference our Slab from Arc<Unsafe<T>>
let slab_ptr = (*connection_slab).inner.get();
// Iterate over our connections and add them to epoll if they are new,
// or re-arm them epoll if they are finished with I/O operations
for ref arc_connection in (*slab_ptr).iter_mut() {
let mut guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut io_state = guard.deref_mut();
if *io_state == IoState::New {
add_connection_to_epoll(epfd, arc_connection);
*io_state = IoState::Waiting;
} else if *io_state == IoState::ReArm {
//rearm_connection_in_epoll(epfd, arc_connection);
remove_connection_from_epoll(epfd, arc_connection);
add_connection_to_epoll(epfd, arc_connection);
*io_state = IoState::Waiting;
}
}
}
/// Adds a new connection to the epoll interest list.
unsafe fn add_connection_to_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_ADD,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Adding fd to epoll: {}", err);
// Update state to IoEvent::ShouldClose
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut event_state = guard.deref_mut();
*event_state = IoEvent::ShouldClose;
}
}
/// Re-arms a connection in the epoll interest list with the event mask.
unsafe fn rearm_connection_in_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_MOD,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Re-arming fd in epoll: {}", err);
// Update state to IoEvent::ShouldClose
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let mut event_state = guard.deref_mut();
*event_state = IoEvent::ShouldClose;
}
}
/// Removes a connection in the epoll interest list.
unsafe fn remove_connection_from_epoll(epfd: RawFd, arc_connection: &Arc<Connection>) {
let fd = (*arc_connection).fd;
let result = libc::epoll_ctl(epfd,
libc::EPOLL_CTL_DEL,
fd,
&mut libc::epoll_event { events: EVENTS, u64: fd });
if result < 0 {
let err = Error::from_raw_os_error(errno().0 as i32);
error!("Removing fd from epoll: {}", err);
}
}
/// Traverses the ConnectionSlab and updates any connection's state reported changed by epoll.
unsafe fn update_io_events(connection_slab: &ConnectionSlab, events: &[libc::epoll_event]) {
const READ_EVENT: i32 = libc::EPOLLIN;
for event in events.iter() {
// Locate the connection this event is for
let fd = event.data as RawFd;
trace!("I/O event for fd: {}", fd);
let find_result = find_connection_from_fd(fd, connection_slab);
if find_result.is_err() {
error!("Finding fd: {} in connection_slab", fd);
continue;
}
let arc_connection = find_result.unwrap();
// Event type branch
let data_available = (event.events & READ_EVENT) > 0;
// If we've properly handled race conditions correctly and state ordering,
// the only thing we care about here are connections that are currently
// in the IoEvent::Waiting state.
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_event = guard.deref_mut();
if data_available {
if *io_event == IoEvent::Waiting {
*io_event = IoEvent::DataAvailable;
}
} else {
*io_event = IoEvent::ShouldClose;
}
}
}
/// Given a fd and ConnectionSlab, returns the Connection associated with fd.
unsafe fn find_connection_from_fd(fd: RawFd,
connection_slab: &ConnectionSlab)
-> Result<Arc<Connection>, ()>
{
let slab_ptr = (*connection_slab).inner.get();
for ref arc_connection in (*slab_ptr).iter() {
if (*arc_connection).fd == fd {
return Ok((*arc_connection).clone());
}
}
Err(())
}
unsafe fn io_sentinel(connection_slab: ConnectionSlab, thread_pool: ThreadPool, handler: Handler) {
// We want to wake up with the same interval consitency as the epoll_wait loop.
// Plus a few ms for hopeful non-interference from mutex contention.
let _100ms = 1000000 * 100;
let wait_interval = Duration::new(0, _100ms);
loop {
thread::sleep(wait_interval);
// Go through the connection_slab and process any connections that
// are in the IoEvent::DataAvailable state.
let slab_ptr = (*connection_slab).inner.get();
for ref arc_connection in (*slab_ptr).iter() {
let mut event_guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let event_state = event_guard.deref_mut();
if *event_state == IoEvent::DataAvailable {
let mut state_guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_state = state_guard.deref_mut();
if *io_state == IoState::Waiting {
// Update state so other threads do not interfere
// with this connection.
*io_state = IoState::InUse;
let conn_clone = (*arc_connection).clone();
let handler_clone = handler.clone();
thread_pool.execute(move || {
handle_data_available(conn_clone, handler_clone);
});
}
}
}
}
}
unsafe fn handle_data_available(arc_connection: Arc<Connection>, handler: Handler) {
// Get a pointer into UnsafeCell<Stream>
let stream_ptr = (*arc_connection).stream.get();
trace!("Read event for fd: {}", (*stream_ptr).as_raw_fd());
// Attempt recv
let recv_result = (*stream_ptr).recv();
if recv_result.is_err() {
let err = recv_result.unwrap_err();
error!("During recv: {}", err);
// Update the state so that the next iteration over the ConnectionSlab
// will remove this connection.
let mut guard = match (*arc_connection).event.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let event_state = guard.deref_mut();
*event_state == IoEvent::ShouldClose;
return;
}
// Update the state so that the next iteration over the ConnectionSlab
// will re-arm this connection in epoll
let mut guard = match (*arc_connection).state.lock() {
Ok(g) => g,
Err(p) => p.into_inner()
};
let io_state = guard.deref_mut();
*io_state == IoState::ReArm;
// Grab the queue of all messages received during the last call
let mut msg_queue = (*stream_ptr).drain_rx_queue();
for msg in msg_queue.drain(..) {
let stream = (*stream_ptr).clone();
let Handler(handler_ptr) = handler;
trace!("Consumer handoff: {}", String::from_utf8(msg.clone()).unwrap());
(*handler_ptr).on_data_received(stream, msg);
}
}
|
use std::{
self,
pin::Pin,
net::{self, SocketAddr, ToSocketAddrs, Ipv4Addr, Ipv6Addr, IpAddr},
task::Context,
future::Future,
};
use log::{debug, error};
use futures::{SinkExt, Stream, StreamExt, select, stream::FusedStream, task::Poll};
use tokio::{
io,
sync::mpsc,
net::UdpSocket,
};
use tokio_util::udp::{UdpFramed};
use coap_lite::{
Packet, CoapRequest, CoapResponse,
};
use super::message::Codec;
use super::observer::Observer;
pub type MessageSender = mpsc::UnboundedSender<(Packet, SocketAddr)>;
type MessageReceiver = mpsc::UnboundedReceiver<(Packet, SocketAddr)>;
#[derive(Debug)]
pub enum CoAPServerError {
NetworkError,
EventLoopError,
AnotherHandlerIsRunning,
EventSendError,
}
#[derive(Debug)]
pub struct QueuedMessage {
pub address: SocketAddr,
pub message: Packet,
}
pub enum Message {
NeedSend(Packet, SocketAddr),
Received(Packet, SocketAddr),
}
pub struct Server<'a, HandlerRet> where HandlerRet: Future<Output=Option<CoapResponse>> {
server: CoAPServer,
observer: Observer,
handler: Option<Box<dyn FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'a>>,
}
impl<'a, HandlerRet> Server<'a, HandlerRet> where HandlerRet: Future<Output=Option<CoapResponse>> {
/// Creates a CoAP server listening on the given address.
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<Server<'a, HandlerRet>, io::Error> {
let (tx, rx) = mpsc::unbounded_channel();
Ok(Server {
server: CoAPServer::new(addr, rx)?,
observer: Observer::new(tx),
handler: None,
})
}
/// run the server.
pub async fn run<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'a>(&mut self, handler: F) -> Result<(), io::Error> {
self.handler = Some(Box::new(handler));
loop {
select! {
message = self.server.select_next_some() => {
match message {
Ok(Message::NeedSend(packet, addr)) => {
self.server.send((packet, addr)).await?;
}
Ok(Message::Received(packet, addr)) => {
self.dispatch_msg(packet, addr).await?;
}
Err(e) => {
error!("select error: {:?}", e);
}
}
}
_ = self.observer.select_next_some() => {
self.observer.timer_handler().await;
}
complete => break,
}
}
Ok(())
}
/// Return the local address that the server is listening on. This can be useful when starting
/// a server on a random port as part of unit testing.
pub fn socket_addr(&self) -> std::io::Result<SocketAddr> {
self.server.socket_addr()
}
async fn dispatch_msg(&mut self, packet: Packet, addr: SocketAddr) -> Result<(), io::Error> {
let request = CoapRequest::from_packet(packet, addr);
let filtered = !self.observer.request_handler(&request).await;
if filtered {
return Ok(());
}
if let Some(ref mut handler) = self.handler {
match handler(request).await {
Some(response) => {
debug!("Response: {:?}", response);
self.server.send((response.message, addr)).await?;
}
None => {
debug!("No response");
}
}
}
Ok(())
}
/// enable AllCoAP multicasts - adds the AllCoap addresses to the listener
/// - IPv4 AllCoAP multicast address is '224.0.1.187'
/// - IPv6 AllCoAp multicast addresses are 'ff0?::fd'
///
/// Parameter segment is used with IPv6 to determine the first octet.
/// - It's value can be between 0x0 and 0xf.
/// - To join multiple segments, you have to call enable_discovery for each of the segments.
///
/// For further details see method join_multicast
pub fn enable_all_coap(&mut self, segment: u8) {
assert!(segment <= 0xf);
let socket = self.server.socket.get_mut();
let m = match socket.local_addr().unwrap() {
SocketAddr::V4(_val) => {
let addr = IpAddr::V4(Ipv4Addr::new(224, 0, 1, 187));
self.server.multicast_addresses.push(addr.clone());
addr
},
SocketAddr::V6(_val) => {
let addr = IpAddr::V6(Ipv6Addr::new(0xff00 + segment as u16,0,0,0,0,0,0,0xfd));
self.server.multicast_addresses.push(addr.clone());
addr
},
};
self.join_multicast(m);
}
/// join multicast - adds the multicast addresses to the unicast listener
/// - IPv4 multicast address range is '224.0.0.0/4'
/// - IPv6 AllCoAp multicast addresses are 'ff00::/8'
///
/// Parameter segment is used with IPv6 to determine the first octet.
/// - It's value can be between 0x0 and 0xf.
/// - To join multiple segments, you have to call enable_discovery for each of the segments.
///
/// Multicast address scope
/// IPv6 IPv4 equivalent[16] Scope Purpose
/// ff00::/16 Reserved
/// ff0f::/16 Reserved
/// ffx1::/16 127.0.0.0/8 Interface-local Packets with this destination address may not be sent over any network link, but must remain within the current node; this is the multicast equivalent of the unicast loopback address.
/// ffx2::/16 224.0.0.0/24 Link-local Packets with this destination address may not be routed anywhere.
/// ffx3::/16 239.255.0.0/16 IPv4 local scope
/// ffx4::/16 Admin-local The smallest scope that must be administratively configured.
/// ffx5::/16 Site-local Restricted to the local physical network.
/// ffx8::/16 239.192.0.0/14 Organization-local Restricted to networks used by the organization administering the local network. (For example, these addresses might be used over VPNs; when packets for this group are routed over the public internet (where these addresses are not valid), they would have to be encapsulated in some other protocol.)
/// ffxe::/16 224.0.1.0-238.255.255.255 Global scope Eligible to be routed over the public internet.
///
/// Notable addresses:
/// ff02::1 All nodes on the local network segment
/// ff02::2 All routers on the local network segment
/// ff02::5 OSPFv3 All SPF routers
/// ff02::6 OSPFv3 All DR routers
/// ff02::8 IS-IS for IPv6 routers
/// ff02::9 RIP routers
/// ff02::a EIGRP routers
/// ff02::d PIM routers
/// ff02::16 MLDv2 reports (defined in RFC 3810)
/// ff02::1:2 All DHCPv6 servers and relay agents on the local network segment (defined in RFC 3315)
/// ff02::1:3 All LLMNR hosts on the local network segment (defined in RFC 4795)
/// ff05::1:3 All DHCP servers on the local network site (defined in RFC 3315)
/// ff0x::c Simple Service Discovery Protocol
/// ff0x::fb Multicast DNS
/// ff0x::101 Network Time Protocol
/// ff0x::108 Network Information Service
/// ff0x::181 Precision Time Protocol (PTP) version 2 messages (Sync, Announce, etc.) except peer delay measurement
/// ff02::6b Precision Time Protocol (PTP) version 2 peer delay measurement messages
/// ff0x::114 Used for experiments
pub fn join_multicast(&mut self, addr: IpAddr) {
assert!(addr.is_multicast());
let socket = self.server.socket.get_mut();
// determine wether IPv4 or IPv6 and
// join the appropriate multicast address
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
match addr {
IpAddr::V4(ipv4) => {
let i = val.ip().clone();
socket.join_multicast_v4(ipv4, i).unwrap();
self.server.multicast_addresses.push(addr);
}
IpAddr::V6(_ipv6) => { /* handle IPv6 */ }
}
},
SocketAddr::V6(_val) => {
match addr {
IpAddr::V4(_ipv4) => { /* handle IPv4 */ }
IpAddr::V6(ipv6) => {
socket.join_multicast_v6(&ipv6, 0).unwrap();
self.server.multicast_addresses.push(addr);
//socket.set_only_v6(true)?;
}
}
},
}
}
/// leave multicast - remove the multicast address from the listener
pub fn leave_multicast(&mut self, addr: IpAddr) {
assert!(addr.is_multicast());
let socket = self.server.socket.get_mut();
// determine wether IPv4 or IPv6 and
// leave the appropriate multicast address
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
match addr {
IpAddr::V4(ipv4) => {
let i = val.ip().clone();
socket.leave_multicast_v4(ipv4, i).unwrap();
let index = self.server.multicast_addresses.iter().position(|&item| item == addr).unwrap();
self.server.multicast_addresses.remove(index);
}
IpAddr::V6(_ipv6) => { /* handle IPv6 */ }
}
},
SocketAddr::V6(_val) => {
match addr {
IpAddr::V4(_ipv4) => { /* handle IPv4 */ }
IpAddr::V6(ipv6) => {
socket.leave_multicast_v6(&ipv6, 0).unwrap();
let index = self.server.multicast_addresses.iter().position(|&item| item == addr).unwrap();
self.server.multicast_addresses.remove(index);
}
}
},
}
}
}
pub struct CoAPServer {
receiver: MessageReceiver,
is_terminated: bool,
socket: UdpFramed<Codec>,
multicast_addresses: Vec<IpAddr>,
}
impl CoAPServer {
/// Creates a CoAP server listening on the given address.
pub fn new<A: ToSocketAddrs>(addr: A, receiver: MessageReceiver) -> Result<CoAPServer, io::Error> {
let socket = UdpSocket::from_std(net::UdpSocket::bind(addr).unwrap())?;
Ok(CoAPServer {
receiver,
is_terminated: false,
socket: UdpFramed::new(socket, Codec::new()),
multicast_addresses: Vec::new(),
})
}
/// Stop the server.
pub fn stop(&mut self) {
self.is_terminated = true;
}
/// send the packet to the specific address.
pub async fn send(&mut self, frame: (Packet, SocketAddr)) -> Result<(), io::Error> {
self.socket.send(frame).await
}
/// Return the local address that the server is listening on. This can be useful when starting
/// a server on a random port as part of unit testing.
pub fn socket_addr(&self) -> std::io::Result<SocketAddr> {
self.socket.get_ref().local_addr()
}
}
impl Drop for CoAPServer {
fn drop(&mut self) {
// unregister still existing multicast addresses
let socket = self.socket.get_mut();
for addr in &self.multicast_addresses {
match addr {
IpAddr::V4(ipv4) => {
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
socket.leave_multicast_v4(*ipv4, val.ip().clone()).unwrap();
}
_ => { panic!("should not happen"); }
}
}
IpAddr::V6(ipv6) => {
socket.leave_multicast_v6(&ipv6, 0).unwrap();
}
}
}
// stop server
self.stop();
}
}
impl Stream for CoAPServer {
type Item = Result<Message, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Poll::Ready(Some((p, a))) = self.receiver.poll_next_unpin(cx) {
return Poll::Ready(Some(Ok(Message::NeedSend(p, a))));
}
let result: Option<_> = futures::ready!(self.socket.poll_next_unpin(cx));
Poll::Ready(match result {
Some(Ok(message)) => {
let (my_packet, addr) = message;
Some(Ok(Message::Received(my_packet, addr)))
}
Some(Err(e)) => Some(Err(e)),
None => None,
})
}
}
impl FusedStream for CoAPServer {
fn is_terminated(&self) -> bool {
self.is_terminated
}
}
#[cfg(test)]
pub mod test {
use std::{
time::Duration,
sync::mpsc,
};
use coap_lite::CoapOption;
use super::super::*;
use super::*;
pub fn spawn_server<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
let mut server = server::Server::new("127.0.0.1:0").unwrap();
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
async fn request_handler(req: CoapRequest<SocketAddr>) -> Option<CoapResponse> {
let uri_path_list = req.message.get_option(CoapOption::UriPath).unwrap().clone();
assert_eq!(uri_path_list.len(), 1);
match req.response {
Some(mut response) => {
response.message.payload = uri_path_list.front().unwrap().clone();
Some(response)
}
_ => None,
}
}
pub fn spawn_v4_server_with_all_coap<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("v4-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("0.0.0.0", 0)).unwrap();
server.enable_all_coap(0x0);
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
pub fn spawn_v6_server_with_all_coap<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("v6-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("::0", 0)).unwrap();
server.enable_all_coap(0x0);
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
#[test]
fn test_echo_server() {
let server_port = spawn_server(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn test_echo_server_no_token() {
let server_port = spawn_server(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut packet = CoapRequest::new();
packet.message.header.set_version(1);
packet.message.header.set_type(coap_lite::MessageType::Confirmable);
packet.message.header.set_code("0.01");
packet.message.header.message_id = 1;
packet.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&packet).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn test_update_resource() {
let path = "/test";
let payload1 = b"data1".to_vec();
let payload2 = b"data2".to_vec();
let (tx, rx) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
let mut step = 1;
let server_port = spawn_server(request_handler).recv().unwrap();
let mut client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
tx.send(step).unwrap();
let mut request = CoapRequest::new();
request.set_method(coap_lite::RequestType::Put);
request.set_path(path);
request.message.payload = payload1.clone();
client.send(&request).unwrap();
client.receive().unwrap();
let mut receive_step = 1;
let payload1_clone = payload1.clone();
let payload2_clone = payload2.clone();
client.observe(path, move |msg| {
match rx.try_recv() {
Ok(n) => receive_step = n,
_ => (),
}
match receive_step {
1 => assert_eq!(msg.payload, payload1_clone),
2 => {
assert_eq!(msg.payload, payload2_clone);
tx2.send(()).unwrap();
}
_ => panic!("unexpected step"),
}
}).unwrap();
step = 2;
tx.send(step).unwrap();
request.message.payload = payload2.clone();
let client2 = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
client2.send(&request).unwrap();
client2.receive().unwrap();
assert_eq!(rx2.recv_timeout(Duration::new(5, 0)).unwrap(), ());
}
#[test]
fn test_server_all_coap_v4() {
let server_port = spawn_v4_server_with_all_coap(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
let client = CoAPClient::new(format!("224.0.1.187:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::NonConfirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 2;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send_all_coap(&request, 0x2).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
#[ignore] // This test does not work, not clear why. With a separate test client things seem to work.
fn test_server_all_coap_v6() {
let server_port = spawn_v6_server_with_all_coap(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("::1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
// use 0xff02 to keep it within this network
let client = CoAPClient::new(format!("ff02::fd:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::NonConfirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 2;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
// use segment 0x02 to keep it within this network
client.send_all_coap(&request, 0x3).unwrap();
//client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn test_join_leave() {
std::thread::Builder::new().name(String::from("v4-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("0.0.0.0", 0)).unwrap();
server.join_multicast(IpAddr::V4(Ipv4Addr::new(224, 0, 1, 1)));
server.join_multicast(IpAddr::V4(Ipv4Addr::new(224, 1, 1, 1)));
server.leave_multicast(IpAddr::V4(Ipv4Addr::new(224, 0, 1, 1)));
server.leave_multicast(IpAddr::V4(Ipv4Addr::new(224, 1, 1, 1)));
server.run(request_handler).await.unwrap();
})
}).unwrap();
std::thread::Builder::new().name(String::from("v6-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("::0", 0)).unwrap();
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,0,1,0x1)));
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,1,0,0x2)));
server.leave_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,0,1,0x1)));
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,1,0,0x2)));
server.run(request_handler).await.unwrap();
})
}).unwrap();
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
restructure
use std::{
self,
pin::Pin,
net::{self, SocketAddr, ToSocketAddrs, Ipv4Addr, Ipv6Addr, IpAddr},
task::Context,
future::Future,
};
use log::{debug, error};
use futures::{SinkExt, Stream, StreamExt, select, stream::FusedStream, task::Poll};
use tokio::{
io,
sync::mpsc,
net::UdpSocket,
};
use tokio_util::udp::{UdpFramed};
use coap_lite::{
Packet, CoapRequest, CoapResponse,
};
use super::message::Codec;
use super::observer::Observer;
pub type MessageSender = mpsc::UnboundedSender<(Packet, SocketAddr)>;
type MessageReceiver = mpsc::UnboundedReceiver<(Packet, SocketAddr)>;
#[derive(Debug)]
pub enum CoAPServerError {
NetworkError,
EventLoopError,
AnotherHandlerIsRunning,
EventSendError,
}
#[derive(Debug)]
pub struct QueuedMessage {
pub address: SocketAddr,
pub message: Packet,
}
pub enum Message {
NeedSend(Packet, SocketAddr),
Received(Packet, SocketAddr),
}
pub struct Server<'a, HandlerRet> where HandlerRet: Future<Output=Option<CoapResponse>> {
server: CoAPServer,
observer: Observer,
handler: Option<Box<dyn FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'a>>,
}
impl<'a, HandlerRet> Server<'a, HandlerRet> where HandlerRet: Future<Output=Option<CoapResponse>> {
/// Creates a CoAP server listening on the given address.
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<Server<'a, HandlerRet>, io::Error> {
let (tx, rx) = mpsc::unbounded_channel();
Ok(Server {
server: CoAPServer::new(addr, rx)?,
observer: Observer::new(tx),
handler: None,
})
}
/// run the server.
pub async fn run<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'a>(&mut self, handler: F) -> Result<(), io::Error> {
self.handler = Some(Box::new(handler));
loop {
select! {
message = self.server.select_next_some() => {
match message {
Ok(Message::NeedSend(packet, addr)) => {
self.server.send((packet, addr)).await?;
}
Ok(Message::Received(packet, addr)) => {
self.dispatch_msg(packet, addr).await?;
}
Err(e) => {
error!("select error: {:?}", e);
}
}
}
_ = self.observer.select_next_some() => {
self.observer.timer_handler().await;
}
complete => break,
}
}
Ok(())
}
/// Return the local address that the server is listening on. This can be useful when starting
/// a server on a random port as part of unit testing.
pub fn socket_addr(&self) -> std::io::Result<SocketAddr> {
self.server.socket_addr()
}
async fn dispatch_msg(&mut self, packet: Packet, addr: SocketAddr) -> Result<(), io::Error> {
let request = CoapRequest::from_packet(packet, addr);
let filtered = !self.observer.request_handler(&request).await;
if filtered {
return Ok(());
}
if let Some(ref mut handler) = self.handler {
match handler(request).await {
Some(response) => {
debug!("Response: {:?}", response);
self.server.send((response.message, addr)).await?;
}
None => {
debug!("No response");
}
}
}
Ok(())
}
/// enable AllCoAP multicasts - adds the AllCoap addresses to the listener
/// - IPv4 AllCoAP multicast address is '224.0.1.187'
/// - IPv6 AllCoAp multicast addresses are 'ff0?::fd'
///
/// Parameter segment is used with IPv6 to determine the first octet.
/// - It's value can be between 0x0 and 0xf.
/// - To join multiple segments, you have to call enable_discovery for each of the segments.
///
/// For further details see method join_multicast
pub fn enable_all_coap(&mut self, segment: u8) {
assert!(segment <= 0xf);
let socket = self.server.socket.get_mut();
let m = match socket.local_addr().unwrap() {
SocketAddr::V4(_val) => {
IpAddr::V4(Ipv4Addr::new(224, 0, 1, 187))
},
SocketAddr::V6(_val) => {
IpAddr::V6(Ipv6Addr::new(0xff00 + segment as u16,0,0,0,0,0,0,0xfd))
},
};
self.join_multicast(m);
}
/// join multicast - adds the multicast addresses to the unicast listener
/// - IPv4 multicast address range is '224.0.0.0/4'
/// - IPv6 AllCoAp multicast addresses are 'ff00::/8'
///
/// Parameter segment is used with IPv6 to determine the first octet.
/// - It's value can be between 0x0 and 0xf.
/// - To join multiple segments, you have to call enable_discovery for each of the segments.
///
/// Some Multicast address scope
/// IPv6 IPv4 equivalent[16] Scope Purpose
/// ffx1::/16 127.0.0.0/8 Interface-local Packets with this destination address may not be sent over any network link, but must remain within the current node; this is the multicast equivalent of the unicast loopback address.
/// ffx2::/16 224.0.0.0/24 Link-local Packets with this destination address may not be routed anywhere.
/// ffx3::/16 239.255.0.0/16 IPv4 local scope
/// ffx4::/16 Admin-local The smallest scope that must be administratively configured.
/// ffx5::/16 Site-local Restricted to the local physical network.
/// ffx8::/16 239.192.0.0/14 Organization-local Restricted to networks used by the organization administering the local network. (For example, these addresses might be used over VPNs; when packets for this group are routed over the public internet (where these addresses are not valid), they would have to be encapsulated in some other protocol.)
/// ffxe::/16 224.0.1.0-238.255.255.255 Global scope Eligible to be routed over the public internet.
///
/// Notable addresses:
/// ff02::1 All nodes on the local network segment
/// ff0x::c Simple Service Discovery Protocol
/// ff0x::fb Multicast DNS
/// ff0x::fb Multicast CoAP
/// ff0x::114 Used for experiments
pub fn join_multicast(&mut self, addr: IpAddr) {
self.server.join_multicast(addr);
}
/// leave multicast - remove the multicast address from the listener
pub fn leave_multicast(&mut self, addr: IpAddr) {
self.server.leave_multicast(addr);
}
}
pub struct CoAPServer {
receiver: MessageReceiver,
is_terminated: bool,
socket: UdpFramed<Codec>,
multicast_addresses: Vec<IpAddr>,
}
impl CoAPServer {
/// Creates a CoAP server listening on the given address.
pub fn new<A: ToSocketAddrs>(addr: A, receiver: MessageReceiver) -> Result<CoAPServer, io::Error> {
let socket = UdpSocket::from_std(net::UdpSocket::bind(addr).unwrap())?;
Ok(CoAPServer {
receiver,
is_terminated: false,
socket: UdpFramed::new(socket, Codec::new()),
multicast_addresses: Vec::new(),
})
}
/// Stop the server.
pub fn stop(&mut self) {
self.is_terminated = true;
}
/// send the packet to the specific address.
pub async fn send(&mut self, frame: (Packet, SocketAddr)) -> Result<(), io::Error> {
self.socket.send(frame).await
}
/// Return the local address that the server is listening on. This can be useful when starting
/// a server on a random port as part of unit testing.
pub fn socket_addr(&self) -> std::io::Result<SocketAddr> {
self.socket.get_ref().local_addr()
}
/// join multicast - adds the multicast addresses to the listener
pub fn join_multicast(&mut self, addr: IpAddr) {
assert!(addr.is_multicast());
let socket = self.socket.get_mut();
// determine wether IPv4 or IPv6 and
// join the appropriate multicast address
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
match addr {
IpAddr::V4(ipv4) => {
let i = val.ip().clone();
socket.join_multicast_v4(ipv4, i).unwrap();
self.multicast_addresses.push(addr);
}
IpAddr::V6(_ipv6) => { /* handle IPv6 */ }
}
},
SocketAddr::V6(_val) => {
match addr {
IpAddr::V4(_ipv4) => { /* handle IPv4 */ }
IpAddr::V6(ipv6) => {
socket.join_multicast_v6(&ipv6, 0).unwrap();
self.multicast_addresses.push(addr);
//socket.set_only_v6(true)?;
}
}
},
}
}
/// leave multicast - remove the multicast address from the listener
pub fn leave_multicast(&mut self, addr: IpAddr) {
assert!(addr.is_multicast());
let socket = self.socket.get_mut();
// determine wether IPv4 or IPv6 and
// leave the appropriate multicast address
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
match addr {
IpAddr::V4(ipv4) => {
let i = val.ip().clone();
socket.leave_multicast_v4(ipv4, i).unwrap();
let index = self.multicast_addresses.iter().position(|&item| item == addr).unwrap();
self.multicast_addresses.remove(index);
}
IpAddr::V6(_ipv6) => { /* handle IPv6 */ }
}
},
SocketAddr::V6(_val) => {
match addr {
IpAddr::V4(_ipv4) => { /* handle IPv4 */ }
IpAddr::V6(ipv6) => {
socket.leave_multicast_v6(&ipv6, 0).unwrap();
let index = self.multicast_addresses.iter().position(|&item| item == addr).unwrap();
self.multicast_addresses.remove(index);
}
}
},
}
}
}
impl Drop for CoAPServer {
fn drop(&mut self) {
// unregister still existing multicast addresses
let socket = self.socket.get_mut();
for addr in &self.multicast_addresses {
match addr {
IpAddr::V4(ipv4) => {
match socket.local_addr().unwrap() {
SocketAddr::V4(val) => {
socket.leave_multicast_v4(*ipv4, val.ip().clone()).unwrap();
}
_ => { panic!("should not happen"); }
}
}
IpAddr::V6(ipv6) => {
socket.leave_multicast_v6(&ipv6, 0).unwrap();
}
}
}
// stop server
self.stop();
}
}
impl Stream for CoAPServer {
type Item = Result<Message, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Poll::Ready(Some((p, a))) = self.receiver.poll_next_unpin(cx) {
return Poll::Ready(Some(Ok(Message::NeedSend(p, a))));
}
let result: Option<_> = futures::ready!(self.socket.poll_next_unpin(cx));
Poll::Ready(match result {
Some(Ok(message)) => {
let (my_packet, addr) = message;
Some(Ok(Message::Received(my_packet, addr)))
}
Some(Err(e)) => Some(Err(e)),
None => None,
})
}
}
impl FusedStream for CoAPServer {
fn is_terminated(&self) -> bool {
self.is_terminated
}
}
#[cfg(test)]
pub mod test {
use std::{
time::Duration,
sync::mpsc,
};
use coap_lite::CoapOption;
use super::super::*;
use super::*;
pub fn spawn_server<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
let mut server = server::Server::new("127.0.0.1:0").unwrap();
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
async fn request_handler(req: CoapRequest<SocketAddr>) -> Option<CoapResponse> {
let uri_path_list = req.message.get_option(CoapOption::UriPath).unwrap().clone();
assert_eq!(uri_path_list.len(), 1);
match req.response {
Some(mut response) => {
response.message.payload = uri_path_list.front().unwrap().clone();
Some(response)
}
_ => None,
}
}
pub fn spawn_v4_server_with_all_coap<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("v4-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("0.0.0.0", 0)).unwrap();
server.enable_all_coap(0x0);
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
pub fn spawn_v6_server_with_all_coap<F: FnMut(CoapRequest<SocketAddr>) -> HandlerRet + Send + 'static, HandlerRet>(request_handler: F, segment: u8) -> mpsc::Receiver<u16> where HandlerRet: Future<Output=Option<CoapResponse>> {
let (tx, rx) = mpsc::channel();
std::thread::Builder::new().name(String::from("v6-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("::0", 0)).unwrap();
server.enable_all_coap(segment);
tx.send(server.socket_addr().unwrap().port()).unwrap();
server.run(request_handler).await.unwrap();
})
}).unwrap();
rx
}
#[test]
fn test_echo_server() {
let server_port = spawn_server(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn test_echo_server_no_token() {
let server_port = spawn_server(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut packet = CoapRequest::new();
packet.message.header.set_version(1);
packet.message.header.set_type(coap_lite::MessageType::Confirmable);
packet.message.header.set_code("0.01");
packet.message.header.message_id = 1;
packet.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&packet).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn test_update_resource() {
let path = "/test";
let payload1 = b"data1".to_vec();
let payload2 = b"data2".to_vec();
let (tx, rx) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
let mut step = 1;
let server_port = spawn_server(request_handler).recv().unwrap();
let mut client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
tx.send(step).unwrap();
let mut request = CoapRequest::new();
request.set_method(coap_lite::RequestType::Put);
request.set_path(path);
request.message.payload = payload1.clone();
client.send(&request).unwrap();
client.receive().unwrap();
let mut receive_step = 1;
let payload1_clone = payload1.clone();
let payload2_clone = payload2.clone();
client.observe(path, move |msg| {
match rx.try_recv() {
Ok(n) => receive_step = n,
_ => (),
}
match receive_step {
1 => assert_eq!(msg.payload, payload1_clone),
2 => {
assert_eq!(msg.payload, payload2_clone);
tx2.send(()).unwrap();
}
_ => panic!("unexpected step"),
}
}).unwrap();
step = 2;
tx.send(step).unwrap();
request.message.payload = payload2.clone();
let client2 = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
client2.send(&request).unwrap();
client2.receive().unwrap();
assert_eq!(rx2.recv_timeout(Duration::new(5, 0)).unwrap(), ());
}
#[test]
fn multicast_server_all_coap_v4() {
let server_port = spawn_v4_server_with_all_coap(request_handler).recv().unwrap();
let client = CoAPClient::new(format!("127.0.0.1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
let client = CoAPClient::new(format!("224.0.1.187:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::NonConfirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 2;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send_all_coap(&request, 0x4).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
#[ignore] // This test does not work, not clear why. With a separate test client things seem to work.
fn multicast_server_all_coap_v6() {
// use segment 0x04 which should be the smallest administered scope
let segment = 0x04;
let server_port = spawn_v6_server_with_all_coap(request_handler, segment).recv().unwrap();
let client = CoAPClient::new(format!("::1:{}", server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::Confirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 1;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send(&request).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
// use 0xff02 to keep it within this network
let client = CoAPClient::new(format!("ff0{}::fd:{}", segment, server_port)).unwrap();
let mut request = CoapRequest::new();
request.message.header.set_version(1);
request.message.header.set_type(coap_lite::MessageType::NonConfirmable);
request.message.header.set_code("0.01");
request.message.header.message_id = 2;
request.message.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.message.add_option(CoapOption::UriPath, b"test-echo".to_vec());
client.send_all_coap(&request, segment).unwrap();
let recv_packet = client.receive().unwrap();
assert_eq!(recv_packet.message.payload, b"test-echo".to_vec());
}
#[test]
fn multicast_join_leave() {
std::thread::Builder::new().name(String::from("v4-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("0.0.0.0", 0)).unwrap();
server.join_multicast(IpAddr::V4(Ipv4Addr::new(224, 0, 1, 1)));
server.join_multicast(IpAddr::V4(Ipv4Addr::new(224, 1, 1, 1)));
server.leave_multicast(IpAddr::V4(Ipv4Addr::new(224, 0, 1, 1)));
server.leave_multicast(IpAddr::V4(Ipv4Addr::new(224, 1, 1, 1)));
server.run(request_handler).await.unwrap();
})
}).unwrap();
std::thread::Builder::new().name(String::from("v6-server")).spawn(move || {
tokio::runtime::Runtime::new().unwrap().block_on(async move {
// multicast needs a server on a real interface
let mut server = server::Server::new(("::0", 0)).unwrap();
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,0,1,0x1)));
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,1,0,0x2)));
server.leave_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,0,1,0x1)));
server.join_multicast(IpAddr::V6(Ipv6Addr::new(0xff02,0,0,0,0,1,0,0x2)));
server.run(request_handler).await.unwrap();
})
}).unwrap();
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
|
extern crate dbus;
use self::dbus::{NameFlag, ReleaseNameReply};
use super::connection::DBusConnection;
use super::error::DBusError;
use super::interface::DBusInterfaceMap;
use super::message::{DBusMessage, DBusMessageType};
use super::object::DBusObject;
use super::target::DBusTarget;
use std::collections::btree_map::{BTreeMap, Entry};
pub type DBusSignalHandler = Box<FnMut(&DBusConnection, &DBusTarget) -> ()>;
type DBusSignalHandlers = Vec<DBusSignalHandler>;
type DBusSignalHandlerMap = BTreeMap<DBusTarget, DBusSignalHandlers>;
fn _add_handler(handlers: &mut DBusSignalHandlerMap, signal: DBusTarget, handler: DBusSignalHandler) {
match handlers.entry(signal) {
Entry::Vacant(v) => { v.insert(vec![handler]); },
Entry::Occupied(o) => o.into_mut().push(handler),
};
}
pub struct DBusServer<'a> {
conn: &'a DBusConnection,
name: String,
objects: BTreeMap<String, DBusObject<'a>>,
signals: DBusSignalHandlerMap,
namespace_signals: DBusSignalHandlerMap,
}
impl<'a> DBusServer<'a> {
pub fn new(conn: &'a DBusConnection, name: &str) -> Result<DBusServer<'a>, DBusError> {
try!(conn.register_name(name, NameFlag::DoNotQueue as u32));
Ok(DBusServer {
conn: conn,
name: name.to_owned(),
objects: BTreeMap::new(),
signals: BTreeMap::new(),
namespace_signals: BTreeMap::new(),
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn add_object(&mut self, path: &str, iface_map: DBusInterfaceMap<'a>) -> Result<&mut Self, DBusError> {
// XXX: Use `.map` when type resolution works better. Currently, `.map` causes the caller
// type to be set in stone due to eager type resolution and no fluidity in setting it. This
// causes the type to be too concrete on the caller side which then fails to map to the end
// result type of `.map` even though `.map` is "transparent" to the error type.
Result::map(match self.objects.entry(path.to_owned()) {
Entry::Vacant(v) => {
let obj = try!(DBusObject::new(self.conn, path, iface_map));
v.insert(obj);
Ok(())
},
Entry::Occupied(_) => Err(DBusError::PathAlreadyRegistered(path.to_owned())),
}, |_| self)
}
pub fn remove_object(&mut self, path: &str) -> Result<&mut Self, DBusError> {
match self.objects.remove(path) {
Some(_) => Ok(self),
None => Err(DBusError::NoSuchPath(path.to_owned())),
}
}
pub fn connect(&mut self, signal: DBusTarget, callback: DBusSignalHandler) -> Result<&mut Self, DBusError> {
try!(self.conn.add_match(&format!("type='signal',interface='{}',path='{}',member='{}'",
signal.interface,
signal.object,
signal.method)));
_add_handler(&mut self.signals, signal, callback);
Ok(self)
}
pub fn connect_namespace(&mut self, signal: DBusTarget, callback: DBusSignalHandler) -> Result<&mut Self, DBusError> {
try!(self.conn.add_match(&format!("type='signal',interface='{}',path_namespace='{}',member='{}'",
signal.interface,
signal.object,
signal.method)));
_add_handler(&mut self.namespace_signals, signal, callback);
Ok(self)
}
pub fn handle_message<'b>(&mut self, m: &'b mut DBusMessage) -> Option<&'b mut DBusMessage> {
match m.msg_type() {
DBusMessageType::Signal => Some(self._match_signal(m)),
DBusMessageType::MethodCall => self._call_method(m),
_ => Some(m),
}
}
fn _call_method<'b>(&mut self, m: &'b mut DBusMessage) -> Option<&'b mut DBusMessage> {
self.objects.iter_mut().fold(Some(m), |opt_m, (_, object)| {
opt_m.and_then(|mut m| {
match object.handle_message(&mut m) {
None => Some(m),
Some(Ok(())) => None,
Some(Err(())) => {
println!("failed to send a reply for {:?}", m);
None
},
}
})
})
}
fn _match_signal<'b>(&mut self, m: &'b mut DBusMessage) -> &'b mut DBusMessage {
let conn = (&self.conn).clone();
DBusTarget::extract(m).map(|signal| {
self.signals.get_mut(&signal).map(|handlers| {
handlers.iter_mut().map(|f| {
f(conn, &signal);
})
});
self.namespace_signals.iter_mut().filter(|&(expect, _)| {
expect.namespace_eq(&signal)
}).map(|(_, handlers)| {
handlers.iter_mut().map(|f| {
f(conn, &signal);
})
}).collect::<Vec<_>>();
});
m
}
}
impl<'a> Drop for DBusServer<'a> {
fn drop(&mut self) {
let res = self.conn.release_name(&self.name);
match res {
Ok(reply) =>
match reply {
ReleaseNameReply::Released => (),
ReleaseNameReply::NonExistent => panic!("internal error: non-existent name {}?!", self.name),
ReleaseNameReply::NotOwner => panic!("internal error: not the owner of {}?!", self.name),
},
Err(err) => println!("failed to release {}: {:?}: {:?}", self.name, err.name(), err.message()),
}
}
}
server: simplify add_object
Unifying the error type has multiple benefits :) .
extern crate dbus;
use self::dbus::{NameFlag, ReleaseNameReply};
use super::connection::DBusConnection;
use super::error::DBusError;
use super::interface::DBusInterfaceMap;
use super::message::{DBusMessage, DBusMessageType};
use super::object::DBusObject;
use super::target::DBusTarget;
use std::collections::btree_map::{BTreeMap, Entry};
pub type DBusSignalHandler = Box<FnMut(&DBusConnection, &DBusTarget) -> ()>;
type DBusSignalHandlers = Vec<DBusSignalHandler>;
type DBusSignalHandlerMap = BTreeMap<DBusTarget, DBusSignalHandlers>;
fn _add_handler(handlers: &mut DBusSignalHandlerMap, signal: DBusTarget, handler: DBusSignalHandler) {
match handlers.entry(signal) {
Entry::Vacant(v) => { v.insert(vec![handler]); },
Entry::Occupied(o) => o.into_mut().push(handler),
};
}
pub struct DBusServer<'a> {
conn: &'a DBusConnection,
name: String,
objects: BTreeMap<String, DBusObject<'a>>,
signals: DBusSignalHandlerMap,
namespace_signals: DBusSignalHandlerMap,
}
impl<'a> DBusServer<'a> {
pub fn new(conn: &'a DBusConnection, name: &str) -> Result<DBusServer<'a>, DBusError> {
try!(conn.register_name(name, NameFlag::DoNotQueue as u32));
Ok(DBusServer {
conn: conn,
name: name.to_owned(),
objects: BTreeMap::new(),
signals: BTreeMap::new(),
namespace_signals: BTreeMap::new(),
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn add_object(&mut self, path: &str, iface_map: DBusInterfaceMap<'a>) -> Result<&mut Self, DBusError> {
match self.objects.entry(path.to_owned()) {
Entry::Vacant(v) => {
let obj = try!(DBusObject::new(self.conn, path, iface_map));
v.insert(obj);
Ok(())
},
Entry::Occupied(_) => Err(DBusError::PathAlreadyRegistered(path.to_owned())),
}.map(|_| self)
}
pub fn remove_object(&mut self, path: &str) -> Result<&mut Self, DBusError> {
match self.objects.remove(path) {
Some(_) => Ok(self),
None => Err(DBusError::NoSuchPath(path.to_owned())),
}
}
pub fn connect(&mut self, signal: DBusTarget, callback: DBusSignalHandler) -> Result<&mut Self, DBusError> {
try!(self.conn.add_match(&format!("type='signal',interface='{}',path='{}',member='{}'",
signal.interface,
signal.object,
signal.method)));
_add_handler(&mut self.signals, signal, callback);
Ok(self)
}
pub fn connect_namespace(&mut self, signal: DBusTarget, callback: DBusSignalHandler) -> Result<&mut Self, DBusError> {
try!(self.conn.add_match(&format!("type='signal',interface='{}',path_namespace='{}',member='{}'",
signal.interface,
signal.object,
signal.method)));
_add_handler(&mut self.namespace_signals, signal, callback);
Ok(self)
}
pub fn handle_message<'b>(&mut self, m: &'b mut DBusMessage) -> Option<&'b mut DBusMessage> {
match m.msg_type() {
DBusMessageType::Signal => Some(self._match_signal(m)),
DBusMessageType::MethodCall => self._call_method(m),
_ => Some(m),
}
}
fn _call_method<'b>(&mut self, m: &'b mut DBusMessage) -> Option<&'b mut DBusMessage> {
self.objects.iter_mut().fold(Some(m), |opt_m, (_, object)| {
opt_m.and_then(|mut m| {
match object.handle_message(&mut m) {
None => Some(m),
Some(Ok(())) => None,
Some(Err(())) => {
println!("failed to send a reply for {:?}", m);
None
},
}
})
})
}
fn _match_signal<'b>(&mut self, m: &'b mut DBusMessage) -> &'b mut DBusMessage {
let conn = (&self.conn).clone();
DBusTarget::extract(m).map(|signal| {
self.signals.get_mut(&signal).map(|handlers| {
handlers.iter_mut().map(|f| {
f(conn, &signal);
})
});
self.namespace_signals.iter_mut().filter(|&(expect, _)| {
expect.namespace_eq(&signal)
}).map(|(_, handlers)| {
handlers.iter_mut().map(|f| {
f(conn, &signal);
})
}).collect::<Vec<_>>();
});
m
}
}
impl<'a> Drop for DBusServer<'a> {
fn drop(&mut self) {
let res = self.conn.release_name(&self.name);
match res {
Ok(reply) =>
match reply {
ReleaseNameReply::Released => (),
ReleaseNameReply::NonExistent => panic!("internal error: non-existent name {}?!", self.name),
ReleaseNameReply::NotOwner => panic!("internal error: not the owner of {}?!", self.name),
},
Err(err) => println!("failed to release {}: {:?}: {:?}", self.name, err.name(), err.message()),
}
}
}
|
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::RwLock;
use std::sync::mpsc::{channel, Receiver, Sender};
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;
/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
item: Arc<T>,
}
impl<T> Clone for SharedItem<T> {
fn clone(&self) -> Self {
SharedItem { item: self.item.clone() }
}
}
impl<T> Deref for SharedItem<T> {
type Target = T;
fn deref(&self) -> &T {
&self.item.as_ref()
}
}
/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
error: Arc<E>,
}
impl<T> Clone for SharedError<T> {
fn clone(&self) -> Self {
SharedError { error: self.error.clone() }
}
}
impl<E> Deref for SharedError<E> {
type Target = E;
fn deref(&self) -> &E {
&self.error.as_ref()
}
}
impl<T> SharedItem<T> {
fn new(item: T) -> Self {
SharedItem { item: Arc::new(item) }
}
}
impl<E> SharedError<E> {
fn new(error: E) -> Self {
SharedError { error: Arc::new(error) }
}
}
/// The data that has to be synced to implement `Shared`, in order to satisfy the `Future` trait's constraints.
struct SyncedInner<F>
where F: Future
{
original_future: F, // The original future
result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>>, // The original future result wrapped with `SharedItem`/`SharedError`
tasks_receiver: Lock<Receiver<Task>>, // When original future is polled and ready, unparks all the tasks in that channel
}
struct Inner<F>
where F: Future
{
synced_inner: RwLock<SyncedInner<F>>,
tasks_unpark_started: AtomicBool,
}
/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
where F: Future
{
inner: Arc<Inner<F>>,
tasks_sender: Sender<Task>,
}
pub fn new<F>(future: F) -> Shared<F>
where F: Future
{
let (tasks_sender, tasks_receiver) = channel();
Shared {
inner: Arc::new(Inner {
synced_inner: RwLock::new(SyncedInner {
original_future: future,
result: None,
tasks_receiver: Lock::new(tasks_receiver),
}),
tasks_unpark_started: AtomicBool::new(false),
}),
tasks_sender: tasks_sender,
}
}
impl<F> Future for Shared<F>
where F: Future
{
type Item = SharedItem<F::Item>;
type Error = SharedError<F::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut polled_result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>> =
None;
// If the result is ready, just return it
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
if let Some(ref result) = inner.result {
return result.clone();
}
}
_ => {} // Mutex is locked for write
}
// The result was not ready.
match self.inner.synced_inner.try_write() {
Ok(mut inner_guard) => {
let ref mut inner = *inner_guard;
// By the time that synced_inner was unlocked, other thread could poll the result,
// so we check if result has a value
if inner.result.is_some() {
polled_result = inner.result.clone();
} else {
match inner.original_future.poll() {
Ok(Async::Ready(item)) => {
inner.result = Some(Ok(Async::Ready(SharedItem::new(item))));
polled_result = inner.result.clone();
}
Err(error) => {
inner.result = Some(Err(SharedError::new(error)));
polled_result = inner.result.clone();
}
Ok(Async::NotReady) => {} // Will be handled later
}
}
}
Err(_) => {} // Will be handled later
}
if polled_result.is_some() {
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
match inner.tasks_receiver.try_lock() {
Some(tasks_receiver_guard) => {
let ref tasks_receiver = *tasks_receiver_guard;
loop {
match tasks_receiver.try_recv() {
Ok(task) => task.unpark(),
_ => break,
}
}
}
None => {} // Other thread is unparking the tasks
}
if let Some(ref result) = inner.result {
return result.clone();
} else {
unreachable!();
}
}
_ => {
// The mutex is locked for write, after the poll was ready.
// The context that locked for write will unpark the tasks.
}
}
}
let t = task::park();
let _ = self.tasks_sender.send(t);
if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
// If the tasks unpark has started, synced_inner can be locked for read,
// and its result has value (not None).
// The result must be read here because it is possible that the task,
// t (see variable above), had not been unparked.
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
if let Some(ref result) = inner.result {
return result.clone();
}
}
_ => {
// The mutex is locked for write, so the sent task will be unparked later
}
}
}
Ok(Async::NotReady)
}
}
impl<F> Clone for Shared<F>
where F: Future
{
fn clone(&self) -> Self {
Shared {
inner: self.inner.clone(),
tasks_sender: self.tasks_sender.clone(),
}
}
}
Some cr fixes
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::RwLock;
use std::sync::mpsc::{channel, Receiver, Sender};
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;
/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
item: Arc<T>,
}
impl<T> Clone for SharedItem<T> {
fn clone(&self) -> Self {
SharedItem { item: self.item.clone() }
}
}
impl<T> Deref for SharedItem<T> {
type Target = T;
fn deref(&self) -> &T {
&self.item.as_ref()
}
}
/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
error: Arc<E>,
}
impl<T> Clone for SharedError<T> {
fn clone(&self) -> Self {
SharedError { error: self.error.clone() }
}
}
impl<E> Deref for SharedError<E> {
type Target = E;
fn deref(&self) -> &E {
&self.error.as_ref()
}
}
impl<T> SharedItem<T> {
fn new(item: T) -> Self {
SharedItem { item: Arc::new(item) }
}
}
impl<E> SharedError<E> {
fn new(error: E) -> Self {
SharedError { error: Arc::new(error) }
}
}
/// The data that has to be synced to implement `Shared`, in order to satisfy the `Future` trait's constraints.
struct SyncedInner<F>
where F: Future
{
original_future: F, // The original future
result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>>, // The original future result wrapped with `SharedItem`/`SharedError`
tasks_receiver: Lock<Receiver<Task>>, // When original future is polled and ready, unparks all the tasks in that channel
}
struct Inner<F>
where F: Future
{
synced_inner: RwLock<SyncedInner<F>>,
tasks_unpark_started: AtomicBool,
}
/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
where F: Future
{
inner: Arc<Inner<F>>,
tasks_sender: Sender<Task>,
}
pub fn new<F>(future: F) -> Shared<F>
where F: Future
{
let (tasks_sender, tasks_receiver) = channel();
Shared {
inner: Arc::new(Inner {
synced_inner: RwLock::new(SyncedInner {
original_future: future,
result: None,
tasks_receiver: Lock::new(tasks_receiver),
}),
tasks_unpark_started: AtomicBool::new(false),
}),
tasks_sender: tasks_sender,
}
}
impl<F> Future for Shared<F>
where F: Future
{
type Item = SharedItem<F::Item>;
type Error = SharedError<F::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut polled_result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>> =
None;
// If the result is ready, just return it
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
if let Some(ref result) = inner.result {
return result.clone();
}
}
_ => {} // Mutex is locked for write
}
// The result was not ready.
match self.inner.synced_inner.try_write() {
Ok(mut inner_guard) => {
let ref mut inner = *inner_guard;
// By the time that synced_inner was unlocked, other thread could poll the result,
// so we check if result has a value
if inner.result.is_some() {
polled_result = inner.result.clone();
} else {
match inner.original_future.poll() {
Ok(Async::Ready(item)) => {
inner.result = Some(Ok(Async::Ready(SharedItem::new(item))));
polled_result = inner.result.clone();
}
Err(error) => {
inner.result = Some(Err(SharedError::new(error)));
polled_result = inner.result.clone();
}
Ok(Async::NotReady) => {} // Will be handled later
}
}
}
Err(_) => {} // Will be handled later
}
if let Some(result) = polled_result {
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
match inner.tasks_receiver.try_lock() {
Some(tasks_receiver_guard) => {
let ref tasks_receiver = *tasks_receiver_guard;
loop {
match tasks_receiver.try_recv() {
Ok(task) => task.unpark(),
_ => break,
}
}
}
None => {} // Other thread is unparking the tasks
}
return result.clone();
}
_ => {
// The mutex is locked for write, after the poll was ready.
// The context that locked for write will unpark the tasks.
}
}
}
let t = task::park();
let _ = self.tasks_sender.send(t);
if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
// If the tasks unpark has started, synced_inner can be locked for read,
// and its result has value (not None).
// The result must be read here because it is possible that the task,
// t (see variable above), had not been unparked.
match self.inner.synced_inner.try_read() {
Ok(inner_guard) => {
let ref inner = *inner_guard;
return inner.result.as_ref().unwrap().clone();
}
_ => {
// The mutex is locked for write, so the sent task will be unparked later
}
}
}
Ok(Async::NotReady)
}
}
impl<F> Clone for Shared<F>
where F: Future
{
fn clone(&self) -> Self {
Shared {
inner: self.inner.clone(),
tasks_sender: self.tasks_sender.clone(),
}
}
}
|
use iron::Middleware;
use std::sync::Arc;
pub struct Shared {
pub middleware: Arc<Box<Middleware + Send + Share>>
}
// Needed to hack name resolution in our Clone impl
fn clone<T: Clone>(t: &T) -> T { t.clone() }
impl Clone for Shared {
fn clone(&self) -> Shared {
Shared {
middleware: clone(&self.middleware)
}
}
}
(feat) Switched to using ShareableMiddleware.
use iron::{Middleware, Request, Response, Alloy};
use iron::middleware::Status;
use std::sync::Arc;
pub trait ShareableMiddleware {
fn shared_enter(&self, req: &mut Request, res: &mut Response, alloy: &mut Alloy) -> Status;
fn shared_exit(&self, req: &mut Request, res: &mut Response, alloy: &mut Alloy) -> Status;
}
pub struct Shared {
pub middleware: Arc<Box<ShareableMiddleware + Send + Share>>
}
// Needed to hack name resolution in our Clone impl
fn clone<T: Clone>(t: &T) -> T { t.clone() }
impl Clone for Shared {
fn clone(&self) -> Shared {
Shared {
middleware: clone(&self.middleware)
}
}
}
impl Middleware for Shared {
fn enter(&mut self, req: &mut Request, res: &mut Response, alloy: &mut Alloy) -> Status {
self.middleware.shared_enter(req, res, alloy)
}
fn exit(&mut self, req: &mut Request, res: &mut Response, alloy: &mut Alloy) -> Status {
self.middleware.shared_exit(req, res, alloy)
}
}
|
#![feature(plugin)]
#![plugin(clippy)]
#[deny(string_add)]
#[allow(string_add_assign)]
fn add_only() { // ignores assignment distinction
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you add something to a string.
}
let y = "".to_owned();
let z = y + "..."; //~ERROR you add something to a string.
assert_eq!(&x, &z);
}
#[deny(string_add_assign)]
fn add_assign_only() {
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you assign the result of adding something to this string.
}
let y = "".to_owned();
let z = y + "...";
assert_eq!(&x, &z);
}
#[deny(string_add, string_add_assign)]
fn both() {
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you assign the result of adding something to this string.
}
let y = "".to_owned();
let z = y + "..."; //~ERROR you add something to a string.
assert_eq!(&x, &z);
}
fn main() {
add_only();
add_assign_only();
both();
// the add is only caught for String
let mut x = 1;
x = x + 1;
assert_eq!(2, x);
}
fixed error messages in compile-fail test
#![feature(plugin)]
#![plugin(clippy)]
#[deny(string_add)]
#[allow(string_add_assign)]
fn add_only() { // ignores assignment distinction
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you added something to a string.
}
let y = "".to_owned();
let z = y + "..."; //~ERROR you added something to a string.
assert_eq!(&x, &z);
}
#[deny(string_add_assign)]
fn add_assign_only() {
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you assigned the result of adding something to this string.
}
let y = "".to_owned();
let z = y + "...";
assert_eq!(&x, &z);
}
#[deny(string_add, string_add_assign)]
fn both() {
let mut x = "".to_owned();
for _ in (1..3) {
x = x + "."; //~ERROR you assigned the result of adding something to this string.
}
let y = "".to_owned();
let z = y + "..."; //~ERROR you added something to a string.
assert_eq!(&x, &z);
}
fn main() {
add_only();
add_assign_only();
both();
// the add is only caught for String
let mut x = 1;
x = x + 1;
assert_eq!(2, x);
}
|
//! Tests for configuration values that point to programs.
use cargo_test_support::{basic_lib_manifest, project, rustc_host, rustc_host_env};
#[cargo_test]
fn pathless_tools() {
let target = rustc_host();
let foo = project()
.file("Cargo.toml", &basic_lib_manifest("foo"))
.file("src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{}]
linker = "nonexistent-linker"
"#,
target
),
)
.build();
foo.cargo("build --verbose")
.with_stderr(
"\
[COMPILING] foo v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker=nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
.run();
}
#[cargo_test]
fn absolute_tools() {
let target = rustc_host();
// Escaped as they appear within a TOML config file
let linker = if cfg!(windows) {
r#"C:\\bogus\\nonexistent-linker"#
} else {
r#"/bogus/nonexistent-linker"#
};
let foo = project()
.file("Cargo.toml", &basic_lib_manifest("foo"))
.file("src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{target}]
linker = "{linker}"
"#,
target = target,
linker = linker
),
)
.build();
foo.cargo("build --verbose")
.with_stderr(
"\
[COMPILING] foo v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker=[..]bogus/nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
.run();
}
#[cargo_test]
fn relative_tools() {
let target = rustc_host();
// Escaped as they appear within a TOML config file
let linker = if cfg!(windows) {
r#".\\tools\\nonexistent-linker"#
} else {
r#"./tools/nonexistent-linker"#
};
// Funky directory structure to test that relative tool paths are made absolute
// by reference to the `.cargo/..` directory and not to (for example) the CWD.
let p = project()
.no_manifest()
.file("bar/Cargo.toml", &basic_lib_manifest("bar"))
.file("bar/src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{target}]
linker = "{linker}"
"#,
target = target,
linker = linker
),
)
.build();
let prefix = p.root().into_os_string().into_string().unwrap();
p.cargo("build --verbose")
.cwd("bar")
.with_stderr(&format!(
"\
[COMPILING] bar v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker={prefix}/./tools/nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
prefix = prefix,
))
.run();
}
#[cargo_test]
fn custom_runner() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file("tests/test.rs", "")
.file("benches/bench.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{}]
runner = "nonexistent-runner -r"
"#,
target
),
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
p.cargo("test --test test --verbose -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc [..]`
[FINISHED] test [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r [..]/target/debug/deps/test-[..][EXE] --param`
",
)
.run();
p.cargo("bench --bench bench --verbose -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc [..]`
[RUNNING] `rustc [..]`
[FINISHED] bench [optimized] target(s) in [..]
[RUNNING] `nonexistent-runner -r [..]/target/release/deps/bench-[..][EXE] --param --bench`
",
)
.run();
}
// can set a custom runner via `target.'cfg(..)'.runner`
#[cargo_test]
fn custom_runner_cfg() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
r#"
[target.'cfg(not(target_os = "none"))']
runner = "nonexistent-runner -r"
"#,
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
}
// custom runner set via `target.$triple.runner` have precedence over `target.'cfg(..)'.runner`
#[cargo_test]
fn custom_runner_cfg_precedence() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
&format!(
r#"
[target.'cfg(not(target_os = "none"))']
runner = "ignored-runner"
[target.{}]
runner = "nonexistent-runner -r"
"#,
target
),
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
}
#[cargo_test]
fn custom_runner_cfg_collision() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
r#"
[target.'cfg(not(target_arch = "avr"))']
runner = "true"
[target.'cfg(not(target_os = "none"))']
runner = "false"
"#,
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr(
"\
[ERROR] several matching instances of `target.'cfg(..)'.runner` in `.cargo/config`
first match `cfg(not(target_arch = \"avr\"))` located in [..]/foo/.cargo/config
second match `cfg(not(target_os = \"none\"))` located in [..]/foo/.cargo/config
",
)
.run();
}
#[cargo_test]
fn custom_runner_env() {
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "nonexistent-runner --foo")
.with_status(101)
// FIXME: Update "Caused by" error message once rust/pull/87704 is merged.
// On Windows, changing to a custom executable resolver has changed the
// error messages.
.with_stderr(&format!(
"\
[COMPILING] foo [..]
[FINISHED] dev [..]
[RUNNING] `nonexistent-runner --foo target/debug/foo[EXE]`
[ERROR] could not execute process `nonexistent-runner --foo target/debug/foo[EXE]` (never executed)
Caused by:
[..]
"
))
.run();
}
#[cargo_test]
fn custom_runner_env_overrides_config() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config.toml",
&format!(
r#"
[target.{}]
runner = "should-not-run -r"
"#,
target
),
)
.build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "should-run --foo")
.with_status(101)
.with_stderr_contains("[RUNNING] `should-run --foo target/debug/foo[EXE]`")
.run();
}
#[cargo_test]
#[cfg(unix)] // Assumes `true` is in PATH.
fn custom_runner_env_true() {
// Check for a bug where "true" was interpreted as a boolean instead of
// the executable.
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "true")
.with_stderr_contains("[RUNNING] `true target/debug/foo[EXE]`")
.run();
}
#[cargo_test]
fn custom_linker_env() {
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_LINKER", rustc_host_env());
p.cargo("build -v")
.env(&key, "nonexistent-linker")
.with_status(101)
.with_stderr_contains("[RUNNING] `rustc [..]-C linker=nonexistent-linker [..]")
.run();
}
#[cargo_test]
fn target_in_environment_contains_lower_case() {
let p = project().file("src/main.rs", "fn main() {}").build();
let target = rustc_host();
let env_key = format!(
"CARGO_TARGET_{}_LINKER",
target.to_lowercase().replace('-', "_")
);
p.cargo("build -v --target")
.arg(target)
.env(&env_key, "nonexistent-linker")
.with_stderr_contains(format!(
"warning: Environment variables are expected to use uppercase \
letters and underscores, the variable `{}` will be ignored and \
have no effect",
env_key
))
.run();
}
#[cargo_test]
fn cfg_ignored_fields() {
// Test for some ignored fields in [target.'cfg()'] tables.
let p = project()
.file(
".cargo/config",
r#"
# Try some empty tables.
[target.'cfg(not(foo))']
[target.'cfg(not(bar))'.somelib]
# A bunch of unused fields.
[target.'cfg(not(target_os = "none"))']
linker = 'false'
ar = 'false'
foo = {rustc-flags = "-l foo"}
invalid = 1
runner = 'false'
rustflags = ''
"#,
)
.file("src/lib.rs", "")
.build();
p.cargo("check")
.with_stderr(
"\
[WARNING] unused key `somelib` in [target] config table `cfg(not(bar))`
[WARNING] unused key `ar` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `foo` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `invalid` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `linker` in [target] config table `cfg(not(target_os = \"none\"))`
[CHECKING] foo v0.0.1 ([..])
[FINISHED] [..]
",
)
.run();
}
Fix test
Signed-off-by: hi-rustin <c7d168847ad25898cad3ce2d480246882ded574b@gmail.com>
//! Tests for configuration values that point to programs.
use cargo_test_support::{basic_lib_manifest, project, rustc_host, rustc_host_env};
#[cargo_test]
fn pathless_tools() {
let target = rustc_host();
let foo = project()
.file("Cargo.toml", &basic_lib_manifest("foo"))
.file("src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{}]
linker = "nonexistent-linker"
"#,
target
),
)
.build();
foo.cargo("build --verbose")
.with_stderr(
"\
[COMPILING] foo v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker=nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
.run();
}
#[cargo_test]
fn absolute_tools() {
let target = rustc_host();
// Escaped as they appear within a TOML config file
let linker = if cfg!(windows) {
r#"C:\\bogus\\nonexistent-linker"#
} else {
r#"/bogus/nonexistent-linker"#
};
let foo = project()
.file("Cargo.toml", &basic_lib_manifest("foo"))
.file("src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{target}]
linker = "{linker}"
"#,
target = target,
linker = linker
),
)
.build();
foo.cargo("build --verbose")
.with_stderr(
"\
[COMPILING] foo v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker=[..]bogus/nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
.run();
}
#[cargo_test]
fn relative_tools() {
let target = rustc_host();
// Escaped as they appear within a TOML config file
let linker = if cfg!(windows) {
r#".\\tools\\nonexistent-linker"#
} else {
r#"./tools/nonexistent-linker"#
};
// Funky directory structure to test that relative tool paths are made absolute
// by reference to the `.cargo/..` directory and not to (for example) the CWD.
let p = project()
.no_manifest()
.file("bar/Cargo.toml", &basic_lib_manifest("bar"))
.file("bar/src/lib.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{target}]
linker = "{linker}"
"#,
target = target,
linker = linker
),
)
.build();
let prefix = p.root().into_os_string().into_string().unwrap();
p.cargo("build --verbose")
.cwd("bar")
.with_stderr(&format!(
"\
[COMPILING] bar v0.5.0 ([CWD])
[RUNNING] `rustc [..] -C linker={prefix}/./tools/nonexistent-linker [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
prefix = prefix,
))
.run();
}
#[cargo_test]
fn custom_runner() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file("tests/test.rs", "")
.file("benches/bench.rs", "")
.file(
".cargo/config",
&format!(
r#"
[target.{}]
runner = "nonexistent-runner -r"
"#,
target
),
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
p.cargo("test --test test --verbose -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc [..]`
[FINISHED] test [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r [..]/target/debug/deps/test-[..][EXE] --param`
",
)
.run();
p.cargo("bench --bench bench --verbose -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc [..]`
[RUNNING] `rustc [..]`
[FINISHED] bench [optimized] target(s) in [..]
[RUNNING] `nonexistent-runner -r [..]/target/release/deps/bench-[..][EXE] --param --bench`
",
)
.run();
}
// can set a custom runner via `target.'cfg(..)'.runner`
#[cargo_test]
fn custom_runner_cfg() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
r#"
[target.'cfg(not(target_os = "none"))']
runner = "nonexistent-runner -r"
"#,
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
}
// custom runner set via `target.$triple.runner` have precedence over `target.'cfg(..)'.runner`
#[cargo_test]
fn custom_runner_cfg_precedence() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
&format!(
r#"
[target.'cfg(not(target_os = "none"))']
runner = "ignored-runner"
[target.{}]
runner = "nonexistent-runner -r"
"#,
target
),
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr_contains(
"\
[COMPILING] foo v0.0.1 ([CWD])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
[RUNNING] `nonexistent-runner -r target/debug/foo[EXE] --param`
",
)
.run();
}
#[cargo_test]
fn custom_runner_cfg_collision() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config",
r#"
[target.'cfg(not(target_arch = "avr"))']
runner = "true"
[target.'cfg(not(target_os = "none"))']
runner = "false"
"#,
)
.build();
p.cargo("run -- --param")
.with_status(101)
.with_stderr(
"\
[ERROR] several matching instances of `target.'cfg(..)'.runner` in configurations
first match `cfg(not(target_arch = \"avr\"))` located in [..]/foo/.cargo/config
second match `cfg(not(target_os = \"none\"))` located in [..]/foo/.cargo/config
",
)
.run();
}
#[cargo_test]
fn custom_runner_env() {
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "nonexistent-runner --foo")
.with_status(101)
// FIXME: Update "Caused by" error message once rust/pull/87704 is merged.
// On Windows, changing to a custom executable resolver has changed the
// error messages.
.with_stderr(&format!(
"\
[COMPILING] foo [..]
[FINISHED] dev [..]
[RUNNING] `nonexistent-runner --foo target/debug/foo[EXE]`
[ERROR] could not execute process `nonexistent-runner --foo target/debug/foo[EXE]` (never executed)
Caused by:
[..]
"
))
.run();
}
#[cargo_test]
fn custom_runner_env_overrides_config() {
let target = rustc_host();
let p = project()
.file("src/main.rs", "fn main() {}")
.file(
".cargo/config.toml",
&format!(
r#"
[target.{}]
runner = "should-not-run -r"
"#,
target
),
)
.build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "should-run --foo")
.with_status(101)
.with_stderr_contains("[RUNNING] `should-run --foo target/debug/foo[EXE]`")
.run();
}
#[cargo_test]
#[cfg(unix)] // Assumes `true` is in PATH.
fn custom_runner_env_true() {
// Check for a bug where "true" was interpreted as a boolean instead of
// the executable.
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_RUNNER", rustc_host_env());
p.cargo("run")
.env(&key, "true")
.with_stderr_contains("[RUNNING] `true target/debug/foo[EXE]`")
.run();
}
#[cargo_test]
fn custom_linker_env() {
let p = project().file("src/main.rs", "fn main() {}").build();
let key = format!("CARGO_TARGET_{}_LINKER", rustc_host_env());
p.cargo("build -v")
.env(&key, "nonexistent-linker")
.with_status(101)
.with_stderr_contains("[RUNNING] `rustc [..]-C linker=nonexistent-linker [..]")
.run();
}
#[cargo_test]
fn target_in_environment_contains_lower_case() {
let p = project().file("src/main.rs", "fn main() {}").build();
let target = rustc_host();
let env_key = format!(
"CARGO_TARGET_{}_LINKER",
target.to_lowercase().replace('-', "_")
);
p.cargo("build -v --target")
.arg(target)
.env(&env_key, "nonexistent-linker")
.with_stderr_contains(format!(
"warning: Environment variables are expected to use uppercase \
letters and underscores, the variable `{}` will be ignored and \
have no effect",
env_key
))
.run();
}
#[cargo_test]
fn cfg_ignored_fields() {
// Test for some ignored fields in [target.'cfg()'] tables.
let p = project()
.file(
".cargo/config",
r#"
# Try some empty tables.
[target.'cfg(not(foo))']
[target.'cfg(not(bar))'.somelib]
# A bunch of unused fields.
[target.'cfg(not(target_os = "none"))']
linker = 'false'
ar = 'false'
foo = {rustc-flags = "-l foo"}
invalid = 1
runner = 'false'
rustflags = ''
"#,
)
.file("src/lib.rs", "")
.build();
p.cargo("check")
.with_stderr(
"\
[WARNING] unused key `somelib` in [target] config table `cfg(not(bar))`
[WARNING] unused key `ar` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `foo` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `invalid` in [target] config table `cfg(not(target_os = \"none\"))`
[WARNING] unused key `linker` in [target] config table `cfg(not(target_os = \"none\"))`
[CHECKING] foo v0.0.1 ([..])
[FINISHED] [..]
",
)
.run();
}
|
use crate::error::{Error, Result};
use crate::gen::fs;
use crate::Project;
use std::env;
use std::path::{Path, PathBuf};
pub(crate) enum TargetDir {
Path(PathBuf),
Unknown,
}
pub(crate) fn out_dir() -> Result<PathBuf> {
env::var_os("OUT_DIR")
.map(PathBuf::from)
.ok_or(Error::MissingOutDir)
}
pub(crate) fn cc_build(prj: &Project) -> cc::Build {
let mut build = cc::Build::new();
build.include(include_dir(prj));
if let TargetDir::Path(target_dir) = &prj.target_dir {
build.include(target_dir.parent().unwrap());
}
build
}
// Symlink the header file into a predictable place. The header generated from
// path/to/mod.rs gets linked to target/cxxbridge/path/to/mod.rs.h.
pub(crate) fn symlink_header(prj: &Project, path: &Path, original: &Path) {
if let TargetDir::Unknown = prj.target_dir {
return;
}
let _ = try_symlink_header(prj, path, original);
}
fn try_symlink_header(prj: &Project, path: &Path, original: &Path) -> Result<()> {
let suffix = relative_to_parent_of_target_dir(prj, original)?;
let ref dst = include_dir(prj).join(suffix);
fs::create_dir_all(dst.parent().unwrap())?;
let _ = fs::remove_file(dst);
symlink_or_copy(path, dst)?;
let mut file_name = dst.file_name().unwrap().to_os_string();
file_name.push(".h");
let ref dst2 = dst.with_file_name(file_name);
symlink_or_copy(path, dst2)?;
Ok(())
}
fn relative_to_parent_of_target_dir(prj: &Project, original: &Path) -> Result<PathBuf> {
let mut outer = match &prj.target_dir {
TargetDir::Path(target_dir) => target_dir.parent().unwrap(),
TargetDir::Unknown => unimplemented!(), // FIXME
};
let original = canonicalize(original)?;
loop {
if let Ok(suffix) = original.strip_prefix(outer) {
return Ok(suffix.to_owned());
}
match outer.parent() {
Some(parent) => outer = parent,
None => return Ok(original.components().skip(1).collect()),
}
}
}
pub(crate) fn out_with_extension(prj: &Project, path: &Path, ext: &str) -> Result<PathBuf> {
let mut file_name = path.file_name().unwrap().to_owned();
file_name.push(ext);
let rel = relative_to_parent_of_target_dir(prj, path)?;
Ok(prj.out_dir.join(rel).with_file_name(file_name))
}
pub(crate) fn include_dir(prj: &Project) -> PathBuf {
match &prj.target_dir {
TargetDir::Path(target_dir) => target_dir.join("cxxbridge"),
TargetDir::Unknown => prj.out_dir.join("cxxbridge"),
}
}
pub(crate) fn search_parents_for_target_dir(out_dir: &Path) -> TargetDir {
let mut dir = match out_dir.canonicalize() {
Ok(dir) => dir,
Err(_) => return TargetDir::Unknown,
};
loop {
if dir.ends_with("target") {
return TargetDir::Path(dir);
}
if !dir.pop() {
return TargetDir::Unknown;
}
}
}
#[cfg(not(windows))]
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
Ok(fs::canonicalize(path)?)
}
#[cfg(windows)]
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
// Real fs::canonicalize on Windows produces UNC paths which cl.exe is
// unable to handle in includes. Use a poor approximation instead.
// https://github.com/rust-lang/rust/issues/42869
// https://github.com/alexcrichton/cc-rs/issues/169
Ok(fs::current_dir()?.join(path))
}
#[cfg(unix)]
use self::fs::symlink_file as symlink_or_copy;
#[cfg(windows)]
fn symlink_or_copy(src: &Path, dst: &Path) -> Result<()> {
// Pre-Windows 10, symlinks require admin privileges. Since Windows 10, they
// require Developer Mode. If it fails, fall back to copying the file.
if fs::symlink_file(src, dst).is_err() {
fs::copy(src, dst)?;
}
Ok(())
}
#[cfg(not(any(unix, windows)))]
use self::fs::copy as symlink_or_copy;
Only assume target dir if parent contains Cargo.toml
use crate::error::{Error, Result};
use crate::gen::fs;
use crate::Project;
use std::env;
use std::path::{Path, PathBuf};
pub(crate) enum TargetDir {
Path(PathBuf),
Unknown,
}
pub(crate) fn out_dir() -> Result<PathBuf> {
env::var_os("OUT_DIR")
.map(PathBuf::from)
.ok_or(Error::MissingOutDir)
}
pub(crate) fn cc_build(prj: &Project) -> cc::Build {
let mut build = cc::Build::new();
build.include(include_dir(prj));
if let TargetDir::Path(target_dir) = &prj.target_dir {
build.include(target_dir.parent().unwrap());
}
build
}
// Symlink the header file into a predictable place. The header generated from
// path/to/mod.rs gets linked to target/cxxbridge/path/to/mod.rs.h.
pub(crate) fn symlink_header(prj: &Project, path: &Path, original: &Path) {
if let TargetDir::Unknown = prj.target_dir {
return;
}
let _ = try_symlink_header(prj, path, original);
}
fn try_symlink_header(prj: &Project, path: &Path, original: &Path) -> Result<()> {
let suffix = relative_to_parent_of_target_dir(prj, original)?;
let ref dst = include_dir(prj).join(suffix);
fs::create_dir_all(dst.parent().unwrap())?;
let _ = fs::remove_file(dst);
symlink_or_copy(path, dst)?;
let mut file_name = dst.file_name().unwrap().to_os_string();
file_name.push(".h");
let ref dst2 = dst.with_file_name(file_name);
symlink_or_copy(path, dst2)?;
Ok(())
}
fn relative_to_parent_of_target_dir(prj: &Project, original: &Path) -> Result<PathBuf> {
let mut outer = match &prj.target_dir {
TargetDir::Path(target_dir) => target_dir.parent().unwrap(),
TargetDir::Unknown => unimplemented!(), // FIXME
};
let original = canonicalize(original)?;
loop {
if let Ok(suffix) = original.strip_prefix(outer) {
return Ok(suffix.to_owned());
}
match outer.parent() {
Some(parent) => outer = parent,
None => return Ok(original.components().skip(1).collect()),
}
}
}
pub(crate) fn out_with_extension(prj: &Project, path: &Path, ext: &str) -> Result<PathBuf> {
let mut file_name = path.file_name().unwrap().to_owned();
file_name.push(ext);
let rel = relative_to_parent_of_target_dir(prj, path)?;
Ok(prj.out_dir.join(rel).with_file_name(file_name))
}
pub(crate) fn include_dir(prj: &Project) -> PathBuf {
match &prj.target_dir {
TargetDir::Path(target_dir) => target_dir.join("cxxbridge"),
TargetDir::Unknown => prj.out_dir.join("cxxbridge"),
}
}
pub(crate) fn search_parents_for_target_dir(out_dir: &Path) -> TargetDir {
let mut dir = match out_dir.canonicalize() {
Ok(dir) => dir,
Err(_) => return TargetDir::Unknown,
};
loop {
let is_target = dir.ends_with("target");
let parent_contains_cargo_toml = dir.with_file_name("Cargo.toml").exists();
if is_target && parent_contains_cargo_toml {
return TargetDir::Path(dir);
}
if !dir.pop() {
return TargetDir::Unknown;
}
}
}
#[cfg(not(windows))]
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
Ok(fs::canonicalize(path)?)
}
#[cfg(windows)]
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
// Real fs::canonicalize on Windows produces UNC paths which cl.exe is
// unable to handle in includes. Use a poor approximation instead.
// https://github.com/rust-lang/rust/issues/42869
// https://github.com/alexcrichton/cc-rs/issues/169
Ok(fs::current_dir()?.join(path))
}
#[cfg(unix)]
use self::fs::symlink_file as symlink_or_copy;
#[cfg(windows)]
fn symlink_or_copy(src: &Path, dst: &Path) -> Result<()> {
// Pre-Windows 10, symlinks require admin privileges. Since Windows 10, they
// require Developer Mode. If it fails, fall back to copying the file.
if fs::symlink_file(src, dst).is_err() {
fs::copy(src, dst)?;
}
Ok(())
}
#[cfg(not(any(unix, windows)))]
use self::fs::copy as symlink_or_copy;
|
use std::cmp::{min, max};
use std::collections::VecDeque;
use std::net::{ToSocketAddrs, SocketAddr, UdpSocket};
use std::io::{Result, Error, ErrorKind};
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, Encodable, Decodable, ExtensionType, HEADER_SIZE};
use rand::{self, Rng};
use with_read_timeout::WithReadTimeout;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
const MAX_SYN_RETRIES: u32 = 5; // maximum connection retries
const MAX_RETRANSMISSION_RETRIES: u32 = 5; // maximum retransmission retries
#[derive(Debug)]
pub enum SocketError {
ConnectionClosed,
ConnectionReset,
ConnectionTimedOut,
InvalidAddress,
InvalidPacket,
InvalidReply,
}
impl From<SocketError> for Error {
fn from(error: SocketError) -> Error {
use self::SocketError::*;
match error {
ConnectionClosed => Error::new(ErrorKind::NotConnected,
"The socket is closed"),
ConnectionReset => Error::new(ErrorKind::ConnectionReset,
"Connection reset by remote peer"),
ConnectionTimedOut => Error::new(ErrorKind::TimedOut,
"Connection timed out"),
InvalidAddress => Error::new(ErrorKind::InvalidInput, "Invalid address"),
InvalidPacket => Error::new(ErrorKind::Other,
"Error parsing packet"),
InvalidReply => Error::new(ErrorKind::ConnectionRefused,
"The remote peer sent an invalid reply"),
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
enum SocketState {
New,
Connected,
SynSent,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// Returns the first valid address in a `ToSocketAddrs` iterator.
fn take_address<A: ToSocketAddrs>(addr: A) -> Result<SocketAddr> {
addr.to_socket_addrs()
.and_then(|mut it| it.next().ok_or(From::from(SocketError::InvalidAddress)))
}
/// A structure that represents a uTP (Micro Transport Protocol) connection between a local socket
/// and a remote socket.
///
/// The socket will be closed when the value is dropped (either explicitly or when it goes out of
/// scope).
///
/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be
/// changed by assigning the desired maximum retransmission retries to a socket's
/// `max_retransmission_retries` field. Notice that the initial congestion timeout is 500 ms and
/// doubles with each timeout.
///
/// # Examples
///
/// ```no_run
/// use utp::UtpSocket;
///
/// let mut socket = UtpSocket::bind("127.0.0.1:1234").unwrap();
///
/// let mut buf = [0; 1000];
/// let (amt, _src) = socket.recv_from(&mut buf).ok().unwrap();
///
/// let mut buf = &mut buf[..amt];
/// buf.reverse();
/// let _ = socket.send_to(buf).unwrap();
///
/// // Close the socket. You can either call `close` on the socket,
/// // explicitly drop it or just let it go out of scope.
/// socket.close();
/// ```
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: VecDeque<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the last packet removed from the incoming buffer
last_dropped: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<i64>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Difference between timestamp of the latest packet received and time of reception
their_delay: u32,
/// Start of the current minute for sampling purposes
last_rollover: i64,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
/// Maximum retransmission retries
pub max_retransmission_retries: u32,
}
impl UtpSocket {
/// Creates a new UTP from the given UDP socket and remote peer's address.
///
/// The connection identifier of the resulting socket is randomly generated.
fn from_raw_parts(s: UdpSocket, src: SocketAddr) -> UtpSocket {
// Safely generate the two sequential connection identifiers.
// This avoids a panic when the generated receiver id is the largest representable value in
// u16 and one increments it to yield the corresponding sender id.
let (receiver_id, sender_id) = || -> (u16, u16) {
let mut rng = rand::thread_rng();
loop {
let id = rng.gen::<u16>();
if id.checked_add(1).is_some() { return (id, id + 1) }
}
}();
UtpSocket {
socket: s,
connected_to: src,
receiver_connection_id: receiver_id,
sender_connection_id: sender_id,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: VecDeque::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
last_dropped: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
their_delay: 0,
last_rollover: 0,
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
max_retransmission_retries: MAX_RETRANSMISSION_RETRIES,
}
}
/// Creates a new UTP socket from the given address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpSocket> {
take_address(addr).and_then(|a| UdpSocket::bind(a).map(|s| UtpSocket::from_raw_parts(s, a)))
}
/// Returns the socket address that this socket was created from.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
/// Opens a connection to a remote host by hostname or IP address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn connect<A: ToSocketAddrs>(other: A) -> Result<UtpSocket> {
let addr = try!(take_address(other));
let my_addr = match addr {
SocketAddr::V4(_) => "0.0.0.0:0",
SocketAddr::V6(_) => ":::0",
};
let mut socket = try!(UtpSocket::bind(my_addr));
socket.connected_to = addr;
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(socket.receiver_connection_id);
packet.set_seq_nr(socket.seq_nr);
let mut len = 0;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = socket.congestion_timeout as i64;
for _ in 0..MAX_SYN_RETRIES {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", socket.connected_to);
try!(socket.socket.send_to(&packet.to_bytes()[..], socket.connected_to));
socket.state = SocketState::SynSent;
debug!("sent {:?}", packet);
// Validate response
match socket.socket.recv_timeout(&mut buf, syn_timeout) {
Ok((read, src)) => { socket.connected_to = src; len = read; break; },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
let addr = socket.connected_to;
let packet = try!(Packet::from_bytes(&buf[..len]).or(Err(SocketError::InvalidPacket)));
debug!("received {:?}", packet);
try!(socket.handle_packet(&packet, addr));
debug!("connected to: {}", socket.connected_to);
return Ok(socket);
}
/// Gracefully closes connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
pub fn close(&mut self) -> Result<()> {
// Nothing to do if the socket's already closed or not connected
if self.state == SocketState::Closed ||
self.state == SocketState::New ||
self.state == SocketState::SynSent {
return Ok(());
}
// Flush unsent and unacknowledged packets
try!(self.flush());
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("sent {:?}", packet);
self.state = SocketState::FinSent;
// Receive JAKE
let mut buf = [0; BUF_SIZE];
while self.state != SocketState::Closed {
try!(self.recv(&mut buf));
}
Ok(())
}
/// Receives data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns 0 bytes read after receiving a FIN packet when the remaining
/// inflight packets are consumed.
pub fn recv_from(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let read = self.flush_incoming_buffer(buf);
if read > 0 {
return Ok((read, self.connected_to));
} else {
// If the socket received a reset packet and all data has been flushed, then it can't
// receive anything else
if self.state == SocketState::ResetReceived {
return Err(Error::from(SocketError::ConnectionReset));
}
loop {
// A closed socket with no pending data can only "read" 0 new bytes.
if self.state == SocketState::Closed {
return Ok((0, self.connected_to));
}
match self.recv(buf) {
Ok((0, _src)) => continue,
Ok(x) => return Ok(x),
Err(e) => return Err(e)
}
}
}
}
fn recv(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
let now = now_microseconds();
let (mut read, mut src);
let mut retries = 0;
// Try to receive a packet and handle timeouts
loop {
// Abort loop if the current try exceeds the maximum number of retransmission retries.
if retries >= self.max_retransmission_retries {
self.state = SocketState::Closed;
return Err(Error::from(SocketError::ConnectionTimedOut));
}
let timeout = if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.congestion_timeout as i64
} else { 0 };
match self.socket.recv_timeout(&mut b, timeout) {
Ok((r, s)) => { read = r; src = s; break },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("recv_from timed out");
try!(self.handle_receive_timeout());
},
Err(e) => return Err(e),
};
let elapsed = now_microseconds() - now;
debug!("now_microseconds() - now = {} ms", elapsed/1000);
retries += 1;
}
// Decode received data into a packet
let packet = match Packet::from_bytes(&b[..read]) {
Ok(packet) => packet,
Err(e) => {
debug!("{}", e);
debug!("Ignoring invalid packet");
return Ok((0, self.connected_to));
}
};
debug!("received {:?}", packet);
// Process packet, including sending a reply if necessary
if let Some(mut pkt) = try!(self.handle_packet(&packet, src)) {
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(&pkt.to_bytes()[..], src));
debug!("sent {:?}", pkt);
}
// Insert data packet into the incoming buffer if it isn't a duplicate of a previously
// discarded packet
if packet.get_type() == PacketType::Data &&
packet.seq_nr().wrapping_sub(self.last_dropped) > 0 {
self.insert_into_buffer(packet);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn handle_receive_timeout(&mut self) -> Result<()> {
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
// There are three possible cases here:
//
// - If the socket is sending and waiting for acknowledgements (the send window is
// not empty), resend the first unacknowledged packet;
//
// - If the socket is not sending and it hasn't sent a FIN yet, then it's waiting
// for incoming packets: send a fast resend request;
//
// - If the socket sent a FIN previously, resend it.
debug!("self.send_window: {:?}", self.send_window.iter()
.map(Packet::seq_nr).collect::<Vec<u16>>());
if self.send_window.is_empty() {
// The socket is trying to close, all sent packets were acknowledged, and it has
// already sent a FIN: resend it.
if self.state == SocketState::FinSent {
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent FIN: {:?}", packet);
} else {
// The socket is waiting for incoming packets but the remote peer is silent:
// send a fast resend request.
debug!("sending fast resend request");
self.send_fast_resend_request();
}
} else {
// The socket is sending data packets but there is no reply from the remote
// peer: resend the first unacknowledged packet with the current timestamp.
let mut packet = &mut self.send_window[0];
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent {:?}", packet);
}
Ok(())
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Removes a packet in the incoming buffer and updates the current acknowledgement number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
self.last_dropped = self.ack_nr;
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
fn unsafe_copy(src: &[u8], dst: &mut [u8]) -> usize {
let max_len = min(src.len(), dst.len());
unsafe {
use std::ptr::copy;
copy(src.as_ptr(), dst.as_mut_ptr(), max_len);
}
return max_len;
}
// Return pending data from a partially read packet
if !self.pending_data.is_empty() {
let flushed = unsafe_copy(&self.pending_data[..], buf);
if flushed == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
} else {
self.pending_data = self.pending_data[flushed..].to_vec();
}
return flushed;
}
if !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let flushed = unsafe_copy(&self.incoming_buffer[0].payload[..], buf);
if flushed == self.incoming_buffer[0].payload.len() {
self.advance_incoming_buffer();
} else {
self.pending_data = self.incoming_buffer[0].payload[flushed..].to_vec();
}
return flushed;
}
return 0;
}
/// Sends data on the socket to the remote peer. On success, returns the number of bytes
/// written.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
pub fn send_to(&mut self, buf: &[u8]) -> Result<usize> {
if self.state == SocketState::Closed {
return Err(Error::from(SocketError::ConnectionClosed));
}
let total_length = buf.len();
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::with_payload(chunk);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
// `OverflowingOps` is marked unstable, so we can't use `overflowing_add` here
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Send every packet in the queue
try!(self.send());
Ok(total_length)
}
/// Consumes acknowledgements for every pending packet.
pub fn flush(&mut self) -> Result<()> {
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
debug!("packets in send window: {}", self.send_window.len());
try!(self.recv(&mut buf));
}
Ok(())
}
/// Sends every packet in the unsent packet queue.
fn send(&mut self) -> Result<()> {
while let Some(mut packet) = self.unsent_queue.pop_front() {
try!(self.send_packet(&mut packet));
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send one packet.
#[inline(always)]
fn send_packet(&mut self, packet: &mut Packet) -> Result<()> {
let dst = self.connected_to;
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
let now = now_microseconds();
// Wait until enough inflight packets are acknowledged for rate control purposes, but don't
// wait more than 500 ms before sending the packet.
while self.curr_window >= max_inflight && now_microseconds() - now < 500_000 {
debug!("self.curr_window: {}", self.curr_window);
debug!("max_inflight: {}", max_inflight);
debug!("self.duplicate_ack_count: {}", self.duplicate_ack_count);
debug!("now_microseconds() - now = {}", now_microseconds() - now);
let mut buf = [0; BUF_SIZE];
try!(self.recv(&mut buf));
}
debug!("out: now_microseconds() - now = {}", now_microseconds() - now);
// Check if it still makes sense to send packet, as we might be trying to resend a lost
// packet acknowledged in the receive loop above.
// If there were no wrapping around of sequence numbers, we'd simply check if the packet's
// sequence number is greater than `last_acked`.
let distance_a = packet.seq_nr().wrapping_sub(self.last_acked);
let distance_b = self.last_acked.wrapping_sub(packet.seq_nr());
if distance_a > distance_b {
debug!("Packet already acknowledged, skipping...");
return Ok(());
}
packet.set_timestamp_microseconds(now_microseconds());
packet.set_timestamp_difference_microseconds(self.their_delay);
try!(self.socket.send_to(&packet.to_bytes()[..], dst));
debug!("sent {:?}", packet);
Ok(())
}
// Insert a new sample in the base delay list.
//
// The base delay list contains at most `BASE_HISTORY` samples, each sample is the minimum
// measured over a period of a minute.
fn update_base_delay(&mut self, base_delay: i64, now: i64) {
let minute_in_microseconds = 60 * 10i64.pow(6);
if self.base_delays.is_empty() || now - self.last_rollover > minute_in_microseconds {
// Update last rollover
self.last_rollover = now;
// Drop the oldest sample, if need be
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_front();
}
// Insert new sample
self.base_delays.push_back(base_delay);
} else {
// Replace sample for the current minute if the delay is lower
let last_idx = self.base_delays.len() - 1;
if base_delay < self.base_delays[last_idx] {
self.base_delays[last_idx] = base_delay;
}
}
}
/// Inserts a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64,
MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculates the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculates the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
self.base_delays.iter().map(|x| *x).min().unwrap_or(0)
}
/// Builds the selective acknowledgment extension data for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|&pkt| pkt.seq_nr() > self.ack_nr);
let mut sack = Vec::new();
for packet in stashed {
let diff = packet.seq_nr() - self.ack_nr - 2;
let byte = (diff / 8) as usize;
let bit = (diff % 8) as usize;
// Make sure the amount of elements in the SACK vector is a
// multiple of 4 and enough to represent the lost packets
while byte >= sack.len() || sack.len() % 4 != 0 {
sack.push(0u8);
}
sack[byte] |= 1 << bit;
}
return sack;
}
/// Sends a fast resend request to the remote peer.
///
/// A fast resend request consists of sending three STATE packets (acknowledging the last
/// received packet) in quick succession.
fn send_fast_resend_request(&self) {
for _ in 0..3 {
let mut packet = Packet::new();
packet.set_type(PacketType::State);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = 0;
packet.set_timestamp_microseconds(self_t_micro);
packet.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
let _ = self.socket.send_to(&packet.to_bytes()[..], self.connected_to);
}
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
debug!("---> resend_lost_packet({}) <---", lost_packet_nr);
match self.send_window.iter().position(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(position) => {
debug!("self.send_window.len(): {}", self.send_window.len());
debug!("position: {}", position);
let mut packet = self.send_window[position].clone();
// FIXME: Unchecked result
let _ = self.send_packet(&mut packet);
// We intentionally don't increase `curr_window` because otherwise a packet's length
// would be counted more than once
}
}
debug!("---> END resend_lost_packet <---");
}
/// Forgets sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
// The reason I'm not removing the first element in a loop while its sequence number is
// smaller than `last_acked` is because of wrapping sequence numbers, which would create the
// sequence [..., 65534, 65535, 0, 1, ...]. If `last_acked` is smaller than the first
// packet's sequence number because of wraparound (for instance, 1), no packets would be
// removed, as the condition `seq_nr < last_acked` would fail immediately.
//
// On the other hand, I can't keep removing the first packet in a loop until its sequence
// number matches `last_acked` because it might never match, and in that case no packets
// should be removed.
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in (0..position + 1) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handles an incoming packet, updating socket state accordingly.
///
/// Returns the appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> Result<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != PacketType::Syn &&
self.state != SocketState::SynSent &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
// Update remote window size
self.remote_wnd_size = packet.wnd_size();
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
// Update remote peer's delay between them sending the packet and us receiving it
let now = now_microseconds();
self.their_delay = if now > packet.timestamp_microseconds() {
now - packet.timestamp_microseconds()
} else {
packet.timestamp_microseconds() - now
};
debug!("self.their_delay: {}", self.their_delay);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
self.last_dropped = self.ack_nr;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(_, PacketType::Syn) => {
Ok(Some(self.prepare_reply(packet, PacketType::Reset)))
}
(SocketState::SynSent, PacketType::State) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(Error::from(SocketError::InvalidReply))
}
(SocketState::Connected, PacketType::Data) |
(SocketState::FinSent, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) |
(SocketState::FinSent, PacketType::Fin) => {
if packet.ack_nr() < self.seq_nr {
debug!("FIN received but there are missing acknowledgments for sent packets");
}
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
// Give up, the remote peer might not care about our missing packets
self.state = SocketState::Closed;
Ok(Some(reply))
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
} else {
self.handle_state_packet(packet);
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(Error::from(SocketError::ConnectionReset))
},
(state, ty) => {
let message = format!("Unimplemented handling for ({:?},{:?})", state, ty);
debug!("{}", message);
Err(Error::new(ErrorKind::Other, message))
}
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
// If a FIN was previously sent, reply with a FIN packet acknowledging the received packet.
let packet_type = if self.state == SocketState::FinSent {
PacketType::Fin
} else {
PacketType::State
};
let mut reply = self.prepare_reply(packet, packet_type);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay - min_base_delay;
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
/// Calculates the new congestion window size, increasing it or decreasing it.
///
/// This is the core of uTP, the [LEDBAT][ledbat_rfc] congestion algorithm. It depends on
/// estimating the queuing delay between the two peers, and adjusting the congestion window
/// accordingly.
///
/// `off_target` is a normalized value representing the difference between the current queuing
/// delay and a fixed target delay (`TARGET`). `off_target` ranges between -1.0 and 1.0. A
/// positive value makes the congestion window increase, while a negative value makes the
/// congestion window decrease.
///
/// `bytes_newly_acked` is the number of bytes acknowledged by an inbound `State` packet. It may
/// be the size of the packet explicitly acknowledged by the inbound packet (i.e., with sequence
/// number equal to the inbound packet's acknowledgement number), or every packet implicitly
/// acknowledged (every packet with sequence number between the previous inbound `State`
/// packet's acknowledgement number and the current inbound `State` packet's acknowledgement
/// number).
///
///[ledbat_rfc]: https://tools.ietf.org/html/rfc6817
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
let flightsize = self.curr_window;
let cwnd_increase = GAIN * off_target * bytes_newly_acked as f64 * MSS as f64;
let cwnd_increase = cwnd_increase / self.cwnd as f64;
debug!("cwnd_increase: {}", cwnd_increase);
self.cwnd = (self.cwnd as f64 + cwnd_increase) as u32;
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update congestion window size
if let Some(index) = self.send_window.iter().position(|p| packet.ack_nr() == p.seq_nr()) {
// Calculate the sum of the size of every packet implicitly and explictly acknowledged
// by the inbout packet (i.e., every packet whose sequence number precedes the inbound
// packet's acknowledgement number, plus the packet whose sequence number matches)
let bytes_newly_acked = self.send_window.iter()
.take(index + 1)
.fold(0, |acc, p| acc + p.len());
// Update base and current delay
let now = now_microseconds() as i64;
let our_delay = now - self.send_window[index].timestamp_microseconds() as i64;
debug!("our_delay: {}", our_delay);
self.update_base_delay(our_delay, now);
self.update_current_delay(our_delay, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
self.update_congestion_window(off_target, bytes_newly_acked as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
}
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if extension.iter().count_ones() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
for seq_nr in extension.iter().enumerate()
.filter(|&(_idx, received)| !received)
.map(|(idx, _received)| packet.ack_nr() + 2 + idx as u16) {
if self.send_window.last().map(|p| seq_nr < p.seq_nr()).unwrap_or(false) {
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Three duplicate ACKs mean a fast resend request. Resend the first unacknowledged packet
// if the incoming packet doesn't have a SACK extension. If it does, the lost packets were
// already resent.
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 &&
!packet.extensions.iter().any(|ext| ext.get_type() == ExtensionType::SelectiveAck) {
self.resend_lost_packet(packet.ack_nr() + 1);
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Success, advance send window
self.advance_send_window();
}
/// Inserts a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
// Immediately push to the end if the packet's sequence number comes after the last
// packet's.
if self.incoming_buffer.last().map(|p| packet.seq_nr() > p.seq_nr()).unwrap_or(false) {
self.incoming_buffer.push(packet);
} else {
// Find index following the most recent packet before the one we wish to insert
let i = self.incoming_buffer.iter().filter(|p| p.seq_nr() < packet.seq_nr()).count();
// Remove packet if it's a duplicate
if self.incoming_buffer.get(i).map(|p| p.seq_nr() == packet.seq_nr()).unwrap_or(false) {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
let _ = self.close();
}
}
/// A structure representing a socket server.
///
/// # Examples
///
/// ```no_run
/// use utp::{UtpListener, UtpSocket};
/// use std::thread;
///
/// fn handle_client(socket: UtpSocket) {
/// // ...
/// }
///
/// fn main() {
/// // Create a listener
/// let addr = "127.0.0.1:8080";
/// let listener = UtpListener::bind(addr).unwrap();
///
/// for connection in listener.incoming() {
/// // Spawn a new handler for each new connection
/// match connection {
/// Ok((socket, _src)) => { thread::spawn(move || { handle_client(socket) }); },
/// _ => ()
/// }
/// }
/// }
/// ```
pub struct UtpListener {
/// The public facing UDP socket
socket: UdpSocket,
}
impl UtpListener {
/// Creates a new `UtpListener` bound to a specific address.
///
/// The resulting listener is ready for accepting connections.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpListener> {
UdpSocket::bind(addr).and_then(|s| Ok(UtpListener { socket: s}))
}
/// Accepts a new incoming connection from this listener.
///
/// This function will block the caller until a new uTP connection is established. When
/// established, the corresponding `UtpSocket` and the peer's remote address will be returned.
///
/// Notice that the resulting `UtpSocket` is bound to a different local port than the public
/// listening port (which `UtpListener` holds). This may confuse the remote peer!
pub fn accept(&self) -> Result<(UtpSocket, SocketAddr)> {
let mut buf = [0; BUF_SIZE];
match self.socket.recv_from(&mut buf) {
Ok((nread, src)) => {
let packet = try!(Packet::from_bytes(&buf[..nread])
.or(Err(SocketError::InvalidPacket)));
// Ignore non-SYN packets
if packet.get_type() != PacketType::Syn {
return Err(Error::from(SocketError::InvalidPacket));
}
// The address of the new socket will depend on the type of the listener.
let inner_socket = self.socket.local_addr().and_then(|addr| match addr {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0"),
SocketAddr::V6(_) => UdpSocket::bind(":::0"),
});
let mut socket = try!(inner_socket.map(|s| UtpSocket::from_raw_parts(s, src)));
// Establish connection with remote peer
match socket.handle_packet(&packet, src) {
Ok(Some(reply)) => { try!(socket.socket.send_to(&reply.to_bytes()[..], src)) },
Ok(None) => return Err(Error::from(SocketError::InvalidPacket)),
Err(e) => return Err(e)
};
Ok((socket, src))
},
Err(e) => Err(e)
}
}
/// Returns an iterator over the connections being received by this listener.
///
/// The returned iterator will never return `None`.
pub fn incoming(&self) -> Incoming {
Incoming { listener: self }
}
/// Returns the local socket address of this listener.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
}
pub struct Incoming<'a> { listener: &'a UtpListener }
impl<'a> Iterator for Incoming<'a> {
type Item = Result<(UtpSocket, SocketAddr)>;
fn next(&mut self) -> Option<Result<(UtpSocket, SocketAddr)>> {
Some(self.listener.accept())
}
}
#[cfg(test)]
mod test {
use std::thread;
use std::net::ToSocketAddrs;
use std::io::ErrorKind;
use super::{UtpSocket, UtpListener, SocketState, BUF_SIZE, take_address};
use packet::{Packet, PacketType, Encodable, Decodable};
use util::now_microseconds;
use rand;
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{:?}", e) })
}
fn next_test_port() -> u16 {
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
const BASE_PORT: u16 = 9600;
BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
fn next_test_ip4<'a>() -> (&'a str, u16) {
("127.0.0.1", next_test_port())
}
fn next_test_ip6<'a>() -> (&'a str, u16) {
("::1", next_test_port())
}
#[test]
fn test_socket_ipv4() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_socket_ipv6() {
let server_addr = next_test_ip6();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert!(client.close().is_ok());
});
// Make the server listen for incoming connections until the end of the input
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Closed);
// Trying to receive again returns Ok(0) [EndOfFile]
match server.recv_from(&mut buf) {
Ok((0, _src)) => {},
e => panic!("Expected Ok(0), got {:?}", e),
}
assert_eq!(server.state, SocketState::Closed);
}
#[test]
fn test_sendto_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
iotry!(client.close());
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an error
match server.send_to(&buf) {
Err(ref e) if e.kind() == ErrorKind::NotConnected => (),
v => panic!("expected {:?}, got {:?}", ErrorKind::NotConnected, v),
}
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let server_addr = next_test_ip4();
let (tx, rx) = channel();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert!(client.close().is_ok());
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1, 2, 3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4, 5, 6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_socket_unordered_packets() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
let s = client.socket.try_clone().ok().expect("Error cloning internal UDP socket");
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>()[..].chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
client.curr_window += packet.len() as u32;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(&window[3].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[2].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[1].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[0].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[4].to_bytes()[..], server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0; BUF_SIZE];
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.state, SocketState::Closed);
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_response_to_triple_ack() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&d[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv(&mut buf));
// Receive data
let data_packet = match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => iotry!(Packet::from_bytes(&buf[..read])),
Err(e) => panic!("{}", e),
};
assert_eq!(data_packet.get_type(), PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to));
}
// Receive data again and check that it's the same we reported as missing
let client_addr = server.connected_to;
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..read]));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(&response.to_bytes()[..], server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(&d[..]));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
server.recv(&mut buf).unwrap();
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1, 2, 3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(client.socket.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
iotry!(server.recv(&mut buf));
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1, 2, 3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
// #[test]
// #[ignore]
// fn test_selective_ack_response() {
// let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
// const LEN: usize = 1024 * 10;
// let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
// let to_send = data.clone();
// // Client
// thread::spawn(move || {
// let client = iotry!(UtpSocket::bind(client_addr));
// let mut client = iotry!(UtpSocket::connect(server_addr));
// client.congestion_timeout = 50;
// iotry!(client.send_to(&to_send[..]));
// iotry!(client.close());
// });
// // Server
// let mut server = iotry!(UtpSocket::bind(server_addr));
// let mut buf = [0; BUF_SIZE];
// // Connect
// iotry!(server.recv_from(&mut buf));
// // Discard packets
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// // Generate SACK
// let mut packet = Packet::new();
// packet.set_seq_nr(server.seq_nr);
// packet.set_ack_nr(server.ack_nr - 1);
// packet.set_connection_id(server.sender_connection_id);
// packet.set_timestamp_microseconds(now_microseconds());
// packet.set_type(PacketType::State);
// packet.set_sack(vec!(12, 0, 0, 0));
// // Send SACK
// iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to.clone()));
// // Expect to receive "missing" packets
// let mut received: Vec<u8> = vec!();
// loop {
// match server.recv_from(&mut buf) {
// Ok((0, _src)) => break,
// Ok((len, _src)) => received.extend(buf[..len].to_vec()),
// Err(e) => panic!("{:?}", e)
// }
// }
// assert!(!received.is_empty());
// assert_eq!(received.len(), data.len());
// assert_eq!(received, data);
// }
#[test]
fn test_correct_packet_loss() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send[..].chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(&packet.to_bytes()[..], dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => break,
Ok((len, _src)) => read.extend(small_buffer[..len].to_vec()),
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(&to_send[..]));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_drop_unused_socket() {
let server_addr = next_test_ip4();
let server = iotry!(UtpSocket::bind(server_addr));
// Explicitly dropping socket. This test should not hang.
drop(server);
}
#[test]
fn test_invalid_packet_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => { iotry!(server.send_to(&[], client_addr)); },
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::Other => (), // OK
Err(e) => panic!("Expected ErrorKind::Other, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receive_unexpected_reply_type_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => {
iotry!(server.send_to(&packet.to_bytes()[..], client_addr));
},
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::ConnectionRefused => (), // OK
Err(e) => panic!("Expected ErrorKind::ConnectionRefused, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receiving_syn_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(e) => panic!("{:?}", e)
}
}
});
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let reply = Packet::from_bytes(&buf[..len]).ok().unwrap();
assert_eq!(reply.get_type(), PacketType::Reset);
}
Err(e) => panic!("{:?}", e)
}
}
#[test]
fn test_receiving_reset_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Reset);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((_len, _src)) => (),
Err(e) => panic!("{:?}", e)
}
});
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(ref e) if e.kind() == ErrorKind::ConnectionReset => return,
Err(e) => panic!("{:?}", e)
}
}
panic!("Should have received Reset");
}
#[test]
fn test_premature_fin() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Accept connection
iotry!(server.recv(&mut buf));
// Send FIN without acknowledging packets received
let mut packet = Packet::new();
packet.set_connection_id(server.sender_connection_id);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
iotry!(server.socket.send_to(&packet.to_bytes()[..], client_addr));
// Receive until end
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_base_delay_calculation() {
let minute_in_microseconds = 60 * 10i64.pow(6);
let samples = vec![(0, 10), (1, 8), (2, 12), (3, 7),
(minute_in_microseconds + 1, 11),
(minute_in_microseconds + 2, 19),
(minute_in_microseconds + 3, 9)];
let addr = next_test_ip4();
let mut socket = UtpSocket::bind(addr).unwrap();
for (timestamp, delay) in samples{
socket.update_base_delay(delay, timestamp + delay);
}
let expected = vec![7, 9];
let actual = socket.base_delays.iter().map(|&x| x).collect::<Vec<_>>();
assert_eq!(expected, actual);
assert_eq!(socket.min_base_delay(), 7);
}
#[test]
fn test_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let socket = UtpSocket::bind(addr).unwrap();
assert!(socket.local_addr().is_ok());
assert_eq!(socket.local_addr().unwrap(), addr);
}
#[test]
fn test_listener_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let listener = UtpListener::bind(addr).unwrap();
assert!(listener.local_addr().is_ok());
assert_eq!(listener.local_addr().unwrap(), addr);
}
#[test]
fn test_take_address() {
// Expected succcesses
assert!(take_address(("0.0.0.0:0")).is_ok());
assert!(take_address((":::0")).is_ok());
assert!(take_address(("0.0.0.0", 0)).is_ok());
assert!(take_address(("::", 0)).is_ok());
assert!(take_address(("1.2.3.4", 5)).is_ok());
// Expected failures
assert!(take_address("999.0.0.0:0").is_err());
assert!(take_address(("1.2.3.4:70000")).is_err());
assert!(take_address("").is_err());
assert!(take_address("this is not an address").is_err());
assert!(take_address("no.dns.resolution.com").is_err());
}
// Test reaction to connection loss when sending data packets
#[test]
fn test_connection_loss_data() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Data),
Err(e) => panic!("{}", e),
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
iotry!(server.send_to(&[0]));
// Try to receive ACKs, time out too many times on flush, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when sending FIN
#[test]
fn test_connection_loss_fin() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Fin),
Err(e) => panic!("{}", e),
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Send FIN, time out too many times, and fail with `TimedOut`
match server.close() {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when waiting for data packets
#[test]
fn test_connection_loss_waiting() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Try to receive data, time out too many times, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
}
Improve tests.
use std::cmp::{min, max};
use std::collections::VecDeque;
use std::net::{ToSocketAddrs, SocketAddr, UdpSocket};
use std::io::{Result, Error, ErrorKind};
use util::{now_microseconds, ewma};
use packet::{Packet, PacketType, Encodable, Decodable, ExtensionType, HEADER_SIZE};
use rand::{self, Rng};
use with_read_timeout::WithReadTimeout;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
const BUF_SIZE: usize = 1500;
const GAIN: f64 = 1.0;
const ALLOWED_INCREASE: u32 = 1;
const TARGET: i64 = 100_000; // 100 milliseconds
const MSS: u32 = 1400;
const MIN_CWND: u32 = 2;
const INIT_CWND: u32 = 2;
const INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second
const MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms
const MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute
const BASE_HISTORY: usize = 10; // base delays history size
const MAX_SYN_RETRIES: u32 = 5; // maximum connection retries
const MAX_RETRANSMISSION_RETRIES: u32 = 5; // maximum retransmission retries
#[derive(Debug)]
pub enum SocketError {
ConnectionClosed,
ConnectionReset,
ConnectionTimedOut,
InvalidAddress,
InvalidPacket,
InvalidReply,
}
impl From<SocketError> for Error {
fn from(error: SocketError) -> Error {
use self::SocketError::*;
match error {
ConnectionClosed => Error::new(ErrorKind::NotConnected,
"The socket is closed"),
ConnectionReset => Error::new(ErrorKind::ConnectionReset,
"Connection reset by remote peer"),
ConnectionTimedOut => Error::new(ErrorKind::TimedOut,
"Connection timed out"),
InvalidAddress => Error::new(ErrorKind::InvalidInput, "Invalid address"),
InvalidPacket => Error::new(ErrorKind::Other,
"Error parsing packet"),
InvalidReply => Error::new(ErrorKind::ConnectionRefused,
"The remote peer sent an invalid reply"),
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
enum SocketState {
New,
Connected,
SynSent,
FinSent,
ResetReceived,
Closed,
}
type TimestampSender = i64;
type TimestampReceived = i64;
struct DelayDifferenceSample {
received_at: TimestampReceived,
difference: TimestampSender,
}
/// Returns the first valid address in a `ToSocketAddrs` iterator.
fn take_address<A: ToSocketAddrs>(addr: A) -> Result<SocketAddr> {
addr.to_socket_addrs()
.and_then(|mut it| it.next().ok_or(From::from(SocketError::InvalidAddress)))
}
/// A structure that represents a uTP (Micro Transport Protocol) connection between a local socket
/// and a remote socket.
///
/// The socket will be closed when the value is dropped (either explicitly or when it goes out of
/// scope).
///
/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be
/// changed by assigning the desired maximum retransmission retries to a socket's
/// `max_retransmission_retries` field. Notice that the initial congestion timeout is 500 ms and
/// doubles with each timeout.
///
/// # Examples
///
/// ```no_run
/// use utp::UtpSocket;
///
/// let mut socket = UtpSocket::bind("127.0.0.1:1234").unwrap();
///
/// let mut buf = [0; 1000];
/// let (amt, _src) = socket.recv_from(&mut buf).ok().unwrap();
///
/// let mut buf = &mut buf[..amt];
/// buf.reverse();
/// let _ = socket.send_to(buf).unwrap();
///
/// // Close the socket. You can either call `close` on the socket,
/// // explicitly drop it or just let it go out of scope.
/// socket.close();
/// ```
pub struct UtpSocket {
/// The wrapped UDP socket
socket: UdpSocket,
/// Remote peer
connected_to: SocketAddr,
/// Sender connection identifier
sender_connection_id: u16,
/// Receiver connection identifier
receiver_connection_id: u16,
/// Sequence number for the next packet
seq_nr: u16,
/// Sequence number of the latest acknowledged packet sent by the remote peer
ack_nr: u16,
/// Socket state
state: SocketState,
/// Received but not acknowledged packets
incoming_buffer: Vec<Packet>,
/// Sent but not yet acknowledged packets
send_window: Vec<Packet>,
/// Packets not yet sent
unsent_queue: VecDeque<Packet>,
/// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`
duplicate_ack_count: u32,
/// Sequence number of the latest packet the remote peer acknowledged
last_acked: u16,
/// Timestamp of the latest packet the remote peer acknowledged
last_acked_timestamp: u32,
/// Sequence number of the last packet removed from the incoming buffer
last_dropped: u16,
/// Round-trip time to remote peer
rtt: i32,
/// Variance of the round-trip time to the remote peer
rtt_variance: i32,
/// Data from the latest packet not yet returned in `recv_from`
pending_data: Vec<u8>,
/// Bytes in flight
curr_window: u32,
/// Window size of the remote peer
remote_wnd_size: u32,
/// Rolling window of packet delay to remote peer
base_delays: VecDeque<i64>,
/// Rolling window of the difference between sending a packet and receiving its acknowledgement
current_delays: Vec<DelayDifferenceSample>,
/// Difference between timestamp of the latest packet received and time of reception
their_delay: u32,
/// Start of the current minute for sampling purposes
last_rollover: i64,
/// Current congestion timeout in milliseconds
congestion_timeout: u64,
/// Congestion window in bytes
cwnd: u32,
/// Maximum retransmission retries
pub max_retransmission_retries: u32,
}
impl UtpSocket {
/// Creates a new UTP from the given UDP socket and remote peer's address.
///
/// The connection identifier of the resulting socket is randomly generated.
fn from_raw_parts(s: UdpSocket, src: SocketAddr) -> UtpSocket {
// Safely generate the two sequential connection identifiers.
// This avoids a panic when the generated receiver id is the largest representable value in
// u16 and one increments it to yield the corresponding sender id.
let (receiver_id, sender_id) = || -> (u16, u16) {
let mut rng = rand::thread_rng();
loop {
let id = rng.gen::<u16>();
if id.checked_add(1).is_some() { return (id, id + 1) }
}
}();
UtpSocket {
socket: s,
connected_to: src,
receiver_connection_id: receiver_id,
sender_connection_id: sender_id,
seq_nr: 1,
ack_nr: 0,
state: SocketState::New,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: VecDeque::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
last_dropped: 0,
rtt: 0,
rtt_variance: 0,
pending_data: Vec::new(),
curr_window: 0,
remote_wnd_size: 0,
current_delays: Vec::new(),
base_delays: VecDeque::with_capacity(BASE_HISTORY),
their_delay: 0,
last_rollover: 0,
congestion_timeout: INITIAL_CONGESTION_TIMEOUT,
cwnd: INIT_CWND * MSS,
max_retransmission_retries: MAX_RETRANSMISSION_RETRIES,
}
}
/// Creates a new UTP socket from the given address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpSocket> {
take_address(addr).and_then(|a| UdpSocket::bind(a).map(|s| UtpSocket::from_raw_parts(s, a)))
}
/// Returns the socket address that this socket was created from.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
/// Opens a connection to a remote host by hostname or IP address.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn connect<A: ToSocketAddrs>(other: A) -> Result<UtpSocket> {
let addr = try!(take_address(other));
let my_addr = match addr {
SocketAddr::V4(_) => "0.0.0.0:0",
SocketAddr::V6(_) => ":::0",
};
let mut socket = try!(UtpSocket::bind(my_addr));
socket.connected_to = addr;
let mut packet = Packet::new();
packet.set_type(PacketType::Syn);
packet.set_connection_id(socket.receiver_connection_id);
packet.set_seq_nr(socket.seq_nr);
let mut len = 0;
let mut buf = [0; BUF_SIZE];
let mut syn_timeout = socket.congestion_timeout as i64;
for _ in 0..MAX_SYN_RETRIES {
packet.set_timestamp_microseconds(now_microseconds());
// Send packet
debug!("Connecting to {}", socket.connected_to);
try!(socket.socket.send_to(&packet.to_bytes()[..], socket.connected_to));
socket.state = SocketState::SynSent;
debug!("sent {:?}", packet);
// Validate response
match socket.socket.recv_timeout(&mut buf, syn_timeout) {
Ok((read, src)) => { socket.connected_to = src; len = read; break; },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("Timed out, retrying");
syn_timeout *= 2;
continue;
},
Err(e) => return Err(e),
};
}
let addr = socket.connected_to;
let packet = try!(Packet::from_bytes(&buf[..len]).or(Err(SocketError::InvalidPacket)));
debug!("received {:?}", packet);
try!(socket.handle_packet(&packet, addr));
debug!("connected to: {}", socket.connected_to);
return Ok(socket);
}
/// Gracefully closes connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
pub fn close(&mut self) -> Result<()> {
// Nothing to do if the socket's already closed or not connected
if self.state == SocketState::Closed ||
self.state == SocketState::New ||
self.state == SocketState::SynSent {
return Ok(());
}
// Flush unsent and unacknowledged packets
try!(self.flush());
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("sent {:?}", packet);
self.state = SocketState::FinSent;
// Receive JAKE
let mut buf = [0; BUF_SIZE];
while self.state != SocketState::Closed {
try!(self.recv(&mut buf));
}
Ok(())
}
/// Receives data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns 0 bytes read after receiving a FIN packet when the remaining
/// inflight packets are consumed.
pub fn recv_from(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let read = self.flush_incoming_buffer(buf);
if read > 0 {
return Ok((read, self.connected_to));
} else {
// If the socket received a reset packet and all data has been flushed, then it can't
// receive anything else
if self.state == SocketState::ResetReceived {
return Err(Error::from(SocketError::ConnectionReset));
}
loop {
// A closed socket with no pending data can only "read" 0 new bytes.
if self.state == SocketState::Closed {
return Ok((0, self.connected_to));
}
match self.recv(buf) {
Ok((0, _src)) => continue,
Ok(x) => return Ok(x),
Err(e) => return Err(e)
}
}
}
}
fn recv(&mut self, buf: &mut[u8]) -> Result<(usize, SocketAddr)> {
let mut b = [0; BUF_SIZE + HEADER_SIZE];
let now = now_microseconds();
let (mut read, mut src);
let mut retries = 0;
// Try to receive a packet and handle timeouts
loop {
// Abort loop if the current try exceeds the maximum number of retransmission retries.
if retries >= self.max_retransmission_retries {
self.state = SocketState::Closed;
return Err(Error::from(SocketError::ConnectionTimedOut));
}
let timeout = if self.state != SocketState::New {
debug!("setting read timeout of {} ms", self.congestion_timeout);
self.congestion_timeout as i64
} else { 0 };
match self.socket.recv_timeout(&mut b, timeout) {
Ok((r, s)) => { read = r; src = s; break },
Err(ref e) if (e.kind() == ErrorKind::WouldBlock ||
e.kind() == ErrorKind::TimedOut) => {
debug!("recv_from timed out");
try!(self.handle_receive_timeout());
},
Err(e) => return Err(e),
};
let elapsed = now_microseconds() - now;
debug!("now_microseconds() - now = {} ms", elapsed/1000);
retries += 1;
}
// Decode received data into a packet
let packet = match Packet::from_bytes(&b[..read]) {
Ok(packet) => packet,
Err(e) => {
debug!("{}", e);
debug!("Ignoring invalid packet");
return Ok((0, self.connected_to));
}
};
debug!("received {:?}", packet);
// Process packet, including sending a reply if necessary
if let Some(mut pkt) = try!(self.handle_packet(&packet, src)) {
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(&pkt.to_bytes()[..], src));
debug!("sent {:?}", pkt);
}
// Insert data packet into the incoming buffer if it isn't a duplicate of a previously
// discarded packet
if packet.get_type() == PacketType::Data &&
packet.seq_nr().wrapping_sub(self.last_dropped) > 0 {
self.insert_into_buffer(packet);
}
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf);
Ok((read, src))
}
fn handle_receive_timeout(&mut self) -> Result<()> {
self.congestion_timeout = self.congestion_timeout * 2;
self.cwnd = MSS;
// There are three possible cases here:
//
// - If the socket is sending and waiting for acknowledgements (the send window is
// not empty), resend the first unacknowledged packet;
//
// - If the socket is not sending and it hasn't sent a FIN yet, then it's waiting
// for incoming packets: send a fast resend request;
//
// - If the socket sent a FIN previously, resend it.
debug!("self.send_window: {:?}", self.send_window.iter()
.map(Packet::seq_nr).collect::<Vec<u16>>());
if self.send_window.is_empty() {
// The socket is trying to close, all sent packets were acknowledged, and it has
// already sent a FIN: resend it.
if self.state == SocketState::FinSent {
let mut packet = Packet::new();
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
// Send FIN
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent FIN: {:?}", packet);
} else {
// The socket is waiting for incoming packets but the remote peer is silent:
// send a fast resend request.
debug!("sending fast resend request");
self.send_fast_resend_request();
}
} else {
// The socket is sending data packets but there is no reply from the remote
// peer: resend the first unacknowledged packet with the current timestamp.
let mut packet = &mut self.send_window[0];
packet.set_timestamp_microseconds(now_microseconds());
try!(self.socket.send_to(&packet.to_bytes()[..], self.connected_to));
debug!("resent {:?}", packet);
}
Ok(())
}
fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {
let mut resp = Packet::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = original.timestamp_microseconds();
resp.set_timestamp_microseconds(self_t_micro);
resp.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
resp.set_connection_id(self.sender_connection_id);
resp.set_seq_nr(self.seq_nr);
resp.set_ack_nr(self.ack_nr);
resp
}
/// Removes a packet in the incoming buffer and updates the current acknowledgement number.
fn advance_incoming_buffer(&mut self) -> Option<Packet> {
if !self.incoming_buffer.is_empty() {
let packet = self.incoming_buffer.remove(0);
debug!("Removed packet from incoming buffer: {:?}", packet);
self.ack_nr = packet.seq_nr();
self.last_dropped = self.ack_nr;
Some(packet)
} else {
None
}
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {
fn unsafe_copy(src: &[u8], dst: &mut [u8]) -> usize {
let max_len = min(src.len(), dst.len());
unsafe {
use std::ptr::copy;
copy(src.as_ptr(), dst.as_mut_ptr(), max_len);
}
return max_len;
}
// Return pending data from a partially read packet
if !self.pending_data.is_empty() {
let flushed = unsafe_copy(&self.pending_data[..], buf);
if flushed == self.pending_data.len() {
self.pending_data.clear();
self.advance_incoming_buffer();
} else {
self.pending_data = self.pending_data[flushed..].to_vec();
}
return flushed;
}
if !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let flushed = unsafe_copy(&self.incoming_buffer[0].payload[..], buf);
if flushed == self.incoming_buffer[0].payload.len() {
self.advance_incoming_buffer();
} else {
self.pending_data = self.incoming_buffer[0].payload[flushed..].to_vec();
}
return flushed;
}
return 0;
}
/// Sends data on the socket to the remote peer. On success, returns the number of bytes
/// written.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
pub fn send_to(&mut self, buf: &[u8]) -> Result<usize> {
if self.state == SocketState::Closed {
return Err(Error::from(SocketError::ConnectionClosed));
}
let total_length = buf.len();
for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {
let mut packet = Packet::with_payload(chunk);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
packet.set_connection_id(self.sender_connection_id);
self.unsent_queue.push_back(packet);
// `OverflowingOps` is marked unstable, so we can't use `overflowing_add` here
if self.seq_nr == ::std::u16::MAX {
self.seq_nr = 0;
} else {
self.seq_nr += 1;
}
}
// Send every packet in the queue
try!(self.send());
Ok(total_length)
}
/// Consumes acknowledgements for every pending packet.
pub fn flush(&mut self) -> Result<()> {
let mut buf = [0u8; BUF_SIZE];
while !self.send_window.is_empty() {
debug!("packets in send window: {}", self.send_window.len());
try!(self.recv(&mut buf));
}
Ok(())
}
/// Sends every packet in the unsent packet queue.
fn send(&mut self) -> Result<()> {
while let Some(mut packet) = self.unsent_queue.pop_front() {
try!(self.send_packet(&mut packet));
self.curr_window += packet.len() as u32;
self.send_window.push(packet);
}
Ok(())
}
/// Send one packet.
#[inline(always)]
fn send_packet(&mut self, packet: &mut Packet) -> Result<()> {
let dst = self.connected_to;
debug!("current window: {}", self.send_window.len());
let max_inflight = min(self.cwnd, self.remote_wnd_size);
let max_inflight = max(MIN_CWND * MSS, max_inflight);
let now = now_microseconds();
// Wait until enough inflight packets are acknowledged for rate control purposes, but don't
// wait more than 500 ms before sending the packet.
while self.curr_window >= max_inflight && now_microseconds() - now < 500_000 {
debug!("self.curr_window: {}", self.curr_window);
debug!("max_inflight: {}", max_inflight);
debug!("self.duplicate_ack_count: {}", self.duplicate_ack_count);
debug!("now_microseconds() - now = {}", now_microseconds() - now);
let mut buf = [0; BUF_SIZE];
try!(self.recv(&mut buf));
}
debug!("out: now_microseconds() - now = {}", now_microseconds() - now);
// Check if it still makes sense to send packet, as we might be trying to resend a lost
// packet acknowledged in the receive loop above.
// If there were no wrapping around of sequence numbers, we'd simply check if the packet's
// sequence number is greater than `last_acked`.
let distance_a = packet.seq_nr().wrapping_sub(self.last_acked);
let distance_b = self.last_acked.wrapping_sub(packet.seq_nr());
if distance_a > distance_b {
debug!("Packet already acknowledged, skipping...");
return Ok(());
}
packet.set_timestamp_microseconds(now_microseconds());
packet.set_timestamp_difference_microseconds(self.their_delay);
try!(self.socket.send_to(&packet.to_bytes()[..], dst));
debug!("sent {:?}", packet);
Ok(())
}
// Insert a new sample in the base delay list.
//
// The base delay list contains at most `BASE_HISTORY` samples, each sample is the minimum
// measured over a period of a minute.
fn update_base_delay(&mut self, base_delay: i64, now: i64) {
let minute_in_microseconds = 60 * 10i64.pow(6);
if self.base_delays.is_empty() || now - self.last_rollover > minute_in_microseconds {
// Update last rollover
self.last_rollover = now;
// Drop the oldest sample, if need be
if self.base_delays.len() == BASE_HISTORY {
self.base_delays.pop_front();
}
// Insert new sample
self.base_delays.push_back(base_delay);
} else {
// Replace sample for the current minute if the delay is lower
let last_idx = self.base_delays.len() - 1;
if base_delay < self.base_delays[last_idx] {
self.base_delays[last_idx] = base_delay;
}
}
}
/// Inserts a new sample in the current delay list after removing samples older than one RTT, as
/// specified in RFC6817.
fn update_current_delay(&mut self, v: i64, now: i64) {
// Remove samples more than one RTT old
let rtt = self.rtt as i64 * 100;
while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {
self.current_delays.remove(0);
}
// Insert new measurement
self.current_delays.push(DelayDifferenceSample{ received_at: now, difference: v });
}
fn update_congestion_timeout(&mut self, current_delay: i32) {
let delta = self.rtt - current_delay;
self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;
self.rtt += (current_delay - self.rtt) / 8;
self.congestion_timeout = max((self.rtt + self.rtt_variance * 4) as u64,
MIN_CONGESTION_TIMEOUT);
self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);
debug!("current_delay: {}", current_delay);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.congestion_timeout: {}", self.congestion_timeout);
}
/// Calculates the filtered current delay in the current window.
///
/// The current delay is calculated through application of the exponential
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|&ref x| x.difference).collect();
ewma(input, 0.333) as i64
}
/// Calculates the lowest base delay in the current window.
fn min_base_delay(&self) -> i64 {
self.base_delays.iter().map(|x| *x).min().unwrap_or(0)
}
/// Builds the selective acknowledgment extension data for usage in packets.
fn build_selective_ack(&self) -> Vec<u8> {
let stashed = self.incoming_buffer.iter()
.filter(|&pkt| pkt.seq_nr() > self.ack_nr);
let mut sack = Vec::new();
for packet in stashed {
let diff = packet.seq_nr() - self.ack_nr - 2;
let byte = (diff / 8) as usize;
let bit = (diff % 8) as usize;
// Make sure the amount of elements in the SACK vector is a
// multiple of 4 and enough to represent the lost packets
while byte >= sack.len() || sack.len() % 4 != 0 {
sack.push(0u8);
}
sack[byte] |= 1 << bit;
}
return sack;
}
/// Sends a fast resend request to the remote peer.
///
/// A fast resend request consists of sending three STATE packets (acknowledging the last
/// received packet) in quick succession.
fn send_fast_resend_request(&self) {
for _ in 0..3 {
let mut packet = Packet::new();
packet.set_type(PacketType::State);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = 0;
packet.set_timestamp_microseconds(self_t_micro);
packet.set_timestamp_difference_microseconds((self_t_micro - other_t_micro));
packet.set_connection_id(self.sender_connection_id);
packet.set_seq_nr(self.seq_nr);
packet.set_ack_nr(self.ack_nr);
let _ = self.socket.send_to(&packet.to_bytes()[..], self.connected_to);
}
}
fn resend_lost_packet(&mut self, lost_packet_nr: u16) {
debug!("---> resend_lost_packet({}) <---", lost_packet_nr);
match self.send_window.iter().position(|pkt| pkt.seq_nr() == lost_packet_nr) {
None => debug!("Packet {} not found", lost_packet_nr),
Some(position) => {
debug!("self.send_window.len(): {}", self.send_window.len());
debug!("position: {}", position);
let mut packet = self.send_window[position].clone();
// FIXME: Unchecked result
let _ = self.send_packet(&mut packet);
// We intentionally don't increase `curr_window` because otherwise a packet's length
// would be counted more than once
}
}
debug!("---> END resend_lost_packet <---");
}
/// Forgets sent packets that were acknowledged by the remote peer.
fn advance_send_window(&mut self) {
// The reason I'm not removing the first element in a loop while its sequence number is
// smaller than `last_acked` is because of wrapping sequence numbers, which would create the
// sequence [..., 65534, 65535, 0, 1, ...]. If `last_acked` is smaller than the first
// packet's sequence number because of wraparound (for instance, 1), no packets would be
// removed, as the condition `seq_nr < last_acked` would fail immediately.
//
// On the other hand, I can't keep removing the first packet in a loop until its sequence
// number matches `last_acked` because it might never match, and in that case no packets
// should be removed.
if let Some(position) = self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
for _ in (0..position + 1) {
let packet = self.send_window.remove(0);
self.curr_window -= packet.len() as u32;
}
}
debug!("self.curr_window: {}", self.curr_window);
}
/// Handles an incoming packet, updating socket state accordingly.
///
/// Returns the appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> Result<Option<Packet>> {
debug!("({:?}, {:?})", self.state, packet.get_type());
// Acknowledge only if the packet strictly follows the previous one
if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {
self.ack_nr = packet.seq_nr();
}
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != PacketType::Syn &&
self.state != SocketState::SynSent &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));
}
// Update remote window size
self.remote_wnd_size = packet.wnd_size();
debug!("self.remote_wnd_size: {}", self.remote_wnd_size);
// Update remote peer's delay between them sending the packet and us receiving it
let now = now_microseconds();
self.their_delay = if now > packet.timestamp_microseconds() {
now - packet.timestamp_microseconds()
} else {
packet.timestamp_microseconds() - now
};
debug!("self.their_delay: {}", self.their_delay);
match (self.state, packet.get_type()) {
(SocketState::New, PacketType::Syn) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr = rand::random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = SocketState::Connected;
self.last_dropped = self.ack_nr;
Ok(Some(self.prepare_reply(packet, PacketType::State)))
},
(_, PacketType::Syn) => {
Ok(Some(self.prepare_reply(packet, PacketType::Reset)))
}
(SocketState::SynSent, PacketType::State) => {
self.connected_to = src;
self.ack_nr = packet.seq_nr();
self.seq_nr += 1;
self.state = SocketState::Connected;
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
Ok(None)
},
(SocketState::SynSent, _) => {
Err(Error::from(SocketError::InvalidReply))
}
(SocketState::Connected, PacketType::Data) |
(SocketState::FinSent, PacketType::Data) => {
Ok(self.handle_data_packet(packet))
},
(SocketState::Connected, PacketType::State) => {
self.handle_state_packet(packet);
Ok(None)
},
(SocketState::Connected, PacketType::Fin) |
(SocketState::FinSent, PacketType::Fin) => {
if packet.ack_nr() < self.seq_nr {
debug!("FIN received but there are missing acknowledgments for sent packets");
}
let mut reply = self.prepare_reply(packet, PacketType::State);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
// Give up, the remote peer might not care about our missing packets
self.state = SocketState::Closed;
Ok(Some(reply))
}
(SocketState::FinSent, PacketType::State) => {
if packet.ack_nr() == self.seq_nr {
self.state = SocketState::Closed;
} else {
self.handle_state_packet(packet);
}
Ok(None)
}
(_, PacketType::Reset) => {
self.state = SocketState::ResetReceived;
Err(Error::from(SocketError::ConnectionReset))
},
(state, ty) => {
let message = format!("Unimplemented handling for ({:?},{:?})", state, ty);
debug!("{}", message);
Err(Error::new(ErrorKind::Other, message))
}
}
}
fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {
// If a FIN was previously sent, reply with a FIN packet acknowledging the received packet.
let packet_type = if self.state == SocketState::FinSent {
PacketType::Fin
} else {
PacketType::State
};
let mut reply = self.prepare_reply(packet, packet_type);
if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let sack = self.build_selective_ack();
if sack.len() > 0 {
reply.set_sack(sack);
}
}
Some(reply)
}
fn queuing_delay(&self) -> i64 {
let filtered_current_delay = self.filtered_current_delay();
let min_base_delay = self.min_base_delay();
let queuing_delay = filtered_current_delay - min_base_delay;
debug!("filtered_current_delay: {}", filtered_current_delay);
debug!("min_base_delay: {}", min_base_delay);
debug!("queuing_delay: {}", queuing_delay);
return queuing_delay;
}
/// Calculates the new congestion window size, increasing it or decreasing it.
///
/// This is the core of uTP, the [LEDBAT][ledbat_rfc] congestion algorithm. It depends on
/// estimating the queuing delay between the two peers, and adjusting the congestion window
/// accordingly.
///
/// `off_target` is a normalized value representing the difference between the current queuing
/// delay and a fixed target delay (`TARGET`). `off_target` ranges between -1.0 and 1.0. A
/// positive value makes the congestion window increase, while a negative value makes the
/// congestion window decrease.
///
/// `bytes_newly_acked` is the number of bytes acknowledged by an inbound `State` packet. It may
/// be the size of the packet explicitly acknowledged by the inbound packet (i.e., with sequence
/// number equal to the inbound packet's acknowledgement number), or every packet implicitly
/// acknowledged (every packet with sequence number between the previous inbound `State`
/// packet's acknowledgement number and the current inbound `State` packet's acknowledgement
/// number).
///
///[ledbat_rfc]: https://tools.ietf.org/html/rfc6817
fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {
let flightsize = self.curr_window;
let cwnd_increase = GAIN * off_target * bytes_newly_acked as f64 * MSS as f64;
let cwnd_increase = cwnd_increase / self.cwnd as f64;
debug!("cwnd_increase: {}", cwnd_increase);
self.cwnd = (self.cwnd as f64 + cwnd_increase) as u32;
let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;
self.cwnd = min(self.cwnd, max_allowed_cwnd);
self.cwnd = max(self.cwnd, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
debug!("max_allowed_cwnd: {}", max_allowed_cwnd);
}
fn handle_state_packet(&mut self, packet: &Packet) {
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Update congestion window size
if let Some(index) = self.send_window.iter().position(|p| packet.ack_nr() == p.seq_nr()) {
// Calculate the sum of the size of every packet implicitly and explictly acknowledged
// by the inbout packet (i.e., every packet whose sequence number precedes the inbound
// packet's acknowledgement number, plus the packet whose sequence number matches)
let bytes_newly_acked = self.send_window.iter()
.take(index + 1)
.fold(0, |acc, p| acc + p.len());
// Update base and current delay
let now = now_microseconds() as i64;
let our_delay = now - self.send_window[index].timestamp_microseconds() as i64;
debug!("our_delay: {}", our_delay);
self.update_base_delay(our_delay, now);
self.update_current_delay(our_delay, now);
let off_target: f64 = (TARGET as f64 - self.queuing_delay() as f64) / TARGET as f64;
debug!("off_target: {}", off_target);
self.update_congestion_window(off_target, bytes_newly_acked as u32);
// Update congestion timeout
let rtt = (TARGET - off_target as i64) / 1000; // in milliseconds
self.update_congestion_timeout(rtt as i32);
}
let mut packet_loss_detected: bool = !self.send_window.is_empty() &&
self.duplicate_ack_count == 3;
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.get_type() == ExtensionType::SelectiveAck {
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if extension.iter().count_ones() >= 3 {
self.resend_lost_packet(packet.ack_nr() + 1);
packet_loss_detected = true;
}
for seq_nr in extension.iter().enumerate()
.filter(|&(_idx, received)| !received)
.map(|(idx, _received)| packet.ack_nr() + 2 + idx as u16) {
if self.send_window.last().map(|p| seq_nr < p.seq_nr()).unwrap_or(false) {
debug!("SACK: packet {} lost", seq_nr);
self.resend_lost_packet(seq_nr);
packet_loss_detected = true;
} else {
break;
}
}
} else {
debug!("Unknown extension {:?}, ignoring", extension.get_type());
}
}
// Three duplicate ACKs mean a fast resend request. Resend the first unacknowledged packet
// if the incoming packet doesn't have a SACK extension. If it does, the lost packets were
// already resent.
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 &&
!packet.extensions.iter().any(|ext| ext.get_type() == ExtensionType::SelectiveAck) {
self.resend_lost_packet(packet.ack_nr() + 1);
}
// Packet lost, halve the congestion window
if packet_loss_detected {
debug!("packet loss detected, halving congestion window");
self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);
debug!("cwnd: {}", self.cwnd);
}
// Success, advance send window
self.advance_send_window();
}
/// Inserts a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: Packet) {
// Immediately push to the end if the packet's sequence number comes after the last
// packet's.
if self.incoming_buffer.last().map(|p| packet.seq_nr() > p.seq_nr()).unwrap_or(false) {
self.incoming_buffer.push(packet);
} else {
// Find index following the most recent packet before the one we wish to insert
let i = self.incoming_buffer.iter().filter(|p| p.seq_nr() < packet.seq_nr()).count();
// Remove packet if it's a duplicate
if self.incoming_buffer.get(i).map(|p| p.seq_nr() == packet.seq_nr()).unwrap_or(false) {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
let _ = self.close();
}
}
/// A structure representing a socket server.
///
/// # Examples
///
/// ```no_run
/// use utp::{UtpListener, UtpSocket};
/// use std::thread;
///
/// fn handle_client(socket: UtpSocket) {
/// // ...
/// }
///
/// fn main() {
/// // Create a listener
/// let addr = "127.0.0.1:8080";
/// let listener = UtpListener::bind(addr).unwrap();
///
/// for connection in listener.incoming() {
/// // Spawn a new handler for each new connection
/// match connection {
/// Ok((socket, _src)) => { thread::spawn(move || { handle_client(socket) }); },
/// _ => ()
/// }
/// }
/// }
/// ```
pub struct UtpListener {
/// The public facing UDP socket
socket: UdpSocket,
}
impl UtpListener {
/// Creates a new `UtpListener` bound to a specific address.
///
/// The resulting listener is ready for accepting connections.
///
/// The address type can be any implementor of the `ToSocketAddr` trait. See its documentation
/// for concrete examples.
///
/// If more than one valid address is specified, only the first will be used.
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpListener> {
UdpSocket::bind(addr).and_then(|s| Ok(UtpListener { socket: s}))
}
/// Accepts a new incoming connection from this listener.
///
/// This function will block the caller until a new uTP connection is established. When
/// established, the corresponding `UtpSocket` and the peer's remote address will be returned.
///
/// Notice that the resulting `UtpSocket` is bound to a different local port than the public
/// listening port (which `UtpListener` holds). This may confuse the remote peer!
pub fn accept(&self) -> Result<(UtpSocket, SocketAddr)> {
let mut buf = [0; BUF_SIZE];
match self.socket.recv_from(&mut buf) {
Ok((nread, src)) => {
let packet = try!(Packet::from_bytes(&buf[..nread])
.or(Err(SocketError::InvalidPacket)));
// Ignore non-SYN packets
if packet.get_type() != PacketType::Syn {
return Err(Error::from(SocketError::InvalidPacket));
}
// The address of the new socket will depend on the type of the listener.
let inner_socket = self.socket.local_addr().and_then(|addr| match addr {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0"),
SocketAddr::V6(_) => UdpSocket::bind(":::0"),
});
let mut socket = try!(inner_socket.map(|s| UtpSocket::from_raw_parts(s, src)));
// Establish connection with remote peer
match socket.handle_packet(&packet, src) {
Ok(Some(reply)) => { try!(socket.socket.send_to(&reply.to_bytes()[..], src)) },
Ok(None) => return Err(Error::from(SocketError::InvalidPacket)),
Err(e) => return Err(e)
};
Ok((socket, src))
},
Err(e) => Err(e)
}
}
/// Returns an iterator over the connections being received by this listener.
///
/// The returned iterator will never return `None`.
pub fn incoming(&self) -> Incoming {
Incoming { listener: self }
}
/// Returns the local socket address of this listener.
pub fn local_addr(&self) -> Result<SocketAddr> {
self.socket.local_addr()
}
}
pub struct Incoming<'a> { listener: &'a UtpListener }
impl<'a> Iterator for Incoming<'a> {
type Item = Result<(UtpSocket, SocketAddr)>;
fn next(&mut self) -> Option<Result<(UtpSocket, SocketAddr)>> {
Some(self.listener.accept())
}
}
#[cfg(test)]
mod test {
use std::thread;
use std::net::ToSocketAddrs;
use std::io::ErrorKind;
use super::{UtpSocket, UtpListener, SocketState, BUF_SIZE, take_address};
use packet::{Packet, PacketType, Encodable, Decodable};
use util::now_microseconds;
use rand;
macro_rules! iotry {
($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{:?}", e) })
}
fn next_test_port() -> u16 {
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
const BASE_PORT: u16 = 9600;
BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
fn next_test_ip4<'a>() -> (&'a str, u16) {
("127.0.0.1", next_test_port())
}
fn next_test_ip6<'a>() -> (&'a str, u16) {
("::1", next_test_port())
}
#[test]
fn test_socket_ipv4() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_socket_ipv6() {
let server_addr = next_test_ip6();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
assert_eq!(client.connected_to,
server_addr.to_socket_addrs().unwrap().next().unwrap());
iotry!(client.close());
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
match server.recv_from(&mut buf) {
e => println!("{:?}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Closed);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert!(client.close().is_ok());
});
// Make the server listen for incoming connections until the end of the input
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv_from(&mut buf);
assert!(server.state == SocketState::Closed);
// Trying to receive again returns Ok(0) [EndOfFile]
match server.recv_from(&mut buf) {
Ok((0, _src)) => {},
e => panic!("Expected Ok(0), got {:?}", e),
}
assert_eq!(server.state, SocketState::Closed);
}
#[test]
fn test_sendto_on_closed_socket() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
iotry!(client.close());
});
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(&mut buf));
assert_eq!(server.state, SocketState::Closed);
// Trying to send to the socket after closing it raises an error
match server.send_to(&buf) {
Err(ref e) if e.kind() == ErrorKind::NotConnected => (),
v => panic!("expected {:?}, got {:?}", ErrorKind::NotConnected, v),
}
}
#[test]
fn test_acks_on_socket() {
use std::sync::mpsc::channel;
let server_addr = next_test_ip4();
let (tx, rx) = channel();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
// Make the server listen for incoming connections
let mut buf = [0u8; BUF_SIZE];
let _resp = server.recv(&mut buf);
tx.send(server.seq_nr).unwrap();
// Close the connection
iotry!(server.recv_from(&mut buf));
drop(server);
});
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let sender_seq_nr = rx.recv().unwrap();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert!(client.close().is_ok());
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = rand::random();
let sender_connection_id = initial_connection_id + 1;
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
// Do we have a response?
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Same connection id on both ends during connection establishment
assert!(response.connection_id() == packet.connection_id());
// Response acknowledges SYN
assert!(response.ack_nr() == packet.seq_nr());
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == packet.connection_id() - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == packet.seq_nr());
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = Packet::new();
packet.set_type(PacketType::Fin);
packet.set_connection_id(sender_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(packet.seq_nr() == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.seq_nr() == old_response.seq_nr());
// FIN should be acknowledged
assert!(response.ack_nr() == packet.seq_nr());
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_none());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
assert!(response.unwrap().get_type() == PacketType::State);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.wrapping_mul(2);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_connection_id(new_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::Reset);
assert!(response.ack_nr() == packet.seq_nr());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = rand::random();
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(initial_connection_id);
let response = socket.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == PacketType::State);
let old_packet = packet;
let old_response = response;
let mut window: Vec<Packet> = Vec::new();
// Now, send a keepalive packet
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 1);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(1, 2, 3);
window.push(packet);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(initial_connection_id);
packet.set_seq_nr(old_packet.seq_nr() + 2);
packet.set_ack_nr(old_response.seq_nr());
packet.payload = vec!(4, 5, 6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(&window[1], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
assert!(response.ack_nr() != window[1].seq_nr());
let response = socket.handle_packet(&window[0], client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
// Mark socket as closed
socket.state = SocketState::Closed;
}
#[test]
fn test_socket_unordered_packets() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
let s = client.socket.try_clone().ok().expect("Error cloning internal UDP socket");
let mut window: Vec<Packet> = Vec::new();
for data in (1..13u8).collect::<Vec<u8>>()[..].chunks(3) {
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = data.to_vec();
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
client.curr_window += packet.len() as u32;
}
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Fin);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(&window[3].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[2].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[1].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[0].to_bytes()[..], server_addr));
iotry!(s.send_to(&window[4].to_bytes()[..], server_addr));
for _ in (0u8..2) {
let mut buf = [0; BUF_SIZE];
iotry!(s.recv_from(&mut buf));
}
});
let mut buf = [0; BUF_SIZE];
let expected: Vec<u8> = (1..13u8).collect();
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.state, SocketState::Closed);
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
#[test]
fn test_response_to_triple_ack() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Fits in a packet
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert_eq!(LEN, data.len());
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&d[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Expect SYN
iotry!(server.recv(&mut buf));
// Receive data
let data_packet = match server.socket.recv_from(&mut buf) {
Ok((read, _src)) => iotry!(Packet::from_bytes(&buf[..read])),
Err(e) => panic!("{}", e),
};
assert_eq!(data_packet.get_type(), PacketType::Data);
assert_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
// Send triple ACK
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::State);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(data_packet.seq_nr() - 1);
packet.set_connection_id(server.sender_connection_id);
for _ in (0u8..3) {
iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to));
}
// Receive data again and check that it's the same we reported as missing
let client_addr = server.connected_to;
match server.socket.recv_from(&mut buf) {
Ok((0, _)) => panic!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..read]));
assert_eq!(packet.get_type(), PacketType::Data);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(&packet, client_addr);
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.is_some());
let response = response.unwrap();
iotry!(server.socket.send_to(&response.to_bytes()[..], server.connected_to));
},
Err(e) => panic!("{}", e),
}
// Receive close
iotry!(server.recv_from(&mut buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) =
(next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),
next_test_ip4().to_socket_addrs().unwrap().next().unwrap());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 512;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let d = data.clone();
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(&d[..]));
drop(client);
});
let mut buf = [0u8; BUF_SIZE];
server.recv(&mut buf).unwrap();
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(&mut buf));
// Set a much smaller than usual timeout, for quicker test completion
server.congestion_timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(&mut buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => panic!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = Packet::new();
packet.set_seq_nr(1);
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(128);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 128);
packet.set_seq_nr(3);
packet.set_timestamp_microseconds(256);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);
assert_eq!(socket.incoming_buffer[2].timestamp_microseconds(), 256);
// Replace a packet with a more recent version
packet.set_seq_nr(2);
packet.set_timestamp_microseconds(456);
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);
assert_eq!(socket.incoming_buffer[1].timestamp_microseconds(), 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == SocketState::New);
assert!(client.state == SocketState::New);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
assert!(client.state == SocketState::Connected);
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Data);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.payload = vec!(1, 2, 3);
// Send two copies of the packet, with different timestamps
for _ in (0u8..2) {
packet.set_timestamp_microseconds(now_microseconds());
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in (0u8..1) {
let mut buf = [0; BUF_SIZE];
iotry!(client.socket.recv_from(&mut buf));
}
iotry!(client.close());
});
let mut buf = [0u8; BUF_SIZE];
iotry!(server.recv(&mut buf));
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == SocketState::Connected);
let expected: Vec<u8> = vec!(1, 2, 3);
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{:?}", e)
}
}
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
}
// #[test]
// #[ignore]
// fn test_selective_ack_response() {
// let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
// const LEN: usize = 1024 * 10;
// let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
// let to_send = data.clone();
// // Client
// thread::spawn(move || {
// let client = iotry!(UtpSocket::bind(client_addr));
// let mut client = iotry!(UtpSocket::connect(server_addr));
// client.congestion_timeout = 50;
// iotry!(client.send_to(&to_send[..]));
// iotry!(client.close());
// });
// // Server
// let mut server = iotry!(UtpSocket::bind(server_addr));
// let mut buf = [0; BUF_SIZE];
// // Connect
// iotry!(server.recv_from(&mut buf));
// // Discard packets
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// iotry!(server.socket.recv_from(&mut buf));
// // Generate SACK
// let mut packet = Packet::new();
// packet.set_seq_nr(server.seq_nr);
// packet.set_ack_nr(server.ack_nr - 1);
// packet.set_connection_id(server.sender_connection_id);
// packet.set_timestamp_microseconds(now_microseconds());
// packet.set_type(PacketType::State);
// packet.set_sack(vec!(12, 0, 0, 0));
// // Send SACK
// iotry!(server.socket.send_to(&packet.to_bytes()[..], server.connected_to.clone()));
// // Expect to receive "missing" packets
// let mut received: Vec<u8> = vec!();
// loop {
// match server.recv_from(&mut buf) {
// Ok((0, _src)) => break,
// Ok((len, _src)) => received.extend(buf[..len].to_vec()),
// Err(e) => panic!("{:?}", e)
// }
// }
// assert!(!received.is_empty());
// assert_eq!(received.len(), data.len());
// assert_eq!(received, data);
// }
#[test]
fn test_correct_packet_loss() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024 * 10;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send[..].chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = Packet::new();
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
packet.set_connection_id(client.sender_connection_id);
packet.set_timestamp_microseconds(now_microseconds());
packet.payload = chunk.to_vec();
packet.set_type(PacketType::Data);
if index % 2 == 0 {
iotry!(client.socket.send_to(&packet.to_bytes()[..], dst));
}
client.curr_window += packet.len() as u32;
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = 1024;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != SocketState::Closed {
let mut small_buffer = [0; 512];
match server.recv_from(&mut small_buffer) {
Ok((0, _src)) => break,
Ok((len, _src)) => read.extend(small_buffer[..len].to_vec()),
Err(e) => panic!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_sequence_number_rollover() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::bind(client_addr));
// Advance socket's sequence number
client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;
let mut client = iotry!(UtpSocket::connect(server_addr));
// Send enough data to rollover
iotry!(client.send_to(&to_send[..]));
// Check that the sequence number did rollover
assert!(client.seq_nr < 50);
// Close connection
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_drop_unused_socket() {
let server_addr = next_test_ip4();
let server = iotry!(UtpSocket::bind(server_addr));
// Explicitly dropping socket. This test should not hang.
drop(server);
}
#[test]
fn test_invalid_packet_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => { iotry!(server.send_to(&[], client_addr)); },
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::Other => (), // OK
Err(e) => panic!("Expected ErrorKind::Other, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receive_unexpected_reply_type_on_connect() {
use std::net::UdpSocket;
let server_addr = next_test_ip4();
let server = iotry!(UdpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
let mut packet = Packet::new();
packet.set_type(PacketType::Data);
match server.recv_from(&mut buf) {
Ok((_len, client_addr)) => {
iotry!(server.send_to(&packet.to_bytes()[..], client_addr));
},
_ => panic!()
}
});
match UtpSocket::connect(server_addr) {
Err(ref e) if e.kind() == ErrorKind::ConnectionRefused => (), // OK
Err(e) => panic!("Expected ErrorKind::ConnectionRefused, got {:?}", e),
Ok(_) => panic!("Expected Err, got Ok")
}
}
#[test]
fn test_receiving_syn_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(e) => panic!("{:?}", e)
}
}
});
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Syn);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let reply = Packet::from_bytes(&buf[..len]).ok().unwrap();
assert_eq!(reply.get_type(), PacketType::Reset);
}
Err(e) => panic!("{:?}", e)
}
}
#[test]
fn test_receiving_reset_on_established_connection() {
// Establish connection
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
thread::spawn(move || {
let client = iotry!(UtpSocket::connect(server_addr));
let mut packet = Packet::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(PacketType::Reset);
packet.set_connection_id(client.sender_connection_id);
packet.set_seq_nr(client.seq_nr);
packet.set_ack_nr(client.ack_nr);
iotry!(client.socket.send_to(&packet.to_bytes()[..], server_addr));
let mut buf = [0; BUF_SIZE];
match client.socket.recv_from(&mut buf) {
Ok((_len, _src)) => (),
Err(e) => panic!("{:?}", e)
}
});
let mut buf = [0; BUF_SIZE];
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok(_) => (),
Err(ref e) if e.kind() == ErrorKind::ConnectionReset => return,
Err(e) => panic!("{:?}", e)
}
}
panic!("Should have received Reset");
}
#[test]
fn test_premature_fin() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
const LEN: usize = BUF_SIZE * 4;
let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();
let to_send = data.clone();
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&to_send[..]));
iotry!(client.close());
});
let mut buf = [0; BUF_SIZE];
// Accept connection
iotry!(server.recv(&mut buf));
// Send FIN without acknowledging packets received
let mut packet = Packet::new();
packet.set_connection_id(server.sender_connection_id);
packet.set_seq_nr(server.seq_nr);
packet.set_ack_nr(server.ack_nr);
packet.set_timestamp_microseconds(now_microseconds());
packet.set_type(PacketType::Fin);
iotry!(server.socket.send_to(&packet.to_bytes()[..], client_addr));
// Receive until end
let mut received: Vec<u8> = vec!();
loop {
match server.recv_from(&mut buf) {
Ok((0, _src)) => break,
Ok((len, _src)) => received.extend(buf[..len].to_vec()),
Err(e) => panic!("{}", e)
}
}
assert_eq!(received.len(), data.len());
assert_eq!(received, data);
}
#[test]
fn test_base_delay_calculation() {
let minute_in_microseconds = 60 * 10i64.pow(6);
let samples = vec![(0, 10), (1, 8), (2, 12), (3, 7),
(minute_in_microseconds + 1, 11),
(minute_in_microseconds + 2, 19),
(minute_in_microseconds + 3, 9)];
let addr = next_test_ip4();
let mut socket = UtpSocket::bind(addr).unwrap();
for (timestamp, delay) in samples{
socket.update_base_delay(delay, timestamp + delay);
}
let expected = vec![7, 9];
let actual = socket.base_delays.iter().map(|&x| x).collect::<Vec<_>>();
assert_eq!(expected, actual);
assert_eq!(socket.min_base_delay(), 7);
}
#[test]
fn test_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let socket = UtpSocket::bind(addr).unwrap();
assert!(socket.local_addr().is_ok());
assert_eq!(socket.local_addr().unwrap(), addr);
}
#[test]
fn test_listener_local_addr() {
let addr = next_test_ip4();
let addr = addr.to_socket_addrs().unwrap().next().unwrap();
let listener = UtpListener::bind(addr).unwrap();
assert!(listener.local_addr().is_ok());
assert_eq!(listener.local_addr().unwrap(), addr);
}
#[test]
fn test_take_address() {
// Expected succcesses
assert!(take_address(("0.0.0.0:0")).is_ok());
assert!(take_address((":::0")).is_ok());
assert!(take_address(("0.0.0.0", 0)).is_ok());
assert!(take_address(("::", 0)).is_ok());
assert!(take_address(("1.2.3.4", 5)).is_ok());
// Expected failures
assert!(take_address("999.0.0.0:0").is_err());
assert!(take_address(("1.2.3.4:70000")).is_err());
assert!(take_address("").is_err());
assert!(take_address("this is not an address").is_err());
assert!(take_address("no.dns.resolution.com").is_err());
}
// Test reaction to connection loss when sending data packets
#[test]
fn test_connection_loss_data() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Data),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
iotry!(server.send_to(&[0]));
// Try to receive ACKs, time out too many times on flush, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when sending FIN
#[test]
fn test_connection_loss_fin() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let mut buf = [0; BUF_SIZE];
iotry!(socket.recv_from(&mut buf));
for _ in 0..attempts {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => assert_eq!(Packet::from_bytes(&buf[..len]).unwrap().get_type(),
PacketType::Fin),
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Send FIN, time out too many times, and fail with `TimedOut`
match server.close() {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
// Test reaction to connection loss when waiting for data packets
#[test]
fn test_connection_loss_waiting() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
// Decrease timeouts for faster tests
server.congestion_timeout = 1;
let attempts = server.max_retransmission_retries;
thread::spawn(move || {
let mut client = iotry!(UtpSocket::connect(server_addr));
iotry!(client.send_to(&[0]));
// Simulate connection loss by killing the socket.
client.state = SocketState::Closed;
let socket = client.socket.try_clone().unwrap();
let seq_nr = client.seq_nr;
let mut buf = [0; BUF_SIZE];
for _ in 0..(3 * attempts) {
match socket.recv_from(&mut buf) {
Ok((len, _src)) => {
let packet = iotry!(Packet::from_bytes(&buf[..len]));
assert_eq!(packet.get_type(), PacketType::State);
assert_eq!(packet.ack_nr(), seq_nr - 1);
},
Err(e) => panic!("{}", e),
}
}
});
// Drain incoming packets
let mut buf = [0; BUF_SIZE];
iotry!(server.recv_from(&mut buf));
// Try to receive data, time out too many times, and fail with `TimedOut`
let mut buf = [0; BUF_SIZE];
match server.recv_from(&mut buf) {
Err(ref e) if e.kind() == ErrorKind::TimedOut => (),
x => panic!("Expected Err(TimedOut), got {:?}", x),
}
}
}
|
//! Generalized type folding mechanism. The setup is a bit convoluted
//! but allows for convenient usage. Let T be an instance of some
//! "foldable type" (one which implements `TypeFoldable`) and F be an
//! instance of a "folder" (a type which implements `TypeFolder`). Then
//! the setup is intended to be:
//!
//! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
//!
//! This way, when you define a new folder F, you can override
//! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
//! to get the original behavior. Meanwhile, to actually fold
//! something, you can just write `T.fold_with(F)`, which is
//! convenient. (Note that `fold_with` will also transparently handle
//! things like a `Vec<T>` where T is foldable and so on.)
//!
//! In this ideal setup, the only function that actually *does*
//! anything is `T.super_fold_with()`, which traverses the type `T`.
//! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
//!
//! In some cases, we follow a degenerate pattern where we do not have
//! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
//! This is suboptimal because the behavior cannot be overridden, but it's
//! much less work to implement. If you ever *do* need an override that
//! doesn't exist, it's not hard to convert the degenerate pattern into the
//! proper thing.
//!
//! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
//!
//! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
//!
//! These methods return true to indicate that the visitor has found what it is
//! looking for, and does not need to visit anything else.
use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_data_structures::fx::FxHashSet;
use std::collections::BTreeMap;
use std::fmt;
use std::ops::ControlFlow;
/// This trait is implemented for every type that can be folded.
/// Basically, every type that has a corresponding method in `TypeFolder`.
///
/// To implement this conveniently, use the derive macro located in librustc_macros.
pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self;
fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
self.super_fold_with(folder)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy>;
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
self.super_visit_with(visitor)
}
/// Returns `true` if `self` has any late-bound regions that are either
/// bound by `binder` or bound by some binder outside of `binder`.
/// If `binder` is `ty::INNERMOST`, this indicates whether
/// there are any late-bound regions that appear free.
fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
}
/// Returns `true` if this `self` has any regions that escape `binder` (and
/// hence are not bound by it).
fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
self.has_vars_bound_at_or_above(binder.shifted_in(1))
}
fn has_escaping_bound_vars(&self) -> bool {
self.has_vars_bound_at_or_above(ty::INNERMOST)
}
fn has_type_flags(&self, flags: TypeFlags) -> bool {
self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags)
}
fn has_projections(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_PROJECTION)
}
fn has_opaque_types(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
}
fn references_error(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_ERROR)
}
fn has_param_types_or_consts(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
}
fn has_infer_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_INFER)
}
fn has_infer_types(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_INFER)
}
fn has_infer_types_or_consts(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
}
fn needs_infer(&self) -> bool {
self.has_type_flags(TypeFlags::NEEDS_INFER)
}
fn has_placeholders(&self) -> bool {
self.has_type_flags(
TypeFlags::HAS_RE_PLACEHOLDER
| TypeFlags::HAS_TY_PLACEHOLDER
| TypeFlags::HAS_CT_PLACEHOLDER,
)
}
fn needs_subst(&self) -> bool {
self.has_type_flags(TypeFlags::NEEDS_SUBST)
}
/// "Free" regions in this context means that it has any region
/// that is not (a) erased or (b) late-bound.
fn has_free_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
}
fn has_erased_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_ERASED)
}
/// True if there are any un-erased free regions.
fn has_erasable_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
}
/// Indicates whether this value references only 'global'
/// generic parameters that are the same regardless of what fn we are
/// in. This is used for caching.
fn is_global(&self) -> bool {
!self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
}
/// True if there are any late-bound regions
fn has_late_bound_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
}
/// Indicates whether this value still has parameters/placeholders/inference variables
/// which could be replaced later, in a way that would change the results of `impl`
/// specialization.
fn still_further_specializable(&self) -> bool {
self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
}
/// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> ControlFlow<()>) -> ControlFlow<()> {
pub struct Visitor<F>(F);
impl<'tcx, F: FnMut(Ty<'tcx>) -> ControlFlow<()>> TypeVisitor<'tcx> for Visitor<F> {
type BreakTy = ();
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
self.0(ty)
}
}
self.visit_with(&mut Visitor(visit))
}
}
impl TypeFoldable<'tcx> for hir::Constness {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
*self
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> ControlFlow<V::BreakTy> {
ControlFlow::CONTINUE
}
}
/// The `TypeFolder` trait defines the actual *folding*. There is a
/// method defined for every foldable type. Each of these has a
/// default implementation that does an "identity" fold. Within each
/// identity fold, it should invoke `foo.fold_with(self)` to fold each
/// sub-item.
pub trait TypeFolder<'tcx>: Sized {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
where
T: TypeFoldable<'tcx>,
{
t.super_fold_with(self)
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
t.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
r.super_fold_with(self)
}
fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
c.super_fold_with(self)
}
}
pub trait TypeVisitor<'tcx>: Sized {
type BreakTy = !;
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
t.super_visit_with(self)
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
t.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
r.super_visit_with(self)
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
c.super_visit_with(self)
}
fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
p.super_visit_with(self)
}
}
///////////////////////////////////////////////////////////////////////////
// Some sample folders
pub struct BottomUpFolder<'tcx, F, G, H>
where
F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
{
pub tcx: TyCtxt<'tcx>,
pub ty_op: F,
pub lt_op: G,
pub ct_op: H,
}
impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
where
F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
{
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let t = ty.super_fold_with(self);
(self.ty_op)(t)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
let r = r.super_fold_with(self);
(self.lt_op)(r)
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
let ct = ct.super_fold_with(self);
(self.ct_op)(ct)
}
}
///////////////////////////////////////////////////////////////////////////
// Region folder
impl<'tcx> TyCtxt<'tcx> {
/// Folds the escaping and free regions in `value` using `f`, and
/// sets `skipped_regions` to true if any late-bound region was found
/// and skipped.
pub fn fold_regions<T>(
self,
value: &T,
skipped_regions: &mut bool,
mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
) -> T
where
T: TypeFoldable<'tcx>,
{
value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
}
/// Invoke `callback` on every region appearing free in `value`.
pub fn for_each_free_region(
self,
value: &impl TypeFoldable<'tcx>,
mut callback: impl FnMut(ty::Region<'tcx>),
) {
self.any_free_region_meets(value, |r| {
callback(r);
false
});
}
/// Returns `true` if `callback` returns true for every region appearing free in `value`.
pub fn all_free_regions_meet(
self,
value: &impl TypeFoldable<'tcx>,
mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
) -> bool {
!self.any_free_region_meets(value, |r| !callback(r))
}
/// Returns `true` if `callback` returns true for some region appearing free in `value`.
pub fn any_free_region_meets(
self,
value: &impl TypeFoldable<'tcx>,
callback: impl FnMut(ty::Region<'tcx>) -> bool,
) -> bool {
struct RegionVisitor<F> {
/// The index of a binder *just outside* the things we have
/// traversed. If we encounter a bound region bound by this
/// binder or one outer to it, it appears free. Example:
///
/// ```
/// for<'a> fn(for<'b> fn(), T)
/// ^ ^ ^ ^
/// | | | | here, would be shifted in 1
/// | | | here, would be shifted in 2
/// | | here, would be `INNERMOST` shifted in by 1
/// | here, initially, binder would be `INNERMOST`
/// ```
///
/// You see that, initially, *any* bound value is free,
/// because we've not traversed any binders. As we pass
/// through a binder, we shift the `outer_index` by 1 to
/// account for the new binder that encloses us.
outer_index: ty::DebruijnIndex,
callback: F,
}
impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
where
F: FnMut(ty::Region<'tcx>) -> bool,
{
type BreakTy = ();
fn visit_binder<T: TypeFoldable<'tcx>>(
&mut self,
t: &Binder<T>,
) -> ControlFlow<Self::BreakTy> {
self.outer_index.shift_in(1);
let result = t.as_ref().skip_binder().visit_with(self);
self.outer_index.shift_out(1);
result
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
match *r {
ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
ControlFlow::CONTINUE
}
_ => {
if (self.callback)(r) {
ControlFlow::BREAK
} else {
ControlFlow::CONTINUE
}
}
}
}
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// We're only interested in types involving regions
if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
ty.super_visit_with(self)
} else {
ControlFlow::CONTINUE
}
}
}
value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
}
}
/// Folds over the substructure of a type, visiting its component
/// types and all regions that occur *free* within it.
///
/// That is, `Ty` can contain function or method types that bind
/// regions at the call site (`ReLateBound`), and occurrences of
/// regions (aka "lifetimes") that are bound within a type are not
/// visited by this folder; only regions that occur free will be
/// visited by `fld_r`.
pub struct RegionFolder<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
skipped_regions: &'a mut bool,
/// Stores the index of a binder *just outside* the stuff we have
/// visited. So this begins as INNERMOST; when we pass through a
/// binder, it is incremented (via `shift_in`).
current_index: ty::DebruijnIndex,
/// Callback invokes for each free region. The `DebruijnIndex`
/// points to the binder *just outside* the ones we have passed
/// through.
fold_region_fn:
&'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
}
impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
#[inline]
pub fn new(
tcx: TyCtxt<'tcx>,
skipped_regions: &'a mut bool,
fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
) -> RegionFolder<'a, 'tcx> {
RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
}
}
impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
debug!(
"RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
r, self.current_index
);
*self.skipped_regions = true;
r
}
_ => {
debug!(
"RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
r, self.current_index
);
(self.fold_region_fn)(r, self.current_index)
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Bound vars replacer
/// Replaces the escaping bound vars (late bound regions or bound types) in a type.
struct BoundVarReplacer<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
/// As with `RegionFolder`, represents the index of a binder *just outside*
/// the ones we have visited.
current_index: ty::DebruijnIndex,
fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
fld_c: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a),
}
impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
fn new<F, G, H>(tcx: TyCtxt<'tcx>, fld_r: &'a mut F, fld_t: &'a mut G, fld_c: &'a mut H) -> Self
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
{
BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
}
}
impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
match *t.kind() {
ty::Bound(debruijn, bound_ty) => {
if debruijn == self.current_index {
let fld_t = &mut self.fld_t;
let ty = fld_t(bound_ty);
ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32())
} else {
t
}
}
_ => {
if !t.has_vars_bound_at_or_above(self.current_index) {
// Nothing more to substitute.
t
} else {
t.super_fold_with(self)
}
}
}
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
let fld_r = &mut self.fld_r;
let region = fld_r(br);
if let ty::ReLateBound(debruijn1, br) = *region {
// If the callback returns a late-bound region,
// that region should always use the INNERMOST
// debruijn index. Then we adjust it to the
// correct depth.
assert_eq!(debruijn1, ty::INNERMOST);
self.tcx.mk_region(ty::ReLateBound(debruijn, br))
} else {
region
}
}
_ => r,
}
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } = *ct {
if debruijn == self.current_index {
let fld_c = &mut self.fld_c;
let ct = fld_c(bound_const, ty);
ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32())
} else {
ct
}
} else {
if !ct.has_vars_bound_at_or_above(self.current_index) {
// Nothing more to substitute.
ct
} else {
ct.super_fold_with(self)
}
}
}
}
impl<'tcx> TyCtxt<'tcx> {
/// Replaces all regions bound by the given `Binder` with the
/// results returned by the closure; the closure is expected to
/// return a free region (relative to this binder), and hence the
/// binder is removed in the return type. The closure is invoked
/// once for each unique `BoundRegion`; multiple references to the
/// same `BoundRegion` will reuse the previous result. A map is
/// returned at the end with each bound region and the free region
/// that replaced it.
///
/// This method only replaces late bound regions and the result may still
/// contain escaping bound types.
pub fn replace_late_bound_regions<T, F>(
self,
value: &Binder<T>,
fld_r: F,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
T: TypeFoldable<'tcx>,
{
// identity for bound types and consts
let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
let fld_c = |bound_ct, ty| {
self.mk_const(ty::Const { val: ty::ConstKind::Bound(ty::INNERMOST, bound_ct), ty })
};
self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
}
/// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
/// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
/// closure replaces escaping bound consts.
pub fn replace_escaping_bound_vars<T, F, G, H>(
self,
value: &T,
mut fld_r: F,
mut fld_t: G,
mut fld_c: H,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
T: TypeFoldable<'tcx>,
{
use rustc_data_structures::fx::FxHashMap;
let mut region_map = BTreeMap::new();
let mut type_map = FxHashMap::default();
let mut const_map = FxHashMap::default();
if !value.has_escaping_bound_vars() {
(value.clone(), region_map)
} else {
let mut real_fld_r = |br| *region_map.entry(br).or_insert_with(|| fld_r(br));
let mut real_fld_t =
|bound_ty| *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty));
let mut real_fld_c =
|bound_ct, ty| *const_map.entry(bound_ct).or_insert_with(|| fld_c(bound_ct, ty));
let mut replacer =
BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t, &mut real_fld_c);
let result = value.fold_with(&mut replacer);
(result, region_map)
}
}
/// Replaces all types or regions bound by the given `Binder`. The `fld_r`
/// closure replaces bound regions while the `fld_t` closure replaces bound
/// types.
pub fn replace_bound_vars<T, F, G, H>(
self,
value: &Binder<T>,
fld_r: F,
fld_t: G,
fld_c: H,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
T: TypeFoldable<'tcx>,
{
self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
}
/// Replaces any late-bound regions bound in `value` with
/// free variants attached to `all_outlive_scope`.
pub fn liberate_late_bound_regions<T>(
self,
all_outlive_scope: DefId,
value: &ty::Binder<T>,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.replace_late_bound_regions(value, |br| {
self.mk_region(ty::ReFree(ty::FreeRegion {
scope: all_outlive_scope,
bound_region: br,
}))
})
.0
}
/// Returns a set of all late-bound regions that are constrained
/// by `value`, meaning that if we instantiate those LBR with
/// variables and equate `value` with something else, those
/// variables will also be equated.
pub fn collect_constrained_late_bound_regions<T>(
self,
value: &Binder<T>,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
self.collect_late_bound_regions(value, true)
}
/// Returns a set of all late-bound regions that appear in `value` anywhere.
pub fn collect_referenced_late_bound_regions<T>(
self,
value: &Binder<T>,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
self.collect_late_bound_regions(value, false)
}
fn collect_late_bound_regions<T>(
self,
value: &Binder<T>,
just_constraint: bool,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
let mut collector = LateBoundRegionsCollector::new(just_constraint);
let result = value.as_ref().skip_binder().visit_with(&mut collector);
assert!(result.is_continue()); // should never have stopped early
collector.regions
}
/// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
/// method lookup and a few other places where precise region relationships are not required.
pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
where
T: TypeFoldable<'tcx>,
{
self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
}
/// Rewrite any late-bound regions so that they are anonymous. Region numbers are
/// assigned starting at 0 and increasing monotonically in the order traversed
/// by the fold operation.
///
/// The chief purpose of this function is to canonicalize regions so that two
/// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
/// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
/// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
where
T: TypeFoldable<'tcx>,
{
let mut counter = 0;
Binder::bind(
self.replace_late_bound_regions(sig, |_| {
let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)));
counter += 1;
r
})
.0,
)
}
}
///////////////////////////////////////////////////////////////////////////
// Shifter
//
// Shifts the De Bruijn indices on all escaping bound vars by a
// fixed amount. Useful in substitution or when otherwise introducing
// a binding level that is not intended to capture the existing bound
// vars. See comment on `shift_vars_through_binders` method in
// `subst.rs` for more details.
struct Shifter<'tcx> {
tcx: TyCtxt<'tcx>,
current_index: ty::DebruijnIndex,
amount: u32,
}
impl Shifter<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
Shifter { tcx, current_index: ty::INNERMOST, amount }
}
}
impl TypeFolder<'tcx> for Shifter<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, br) => {
if self.amount == 0 || debruijn < self.current_index {
r
} else {
let debruijn = debruijn.shifted_in(self.amount);
let shifted = ty::ReLateBound(debruijn, br);
self.tcx.mk_region(shifted)
}
}
_ => r,
}
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
match *ty.kind() {
ty::Bound(debruijn, bound_ty) => {
if self.amount == 0 || debruijn < self.current_index {
ty
} else {
let debruijn = debruijn.shifted_in(self.amount);
self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
}
}
_ => ty.super_fold_with(self),
}
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
if self.amount == 0 || debruijn < self.current_index {
ct
} else {
let debruijn = debruijn.shifted_in(self.amount);
self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
}
} else {
ct.super_fold_with(self)
}
}
}
pub fn shift_region<'tcx>(
tcx: TyCtxt<'tcx>,
region: ty::Region<'tcx>,
amount: u32,
) -> ty::Region<'tcx> {
match region {
ty::ReLateBound(debruijn, br) if amount > 0 => {
tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
}
_ => region,
}
}
pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: &T, amount: u32) -> T
where
T: TypeFoldable<'tcx>,
{
debug!("shift_vars(value={:?}, amount={})", value, amount);
value.fold_with(&mut Shifter::new(tcx, amount))
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct FoundEscapingVars;
/// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
/// bound region or a bound type.
///
/// So, for example, consider a type like the following, which has two binders:
///
/// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
/// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
/// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
///
/// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
/// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
/// fn type*, that type has an escaping region: `'a`.
///
/// Note that what I'm calling an "escaping var" is often just called a "free var". However,
/// we already use the term "free var". It refers to the regions or types that we use to represent
/// bound regions or type params on a fn definition while we are type checking its body.
///
/// To clarify, conceptually there is no particular difference between
/// an "escaping" var and a "free" var. However, there is a big
/// difference in practice. Basically, when "entering" a binding
/// level, one is generally required to do some sort of processing to
/// a bound var, such as replacing it with a fresh/placeholder
/// var, or making an entry in the environment to represent the
/// scope to which it is attached, etc. An escaping var represents
/// a bound var for which this processing has not yet been done.
struct HasEscapingVarsVisitor {
/// Anything bound by `outer_index` or "above" is escaping.
outer_index: ty::DebruijnIndex,
}
impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
type BreakTy = FoundEscapingVars;
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
self.outer_index.shift_in(1);
let result = t.super_visit_with(self);
self.outer_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// If the outer-exclusive-binder is *strictly greater* than
// `outer_index`, that means that `t` contains some content
// bound at `outer_index` or above (because
// `outer_exclusive_binder` is always 1 higher than the
// content in `t`). Therefore, `t` has some escaping vars.
if t.outer_exclusive_binder > self.outer_index {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
// If the region is bound by `outer_index` or anything outside
// of outer index, then it escapes the binders we have
// visited.
if r.bound_at_or_above_binder(self.outer_index) {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
// we don't have a `visit_infer_const` callback, so we have to
// hook in here to catch this case (annoying...), but
// otherwise we do want to remember to visit the rest of the
// const, as it has types/regions embedded in a lot of other
// places.
match ct.val {
ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
ControlFlow::Break(FoundEscapingVars)
}
_ => ct.super_visit_with(self),
}
}
fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
if predicate.inner.outer_exclusive_binder > self.outer_index {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct FoundFlags;
// FIXME: Optimize for checking for infer flags
struct HasTypeFlagsVisitor {
flags: ty::TypeFlags,
}
impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
type BreakTy = FoundFlags;
fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<Self::BreakTy> {
debug!(
"HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
t,
t.flags(),
self.flags
);
if t.flags().intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
let flags = r.type_flags();
debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
if flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
let flags = FlagComputation::for_const(c);
debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
if flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
debug!(
"HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
predicate, predicate.inner.flags, self.flags
);
if predicate.inner.flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
}
/// Collects all the late-bound regions at the innermost binding level
/// into a hash set.
struct LateBoundRegionsCollector {
current_index: ty::DebruijnIndex,
regions: FxHashSet<ty::BoundRegion>,
/// `true` if we only want regions that are known to be
/// "constrained" when you equate this type with another type. In
/// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
/// them constraints `'a == 'b`. But if you have `<&'a u32 as
/// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
/// types may mean that `'a` and `'b` don't appear in the results,
/// so they are not considered *constrained*.
just_constrained: bool,
}
impl LateBoundRegionsCollector {
fn new(just_constrained: bool) -> Self {
LateBoundRegionsCollector {
current_index: ty::INNERMOST,
regions: Default::default(),
just_constrained,
}
}
}
impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
self.current_index.shift_in(1);
let result = t.super_visit_with(self);
self.current_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// if we are only looking for "constrained" region, we have to
// ignore the inputs to a projection, as they may not appear
// in the normalized form
if self.just_constrained {
if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
return ControlFlow::CONTINUE;
}
}
t.super_visit_with(self)
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
// if we are only looking for "constrained" region, we have to
// ignore the inputs of an unevaluated const, as they may not appear
// in the normalized form
if self.just_constrained {
if let ty::ConstKind::Unevaluated(..) = c.val {
return ControlFlow::CONTINUE;
}
}
c.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
if let ty::ReLateBound(debruijn, br) = *r {
if debruijn == self.current_index {
self.regions.insert(br);
}
}
ControlFlow::CONTINUE
}
}
Remove dead `TypeFoldable::visit_tys_shallow` method
//! Generalized type folding mechanism. The setup is a bit convoluted
//! but allows for convenient usage. Let T be an instance of some
//! "foldable type" (one which implements `TypeFoldable`) and F be an
//! instance of a "folder" (a type which implements `TypeFolder`). Then
//! the setup is intended to be:
//!
//! T.fold_with(F) --calls--> F.fold_T(T) --calls--> T.super_fold_with(F)
//!
//! This way, when you define a new folder F, you can override
//! `fold_T()` to customize the behavior, and invoke `T.super_fold_with()`
//! to get the original behavior. Meanwhile, to actually fold
//! something, you can just write `T.fold_with(F)`, which is
//! convenient. (Note that `fold_with` will also transparently handle
//! things like a `Vec<T>` where T is foldable and so on.)
//!
//! In this ideal setup, the only function that actually *does*
//! anything is `T.super_fold_with()`, which traverses the type `T`.
//! Moreover, `T.super_fold_with()` should only ever call `T.fold_with()`.
//!
//! In some cases, we follow a degenerate pattern where we do not have
//! a `fold_T` method. Instead, `T.fold_with` traverses the structure directly.
//! This is suboptimal because the behavior cannot be overridden, but it's
//! much less work to implement. If you ever *do* need an override that
//! doesn't exist, it's not hard to convert the degenerate pattern into the
//! proper thing.
//!
//! A `TypeFoldable` T can also be visited by a `TypeVisitor` V using similar setup:
//!
//! T.visit_with(V) --calls--> V.visit_T(T) --calls--> T.super_visit_with(V).
//!
//! These methods return true to indicate that the visitor has found what it is
//! looking for, and does not need to visit anything else.
use crate::ty::{self, flags::FlagComputation, Binder, Ty, TyCtxt, TypeFlags};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_data_structures::fx::FxHashSet;
use std::collections::BTreeMap;
use std::fmt;
use std::ops::ControlFlow;
/// This trait is implemented for every type that can be folded.
/// Basically, every type that has a corresponding method in `TypeFolder`.
///
/// To implement this conveniently, use the derive macro located in librustc_macros.
pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self;
fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
self.super_fold_with(folder)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy>;
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
self.super_visit_with(visitor)
}
/// Returns `true` if `self` has any late-bound regions that are either
/// bound by `binder` or bound by some binder outside of `binder`.
/// If `binder` is `ty::INNERMOST`, this indicates whether
/// there are any late-bound regions that appear free.
fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool {
self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break()
}
/// Returns `true` if this `self` has any regions that escape `binder` (and
/// hence are not bound by it).
fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool {
self.has_vars_bound_at_or_above(binder.shifted_in(1))
}
fn has_escaping_bound_vars(&self) -> bool {
self.has_vars_bound_at_or_above(ty::INNERMOST)
}
fn has_type_flags(&self, flags: TypeFlags) -> bool {
self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags)
}
fn has_projections(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_PROJECTION)
}
fn has_opaque_types(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
}
fn references_error(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_ERROR)
}
fn has_param_types_or_consts(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM)
}
fn has_infer_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_INFER)
}
fn has_infer_types(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_INFER)
}
fn has_infer_types_or_consts(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER)
}
fn needs_infer(&self) -> bool {
self.has_type_flags(TypeFlags::NEEDS_INFER)
}
fn has_placeholders(&self) -> bool {
self.has_type_flags(
TypeFlags::HAS_RE_PLACEHOLDER
| TypeFlags::HAS_TY_PLACEHOLDER
| TypeFlags::HAS_CT_PLACEHOLDER,
)
}
fn needs_subst(&self) -> bool {
self.has_type_flags(TypeFlags::NEEDS_SUBST)
}
/// "Free" regions in this context means that it has any region
/// that is not (a) erased or (b) late-bound.
fn has_free_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
}
fn has_erased_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_ERASED)
}
/// True if there are any un-erased free regions.
fn has_erasable_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_FREE_REGIONS)
}
/// Indicates whether this value references only 'global'
/// generic parameters that are the same regardless of what fn we are
/// in. This is used for caching.
fn is_global(&self) -> bool {
!self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES)
}
/// True if there are any late-bound regions
fn has_late_bound_regions(&self) -> bool {
self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND)
}
/// Indicates whether this value still has parameters/placeholders/inference variables
/// which could be replaced later, in a way that would change the results of `impl`
/// specialization.
fn still_further_specializable(&self) -> bool {
self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
}
}
impl TypeFoldable<'tcx> for hir::Constness {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
*self
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> ControlFlow<V::BreakTy> {
ControlFlow::CONTINUE
}
}
/// The `TypeFolder` trait defines the actual *folding*. There is a
/// method defined for every foldable type. Each of these has a
/// default implementation that does an "identity" fold. Within each
/// identity fold, it should invoke `foo.fold_with(self)` to fold each
/// sub-item.
pub trait TypeFolder<'tcx>: Sized {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
fn fold_binder<T>(&mut self, t: &Binder<T>) -> Binder<T>
where
T: TypeFoldable<'tcx>,
{
t.super_fold_with(self)
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
t.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
r.super_fold_with(self)
}
fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
c.super_fold_with(self)
}
}
pub trait TypeVisitor<'tcx>: Sized {
type BreakTy = !;
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
t.super_visit_with(self)
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
t.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
r.super_visit_with(self)
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
c.super_visit_with(self)
}
fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
p.super_visit_with(self)
}
}
///////////////////////////////////////////////////////////////////////////
// Some sample folders
pub struct BottomUpFolder<'tcx, F, G, H>
where
F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
{
pub tcx: TyCtxt<'tcx>,
pub ty_op: F,
pub lt_op: G,
pub ct_op: H,
}
impl<'tcx, F, G, H> TypeFolder<'tcx> for BottomUpFolder<'tcx, F, G, H>
where
F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>,
H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>,
{
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let t = ty.super_fold_with(self);
(self.ty_op)(t)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
let r = r.super_fold_with(self);
(self.lt_op)(r)
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
let ct = ct.super_fold_with(self);
(self.ct_op)(ct)
}
}
///////////////////////////////////////////////////////////////////////////
// Region folder
impl<'tcx> TyCtxt<'tcx> {
/// Folds the escaping and free regions in `value` using `f`, and
/// sets `skipped_regions` to true if any late-bound region was found
/// and skipped.
pub fn fold_regions<T>(
self,
value: &T,
skipped_regions: &mut bool,
mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
) -> T
where
T: TypeFoldable<'tcx>,
{
value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f))
}
/// Invoke `callback` on every region appearing free in `value`.
pub fn for_each_free_region(
self,
value: &impl TypeFoldable<'tcx>,
mut callback: impl FnMut(ty::Region<'tcx>),
) {
self.any_free_region_meets(value, |r| {
callback(r);
false
});
}
/// Returns `true` if `callback` returns true for every region appearing free in `value`.
pub fn all_free_regions_meet(
self,
value: &impl TypeFoldable<'tcx>,
mut callback: impl FnMut(ty::Region<'tcx>) -> bool,
) -> bool {
!self.any_free_region_meets(value, |r| !callback(r))
}
/// Returns `true` if `callback` returns true for some region appearing free in `value`.
pub fn any_free_region_meets(
self,
value: &impl TypeFoldable<'tcx>,
callback: impl FnMut(ty::Region<'tcx>) -> bool,
) -> bool {
struct RegionVisitor<F> {
/// The index of a binder *just outside* the things we have
/// traversed. If we encounter a bound region bound by this
/// binder or one outer to it, it appears free. Example:
///
/// ```
/// for<'a> fn(for<'b> fn(), T)
/// ^ ^ ^ ^
/// | | | | here, would be shifted in 1
/// | | | here, would be shifted in 2
/// | | here, would be `INNERMOST` shifted in by 1
/// | here, initially, binder would be `INNERMOST`
/// ```
///
/// You see that, initially, *any* bound value is free,
/// because we've not traversed any binders. As we pass
/// through a binder, we shift the `outer_index` by 1 to
/// account for the new binder that encloses us.
outer_index: ty::DebruijnIndex,
callback: F,
}
impl<'tcx, F> TypeVisitor<'tcx> for RegionVisitor<F>
where
F: FnMut(ty::Region<'tcx>) -> bool,
{
type BreakTy = ();
fn visit_binder<T: TypeFoldable<'tcx>>(
&mut self,
t: &Binder<T>,
) -> ControlFlow<Self::BreakTy> {
self.outer_index.shift_in(1);
let result = t.as_ref().skip_binder().visit_with(self);
self.outer_index.shift_out(1);
result
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
match *r {
ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => {
ControlFlow::CONTINUE
}
_ => {
if (self.callback)(r) {
ControlFlow::BREAK
} else {
ControlFlow::CONTINUE
}
}
}
}
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// We're only interested in types involving regions
if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) {
ty.super_visit_with(self)
} else {
ControlFlow::CONTINUE
}
}
}
value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break()
}
}
/// Folds over the substructure of a type, visiting its component
/// types and all regions that occur *free* within it.
///
/// That is, `Ty` can contain function or method types that bind
/// regions at the call site (`ReLateBound`), and occurrences of
/// regions (aka "lifetimes") that are bound within a type are not
/// visited by this folder; only regions that occur free will be
/// visited by `fld_r`.
pub struct RegionFolder<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
skipped_regions: &'a mut bool,
/// Stores the index of a binder *just outside* the stuff we have
/// visited. So this begins as INNERMOST; when we pass through a
/// binder, it is incremented (via `shift_in`).
current_index: ty::DebruijnIndex,
/// Callback invokes for each free region. The `DebruijnIndex`
/// points to the binder *just outside* the ones we have passed
/// through.
fold_region_fn:
&'a mut (dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx> + 'a),
}
impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
#[inline]
pub fn new(
tcx: TyCtxt<'tcx>,
skipped_regions: &'a mut bool,
fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>,
) -> RegionFolder<'a, 'tcx> {
RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn }
}
}
impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, _) if debruijn < self.current_index => {
debug!(
"RegionFolder.fold_region({:?}) skipped bound region (current index={:?})",
r, self.current_index
);
*self.skipped_regions = true;
r
}
_ => {
debug!(
"RegionFolder.fold_region({:?}) folding free region (current_index={:?})",
r, self.current_index
);
(self.fold_region_fn)(r, self.current_index)
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Bound vars replacer
/// Replaces the escaping bound vars (late bound regions or bound types) in a type.
struct BoundVarReplacer<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
/// As with `RegionFolder`, represents the index of a binder *just outside*
/// the ones we have visited.
current_index: ty::DebruijnIndex,
fld_r: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
fld_t: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
fld_c: &'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a),
}
impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> {
fn new<F, G, H>(tcx: TyCtxt<'tcx>, fld_r: &'a mut F, fld_t: &'a mut G, fld_c: &'a mut H) -> Self
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
{
BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c }
}
}
impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
match *t.kind() {
ty::Bound(debruijn, bound_ty) => {
if debruijn == self.current_index {
let fld_t = &mut self.fld_t;
let ty = fld_t(bound_ty);
ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32())
} else {
t
}
}
_ => {
if !t.has_vars_bound_at_or_above(self.current_index) {
// Nothing more to substitute.
t
} else {
t.super_fold_with(self)
}
}
}
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
let fld_r = &mut self.fld_r;
let region = fld_r(br);
if let ty::ReLateBound(debruijn1, br) = *region {
// If the callback returns a late-bound region,
// that region should always use the INNERMOST
// debruijn index. Then we adjust it to the
// correct depth.
assert_eq!(debruijn1, ty::INNERMOST);
self.tcx.mk_region(ty::ReLateBound(debruijn, br))
} else {
region
}
}
_ => r,
}
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } = *ct {
if debruijn == self.current_index {
let fld_c = &mut self.fld_c;
let ct = fld_c(bound_const, ty);
ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32())
} else {
ct
}
} else {
if !ct.has_vars_bound_at_or_above(self.current_index) {
// Nothing more to substitute.
ct
} else {
ct.super_fold_with(self)
}
}
}
}
impl<'tcx> TyCtxt<'tcx> {
/// Replaces all regions bound by the given `Binder` with the
/// results returned by the closure; the closure is expected to
/// return a free region (relative to this binder), and hence the
/// binder is removed in the return type. The closure is invoked
/// once for each unique `BoundRegion`; multiple references to the
/// same `BoundRegion` will reuse the previous result. A map is
/// returned at the end with each bound region and the free region
/// that replaced it.
///
/// This method only replaces late bound regions and the result may still
/// contain escaping bound types.
pub fn replace_late_bound_regions<T, F>(
self,
value: &Binder<T>,
fld_r: F,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
T: TypeFoldable<'tcx>,
{
// identity for bound types and consts
let fld_t = |bound_ty| self.mk_ty(ty::Bound(ty::INNERMOST, bound_ty));
let fld_c = |bound_ct, ty| {
self.mk_const(ty::Const { val: ty::ConstKind::Bound(ty::INNERMOST, bound_ct), ty })
};
self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
}
/// Replaces all escaping bound vars. The `fld_r` closure replaces escaping
/// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c`
/// closure replaces escaping bound consts.
pub fn replace_escaping_bound_vars<T, F, G, H>(
self,
value: &T,
mut fld_r: F,
mut fld_t: G,
mut fld_c: H,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
T: TypeFoldable<'tcx>,
{
use rustc_data_structures::fx::FxHashMap;
let mut region_map = BTreeMap::new();
let mut type_map = FxHashMap::default();
let mut const_map = FxHashMap::default();
if !value.has_escaping_bound_vars() {
(value.clone(), region_map)
} else {
let mut real_fld_r = |br| *region_map.entry(br).or_insert_with(|| fld_r(br));
let mut real_fld_t =
|bound_ty| *type_map.entry(bound_ty).or_insert_with(|| fld_t(bound_ty));
let mut real_fld_c =
|bound_ct, ty| *const_map.entry(bound_ct).or_insert_with(|| fld_c(bound_ct, ty));
let mut replacer =
BoundVarReplacer::new(self, &mut real_fld_r, &mut real_fld_t, &mut real_fld_c);
let result = value.fold_with(&mut replacer);
(result, region_map)
}
}
/// Replaces all types or regions bound by the given `Binder`. The `fld_r`
/// closure replaces bound regions while the `fld_t` closure replaces bound
/// types.
pub fn replace_bound_vars<T, F, G, H>(
self,
value: &Binder<T>,
fld_r: F,
fld_t: G,
fld_c: H,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
G: FnMut(ty::BoundTy) -> Ty<'tcx>,
H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>,
T: TypeFoldable<'tcx>,
{
self.replace_escaping_bound_vars(value.as_ref().skip_binder(), fld_r, fld_t, fld_c)
}
/// Replaces any late-bound regions bound in `value` with
/// free variants attached to `all_outlive_scope`.
pub fn liberate_late_bound_regions<T>(
self,
all_outlive_scope: DefId,
value: &ty::Binder<T>,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.replace_late_bound_regions(value, |br| {
self.mk_region(ty::ReFree(ty::FreeRegion {
scope: all_outlive_scope,
bound_region: br,
}))
})
.0
}
/// Returns a set of all late-bound regions that are constrained
/// by `value`, meaning that if we instantiate those LBR with
/// variables and equate `value` with something else, those
/// variables will also be equated.
pub fn collect_constrained_late_bound_regions<T>(
self,
value: &Binder<T>,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
self.collect_late_bound_regions(value, true)
}
/// Returns a set of all late-bound regions that appear in `value` anywhere.
pub fn collect_referenced_late_bound_regions<T>(
self,
value: &Binder<T>,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
self.collect_late_bound_regions(value, false)
}
fn collect_late_bound_regions<T>(
self,
value: &Binder<T>,
just_constraint: bool,
) -> FxHashSet<ty::BoundRegion>
where
T: TypeFoldable<'tcx>,
{
let mut collector = LateBoundRegionsCollector::new(just_constraint);
let result = value.as_ref().skip_binder().visit_with(&mut collector);
assert!(result.is_continue()); // should never have stopped early
collector.regions
}
/// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also
/// method lookup and a few other places where precise region relationships are not required.
pub fn erase_late_bound_regions<T>(self, value: &Binder<T>) -> T
where
T: TypeFoldable<'tcx>,
{
self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0
}
/// Rewrite any late-bound regions so that they are anonymous. Region numbers are
/// assigned starting at 0 and increasing monotonically in the order traversed
/// by the fold operation.
///
/// The chief purpose of this function is to canonicalize regions so that two
/// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
/// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and
/// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization.
pub fn anonymize_late_bound_regions<T>(self, sig: &Binder<T>) -> Binder<T>
where
T: TypeFoldable<'tcx>,
{
let mut counter = 0;
Binder::bind(
self.replace_late_bound_regions(sig, |_| {
let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(counter)));
counter += 1;
r
})
.0,
)
}
}
///////////////////////////////////////////////////////////////////////////
// Shifter
//
// Shifts the De Bruijn indices on all escaping bound vars by a
// fixed amount. Useful in substitution or when otherwise introducing
// a binding level that is not intended to capture the existing bound
// vars. See comment on `shift_vars_through_binders` method in
// `subst.rs` for more details.
struct Shifter<'tcx> {
tcx: TyCtxt<'tcx>,
current_index: ty::DebruijnIndex,
amount: u32,
}
impl Shifter<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self {
Shifter { tcx, current_index: ty::INNERMOST, amount }
}
}
impl TypeFolder<'tcx> for Shifter<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
self.current_index.shift_in(1);
let t = t.super_fold_with(self);
self.current_index.shift_out(1);
t
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
match *r {
ty::ReLateBound(debruijn, br) => {
if self.amount == 0 || debruijn < self.current_index {
r
} else {
let debruijn = debruijn.shifted_in(self.amount);
let shifted = ty::ReLateBound(debruijn, br);
self.tcx.mk_region(shifted)
}
}
_ => r,
}
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
match *ty.kind() {
ty::Bound(debruijn, bound_ty) => {
if self.amount == 0 || debruijn < self.current_index {
ty
} else {
let debruijn = debruijn.shifted_in(self.amount);
self.tcx.mk_ty(ty::Bound(debruijn, bound_ty))
}
}
_ => ty.super_fold_with(self),
}
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct {
if self.amount == 0 || debruijn < self.current_index {
ct
} else {
let debruijn = debruijn.shifted_in(self.amount);
self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty })
}
} else {
ct.super_fold_with(self)
}
}
}
pub fn shift_region<'tcx>(
tcx: TyCtxt<'tcx>,
region: ty::Region<'tcx>,
amount: u32,
) -> ty::Region<'tcx> {
match region {
ty::ReLateBound(debruijn, br) if amount > 0 => {
tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br))
}
_ => region,
}
}
pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: &T, amount: u32) -> T
where
T: TypeFoldable<'tcx>,
{
debug!("shift_vars(value={:?}, amount={})", value, amount);
value.fold_with(&mut Shifter::new(tcx, amount))
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct FoundEscapingVars;
/// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a
/// bound region or a bound type.
///
/// So, for example, consider a type like the following, which has two binders:
///
/// for<'a> fn(x: for<'b> fn(&'a isize, &'b isize))
/// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
/// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ inner scope
///
/// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
/// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
/// fn type*, that type has an escaping region: `'a`.
///
/// Note that what I'm calling an "escaping var" is often just called a "free var". However,
/// we already use the term "free var". It refers to the regions or types that we use to represent
/// bound regions or type params on a fn definition while we are type checking its body.
///
/// To clarify, conceptually there is no particular difference between
/// an "escaping" var and a "free" var. However, there is a big
/// difference in practice. Basically, when "entering" a binding
/// level, one is generally required to do some sort of processing to
/// a bound var, such as replacing it with a fresh/placeholder
/// var, or making an entry in the environment to represent the
/// scope to which it is attached, etc. An escaping var represents
/// a bound var for which this processing has not yet been done.
struct HasEscapingVarsVisitor {
/// Anything bound by `outer_index` or "above" is escaping.
outer_index: ty::DebruijnIndex,
}
impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor {
type BreakTy = FoundEscapingVars;
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
self.outer_index.shift_in(1);
let result = t.super_visit_with(self);
self.outer_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// If the outer-exclusive-binder is *strictly greater* than
// `outer_index`, that means that `t` contains some content
// bound at `outer_index` or above (because
// `outer_exclusive_binder` is always 1 higher than the
// content in `t`). Therefore, `t` has some escaping vars.
if t.outer_exclusive_binder > self.outer_index {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
// If the region is bound by `outer_index` or anything outside
// of outer index, then it escapes the binders we have
// visited.
if r.bound_at_or_above_binder(self.outer_index) {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
// we don't have a `visit_infer_const` callback, so we have to
// hook in here to catch this case (annoying...), but
// otherwise we do want to remember to visit the rest of the
// const, as it has types/regions embedded in a lot of other
// places.
match ct.val {
ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => {
ControlFlow::Break(FoundEscapingVars)
}
_ => ct.super_visit_with(self),
}
}
fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
if predicate.inner.outer_exclusive_binder > self.outer_index {
ControlFlow::Break(FoundEscapingVars)
} else {
ControlFlow::CONTINUE
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct FoundFlags;
// FIXME: Optimize for checking for infer flags
struct HasTypeFlagsVisitor {
flags: ty::TypeFlags,
}
impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
type BreakTy = FoundFlags;
fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow<Self::BreakTy> {
debug!(
"HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}",
t,
t.flags(),
self.flags
);
if t.flags().intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
let flags = r.type_flags();
debug!("HasTypeFlagsVisitor: r={:?} r.flags={:?} self.flags={:?}", r, flags, self.flags);
if flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
let flags = FlagComputation::for_const(c);
debug!("HasTypeFlagsVisitor: c={:?} c.flags={:?} self.flags={:?}", c, flags, self.flags);
if flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
debug!(
"HasTypeFlagsVisitor: predicate={:?} predicate.flags={:?} self.flags={:?}",
predicate, predicate.inner.flags, self.flags
);
if predicate.inner.flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}
}
/// Collects all the late-bound regions at the innermost binding level
/// into a hash set.
struct LateBoundRegionsCollector {
current_index: ty::DebruijnIndex,
regions: FxHashSet<ty::BoundRegion>,
/// `true` if we only want regions that are known to be
/// "constrained" when you equate this type with another type. In
/// particular, if you have e.g., `&'a u32` and `&'b u32`, equating
/// them constraints `'a == 'b`. But if you have `<&'a u32 as
/// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those
/// types may mean that `'a` and `'b` don't appear in the results,
/// so they are not considered *constrained*.
just_constrained: bool,
}
impl LateBoundRegionsCollector {
fn new(just_constrained: bool) -> Self {
LateBoundRegionsCollector {
current_index: ty::INNERMOST,
regions: Default::default(),
just_constrained,
}
}
}
impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<Self::BreakTy> {
self.current_index.shift_in(1);
let result = t.super_visit_with(self);
self.current_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// if we are only looking for "constrained" region, we have to
// ignore the inputs to a projection, as they may not appear
// in the normalized form
if self.just_constrained {
if let ty::Projection(..) | ty::Opaque(..) = t.kind() {
return ControlFlow::CONTINUE;
}
}
t.super_visit_with(self)
}
fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
// if we are only looking for "constrained" region, we have to
// ignore the inputs of an unevaluated const, as they may not appear
// in the normalized form
if self.just_constrained {
if let ty::ConstKind::Unevaluated(..) = c.val {
return ControlFlow::CONTINUE;
}
}
c.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
if let ty::ReLateBound(debruijn, br) = *r {
if debruijn == self.current_index {
self.regions.insert(br);
}
}
ControlFlow::CONTINUE
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositor_layer::{CompositorData, CompositorLayer, DoesntWantScrollEvents};
use compositor_layer::{WantsScrollEvents};
use compositor_task;
use compositor_task::{ChangePageLoadData, ChangePageTitle, ChangePaintState, ChangeReadyState};
use compositor_task::{CompositorEventListener, CompositorProxy, CompositorReceiver};
use compositor_task::{CompositorTask, CreateOrUpdateDescendantLayer, CreateOrUpdateRootLayer};
use compositor_task::{Exit, FrameTreeUpdateMsg, GetGraphicsMetadata, LayerProperties};
use compositor_task::{LoadComplete, Msg, Paint, PaintMsgDiscarded, ScrollFragmentPoint};
use compositor_task::{ScrollTimeout, SetIds, SetLayerOrigin, ShutdownComplete};
use constellation::{FrameId, FrameTreeDiff, SendableFrameTree};
use pipeline::CompositionPipeline;
use scrolling::ScrollingTimerProxy;
use windowing;
use windowing::{IdleWindowEvent, InitializeCompositingWindowEvent};
use windowing::{KeyEvent, LoadUrlWindowEvent, MouseWindowClickEvent, MouseWindowEvent};
use windowing::{MouseWindowEventClass, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use windowing::{MouseWindowMoveEventClass, NavigationWindowEvent, PinchZoomWindowEvent};
use windowing::{QuitWindowEvent, RefreshWindowEvent, ResizeWindowEvent, ScrollWindowEvent};
use windowing::{WindowEvent, WindowMethods, WindowNavigateMsg, ZoomWindowEvent};
use azure::azure_hl;
use std::cmp;
use std::mem;
use std::num::Zero;
use geom::point::{Point2D, TypedPoint2D};
use geom::rect::{Rect, TypedRect};
use geom::size::TypedSize2D;
use geom::scale_factor::ScaleFactor;
use gfx::paint_task::{PaintChan, PaintMsg, PaintRequest, UnusedBufferMsg};
use layers::geometry::{DevicePixel, LayerPixel};
use layers::layers::{BufferRequest, Layer, LayerBufferSet};
use layers::rendergl;
use layers::rendergl::RenderContext;
use layers::scene::Scene;
use png;
use gleam::gl::types::{GLint, GLsizei};
use gleam::gl;
use script_traits::{ViewportMsg, ScriptControlChan};
use servo_msg::compositor_msg::{Blank, Epoch, FinishedLoading, IdlePaintState, LayerId};
use servo_msg::compositor_msg::{ReadyState, PaintState, PaintingPaintState, Scrollable};
use servo_msg::constellation_msg::{mod, ConstellationChan, ExitMsg};
use servo_msg::constellation_msg::{GetPipelineTitleMsg, Key, KeyModifiers, KeyState, LoadData};
use servo_msg::constellation_msg::{LoadUrlMsg, NavigateMsg, PipelineId, ResizedWindowMsg};
use servo_msg::constellation_msg::{WindowSizeData};
use servo_util::geometry::{PagePx, ScreenPx, ViewportPx};
use servo_util::memory::MemoryProfilerChan;
use servo_util::opts;
use servo_util::time::{profile, TimeProfilerChan};
use servo_util::{memory, time};
use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant};
use std::path::Path;
use std::rc::Rc;
use std::slice::bytes::copy_memory;
use time::{precise_time_ns, precise_time_s};
use url::Url;
/// NB: Never block on the constellation, because sometimes the constellation blocks on us.
pub struct IOCompositor<Window: WindowMethods> {
/// The application window.
window: Rc<Window>,
/// The port on which we receive messages.
port: Box<CompositorReceiver>,
/// The render context. This will be `None` if the windowing system has not yet sent us a
/// `PrepareRenderingEvent`.
context: Option<RenderContext>,
/// The root pipeline.
root_pipeline: Option<CompositionPipeline>,
/// The canvas to paint a page.
scene: Scene<CompositorData>,
/// The application window size.
window_size: TypedSize2D<DevicePixel, uint>,
/// "Mobile-style" zoom that does not reflow the page.
viewport_zoom: ScaleFactor<PagePx, ViewportPx, f32>,
/// "Desktop-style" zoom that resizes the viewport to fit the window.
/// See `ViewportPx` docs in util/geom.rs for details.
page_zoom: ScaleFactor<ViewportPx, ScreenPx, f32>,
/// The device pixel ratio for this window.
hidpi_factor: ScaleFactor<ScreenPx, DevicePixel, f32>,
/// A handle to the scrolling timer.
scrolling_timer: ScrollingTimerProxy,
/// Tracks whether we should composite this frame.
composition_request: CompositionRequest,
/// Tracks whether we are in the process of shutting down, or have shut down and should close
/// the compositor.
shutdown_state: ShutdownState,
/// Tracks outstanding paint_msg's sent to the paint tasks.
outstanding_paint_msgs: uint,
/// Tracks the last composite time.
last_composite_time: u64,
/// Tracks whether the zoom action has happened recently.
zoom_action: bool,
/// The time of the last zoom action has started.
zoom_time: f64,
/// Current display/reflow status of each pipeline.
ready_states: HashMap<PipelineId, ReadyState>,
/// Current paint status of each pipeline.
paint_states: HashMap<PipelineId, PaintState>,
/// Whether the page being rendered has loaded completely.
/// Differs from ReadyState because we can finish loading (ready)
/// many times for a single page.
got_load_complete_message: bool,
/// Whether we have gotten a `SetIds` message.
got_set_ids_message: bool,
/// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan,
/// The channel on which messages can be sent to the time profiler.
time_profiler_chan: TimeProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
memory_profiler_chan: MemoryProfilerChan,
/// Pending scroll to fragment event, if any
fragment_point: Option<Point2D<f32>>,
/// Pending scroll events.
pending_scroll_events: Vec<ScrollEvent>,
}
pub struct ScrollEvent {
delta: TypedPoint2D<DevicePixel,f32>,
cursor: TypedPoint2D<DevicePixel,i32>,
}
#[deriving(PartialEq)]
enum CompositionRequest {
NoCompositingNecessary,
CompositeOnScrollTimeout(u64),
CompositeNow,
}
#[deriving(PartialEq, Show)]
enum ShutdownState {
NotShuttingDown,
ShuttingDown,
FinishedShuttingDown,
}
struct HitTestResult {
layer: Rc<Layer<CompositorData>>,
point: TypedPoint2D<LayerPixel, f32>,
}
impl<Window: WindowMethods> IOCompositor<Window> {
fn new(window: Rc<Window>,
sender: Box<CompositorProxy+Send>,
receiver: Box<CompositorReceiver>,
constellation_chan: ConstellationChan,
time_profiler_chan: TimeProfilerChan,
memory_profiler_chan: MemoryProfilerChan)
-> IOCompositor<Window> {
// Create an initial layer tree.
//
// TODO: There should be no initial layer tree until the painter creates one from the
// display list. This is only here because we don't have that logic in the painter yet.
let window_size = window.framebuffer_size();
let hidpi_factor = window.hidpi_factor();
IOCompositor {
window: window,
port: receiver,
context: None,
root_pipeline: None,
scene: Scene::new(Rect {
origin: Zero::zero(),
size: window_size.as_f32(),
}),
window_size: window_size,
hidpi_factor: hidpi_factor,
scrolling_timer: ScrollingTimerProxy::new(sender),
composition_request: NoCompositingNecessary,
pending_scroll_events: Vec::new(),
shutdown_state: NotShuttingDown,
page_zoom: ScaleFactor(1.0),
viewport_zoom: ScaleFactor(1.0),
zoom_action: false,
zoom_time: 0f64,
ready_states: HashMap::new(),
paint_states: HashMap::new(),
got_load_complete_message: false,
got_set_ids_message: false,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
memory_profiler_chan: memory_profiler_chan,
fragment_point: None,
outstanding_paint_msgs: 0,
last_composite_time: 0,
}
}
pub fn create(window: Rc<Window>,
sender: Box<CompositorProxy+Send>,
receiver: Box<CompositorReceiver>,
constellation_chan: ConstellationChan,
time_profiler_chan: TimeProfilerChan,
memory_profiler_chan: MemoryProfilerChan)
-> IOCompositor<Window> {
let mut compositor = IOCompositor::new(window,
sender,
receiver,
constellation_chan,
time_profiler_chan,
memory_profiler_chan);
// Set the size of the root layer.
compositor.update_zoom_transform();
// Tell the constellation about the initial window size.
compositor.send_window_size();
compositor
}
fn handle_browser_message(&mut self, msg: Msg) -> bool {
match (msg, self.shutdown_state) {
(_, FinishedShuttingDown) =>
panic!("compositor shouldn't be handling messages after shutting down"),
(Exit(chan), _) => {
debug!("shutting down the constellation");
let ConstellationChan(ref con_chan) = self.constellation_chan;
con_chan.send(ExitMsg);
chan.send(());
self.shutdown_state = ShuttingDown;
}
(ShutdownComplete, _) => {
debug!("constellation completed shutdown");
self.shutdown_state = FinishedShuttingDown;
return false;
}
(ChangeReadyState(pipeline_id, ready_state), NotShuttingDown) => {
self.change_ready_state(pipeline_id, ready_state);
}
(ChangePaintState(pipeline_id, paint_state), NotShuttingDown) => {
self.change_paint_state(pipeline_id, paint_state);
}
(ChangePageTitle(pipeline_id, title), NotShuttingDown) => {
self.change_page_title(pipeline_id, title);
}
(ChangePageLoadData(frame_id, load_data), NotShuttingDown) => {
self.change_page_load_data(frame_id, load_data);
}
(PaintMsgDiscarded, NotShuttingDown) => {
self.remove_outstanding_paint_msg();
}
(SetIds(frame_tree, response_chan, new_constellation_chan), NotShuttingDown) => {
self.set_frame_tree(&frame_tree,
response_chan,
new_constellation_chan);
self.send_viewport_rects_for_all_layers();
}
(FrameTreeUpdateMsg(frame_tree_diff, response_channel), NotShuttingDown) => {
self.update_frame_tree(&frame_tree_diff);
response_channel.send(());
}
(CreateOrUpdateRootLayer(layer_properties), NotShuttingDown) => {
self.create_or_update_root_layer(layer_properties);
}
(CreateOrUpdateDescendantLayer(layer_properties), NotShuttingDown) => {
self.create_or_update_descendant_layer(layer_properties);
}
(GetGraphicsMetadata(chan), NotShuttingDown) => {
chan.send(Some(self.window.native_metadata()));
}
(SetLayerOrigin(pipeline_id, layer_id, origin), NotShuttingDown) => {
self.set_layer_origin(pipeline_id, layer_id, origin);
}
(Paint(pipeline_id, epoch, replies), NotShuttingDown) => {
for (layer_id, new_layer_buffer_set) in replies.into_iter() {
self.paint(pipeline_id, layer_id, new_layer_buffer_set, epoch);
}
self.remove_outstanding_paint_msg();
}
(ScrollFragmentPoint(pipeline_id, layer_id, point), NotShuttingDown) => {
self.scroll_fragment_to_point(pipeline_id, layer_id, point);
}
(LoadComplete, NotShuttingDown) => {
self.got_load_complete_message = true;
// If we're painting in headless mode, schedule a recomposite.
if opts::get().output_file.is_some() {
self.composite_if_necessary();
}
// Inform the embedder that the load has finished.
//
// TODO(pcwalton): Specify which frame's load completed.
self.window.load_end();
}
(ScrollTimeout(timestamp), NotShuttingDown) => {
debug!("scroll timeout, drawing unpainted content!");
match self.composition_request {
CompositeOnScrollTimeout(this_timestamp) if timestamp == this_timestamp => {
self.composition_request = CompositeNow
}
_ => {}
}
}
(compositor_task::KeyEvent(key, modified), NotShuttingDown) => {
self.window.handle_key(key, modified);
}
// When we are shutting_down, we need to avoid performing operations
// such as Paint that may crash because we have begun tearing down
// the rest of our resources.
(_, ShuttingDown) => { }
}
true
}
fn change_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) {
match self.ready_states.entry(pipeline_id) {
Occupied(entry) => {
*entry.into_mut() = ready_state;
}
Vacant(entry) => {
entry.set(ready_state);
}
}
self.window.set_ready_state(self.get_earliest_pipeline_ready_state());
// If we're painting in headless mode, schedule a recomposite.
if opts::get().output_file.is_some() {
self.composite_if_necessary()
}
}
fn get_earliest_pipeline_ready_state(&self) -> ReadyState {
if self.ready_states.len() == 0 {
return Blank;
}
return self.ready_states.values().fold(FinishedLoading, |a, &b| cmp::min(a, b));
}
fn change_paint_state(&mut self, pipeline_id: PipelineId, paint_state: PaintState) {
match self.paint_states.entry(pipeline_id) {
Occupied(entry) => {
*entry.into_mut() = paint_state;
}
Vacant(entry) => {
entry.set(paint_state);
}
}
self.window.set_paint_state(paint_state);
}
fn change_page_title(&mut self, _: PipelineId, title: Option<String>) {
self.window.set_page_title(title);
}
fn change_page_load_data(&mut self, _: FrameId, load_data: LoadData) {
self.window.set_page_load_data(load_data);
}
fn all_pipelines_in_idle_paint_state(&self) -> bool {
if self.ready_states.len() == 0 {
return false;
}
return self.paint_states.values().all(|&value| value == IdlePaintState);
}
fn has_paint_msg_tracking(&self) -> bool {
// only track PaintMsg's if the compositor outputs to a file.
opts::get().output_file.is_some()
}
fn has_outstanding_paint_msgs(&self) -> bool {
self.has_paint_msg_tracking() && self.outstanding_paint_msgs > 0
}
fn add_outstanding_paint_msg(&mut self, count: uint) {
// return early if not tracking paint_msg's
if !self.has_paint_msg_tracking() {
return;
}
debug!("add_outstanding_paint_msg {}", self.outstanding_paint_msgs);
self.outstanding_paint_msgs += count;
}
fn remove_outstanding_paint_msg(&mut self) {
if !self.has_paint_msg_tracking() {
return;
}
if self.outstanding_paint_msgs > 0 {
self.outstanding_paint_msgs -= 1;
} else {
debug!("too many repaint msgs completed");
}
}
fn set_frame_tree(&mut self,
frame_tree: &SendableFrameTree,
response_chan: Sender<()>,
new_constellation_chan: ConstellationChan) {
response_chan.send(());
self.root_pipeline = Some(frame_tree.pipeline.clone());
// If we have an old root layer, release all old tiles before replacing it.
match self.scene.root {
Some(ref mut layer) => layer.clear_all_tiles(),
None => { }
}
self.scene.root = Some(self.create_frame_tree_root_layers(frame_tree, None));
self.scene.set_root_layer_size(self.window_size.as_f32());
// Initialize the new constellation channel by sending it the root window size.
self.constellation_chan = new_constellation_chan;
self.send_window_size();
self.got_set_ids_message = true;
self.composite_if_necessary();
}
fn create_frame_tree_root_layers(&mut self,
frame_tree: &SendableFrameTree,
frame_rect: Option<TypedRect<PagePx, f32>>)
-> Rc<Layer<CompositorData>> {
// Initialize the ReadyState and PaintState for this pipeline.
self.ready_states.insert(frame_tree.pipeline.id, Blank);
self.paint_states.insert(frame_tree.pipeline.id, PaintingPaintState);
let root_layer = create_root_layer_for_pipeline_and_rect(&frame_tree.pipeline, frame_rect);
for kid in frame_tree.children.iter() {
root_layer.add_child(self.create_frame_tree_root_layers(&kid.frame_tree, kid.rect));
}
return root_layer;
}
fn update_frame_tree(&mut self, frame_tree_diff: &FrameTreeDiff) {
let parent_layer = self.find_pipeline_root_layer(frame_tree_diff.parent_pipeline.id);
parent_layer.add_child(
create_root_layer_for_pipeline_and_rect(&frame_tree_diff.pipeline,
frame_tree_diff.rect));
}
fn find_pipeline_root_layer(&self, pipeline_id: PipelineId) -> Rc<Layer<CompositorData>> {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, LayerId::null()) {
Some(ref layer) => layer.clone(),
None => panic!("Tried to create or update layer for unknown pipeline"),
}
}
fn update_layer_if_exists(&mut self, properties: LayerProperties) -> bool {
match self.find_layer_with_pipeline_and_layer_id(properties.pipeline_id, properties.id) {
Some(existing_layer) => {
existing_layer.update_layer(properties);
true
}
None => false,
}
}
fn create_or_update_root_layer(&mut self, layer_properties: LayerProperties) {
let need_new_root_layer = !self.update_layer_if_exists(layer_properties);
if need_new_root_layer {
let root_layer = self.find_pipeline_root_layer(layer_properties.pipeline_id);
root_layer.update_layer_except_size(layer_properties);
let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone();
let first_child = CompositorData::new_layer(root_layer_pipeline.clone(),
layer_properties,
DoesntWantScrollEvents,
opts::get().tile_size);
// Add the first child / base layer to the front of the child list, so that
// child iframe layers are painted on top of the base layer. These iframe
// layers were added previously when creating the layer tree skeleton in
// create_frame_tree_root_layers.
root_layer.children().insert(0, first_child);
}
self.scroll_layer_to_fragment_point_if_necessary(layer_properties.pipeline_id,
layer_properties.id);
self.send_buffer_requests_for_all_layers();
}
fn create_or_update_descendant_layer(&mut self, layer_properties: LayerProperties) {
if !self.update_layer_if_exists(layer_properties) {
self.create_descendant_layer(layer_properties);
}
self.scroll_layer_to_fragment_point_if_necessary(layer_properties.pipeline_id,
layer_properties.id);
self.send_buffer_requests_for_all_layers();
}
fn create_descendant_layer(&self, layer_properties: LayerProperties) {
let root_layer = self.find_pipeline_root_layer(layer_properties.pipeline_id);
let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone();
let new_layer = CompositorData::new_layer(root_layer_pipeline,
layer_properties,
DoesntWantScrollEvents,
root_layer.tile_size);
root_layer.add_child(new_layer);
}
fn send_window_size(&self) {
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let initial_viewport = self.window_size.as_f32() / dppx;
let visible_viewport = initial_viewport / self.viewport_zoom;
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ResizedWindowMsg(WindowSizeData {
device_pixel_ratio: dppx,
initial_viewport: initial_viewport,
visible_viewport: visible_viewport,
}));
}
pub fn move_layer(&self,
pipeline_id: PipelineId,
layer_id: LayerId,
origin: TypedPoint2D<LayerPixel, f32>)
-> bool {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
if layer.extra_data.borrow().wants_scroll_events == WantsScrollEvents {
layer.clamp_scroll_offset_and_scroll_layer(TypedPoint2D(0f32, 0f32) - origin);
}
true
}
None => false,
}
}
fn scroll_layer_to_fragment_point_if_necessary(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId) {
match self.fragment_point.take() {
Some(point) => {
if !self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
panic!("Compositor: Tried to scroll to fragment with unknown layer.");
}
self.start_scrolling_timer_if_necessary();
}
None => {}
}
}
fn start_scrolling_timer_if_necessary(&mut self) {
match self.composition_request {
CompositeNow | CompositeOnScrollTimeout(_) => return,
NoCompositingNecessary => {}
}
let timestamp = precise_time_ns();
self.scrolling_timer.scroll_event_processed(timestamp);
self.composition_request = CompositeOnScrollTimeout(timestamp);
}
fn set_layer_origin(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
new_origin: Point2D<f32>) {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
layer.bounds.borrow_mut().origin = Point2D::from_untyped(&new_origin)
}
None => panic!("Compositor received SetLayerOrigin for nonexistent layer"),
};
self.send_buffer_requests_for_all_layers();
}
fn paint(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
new_layer_buffer_set: Box<LayerBufferSet>,
epoch: Epoch) {
debug!("compositor received new frame at size {}x{}",
self.window_size.width.get(),
self.window_size.height.get());
// From now on, if we destroy the buffers, they will leak.
let mut new_layer_buffer_set = new_layer_buffer_set;
new_layer_buffer_set.mark_will_leak();
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
// FIXME(pcwalton): This is going to cause problems with inconsistent frames since
// we only composite one layer at a time.
assert!(layer.add_buffers(new_layer_buffer_set, epoch));
self.composite_if_necessary();
}
None => {
// FIXME: This may potentially be triggered by a race condition where a
// buffers are being painted but the layer is removed before painting
// completes.
panic!("compositor given paint command for non-existent layer");
}
}
}
fn scroll_fragment_to_point(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
point: Point2D<f32>) {
if self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
if self.send_buffer_requests_for_all_layers() {
self.start_scrolling_timer_if_necessary();
}
} else {
self.fragment_point = Some(point);
}
}
fn handle_window_message(&mut self, event: WindowEvent) {
match event {
IdleWindowEvent => {}
RefreshWindowEvent => {
self.composite();
}
InitializeCompositingWindowEvent => {
self.initialize_compositing();
}
ResizeWindowEvent(size) => {
self.on_resize_window_event(size);
}
LoadUrlWindowEvent(url_string) => {
self.on_load_url_window_event(url_string);
}
MouseWindowEventClass(mouse_window_event) => {
self.on_mouse_window_event_class(mouse_window_event);
}
MouseWindowMoveEventClass(cursor) => {
self.on_mouse_window_move_event_class(cursor);
}
ScrollWindowEvent(delta, cursor) => {
self.on_scroll_window_event(delta, cursor);
}
ZoomWindowEvent(magnification) => {
self.on_zoom_window_event(magnification);
}
PinchZoomWindowEvent(magnification) => {
self.on_pinch_zoom_window_event(magnification);
}
NavigationWindowEvent(direction) => {
self.on_navigation_window_event(direction);
}
KeyEvent(key, state, modifiers) => {
self.on_key_event(key, state, modifiers);
}
QuitWindowEvent => {
debug!("shutting down the constellation for QuitWindowEvent");
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ExitMsg);
self.shutdown_state = ShuttingDown;
}
}
}
fn on_resize_window_event(&mut self, new_size: TypedSize2D<DevicePixel, uint>) {
debug!("compositor resizing to {}", new_size.to_untyped());
// A size change could also mean a resolution change.
let new_hidpi_factor = self.window.hidpi_factor();
if self.hidpi_factor != new_hidpi_factor {
self.hidpi_factor = new_hidpi_factor;
self.update_zoom_transform();
}
if self.window_size == new_size {
return;
}
self.window_size = new_size;
self.scene.set_root_layer_size(new_size.as_f32());
self.send_window_size();
}
fn on_load_url_window_event(&mut self, url_string: String) {
debug!("osmain: loading URL `{:s}`", url_string);
self.got_load_complete_message = false;
let root_pipeline_id = match self.scene.root {
Some(ref layer) => layer.extra_data.borrow().pipeline.id.clone(),
None => panic!("Compositor: Received LoadUrlWindowEvent without initialized compositor \
layers"),
};
let msg = LoadUrlMsg(root_pipeline_id,
LoadData::new(Url::parse(url_string.as_slice()).unwrap()));
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(msg);
}
fn on_mouse_window_event_class(&self, mouse_window_event: MouseWindowEvent) {
let point = match mouse_window_event {
MouseWindowClickEvent(_, p) => p,
MouseWindowMouseDownEvent(_, p) => p,
MouseWindowMouseUpEvent(_, p) => p,
};
match self.find_topmost_layer_at_point(point / self.scene.scale) {
Some(result) => result.layer.send_mouse_event(mouse_window_event, result.point),
None => {},
}
}
fn on_mouse_window_move_event_class(&self, cursor: TypedPoint2D<DevicePixel, f32>) {
match self.find_topmost_layer_at_point(cursor / self.scene.scale) {
Some(result) => result.layer.send_mouse_move_event(result.point),
None => {},
}
}
fn on_scroll_window_event(&mut self,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, i32>) {
self.pending_scroll_events.push(ScrollEvent {
delta: delta,
cursor: cursor,
});
self.composite_if_necessary();
}
fn process_pending_scroll_events(&mut self) {
let had_scroll_events = self.pending_scroll_events.len() > 0;
for scroll_event in mem::replace(&mut self.pending_scroll_events, Vec::new()).into_iter() {
let delta = scroll_event.delta / self.scene.scale;
let cursor = scroll_event.cursor.as_f32() / self.scene.scale;
match self.scene.root {
Some(ref mut layer) => {
layer.handle_scroll_event(delta, cursor);
}
None => {}
}
self.start_scrolling_timer_if_necessary();
self.send_buffer_requests_for_all_layers();
}
if had_scroll_events {
self.send_viewport_rects_for_all_layers();
}
}
fn device_pixels_per_screen_px(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
match opts::get().device_pixels_per_px {
Some(device_pixels_per_px) => device_pixels_per_px,
None => match opts::get().output_file {
Some(_) => ScaleFactor(1.0),
None => self.hidpi_factor
}
}
}
fn device_pixels_per_page_px(&self) -> ScaleFactor<PagePx, DevicePixel, f32> {
self.viewport_zoom * self.page_zoom * self.device_pixels_per_screen_px()
}
fn update_zoom_transform(&mut self) {
let scale = self.device_pixels_per_page_px();
self.scene.scale = ScaleFactor(scale.get());
// We need to set the size of the root layer again, since the window size
// has changed in unscaled layer pixels.
self.scene.set_root_layer_size(self.window_size.as_f32());
}
fn on_zoom_window_event(&mut self, magnification: f32) {
self.page_zoom = ScaleFactor((self.page_zoom.get() * magnification).max(1.0));
self.update_zoom_transform();
self.send_window_size();
}
// TODO(pcwalton): I think this should go through the same queuing as scroll events do.
fn on_pinch_zoom_window_event(&mut self, magnification: f32) {
self.zoom_action = true;
self.zoom_time = precise_time_s();
let old_viewport_zoom = self.viewport_zoom;
self.viewport_zoom = ScaleFactor((self.viewport_zoom.get() * magnification).max(1.0));
let viewport_zoom = self.viewport_zoom;
self.update_zoom_transform();
// Scroll as needed
let window_size = self.window_size.as_f32();
let page_delta: TypedPoint2D<LayerPixel, f32> = TypedPoint2D(
window_size.width.get() * (viewport_zoom.inv() - old_viewport_zoom.inv()).get() * 0.5,
window_size.height.get() * (viewport_zoom.inv() - old_viewport_zoom.inv()).get() * 0.5);
let cursor = TypedPoint2D(-1f32, -1f32); // Make sure this hits the base layer.
match self.scene.root {
Some(ref mut layer) => {
layer.handle_scroll_event(page_delta, cursor);
}
None => { }
}
self.send_viewport_rects_for_all_layers();
self.composite_if_necessary();
}
fn on_navigation_window_event(&self, direction: WindowNavigateMsg) {
let direction = match direction {
windowing::Forward => constellation_msg::Forward,
windowing::Back => constellation_msg::Back,
};
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(NavigateMsg(direction))
}
fn on_key_event(&self, key: Key, state: KeyState, modifiers: KeyModifiers) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::KeyEvent(key, state, modifiers))
}
fn convert_buffer_requests_to_pipeline_requests_map(&self,
requests: Vec<(Rc<Layer<CompositorData>>,
Vec<BufferRequest>)>) ->
HashMap<PipelineId, (PaintChan,
Vec<PaintRequest>)> {
let scale = self.device_pixels_per_page_px();
let mut results:
HashMap<PipelineId, (PaintChan, Vec<PaintRequest>)> = HashMap::new();
for (layer, mut layer_requests) in requests.into_iter() {
let &(_, ref mut vec) =
match results.entry(layer.extra_data.borrow().pipeline.id) {
Occupied(mut entry) => {
*entry.get_mut() =
(layer.extra_data.borrow().pipeline.paint_chan.clone(), vec!());
entry.into_mut()
}
Vacant(entry) => {
entry.set((layer.extra_data.borrow().pipeline.paint_chan.clone(), vec!()))
}
};
// All the BufferRequests are in layer/device coordinates, but the paint task
// wants to know the page coordinates. We scale them before sending them.
for request in layer_requests.iter_mut() {
request.page_rect = request.page_rect / scale.get();
}
vec.push(PaintRequest {
buffer_requests: layer_requests,
scale: scale.get(),
layer_id: layer.extra_data.borrow().id,
epoch: layer.extra_data.borrow().epoch,
});
}
return results;
}
fn send_back_unused_buffers(&mut self) {
match self.root_pipeline {
Some(ref pipeline) => {
let unused_buffers = self.scene.collect_unused_buffers();
if unused_buffers.len() != 0 {
let message = UnusedBufferMsg(unused_buffers);
let _ = pipeline.paint_chan.send_opt(message);
}
},
None => {}
}
}
fn send_viewport_rect_for_layer(&self, layer: Rc<Layer<CompositorData>>) {
if layer.extra_data.borrow().id == LayerId::null() {
let layer_rect = Rect(-layer.extra_data.borrow().scroll_offset.to_untyped(),
layer.bounds.borrow().size.to_untyped());
let pipeline = &layer.extra_data.borrow().pipeline;
let ScriptControlChan(ref chan) = pipeline.script_chan;
chan.send(ViewportMsg(pipeline.id.clone(), layer_rect));
}
for kid in layer.children().iter() {
self.send_viewport_rect_for_layer(kid.clone());
}
}
fn send_viewport_rects_for_all_layers(&self) {
match self.scene.root {
Some(ref root) => self.send_viewport_rect_for_layer(root.clone()),
None => {},
}
}
/// Returns true if any buffer requests were sent or false otherwise.
fn send_buffer_requests_for_all_layers(&mut self) -> bool {
let mut layers_and_requests = Vec::new();
self.scene.get_buffer_requests(&mut layers_and_requests,
Rect(TypedPoint2D(0f32, 0f32), self.window_size.as_f32()));
// Return unused tiles first, so that they can be reused by any new BufferRequests.
self.send_back_unused_buffers();
if layers_and_requests.len() == 0 {
return false;
}
// We want to batch requests for each pipeline to avoid race conditions
// when handling the resulting BufferRequest responses.
let pipeline_requests =
self.convert_buffer_requests_to_pipeline_requests_map(layers_and_requests);
let mut num_paint_msgs_sent = 0;
for (_pipeline_id, (chan, requests)) in pipeline_requests.into_iter() {
num_paint_msgs_sent += 1;
let _ = chan.send_opt(PaintMsg(requests));
}
self.add_outstanding_paint_msg(num_paint_msgs_sent);
true
}
fn is_ready_to_paint_image_output(&self) -> bool {
if !self.got_load_complete_message {
return false;
}
if self.get_earliest_pipeline_ready_state() != FinishedLoading {
return false;
}
if self.has_outstanding_paint_msgs() {
return false;
}
if !self.all_pipelines_in_idle_paint_state() {
return false;
}
if !self.got_set_ids_message {
return false;
}
return true;
}
fn composite(&mut self) {
if !self.window.prepare_for_composite() {
return
}
let output_image = opts::get().output_file.is_some() &&
self.is_ready_to_paint_image_output();
let mut framebuffer_ids = vec!();
let mut texture_ids = vec!();
let (width, height) = (self.window_size.width.get(), self.window_size.height.get());
if output_image {
framebuffer_ids = gl::gen_framebuffers(1);
gl::bind_framebuffer(gl::FRAMEBUFFER, framebuffer_ids[0]);
texture_ids = gl::gen_textures(1);
gl::bind_texture(gl::TEXTURE_2D, texture_ids[0]);
gl::tex_image_2d(gl::TEXTURE_2D, 0, gl::RGB as GLint, width as GLsizei,
height as GLsizei, 0, gl::RGB, gl::UNSIGNED_BYTE, None);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
gl::framebuffer_texture_2d(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D,
texture_ids[0], 0);
gl::bind_texture(gl::TEXTURE_2D, 0);
}
profile(time::CompositingCategory, None, self.time_profiler_chan.clone(), || {
debug!("compositor: compositing");
// Adjust the layer dimensions as necessary to correspond to the size of the window.
self.scene.viewport = Rect {
origin: Zero::zero(),
size: self.window_size.as_f32(),
};
// paint the scene.
match self.scene.root {
Some(ref layer) => {
match self.context {
None => {
debug!("compositor: not compositing because context not yet set up")
}
Some(context) => {
rendergl::render_scene(layer.clone(), context, &self.scene);
}
}
}
None => {}
}
});
if output_image {
let path =
from_str::<Path>(opts::get().output_file.as_ref().unwrap().as_slice()).unwrap();
let mut pixels = gl::read_pixels(0, 0,
width as gl::GLsizei,
height as gl::GLsizei,
gl::RGB, gl::UNSIGNED_BYTE);
gl::bind_framebuffer(gl::FRAMEBUFFER, 0);
gl::delete_buffers(texture_ids.as_slice());
gl::delete_frame_buffers(framebuffer_ids.as_slice());
// flip image vertically (texture is upside down)
let orig_pixels = pixels.clone();
let stride = width * 3;
for y in range(0, height) {
let dst_start = y * stride;
let src_start = (height - y - 1) * stride;
let src_slice = orig_pixels.slice(src_start, src_start + stride);
copy_memory(pixels.slice_mut(dst_start, dst_start + stride),
src_slice.slice_to(stride));
}
let mut img = png::Image {
width: width as u32,
height: height as u32,
pixels: png::RGB8(pixels),
};
let res = png::store_png(&mut img, &path);
assert!(res.is_ok());
debug!("shutting down the constellation after generating an output file");
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ExitMsg);
self.shutdown_state = ShuttingDown;
}
// Perform the page flip. This will likely block for a while.
self.window.present();
self.last_composite_time = precise_time_ns();
self.composition_request = NoCompositingNecessary;
self.process_pending_scroll_events();
}
fn composite_if_necessary(&mut self) {
if self.composition_request == NoCompositingNecessary {
self.composition_request = CompositeNow
}
}
fn initialize_compositing(&mut self) {
let context = CompositorTask::create_graphics_context(&self.window.native_metadata());
let show_debug_borders = opts::get().show_debug_borders;
self.context = Some(rendergl::RenderContext::new(context, show_debug_borders))
}
fn find_topmost_layer_at_point_for_layer(&self,
layer: Rc<Layer<CompositorData>>,
point: TypedPoint2D<LayerPixel, f32>,
clip_rect: &TypedRect<LayerPixel, f32>)
-> Option<HitTestResult> {
let layer_bounds = *layer.bounds.borrow();
let masks_to_bounds = *layer.masks_to_bounds.borrow();
if layer_bounds.is_empty() && masks_to_bounds {
return None;
}
let clipped_layer_bounds = match clip_rect.intersection(&layer_bounds) {
Some(rect) => rect,
None => return None,
};
let clip_rect_for_children = if masks_to_bounds {
Rect(Zero::zero(), clipped_layer_bounds.size)
} else {
clipped_layer_bounds.translate(&clip_rect.origin)
};
let child_point = point - layer_bounds.origin;
for child in layer.children().iter().rev() {
let result = self.find_topmost_layer_at_point_for_layer(child.clone(),
child_point,
&clip_rect_for_children);
if result.is_some() {
return result;
}
}
let point = point - *layer.content_offset.borrow();
if !clipped_layer_bounds.contains(&point) {
return None;
}
return Some(HitTestResult { layer: layer, point: point });
}
fn find_topmost_layer_at_point(&self,
point: TypedPoint2D<LayerPixel, f32>)
-> Option<HitTestResult> {
match self.scene.root {
Some(ref layer) => self.find_topmost_layer_at_point_for_layer(layer.clone(),
point,
&*layer.bounds.borrow()),
None => None,
}
}
fn find_layer_with_pipeline_and_layer_id(&self,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
match self.scene.root {
Some(ref layer) =>
find_layer_with_pipeline_and_layer_id_for_layer(layer.clone(),
pipeline_id,
layer_id),
None => None,
}
}
}
fn find_layer_with_pipeline_and_layer_id_for_layer(layer: Rc<Layer<CompositorData>>,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
if layer.extra_data.borrow().pipeline.id == pipeline_id &&
layer.extra_data.borrow().id == layer_id {
return Some(layer);
}
for kid in layer.children().iter() {
let result = find_layer_with_pipeline_and_layer_id_for_layer(kid.clone(),
pipeline_id,
layer_id);
if result.is_some() {
return result;
}
}
return None;
}
fn create_root_layer_for_pipeline_and_rect(pipeline: &CompositionPipeline,
frame_rect: Option<TypedRect<PagePx, f32>>)
-> Rc<Layer<CompositorData>> {
let layer_properties = LayerProperties {
pipeline_id: pipeline.id,
epoch: Epoch(0),
id: LayerId::null(),
rect: Rect::zero(),
background_color: azure_hl::Color::new(0., 0., 0., 0.),
scroll_policy: Scrollable,
};
let root_layer = CompositorData::new_layer(pipeline.clone(),
layer_properties,
WantsScrollEvents,
opts::get().tile_size);
// All root layers mask to bounds.
*root_layer.masks_to_bounds.borrow_mut() = true;
match frame_rect {
Some(ref frame_rect) => {
let frame_rect = frame_rect.to_untyped();
*root_layer.bounds.borrow_mut() = Rect::from_untyped(&frame_rect);
}
None => {}
}
return root_layer;
}
impl<Window> CompositorEventListener for IOCompositor<Window> where Window: WindowMethods {
fn handle_event(&mut self, msg: WindowEvent) -> bool {
// Check for new messages coming from the other tasks in the system.
loop {
match self.port.try_recv_compositor_msg() {
None => break,
Some(msg) => {
if !self.handle_browser_message(msg) {
break
}
}
}
}
if self.shutdown_state == FinishedShuttingDown {
// We have exited the compositor and passing window
// messages to script may crash.
debug!("Exiting the compositor due to a request from script.");
return false;
}
// Handle the message coming from the windowing system.
self.handle_window_message(msg);
// If a pinch-zoom happened recently, ask for tiles at the new resolution
if self.zoom_action && precise_time_s() - self.zoom_time > 0.3 {
self.zoom_action = false;
self.scene.mark_layer_contents_as_changed_recursively();
self.send_buffer_requests_for_all_layers();
}
match self.composition_request {
NoCompositingNecessary | CompositeOnScrollTimeout(_) => {}
CompositeNow => self.composite(),
}
self.shutdown_state != FinishedShuttingDown
}
/// Repaints and recomposites synchronously. You must be careful when calling this, as if a
/// paint is not scheduled the compositor will hang forever.
///
/// This is used when resizing the window.
fn repaint_synchronously(&mut self) {
while self.shutdown_state != ShuttingDown {
let msg = self.port.recv_compositor_msg();
let is_paint = match msg {
Paint(..) => true,
_ => false,
};
let keep_going = self.handle_browser_message(msg);
if is_paint {
self.composite();
break
}
if !keep_going {
break
}
}
}
fn shutdown(&mut self) {
// Clear out the compositor layers so that painting tasks can destroy the buffers.
match self.scene.root {
None => {}
Some(ref layer) => layer.forget_all_tiles(),
}
// Drain compositor port, sometimes messages contain channels that are blocking
// another task from finishing (i.e. SetIds)
while self.port.try_recv_compositor_msg().is_some() {}
// Tell the profiler, memory profiler, and scrolling timer to shut down.
let TimeProfilerChan(ref time_profiler_chan) = self.time_profiler_chan;
time_profiler_chan.send(time::ExitMsg);
let MemoryProfilerChan(ref memory_profiler_chan) = self.memory_profiler_chan;
memory_profiler_chan.send(memory::ExitMsg);
self.scrolling_timer.shutdown();
}
fn pinch_zoom_level(&self) -> f32 {
self.viewport_zoom.get() as f32
}
fn get_title_for_main_frame(&self) {
let root_pipeline_id = match self.root_pipeline {
None => return,
Some(ref root_pipeline) => root_pipeline.id,
};
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(GetPipelineTitleMsg(root_pipeline_id));
}
}
auto merge of #4357 : pcwalton/servo/compositor-hit-test-clipping, r=mrobinson
Fixes clicking on links on the second page of Hacker News.
r? @mrobinson
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositor_layer::{CompositorData, CompositorLayer, DoesntWantScrollEvents};
use compositor_layer::{WantsScrollEvents};
use compositor_task;
use compositor_task::{ChangePageLoadData, ChangePageTitle, ChangePaintState, ChangeReadyState};
use compositor_task::{CompositorEventListener, CompositorProxy, CompositorReceiver};
use compositor_task::{CompositorTask, CreateOrUpdateDescendantLayer, CreateOrUpdateRootLayer};
use compositor_task::{Exit, FrameTreeUpdateMsg, GetGraphicsMetadata, LayerProperties};
use compositor_task::{LoadComplete, Msg, Paint, PaintMsgDiscarded, ScrollFragmentPoint};
use compositor_task::{ScrollTimeout, SetIds, SetLayerOrigin, ShutdownComplete};
use constellation::{FrameId, FrameTreeDiff, SendableFrameTree};
use pipeline::CompositionPipeline;
use scrolling::ScrollingTimerProxy;
use windowing;
use windowing::{IdleWindowEvent, InitializeCompositingWindowEvent};
use windowing::{KeyEvent, LoadUrlWindowEvent, MouseWindowClickEvent, MouseWindowEvent};
use windowing::{MouseWindowEventClass, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use windowing::{MouseWindowMoveEventClass, NavigationWindowEvent, PinchZoomWindowEvent};
use windowing::{QuitWindowEvent, RefreshWindowEvent, ResizeWindowEvent, ScrollWindowEvent};
use windowing::{WindowEvent, WindowMethods, WindowNavigateMsg, ZoomWindowEvent};
use azure::azure_hl;
use std::cmp;
use std::mem;
use std::num::Zero;
use geom::point::{Point2D, TypedPoint2D};
use geom::rect::{Rect, TypedRect};
use geom::size::TypedSize2D;
use geom::scale_factor::ScaleFactor;
use gfx::paint_task::{PaintChan, PaintMsg, PaintRequest, UnusedBufferMsg};
use layers::geometry::{DevicePixel, LayerPixel};
use layers::layers::{BufferRequest, Layer, LayerBufferSet};
use layers::rendergl;
use layers::rendergl::RenderContext;
use layers::scene::Scene;
use png;
use gleam::gl::types::{GLint, GLsizei};
use gleam::gl;
use script_traits::{ViewportMsg, ScriptControlChan};
use servo_msg::compositor_msg::{Blank, Epoch, FinishedLoading, IdlePaintState, LayerId};
use servo_msg::compositor_msg::{ReadyState, PaintState, PaintingPaintState, Scrollable};
use servo_msg::constellation_msg::{mod, ConstellationChan, ExitMsg};
use servo_msg::constellation_msg::{GetPipelineTitleMsg, Key, KeyModifiers, KeyState, LoadData};
use servo_msg::constellation_msg::{LoadUrlMsg, NavigateMsg, PipelineId, ResizedWindowMsg};
use servo_msg::constellation_msg::{WindowSizeData};
use servo_util::geometry::{PagePx, ScreenPx, ViewportPx};
use servo_util::memory::MemoryProfilerChan;
use servo_util::opts;
use servo_util::time::{profile, TimeProfilerChan};
use servo_util::{memory, time};
use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant};
use std::path::Path;
use std::rc::Rc;
use std::slice::bytes::copy_memory;
use time::{precise_time_ns, precise_time_s};
use url::Url;
/// NB: Never block on the constellation, because sometimes the constellation blocks on us.
pub struct IOCompositor<Window: WindowMethods> {
/// The application window.
window: Rc<Window>,
/// The port on which we receive messages.
port: Box<CompositorReceiver>,
/// The render context. This will be `None` if the windowing system has not yet sent us a
/// `PrepareRenderingEvent`.
context: Option<RenderContext>,
/// The root pipeline.
root_pipeline: Option<CompositionPipeline>,
/// The canvas to paint a page.
scene: Scene<CompositorData>,
/// The application window size.
window_size: TypedSize2D<DevicePixel, uint>,
/// "Mobile-style" zoom that does not reflow the page.
viewport_zoom: ScaleFactor<PagePx, ViewportPx, f32>,
/// "Desktop-style" zoom that resizes the viewport to fit the window.
/// See `ViewportPx` docs in util/geom.rs for details.
page_zoom: ScaleFactor<ViewportPx, ScreenPx, f32>,
/// The device pixel ratio for this window.
hidpi_factor: ScaleFactor<ScreenPx, DevicePixel, f32>,
/// A handle to the scrolling timer.
scrolling_timer: ScrollingTimerProxy,
/// Tracks whether we should composite this frame.
composition_request: CompositionRequest,
/// Tracks whether we are in the process of shutting down, or have shut down and should close
/// the compositor.
shutdown_state: ShutdownState,
/// Tracks outstanding paint_msg's sent to the paint tasks.
outstanding_paint_msgs: uint,
/// Tracks the last composite time.
last_composite_time: u64,
/// Tracks whether the zoom action has happened recently.
zoom_action: bool,
/// The time of the last zoom action has started.
zoom_time: f64,
/// Current display/reflow status of each pipeline.
ready_states: HashMap<PipelineId, ReadyState>,
/// Current paint status of each pipeline.
paint_states: HashMap<PipelineId, PaintState>,
/// Whether the page being rendered has loaded completely.
/// Differs from ReadyState because we can finish loading (ready)
/// many times for a single page.
got_load_complete_message: bool,
/// Whether we have gotten a `SetIds` message.
got_set_ids_message: bool,
/// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan,
/// The channel on which messages can be sent to the time profiler.
time_profiler_chan: TimeProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
memory_profiler_chan: MemoryProfilerChan,
/// Pending scroll to fragment event, if any
fragment_point: Option<Point2D<f32>>,
/// Pending scroll events.
pending_scroll_events: Vec<ScrollEvent>,
}
pub struct ScrollEvent {
delta: TypedPoint2D<DevicePixel,f32>,
cursor: TypedPoint2D<DevicePixel,i32>,
}
#[deriving(PartialEq)]
enum CompositionRequest {
NoCompositingNecessary,
CompositeOnScrollTimeout(u64),
CompositeNow,
}
#[deriving(PartialEq, Show)]
enum ShutdownState {
NotShuttingDown,
ShuttingDown,
FinishedShuttingDown,
}
struct HitTestResult {
layer: Rc<Layer<CompositorData>>,
point: TypedPoint2D<LayerPixel, f32>,
}
impl<Window: WindowMethods> IOCompositor<Window> {
fn new(window: Rc<Window>,
sender: Box<CompositorProxy+Send>,
receiver: Box<CompositorReceiver>,
constellation_chan: ConstellationChan,
time_profiler_chan: TimeProfilerChan,
memory_profiler_chan: MemoryProfilerChan)
-> IOCompositor<Window> {
// Create an initial layer tree.
//
// TODO: There should be no initial layer tree until the painter creates one from the
// display list. This is only here because we don't have that logic in the painter yet.
let window_size = window.framebuffer_size();
let hidpi_factor = window.hidpi_factor();
IOCompositor {
window: window,
port: receiver,
context: None,
root_pipeline: None,
scene: Scene::new(Rect {
origin: Zero::zero(),
size: window_size.as_f32(),
}),
window_size: window_size,
hidpi_factor: hidpi_factor,
scrolling_timer: ScrollingTimerProxy::new(sender),
composition_request: NoCompositingNecessary,
pending_scroll_events: Vec::new(),
shutdown_state: NotShuttingDown,
page_zoom: ScaleFactor(1.0),
viewport_zoom: ScaleFactor(1.0),
zoom_action: false,
zoom_time: 0f64,
ready_states: HashMap::new(),
paint_states: HashMap::new(),
got_load_complete_message: false,
got_set_ids_message: false,
constellation_chan: constellation_chan,
time_profiler_chan: time_profiler_chan,
memory_profiler_chan: memory_profiler_chan,
fragment_point: None,
outstanding_paint_msgs: 0,
last_composite_time: 0,
}
}
pub fn create(window: Rc<Window>,
sender: Box<CompositorProxy+Send>,
receiver: Box<CompositorReceiver>,
constellation_chan: ConstellationChan,
time_profiler_chan: TimeProfilerChan,
memory_profiler_chan: MemoryProfilerChan)
-> IOCompositor<Window> {
let mut compositor = IOCompositor::new(window,
sender,
receiver,
constellation_chan,
time_profiler_chan,
memory_profiler_chan);
// Set the size of the root layer.
compositor.update_zoom_transform();
// Tell the constellation about the initial window size.
compositor.send_window_size();
compositor
}
fn handle_browser_message(&mut self, msg: Msg) -> bool {
match (msg, self.shutdown_state) {
(_, FinishedShuttingDown) =>
panic!("compositor shouldn't be handling messages after shutting down"),
(Exit(chan), _) => {
debug!("shutting down the constellation");
let ConstellationChan(ref con_chan) = self.constellation_chan;
con_chan.send(ExitMsg);
chan.send(());
self.shutdown_state = ShuttingDown;
}
(ShutdownComplete, _) => {
debug!("constellation completed shutdown");
self.shutdown_state = FinishedShuttingDown;
return false;
}
(ChangeReadyState(pipeline_id, ready_state), NotShuttingDown) => {
self.change_ready_state(pipeline_id, ready_state);
}
(ChangePaintState(pipeline_id, paint_state), NotShuttingDown) => {
self.change_paint_state(pipeline_id, paint_state);
}
(ChangePageTitle(pipeline_id, title), NotShuttingDown) => {
self.change_page_title(pipeline_id, title);
}
(ChangePageLoadData(frame_id, load_data), NotShuttingDown) => {
self.change_page_load_data(frame_id, load_data);
}
(PaintMsgDiscarded, NotShuttingDown) => {
self.remove_outstanding_paint_msg();
}
(SetIds(frame_tree, response_chan, new_constellation_chan), NotShuttingDown) => {
self.set_frame_tree(&frame_tree,
response_chan,
new_constellation_chan);
self.send_viewport_rects_for_all_layers();
}
(FrameTreeUpdateMsg(frame_tree_diff, response_channel), NotShuttingDown) => {
self.update_frame_tree(&frame_tree_diff);
response_channel.send(());
}
(CreateOrUpdateRootLayer(layer_properties), NotShuttingDown) => {
self.create_or_update_root_layer(layer_properties);
}
(CreateOrUpdateDescendantLayer(layer_properties), NotShuttingDown) => {
self.create_or_update_descendant_layer(layer_properties);
}
(GetGraphicsMetadata(chan), NotShuttingDown) => {
chan.send(Some(self.window.native_metadata()));
}
(SetLayerOrigin(pipeline_id, layer_id, origin), NotShuttingDown) => {
self.set_layer_origin(pipeline_id, layer_id, origin);
}
(Paint(pipeline_id, epoch, replies), NotShuttingDown) => {
for (layer_id, new_layer_buffer_set) in replies.into_iter() {
self.paint(pipeline_id, layer_id, new_layer_buffer_set, epoch);
}
self.remove_outstanding_paint_msg();
}
(ScrollFragmentPoint(pipeline_id, layer_id, point), NotShuttingDown) => {
self.scroll_fragment_to_point(pipeline_id, layer_id, point);
}
(LoadComplete, NotShuttingDown) => {
self.got_load_complete_message = true;
// If we're painting in headless mode, schedule a recomposite.
if opts::get().output_file.is_some() {
self.composite_if_necessary();
}
// Inform the embedder that the load has finished.
//
// TODO(pcwalton): Specify which frame's load completed.
self.window.load_end();
}
(ScrollTimeout(timestamp), NotShuttingDown) => {
debug!("scroll timeout, drawing unpainted content!");
match self.composition_request {
CompositeOnScrollTimeout(this_timestamp) if timestamp == this_timestamp => {
self.composition_request = CompositeNow
}
_ => {}
}
}
(compositor_task::KeyEvent(key, modified), NotShuttingDown) => {
self.window.handle_key(key, modified);
}
// When we are shutting_down, we need to avoid performing operations
// such as Paint that may crash because we have begun tearing down
// the rest of our resources.
(_, ShuttingDown) => { }
}
true
}
fn change_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) {
match self.ready_states.entry(pipeline_id) {
Occupied(entry) => {
*entry.into_mut() = ready_state;
}
Vacant(entry) => {
entry.set(ready_state);
}
}
self.window.set_ready_state(self.get_earliest_pipeline_ready_state());
// If we're painting in headless mode, schedule a recomposite.
if opts::get().output_file.is_some() {
self.composite_if_necessary()
}
}
fn get_earliest_pipeline_ready_state(&self) -> ReadyState {
if self.ready_states.len() == 0 {
return Blank;
}
return self.ready_states.values().fold(FinishedLoading, |a, &b| cmp::min(a, b));
}
fn change_paint_state(&mut self, pipeline_id: PipelineId, paint_state: PaintState) {
match self.paint_states.entry(pipeline_id) {
Occupied(entry) => {
*entry.into_mut() = paint_state;
}
Vacant(entry) => {
entry.set(paint_state);
}
}
self.window.set_paint_state(paint_state);
}
fn change_page_title(&mut self, _: PipelineId, title: Option<String>) {
self.window.set_page_title(title);
}
fn change_page_load_data(&mut self, _: FrameId, load_data: LoadData) {
self.window.set_page_load_data(load_data);
}
fn all_pipelines_in_idle_paint_state(&self) -> bool {
if self.ready_states.len() == 0 {
return false;
}
return self.paint_states.values().all(|&value| value == IdlePaintState);
}
fn has_paint_msg_tracking(&self) -> bool {
// only track PaintMsg's if the compositor outputs to a file.
opts::get().output_file.is_some()
}
fn has_outstanding_paint_msgs(&self) -> bool {
self.has_paint_msg_tracking() && self.outstanding_paint_msgs > 0
}
fn add_outstanding_paint_msg(&mut self, count: uint) {
// return early if not tracking paint_msg's
if !self.has_paint_msg_tracking() {
return;
}
debug!("add_outstanding_paint_msg {}", self.outstanding_paint_msgs);
self.outstanding_paint_msgs += count;
}
fn remove_outstanding_paint_msg(&mut self) {
if !self.has_paint_msg_tracking() {
return;
}
if self.outstanding_paint_msgs > 0 {
self.outstanding_paint_msgs -= 1;
} else {
debug!("too many repaint msgs completed");
}
}
fn set_frame_tree(&mut self,
frame_tree: &SendableFrameTree,
response_chan: Sender<()>,
new_constellation_chan: ConstellationChan) {
response_chan.send(());
self.root_pipeline = Some(frame_tree.pipeline.clone());
// If we have an old root layer, release all old tiles before replacing it.
match self.scene.root {
Some(ref mut layer) => layer.clear_all_tiles(),
None => { }
}
self.scene.root = Some(self.create_frame_tree_root_layers(frame_tree, None));
self.scene.set_root_layer_size(self.window_size.as_f32());
// Initialize the new constellation channel by sending it the root window size.
self.constellation_chan = new_constellation_chan;
self.send_window_size();
self.got_set_ids_message = true;
self.composite_if_necessary();
}
fn create_frame_tree_root_layers(&mut self,
frame_tree: &SendableFrameTree,
frame_rect: Option<TypedRect<PagePx, f32>>)
-> Rc<Layer<CompositorData>> {
// Initialize the ReadyState and PaintState for this pipeline.
self.ready_states.insert(frame_tree.pipeline.id, Blank);
self.paint_states.insert(frame_tree.pipeline.id, PaintingPaintState);
let root_layer = create_root_layer_for_pipeline_and_rect(&frame_tree.pipeline, frame_rect);
for kid in frame_tree.children.iter() {
root_layer.add_child(self.create_frame_tree_root_layers(&kid.frame_tree, kid.rect));
}
return root_layer;
}
fn update_frame_tree(&mut self, frame_tree_diff: &FrameTreeDiff) {
let parent_layer = self.find_pipeline_root_layer(frame_tree_diff.parent_pipeline.id);
parent_layer.add_child(
create_root_layer_for_pipeline_and_rect(&frame_tree_diff.pipeline,
frame_tree_diff.rect));
}
fn find_pipeline_root_layer(&self, pipeline_id: PipelineId) -> Rc<Layer<CompositorData>> {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, LayerId::null()) {
Some(ref layer) => layer.clone(),
None => panic!("Tried to create or update layer for unknown pipeline"),
}
}
fn update_layer_if_exists(&mut self, properties: LayerProperties) -> bool {
match self.find_layer_with_pipeline_and_layer_id(properties.pipeline_id, properties.id) {
Some(existing_layer) => {
existing_layer.update_layer(properties);
true
}
None => false,
}
}
fn create_or_update_root_layer(&mut self, layer_properties: LayerProperties) {
let need_new_root_layer = !self.update_layer_if_exists(layer_properties);
if need_new_root_layer {
let root_layer = self.find_pipeline_root_layer(layer_properties.pipeline_id);
root_layer.update_layer_except_size(layer_properties);
let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone();
let first_child = CompositorData::new_layer(root_layer_pipeline.clone(),
layer_properties,
DoesntWantScrollEvents,
opts::get().tile_size);
// Add the first child / base layer to the front of the child list, so that
// child iframe layers are painted on top of the base layer. These iframe
// layers were added previously when creating the layer tree skeleton in
// create_frame_tree_root_layers.
root_layer.children().insert(0, first_child);
}
self.scroll_layer_to_fragment_point_if_necessary(layer_properties.pipeline_id,
layer_properties.id);
self.send_buffer_requests_for_all_layers();
}
fn create_or_update_descendant_layer(&mut self, layer_properties: LayerProperties) {
if !self.update_layer_if_exists(layer_properties) {
self.create_descendant_layer(layer_properties);
}
self.scroll_layer_to_fragment_point_if_necessary(layer_properties.pipeline_id,
layer_properties.id);
self.send_buffer_requests_for_all_layers();
}
fn create_descendant_layer(&self, layer_properties: LayerProperties) {
let root_layer = self.find_pipeline_root_layer(layer_properties.pipeline_id);
let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone();
let new_layer = CompositorData::new_layer(root_layer_pipeline,
layer_properties,
DoesntWantScrollEvents,
root_layer.tile_size);
root_layer.add_child(new_layer);
}
fn send_window_size(&self) {
let dppx = self.page_zoom * self.device_pixels_per_screen_px();
let initial_viewport = self.window_size.as_f32() / dppx;
let visible_viewport = initial_viewport / self.viewport_zoom;
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ResizedWindowMsg(WindowSizeData {
device_pixel_ratio: dppx,
initial_viewport: initial_viewport,
visible_viewport: visible_viewport,
}));
}
pub fn move_layer(&self,
pipeline_id: PipelineId,
layer_id: LayerId,
origin: TypedPoint2D<LayerPixel, f32>)
-> bool {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
if layer.extra_data.borrow().wants_scroll_events == WantsScrollEvents {
layer.clamp_scroll_offset_and_scroll_layer(TypedPoint2D(0f32, 0f32) - origin);
}
true
}
None => false,
}
}
fn scroll_layer_to_fragment_point_if_necessary(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId) {
match self.fragment_point.take() {
Some(point) => {
if !self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
panic!("Compositor: Tried to scroll to fragment with unknown layer.");
}
self.start_scrolling_timer_if_necessary();
}
None => {}
}
}
fn start_scrolling_timer_if_necessary(&mut self) {
match self.composition_request {
CompositeNow | CompositeOnScrollTimeout(_) => return,
NoCompositingNecessary => {}
}
let timestamp = precise_time_ns();
self.scrolling_timer.scroll_event_processed(timestamp);
self.composition_request = CompositeOnScrollTimeout(timestamp);
}
fn set_layer_origin(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
new_origin: Point2D<f32>) {
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
layer.bounds.borrow_mut().origin = Point2D::from_untyped(&new_origin)
}
None => panic!("Compositor received SetLayerOrigin for nonexistent layer"),
};
self.send_buffer_requests_for_all_layers();
}
fn paint(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
new_layer_buffer_set: Box<LayerBufferSet>,
epoch: Epoch) {
debug!("compositor received new frame at size {}x{}",
self.window_size.width.get(),
self.window_size.height.get());
// From now on, if we destroy the buffers, they will leak.
let mut new_layer_buffer_set = new_layer_buffer_set;
new_layer_buffer_set.mark_will_leak();
match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) {
Some(ref layer) => {
// FIXME(pcwalton): This is going to cause problems with inconsistent frames since
// we only composite one layer at a time.
assert!(layer.add_buffers(new_layer_buffer_set, epoch));
self.composite_if_necessary();
}
None => {
// FIXME: This may potentially be triggered by a race condition where a
// buffers are being painted but the layer is removed before painting
// completes.
panic!("compositor given paint command for non-existent layer");
}
}
}
fn scroll_fragment_to_point(&mut self,
pipeline_id: PipelineId,
layer_id: LayerId,
point: Point2D<f32>) {
if self.move_layer(pipeline_id, layer_id, Point2D::from_untyped(&point)) {
if self.send_buffer_requests_for_all_layers() {
self.start_scrolling_timer_if_necessary();
}
} else {
self.fragment_point = Some(point);
}
}
fn handle_window_message(&mut self, event: WindowEvent) {
match event {
IdleWindowEvent => {}
RefreshWindowEvent => {
self.composite();
}
InitializeCompositingWindowEvent => {
self.initialize_compositing();
}
ResizeWindowEvent(size) => {
self.on_resize_window_event(size);
}
LoadUrlWindowEvent(url_string) => {
self.on_load_url_window_event(url_string);
}
MouseWindowEventClass(mouse_window_event) => {
self.on_mouse_window_event_class(mouse_window_event);
}
MouseWindowMoveEventClass(cursor) => {
self.on_mouse_window_move_event_class(cursor);
}
ScrollWindowEvent(delta, cursor) => {
self.on_scroll_window_event(delta, cursor);
}
ZoomWindowEvent(magnification) => {
self.on_zoom_window_event(magnification);
}
PinchZoomWindowEvent(magnification) => {
self.on_pinch_zoom_window_event(magnification);
}
NavigationWindowEvent(direction) => {
self.on_navigation_window_event(direction);
}
KeyEvent(key, state, modifiers) => {
self.on_key_event(key, state, modifiers);
}
QuitWindowEvent => {
debug!("shutting down the constellation for QuitWindowEvent");
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ExitMsg);
self.shutdown_state = ShuttingDown;
}
}
}
fn on_resize_window_event(&mut self, new_size: TypedSize2D<DevicePixel, uint>) {
debug!("compositor resizing to {}", new_size.to_untyped());
// A size change could also mean a resolution change.
let new_hidpi_factor = self.window.hidpi_factor();
if self.hidpi_factor != new_hidpi_factor {
self.hidpi_factor = new_hidpi_factor;
self.update_zoom_transform();
}
if self.window_size == new_size {
return;
}
self.window_size = new_size;
self.scene.set_root_layer_size(new_size.as_f32());
self.send_window_size();
}
fn on_load_url_window_event(&mut self, url_string: String) {
debug!("osmain: loading URL `{:s}`", url_string);
self.got_load_complete_message = false;
let root_pipeline_id = match self.scene.root {
Some(ref layer) => layer.extra_data.borrow().pipeline.id.clone(),
None => panic!("Compositor: Received LoadUrlWindowEvent without initialized compositor \
layers"),
};
let msg = LoadUrlMsg(root_pipeline_id,
LoadData::new(Url::parse(url_string.as_slice()).unwrap()));
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(msg);
}
fn on_mouse_window_event_class(&self, mouse_window_event: MouseWindowEvent) {
let point = match mouse_window_event {
MouseWindowClickEvent(_, p) => p,
MouseWindowMouseDownEvent(_, p) => p,
MouseWindowMouseUpEvent(_, p) => p,
};
match self.find_topmost_layer_at_point(point / self.scene.scale) {
Some(result) => result.layer.send_mouse_event(mouse_window_event, result.point),
None => {},
}
}
fn on_mouse_window_move_event_class(&self, cursor: TypedPoint2D<DevicePixel, f32>) {
match self.find_topmost_layer_at_point(cursor / self.scene.scale) {
Some(result) => result.layer.send_mouse_move_event(result.point),
None => {},
}
}
fn on_scroll_window_event(&mut self,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, i32>) {
self.pending_scroll_events.push(ScrollEvent {
delta: delta,
cursor: cursor,
});
self.composite_if_necessary();
}
fn process_pending_scroll_events(&mut self) {
let had_scroll_events = self.pending_scroll_events.len() > 0;
for scroll_event in mem::replace(&mut self.pending_scroll_events, Vec::new()).into_iter() {
let delta = scroll_event.delta / self.scene.scale;
let cursor = scroll_event.cursor.as_f32() / self.scene.scale;
match self.scene.root {
Some(ref mut layer) => {
layer.handle_scroll_event(delta, cursor);
}
None => {}
}
self.start_scrolling_timer_if_necessary();
self.send_buffer_requests_for_all_layers();
}
if had_scroll_events {
self.send_viewport_rects_for_all_layers();
}
}
fn device_pixels_per_screen_px(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
match opts::get().device_pixels_per_px {
Some(device_pixels_per_px) => device_pixels_per_px,
None => match opts::get().output_file {
Some(_) => ScaleFactor(1.0),
None => self.hidpi_factor
}
}
}
fn device_pixels_per_page_px(&self) -> ScaleFactor<PagePx, DevicePixel, f32> {
self.viewport_zoom * self.page_zoom * self.device_pixels_per_screen_px()
}
fn update_zoom_transform(&mut self) {
let scale = self.device_pixels_per_page_px();
self.scene.scale = ScaleFactor(scale.get());
// We need to set the size of the root layer again, since the window size
// has changed in unscaled layer pixels.
self.scene.set_root_layer_size(self.window_size.as_f32());
}
fn on_zoom_window_event(&mut self, magnification: f32) {
self.page_zoom = ScaleFactor((self.page_zoom.get() * magnification).max(1.0));
self.update_zoom_transform();
self.send_window_size();
}
// TODO(pcwalton): I think this should go through the same queuing as scroll events do.
fn on_pinch_zoom_window_event(&mut self, magnification: f32) {
self.zoom_action = true;
self.zoom_time = precise_time_s();
let old_viewport_zoom = self.viewport_zoom;
self.viewport_zoom = ScaleFactor((self.viewport_zoom.get() * magnification).max(1.0));
let viewport_zoom = self.viewport_zoom;
self.update_zoom_transform();
// Scroll as needed
let window_size = self.window_size.as_f32();
let page_delta: TypedPoint2D<LayerPixel, f32> = TypedPoint2D(
window_size.width.get() * (viewport_zoom.inv() - old_viewport_zoom.inv()).get() * 0.5,
window_size.height.get() * (viewport_zoom.inv() - old_viewport_zoom.inv()).get() * 0.5);
let cursor = TypedPoint2D(-1f32, -1f32); // Make sure this hits the base layer.
match self.scene.root {
Some(ref mut layer) => {
layer.handle_scroll_event(page_delta, cursor);
}
None => { }
}
self.send_viewport_rects_for_all_layers();
self.composite_if_necessary();
}
fn on_navigation_window_event(&self, direction: WindowNavigateMsg) {
let direction = match direction {
windowing::Forward => constellation_msg::Forward,
windowing::Back => constellation_msg::Back,
};
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(NavigateMsg(direction))
}
fn on_key_event(&self, key: Key, state: KeyState, modifiers: KeyModifiers) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::KeyEvent(key, state, modifiers))
}
fn convert_buffer_requests_to_pipeline_requests_map(&self,
requests: Vec<(Rc<Layer<CompositorData>>,
Vec<BufferRequest>)>) ->
HashMap<PipelineId, (PaintChan,
Vec<PaintRequest>)> {
let scale = self.device_pixels_per_page_px();
let mut results:
HashMap<PipelineId, (PaintChan, Vec<PaintRequest>)> = HashMap::new();
for (layer, mut layer_requests) in requests.into_iter() {
let &(_, ref mut vec) =
match results.entry(layer.extra_data.borrow().pipeline.id) {
Occupied(mut entry) => {
*entry.get_mut() =
(layer.extra_data.borrow().pipeline.paint_chan.clone(), vec!());
entry.into_mut()
}
Vacant(entry) => {
entry.set((layer.extra_data.borrow().pipeline.paint_chan.clone(), vec!()))
}
};
// All the BufferRequests are in layer/device coordinates, but the paint task
// wants to know the page coordinates. We scale them before sending them.
for request in layer_requests.iter_mut() {
request.page_rect = request.page_rect / scale.get();
}
vec.push(PaintRequest {
buffer_requests: layer_requests,
scale: scale.get(),
layer_id: layer.extra_data.borrow().id,
epoch: layer.extra_data.borrow().epoch,
});
}
return results;
}
fn send_back_unused_buffers(&mut self) {
match self.root_pipeline {
Some(ref pipeline) => {
let unused_buffers = self.scene.collect_unused_buffers();
if unused_buffers.len() != 0 {
let message = UnusedBufferMsg(unused_buffers);
let _ = pipeline.paint_chan.send_opt(message);
}
},
None => {}
}
}
fn send_viewport_rect_for_layer(&self, layer: Rc<Layer<CompositorData>>) {
if layer.extra_data.borrow().id == LayerId::null() {
let layer_rect = Rect(-layer.extra_data.borrow().scroll_offset.to_untyped(),
layer.bounds.borrow().size.to_untyped());
let pipeline = &layer.extra_data.borrow().pipeline;
let ScriptControlChan(ref chan) = pipeline.script_chan;
chan.send(ViewportMsg(pipeline.id.clone(), layer_rect));
}
for kid in layer.children().iter() {
self.send_viewport_rect_for_layer(kid.clone());
}
}
fn send_viewport_rects_for_all_layers(&self) {
match self.scene.root {
Some(ref root) => self.send_viewport_rect_for_layer(root.clone()),
None => {},
}
}
/// Returns true if any buffer requests were sent or false otherwise.
fn send_buffer_requests_for_all_layers(&mut self) -> bool {
let mut layers_and_requests = Vec::new();
self.scene.get_buffer_requests(&mut layers_and_requests,
Rect(TypedPoint2D(0f32, 0f32), self.window_size.as_f32()));
// Return unused tiles first, so that they can be reused by any new BufferRequests.
self.send_back_unused_buffers();
if layers_and_requests.len() == 0 {
return false;
}
// We want to batch requests for each pipeline to avoid race conditions
// when handling the resulting BufferRequest responses.
let pipeline_requests =
self.convert_buffer_requests_to_pipeline_requests_map(layers_and_requests);
let mut num_paint_msgs_sent = 0;
for (_pipeline_id, (chan, requests)) in pipeline_requests.into_iter() {
num_paint_msgs_sent += 1;
let _ = chan.send_opt(PaintMsg(requests));
}
self.add_outstanding_paint_msg(num_paint_msgs_sent);
true
}
fn is_ready_to_paint_image_output(&self) -> bool {
if !self.got_load_complete_message {
return false;
}
if self.get_earliest_pipeline_ready_state() != FinishedLoading {
return false;
}
if self.has_outstanding_paint_msgs() {
return false;
}
if !self.all_pipelines_in_idle_paint_state() {
return false;
}
if !self.got_set_ids_message {
return false;
}
return true;
}
fn composite(&mut self) {
if !self.window.prepare_for_composite() {
return
}
let output_image = opts::get().output_file.is_some() &&
self.is_ready_to_paint_image_output();
let mut framebuffer_ids = vec!();
let mut texture_ids = vec!();
let (width, height) = (self.window_size.width.get(), self.window_size.height.get());
if output_image {
framebuffer_ids = gl::gen_framebuffers(1);
gl::bind_framebuffer(gl::FRAMEBUFFER, framebuffer_ids[0]);
texture_ids = gl::gen_textures(1);
gl::bind_texture(gl::TEXTURE_2D, texture_ids[0]);
gl::tex_image_2d(gl::TEXTURE_2D, 0, gl::RGB as GLint, width as GLsizei,
height as GLsizei, 0, gl::RGB, gl::UNSIGNED_BYTE, None);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);
gl::tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);
gl::framebuffer_texture_2d(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0, gl::TEXTURE_2D,
texture_ids[0], 0);
gl::bind_texture(gl::TEXTURE_2D, 0);
}
profile(time::CompositingCategory, None, self.time_profiler_chan.clone(), || {
debug!("compositor: compositing");
// Adjust the layer dimensions as necessary to correspond to the size of the window.
self.scene.viewport = Rect {
origin: Zero::zero(),
size: self.window_size.as_f32(),
};
// paint the scene.
match self.scene.root {
Some(ref layer) => {
match self.context {
None => {
debug!("compositor: not compositing because context not yet set up")
}
Some(context) => {
rendergl::render_scene(layer.clone(), context, &self.scene);
}
}
}
None => {}
}
});
if output_image {
let path =
from_str::<Path>(opts::get().output_file.as_ref().unwrap().as_slice()).unwrap();
let mut pixels = gl::read_pixels(0, 0,
width as gl::GLsizei,
height as gl::GLsizei,
gl::RGB, gl::UNSIGNED_BYTE);
gl::bind_framebuffer(gl::FRAMEBUFFER, 0);
gl::delete_buffers(texture_ids.as_slice());
gl::delete_frame_buffers(framebuffer_ids.as_slice());
// flip image vertically (texture is upside down)
let orig_pixels = pixels.clone();
let stride = width * 3;
for y in range(0, height) {
let dst_start = y * stride;
let src_start = (height - y - 1) * stride;
let src_slice = orig_pixels.slice(src_start, src_start + stride);
copy_memory(pixels.slice_mut(dst_start, dst_start + stride),
src_slice.slice_to(stride));
}
let mut img = png::Image {
width: width as u32,
height: height as u32,
pixels: png::RGB8(pixels),
};
let res = png::store_png(&mut img, &path);
assert!(res.is_ok());
debug!("shutting down the constellation after generating an output file");
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ExitMsg);
self.shutdown_state = ShuttingDown;
}
// Perform the page flip. This will likely block for a while.
self.window.present();
self.last_composite_time = precise_time_ns();
self.composition_request = NoCompositingNecessary;
self.process_pending_scroll_events();
}
fn composite_if_necessary(&mut self) {
if self.composition_request == NoCompositingNecessary {
self.composition_request = CompositeNow
}
}
fn initialize_compositing(&mut self) {
let context = CompositorTask::create_graphics_context(&self.window.native_metadata());
let show_debug_borders = opts::get().show_debug_borders;
self.context = Some(rendergl::RenderContext::new(context, show_debug_borders))
}
fn find_topmost_layer_at_point_for_layer(&self,
layer: Rc<Layer<CompositorData>>,
point: TypedPoint2D<LayerPixel, f32>,
clip_rect: &TypedRect<LayerPixel, f32>)
-> Option<HitTestResult> {
let layer_bounds = *layer.bounds.borrow();
let masks_to_bounds = *layer.masks_to_bounds.borrow();
if layer_bounds.is_empty() && masks_to_bounds {
return None;
}
let clipped_layer_bounds = match clip_rect.intersection(&layer_bounds) {
Some(rect) => rect,
None => return None,
};
let clip_rect_for_children = if masks_to_bounds {
Rect(Zero::zero(), clipped_layer_bounds.size)
} else {
clipped_layer_bounds.translate(&clip_rect.origin)
};
let child_point = point - layer_bounds.origin;
for child in layer.children().iter().rev() {
// Translate the clip rect into the child's coordinate system.
let clip_rect_for_child =
clip_rect_for_children.translate(&-*child.content_offset.borrow());
let result = self.find_topmost_layer_at_point_for_layer(child.clone(),
child_point,
&clip_rect_for_child);
if result.is_some() {
return result;
}
}
let point = point - *layer.content_offset.borrow();
if !clipped_layer_bounds.contains(&point) {
return None;
}
return Some(HitTestResult { layer: layer, point: point });
}
fn find_topmost_layer_at_point(&self,
point: TypedPoint2D<LayerPixel, f32>)
-> Option<HitTestResult> {
match self.scene.root {
Some(ref layer) => {
self.find_topmost_layer_at_point_for_layer(layer.clone(),
point,
&*layer.bounds.borrow())
}
None => None,
}
}
fn find_layer_with_pipeline_and_layer_id(&self,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
match self.scene.root {
Some(ref layer) =>
find_layer_with_pipeline_and_layer_id_for_layer(layer.clone(),
pipeline_id,
layer_id),
None => None,
}
}
}
fn find_layer_with_pipeline_and_layer_id_for_layer(layer: Rc<Layer<CompositorData>>,
pipeline_id: PipelineId,
layer_id: LayerId)
-> Option<Rc<Layer<CompositorData>>> {
if layer.extra_data.borrow().pipeline.id == pipeline_id &&
layer.extra_data.borrow().id == layer_id {
return Some(layer);
}
for kid in layer.children().iter() {
let result = find_layer_with_pipeline_and_layer_id_for_layer(kid.clone(),
pipeline_id,
layer_id);
if result.is_some() {
return result;
}
}
return None;
}
fn create_root_layer_for_pipeline_and_rect(pipeline: &CompositionPipeline,
frame_rect: Option<TypedRect<PagePx, f32>>)
-> Rc<Layer<CompositorData>> {
let layer_properties = LayerProperties {
pipeline_id: pipeline.id,
epoch: Epoch(0),
id: LayerId::null(),
rect: Rect::zero(),
background_color: azure_hl::Color::new(0., 0., 0., 0.),
scroll_policy: Scrollable,
};
let root_layer = CompositorData::new_layer(pipeline.clone(),
layer_properties,
WantsScrollEvents,
opts::get().tile_size);
// All root layers mask to bounds.
*root_layer.masks_to_bounds.borrow_mut() = true;
match frame_rect {
Some(ref frame_rect) => {
let frame_rect = frame_rect.to_untyped();
*root_layer.bounds.borrow_mut() = Rect::from_untyped(&frame_rect);
}
None => {}
}
return root_layer;
}
impl<Window> CompositorEventListener for IOCompositor<Window> where Window: WindowMethods {
fn handle_event(&mut self, msg: WindowEvent) -> bool {
// Check for new messages coming from the other tasks in the system.
loop {
match self.port.try_recv_compositor_msg() {
None => break,
Some(msg) => {
if !self.handle_browser_message(msg) {
break
}
}
}
}
if self.shutdown_state == FinishedShuttingDown {
// We have exited the compositor and passing window
// messages to script may crash.
debug!("Exiting the compositor due to a request from script.");
return false;
}
// Handle the message coming from the windowing system.
self.handle_window_message(msg);
// If a pinch-zoom happened recently, ask for tiles at the new resolution
if self.zoom_action && precise_time_s() - self.zoom_time > 0.3 {
self.zoom_action = false;
self.scene.mark_layer_contents_as_changed_recursively();
self.send_buffer_requests_for_all_layers();
}
match self.composition_request {
NoCompositingNecessary | CompositeOnScrollTimeout(_) => {}
CompositeNow => self.composite(),
}
self.shutdown_state != FinishedShuttingDown
}
/// Repaints and recomposites synchronously. You must be careful when calling this, as if a
/// paint is not scheduled the compositor will hang forever.
///
/// This is used when resizing the window.
fn repaint_synchronously(&mut self) {
while self.shutdown_state != ShuttingDown {
let msg = self.port.recv_compositor_msg();
let is_paint = match msg {
Paint(..) => true,
_ => false,
};
let keep_going = self.handle_browser_message(msg);
if is_paint {
self.composite();
break
}
if !keep_going {
break
}
}
}
fn shutdown(&mut self) {
// Clear out the compositor layers so that painting tasks can destroy the buffers.
match self.scene.root {
None => {}
Some(ref layer) => layer.forget_all_tiles(),
}
// Drain compositor port, sometimes messages contain channels that are blocking
// another task from finishing (i.e. SetIds)
while self.port.try_recv_compositor_msg().is_some() {}
// Tell the profiler, memory profiler, and scrolling timer to shut down.
let TimeProfilerChan(ref time_profiler_chan) = self.time_profiler_chan;
time_profiler_chan.send(time::ExitMsg);
let MemoryProfilerChan(ref memory_profiler_chan) = self.memory_profiler_chan;
memory_profiler_chan.send(memory::ExitMsg);
self.scrolling_timer.shutdown();
}
fn pinch_zoom_level(&self) -> f32 {
self.viewport_zoom.get() as f32
}
fn get_title_for_main_frame(&self) {
let root_pipeline_id = match self.root_pipeline {
None => return,
Some(ref root_pipeline) => root_pipeline.id,
};
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(GetPipelineTitleMsg(root_pipeline_id));
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use serde_json::Value;
use std::collections::BTreeMap;
use std::net::TcpStream;
#[derive(Serialize)]
struct ThreadAttachedReply {
from: String,
#[serde(rename = "type")]
type_: String,
actor: String,
poppedFrames: Vec<PoppedFrameMsg>,
why: WhyMsg,
}
#[derive(Serialize)]
enum PoppedFrameMsg {}
#[derive(Serialize)]
struct WhyMsg {
#[serde(rename = "type")]
type_: String,
}
#[derive(Serialize)]
struct ThreadResumedReply {
from: String,
#[serde(rename = "type")]
type_: String,
}
#[derive(Serialize)]
struct ReconfigureReply {
from: String
}
pub struct ThreadActor {
name: String,
}
impl ThreadActor {
pub fn new(name: String) -> ThreadActor {
ThreadActor {
name: name,
}
}
}
impl Actor for ThreadActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &BTreeMap<String, Value>,
stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"attach" => {
let msg = ThreadAttachedReply {
from: self.name(),
type_: "paused".to_owned(),
actor: registry.new_name("pause"),
poppedFrames: vec![],
why: WhyMsg { type_: "attached".to_owned() },
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"resume" => {
let msg = ThreadResumedReply {
from: self.name(),
type_: "resumed".to_owned(),
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"reconfigure" => {
stream.write_json_packet(&ReconfigureReply { from: self.name() });
ActorMessageStatus::Processed
}
_ => ActorMessageStatus::Ignored,
})
}
}
Implement a dummy sources message in the thread actor
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use serde_json::Value;
use std::collections::BTreeMap;
use std::net::TcpStream;
#[derive(Serialize)]
struct ThreadAttachedReply {
from: String,
#[serde(rename = "type")]
type_: String,
actor: String,
poppedFrames: Vec<PoppedFrameMsg>,
why: WhyMsg,
}
#[derive(Serialize)]
enum PoppedFrameMsg {}
#[derive(Serialize)]
struct WhyMsg {
#[serde(rename = "type")]
type_: String,
}
#[derive(Serialize)]
struct ThreadResumedReply {
from: String,
#[serde(rename = "type")]
type_: String,
}
#[derive(Serialize)]
struct ReconfigureReply {
from: String
}
#[derive(Serialize)]
struct SourcesReply {
from: String,
sources: Vec<Source>,
}
#[derive(Serialize)]
enum Source {}
pub struct ThreadActor {
name: String,
}
impl ThreadActor {
pub fn new(name: String) -> ThreadActor {
ThreadActor {
name: name,
}
}
}
impl Actor for ThreadActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &BTreeMap<String, Value>,
stream: &mut TcpStream) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"attach" => {
let msg = ThreadAttachedReply {
from: self.name(),
type_: "paused".to_owned(),
actor: registry.new_name("pause"),
poppedFrames: vec![],
why: WhyMsg { type_: "attached".to_owned() },
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"resume" => {
let msg = ThreadResumedReply {
from: self.name(),
type_: "resumed".to_owned(),
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"reconfigure" => {
stream.write_json_packet(&ReconfigureReply { from: self.name() });
ActorMessageStatus::Processed
}
"sources" => {
let msg = SourcesReply {
from: self.name(),
sources: vec![],
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
}
_ => ActorMessageStatus::Ignored,
})
}
}
|
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/arch/amd64/threads.rs
//! Architecture-level thread handling (helpers for ::threads).
use _common::*;
#[derive(Default)]//,Copy,Clone)]
/// Low-level thread state
pub struct State
{
cr3: u64,
rsp: u64,
tlsbase: u64,
// TODO: SSE state
}
extern "C" {
static low_InitialPML4: ();
static v_ktls_size: ();
static v_t_thread_ptr_ofs: ();
static s_tid0_tls_base: u64;
fn task_switch(oldrsp: &mut u64, newrsp: &u64, cr3: u64, tlsbase: u64);
}
#[thread_local]
#[no_mangle]
pub static mut t_thread_ptr: *mut ::threads::Thread = 0 as *mut _;
#[thread_local]
static mut t_thread_ptr_sent: bool = false;
//#[attribute(address_space(256))]
//static cpu_switch_disable: AtomicUsize = ATOMIC_USIZE_INIT;
/// Returns the thread state for TID0 (aka the kernel's core thread)
pub fn init_tid0_state() -> State
{
State {
cr3: &low_InitialPML4 as *const _ as u64,
rsp: 0,
tlsbase: s_tid0_tls_base,
}
}
/// Idle for a short period, called when the CPU has nothing else to do
pub fn idle()
{
if true {
let flags = unsafe { let v: u64; asm!("pushf; pop $0" : "=r" (v)); v };
assert!(flags & 0x200 != 0, "idle() with IF clear, RFLAGS = {:#x}", flags);
}
unsafe { asm!("hlt" : : : : "volatile"); }
}
/// Prepares the TLS block at the stop of a kernel stack
#[no_mangle]
pub extern "C" fn prep_tls(top: usize, bottom: usize, thread_ptr: *mut ::threads::Thread) -> usize
{
/*const*/ let tls_size = &v_ktls_size as *const () as usize;
/*const*/ let t_thread_ptr_ofs = &v_t_thread_ptr_ofs as *const () as usize;
let mut pos = top;
// 1. Create the TLS data block
let tlsblock_top = pos;
pos -= tls_size;
let tlsblock = pos;
// - Populate the TLS data area from the template
// > Also set the thread pointer
unsafe {
assert!( t_thread_ptr_ofs + 8 < tls_size );
::lib::mem::memset(tlsblock as *mut u8, 0, tls_size);
::core::ptr::write( (tlsblock + t_thread_ptr_ofs) as *mut *mut ::threads::Thread, thread_ptr );
}
// 2. Create the TLS pointer region (i.e. the stuff right behind %fs:0)
#[repr(C)]
struct TlsPtrArea
{
data_ptr: usize,
_unk: [u64; 13],
stack_limit: usize,
}
pos -= ::core::mem::size_of::<TlsPtrArea>();
pos -= pos % ::core::mem::min_align_of::<TlsPtrArea>();
let tls_base = pos;
unsafe {
let tls_base = &mut *(tls_base as *mut TlsPtrArea);
tls_base.data_ptr = tlsblock_top;
tls_base.stack_limit = bottom;
}
tls_base
}
/// Start a new thread using the provided TCB
///
/// Allocates a new stack within the current address space
pub fn start_thread<F: FnOnce()+Send>(mut thread: Box<::threads::Thread>, code: F)
{
let stack = ::memory::virt::alloc_stack().into_array::<u8>();;
let stack_rgn_top = &stack[stack.len()-1] as *const _ as usize + 1;
let mut stack_top = stack_rgn_top;
let stack_bottom = &stack[0] as *const _ as usize;
// 1. Allocate TLS block at the top of the stack
log_trace!("prep_tls({:#x},{:#x},{:p})", stack_top, stack_bottom, &*thread);
let tls_base = prep_tls(stack_top, stack_bottom, &mut *thread as *mut _);
stack_top = tls_base;
// 2. Populate stack with `code`
stack_top -= ::core::mem::size_of::<F>();
stack_top -= stack_top % ::core::mem::min_align_of::<F>();
let code_ptr = stack_top;
unsafe {
::core::ptr::write(code_ptr as *mut F, code);
}
// 3. Populate stack with trampoline state
// - All that is needed is to push the trampoline address (it handles calling the rust code)
unsafe {
stack_top -= 8;
::core::ptr::write(stack_top as *mut u64, thread_root::<F> as usize as u64);
stack_top -= 8;
::core::ptr::write(stack_top as *mut u64, thread_trampoline as usize as u64);
}
// 4. Apply newly updated state
thread.cpu_state.rsp = stack_top as u64;
thread.cpu_state.tlsbase = tls_base as u64;
thread.cpu_state.cr3 = unsafe { (*t_thread_ptr).cpu_state.cr3 };
// 5. Switch to new thread
switch_to(thread);
extern "C" {
/// Pops the root function, and sets RDI=RSP
fn thread_trampoline();
}
fn thread_root<F: FnOnce()+Send>(code_ptr: *const F) -> ! {
// Copy the closure locally
// - TODO: Find a way that avoids needing to make this unnessesary copy. By-value FnOnce is kinda undefined, sadly
let code = unsafe { ::core::ptr::read(code_ptr) };
// 1. Run closure
code();
// 2. terminate thread
panic!("TODO: Terminate thread at end of thread_root");
}
}
/// Switch to the passed thread (suspending the current thread until it is rescheduled)
pub fn switch_to(newthread: Box<::threads::Thread>)
{
if is_task_switching_disabled()
{
// This code should only ever trigger if a Spinlock-holding thread
// was interrupted by an IRQ. If said thread attempts to sleep, it's an error
assert!( newthread.is_runnable() );
}
else
{
unsafe
{
// TODO: Lazy save/restore SSE state
let outstate = &mut (*t_thread_ptr).cpu_state;
let state = &newthread.cpu_state;
//assert!(state.rsp != 0);
assert!(state.cr3 != 0);
assert!(state.tlsbase != 0);
task_switch(&mut outstate.rsp, &state.rsp, state.cr3, state.tlsbase);
}
unsafe
{
t_thread_ptr_sent = false;
::core::mem::forget(newthread);
}
}
}
/// Obtain the current thread's pointer (as a owned box, thread is destroyed when box is dropped)
pub fn get_thread_ptr() -> Option<Box<::threads::Thread>>
{
unsafe {
assert!( !t_thread_ptr.is_null() );
assert!( !t_thread_ptr_sent );
t_thread_ptr_sent = true;
::core::mem::transmute( t_thread_ptr )
}
}
/// Release or set the current thread pointer
pub fn set_thread_ptr(ptr: Box<::threads::Thread>)
{
unsafe {
let ptr: *mut _ = ::core::mem::transmute(ptr);
if t_thread_ptr == ptr {
assert!( !t_thread_ptr_sent );
t_thread_ptr_sent = false;
}
else {
assert!( t_thread_ptr.is_null(), "t_thread_ptr is not null when set_thread_ptr is called, instead {:p}", t_thread_ptr );
t_thread_ptr = ptr;
t_thread_ptr_sent = false;
}
}
}
/// Disable task switching until corresponding `enable_task_switch` call
pub fn disable_task_switch()
{
// TODO: increment CPU-local counter representing task switch state
}
/// Re-enable task switching
pub fn enable_task_switch()
{
}
/// Returns true is task switching is enabled
pub fn is_task_switching_disabled() -> bool
{
// Return (s_cpu_local.
false
}
// vim: ft=rust
Fixed bug caused/exposed by binutils upgrade
- llvm generated a PC-relative address calculation, but the address was <2GB, link error
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/arch/amd64/threads.rs
//! Architecture-level thread handling (helpers for ::threads).
use _common::*;
#[derive(Default)]//,Copy,Clone)]
/// Low-level thread state
pub struct State
{
cr3: u64,
rsp: u64,
tlsbase: u64,
// TODO: SSE state
}
extern "C" {
static InitialPML4: ();
static v_ktls_size: ();
static v_t_thread_ptr_ofs: ();
static s_tid0_tls_base: u64;
fn task_switch(oldrsp: &mut u64, newrsp: &u64, cr3: u64, tlsbase: u64);
}
#[thread_local]
#[no_mangle]
pub static mut t_thread_ptr: *mut ::threads::Thread = 0 as *mut _;
#[thread_local]
static mut t_thread_ptr_sent: bool = false;
//#[attribute(address_space(256))]
//static cpu_switch_disable: AtomicUsize = ATOMIC_USIZE_INIT;
/// Returns the thread state for TID0 (aka the kernel's core thread)
pub fn init_tid0_state() -> State
{
State {
cr3: &InitialPML4 as *const _ as u64 - super::memory::addresses::IDENT_START as u64,
rsp: 0,
tlsbase: s_tid0_tls_base,
}
}
/// Idle for a short period, called when the CPU has nothing else to do
pub fn idle()
{
if true {
let flags = unsafe { let v: u64; asm!("pushf; pop $0" : "=r" (v)); v };
assert!(flags & 0x200 != 0, "idle() with IF clear, RFLAGS = {:#x}", flags);
}
unsafe { asm!("hlt" : : : : "volatile"); }
}
/// Prepares the TLS block at the stop of a kernel stack
#[no_mangle]
pub extern "C" fn prep_tls(top: usize, bottom: usize, thread_ptr: *mut ::threads::Thread) -> usize
{
/*const*/ let tls_size = &v_ktls_size as *const () as usize;
/*const*/ let t_thread_ptr_ofs = &v_t_thread_ptr_ofs as *const () as usize;
let mut pos = top;
// 1. Create the TLS data block
let tlsblock_top = pos;
pos -= tls_size;
let tlsblock = pos;
// - Populate the TLS data area from the template
// > Also set the thread pointer
unsafe {
assert!( t_thread_ptr_ofs + 8 < tls_size );
::lib::mem::memset(tlsblock as *mut u8, 0, tls_size);
::core::ptr::write( (tlsblock + t_thread_ptr_ofs) as *mut *mut ::threads::Thread, thread_ptr );
}
// 2. Create the TLS pointer region (i.e. the stuff right behind %fs:0)
#[repr(C)]
struct TlsPtrArea
{
data_ptr: usize,
_unk: [u64; 13],
stack_limit: usize,
}
pos -= ::core::mem::size_of::<TlsPtrArea>();
pos -= pos % ::core::mem::min_align_of::<TlsPtrArea>();
let tls_base = pos;
unsafe {
let tls_base = &mut *(tls_base as *mut TlsPtrArea);
tls_base.data_ptr = tlsblock_top;
tls_base.stack_limit = bottom;
}
tls_base
}
/// Start a new thread using the provided TCB
///
/// Allocates a new stack within the current address space
pub fn start_thread<F: FnOnce()+Send>(mut thread: Box<::threads::Thread>, code: F)
{
let stack = ::memory::virt::alloc_stack().into_array::<u8>();;
let stack_rgn_top = &stack[stack.len()-1] as *const _ as usize + 1;
let mut stack_top = stack_rgn_top;
let stack_bottom = &stack[0] as *const _ as usize;
// 1. Allocate TLS block at the top of the stack
log_trace!("prep_tls({:#x},{:#x},{:p})", stack_top, stack_bottom, &*thread);
let tls_base = prep_tls(stack_top, stack_bottom, &mut *thread as *mut _);
stack_top = tls_base;
// 2. Populate stack with `code`
stack_top -= ::core::mem::size_of::<F>();
stack_top -= stack_top % ::core::mem::min_align_of::<F>();
let code_ptr = stack_top;
unsafe {
::core::ptr::write(code_ptr as *mut F, code);
}
// 3. Populate stack with trampoline state
// - All that is needed is to push the trampoline address (it handles calling the rust code)
unsafe {
stack_top -= 8;
::core::ptr::write(stack_top as *mut u64, thread_root::<F> as usize as u64);
stack_top -= 8;
::core::ptr::write(stack_top as *mut u64, thread_trampoline as usize as u64);
}
// 4. Apply newly updated state
thread.cpu_state.rsp = stack_top as u64;
thread.cpu_state.tlsbase = tls_base as u64;
thread.cpu_state.cr3 = unsafe { (*t_thread_ptr).cpu_state.cr3 };
// 5. Switch to new thread
switch_to(thread);
extern "C" {
/// Pops the root function, and sets RDI=RSP
fn thread_trampoline();
}
fn thread_root<F: FnOnce()+Send>(code_ptr: *const F) -> ! {
// Copy the closure locally
// - TODO: Find a way that avoids needing to make this unnessesary copy. By-value FnOnce is kinda undefined, sadly
let code = unsafe { ::core::ptr::read(code_ptr) };
// 1. Run closure
code();
// 2. terminate thread
panic!("TODO: Terminate thread at end of thread_root");
}
}
/// Switch to the passed thread (suspending the current thread until it is rescheduled)
pub fn switch_to(newthread: Box<::threads::Thread>)
{
if is_task_switching_disabled()
{
// This code should only ever trigger if a Spinlock-holding thread
// was interrupted by an IRQ. If said thread attempts to sleep, it's an error
assert!( newthread.is_runnable() );
}
else
{
unsafe
{
// TODO: Lazy save/restore SSE state
let outstate = &mut (*t_thread_ptr).cpu_state;
let state = &newthread.cpu_state;
//assert!(state.rsp != 0);
assert!(state.cr3 != 0);
assert!(state.tlsbase != 0);
task_switch(&mut outstate.rsp, &state.rsp, state.cr3, state.tlsbase);
}
unsafe
{
t_thread_ptr_sent = false;
::core::mem::forget(newthread);
}
}
}
/// Obtain the current thread's pointer (as a owned box, thread is destroyed when box is dropped)
pub fn get_thread_ptr() -> Option<Box<::threads::Thread>>
{
unsafe {
assert!( !t_thread_ptr.is_null() );
assert!( !t_thread_ptr_sent );
t_thread_ptr_sent = true;
::core::mem::transmute( t_thread_ptr )
}
}
/// Release or set the current thread pointer
pub fn set_thread_ptr(ptr: Box<::threads::Thread>)
{
unsafe {
let ptr: *mut _ = ::core::mem::transmute(ptr);
if t_thread_ptr == ptr {
assert!( !t_thread_ptr_sent );
t_thread_ptr_sent = false;
}
else {
assert!( t_thread_ptr.is_null(), "t_thread_ptr is not null when set_thread_ptr is called, instead {:p}", t_thread_ptr );
t_thread_ptr = ptr;
t_thread_ptr_sent = false;
}
}
}
/// Disable task switching until corresponding `enable_task_switch` call
pub fn disable_task_switch()
{
// TODO: increment CPU-local counter representing task switch state
}
/// Re-enable task switching
pub fn enable_task_switch()
{
}
/// Returns true is task switching is enabled
pub fn is_task_switching_disabled() -> bool
{
// Return (s_cpu_local.
false
}
// vim: ft=rust
|
extern crate nucleotide_codons as codons;
#[test]
fn test_methionine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("ATG"), Ok("methionine"));
}
#[test]
#[ignore]
fn test_cysteine_tgt() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TGT"), Ok("cysteine"));
}
#[test]
#[ignore]
fn test_cysteine_tgy() { // "compressed" name for TGT and TGC
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TGY"), Ok("cysteine"));
}
#[test]
#[ignore]
fn test_stop() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TAA"), Ok("stop codon"));
}
#[test]
#[ignore]
fn test_valine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("GTN"), Ok("valine"));
}
#[test]
#[ignore]
fn test_isoleucine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("ATH"), Ok("isoleucine"));
}
#[test]
#[ignore]
fn test_arginine_name() {
// In arginine CGA can be "compresed" both as CGN and as MGR
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("CGA"), Ok("arginine"));
assert_eq!(info.name_for("CGN"), Ok("arginine"));
assert_eq!(info.name_for("MGR"), Ok("arginine"));
}
#[test]
#[ignore]
fn test_invalid() {
let info = codons::parse(make_pairs());
assert!(info.name_for("").is_err());
assert!(info.name_for("VWX").is_err()); // X is not a shorthand
assert!(info.name_for("AB").is_err()); // too short
assert!(info.name_for("ABCD").is_err()); // too long
}
// The input data constructor. Returns a list of codon, name pairs.
fn make_pairs() -> Vec<(&'static str, &'static str)> {
let grouped = vec![
("isoleucine", vec!["ATT", "ATC", "ATA"]),
("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]),
("valine", vec!["GTT", "GTC", "GTA", "GTG"]),
("phenylalanine", vec!["TTT", "TTC"]),
("methionine", vec!["ATG"]),
("cysteine", vec!["TGT", "TGC"]),
("alanine", vec!["GCT", "GCC", "GCA", "GCG"]),
("glycine", vec!["GGT", "GGC", "GGA", "GGG"]),
("proline", vec!["CCT", "CCC", "CCA", "CCG"]),
("threonine", vec!["ACT", "ACC", "ACA", "ACG"]),
("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]),
("tyrosine", vec!["TAT", "TAC"]),
("tryptophan", vec!["TGG"]),
("glutamine", vec!["CAA", "CAG"]),
("asparagine", vec!["AAT", "AAC"]),
("histidine", vec!["CAT", "CAC"]),
("glutamic acid", vec!["GAA", "GAG"]),
("aspartic acid", vec!["GAT", "GAC"]),
("lysine", vec!["AAA", "AAG"]),
("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]),
("stop codon", vec!["TAA", "TAG", "TGA"])];
let mut pairs = Vec::<(&'static str, &'static str)>::new();
for (name, codons) in grouped.into_iter() {
for codon in codons {
pairs.push((codon, name));
}
};
pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b));
return pairs
}
nucleotide-codons: Test TGT and TGC in TGY test
The comment at the top of the test explains that TGY decompresses to one
of TGT, TGC. So then, the test should test that.
extern crate nucleotide_codons as codons;
#[test]
fn test_methionine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("ATG"), Ok("methionine"));
}
#[test]
#[ignore]
fn test_cysteine_tgt() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TGT"), Ok("cysteine"));
}
#[test]
#[ignore]
fn test_cysteine_tgy() { // "compressed" name for TGT and TGC
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TGT"), info.name_for("TGY"));
assert_eq!(info.name_for("TGC"), info.name_for("TGY"));
}
#[test]
#[ignore]
fn test_stop() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("TAA"), Ok("stop codon"));
}
#[test]
#[ignore]
fn test_valine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("GTN"), Ok("valine"));
}
#[test]
#[ignore]
fn test_isoleucine() {
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("ATH"), Ok("isoleucine"));
}
#[test]
#[ignore]
fn test_arginine_name() {
// In arginine CGA can be "compresed" both as CGN and as MGR
let info = codons::parse(make_pairs());
assert_eq!(info.name_for("CGA"), Ok("arginine"));
assert_eq!(info.name_for("CGN"), Ok("arginine"));
assert_eq!(info.name_for("MGR"), Ok("arginine"));
}
#[test]
#[ignore]
fn test_invalid() {
let info = codons::parse(make_pairs());
assert!(info.name_for("").is_err());
assert!(info.name_for("VWX").is_err()); // X is not a shorthand
assert!(info.name_for("AB").is_err()); // too short
assert!(info.name_for("ABCD").is_err()); // too long
}
// The input data constructor. Returns a list of codon, name pairs.
fn make_pairs() -> Vec<(&'static str, &'static str)> {
let grouped = vec![
("isoleucine", vec!["ATT", "ATC", "ATA"]),
("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]),
("valine", vec!["GTT", "GTC", "GTA", "GTG"]),
("phenylalanine", vec!["TTT", "TTC"]),
("methionine", vec!["ATG"]),
("cysteine", vec!["TGT", "TGC"]),
("alanine", vec!["GCT", "GCC", "GCA", "GCG"]),
("glycine", vec!["GGT", "GGC", "GGA", "GGG"]),
("proline", vec!["CCT", "CCC", "CCA", "CCG"]),
("threonine", vec!["ACT", "ACC", "ACA", "ACG"]),
("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]),
("tyrosine", vec!["TAT", "TAC"]),
("tryptophan", vec!["TGG"]),
("glutamine", vec!["CAA", "CAG"]),
("asparagine", vec!["AAT", "AAC"]),
("histidine", vec!["CAT", "CAC"]),
("glutamic acid", vec!["GAA", "GAG"]),
("aspartic acid", vec!["GAT", "GAC"]),
("lysine", vec!["AAA", "AAG"]),
("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]),
("stop codon", vec!["TAA", "TAG", "TGA"])];
let mut pairs = Vec::<(&'static str, &'static str)>::new();
for (name, codons) in grouped.into_iter() {
for codon in codons {
pairs.push((codon, name));
}
};
pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b));
return pairs
}
|
#![feature(test)]
extern crate test;
extern crate columnar;
use columnar::Columnar;
use columnar::bitmap::FilteredCollection;
#[macro_use] extern crate columnar_derive;
use std::mem::size_of;
// The data for the benchmark, consiting of 8x64b=512b which is a cache line on most architectures
#[derive(Columnar, Debug, Default, Clone)]
struct Data {
id: usize,
val: f64,
dummy: [usize; 6],
}
/// Perform assign operation on columnar type, input=output
#[bench]
fn data_columnar(b: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: 15., ..Data::default()});
}
let mut dc = <Data as Columnar>::with_capacity(size);
dc.extend(a);
b.bytes = (size_of::<usize>() * size) as u64;
b.iter(|| {
for e in dc.iter_mut() {
*e.id *= 2;
}
})
}
/// Perform add/assign operation on row type with three inputs, one output
#[bench]
fn data_columnar_add_assign(bench: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
let mut ca = <Data as Columnar>::with_capacity(size);
let mut cb = <Data as Columnar>::with_capacity(size);
let mut cr = <Data as Columnar>::with_capacity(size);
ca.extend(a);
cb.extend(b);
test::black_box(r.first().unwrap().dummy);
cr.extend(r);
bench.bytes = (size_of::<f64>() * size * 3) as u64;
bench.iter(|| {
let zip: ::std::iter::Zip<_, _> = ca.iter().zip(cb.iter()).zip(cr.iter_mut());
for ((ea, eb), er) in zip {
*er.val += ea.val + eb.val;
};
})
}
/// Perform assign operation on row type, input=output
#[bench]
fn data_row_add_assign(bench: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
test::black_box(r.first().unwrap().dummy);
bench.bytes = (size_of::<f64>() * size * 3) as u64;
bench.iter(|| {
let zip: ::std::iter::Zip<_, _> = a.iter().zip(b.iter()).zip(r.iter_mut());
for ((ea, eb), er) in zip {
er.val += ea.val + eb.val;
};
})
}
/// Perform assign operation on row type, input=output
#[bench]
fn data_row(b: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: 15., ..Data::default()});
}
b.bytes = (size_of::<usize>() * size) as u64;
b.iter(|| {
for e in &mut a {
e.id *= 2;
}
})
}
/// Perform add/assign operation on columnar type with three inputs, one output
#[bench]
fn data_bitmap_columnar_add_assign(bench: &mut test::Bencher) {
let size = 1 << (20 + 1);
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
let mut ca = <Data as Columnar>::with_capacity(size);
let mut cb = <Data as Columnar>::with_capacity(size);
let mut cr = <Data as Columnar>::with_capacity(size);
ca.extend(a);
cb.extend(b);
test::black_box(r.first().unwrap().dummy);
cr.extend(r);
let mut bitmap_container: FilteredCollection<_> = FilteredCollection::new(&ca, ca.len());
// Retain every second element
bitmap_container.retain(|d| d.id & 1 == 1);
// We touch three values but the bitmap only exposes every second element
bench.bytes = (size_of::<f64>() * size * 3 / 2) as u64;
bench.iter(|| {
// iterate the filtered collection and zip it with `cb` and `cr`.
let zip: ::std::iter::Zip<_, _> = bitmap_container.iter().zip(cb.iter()).zip(cr.iter_mut());
for ((ea, eb), er) in zip {
*er.val += ea.val + eb.val;
};
})
}
/// Perform add/assign operation on columnar type with three inputs, one output
#[bench]
fn data_bitmap_vec_add_assign(bench: &mut test::Bencher) {
let size = 1 << (20 + 1);
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
test::black_box(r.first().unwrap().dummy);
let mut bitmap_container: FilteredCollection<_> = FilteredCollection::new(&a, a.len());
// Retain every second element
bitmap_container.retain(|d| d.id & 1 == 1);
// We touch three values but the bitmap only exposes every second element
bench.bytes = (size_of::<f64>() * size * 3 / 2) as u64;
bench.iter(|| {
// iterate the filtered collection and zip it with `b` and `r`.
let zip: ::std::iter::Zip<_, _> = bitmap_container.iter().zip(b.iter()).zip(r.iter_mut());
for ((ea, eb), er) in zip {
er.val += ea.val + eb.val;
};
})
}
bench: Benchmark extend operation
Signed-off-by: Moritz Hoffmann <ed7fdef65a78bc496c776e2fef393a99a38e9286@gmail.com>
#![feature(test)]
extern crate test;
extern crate columnar;
use columnar::Columnar;
use columnar::bitmap::FilteredCollection;
#[macro_use] extern crate columnar_derive;
use std::mem::size_of;
// The data for the benchmark, consiting of 8x64b=512b which is a cache line on most architectures
#[derive(Columnar, Debug, Default, Clone)]
struct Data {
id: usize,
val: f64,
dummy: [usize; 6],
}
/// Perform assign operation on columnar type, input=output
#[bench]
fn data_columnar(b: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: 15., ..Data::default()});
}
let mut dc = <Data as Columnar>::with_capacity(size);
dc.extend(a);
b.bytes = (size_of::<usize>() * size) as u64;
b.iter(|| {
for e in dc.iter_mut() {
*e.id *= 2;
}
})
}
/// Perform add/assign operation on row type with three inputs, one output
#[bench]
fn data_columnar_add_assign(bench: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
let mut ca = <Data as Columnar>::with_capacity(size);
let mut cb = <Data as Columnar>::with_capacity(size);
let mut cr = <Data as Columnar>::with_capacity(size);
ca.extend(a);
cb.extend(b);
test::black_box(r.first().unwrap().dummy);
cr.extend(r);
bench.bytes = (size_of::<f64>() * size * 3) as u64;
bench.iter(|| {
let zip: ::std::iter::Zip<_, _> = ca.iter().zip(cb.iter()).zip(cr.iter_mut());
for ((ea, eb), er) in zip {
*er.val += ea.val + eb.val;
};
})
}
/// Perform assign operation on row type, input=output
#[bench]
fn data_row_add_assign(bench: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
test::black_box(r.first().unwrap().dummy);
bench.bytes = (size_of::<f64>() * size * 3) as u64;
bench.iter(|| {
let zip: ::std::iter::Zip<_, _> = a.iter().zip(b.iter()).zip(r.iter_mut());
for ((ea, eb), er) in zip {
er.val += ea.val + eb.val;
};
})
}
/// Perform assign operation on row type, input=output
#[bench]
fn data_row(b: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: 15., ..Data::default()});
}
b.bytes = (size_of::<usize>() * size) as u64;
b.iter(|| {
for e in &mut a {
e.id *= 2;
}
})
}
/// Perform add/assign operation on columnar type with three inputs, one output
#[bench]
fn data_bitmap_columnar_add_assign(bench: &mut test::Bencher) {
let size = 1 << (20 + 1);
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
let mut ca = <Data as Columnar>::with_capacity(size);
let mut cb = <Data as Columnar>::with_capacity(size);
let mut cr = <Data as Columnar>::with_capacity(size);
ca.extend(a);
cb.extend(b);
test::black_box(r.first().unwrap().dummy);
cr.extend(r);
let mut bitmap_container: FilteredCollection<_> = FilteredCollection::new(&ca, ca.len());
// Retain every second element
bitmap_container.retain(|d| d.id & 1 == 1);
// We touch three values but the bitmap only exposes every second element
bench.bytes = (size_of::<f64>() * size * 3 / 2) as u64;
bench.iter(|| {
// iterate the filtered collection and zip it with `cb` and `cr`.
let zip: ::std::iter::Zip<_, _> = bitmap_container.iter().zip(cb.iter()).zip(cr.iter_mut());
for ((ea, eb), er) in zip {
*er.val += ea.val + eb.val;
};
})
}
/// Perform add/assign operation on columnar type with three inputs, one output
#[bench]
fn data_bitmap_vec_add_assign(bench: &mut test::Bencher) {
let size = 1 << (20 + 1);
let mut a = Vec::with_capacity(size);
let mut b = Vec::with_capacity(size);
let mut r = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: i as f64 * 0.6, ..Data::default()});
b.push(Data { id: i + size, val: size as f64 + i as f64 * 0.6, ..Data::default()});
r.push(Data { id: 0, val: 1., ..Data::default()});
}
test::black_box(r.first().unwrap().dummy);
let mut bitmap_container: FilteredCollection<_> = FilteredCollection::new(&a, a.len());
// Retain every second element
bitmap_container.retain(|d| d.id & 1 == 1);
// We touch three values but the bitmap only exposes every second element
bench.bytes = (size_of::<f64>() * size * 3 / 2) as u64;
bench.iter(|| {
// iterate the filtered collection and zip it with `b` and `r`.
let zip: ::std::iter::Zip<_, _> = bitmap_container.iter().zip(b.iter()).zip(r.iter_mut());
for ((ea, eb), er) in zip {
er.val += ea.val + eb.val;
};
})
}
/// Perform assign operation on columnar type, input=output
#[bench]
fn data_row_to_columnar(b: &mut test::Bencher) {
let size = 1 << 20;
let mut a = Vec::with_capacity(size);
for i in 0..size {
a.push(Data { id: i, val: 15., ..Data::default()});
}
b.bytes = (size_of::<Data>() * size) as u64;
let mut dc = <Data as Columnar>::with_capacity(size);
let a = &a;
b.iter(move || {
dc.clear();
dc.extend(a.iter().cloned());
})
}
|
//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//
use crate::sys::component::Component;
use crate::sys::disk::*;
use crate::sys::ffi;
use crate::sys::network::Networks;
use crate::sys::process::*;
use crate::sys::processor::*;
#[cfg(target_os = "macos")]
use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease};
use crate::{LoadAvg, Pid, ProcessorExt, RefreshKind, SystemExt, User};
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use crate::ProcessExt;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::mem;
use std::sync::Arc;
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use libc::size_t;
use libc::{
c_char, c_int, c_void, host_statistics64, mach_port_t, mach_task_self, sysconf, sysctl,
sysctlbyname, timeval, vm_statistics64, _SC_PAGESIZE,
};
/// Structs containing system's information.
pub struct System {
process_list: HashMap<Pid, Process>,
mem_total: u64,
mem_free: u64,
mem_available: u64,
swap_total: u64,
swap_free: u64,
global_processor: Processor,
processors: Vec<Processor>,
page_size_kb: u64,
components: Vec<Component>,
// Used to get CPU information, not supported on iOS, or inside the default macOS sandbox.
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
connection: Option<ffi::io_connect_t>,
disks: Vec<Disk>,
networks: Networks,
port: mach_port_t,
users: Vec<User>,
boot_time: u64,
// Used to get disk information, to be more specific, it's needed by the
// DADiskCreateFromVolumePath function. Not supported on iOS.
#[cfg(target_os = "macos")]
session: ffi::SessionWrap,
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
clock_info: Option<crate::sys::macos::system::SystemTimeInfo>,
}
impl Drop for System {
fn drop(&mut self) {
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
if let Some(conn) = self.connection {
unsafe {
ffi::IOServiceClose(conn);
}
}
#[cfg(target_os = "macos")]
if !self.session.0.is_null() {
unsafe {
CFRelease(self.session.0 as _);
}
}
}
}
pub(crate) struct Wrap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>);
unsafe impl<'a> Send for Wrap<'a> {}
unsafe impl<'a> Sync for Wrap<'a> {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
impl System {
fn clear_procs(&mut self) {
use crate::sys::macos::process;
let mut to_delete = Vec::new();
for (pid, mut proc_) in &mut self.process_list {
if !process::has_been_updated(&mut proc_) {
to_delete.push(*pid);
}
}
for pid in to_delete {
self.process_list.remove(&pid);
}
}
}
fn boot_time() -> u64 {
let mut boot_time = timeval {
tv_sec: 0,
tv_usec: 0,
};
let mut len = std::mem::size_of::<timeval>();
let mut mib: [c_int; 2] = [libc::CTL_KERN, libc::KERN_BOOTTIME];
if unsafe {
sysctl(
mib.as_mut_ptr(),
2,
&mut boot_time as *mut timeval as *mut _,
&mut len,
std::ptr::null_mut(),
0,
)
} < 0
{
0
} else {
boot_time.tv_sec as _
}
}
impl SystemExt for System {
const IS_SUPPORTED: bool = true;
fn new_with_specifics(refreshes: RefreshKind) -> System {
let port = unsafe { libc::mach_host_self() };
let (global_processor, processors) = init_processors(port);
let mut s = System {
process_list: HashMap::with_capacity(200),
mem_total: 0,
mem_free: 0,
mem_available: 0,
swap_total: 0,
swap_free: 0,
global_processor,
processors,
page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 / 1_000 },
components: Vec::with_capacity(2),
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
connection: get_io_service_connection(),
disks: Vec::with_capacity(1),
networks: Networks::new(),
port,
users: Vec::new(),
boot_time: boot_time(),
#[cfg(target_os = "macos")]
session: ffi::SessionWrap(::std::ptr::null_mut()),
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
clock_info: crate::sys::macos::system::SystemTimeInfo::new(port),
};
s.refresh_specifics(refreshes);
s
}
fn refresh_memory(&mut self) {
let mut mib = [0, 0];
unsafe {
// get system values
// get swap info
let mut xs: libc::xsw_usage = mem::zeroed::<libc::xsw_usage>();
if get_sys_value(
libc::CTL_VM as _,
libc::VM_SWAPUSAGE as _,
mem::size_of::<libc::xsw_usage>(),
&mut xs as *mut _ as *mut c_void,
&mut mib,
) {
self.swap_total = xs.xsu_total / 1_000;
self.swap_free = xs.xsu_avail / 1_000;
}
// get ram info
if self.mem_total < 1 {
get_sys_value(
libc::CTL_HW as _,
libc::HW_MEMSIZE as _,
mem::size_of::<u64>(),
&mut self.mem_total as *mut u64 as *mut c_void,
&mut mib,
);
self.mem_total /= 1_000;
}
let mut count: u32 = ffi::HOST_VM_INFO64_COUNT;
let mut stat = mem::zeroed::<vm_statistics64>();
if host_statistics64(
self.port,
libc::HOST_VM_INFO64,
&mut stat as *mut vm_statistics64 as *mut _,
&mut count,
) == libc::KERN_SUCCESS
{
// From the apple documentation:
//
// /*
// * NB: speculative pages are already accounted for in "free_count",
// * so "speculative_count" is the number of "free" pages that are
// * used to hold data that was read speculatively from disk but
// * haven't actually been used by anyone so far.
// */
self.mem_available = self.mem_total
- (u64::from(stat.active_count)
+ u64::from(stat.inactive_count)
+ u64::from(stat.wire_count)
+ u64::from(stat.speculative_count)
- u64::from(stat.purgeable_count))
* self.page_size_kb;
self.mem_free = u64::from(stat.free_count) * self.page_size_kb;
}
}
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_components_list(&mut self) {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_components_list(&mut self) {
if let Some(con) = self.connection {
self.components.clear();
// getting CPU critical temperature
let critical_temp = crate::apple::component::get_temperature(
con,
&['T' as i8, 'C' as i8, '0' as i8, 'D' as i8, 0],
);
for (id, v) in crate::apple::component::COMPONENTS_TEMPERATURE_IDS.iter() {
if let Some(c) = Component::new((*id).to_owned(), None, critical_temp, v, con) {
self.components.push(c);
}
}
}
}
fn refresh_cpu(&mut self) {
let processors = &mut self.processors;
update_processor_usage(
self.port,
&mut self.global_processor,
|proc_data, cpu_info| {
let mut percentage = 0f32;
let mut offset = 0;
for proc_ in processors.iter_mut() {
let cpu_usage = compute_processor_usage(proc_, cpu_info, offset);
proc_.update(cpu_usage, Arc::clone(&proc_data));
percentage += proc_.cpu_usage();
offset += libc::CPU_STATE_MAX as isize;
}
(percentage, processors.len())
},
);
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_processes(&mut self) {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_processes(&mut self) {
use crate::utils::into_iter;
let count = unsafe { libc::proc_listallpids(::std::ptr::null_mut(), 0) };
if count < 1 {
return;
}
if let Some(pids) = get_proc_list() {
let arg_max = get_arg_max();
let port = self.port;
let time_interval = self.clock_info.as_mut().map(|c| c.get_time_interval(port));
let entries: Vec<Process> = {
let wrap = &Wrap(UnsafeCell::new(&mut self.process_list));
#[cfg(feature = "multithread")]
use rayon::iter::ParallelIterator;
into_iter(pids)
.flat_map(|pid| {
update_process(wrap, pid, arg_max as size_t, time_interval)
.ok()
.flatten()
})
.collect()
};
entries.into_iter().for_each(|entry| {
self.process_list.insert(entry.pid(), entry);
});
self.clear_procs();
}
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_process(&mut self, _: Pid) -> bool {
false
}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_process(&mut self, pid: Pid) -> bool {
let arg_max = get_arg_max();
let port = self.port;
let time_interval = self.clock_info.as_mut().map(|c| c.get_time_interval(port));
match {
let wrap = Wrap(UnsafeCell::new(&mut self.process_list));
update_process(&wrap, pid, arg_max as size_t, time_interval)
} {
Ok(Some(p)) => {
self.process_list.insert(p.pid(), p);
true
}
Ok(_) => true,
Err(_) => false,
}
}
#[cfg(target_os = "ios")]
fn refresh_disks_list(&mut self) {}
#[cfg(target_os = "macos")]
fn refresh_disks_list(&mut self) {
if self.session.0.is_null() {
self.session.0 = unsafe { ffi::DASessionCreate(kCFAllocatorDefault as _) };
}
self.disks = get_disks(self.session.0);
}
fn refresh_users_list(&mut self) {
self.users = crate::apple::users::get_users_list();
}
// COMMON PART
//
// Need to be moved into a "common" file to avoid duplication.
fn processes(&self) -> &HashMap<Pid, Process> {
&self.process_list
}
fn process(&self, pid: Pid) -> Option<&Process> {
self.process_list.get(&pid)
}
fn global_processor_info(&self) -> &Processor {
&self.global_processor
}
fn processors(&self) -> &[Processor] {
&self.processors
}
fn physical_core_count(&self) -> Option<usize> {
let mut physical_core_count = 0;
if unsafe {
get_sys_value_by_name(
b"hw.physicalcpu\0",
&mut mem::size_of::<u32>(),
&mut physical_core_count as *mut usize as *mut c_void,
)
} {
Some(physical_core_count)
} else {
None
}
}
fn networks(&self) -> &Networks {
&self.networks
}
fn networks_mut(&mut self) -> &mut Networks {
&mut self.networks
}
fn total_memory(&self) -> u64 {
self.mem_total
}
fn free_memory(&self) -> u64 {
self.mem_free
}
fn available_memory(&self) -> u64 {
self.mem_available
}
fn used_memory(&self) -> u64 {
self.mem_total - self.mem_free
}
fn total_swap(&self) -> u64 {
self.swap_total
}
fn free_swap(&self) -> u64 {
self.swap_free
}
// need to be checked
fn used_swap(&self) -> u64 {
self.swap_total - self.swap_free
}
fn components(&self) -> &[Component] {
&self.components
}
fn components_mut(&mut self) -> &mut [Component] {
&mut self.components
}
fn disks(&self) -> &[Disk] {
&self.disks
}
fn disks_mut(&mut self) -> &mut [Disk] {
&mut self.disks
}
fn uptime(&self) -> u64 {
let csec = unsafe { libc::time(::std::ptr::null_mut()) };
unsafe { libc::difftime(csec, self.boot_time as _) as u64 }
}
fn load_average(&self) -> LoadAvg {
let mut loads = vec![0f64; 3];
unsafe {
libc::getloadavg(loads.as_mut_ptr(), 3);
}
LoadAvg {
one: loads[0],
five: loads[1],
fifteen: loads[2],
}
}
fn users(&self) -> &[User] {
&self.users
}
fn boot_time(&self) -> u64 {
self.boot_time
}
fn name(&self) -> Option<String> {
get_system_info(libc::KERN_OSTYPE, Some("Darwin"))
}
fn long_os_version(&self) -> Option<String> {
#[cfg(target_os = "macos")]
let friendly_name = match self.os_version().unwrap_or_default() {
f_n if f_n.starts_with("10.16")
| f_n.starts_with("11.0")
| f_n.starts_with("11.1")
| f_n.starts_with("11.2") =>
{
"Big Sur"
}
f_n if f_n.starts_with("10.15") => "Catalina",
f_n if f_n.starts_with("10.14") => "Mojave",
f_n if f_n.starts_with("10.13") => "High Sierra",
f_n if f_n.starts_with("10.12") => "Sierra",
f_n if f_n.starts_with("10.11") => "El Capitan",
f_n if f_n.starts_with("10.10") => "Yosemite",
f_n if f_n.starts_with("10.9") => "Mavericks",
f_n if f_n.starts_with("10.8") => "Mountain Lion",
f_n if f_n.starts_with("10.7") => "Lion",
f_n if f_n.starts_with("10.6") => "Snow Leopard",
f_n if f_n.starts_with("10.5") => "Leopard",
f_n if f_n.starts_with("10.4") => "Tiger",
f_n if f_n.starts_with("10.3") => "Panther",
f_n if f_n.starts_with("10.2") => "Jaguar",
f_n if f_n.starts_with("10.1") => "Puma",
f_n if f_n.starts_with("10.0") => "Cheetah",
_ => "",
};
#[cfg(target_os = "macos")]
let long_name = Some(format!(
"MacOS {} {}",
self.os_version().unwrap_or_default(),
friendly_name
));
#[cfg(target_os = "ios")]
let long_name = Some(format!("iOS {}", self.os_version().unwrap_or_default()));
long_name
}
fn host_name(&self) -> Option<String> {
get_system_info(libc::KERN_HOSTNAME, None)
}
fn kernel_version(&self) -> Option<String> {
get_system_info(libc::KERN_OSRELEASE, None)
}
fn os_version(&self) -> Option<String> {
unsafe {
// get the size for the buffer first
let mut size = 0;
if get_sys_value_by_name(b"kern.osproductversion\0", &mut size, std::ptr::null_mut())
&& size > 0
{
// now create a buffer with the size and get the real value
let mut buf = vec![0_u8; size as usize];
if get_sys_value_by_name(
b"kern.osproductversion\0",
&mut size,
buf.as_mut_ptr() as *mut c_void,
) {
if let Some(pos) = buf.iter().position(|x| *x == 0) {
// Shrink buffer to terminate the null bytes
buf.resize(pos, 0);
}
String::from_utf8(buf).ok()
} else {
// getting the system value failed
None
}
} else {
// getting the system value failed, or did not return a buffer size
None
}
}
}
}
impl Default for System {
fn default() -> System {
System::new()
}
}
// code from https://github.com/Chris911/iStats
// Not supported on iOS, or in the default macOS
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn get_io_service_connection() -> Option<ffi::io_connect_t> {
let mut master_port: mach_port_t = 0;
let mut iterator: ffi::io_iterator_t = 0;
unsafe {
ffi::IOMasterPort(ffi::MACH_PORT_NULL, &mut master_port);
let matching_dictionary = ffi::IOServiceMatching(b"AppleSMC\0".as_ptr() as *const i8);
let result =
ffi::IOServiceGetMatchingServices(master_port, matching_dictionary, &mut iterator);
if result != ffi::KIO_RETURN_SUCCESS {
sysinfo_debug!("Error: IOServiceGetMatchingServices() = {}", result);
return None;
}
let device = ffi::IOIteratorNext(iterator);
ffi::IOObjectRelease(iterator);
if device == 0 {
sysinfo_debug!("Error: no SMC found");
return None;
}
let mut conn = 0;
let result = ffi::IOServiceOpen(device, mach_task_self(), 0, &mut conn);
ffi::IOObjectRelease(device);
if result != ffi::KIO_RETURN_SUCCESS {
sysinfo_debug!("Error: IOServiceOpen() = {}", result);
return None;
}
Some(conn)
}
}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn get_arg_max() -> usize {
let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0];
let mut arg_max = 0i32;
let mut size = mem::size_of::<c_int>();
unsafe {
if sysctl(
mib.as_mut_ptr(),
2,
(&mut arg_max) as *mut i32 as *mut c_void,
&mut size,
std::ptr::null_mut(),
0,
) == -1
{
4096 // We default to this value
} else {
arg_max as usize
}
}
}
pub(crate) unsafe fn get_sys_value(
high: u32,
low: u32,
mut len: usize,
value: *mut c_void,
mib: &mut [i32; 2],
) -> bool {
mib[0] = high as i32;
mib[1] = low as i32;
sysctl(
mib.as_mut_ptr(),
2,
value,
&mut len as *mut usize,
std::ptr::null_mut(),
0,
) == 0
}
unsafe fn get_sys_value_by_name(name: &[u8], len: &mut usize, value: *mut c_void) -> bool {
sysctlbyname(
name.as_ptr() as *const c_char,
value,
len,
std::ptr::null_mut(),
0,
) == 0
}
fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {
let mut mib: [c_int; 2] = [libc::CTL_KERN, value];
let mut size = 0;
// Call first to get size
unsafe {
sysctl(
mib.as_mut_ptr(),
2,
std::ptr::null_mut(),
&mut size,
std::ptr::null_mut(),
0,
)
};
// exit early if we did not update the size
if size == 0 {
default.map(|s| s.to_owned())
} else {
// set the buffer to the correct size
let mut buf = vec![0_u8; size as usize];
if unsafe {
sysctl(
mib.as_mut_ptr(),
2,
buf.as_mut_ptr() as _,
&mut size,
std::ptr::null_mut(),
0,
)
} == -1
{
// If command fails return default
default.map(|s| s.to_owned())
} else {
if let Some(pos) = buf.iter().position(|x| *x == 0) {
// Shrink buffer to terminate the null bytes
buf.resize(pos, 0);
}
String::from_utf8(buf).ok()
}
}
}
Replace ".ok().flatten()" with a simple match
//
// Sysinfo
//
// Copyright (c) 2015 Guillaume Gomez
//
use crate::sys::component::Component;
use crate::sys::disk::*;
use crate::sys::ffi;
use crate::sys::network::Networks;
use crate::sys::process::*;
use crate::sys::processor::*;
#[cfg(target_os = "macos")]
use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease};
use crate::{LoadAvg, Pid, ProcessorExt, RefreshKind, SystemExt, User};
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use crate::ProcessExt;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::mem;
use std::sync::Arc;
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use libc::size_t;
use libc::{
c_char, c_int, c_void, host_statistics64, mach_port_t, mach_task_self, sysconf, sysctl,
sysctlbyname, timeval, vm_statistics64, _SC_PAGESIZE,
};
/// Structs containing system's information.
pub struct System {
process_list: HashMap<Pid, Process>,
mem_total: u64,
mem_free: u64,
mem_available: u64,
swap_total: u64,
swap_free: u64,
global_processor: Processor,
processors: Vec<Processor>,
page_size_kb: u64,
components: Vec<Component>,
// Used to get CPU information, not supported on iOS, or inside the default macOS sandbox.
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
connection: Option<ffi::io_connect_t>,
disks: Vec<Disk>,
networks: Networks,
port: mach_port_t,
users: Vec<User>,
boot_time: u64,
// Used to get disk information, to be more specific, it's needed by the
// DADiskCreateFromVolumePath function. Not supported on iOS.
#[cfg(target_os = "macos")]
session: ffi::SessionWrap,
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
clock_info: Option<crate::sys::macos::system::SystemTimeInfo>,
}
impl Drop for System {
fn drop(&mut self) {
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
if let Some(conn) = self.connection {
unsafe {
ffi::IOServiceClose(conn);
}
}
#[cfg(target_os = "macos")]
if !self.session.0.is_null() {
unsafe {
CFRelease(self.session.0 as _);
}
}
}
}
pub(crate) struct Wrap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>);
unsafe impl<'a> Send for Wrap<'a> {}
unsafe impl<'a> Sync for Wrap<'a> {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
impl System {
fn clear_procs(&mut self) {
use crate::sys::macos::process;
let mut to_delete = Vec::new();
for (pid, mut proc_) in &mut self.process_list {
if !process::has_been_updated(&mut proc_) {
to_delete.push(*pid);
}
}
for pid in to_delete {
self.process_list.remove(&pid);
}
}
}
fn boot_time() -> u64 {
let mut boot_time = timeval {
tv_sec: 0,
tv_usec: 0,
};
let mut len = std::mem::size_of::<timeval>();
let mut mib: [c_int; 2] = [libc::CTL_KERN, libc::KERN_BOOTTIME];
if unsafe {
sysctl(
mib.as_mut_ptr(),
2,
&mut boot_time as *mut timeval as *mut _,
&mut len,
std::ptr::null_mut(),
0,
)
} < 0
{
0
} else {
boot_time.tv_sec as _
}
}
impl SystemExt for System {
const IS_SUPPORTED: bool = true;
fn new_with_specifics(refreshes: RefreshKind) -> System {
let port = unsafe { libc::mach_host_self() };
let (global_processor, processors) = init_processors(port);
let mut s = System {
process_list: HashMap::with_capacity(200),
mem_total: 0,
mem_free: 0,
mem_available: 0,
swap_total: 0,
swap_free: 0,
global_processor,
processors,
page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 / 1_000 },
components: Vec::with_capacity(2),
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
connection: get_io_service_connection(),
disks: Vec::with_capacity(1),
networks: Networks::new(),
port,
users: Vec::new(),
boot_time: boot_time(),
#[cfg(target_os = "macos")]
session: ffi::SessionWrap(::std::ptr::null_mut()),
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
clock_info: crate::sys::macos::system::SystemTimeInfo::new(port),
};
s.refresh_specifics(refreshes);
s
}
fn refresh_memory(&mut self) {
let mut mib = [0, 0];
unsafe {
// get system values
// get swap info
let mut xs: libc::xsw_usage = mem::zeroed::<libc::xsw_usage>();
if get_sys_value(
libc::CTL_VM as _,
libc::VM_SWAPUSAGE as _,
mem::size_of::<libc::xsw_usage>(),
&mut xs as *mut _ as *mut c_void,
&mut mib,
) {
self.swap_total = xs.xsu_total / 1_000;
self.swap_free = xs.xsu_avail / 1_000;
}
// get ram info
if self.mem_total < 1 {
get_sys_value(
libc::CTL_HW as _,
libc::HW_MEMSIZE as _,
mem::size_of::<u64>(),
&mut self.mem_total as *mut u64 as *mut c_void,
&mut mib,
);
self.mem_total /= 1_000;
}
let mut count: u32 = ffi::HOST_VM_INFO64_COUNT;
let mut stat = mem::zeroed::<vm_statistics64>();
if host_statistics64(
self.port,
libc::HOST_VM_INFO64,
&mut stat as *mut vm_statistics64 as *mut _,
&mut count,
) == libc::KERN_SUCCESS
{
// From the apple documentation:
//
// /*
// * NB: speculative pages are already accounted for in "free_count",
// * so "speculative_count" is the number of "free" pages that are
// * used to hold data that was read speculatively from disk but
// * haven't actually been used by anyone so far.
// */
self.mem_available = self.mem_total
- (u64::from(stat.active_count)
+ u64::from(stat.inactive_count)
+ u64::from(stat.wire_count)
+ u64::from(stat.speculative_count)
- u64::from(stat.purgeable_count))
* self.page_size_kb;
self.mem_free = u64::from(stat.free_count) * self.page_size_kb;
}
}
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_components_list(&mut self) {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_components_list(&mut self) {
if let Some(con) = self.connection {
self.components.clear();
// getting CPU critical temperature
let critical_temp = crate::apple::component::get_temperature(
con,
&['T' as i8, 'C' as i8, '0' as i8, 'D' as i8, 0],
);
for (id, v) in crate::apple::component::COMPONENTS_TEMPERATURE_IDS.iter() {
if let Some(c) = Component::new((*id).to_owned(), None, critical_temp, v, con) {
self.components.push(c);
}
}
}
}
fn refresh_cpu(&mut self) {
let processors = &mut self.processors;
update_processor_usage(
self.port,
&mut self.global_processor,
|proc_data, cpu_info| {
let mut percentage = 0f32;
let mut offset = 0;
for proc_ in processors.iter_mut() {
let cpu_usage = compute_processor_usage(proc_, cpu_info, offset);
proc_.update(cpu_usage, Arc::clone(&proc_data));
percentage += proc_.cpu_usage();
offset += libc::CPU_STATE_MAX as isize;
}
(percentage, processors.len())
},
);
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_processes(&mut self) {}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_processes(&mut self) {
use crate::utils::into_iter;
let count = unsafe { libc::proc_listallpids(::std::ptr::null_mut(), 0) };
if count < 1 {
return;
}
if let Some(pids) = get_proc_list() {
let arg_max = get_arg_max();
let port = self.port;
let time_interval = self.clock_info.as_mut().map(|c| c.get_time_interval(port));
let entries: Vec<Process> = {
let wrap = &Wrap(UnsafeCell::new(&mut self.process_list));
#[cfg(feature = "multithread")]
use rayon::iter::ParallelIterator;
into_iter(pids)
.flat_map(|pid| {
match update_process(wrap, pid, arg_max as size_t, time_interval) {
Ok(x) => x,
_ => None,
}
})
.collect()
};
entries.into_iter().for_each(|entry| {
self.process_list.insert(entry.pid(), entry);
});
self.clear_procs();
}
}
#[cfg(any(target_os = "ios", feature = "apple-sandbox"))]
fn refresh_process(&mut self, _: Pid) -> bool {
false
}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn refresh_process(&mut self, pid: Pid) -> bool {
let arg_max = get_arg_max();
let port = self.port;
let time_interval = self.clock_info.as_mut().map(|c| c.get_time_interval(port));
match {
let wrap = Wrap(UnsafeCell::new(&mut self.process_list));
update_process(&wrap, pid, arg_max as size_t, time_interval)
} {
Ok(Some(p)) => {
self.process_list.insert(p.pid(), p);
true
}
Ok(_) => true,
Err(_) => false,
}
}
#[cfg(target_os = "ios")]
fn refresh_disks_list(&mut self) {}
#[cfg(target_os = "macos")]
fn refresh_disks_list(&mut self) {
if self.session.0.is_null() {
self.session.0 = unsafe { ffi::DASessionCreate(kCFAllocatorDefault as _) };
}
self.disks = get_disks(self.session.0);
}
fn refresh_users_list(&mut self) {
self.users = crate::apple::users::get_users_list();
}
// COMMON PART
//
// Need to be moved into a "common" file to avoid duplication.
fn processes(&self) -> &HashMap<Pid, Process> {
&self.process_list
}
fn process(&self, pid: Pid) -> Option<&Process> {
self.process_list.get(&pid)
}
fn global_processor_info(&self) -> &Processor {
&self.global_processor
}
fn processors(&self) -> &[Processor] {
&self.processors
}
fn physical_core_count(&self) -> Option<usize> {
let mut physical_core_count = 0;
if unsafe {
get_sys_value_by_name(
b"hw.physicalcpu\0",
&mut mem::size_of::<u32>(),
&mut physical_core_count as *mut usize as *mut c_void,
)
} {
Some(physical_core_count)
} else {
None
}
}
fn networks(&self) -> &Networks {
&self.networks
}
fn networks_mut(&mut self) -> &mut Networks {
&mut self.networks
}
fn total_memory(&self) -> u64 {
self.mem_total
}
fn free_memory(&self) -> u64 {
self.mem_free
}
fn available_memory(&self) -> u64 {
self.mem_available
}
fn used_memory(&self) -> u64 {
self.mem_total - self.mem_free
}
fn total_swap(&self) -> u64 {
self.swap_total
}
fn free_swap(&self) -> u64 {
self.swap_free
}
// need to be checked
fn used_swap(&self) -> u64 {
self.swap_total - self.swap_free
}
fn components(&self) -> &[Component] {
&self.components
}
fn components_mut(&mut self) -> &mut [Component] {
&mut self.components
}
fn disks(&self) -> &[Disk] {
&self.disks
}
fn disks_mut(&mut self) -> &mut [Disk] {
&mut self.disks
}
fn uptime(&self) -> u64 {
let csec = unsafe { libc::time(::std::ptr::null_mut()) };
unsafe { libc::difftime(csec, self.boot_time as _) as u64 }
}
fn load_average(&self) -> LoadAvg {
let mut loads = vec![0f64; 3];
unsafe {
libc::getloadavg(loads.as_mut_ptr(), 3);
}
LoadAvg {
one: loads[0],
five: loads[1],
fifteen: loads[2],
}
}
fn users(&self) -> &[User] {
&self.users
}
fn boot_time(&self) -> u64 {
self.boot_time
}
fn name(&self) -> Option<String> {
get_system_info(libc::KERN_OSTYPE, Some("Darwin"))
}
fn long_os_version(&self) -> Option<String> {
#[cfg(target_os = "macos")]
let friendly_name = match self.os_version().unwrap_or_default() {
f_n if f_n.starts_with("10.16")
| f_n.starts_with("11.0")
| f_n.starts_with("11.1")
| f_n.starts_with("11.2") =>
{
"Big Sur"
}
f_n if f_n.starts_with("10.15") => "Catalina",
f_n if f_n.starts_with("10.14") => "Mojave",
f_n if f_n.starts_with("10.13") => "High Sierra",
f_n if f_n.starts_with("10.12") => "Sierra",
f_n if f_n.starts_with("10.11") => "El Capitan",
f_n if f_n.starts_with("10.10") => "Yosemite",
f_n if f_n.starts_with("10.9") => "Mavericks",
f_n if f_n.starts_with("10.8") => "Mountain Lion",
f_n if f_n.starts_with("10.7") => "Lion",
f_n if f_n.starts_with("10.6") => "Snow Leopard",
f_n if f_n.starts_with("10.5") => "Leopard",
f_n if f_n.starts_with("10.4") => "Tiger",
f_n if f_n.starts_with("10.3") => "Panther",
f_n if f_n.starts_with("10.2") => "Jaguar",
f_n if f_n.starts_with("10.1") => "Puma",
f_n if f_n.starts_with("10.0") => "Cheetah",
_ => "",
};
#[cfg(target_os = "macos")]
let long_name = Some(format!(
"MacOS {} {}",
self.os_version().unwrap_or_default(),
friendly_name
));
#[cfg(target_os = "ios")]
let long_name = Some(format!("iOS {}", self.os_version().unwrap_or_default()));
long_name
}
fn host_name(&self) -> Option<String> {
get_system_info(libc::KERN_HOSTNAME, None)
}
fn kernel_version(&self) -> Option<String> {
get_system_info(libc::KERN_OSRELEASE, None)
}
fn os_version(&self) -> Option<String> {
unsafe {
// get the size for the buffer first
let mut size = 0;
if get_sys_value_by_name(b"kern.osproductversion\0", &mut size, std::ptr::null_mut())
&& size > 0
{
// now create a buffer with the size and get the real value
let mut buf = vec![0_u8; size as usize];
if get_sys_value_by_name(
b"kern.osproductversion\0",
&mut size,
buf.as_mut_ptr() as *mut c_void,
) {
if let Some(pos) = buf.iter().position(|x| *x == 0) {
// Shrink buffer to terminate the null bytes
buf.resize(pos, 0);
}
String::from_utf8(buf).ok()
} else {
// getting the system value failed
None
}
} else {
// getting the system value failed, or did not return a buffer size
None
}
}
}
}
impl Default for System {
fn default() -> System {
System::new()
}
}
// code from https://github.com/Chris911/iStats
// Not supported on iOS, or in the default macOS
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn get_io_service_connection() -> Option<ffi::io_connect_t> {
let mut master_port: mach_port_t = 0;
let mut iterator: ffi::io_iterator_t = 0;
unsafe {
ffi::IOMasterPort(ffi::MACH_PORT_NULL, &mut master_port);
let matching_dictionary = ffi::IOServiceMatching(b"AppleSMC\0".as_ptr() as *const i8);
let result =
ffi::IOServiceGetMatchingServices(master_port, matching_dictionary, &mut iterator);
if result != ffi::KIO_RETURN_SUCCESS {
sysinfo_debug!("Error: IOServiceGetMatchingServices() = {}", result);
return None;
}
let device = ffi::IOIteratorNext(iterator);
ffi::IOObjectRelease(iterator);
if device == 0 {
sysinfo_debug!("Error: no SMC found");
return None;
}
let mut conn = 0;
let result = ffi::IOServiceOpen(device, mach_task_self(), 0, &mut conn);
ffi::IOObjectRelease(device);
if result != ffi::KIO_RETURN_SUCCESS {
sysinfo_debug!("Error: IOServiceOpen() = {}", result);
return None;
}
Some(conn)
}
}
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
fn get_arg_max() -> usize {
let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0];
let mut arg_max = 0i32;
let mut size = mem::size_of::<c_int>();
unsafe {
if sysctl(
mib.as_mut_ptr(),
2,
(&mut arg_max) as *mut i32 as *mut c_void,
&mut size,
std::ptr::null_mut(),
0,
) == -1
{
4096 // We default to this value
} else {
arg_max as usize
}
}
}
pub(crate) unsafe fn get_sys_value(
high: u32,
low: u32,
mut len: usize,
value: *mut c_void,
mib: &mut [i32; 2],
) -> bool {
mib[0] = high as i32;
mib[1] = low as i32;
sysctl(
mib.as_mut_ptr(),
2,
value,
&mut len as *mut usize,
std::ptr::null_mut(),
0,
) == 0
}
unsafe fn get_sys_value_by_name(name: &[u8], len: &mut usize, value: *mut c_void) -> bool {
sysctlbyname(
name.as_ptr() as *const c_char,
value,
len,
std::ptr::null_mut(),
0,
) == 0
}
fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {
let mut mib: [c_int; 2] = [libc::CTL_KERN, value];
let mut size = 0;
// Call first to get size
unsafe {
sysctl(
mib.as_mut_ptr(),
2,
std::ptr::null_mut(),
&mut size,
std::ptr::null_mut(),
0,
)
};
// exit early if we did not update the size
if size == 0 {
default.map(|s| s.to_owned())
} else {
// set the buffer to the correct size
let mut buf = vec![0_u8; size as usize];
if unsafe {
sysctl(
mib.as_mut_ptr(),
2,
buf.as_mut_ptr() as _,
&mut size,
std::ptr::null_mut(),
0,
)
} == -1
{
// If command fails return default
default.map(|s| s.to_owned())
} else {
if let Some(pos) = buf.iter().position(|x| *x == 0) {
// Shrink buffer to terminate the null bytes
buf.resize(pos, 0);
}
String::from_utf8(buf).ok()
}
}
}
|
// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Genesis. If not, see <http://www.gnu.org/licenses/>.
use core::cmp::Ordering;
use core::fmt;
#[derive(Copy, Clone, Debug, Default)]
pub struct PAddr(u64);
#[derive(Copy, Clone, Debug, Default)]
pub struct VAddr(usize);
impl PAddr {
pub fn as_u64(&self) -> u64 {
self.0
}
pub fn from_u64(v: u64) -> Self {
PAddr(v)
}
}
impl fmt::Binary for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::LowerHex for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Octal for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::UpperHex for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Eq for PAddr {}
impl PartialEq for PAddr {
fn eq(&self, other: &PAddr) -> bool {
self.0.eq(&other.0)
}
}
impl PartialOrd for PAddr {
fn partial_cmp(&self, other: &PAddr) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for PAddr {
fn cmp(&self, other: &PAddr) -> Ordering {
self.0.cmp(&other.0)
}
}
impl fmt::Binary for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::LowerHex for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Octal for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::UpperHex for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Eq for VAddr {}
impl PartialEq for VAddr {
fn eq(&self, other: &VAddr) -> bool {
self.0.eq(&other.0)
}
}
impl PartialOrd for VAddr {
fn partial_cmp(&self, other: &VAddr) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for VAddr {
fn cmp(&self, other: &VAddr) -> Ordering {
self.0.cmp(&other.0)
}
}
Change mem ordering impls to #[derive]
Signed-off-by: Dan Schatzberg <2fd18fbc94e1d251ef5884a6fa05a98ae57788ae@gmail.com>
// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Genesis. If not, see <http://www.gnu.org/licenses/>.
use core::fmt;
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct PAddr(u64);
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct VAddr(usize);
impl PAddr {
pub fn as_u64(&self) -> u64 {
self.0
}
pub fn from_u64(v: u64) -> Self {
PAddr(v)
}
}
impl fmt::Binary for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::LowerHex for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Octal for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::UpperHex for PAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Binary for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::LowerHex for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Octal for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::UpperHex for VAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
|
// 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.
#![feature(rustc_private, rustdoc)]
extern crate syntax;
extern crate rustdoc;
extern crate serialize as rustc_serialize;
use std::collections::BTreeMap;
use std::fs::{read_dir, File};
use std::io::{Read, Write};
use std::env;
use std::path::Path;
use std::error::Error;
use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap};
use rustdoc::html::markdown::Markdown;
use rustc_serialize::json;
/// Load all the metadata files from `metadata_dir` into an in-memory map.
fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> {
let mut all_errors = BTreeMap::new();
for entry in try!(read_dir(metadata_dir)) {
let path = try!(entry).path();
let mut metadata_str = String::new();
try!(
File::open(&path).and_then(|mut f|
f.read_to_string(&mut metadata_str))
);
let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str));
for (err_code, info) in some_errors {
all_errors.insert(err_code, info);
}
}
Ok(all_errors)
}
/// Output an HTML page for the errors in `err_map` to `output_path`.
fn render_error_page(err_map: &ErrorMetadataMap, output_path: &Path) -> Result<(), Box<Error>> {
let mut output_file = try!(File::create(output_path));
try!(write!(&mut output_file,
r##"<!DOCTYPE html>
<html>
<head>
<title>Rust Compiler Error Index</title>
<meta charset="utf-8">
<!-- Include rust.css after main.css so its rules take priority. -->
<link rel="stylesheet" type="text/css" href="main.css"/>
<link rel="stylesheet" type="text/css" href="rust.css"/>
<style>
.error-undescribed {{
display: none;
}}
</style>
</head>
<body>
"##
));
try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n"));
for (err_code, info) in err_map {
// Enclose each error in a div so they can be shown/hidden en masse.
let desc_desc = match info.description {
Some(_) => "error-described",
None => "error-undescribed"
};
let use_desc = match info.use_site {
Some(_) => "error-used",
None => "error-unused"
};
try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc));
// Error title (with self-link).
try!(write!(&mut output_file,
"<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n",
err_code
));
// Description rendered as markdown.
match info.description {
Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))),
None => try!(write!(&mut output_file, "<p>No description.</p>\n"))
}
try!(write!(&mut output_file, "</div>\n"));
}
try!(write!(&mut output_file, "</body>\n</html>"));
Ok(())
}
fn main_with_result() -> Result<(), Box<Error>> {
let build_arch = try!(env::var("CFG_BUILD"));
let metadata_dir = get_metadata_dir(&build_arch);
let err_map = try!(load_all_errors(&metadata_dir));
try!(render_error_page(&err_map, Path::new("doc/error-index.html")));
Ok(())
}
fn main() {
if let Err(e) = main_with_result() {
panic!("{}", e.description());
}
}
Run rustfmt on error-index-generator.
// 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.
#![feature(rustc_private, rustdoc)]
extern crate syntax;
extern crate rustdoc;
extern crate serialize as rustc_serialize;
use std::collections::BTreeMap;
use std::fs::{read_dir, File};
use std::io::{Read, Write};
use std::env;
use std::path::Path;
use std::error::Error;
use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap};
use rustdoc::html::markdown::Markdown;
use rustc_serialize::json;
/// Load all the metadata files from `metadata_dir` into an in-memory map.
fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<Error>> {
let mut all_errors = BTreeMap::new();
for entry in try!(read_dir(metadata_dir)) {
let path = try!(entry).path();
let mut metadata_str = String::new();
try!(File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str)));
let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str));
for (err_code, info) in some_errors {
all_errors.insert(err_code, info);
}
}
Ok(all_errors)
}
/// Output an HTML page for the errors in `err_map` to `output_path`.
fn render_error_page(err_map: &ErrorMetadataMap, output_path: &Path) -> Result<(), Box<Error>> {
let mut output_file = try!(File::create(output_path));
try!(write!(&mut output_file,
r##"<!DOCTYPE html>
<html>
<head>
<title>Rust Compiler Error Index</title>
<meta charset="utf-8">
<!-- Include rust.css after main.css so its rules take priority. -->
<link rel="stylesheet" type="text/css" href="main.css"/>
<link rel="stylesheet" type="text/css" href="rust.css"/>
<style>
.error-undescribed {{
display: none;
}}
</style>
</head>
<body>
"##
));
try!(write!(&mut output_file, "<h1>Rust Compiler Error Index</h1>\n"));
for (err_code, info) in err_map {
// Enclose each error in a div so they can be shown/hidden en masse.
let desc_desc = match info.description {
Some(_) => "error-described",
None => "error-undescribed",
};
let use_desc = match info.use_site {
Some(_) => "error-used",
None => "error-unused",
};
try!(write!(&mut output_file, "<div class=\"{} {}\">", desc_desc, use_desc));
// Error title (with self-link).
try!(write!(&mut output_file,
"<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n",
err_code));
// Description rendered as markdown.
match info.description {
Some(ref desc) => try!(write!(&mut output_file, "{}", Markdown(desc))),
None => try!(write!(&mut output_file, "<p>No description.</p>\n")),
}
try!(write!(&mut output_file, "</div>\n"));
}
try!(write!(&mut output_file, "</body>\n</html>"));
Ok(())
}
fn main_with_result() -> Result<(), Box<Error>> {
let build_arch = try!(env::var("CFG_BUILD"));
let metadata_dir = get_metadata_dir(&build_arch);
let err_map = try!(load_all_errors(&metadata_dir));
try!(render_error_page(&err_map, Path::new("doc/error-index.html")));
Ok(())
}
fn main() {
if let Err(e) = main_with_result() {
panic!("{}", e.description());
}
}
|
use nom;
use nom::{Err, IResult};
use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo, metadata_parser};
use frame::{frame_parser, Frame};
use utility::{ErrorKind, ByteStream, ReadStream, StreamProducer};
use std::io;
use std::usize;
use std::fs::File;
enum ParserState {
Marker,
Metadata,
Frame,
}
pub struct Stream {
info: StreamInfo,
pub metadata: Vec<Metadata>,
pub frames: Vec<Frame>,
state: ParserState,
output: Vec<i32>,
frame_index: usize,
}
named!(pub stream_parser <&[u8], Stream>,
chain!(
blocks: metadata_parser ~
frames: many1!(apply!(frame_parser, &blocks.0)),
move|| {
Stream {
info: blocks.0,
metadata: blocks.1,
frames: frames,
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
}
}
)
);
impl Stream {
pub fn new() -> Stream {
Stream {
info: StreamInfo::new(),
metadata: Vec::new(),
frames: Vec::new(),
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
}
}
pub fn info(&self) -> StreamInfo {
self.info
}
pub fn from_file(filename: &str) -> io::Result<Stream> {
File::open(filename).and_then(|file| {
let mut producer = ReadStream::new(file);
let error_str = format!("parser: couldn't parse the given file {}",
filename);
Stream::from_stream_producer(&mut producer, &error_str)
})
}
pub fn from_buffer(buffer: &[u8]) -> io::Result<Stream> {
let mut producer = ByteStream::new(buffer);
let error_str = "parser: couldn't parse the buffer";
Stream::from_stream_producer(&mut producer, error_str)
}
fn from_stream_producer<P>(producer: &mut P, error_str: &str)
-> io::Result<Stream>
where P: StreamProducer {
let mut is_error = false;
let mut stream = Stream {
info: StreamInfo::new(),
metadata: Vec::new(),
frames: Vec::new(),
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
};
loop {
match stream.handle(producer) {
Ok(_) => break,
Err(ErrorKind::EndOfInput) => break,
Err(ErrorKind::Consumed(_)) => continue,
Err(ErrorKind::Incomplete(_)) => continue,
Err(_) => {
is_error = true;
break;
}
}
}
if !is_error {
let channels = stream.info.channels as usize;
let block_size = stream.info.max_block_size as usize;
let output_size = block_size * channels;
stream.output.reserve_exact(output_size);
unsafe { stream.output.set_len(output_size) }
Ok(stream)
} else {
Err(io::Error::new(io::ErrorKind::InvalidData, error_str))
}
}
pub fn iter(&mut self) -> Iter {
Iter::new(self)
}
pub fn next_frame<'a>(&'a mut self) -> Option<&'a [i32]> {
if self.frames.is_empty() || self.frame_index >= self.frames.len() {
None
} else {
let frame = &self.frames[self.frame_index];
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let mut channel = 0;
for subframe in &frame.subframes[0..channels] {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut self.output[start..end];
subframe::decode(&subframe, output);
channel += 1;
}
frame::decode(frame.header.channel_assignment, &mut self.output);
self.frame_index += 1;
Some(&self.output[0..(block_size * channels)])
}
}
fn handle_marker<'a>(&mut self, input: &'a [u8]) -> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(0);
match tag!(input, "fLaC") {
IResult::Done(i, _) => {
self.state = ParserState::Metadata;
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
fn handle_metadata<'a>(&mut self, input: &'a [u8])
-> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(1);
match metadata::block(input) {
IResult::Done(i, block) => {
let is_last = block.is_last;
if let metadata::Data::StreamInfo(info) = block.data {
self.info = info;
} else {
self.metadata.push(block);
}
if is_last {
self.state = ParserState::Frame;
}
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
fn handle_frame<'a>(&mut self, input: &'a [u8]) -> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(2);
match frame_parser(input, &self.info) {
IResult::Done(i, frame) => {
self.frames.push(frame);
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
pub fn handle<S: StreamProducer>(&mut self, stream: &mut S)
-> Result<(), ErrorKind> {
stream.parse(|input| {
match self.state {
ParserState::Marker => self.handle_marker(input),
ParserState::Metadata => self.handle_metadata(input),
ParserState::Frame => self.handle_frame(input),
}
})
}
}
pub struct Iter<'a> {
stream: &'a mut Stream,
channel: usize,
frame_index: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
}
impl<'a> Iter<'a> {
pub fn new(stream: &'a mut Stream) -> Iter<'a> {
let samples_left = stream.info.total_samples;
Iter {
stream: stream,
channel: 0,
frame_index: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
if self.block_size == 0 || self.sample_index == self.block_size {
if self.stream.next_frame().is_none() {
return None;
} else {
let frame = &self.stream.frames[self.frame_index];
self.sample_index = 0;
self.block_size = frame.header.block_size as usize;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = self.stream.output[index];
self.channel += 1;
self.samples_left -= 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
}
Some(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a change that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
Remove public access to a few methods and data
use nom;
use nom::{Err, IResult};
use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo, metadata_parser};
use frame::{frame_parser, Frame};
use utility::{ErrorKind, ByteStream, ReadStream, StreamProducer};
use std::io;
use std::usize;
use std::fs::File;
enum ParserState {
Marker,
Metadata,
Frame,
}
pub struct Stream {
info: StreamInfo,
pub metadata: Vec<Metadata>,
frames: Vec<Frame>,
state: ParserState,
output: Vec<i32>,
frame_index: usize,
}
named!(pub stream_parser <&[u8], Stream>,
chain!(
blocks: metadata_parser ~
frames: many1!(apply!(frame_parser, &blocks.0)),
move|| {
Stream {
info: blocks.0,
metadata: blocks.1,
frames: frames,
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
}
}
)
);
impl Stream {
pub fn new() -> Stream {
Stream {
info: StreamInfo::new(),
metadata: Vec::new(),
frames: Vec::new(),
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
}
}
pub fn info(&self) -> StreamInfo {
self.info
}
pub fn from_file(filename: &str) -> io::Result<Stream> {
File::open(filename).and_then(|file| {
let mut producer = ReadStream::new(file);
let error_str = format!("parser: couldn't parse the given file {}",
filename);
Stream::from_stream_producer(&mut producer, &error_str)
})
}
pub fn from_buffer(buffer: &[u8]) -> io::Result<Stream> {
let mut producer = ByteStream::new(buffer);
let error_str = "parser: couldn't parse the buffer";
Stream::from_stream_producer(&mut producer, error_str)
}
fn from_stream_producer<P>(producer: &mut P, error_str: &str)
-> io::Result<Stream>
where P: StreamProducer {
let mut is_error = false;
let mut stream = Stream {
info: StreamInfo::new(),
metadata: Vec::new(),
frames: Vec::new(),
state: ParserState::Marker,
output: Vec::new(),
frame_index: 0,
};
loop {
match stream.handle(producer) {
Ok(_) => break,
Err(ErrorKind::EndOfInput) => break,
Err(ErrorKind::Consumed(_)) => continue,
Err(ErrorKind::Incomplete(_)) => continue,
Err(_) => {
is_error = true;
break;
}
}
}
if !is_error {
let channels = stream.info.channels as usize;
let block_size = stream.info.max_block_size as usize;
let output_size = block_size * channels;
stream.output.reserve_exact(output_size);
unsafe { stream.output.set_len(output_size) }
Ok(stream)
} else {
Err(io::Error::new(io::ErrorKind::InvalidData, error_str))
}
}
pub fn iter(&mut self) -> Iter {
Iter::new(self)
}
fn next_frame<'a>(&'a mut self) -> Option<&'a [i32]> {
if self.frames.is_empty() || self.frame_index >= self.frames.len() {
None
} else {
let frame = &self.frames[self.frame_index];
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let mut channel = 0;
for subframe in &frame.subframes[0..channels] {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut self.output[start..end];
subframe::decode(&subframe, output);
channel += 1;
}
frame::decode(frame.header.channel_assignment, &mut self.output);
self.frame_index += 1;
Some(&self.output[0..(block_size * channels)])
}
}
fn handle_marker<'a>(&mut self, input: &'a [u8]) -> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(0);
match tag!(input, "fLaC") {
IResult::Done(i, _) => {
self.state = ParserState::Metadata;
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
fn handle_metadata<'a>(&mut self, input: &'a [u8])
-> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(1);
match metadata::block(input) {
IResult::Done(i, block) => {
let is_last = block.is_last;
if let metadata::Data::StreamInfo(info) = block.data {
self.info = info;
} else {
self.metadata.push(block);
}
if is_last {
self.state = ParserState::Frame;
}
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
fn handle_frame<'a>(&mut self, input: &'a [u8]) -> IResult<&'a [u8], ()> {
let kind = nom::ErrorKind::Custom(2);
match frame_parser(input, &self.info) {
IResult::Done(i, frame) => {
self.frames.push(frame);
IResult::Error(Err::Position(kind, i))
}
IResult::Error(_) => IResult::Error(Err::Code(kind)),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
fn handle<S: StreamProducer>(&mut self, stream: &mut S)
-> Result<(), ErrorKind> {
stream.parse(|input| {
match self.state {
ParserState::Marker => self.handle_marker(input),
ParserState::Metadata => self.handle_metadata(input),
ParserState::Frame => self.handle_frame(input),
}
})
}
}
pub struct Iter<'a> {
stream: &'a mut Stream,
channel: usize,
frame_index: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
}
impl<'a> Iter<'a> {
pub fn new(stream: &'a mut Stream) -> Iter<'a> {
let samples_left = stream.info.total_samples;
Iter {
stream: stream,
channel: 0,
frame_index: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
if self.block_size == 0 || self.sample_index == self.block_size {
if self.stream.next_frame().is_none() {
return None;
} else {
let frame = &self.stream.frames[self.frame_index];
self.sample_index = 0;
self.block_size = frame.header.block_size as usize;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = self.stream.output[index];
self.channel += 1;
self.samples_left -= 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
}
Some(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a change that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
|
use std::io;
use std::io::Write;
use std::marker::PhantomData;
use Event;
pub struct HtmlStreamer<'a, I>
where I: Iterator<Item = Event<'a>> + 'a
{
events: I,
buffer: Vec<u8>,
ev_life: PhantomData<Event<'a>>,
}
impl<'a, I> HtmlStreamer<'a, I>
where I: Iterator<Item = Event<'a>>
{
pub fn new<II>(events: II) -> HtmlStreamer<'a, I>
where II: IntoIterator<IntoIter = I, Item = Event<'a>>
{
HtmlStreamer {
events: events.into_iter(),
buffer: Vec::new(),
ev_life: PhantomData,
}
}
}
impl<'a, I> io::Read for HtmlStreamer<'a, I>
where I: Iterator<Item = Event<'a>>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.buffer.len() == 0 {
if let Some(event) = self.events.next() {
// Possible to do better?
try!(write!(&mut self.buffer, "{}", event));
} else {
return Ok(0);
}
}
let curlen = self.buffer.len();
let len = ::std::cmp::min(curlen, buf.len());
buf[..len].clone_from_slice(&self.buffer[..len]);
for i in len..curlen {
self.buffer[i - len] = self.buffer[i];
}
self.buffer.truncate(curlen - len);
Ok(len)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
let start = buf.len();
while let Some(event) = self.events.next() {
try!(write!(buf, "{}", event));
}
Ok(buf.len() - start)
}
}
#[cfg(test)]
mod tests {
use std::io::Read;
use HtmlStreamer;
#[test]
fn test() {
let events = vec![
start_tag!("h1", id="hello", class="fun"),
text!("Hello, "),
raw_html!(""), // empty event
start_tag!("small"),
text!("world"),
end_tag!("small"),
closed_tag!("img", src="foo-link"),
end_tag!("h1"),
];
let mut result = String::new();
HtmlStreamer::new(events).read_to_string(&mut result).unwrap();
assert_eq!(result, "<h1 id=\"hello\" class=\"fun\">Hello, \
<small>world</small><img src=\"foo-link\" /></h1>");
}
}
HtmlStreamer should stream!
use std::io;
use std::marker::PhantomData;
use Event;
pub struct HtmlStreamer<'a, I, J>
where I: IntoIterator<IntoIter = J, Item = Event<'a>> + 'a,
J: Iterator<Item = Event<'a>>
{
events: I,
ev_life: PhantomData<Event<'a>>,
}
impl<'a, I, J> HtmlStreamer<'a, I, J>
where I: IntoIterator<IntoIter = J, Item = Event<'a>> + 'a,
J: Iterator<Item = Event<'a>>
{
pub fn new(events: I) -> HtmlStreamer<'a, I, J> {
HtmlStreamer {
events: events,
ev_life: PhantomData,
}
}
pub fn stream(self, w: &mut io::Write) -> io::Result<usize> {
for ev in self.events.into_iter() {
try!(write!(w, "{}", ev));
}
return Ok(0);
}
}
#[cfg(test)]
mod tests {
use HtmlStreamer;
#[test]
fn test() {
let events = vec![
start_tag!("h1", id="hello", class="fun"),
text!("Hello, "),
raw_html!(""), // empty event
start_tag!("small"),
text!("world"),
end_tag!("small"),
closed_tag!("img", src="foo-link"),
end_tag!("h1"),
];
let mut result = Vec::new();
HtmlStreamer::new(events).stream(&mut result).unwrap();
let res_str = String::from_utf8(result).unwrap();
assert_eq!(res_str.as_str(),
"<h1 id=\"hello\" class=\"fun\">Hello, \
<small>world</small><img src=\"foo-link\" /></h1>");
}
}
|
use std::collections::{VecDeque};
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidHexValue(c: u8)
InvalidOctValue(c: u8)
UnexpectedEnd
}
}
fn hex_to_digit(c: u8) -> Result<u8, Error> {
Ok(match c {
b'0' ... b'9' => c - b'0',
b'a' ... b'f' => c - b'a' + 10,
b'A' ... b'F' => c - b'A' + 10,
_ => return Err(Error::InvalidHexValue(c)),
})
}
fn oct_to_digit(c: u8) -> Result<u8, Error> {
Ok(match c {
b'0' ... b'7' => c - b'0',
_ => return Err(Error::InvalidOctValue(c)),
})
}
pub fn unescape(s: &[u8], unicode: bool) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(s.len());
let mut oct_buf = VecDeque::with_capacity(3);
let mut i = 0;
macro_rules! read {
() => ({
match s.get(i) {
None => return Err(Error::UnexpectedEnd),
Some(c) => {
i += 1;
*c
}
}
})
}
macro_rules! peek {
() => ({
s.get(i).map(|c| *c)
})
}
loop {
if i >= s.len() {
return Ok(buf)
}
let c = read!();
if c != b'\\' {
buf.push(c);
continue
}
let marker = read!();
match marker {
b'\n' => (),
b'\\' => buf.push(b'\\'),
b'\'' => buf.push(b'\''),
b'"' => buf.push(b'"'),
b'a' => buf.push(b'\x07'),
b'b' => buf.push(b'\x08'),
b'f' => buf.push(b'\x0c'),
b'n' => buf.push(b'\n'),
b'r' => buf.push(b'\r'),
b't' => buf.push(b'\t'),
b'v' => buf.push(b'\x0b'),
b'x' => {
let first = try!(hex_to_digit(read!()));
let second = try!(hex_to_digit(read!()));
buf.push(first * 15 + second)
}
b'0' ... b'7' => {
oct_buf.push_front(try!(oct_to_digit(marker)));
peek!().and_then(|c| oct_to_digit(c).ok()).map(|s| {
oct_buf.push_front(s);
i += 1;
peek!().and_then(|c| oct_to_digit(c).ok()).map(|s| {
oct_buf.push_front(s);
i += 1;
});
});
let value = oct_buf.iter().enumerate().fold(0u16, |acc, (i, &v)| acc + v as u16 * (8u16.pow(i as u32)));
oct_buf.clear();
buf.push(if value > 255 {
255
} else {
value as u8
});
continue
},
b'u' if unicode => unimplemented!(),
b'U' if unicode => unimplemented!(),
_ => {
buf.push(b'\\');
buf.push(marker);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{unescape};
#[test]
fn test_unescape() {
assert_eq!(unescape(b"foo", false).unwrap(), b"foo");
assert_eq!(unescape(b"f\\noo", false).unwrap(), b"f\noo");
assert_eq!(unescape(b"f\\x01oo", false).unwrap(), b"f\x01oo");
assert_eq!(unescape(b"f\\375oo", false).unwrap(), b"f\xfdoo");
assert_eq!(unescape(b"f\\75oo", false).unwrap(), b"f\x3doo");
assert_eq!(unescape(b"f\\5oo", false).unwrap(), b"f\x05oo");
assert_eq!(unescape(b"f\\oo", false).unwrap(), b"f\\oo");
assert_eq!(unescape(b"f\\coo", false).unwrap(), b"f\\coo");
}
}
Use FromAsciiRadix in unescape
use std::collections::{VecDeque};
use from_ascii::{FromAsciiRadix, ParseIntError};
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidValue {
from(ParseIntError)
}
UnexpectedEnd
}
}
fn oct_to_digit(c: u8) -> Result<u8, Error> {
Ok(match c {
b'0' ... b'7' => c - b'0',
_ => return Err(Error::InvalidValue),
})
}
pub fn unescape(s: &[u8], unicode: bool) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(s.len());
let mut oct_buf = VecDeque::with_capacity(3);
let mut i = 0;
macro_rules! read {
() => ({
match s.get(i) {
None => return Err(Error::UnexpectedEnd),
Some(c) => {
i += 1;
*c
}
}
})
}
macro_rules! peek {
() => ({
s.get(i).map(|c| *c)
})
}
loop {
if i >= s.len() {
return Ok(buf)
}
let c = read!();
if c != b'\\' {
buf.push(c);
continue
}
let marker = read!();
match marker {
b'\n' => (),
b'\\' => buf.push(b'\\'),
b'\'' => buf.push(b'\''),
b'"' => buf.push(b'"'),
b'a' => buf.push(b'\x07'),
b'b' => buf.push(b'\x08'),
b'f' => buf.push(b'\x0c'),
b'n' => buf.push(b'\n'),
b'r' => buf.push(b'\r'),
b't' => buf.push(b'\t'),
b'v' => buf.push(b'\x0b'),
b'x' => {
let hex_buf = [read!(), read!()];
buf.push(try!(u8::from_ascii_radix(&hex_buf, 16)))
}
b'0' ... b'7' => {
oct_buf.push_front(try!(oct_to_digit(marker)));
peek!().and_then(|c| oct_to_digit(c).ok()).map(|s| {
oct_buf.push_front(s);
i += 1;
peek!().and_then(|c| oct_to_digit(c).ok()).map(|s| {
oct_buf.push_front(s);
i += 1;
});
});
let value = oct_buf.iter().enumerate().fold(0u16, |acc, (i, &v)| acc + v as u16 * (8u16.pow(i as u32)));
oct_buf.clear();
buf.push(if value > 255 {
255
} else {
value as u8
});
continue
},
b'u' if unicode => unimplemented!(),
b'U' if unicode => unimplemented!(),
_ => {
buf.push(b'\\');
buf.push(marker);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{unescape};
#[test]
fn test_unescape() {
assert_eq!(unescape(b"foo", false).unwrap(), b"foo");
assert_eq!(unescape(b"f\\noo", false).unwrap(), b"f\noo");
assert_eq!(unescape(b"f\\x01oo", false).unwrap(), b"f\x01oo");
assert_eq!(unescape(b"f\\375oo", false).unwrap(), b"f\xfdoo");
assert_eq!(unescape(b"f\\75oo", false).unwrap(), b"f\x3doo");
assert_eq!(unescape(b"f\\5oo", false).unwrap(), b"f\x05oo");
assert_eq!(unescape(b"f\\oo", false).unwrap(), b"f\\oo");
assert_eq!(unescape(b"f\\coo", false).unwrap(), b"f\\coo");
}
} |
// The tiles in the map, and a struct to contain them
use rand;
use rand::Rng;
use line_drawing::Bresenham;
use super::units::{UnitSide, Units, WALK_LATERAL_COST, WALK_DIAGONAL_COST, UNIT_SIGHT};
use super::walls::{Walls, WallType, WallSide};
use super::iter_2d::Iter2D;
use items::Item;
use utils::{distance_under, min, lerp};
use resources::Image;
use std::mem::swap;
const DAY_DARKNESS_RATE: f32 = 0.025;
const NIGHT_DARKNESS_RATE: f32 = 0.05;
const MIN_PIT_SIZE: usize = 2;
const MAX_PIT_SIZE: usize = 5;
// A point for line-of-sight
type Point = (isize, isize);
// Sort two points on the y axis
fn sort(a: Point, b: Point) -> (Point, Point, bool) {
if a.1 > b.1 {
(b, a, true)
} else {
(a, b, false)
}
}
// Convert a coord in `usize`s to a point
fn to_point(x: usize, y: usize) -> Point {
(x as isize, y as isize)
}
// Convert a point back into `usize`s
fn from_point(point: Point) -> (usize, usize) {
(point.0 as usize, point.1 as usize)
}
// The visibility of the tile
#[derive(Copy, Clone, Serialize, Deserialize, Debug, is_enum_variant)]
pub enum Visibility {
Visible(u8),
Foggy,
Invisible
}
impl Visibility {
// Get the corresponding colour for a visibility
pub fn colour(&self, light: f32) -> [f32; 4] {
// Get the rate at which tiles get darker
let rate = lerp(NIGHT_DARKNESS_RATE, DAY_DARKNESS_RATE, light);
// Use the distance if the tile is visible
let alpha = if let Visibility::Visible(distance) = *self {
f32::from(distance) * rate
// Or use the maximum darkness + 0.1
} else if self.is_foggy() {
rate * (UNIT_SIGHT * f32::from(WALK_LATERAL_COST)) + 0.1
} else {
0.0
};
[0.0, 0.0, 0.0, alpha]
}
// Return the distance of the tile or the maximum value
fn distance(&self) -> u8 {
if let Visibility::Visible(value) = *self {
value
} else {
u8::max_value()
}
}
}
// Get the highest of two visibilities
fn combine_visibilities(a: Visibility, b: Visibility) -> Visibility {
if a.is_visible() || b.is_visible() {
// Use the mimimum of the two distances
Visibility::Visible(min(a.distance(), b.distance()))
} else if a.is_foggy() || b.is_foggy() {
Visibility::Foggy
} else {
Visibility::Invisible
}
}
#[derive(Serialize, Deserialize, is_enum_variant)]
pub enum Obstacle {
Object(Image),
Pit(Image),
Empty
}
// A tile in the map
#[derive(Serialize, Deserialize)]
pub struct Tile {
pub base: Image,
pub obstacle: Obstacle,
pub decoration: Option<Image>,
pub walls: Walls,
pub player_visibility: Visibility,
pub ai_visibility: Visibility,
pub items: Vec<Item>
}
impl Tile {
// Create a new tile
fn new(base: Image) -> Tile {
Tile {
base,
obstacle: Obstacle::Empty,
decoration: None,
walls: Walls::new(),
player_visibility: Visibility::Invisible,
ai_visibility: Visibility::Invisible,
items: Vec::new()
}
}
// Set the tile to be one of the pit images and remove the decoration
fn set_pit(&mut self, pit_image: Image) {
self.obstacle = Obstacle::Pit(pit_image);
self.decoration = None;
}
// return if the tile is visible to the player
pub fn visible(&self) -> bool {
!self.player_visibility.is_invisible()
}
// Actions that occur when the tile is walked on
pub fn walk_on(&mut self) {
// Crush the skeleton decoration
if let Some(Image::Skeleton) = self.decoration {
self.decoration = Some(Image::SkeletonCracked);
}
}
}
// A 2D array of tiles
#[derive(Serialize, Deserialize)]
pub struct Tiles {
tiles: Vec<Tile>,
pub cols: usize,
pub rows: usize
}
impl Tiles {
// Create a new set of tiles but do not generate it
pub fn new(cols: usize, rows: usize) -> Tiles {
let mut rng = rand::thread_rng();
let mut tiles = Vec::new();
let bases = &[Image::Base1, Image::Base2];
for _ in 0 .. cols * rows {
tiles.push(Tile::new(*rng.choose(bases).unwrap()));
}
Tiles {
cols, rows, tiles
}
}
// Generate the tiles
pub fn generate(&mut self, units: &Units) {
let mut rng = rand::thread_rng();
let objects = &[Image::ObjectRebar, Image::ObjectRubble];
for (x, y) in self.iter() {
let tile = self.at_mut(x, y);
let unit = units.at(x, y).is_some();
// Add in decorations
if rng.gen::<f32>() < 0.05 {
tile.decoration = Some(if rng.gen::<bool>() {
if unit { Image::SkeletonCracked } else { Image::Skeleton }
} else {
Image::Rubble
});
}
// Add in objects
if !unit && rng.gen::<f32>() < 0.05 {
tile.obstacle = Obstacle::Object(*rng.choose(objects).unwrap());
}
}
// Generate a randomly sized pit
self.add_pit(
rng.gen_range(MIN_PIT_SIZE, MAX_PIT_SIZE + 1),
rng.gen_range(MIN_PIT_SIZE, MAX_PIT_SIZE + 1)
);
// Add in the walls
for (x, y) in self.iter() {
if rng.gen::<f32>() < 0.1 {
if rng.gen::<bool>() {
self.add_left_wall(x, y, WallType::Ruin1);
self.add_top_wall(x, y + 1, WallType::Ruin1);
} else {
self.add_left_wall(x + 1, y, WallType::Ruin2);
self.add_top_wall(x, y + 1, WallType::Ruin2);
}
}
}
// Update visibility
self.update_visibility(units);
}
// Add a left wall if possible
pub fn add_left_wall(&mut self, x: usize, y: usize, tag: WallType) {
if x < self.cols && y < self.rows && (self.not_pit(x, y) || self.not_pit(x - 1, y)) {
self.at_mut(x, y).walls.set_left(tag);
}
}
// Add a top wall if possible
pub fn add_top_wall(&mut self, x: usize, y: usize, tag: WallType) {
if x < self.cols && y < self.rows && (self.not_pit(x, y) || self.not_pit(x, y - 1)) {
self.at_mut(x, y).walls.set_top(tag);
}
}
// Check if a position is in-bounds and not a pit
fn not_pit(&self, x: usize, y: usize) -> bool {
x < self.cols && y < self.rows && !self.at(x, y).obstacle.is_pit()
}
fn add_pit(&mut self, width: usize, height: usize) {
// Generate pit position and size
let mut rng = rand::thread_rng();
let max_x = self.cols - width - 1;
let max_y = self.rows - height - 1;
let pit_x = if max_x > 1 { rng.gen_range(1, max_x) } else { 1 };
let pit_y = if max_y > 1 { rng.gen_range(1, max_y) } else { 1 };
// Add pit corners
self.at_mut(pit_x, pit_y ).set_pit(Image::PitTop);
self.at_mut(pit_x, pit_y + height - 1).set_pit(Image::PitLeft);
self.at_mut(pit_x + width - 1, pit_y ).set_pit(Image::PitRight);
self.at_mut(pit_x + width - 1, pit_y + height - 1).set_pit(Image::PitBottom);
// Add in the top/bottom pit edges and center
for x in pit_x + 1 .. pit_x + width - 1 {
self.at_mut(x, pit_y ).set_pit(Image::PitTR);
self.at_mut(x, pit_y + height - 1).set_pit(Image::PitBL);
for y in pit_y + 1 .. pit_y + height - 1 {
self.at_mut(x, y).set_pit(Image::PitCenter);
}
}
// Add in the left/right pit edges
for y in pit_y + 1 .. pit_y + height - 1 {
self.at_mut(pit_x, y).set_pit(Image::PitTL);
self.at_mut(pit_x + width - 1, y).set_pit(Image::PitBR);
}
}
// Get a reference to a tile
pub fn at(&self, x: usize, y: usize) -> &Tile {
assert!(x < self.cols && y < self.rows, "Tile at ({}, {}) is out of bounds", x, y);
&self.tiles[x * self.rows + y]
}
// Get a mutable reference to a tile
pub fn at_mut(&mut self, x: usize, y: usize) -> &mut Tile {
assert!(x < self.cols && y < self.rows, "Tile at ({}, {}) is out of bounds", x, y);
&mut self.tiles[x * self.rows + y]
}
// Update the visibility of the map
pub fn update_visibility(&mut self, units: &Units) {
for (x, y) in self.iter() {
let player_visible = self.tile_visible(units, UnitSide::Player, x, y);
let ai_visible = self.tile_visible(units, UnitSide::AI, x, y);
let tile = self.at_mut(x, y);
// If the tile is visible set the visibility to visible, or if it was visible make it foggy
if let Some(distance) = player_visible {
tile.player_visibility = Visibility::Visible(distance);
} else if tile.player_visibility.is_visible() {
tile.player_visibility = Visibility::Foggy;
}
if let Some(distance) = ai_visible {
tile.ai_visibility = Visibility::Visible(distance);
} else if tile.ai_visibility.is_visible() {
tile.ai_visibility = Visibility::Foggy;
}
}
}
// Drop an item onto the map
pub fn drop(&mut self, x: usize, y: usize, item: Item) {
self.at_mut(x, y).items.push(item);
}
// Drop a vec of items onto the map
pub fn drop_all(&mut self, x: usize, y: usize, items: &mut Vec<Item>) {
self.at_mut(x, y).items.append(items);
}
// Return whether there is a wall between two tiles
fn wall_between(&self, a: Point, b: Point) -> bool {
let ((a_x, a_y), (b_x, b_y)) = (from_point(a), from_point(b));
! match (b.0 - a.0, b.1 - a.1) {
(0, 1) => self.vertical_clear(b_x, b_y),
(1, 0) => self.horizontal_clear(b_x, b_y),
(-1, 0) => self.horizontal_clear(a_x, a_y),
(-1, 1) => self.diagonal_clear(a_x, b_y, false),
(1, 1) => self.diagonal_clear(b_x, b_y, true),
_ => unreachable!()
}
}
// Return the first blocking obstacle between two points or none
pub fn line_of_fire(&self, start_x: usize, start_y: usize, end_x: usize, end_y: usize) -> Option<(Point, WallSide)> {
// Convert the points to isize and sort
let (start, end) = (to_point(start_x, start_y), to_point(end_x, end_y));
let (start, end, reversed) = sort(start, end);
// Create an iterator of tile steps
let mut iter = Bresenham::new(start, end).steps()
// Filter to steps with walls between
.filter(|&(a, b)| self.wall_between(a, b))
// Map to the containing tile and wall direction
.map(|(a, b)| match (b.0 - a.0, b.1 - a.1) {
(0, 1) => (b, WallSide::Top),
(1, 0) => (b, WallSide::Left),
(-1, 0) => (a, WallSide::Left),
// For diagonal steps we have to randomly pick one of the two closest walls
(-1, 1) | (1, 1) => {
let left_to_right = a.0 < b.0;
// Get the four walls segments between the tiles if left-to-right or their flipped equivalents
let (mut top, mut left, mut right, mut bottom) = if left_to_right {
((b.0, a.1), (a.0, b.1), b, b)
} else {
(a, (a.0, b.1), b, (a.0, b.1))
};
// Swap the points around if the line is reversed
if reversed {
swap(&mut top, &mut bottom);
swap(&mut left, &mut right);
}
// Get whether each of these segments contain walls
let top_block = !self.horizontal_clear(top.0 as usize, top.1 as usize);
let left_block = !self.vertical_clear(left.0 as usize, left.1 as usize);
let right_block = !self.vertical_clear(right.0 as usize, right.1 as usize);
let bottom_block = !self.horizontal_clear(bottom.0 as usize, bottom.1 as usize);
// Get the pairs of walls to choose from
let (wall_a, wall_b) = if top_block && left_block {
((top, WallSide::Left), (left, WallSide::Top))
} else if left_block && right_block {
((left, WallSide::Top), (right, WallSide::Top))
} else if top_block && bottom_block {
((top, WallSide::Left), (bottom, WallSide::Left))
} else {
((bottom, WallSide::Left), (right, WallSide::Top))
};
// Choose a random wall
if rand::random::<bool>() { wall_a } else { wall_b }
},
_ => unreachable!()
});
// Return either the last or first wall found or none
if reversed { iter.last() } else { iter.next() }
}
// Would a unit with a particular sight range be able to see from one tile to another
// Return the number of tiles away a point is, or none if visibility is blocked
pub fn line_of_sight(&self, a_x: usize, a_y: usize, b_x: usize, b_y: usize, sight: f32) -> Option<u8> {
if distance_under(a_x, a_y, b_x, b_y, sight) {
// Sort the points so that line-of-sight is symmetrical
let (start, end, _) = sort(to_point(a_x, a_y), to_point(b_x, b_y));
let mut distance = 0;
for (a, b) in Bresenham::new(start, end).steps() {
// Return if line of sight is blocked by a wall
if self.wall_between(a, b) {
return None;
}
// Increase the distance
distance += if a.0 == b.0 || a.1 == b.1 {
WALK_LATERAL_COST
} else {
WALK_DIAGONAL_COST
} as u8;
}
Some(distance)
} else {
None
}
}
// Is a tile visible by any unit on a particular side
fn tile_visible(&self, units: &Units, side: UnitSide, x: usize, y: usize) -> Option<u8> {
units.iter()
.filter(|unit| unit.side == side)
.map(|unit| self.line_of_sight(unit.x, unit.y, x, y, unit.tag.sight()))
// Get the minimum distance or none
.fold(None, |sum, dist| sum.and_then(|sum| dist.map(|dist| min(sum, dist))).or(sum).or(dist))
}
// Is the wall space between two horizontal tiles empty
pub fn horizontal_clear(&self, x: usize, y: usize) -> bool {
self.at(x, y).walls.left.is_none()
}
// Is the wall space between two vertical tiles empty
pub fn vertical_clear(&self, x: usize, y: usize) -> bool {
self.at(x, y).walls.top.is_none()
}
// Is a diagonal clear
pub fn diagonal_clear(&self, x: usize, y: usize, tl_to_br: bool) -> bool {
if x.wrapping_sub(1) >= self.cols - 1 || y.wrapping_sub(1) >= self.rows - 1 {
return false;
}
// Check the walls between the tiles
let top = self.horizontal_clear(x, y - 1);
let left = self.vertical_clear(x - 1, y);
let right = self.vertical_clear(x, y);
let bottom = self.horizontal_clear(x, y);
// Check that there isn't a wall across the tiles and the right corners are open
(top || bottom) && (left || right) && if tl_to_br {
(top || left) && (bottom || right)
} else {
(top || right) && (bottom || left)
}
}
// What should the visiblity of a left wall at a position be
pub fn left_wall_visibility(&self, x: usize, y: usize) -> Visibility {
let visibility = self.at(x, y).player_visibility;
if x > 0 {
combine_visibilities(visibility, self.at(x - 1, y).player_visibility)
} else {
visibility
}
}
// What should the visibility of a top wall at a position be
pub fn top_wall_visibility(&self, x: usize, y: usize) -> Visibility {
let visibility = self.at(x, y).player_visibility;
if y > 0 {
combine_visibilities(visibility, self.at(x, y - 1).player_visibility)
} else {
visibility
}
}
// Iterate through the rows and columns
pub fn iter(&self) -> Iter2D {
Iter2D::new(self.cols, self.rows)
}
}
#[test]
fn unit_visibility() {
use super::units::UnitType;
let mut tiles = Tiles::new(30, 30);
let mut units = Units::new();
units.add(UnitType::Squaddie, UnitSide::Player, 0, 0);
tiles.update_visibility(&units);
// A tile a unit is standing on should be visible with a distance of 0
assert_eq!(tiles.at(0, 0).player_visibility, Visibility::Visible(0));
// A far away tile should be invisible
assert_eq!(tiles.at(29, 29).player_visibility, Visibility::Invisible);
// A tile that was visible but is no longer should be foggy
units.get_mut(0).unwrap().move_to(29, 0, 0);
tiles.update_visibility(&units);
assert_eq!(tiles.at(0, 0).player_visibility, Visibility::Foggy);
// If the unit is boxed into a corner, only it's tile should be visible
tiles.add_left_wall(29, 0, WallType::Ruin1);
tiles.add_top_wall(29, 1, WallType::Ruin2);
tiles.update_visibility(&units);
for (x, y) in tiles.iter() {
let visibility = tiles.at(x, y).player_visibility;
if x == 29 && y == 0 {
assert_eq!(visibility, Visibility::Visible(0));
} else {
assert!(!visibility.is_visible());
}
}
}
#[test]
fn line_of_fire() {
let mut tiles = Tiles::new(5, 5);
tiles.add_left_wall(1, 0, WallType::Ruin1);
tiles.add_top_wall(0, 1, WallType::Ruin1);
tiles.add_top_wall(1, 1, WallType::Ruin1);
tiles.add_left_wall(1, 1, WallType::Ruin1);
let top = Some(((1, 0), WallSide::Left));
let left = Some(((0, 1), WallSide::Top));
let right = Some(((1, 1), WallSide::Top));
let bottom = Some(((1, 1), WallSide::Left));
// Test lateral directions
assert_eq!(tiles.line_of_fire(0, 0, 1, 0), top);
assert_eq!(tiles.line_of_fire(0, 0, 0, 1), left);
// Test diagonal directions
let diag_1 = tiles.line_of_fire(0, 0, 1, 1);
assert!(diag_1 == top || diag_1 == left);
let diag_2 = tiles.line_of_fire(1, 1, 0, 0);
assert!(diag_2 == bottom || diag_2 == right);
let diag_3 = tiles.line_of_fire(0, 1, 1, 0);
assert!(diag_3 == left || diag_3 == bottom);
let diag_4 = tiles.line_of_fire(1, 0, 0, 1);
assert!(diag_4 == right || diag_4 == top);
}
#[test]
fn pit_generation() {
let mut tiles = Tiles::new(30, 30);
tiles.generate(&Units::new());
// At least one tile should have a pit on it
assert!(tiles.tiles.iter().any(|tile| tile.obstacle.is_pit()));
}
#[test]
fn walk_on_tile() {
let mut tiles = Tiles::new(30, 30);
let tile = tiles.at_mut(0, 0);
tile.decoration = Some(Image::Skeleton);
tile.walk_on();
assert_eq!(tile.decoration, Some(Image::SkeletonCracked));
}
#[test]
fn map_generation() {
let units = Units::new();
// Test generating maps at various sizes
Tiles::new(10, 10).generate(&units);
Tiles::new(30, 30).generate(&units);
Tiles::new(10, 30).generate(&units);
Tiles::new(30, 10).generate(&units);
}
Fixed tests
// The tiles in the map, and a struct to contain them
use rand;
use rand::Rng;
use line_drawing::Bresenham;
use super::units::{UnitSide, Units, WALK_LATERAL_COST, WALK_DIAGONAL_COST, UNIT_SIGHT};
use super::walls::{Walls, WallType, WallSide};
use super::iter_2d::Iter2D;
use items::Item;
use utils::{distance_under, min, lerp};
use resources::Image;
use std::mem::swap;
const DAY_DARKNESS_RATE: f32 = 0.025;
const NIGHT_DARKNESS_RATE: f32 = 0.05;
const MIN_PIT_SIZE: usize = 2;
const MAX_PIT_SIZE: usize = 5;
// A point for line-of-sight
type Point = (isize, isize);
// Sort two points on the y axis
fn sort(a: Point, b: Point) -> (Point, Point, bool) {
if a.1 > b.1 {
(b, a, true)
} else {
(a, b, false)
}
}
// Convert a coord in `usize`s to a point
fn to_point(x: usize, y: usize) -> Point {
(x as isize, y as isize)
}
// Convert a point back into `usize`s
fn from_point(point: Point) -> (usize, usize) {
(point.0 as usize, point.1 as usize)
}
// The visibility of the tile
#[derive(Copy, Clone, Serialize, Deserialize, Debug, is_enum_variant, PartialEq)]
pub enum Visibility {
Visible(u8),
Foggy,
Invisible
}
impl Visibility {
// Get the corresponding colour for a visibility
pub fn colour(&self, light: f32) -> [f32; 4] {
// Get the rate at which tiles get darker
let rate = lerp(NIGHT_DARKNESS_RATE, DAY_DARKNESS_RATE, light);
// Use the distance if the tile is visible
let alpha = if let Visibility::Visible(distance) = *self {
f32::from(distance) * rate
// Or use the maximum darkness + 0.1
} else if self.is_foggy() {
rate * (UNIT_SIGHT * f32::from(WALK_LATERAL_COST)) + 0.1
} else {
0.0
};
[0.0, 0.0, 0.0, alpha]
}
// Return the distance of the tile or the maximum value
fn distance(&self) -> u8 {
if let Visibility::Visible(value) = *self {
value
} else {
u8::max_value()
}
}
}
// Get the highest of two visibilities
fn combine_visibilities(a: Visibility, b: Visibility) -> Visibility {
if a.is_visible() || b.is_visible() {
// Use the mimimum of the two distances
Visibility::Visible(min(a.distance(), b.distance()))
} else if a.is_foggy() || b.is_foggy() {
Visibility::Foggy
} else {
Visibility::Invisible
}
}
#[derive(Serialize, Deserialize, is_enum_variant)]
pub enum Obstacle {
Object(Image),
Pit(Image),
Empty
}
// A tile in the map
#[derive(Serialize, Deserialize)]
pub struct Tile {
pub base: Image,
pub obstacle: Obstacle,
pub decoration: Option<Image>,
pub walls: Walls,
pub player_visibility: Visibility,
pub ai_visibility: Visibility,
pub items: Vec<Item>
}
impl Tile {
// Create a new tile
fn new(base: Image) -> Tile {
Tile {
base,
obstacle: Obstacle::Empty,
decoration: None,
walls: Walls::new(),
player_visibility: Visibility::Invisible,
ai_visibility: Visibility::Invisible,
items: Vec::new()
}
}
// Set the tile to be one of the pit images and remove the decoration
fn set_pit(&mut self, pit_image: Image) {
self.obstacle = Obstacle::Pit(pit_image);
self.decoration = None;
}
// return if the tile is visible to the player
pub fn visible(&self) -> bool {
!self.player_visibility.is_invisible()
}
// Actions that occur when the tile is walked on
pub fn walk_on(&mut self) {
// Crush the skeleton decoration
if let Some(Image::Skeleton) = self.decoration {
self.decoration = Some(Image::SkeletonCracked);
}
}
}
// A 2D array of tiles
#[derive(Serialize, Deserialize)]
pub struct Tiles {
tiles: Vec<Tile>,
pub cols: usize,
pub rows: usize
}
impl Tiles {
// Create a new set of tiles but do not generate it
pub fn new(cols: usize, rows: usize) -> Tiles {
let mut rng = rand::thread_rng();
let mut tiles = Vec::new();
let bases = &[Image::Base1, Image::Base2];
for _ in 0 .. cols * rows {
tiles.push(Tile::new(*rng.choose(bases).unwrap()));
}
Tiles {
cols, rows, tiles
}
}
// Generate the tiles
pub fn generate(&mut self, units: &Units) {
let mut rng = rand::thread_rng();
let objects = &[Image::ObjectRebar, Image::ObjectRubble];
for (x, y) in self.iter() {
let tile = self.at_mut(x, y);
let unit = units.at(x, y).is_some();
// Add in decorations
if rng.gen::<f32>() < 0.05 {
tile.decoration = Some(if rng.gen::<bool>() {
if unit { Image::SkeletonCracked } else { Image::Skeleton }
} else {
Image::Rubble
});
}
// Add in objects
if !unit && rng.gen::<f32>() < 0.05 {
tile.obstacle = Obstacle::Object(*rng.choose(objects).unwrap());
}
}
// Generate a randomly sized pit
self.add_pit(
rng.gen_range(MIN_PIT_SIZE, MAX_PIT_SIZE + 1),
rng.gen_range(MIN_PIT_SIZE, MAX_PIT_SIZE + 1)
);
// Add in the walls
for (x, y) in self.iter() {
if rng.gen::<f32>() < 0.1 {
if rng.gen::<bool>() {
self.add_left_wall(x, y, WallType::Ruin1);
self.add_top_wall(x, y + 1, WallType::Ruin1);
} else {
self.add_left_wall(x + 1, y, WallType::Ruin2);
self.add_top_wall(x, y + 1, WallType::Ruin2);
}
}
}
// Update visibility
self.update_visibility(units);
}
// Add a left wall if possible
pub fn add_left_wall(&mut self, x: usize, y: usize, tag: WallType) {
if x < self.cols && y < self.rows && (self.not_pit(x, y) || self.not_pit(x - 1, y)) {
self.at_mut(x, y).walls.set_left(tag);
}
}
// Add a top wall if possible
pub fn add_top_wall(&mut self, x: usize, y: usize, tag: WallType) {
if x < self.cols && y < self.rows && (self.not_pit(x, y) || self.not_pit(x, y - 1)) {
self.at_mut(x, y).walls.set_top(tag);
}
}
// Check if a position is in-bounds and not a pit
fn not_pit(&self, x: usize, y: usize) -> bool {
x < self.cols && y < self.rows && !self.at(x, y).obstacle.is_pit()
}
fn add_pit(&mut self, width: usize, height: usize) {
// Generate pit position and size
let mut rng = rand::thread_rng();
let max_x = self.cols - width - 1;
let max_y = self.rows - height - 1;
let pit_x = if max_x > 1 { rng.gen_range(1, max_x) } else { 1 };
let pit_y = if max_y > 1 { rng.gen_range(1, max_y) } else { 1 };
// Add pit corners
self.at_mut(pit_x, pit_y ).set_pit(Image::PitTop);
self.at_mut(pit_x, pit_y + height - 1).set_pit(Image::PitLeft);
self.at_mut(pit_x + width - 1, pit_y ).set_pit(Image::PitRight);
self.at_mut(pit_x + width - 1, pit_y + height - 1).set_pit(Image::PitBottom);
// Add in the top/bottom pit edges and center
for x in pit_x + 1 .. pit_x + width - 1 {
self.at_mut(x, pit_y ).set_pit(Image::PitTR);
self.at_mut(x, pit_y + height - 1).set_pit(Image::PitBL);
for y in pit_y + 1 .. pit_y + height - 1 {
self.at_mut(x, y).set_pit(Image::PitCenter);
}
}
// Add in the left/right pit edges
for y in pit_y + 1 .. pit_y + height - 1 {
self.at_mut(pit_x, y).set_pit(Image::PitTL);
self.at_mut(pit_x + width - 1, y).set_pit(Image::PitBR);
}
}
// Get a reference to a tile
pub fn at(&self, x: usize, y: usize) -> &Tile {
assert!(x < self.cols && y < self.rows, "Tile at ({}, {}) is out of bounds", x, y);
&self.tiles[x * self.rows + y]
}
// Get a mutable reference to a tile
pub fn at_mut(&mut self, x: usize, y: usize) -> &mut Tile {
assert!(x < self.cols && y < self.rows, "Tile at ({}, {}) is out of bounds", x, y);
&mut self.tiles[x * self.rows + y]
}
// Update the visibility of the map
pub fn update_visibility(&mut self, units: &Units) {
for (x, y) in self.iter() {
let player_visible = self.tile_visible(units, UnitSide::Player, x, y);
let ai_visible = self.tile_visible(units, UnitSide::AI, x, y);
let tile = self.at_mut(x, y);
// If the tile is visible set the visibility to visible, or if it was visible make it foggy
if let Some(distance) = player_visible {
tile.player_visibility = Visibility::Visible(distance);
} else if tile.player_visibility.is_visible() {
tile.player_visibility = Visibility::Foggy;
}
if let Some(distance) = ai_visible {
tile.ai_visibility = Visibility::Visible(distance);
} else if tile.ai_visibility.is_visible() {
tile.ai_visibility = Visibility::Foggy;
}
}
}
// Drop an item onto the map
pub fn drop(&mut self, x: usize, y: usize, item: Item) {
self.at_mut(x, y).items.push(item);
}
// Drop a vec of items onto the map
pub fn drop_all(&mut self, x: usize, y: usize, items: &mut Vec<Item>) {
self.at_mut(x, y).items.append(items);
}
// Return whether there is a wall between two tiles
fn wall_between(&self, a: Point, b: Point) -> bool {
let ((a_x, a_y), (b_x, b_y)) = (from_point(a), from_point(b));
! match (b.0 - a.0, b.1 - a.1) {
(0, 1) => self.vertical_clear(b_x, b_y),
(1, 0) => self.horizontal_clear(b_x, b_y),
(-1, 0) => self.horizontal_clear(a_x, a_y),
(-1, 1) => self.diagonal_clear(a_x, b_y, false),
(1, 1) => self.diagonal_clear(b_x, b_y, true),
_ => unreachable!()
}
}
// Return the first blocking obstacle between two points or none
pub fn line_of_fire(&self, start_x: usize, start_y: usize, end_x: usize, end_y: usize) -> Option<(Point, WallSide)> {
// Convert the points to isize and sort
let (start, end) = (to_point(start_x, start_y), to_point(end_x, end_y));
let (start, end, reversed) = sort(start, end);
// Create an iterator of tile steps
let mut iter = Bresenham::new(start, end).steps()
// Filter to steps with walls between
.filter(|&(a, b)| self.wall_between(a, b))
// Map to the containing tile and wall direction
.map(|(a, b)| match (b.0 - a.0, b.1 - a.1) {
(0, 1) => (b, WallSide::Top),
(1, 0) => (b, WallSide::Left),
(-1, 0) => (a, WallSide::Left),
// For diagonal steps we have to randomly pick one of the two closest walls
(-1, 1) | (1, 1) => {
let left_to_right = a.0 < b.0;
// Get the four walls segments between the tiles if left-to-right or their flipped equivalents
let (mut top, mut left, mut right, mut bottom) = if left_to_right {
((b.0, a.1), (a.0, b.1), b, b)
} else {
(a, (a.0, b.1), b, (a.0, b.1))
};
// Swap the points around if the line is reversed
if reversed {
swap(&mut top, &mut bottom);
swap(&mut left, &mut right);
}
// Get whether each of these segments contain walls
let top_block = !self.horizontal_clear(top.0 as usize, top.1 as usize);
let left_block = !self.vertical_clear(left.0 as usize, left.1 as usize);
let right_block = !self.vertical_clear(right.0 as usize, right.1 as usize);
let bottom_block = !self.horizontal_clear(bottom.0 as usize, bottom.1 as usize);
// Get the pairs of walls to choose from
let (wall_a, wall_b) = if top_block && left_block {
((top, WallSide::Left), (left, WallSide::Top))
} else if left_block && right_block {
((left, WallSide::Top), (right, WallSide::Top))
} else if top_block && bottom_block {
((top, WallSide::Left), (bottom, WallSide::Left))
} else {
((bottom, WallSide::Left), (right, WallSide::Top))
};
// Choose a random wall
if rand::random::<bool>() { wall_a } else { wall_b }
},
_ => unreachable!()
});
// Return either the last or first wall found or none
if reversed { iter.last() } else { iter.next() }
}
// Would a unit with a particular sight range be able to see from one tile to another
// Return the number of tiles away a point is, or none if visibility is blocked
pub fn line_of_sight(&self, a_x: usize, a_y: usize, b_x: usize, b_y: usize, sight: f32) -> Option<u8> {
if distance_under(a_x, a_y, b_x, b_y, sight) {
// Sort the points so that line-of-sight is symmetrical
let (start, end, _) = sort(to_point(a_x, a_y), to_point(b_x, b_y));
let mut distance = 0;
for (a, b) in Bresenham::new(start, end).steps() {
// Return if line of sight is blocked by a wall
if self.wall_between(a, b) {
return None;
}
// Increase the distance
distance += if a.0 == b.0 || a.1 == b.1 {
WALK_LATERAL_COST
} else {
WALK_DIAGONAL_COST
} as u8;
}
Some(distance)
} else {
None
}
}
// Is a tile visible by any unit on a particular side
fn tile_visible(&self, units: &Units, side: UnitSide, x: usize, y: usize) -> Option<u8> {
units.iter()
.filter(|unit| unit.side == side)
.map(|unit| self.line_of_sight(unit.x, unit.y, x, y, unit.tag.sight()))
// Get the minimum distance or none
.fold(None, |sum, dist| sum.and_then(|sum| dist.map(|dist| min(sum, dist))).or(sum).or(dist))
}
// Is the wall space between two horizontal tiles empty
pub fn horizontal_clear(&self, x: usize, y: usize) -> bool {
self.at(x, y).walls.left.is_none()
}
// Is the wall space between two vertical tiles empty
pub fn vertical_clear(&self, x: usize, y: usize) -> bool {
self.at(x, y).walls.top.is_none()
}
// Is a diagonal clear
pub fn diagonal_clear(&self, x: usize, y: usize, tl_to_br: bool) -> bool {
if x.wrapping_sub(1) >= self.cols - 1 || y.wrapping_sub(1) >= self.rows - 1 {
return false;
}
// Check the walls between the tiles
let top = self.horizontal_clear(x, y - 1);
let left = self.vertical_clear(x - 1, y);
let right = self.vertical_clear(x, y);
let bottom = self.horizontal_clear(x, y);
// Check that there isn't a wall across the tiles and the right corners are open
(top || bottom) && (left || right) && if tl_to_br {
(top || left) && (bottom || right)
} else {
(top || right) && (bottom || left)
}
}
// What should the visiblity of a left wall at a position be
pub fn left_wall_visibility(&self, x: usize, y: usize) -> Visibility {
let visibility = self.at(x, y).player_visibility;
if x > 0 {
combine_visibilities(visibility, self.at(x - 1, y).player_visibility)
} else {
visibility
}
}
// What should the visibility of a top wall at a position be
pub fn top_wall_visibility(&self, x: usize, y: usize) -> Visibility {
let visibility = self.at(x, y).player_visibility;
if y > 0 {
combine_visibilities(visibility, self.at(x, y - 1).player_visibility)
} else {
visibility
}
}
// Iterate through the rows and columns
pub fn iter(&self) -> Iter2D {
Iter2D::new(self.cols, self.rows)
}
}
#[test]
fn unit_visibility() {
use super::units::UnitType;
let mut tiles = Tiles::new(30, 30);
let mut units = Units::new();
units.add(UnitType::Squaddie, UnitSide::Player, 0, 0);
tiles.update_visibility(&units);
// A tile a unit is standing on should be visible with a distance of 0
assert_eq!(tiles.at(0, 0).player_visibility, Visibility::Visible(0));
// A far away tile should be invisible
assert_eq!(tiles.at(29, 29).player_visibility, Visibility::Invisible);
// A tile that was visible but is no longer should be foggy
units.get_mut(0).unwrap().move_to(29, 0, 0);
tiles.update_visibility(&units);
assert_eq!(tiles.at(0, 0).player_visibility, Visibility::Foggy);
// If the unit is boxed into a corner, only it's tile should be visible
tiles.add_left_wall(29, 0, WallType::Ruin1);
tiles.add_top_wall(29, 1, WallType::Ruin2);
tiles.update_visibility(&units);
for (x, y) in tiles.iter() {
let visibility = tiles.at(x, y).player_visibility;
if x == 29 && y == 0 {
assert_eq!(visibility, Visibility::Visible(0));
} else {
assert!(!visibility.is_visible());
}
}
}
#[test]
fn line_of_fire() {
let mut tiles = Tiles::new(5, 5);
tiles.add_left_wall(1, 0, WallType::Ruin1);
tiles.add_top_wall(0, 1, WallType::Ruin1);
tiles.add_top_wall(1, 1, WallType::Ruin1);
tiles.add_left_wall(1, 1, WallType::Ruin1);
let top = Some(((1, 0), WallSide::Left));
let left = Some(((0, 1), WallSide::Top));
let right = Some(((1, 1), WallSide::Top));
let bottom = Some(((1, 1), WallSide::Left));
// Test lateral directions
assert_eq!(tiles.line_of_fire(0, 0, 1, 0), top);
assert_eq!(tiles.line_of_fire(0, 0, 0, 1), left);
// Test diagonal directions
let diag_1 = tiles.line_of_fire(0, 0, 1, 1);
assert!(diag_1 == top || diag_1 == left);
let diag_2 = tiles.line_of_fire(1, 1, 0, 0);
assert!(diag_2 == bottom || diag_2 == right);
let diag_3 = tiles.line_of_fire(0, 1, 1, 0);
assert!(diag_3 == left || diag_3 == bottom);
let diag_4 = tiles.line_of_fire(1, 0, 0, 1);
assert!(diag_4 == right || diag_4 == top);
}
#[test]
fn pit_generation() {
let mut tiles = Tiles::new(30, 30);
tiles.generate(&Units::new());
// At least one tile should have a pit on it
assert!(tiles.tiles.iter().any(|tile| tile.obstacle.is_pit()));
}
#[test]
fn walk_on_tile() {
let mut tiles = Tiles::new(30, 30);
let tile = tiles.at_mut(0, 0);
tile.decoration = Some(Image::Skeleton);
tile.walk_on();
assert_eq!(tile.decoration, Some(Image::SkeletonCracked));
}
#[test]
fn map_generation() {
let units = Units::new();
// Test generating maps at various sizes
Tiles::new(10, 10).generate(&units);
Tiles::new(30, 30).generate(&units);
Tiles::new(10, 30).generate(&units);
Tiles::new(30, 10).generate(&units);
} |
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.com>
//
// 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.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
extern crate libc;
pub const AF_LINK: libc::c_int = 18;
const IF_NAMESIZE: uint = 16;
const IFNAMSIZ: uint = IF_NAMESIZE;
const IOC_IN: libc::c_ulong = 0x80000000;
const IOC_OUT: libc::c_ulong = 0x40000000;
const IOC_INOUT: libc::c_ulong = IOC_IN | IOC_OUT;
const IOCPARM_SHIFT: libc::c_ulong = 13;
const IOCPARM_MASK: libc::c_ulong = (1 << (IOCPARM_SHIFT as uint)) - 1;
const SIZEOF_IFREQ: libc::c_ulong = 32;
const SIZEOF_C_UINT: libc::c_ulong = 4;
#[cfg(target_os = "freebsd")]
const SIZEOF_C_LONG: libc::c_int = 8;
pub const BIOCSETIF: libc::c_ulong = IOC_IN |
((SIZEOF_IFREQ & IOCPARM_MASK) << 16u) |
('B' as libc::c_ulong << 8u) |
108;
pub const BIOCIMMEDIATE: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
112;
pub const BIOCGBLEN: libc::c_ulong = IOC_OUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
102;
pub const BIOCGDLT: libc::c_ulong = IOC_OUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
106;
pub const BIOCSBLEN: libc::c_ulong = IOC_INOUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
102;
pub const BIOCSHDRCMPLT: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
117;
#[cfg(target_os = "freebsd")]
pub const BIOCFEEDBACK: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
124;
// NOTE Could use BIOCSSEESENT on OS X, though set to 1 by default anyway
pub const DLT_NULL: libc::c_uint = 0;
#[cfg(target_os = "freebsd")]
const BPF_ALIGNMENT: libc::c_int = SIZEOF_C_LONG;
#[cfg(target_os = "macos")]
#[cfg(windows)]
const BPF_ALIGNMENT: libc::c_int = 4;
pub fn BPF_WORDALIGN<T : Int + ToPrimitive + FromPrimitive>(x: T) -> T {
use std::num::{from_i32};
let bpf_alignment: T = from_i32(BPF_ALIGNMENT).unwrap();
let one: T = from_i32(1).unwrap();
(x + (bpf_alignment - one)) & !(bpf_alignment - one)
}
// See /usr/include/net/if.h
pub struct ifreq {
pub ifr_name: [libc::c_char, ..IFNAMSIZ],
pub ifru_addr: libc::sockaddr, // NOTE Should be a union
}
// See /usr/include/net/if_dl.h
#[cfg(target_os = "freebsd")]
pub struct sockaddr_dl {
pub sdl_len: libc::c_uchar,
pub sdl_family: libc::c_uchar,
pub sdl_index: libc::c_ushort,
pub sdl_type: libc::c_uchar,
pub sdl_nlen: libc::c_uchar,
pub sdl_alen: libc::c_uchar,
pub sdl_slen: libc::c_uchar,
pub sdl_data: [libc::c_char, ..46],
}
#[cfg(target_os = "macos")]
pub struct sockaddr_dl {
pub sdl_len: libc::c_uchar,
pub sdl_family: libc::c_uchar,
pub sdl_index: libc::c_ushort,
pub sdl_type: libc::c_uchar,
pub sdl_nlen: libc::c_uchar,
pub sdl_alen: libc::c_uchar,
pub sdl_slen: libc::c_uchar,
pub sdl_data: [libc::c_char, ..12],
pub sdl_rcf: libc::c_ushort,
pub sdl_route: [libc::c_ushort, ..16],
}
// See man 4 bpf or /usr/include/net/bpf.h [windows: or Common/Packet32.h]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "macos", target_word_size = "32")]
#[cfg(windows)]
pub struct bpf_hdr {
pub bh_tstamp: libc::timeval,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,
}
pub struct timeval32 {
pub tv_sec: i32,
pub tv_usec: i32,
}
#[cfg(target_os = "macos", target_word_size = "64")]
pub struct bpf_hdr {
pub bh_tstamp: timeval32,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,
}
#[cfg(not(windows))]
extern {
pub fn ioctl(d: libc::c_int, request: libc::c_ulong, ...) -> libc::c_int;
}
Tests failed when presented with an interface name longer than 6 characters on OS X. Since sdl_data is variable length on OS X, and sdl_rcf and sdl_route aren't used in the library it seems sensible just to merge the structs for freebsd and os x here. Not sure if 46 is the correct maximum for sdl_data, however.
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.com>
//
// 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.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
extern crate libc;
pub const AF_LINK: libc::c_int = 18;
const IF_NAMESIZE: uint = 16;
const IFNAMSIZ: uint = IF_NAMESIZE;
const IOC_IN: libc::c_ulong = 0x80000000;
const IOC_OUT: libc::c_ulong = 0x40000000;
const IOC_INOUT: libc::c_ulong = IOC_IN | IOC_OUT;
const IOCPARM_SHIFT: libc::c_ulong = 13;
const IOCPARM_MASK: libc::c_ulong = (1 << (IOCPARM_SHIFT as uint)) - 1;
const SIZEOF_IFREQ: libc::c_ulong = 32;
const SIZEOF_C_UINT: libc::c_ulong = 4;
#[cfg(target_os = "freebsd")]
const SIZEOF_C_LONG: libc::c_int = 8;
pub const BIOCSETIF: libc::c_ulong = IOC_IN |
((SIZEOF_IFREQ & IOCPARM_MASK) << 16u) |
('B' as libc::c_ulong << 8u) |
108;
pub const BIOCIMMEDIATE: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
112;
pub const BIOCGBLEN: libc::c_ulong = IOC_OUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
102;
pub const BIOCGDLT: libc::c_ulong = IOC_OUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
106;
pub const BIOCSBLEN: libc::c_ulong = IOC_INOUT |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
102;
pub const BIOCSHDRCMPLT: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
117;
#[cfg(target_os = "freebsd")]
pub const BIOCFEEDBACK: libc::c_ulong = IOC_IN |
((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
('B' as libc::c_ulong << 8) |
124;
// NOTE Could use BIOCSSEESENT on OS X, though set to 1 by default anyway
pub const DLT_NULL: libc::c_uint = 0;
#[cfg(target_os = "freebsd")]
const BPF_ALIGNMENT: libc::c_int = SIZEOF_C_LONG;
#[cfg(target_os = "macos")]
#[cfg(windows)]
const BPF_ALIGNMENT: libc::c_int = 4;
pub fn BPF_WORDALIGN<T : Int + ToPrimitive + FromPrimitive>(x: T) -> T {
use std::num::{from_i32};
let bpf_alignment: T = from_i32(BPF_ALIGNMENT).unwrap();
let one: T = from_i32(1).unwrap();
(x + (bpf_alignment - one)) & !(bpf_alignment - one)
}
// See /usr/include/net/if.h
pub struct ifreq {
pub ifr_name: [libc::c_char, ..IFNAMSIZ],
pub ifru_addr: libc::sockaddr, // NOTE Should be a union
}
// See /usr/include/net/if_dl.h
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
pub struct sockaddr_dl {
pub sdl_len: libc::c_uchar,
pub sdl_family: libc::c_uchar,
pub sdl_index: libc::c_ushort,
pub sdl_type: libc::c_uchar,
pub sdl_nlen: libc::c_uchar,
pub sdl_alen: libc::c_uchar,
pub sdl_slen: libc::c_uchar,
pub sdl_data: [libc::c_char, ..46],
}
// See man 4 bpf or /usr/include/net/bpf.h [windows: or Common/Packet32.h]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "macos", target_word_size = "32")]
#[cfg(windows)]
pub struct bpf_hdr {
pub bh_tstamp: libc::timeval,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,
}
pub struct timeval32 {
pub tv_sec: i32,
pub tv_usec: i32,
}
#[cfg(target_os = "macos", target_word_size = "64")]
pub struct bpf_hdr {
pub bh_tstamp: timeval32,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,
}
#[cfg(not(windows))]
extern {
pub fn ioctl(d: libc::c_int, request: libc::c_ulong, ...) -> libc::c_int;
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use super::apply_transforms::Programs;
use crate::config::{Config, ProjectConfig};
use crate::errors::BuildProjectError;
use graphql_ir::{FragmentDefinition, OperationDefinition};
use graphql_text_printer::{
print_fragment, print_full_operation, write_operation_with_graphqljs_formatting,
};
use interner::StringKey;
use md5::{Digest, Md5};
use persist_query::persist;
use relay_codegen::build_request_params;
use signedsource::{sign_file, SIGNING_TOKEN};
use std::fmt::Write;
/// Represents a generated output artifact.
#[derive(Clone)]
pub struct Artifact {
pub name: StringKey,
pub content: String,
pub hash: String,
}
pub async fn generate_artifacts(
config: &Config,
project_config: &ProjectConfig,
programs: &Programs<'_>,
) -> Result<Vec<Artifact>, BuildProjectError> {
let mut artifacts = Vec::new();
for node in programs.normalization.operations() {
let source_node = programs.source.operation(node.name.item).unwrap();
// TODO: Consider using the std::io::Write trait here to directly
// write to the md5. Currently, this doesn't work as `write_operation`
// expects a `std::fmt::Write`.
// Same for fragment hashing below.
let mut source_string = String::new();
write_operation_with_graphqljs_formatting(
programs.source.schema(),
&source_node,
&mut source_string,
)
.unwrap();
let hash = md5(&source_string);
artifacts.push(
generate_normalization_artifact(config, project_config, programs, node, &hash).await?,
);
}
for node in programs.reader.fragments() {
let source_node = programs.source.fragment(node.name.item).unwrap();
// Same as for operation hashing above.
let source_string = print_fragment(programs.source.schema(), &source_node);
let hash = md5(&source_string);
artifacts.push(generate_reader_artifact(config, programs, node, &hash));
}
Ok(artifacts)
}
async fn generate_normalization_artifact(
config: &Config,
project_config: &ProjectConfig,
programs: &Programs<'_>,
node: &OperationDefinition,
source_hash: &str,
) -> Result<Artifact, BuildProjectError> {
let name = node.name.item;
let print_operation_node = programs
.operation_text
.operation(name)
.expect("a query text operation should be generated for this operation");
let text = print_full_operation(&programs.operation_text, print_operation_node);
let mut request_parameters = build_request_params(&node);
let mut operation_hash = None;
if let Some(ref persist_config) = project_config.persist {
operation_hash = Some(md5(&text));
let id = persist(&text, &persist_config.url, &persist_config.params)
.await
.map_err(BuildProjectError::PersistError)?;
request_parameters.id = Some(id);
} else {
request_parameters.text = Some(text.clone());
};
let reader_operation = programs
.reader
.operation(name)
.expect("a reader fragment should be generated for this operation");
let operation_fragment = FragmentDefinition {
name: reader_operation.name,
variable_definitions: reader_operation.variable_definitions.clone(),
selections: reader_operation.selections.clone(),
used_global_variables: Default::default(),
directives: reader_operation.directives.clone(),
type_condition: reader_operation.type_,
};
let mut content = get_content_start(config);
writeln!(content, " * {}", SIGNING_TOKEN).unwrap();
if let Some(operation_hash) = operation_hash {
writeln!(content, " * @relayHash {}", operation_hash).unwrap();
}
writeln!(content, " * @flow").unwrap();
writeln!(content, " * @lightSyntaxTransform").unwrap();
writeln!(content, " * @nogrep").unwrap();
if let Some(codegen_command) = &config.codegen_command {
writeln!(content, " * @codegen-command: {}", codegen_command).unwrap();
}
writeln!(content, " */\n").unwrap();
writeln!(content, "/* eslint-disable */\n").unwrap();
writeln!(content, "'use strict';\n").unwrap();
if let Some(id) = &request_parameters.id {
writeln!(content, "// @relayRequestID {}\n", id).unwrap();
}
writeln!(content, "/*::\nTODO flow\n*/\n").unwrap();
writeln!(content, "/*\n{}*/\n", text).unwrap();
writeln!(
content,
"var node/*: ConcreteRequest*/ = {};\n",
relay_codegen::print_request_deduped(
programs.normalization.schema(),
node,
&operation_fragment,
request_parameters
)
)
.unwrap();
writeln!(content, "if (__DEV__) {{").unwrap();
writeln!(content, " (node/*: any*/).hash = \"{}\";", source_hash).unwrap();
writeln!(content, "}}\n").unwrap();
writeln!(content, "module.exports = node;").unwrap();
Ok(Artifact {
name: node.name.item,
content: sign_file(&content),
hash: source_hash.to_string(),
})
}
fn generate_reader_artifact(
config: &Config,
programs: &Programs<'_>,
node: &FragmentDefinition,
hash: &str,
) -> Artifact {
let mut content = get_content_start(config);
writeln!(content, " * {}", SIGNING_TOKEN).unwrap();
writeln!(content, " * @flow").unwrap();
writeln!(content, " * @lightSyntaxTransform").unwrap();
writeln!(content, " * @nogrep").unwrap();
if let Some(codegen_command) = &config.codegen_command {
writeln!(content, " * @codegen-command: {}", codegen_command).unwrap();
}
writeln!(content, " */\n").unwrap();
writeln!(content, "/* eslint-disable */\n").unwrap();
writeln!(content, "'use strict';\n").unwrap();
writeln!(content, "/*::\nTODO flow\n*/\n").unwrap();
writeln!(
content,
"var node/*: ReaderFragment*/ = {};\n",
relay_codegen::print_fragment_deduped(programs.normalization.schema(), node)
)
.unwrap();
writeln!(content, "if (__DEV__) {{").unwrap();
writeln!(content, " (node/*: any*/).hash = \"{}\";", hash).unwrap();
writeln!(content, "}}\n").unwrap();
writeln!(content, "module.exports = node;").unwrap();
Artifact {
name: node.name.item,
content: sign_file(&content),
hash: hash.to_string(),
}
}
fn get_content_start(config: &Config) -> String {
let mut content = String::new();
writeln!(content, "/**").unwrap();
if !config.header.is_empty() {
for header_line in &config.header {
writeln!(content, " * {}", header_line).unwrap();
}
writeln!(content, " *").unwrap();
}
content
}
fn md5(data: &str) -> String {
let mut md5 = Md5::new();
md5.input(data);
hex::encode(md5.result())
}
Generate $normalization.graphql files
Reviewed By: alunyov
Differential Revision: D20973325
fbshipit-source-id: 66efb4b00f93190f995d1cdd5d01ebe4ec072b88
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use super::apply_transforms::Programs;
use crate::config::{Config, ProjectConfig};
use crate::errors::BuildProjectError;
use graphql_ir::{FragmentDefinition, NamedItem, OperationDefinition};
use graphql_text_printer::{
print_fragment, print_full_operation, write_operation_with_graphqljs_formatting,
};
use graphql_transforms::MATCH_CONSTANTS;
use interner::StringKey;
use md5::{Digest, Md5};
use persist_query::persist;
use relay_codegen::build_request_params;
use signedsource::{sign_file, SIGNING_TOKEN};
use std::fmt::Write;
/// Represents a generated output artifact.
#[derive(Clone)]
pub struct Artifact {
pub name: StringKey,
pub content: String,
pub hash: String,
}
pub async fn generate_artifacts(
config: &Config,
project_config: &ProjectConfig,
programs: &Programs<'_>,
) -> Result<Vec<Artifact>, BuildProjectError> {
let mut artifacts = Vec::new();
for node in programs.normalization.operations() {
if let Some(directive) = node
.directives
.named(MATCH_CONSTANTS.custom_module_directive_name)
{
// Generate normalization file for SplitOperation
let name_arg = directive
.arguments
.named(MATCH_CONSTANTS.derived_from_arg)
.unwrap();
let source_name = name_arg
.value
.item
.get_string_literal()
.expect("Expected `derived_from` argument to be a literal string.");
let source_node = programs
.source
.fragment(source_name)
.expect("Expected the source document for the SplitOperation to exist.");
let source_string = print_fragment(programs.source.schema(), &source_node);
let hash = md5(&source_string);
artifacts.push(generate_split_operation_artifact(
config, programs, node, &hash,
));
} else {
let source_node = programs.source.operation(node.name.item).unwrap();
// TODO: Consider using the std::io::Write trait here to directly
// write to the md5. Currently, this doesn't work as `write_operation`
// expects a `std::fmt::Write`.
// Same for fragment hashing below.
let mut source_string = String::new();
write_operation_with_graphqljs_formatting(
programs.source.schema(),
&source_node,
&mut source_string,
)
.unwrap();
let hash = md5(&source_string);
artifacts.push(
generate_normalization_artifact(config, project_config, programs, node, &hash)
.await?,
);
}
}
for node in programs.reader.fragments() {
let source_node = programs.source.fragment(node.name.item).unwrap();
// Same as for operation hashing above.
let source_string = print_fragment(programs.source.schema(), &source_node);
let hash = md5(&source_string);
artifacts.push(generate_reader_artifact(config, programs, node, &hash));
}
Ok(artifacts)
}
async fn generate_normalization_artifact(
config: &Config,
project_config: &ProjectConfig,
programs: &Programs<'_>,
node: &OperationDefinition,
source_hash: &str,
) -> Result<Artifact, BuildProjectError> {
let name = node.name.item;
let print_operation_node = programs
.operation_text
.operation(name)
.expect("a query text operation should be generated for this operation");
let text = print_full_operation(&programs.operation_text, print_operation_node);
let mut request_parameters = build_request_params(&node);
let mut operation_hash = None;
if let Some(ref persist_config) = project_config.persist {
operation_hash = Some(md5(&text));
let id = persist(&text, &persist_config.url, &persist_config.params)
.await
.map_err(BuildProjectError::PersistError)?;
request_parameters.id = Some(id);
} else {
request_parameters.text = Some(text.clone());
};
let reader_operation = programs
.reader
.operation(name)
.expect("a reader fragment should be generated for this operation");
let operation_fragment = FragmentDefinition {
name: reader_operation.name,
variable_definitions: reader_operation.variable_definitions.clone(),
selections: reader_operation.selections.clone(),
used_global_variables: Default::default(),
directives: reader_operation.directives.clone(),
type_condition: reader_operation.type_,
};
let mut content = get_content_start(config);
writeln!(content, " * {}", SIGNING_TOKEN).unwrap();
if let Some(operation_hash) = operation_hash {
writeln!(content, " * @relayHash {}", operation_hash).unwrap();
}
writeln!(content, " * @flow").unwrap();
writeln!(content, " * @lightSyntaxTransform").unwrap();
writeln!(content, " * @nogrep").unwrap();
if let Some(codegen_command) = &config.codegen_command {
writeln!(content, " * @codegen-command: {}", codegen_command).unwrap();
}
writeln!(content, " */\n").unwrap();
writeln!(content, "/* eslint-disable */\n").unwrap();
writeln!(content, "'use strict';\n").unwrap();
if let Some(id) = &request_parameters.id {
writeln!(content, "// @relayRequestID {}\n", id).unwrap();
}
writeln!(content, "/*::\nTODO flow\n*/\n").unwrap();
writeln!(content, "/*\n{}*/\n", text).unwrap();
writeln!(
content,
"var node/*: ConcreteRequest*/ = {};\n",
relay_codegen::print_request_deduped(
programs.normalization.schema(),
node,
&operation_fragment,
request_parameters
)
)
.unwrap();
writeln!(content, "if (__DEV__) {{").unwrap();
writeln!(content, " (node/*: any*/).hash = \"{}\";", source_hash).unwrap();
writeln!(content, "}}\n").unwrap();
writeln!(content, "module.exports = node;").unwrap();
Ok(Artifact {
name: node.name.item,
content: sign_file(&content),
hash: source_hash.to_string(),
})
}
fn generate_reader_artifact(
config: &Config,
programs: &Programs<'_>,
node: &FragmentDefinition,
hash: &str,
) -> Artifact {
let mut content = get_content_start(config);
writeln!(content, " * {}", SIGNING_TOKEN).unwrap();
writeln!(content, " * @flow").unwrap();
writeln!(content, " * @lightSyntaxTransform").unwrap();
writeln!(content, " * @nogrep").unwrap();
if let Some(codegen_command) = &config.codegen_command {
writeln!(content, " * @codegen-command: {}", codegen_command).unwrap();
}
writeln!(content, " */\n").unwrap();
writeln!(content, "/* eslint-disable */\n").unwrap();
writeln!(content, "'use strict';\n").unwrap();
writeln!(content, "/*::\nTODO flow\n*/\n").unwrap();
writeln!(
content,
"var node/*: ReaderFragment*/ = {};\n",
relay_codegen::print_fragment_deduped(programs.normalization.schema(), node)
)
.unwrap();
writeln!(content, "if (__DEV__) {{").unwrap();
writeln!(content, " (node/*: any*/).hash = \"{}\";", hash).unwrap();
writeln!(content, "}}\n").unwrap();
writeln!(content, "module.exports = node;").unwrap();
Artifact {
name: node.name.item,
content: sign_file(&content),
hash: hash.to_string(),
}
}
fn generate_split_operation_artifact(
config: &Config,
programs: &Programs<'_>,
node: &OperationDefinition,
hash: &str,
) -> Artifact {
let mut content = get_content_start(config);
writeln!(content, " * {}", SIGNING_TOKEN).unwrap();
writeln!(content, " * @flow").unwrap();
writeln!(content, " * @lightSyntaxTransform").unwrap();
writeln!(content, " * @nogrep").unwrap();
if let Some(codegen_command) = &config.codegen_command {
writeln!(content, " * @codegen-command: {}", codegen_command).unwrap();
}
writeln!(content, " */\n").unwrap();
writeln!(content, "/* eslint-disable */\n").unwrap();
writeln!(content, "'use strict';\n").unwrap();
writeln!(
content,
"/*::\nimport type {{ NormalizationSplitOperation }} from 'relay-runtime';\n\n*/\n"
)
.unwrap();
writeln!(
content,
"var node/*: NormalizationSplitOperation*/ = {};\n",
relay_codegen::print_operation_deduped(programs.normalization.schema(), node)
)
.unwrap();
writeln!(content, "if (__DEV__) {{").unwrap();
writeln!(content, " (node/*: any*/).hash = \"{}\";", hash).unwrap();
writeln!(content, "}}\n").unwrap();
writeln!(content, "module.exports = node;").unwrap();
Artifact {
name: node.name.item,
content: sign_file(&content),
hash: hash.to_string(),
}
}
fn get_content_start(config: &Config) -> String {
let mut content = String::new();
writeln!(content, "/**").unwrap();
if !config.header.is_empty() {
for header_line in &config.header {
writeln!(content, " * {}", header_line).unwrap();
}
writeln!(content, " *").unwrap();
}
content
}
fn md5(data: &str) -> String {
let mut md5 = Md5::new();
md5.input(data);
hex::encode(md5.result())
}
|
//! Implements threads.
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::convert::TryFrom;
use std::num::TryFromIntError;
use std::time::{Duration, Instant, SystemTime};
use log::trace;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::DefId;
use rustc_index::vec::{Idx, IndexVec};
use crate::sync::SynchronizationState;
use crate::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SchedulingAction {
/// Execute step on the active thread.
ExecuteStep,
/// Execute a timeout callback.
ExecuteTimeoutCallback,
/// Execute destructors of the active thread.
ExecuteDtors,
/// Stop the program.
Stop,
}
/// Timeout callbacks can be created by synchronization primitives to tell the
/// scheduler that they should be called once some period of time passes.
type TimeoutCallback<'mir, 'tcx> =
Box<dyn FnOnce(&mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>) -> InterpResult<'tcx> + 'tcx>;
/// A thread identifier.
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ThreadId(u32);
/// The main thread. When it terminates, the whole application terminates.
const MAIN_THREAD: ThreadId = ThreadId(0);
impl ThreadId {
pub fn to_u32(self) -> u32 {
self.0
}
}
impl Idx for ThreadId {
fn new(idx: usize) -> Self {
ThreadId(u32::try_from(idx).unwrap())
}
fn index(self) -> usize {
usize::try_from(self.0).unwrap()
}
}
impl TryFrom<u64> for ThreadId {
type Error = TryFromIntError;
fn try_from(id: u64) -> Result<Self, Self::Error> {
u32::try_from(id).map(|id_u32| Self(id_u32))
}
}
impl From<u32> for ThreadId {
fn from(id: u32) -> Self {
Self(id)
}
}
impl ThreadId {
pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
Scalar::from_u32(u32::try_from(self.0).unwrap())
}
}
/// The state of a thread.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ThreadState {
/// The thread is enabled and can be executed.
Enabled,
/// The thread tried to join the specified thread and is blocked until that
/// thread terminates.
BlockedOnJoin(ThreadId),
/// The thread is blocked on some synchronization primitive. It is the
/// responsibility of the synchronization primitives to track threads that
/// are blocked by them.
BlockedOnSync,
/// The thread has terminated its execution. We do not delete terminated
/// threads (FIXME: why?).
Terminated,
}
/// The join status of a thread.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ThreadJoinStatus {
/// The thread can be joined.
Joinable,
/// A thread is detached if its join handle was destroyed and no other
/// thread can join it.
Detached,
/// The thread was already joined by some thread and cannot be joined again.
Joined,
}
/// A thread.
pub struct Thread<'mir, 'tcx> {
state: ThreadState,
/// Name of the thread.
thread_name: Option<Vec<u8>>,
/// The virtual call stack.
stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
/// The join status.
join_status: ThreadJoinStatus,
}
impl<'mir, 'tcx> Thread<'mir, 'tcx> {
/// Check if the thread is done executing (no more stack frames). If yes,
/// change the state to terminated and return `true`.
fn check_terminated(&mut self) -> bool {
if self.state == ThreadState::Enabled {
if self.stack.is_empty() {
self.state = ThreadState::Terminated;
return true;
}
}
false
}
/// Get the name of the current thread, or `<unnamed>` if it was not set.
fn thread_name(&self) -> &[u8] {
if let Some(ref thread_name) = self.thread_name {
thread_name
} else {
b"<unnamed>"
}
}
}
impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}({:?}, {:?})", String::from_utf8_lossy(self.thread_name()), self.state, self.join_status)
}
}
impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
fn default() -> Self {
Self {
state: ThreadState::Enabled,
thread_name: None,
stack: Vec::new(),
join_status: ThreadJoinStatus::Joinable,
}
}
}
/// A specific moment in time.
#[derive(Debug)]
pub enum Time {
Monotonic(Instant),
RealTime(SystemTime),
}
impl Time {
/// How long do we have to wait from now until the specified time?
fn get_wait_time(&self) -> Duration {
match self {
Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
Time::RealTime(time) =>
time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
}
}
}
/// Callbacks are used to implement timeouts. For example, waiting on a
/// conditional variable with a timeout creates a callback that is called after
/// the specified time and unblocks the thread. If another thread signals on the
/// conditional variable, the signal handler deletes the callback.
struct TimeoutCallbackInfo<'mir, 'tcx> {
/// The callback should be called no earlier than this time.
call_time: Time,
/// The called function.
callback: TimeoutCallback<'mir, 'tcx>,
}
impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TimeoutCallback({:?})", self.call_time)
}
}
/// A set of threads.
#[derive(Debug)]
pub struct ThreadManager<'mir, 'tcx> {
/// Identifier of the currently active thread.
active_thread: ThreadId,
/// Threads used in the program.
///
/// Note that this vector also contains terminated threads.
threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
/// This field is pub(crate) because the synchronization primitives
/// (`crate::sync`) need a way to access it.
pub(crate) sync: SynchronizationState,
/// A mapping from a thread-local static to an allocation id of a thread
/// specific allocation.
thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), AllocId>>,
/// A flag that indicates that we should change the active thread.
yield_active_thread: bool,
/// Callbacks that are called once the specified time passes.
timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
}
impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
fn default() -> Self {
let mut threads = IndexVec::new();
// Create the main thread and add it to the list of threads.
let mut main_thread = Thread::default();
// The main thread can *not* be joined on.
main_thread.join_status = ThreadJoinStatus::Detached;
threads.push(main_thread);
Self {
active_thread: ThreadId::new(0),
threads: threads,
sync: SynchronizationState::default(),
thread_local_alloc_ids: Default::default(),
yield_active_thread: false,
timeout_callbacks: FxHashMap::default(),
}
}
}
impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
/// Check if we have an allocation for the given thread local static for the
/// active thread.
fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<AllocId> {
self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
}
/// Set the allocation id as the allocation id of the given thread local
/// static for the active thread.
///
/// Panics if a thread local is initialized twice for the same thread.
fn set_thread_local_alloc_id(&self, def_id: DefId, new_alloc_id: AllocId) {
self.thread_local_alloc_ids
.borrow_mut()
.insert((def_id, self.active_thread), new_alloc_id)
.unwrap_none();
}
/// Borrow the stack of the active thread.
fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
&self.threads[self.active_thread].stack
}
/// Mutably borrow the stack of the active thread.
fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
&mut self.threads[self.active_thread].stack
}
/// Create a new thread and returns its id.
fn create_thread(&mut self) -> ThreadId {
let new_thread_id = ThreadId::new(self.threads.len());
self.threads.push(Default::default());
new_thread_id
}
/// Set an active thread and return the id of the thread that was active before.
fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
let active_thread_id = self.active_thread;
self.active_thread = id;
assert!(self.active_thread.index() < self.threads.len());
active_thread_id
}
/// Get the id of the currently active thread.
fn get_active_thread_id(&self) -> ThreadId {
self.active_thread
}
/// Get the total number of threads that were ever spawn by this program.
fn get_total_thread_count(&self) -> usize {
self.threads.len()
}
/// Has the given thread terminated?
fn has_terminated(&self, thread_id: ThreadId) -> bool {
self.threads[thread_id].state == ThreadState::Terminated
}
/// Enable the thread for execution. The thread must be terminated.
fn enable_thread(&mut self, thread_id: ThreadId) {
assert!(self.has_terminated(thread_id));
self.threads[thread_id].state = ThreadState::Enabled;
}
/// Get a mutable borrow of the currently active thread.
fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
&mut self.threads[self.active_thread]
}
/// Get a shared borrow of the currently active thread.
fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
&self.threads[self.active_thread]
}
/// Mark the thread as detached, which means that no other thread will try
/// to join it and the thread is responsible for cleaning up.
fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
if self.threads[id].join_status != ThreadJoinStatus::Joinable {
throw_ub_format!("trying to detach thread that was already detached or joined");
}
self.threads[id].join_status = ThreadJoinStatus::Detached;
Ok(())
}
/// Mark that the active thread tries to join the thread with `joined_thread_id`.
fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
throw_ub_format!("trying to join a detached or already joined thread");
}
if joined_thread_id == self.active_thread {
throw_ub_format!("trying to join itself");
}
assert!(
self.threads
.iter()
.all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
"a joinable thread already has threads waiting for its termination"
);
// Mark the joined thread as being joined so that we detect if other
// threads try to join it.
self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
if self.threads[joined_thread_id].state != ThreadState::Terminated {
// The joined thread is still running, we need to wait for it.
self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
trace!(
"{:?} blocked on {:?} when trying to join",
self.active_thread,
joined_thread_id
);
}
Ok(())
}
/// Set the name of the active thread.
fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
self.active_thread_mut().thread_name = Some(new_thread_name);
}
/// Get the name of the active thread.
fn get_thread_name(&self) -> &[u8] {
self.active_thread_ref().thread_name()
}
/// Put the thread into the blocked state.
fn block_thread(&mut self, thread: ThreadId) {
let state = &mut self.threads[thread].state;
assert_eq!(*state, ThreadState::Enabled);
*state = ThreadState::BlockedOnSync;
}
/// Put the blocked thread into the enabled state.
fn unblock_thread(&mut self, thread: ThreadId) {
let state = &mut self.threads[thread].state;
assert_eq!(*state, ThreadState::BlockedOnSync);
*state = ThreadState::Enabled;
}
/// Change the active thread to some enabled thread.
fn yield_active_thread(&mut self) {
// We do not yield immediately, as swapping out the current stack while executing a MIR statement
// could lead to all sorts of confusion.
// We should only switch stacks between steps.
self.yield_active_thread = true;
}
/// Register the given `callback` to be called once the `call_time` passes.
///
/// The callback will be called with `thread` being the active thread, and
/// the callback may not change the active thread.
fn register_timeout_callback(
&mut self,
thread: ThreadId,
call_time: Time,
callback: TimeoutCallback<'mir, 'tcx>,
) {
self.timeout_callbacks
.insert(thread, TimeoutCallbackInfo { call_time, callback })
.unwrap_none();
}
/// Unregister the callback for the `thread`.
fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
self.timeout_callbacks.remove(&thread);
}
/// Get a callback that is ready to be called.
fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
// We iterate over all threads in the order of their indices because
// this allows us to have a deterministic scheduler.
for thread in self.threads.indices() {
match self.timeout_callbacks.entry(thread) {
Entry::Occupied(entry) =>
if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
return Some((thread, entry.remove().callback));
},
Entry::Vacant(_) => {}
}
}
None
}
/// Wakes up threads joining on the active one and deallocates thread-local statics.
/// The `AllocId` that can now be freed is returned.
fn thread_terminated(&mut self) -> Vec<AllocId> {
let mut free_tls_statics = Vec::new();
{
let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
if thread != self.active_thread {
// Keep this static around.
return true;
}
// Delete this static from the map and from memory.
// We cannot free directly here as we cannot use `?` in this context.
free_tls_statics.push(alloc_id);
return false;
});
}
// Check if we need to unblock any threads.
for (i, thread) in self.threads.iter_enumerated_mut() {
if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
thread.state = ThreadState::Enabled;
}
}
return free_tls_statics;
}
/// Decide which action to take next and on which thread.
///
/// The currently implemented scheduling policy is the one that is commonly
/// used in stateless model checkers such as Loom: run the active thread as
/// long as we can and switch only when we have to (the active thread was
/// blocked, terminated, or has explicitly asked to be preempted).
fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
// Check whether the thread has **just** terminated (`check_terminated`
// checks whether the thread has popped all its stack and if yes, sets
// the thread state to terminated).
if self.threads[self.active_thread].check_terminated() {
return Ok(SchedulingAction::ExecuteDtors);
}
if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
// The main thread terminated; stop the program.
if self.threads.iter().any(|thread| thread.state != ThreadState::Terminated) {
// FIXME: This check should be either configurable or just emit
// a warning. For example, it seems normal for a program to
// terminate without waiting for its detached threads to
// terminate. However, this case is not trivial to support
// because we also probably do not want to consider the memory
// owned by these threads as leaked.
throw_unsup_format!("the main thread terminated without waiting for other threads");
}
return Ok(SchedulingAction::Stop);
}
// At least for `pthread_cond_timedwait` we need to report timeout when
// the function is called already after the specified time even if a
// signal is received before the thread gets scheduled. Therefore, we
// need to schedule all timeout callbacks before we continue regular
// execution.
//
// Documentation:
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html#
let potential_sleep_time =
self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
if potential_sleep_time == Some(Duration::new(0, 0)) {
return Ok(SchedulingAction::ExecuteTimeoutCallback);
}
// No callbacks scheduled, pick a regular thread to execute.
if self.threads[self.active_thread].state == ThreadState::Enabled
&& !self.yield_active_thread
{
// The currently active thread is still enabled, just continue with it.
return Ok(SchedulingAction::ExecuteStep);
}
// We need to pick a new thread for execution.
for (id, thread) in self.threads.iter_enumerated() {
if thread.state == ThreadState::Enabled {
if !self.yield_active_thread || id != self.active_thread {
self.active_thread = id;
break;
}
}
}
self.yield_active_thread = false;
if self.threads[self.active_thread].state == ThreadState::Enabled {
return Ok(SchedulingAction::ExecuteStep);
}
// We have not found a thread to execute.
if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
unreachable!("all threads terminated without the main thread terminating?!");
} else if let Some(sleep_time) = potential_sleep_time {
// All threads are currently blocked, but we have unexecuted
// timeout_callbacks, which may unblock some of the threads. Hence,
// sleep until the first callback.
std::thread::sleep(sleep_time);
Ok(SchedulingAction::ExecuteTimeoutCallback)
} else {
throw_machine_stop!(TerminationInfo::Deadlock);
}
}
}
// Public interface to thread management.
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
/// Get a thread-specific allocation id for the given thread-local static.
/// If needed, allocate a new one.
fn get_or_create_thread_local_alloc_id(&mut self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
let this = self.eval_context_mut();
let tcx = this.tcx;
if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
// We already have a thread-specific allocation id for this
// thread-local static.
Ok(new_alloc_id)
} else {
// We need to allocate a thread-specific allocation id for this
// thread-local static.
// First, we compute the initial value for this static.
if tcx.is_foreign_item(def_id) {
throw_unsup_format!("foreign thread-local statics are not supported");
}
let allocation = interpret::get_static(*tcx, def_id)?;
// Create a fresh allocation with this content.
let new_alloc_id = this.memory.allocate_with(allocation.clone(), MiriMemoryKind::Tls.into()).alloc_id;
this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
Ok(new_alloc_id)
}
}
#[inline]
fn create_thread(&mut self) -> ThreadId {
let this = self.eval_context_mut();
this.machine.threads.create_thread()
}
#[inline]
fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
this.machine.threads.detach_thread(thread_id)
}
#[inline]
fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
this.machine.threads.join_thread(joined_thread_id)
}
#[inline]
fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
let this = self.eval_context_mut();
this.machine.threads.set_active_thread_id(thread_id)
}
#[inline]
fn get_active_thread(&self) -> ThreadId {
let this = self.eval_context_ref();
this.machine.threads.get_active_thread_id()
}
#[inline]
fn get_total_thread_count(&self) -> usize {
let this = self.eval_context_ref();
this.machine.threads.get_total_thread_count()
}
#[inline]
fn has_terminated(&self, thread_id: ThreadId) -> bool {
let this = self.eval_context_ref();
this.machine.threads.has_terminated(thread_id)
}
#[inline]
fn enable_thread(&mut self, thread_id: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.enable_thread(thread_id);
}
#[inline]
fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
let this = self.eval_context_ref();
this.machine.threads.active_thread_stack()
}
#[inline]
fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
let this = self.eval_context_mut();
this.machine.threads.active_thread_stack_mut()
}
#[inline]
fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
let this = self.eval_context_mut();
this.machine.threads.set_thread_name(new_thread_name);
}
#[inline]
fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
where
'mir: 'c,
{
let this = self.eval_context_ref();
this.machine.threads.get_thread_name()
}
#[inline]
fn block_thread(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.block_thread(thread);
}
#[inline]
fn unblock_thread(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.unblock_thread(thread);
}
#[inline]
fn yield_active_thread(&mut self) {
let this = self.eval_context_mut();
this.machine.threads.yield_active_thread();
}
#[inline]
fn register_timeout_callback(
&mut self,
thread: ThreadId,
call_time: Time,
callback: TimeoutCallback<'mir, 'tcx>,
) {
let this = self.eval_context_mut();
this.machine.threads.register_timeout_callback(thread, call_time, callback);
}
#[inline]
fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.unregister_timeout_callback_if_exists(thread);
}
/// Execute a timeout callback on the callback's thread.
#[inline]
fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
let (thread, callback) =
this.machine.threads.get_ready_callback().expect("no callback found");
// This back-and-forth with `set_active_thread` is here because of two
// design decisions:
// 1. Make the caller and not the callback responsible for changing
// thread.
// 2. Make the scheduler the only place that can change the active
// thread.
let old_thread = this.set_active_thread(thread);
callback(this)?;
this.set_active_thread(old_thread);
Ok(())
}
/// Decide which action to take next and on which thread.
#[inline]
fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
let this = self.eval_context_mut();
this.machine.threads.schedule()
}
/// Handles thread termination of the active thread: wakes up threads joining on this one,
/// and deallocated thread-local statics.
///
/// This is called from `tls.rs` after handling the TLS dtors.
#[inline]
fn thread_terminated(&mut self) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
for alloc_id in this.machine.threads.thread_terminated() {
let ptr = this.memory.global_base_pointer(alloc_id.into())?;
this.memory.deallocate(ptr, None, MiriMemoryKind::Tls.into())?;
}
Ok(())
}
}
Bump for rustc changes
//! Implements threads.
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::convert::TryFrom;
use std::num::TryFromIntError;
use std::time::{Duration, Instant, SystemTime};
use log::trace;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::DefId;
use rustc_index::vec::{Idx, IndexVec};
use crate::sync::SynchronizationState;
use crate::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SchedulingAction {
/// Execute step on the active thread.
ExecuteStep,
/// Execute a timeout callback.
ExecuteTimeoutCallback,
/// Execute destructors of the active thread.
ExecuteDtors,
/// Stop the program.
Stop,
}
/// Timeout callbacks can be created by synchronization primitives to tell the
/// scheduler that they should be called once some period of time passes.
type TimeoutCallback<'mir, 'tcx> =
Box<dyn FnOnce(&mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>) -> InterpResult<'tcx> + 'tcx>;
/// A thread identifier.
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ThreadId(u32);
/// The main thread. When it terminates, the whole application terminates.
const MAIN_THREAD: ThreadId = ThreadId(0);
impl ThreadId {
pub fn to_u32(self) -> u32 {
self.0
}
}
impl Idx for ThreadId {
fn new(idx: usize) -> Self {
ThreadId(u32::try_from(idx).unwrap())
}
fn index(self) -> usize {
usize::try_from(self.0).unwrap()
}
}
impl TryFrom<u64> for ThreadId {
type Error = TryFromIntError;
fn try_from(id: u64) -> Result<Self, Self::Error> {
u32::try_from(id).map(|id_u32| Self(id_u32))
}
}
impl From<u32> for ThreadId {
fn from(id: u32) -> Self {
Self(id)
}
}
impl ThreadId {
pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
Scalar::from_u32(u32::try_from(self.0).unwrap())
}
}
/// The state of a thread.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ThreadState {
/// The thread is enabled and can be executed.
Enabled,
/// The thread tried to join the specified thread and is blocked until that
/// thread terminates.
BlockedOnJoin(ThreadId),
/// The thread is blocked on some synchronization primitive. It is the
/// responsibility of the synchronization primitives to track threads that
/// are blocked by them.
BlockedOnSync,
/// The thread has terminated its execution. We do not delete terminated
/// threads (FIXME: why?).
Terminated,
}
/// The join status of a thread.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ThreadJoinStatus {
/// The thread can be joined.
Joinable,
/// A thread is detached if its join handle was destroyed and no other
/// thread can join it.
Detached,
/// The thread was already joined by some thread and cannot be joined again.
Joined,
}
/// A thread.
pub struct Thread<'mir, 'tcx> {
state: ThreadState,
/// Name of the thread.
thread_name: Option<Vec<u8>>,
/// The virtual call stack.
stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
/// The join status.
join_status: ThreadJoinStatus,
}
impl<'mir, 'tcx> Thread<'mir, 'tcx> {
/// Check if the thread is done executing (no more stack frames). If yes,
/// change the state to terminated and return `true`.
fn check_terminated(&mut self) -> bool {
if self.state == ThreadState::Enabled {
if self.stack.is_empty() {
self.state = ThreadState::Terminated;
return true;
}
}
false
}
/// Get the name of the current thread, or `<unnamed>` if it was not set.
fn thread_name(&self) -> &[u8] {
if let Some(ref thread_name) = self.thread_name {
thread_name
} else {
b"<unnamed>"
}
}
}
impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}({:?}, {:?})", String::from_utf8_lossy(self.thread_name()), self.state, self.join_status)
}
}
impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
fn default() -> Self {
Self {
state: ThreadState::Enabled,
thread_name: None,
stack: Vec::new(),
join_status: ThreadJoinStatus::Joinable,
}
}
}
/// A specific moment in time.
#[derive(Debug)]
pub enum Time {
Monotonic(Instant),
RealTime(SystemTime),
}
impl Time {
/// How long do we have to wait from now until the specified time?
fn get_wait_time(&self) -> Duration {
match self {
Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
Time::RealTime(time) =>
time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
}
}
}
/// Callbacks are used to implement timeouts. For example, waiting on a
/// conditional variable with a timeout creates a callback that is called after
/// the specified time and unblocks the thread. If another thread signals on the
/// conditional variable, the signal handler deletes the callback.
struct TimeoutCallbackInfo<'mir, 'tcx> {
/// The callback should be called no earlier than this time.
call_time: Time,
/// The called function.
callback: TimeoutCallback<'mir, 'tcx>,
}
impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TimeoutCallback({:?})", self.call_time)
}
}
/// A set of threads.
#[derive(Debug)]
pub struct ThreadManager<'mir, 'tcx> {
/// Identifier of the currently active thread.
active_thread: ThreadId,
/// Threads used in the program.
///
/// Note that this vector also contains terminated threads.
threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
/// This field is pub(crate) because the synchronization primitives
/// (`crate::sync`) need a way to access it.
pub(crate) sync: SynchronizationState,
/// A mapping from a thread-local static to an allocation id of a thread
/// specific allocation.
thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), AllocId>>,
/// A flag that indicates that we should change the active thread.
yield_active_thread: bool,
/// Callbacks that are called once the specified time passes.
timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
}
impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
fn default() -> Self {
let mut threads = IndexVec::new();
// Create the main thread and add it to the list of threads.
let mut main_thread = Thread::default();
// The main thread can *not* be joined on.
main_thread.join_status = ThreadJoinStatus::Detached;
threads.push(main_thread);
Self {
active_thread: ThreadId::new(0),
threads: threads,
sync: SynchronizationState::default(),
thread_local_alloc_ids: Default::default(),
yield_active_thread: false,
timeout_callbacks: FxHashMap::default(),
}
}
}
impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
/// Check if we have an allocation for the given thread local static for the
/// active thread.
fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<AllocId> {
self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
}
/// Set the allocation id as the allocation id of the given thread local
/// static for the active thread.
///
/// Panics if a thread local is initialized twice for the same thread.
fn set_thread_local_alloc_id(&self, def_id: DefId, new_alloc_id: AllocId) {
self.thread_local_alloc_ids
.borrow_mut()
.insert((def_id, self.active_thread), new_alloc_id)
.unwrap_none();
}
/// Borrow the stack of the active thread.
fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
&self.threads[self.active_thread].stack
}
/// Mutably borrow the stack of the active thread.
fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
&mut self.threads[self.active_thread].stack
}
/// Create a new thread and returns its id.
fn create_thread(&mut self) -> ThreadId {
let new_thread_id = ThreadId::new(self.threads.len());
self.threads.push(Default::default());
new_thread_id
}
/// Set an active thread and return the id of the thread that was active before.
fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
let active_thread_id = self.active_thread;
self.active_thread = id;
assert!(self.active_thread.index() < self.threads.len());
active_thread_id
}
/// Get the id of the currently active thread.
fn get_active_thread_id(&self) -> ThreadId {
self.active_thread
}
/// Get the total number of threads that were ever spawn by this program.
fn get_total_thread_count(&self) -> usize {
self.threads.len()
}
/// Has the given thread terminated?
fn has_terminated(&self, thread_id: ThreadId) -> bool {
self.threads[thread_id].state == ThreadState::Terminated
}
/// Enable the thread for execution. The thread must be terminated.
fn enable_thread(&mut self, thread_id: ThreadId) {
assert!(self.has_terminated(thread_id));
self.threads[thread_id].state = ThreadState::Enabled;
}
/// Get a mutable borrow of the currently active thread.
fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
&mut self.threads[self.active_thread]
}
/// Get a shared borrow of the currently active thread.
fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
&self.threads[self.active_thread]
}
/// Mark the thread as detached, which means that no other thread will try
/// to join it and the thread is responsible for cleaning up.
fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
if self.threads[id].join_status != ThreadJoinStatus::Joinable {
throw_ub_format!("trying to detach thread that was already detached or joined");
}
self.threads[id].join_status = ThreadJoinStatus::Detached;
Ok(())
}
/// Mark that the active thread tries to join the thread with `joined_thread_id`.
fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
throw_ub_format!("trying to join a detached or already joined thread");
}
if joined_thread_id == self.active_thread {
throw_ub_format!("trying to join itself");
}
assert!(
self.threads
.iter()
.all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
"a joinable thread already has threads waiting for its termination"
);
// Mark the joined thread as being joined so that we detect if other
// threads try to join it.
self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
if self.threads[joined_thread_id].state != ThreadState::Terminated {
// The joined thread is still running, we need to wait for it.
self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
trace!(
"{:?} blocked on {:?} when trying to join",
self.active_thread,
joined_thread_id
);
}
Ok(())
}
/// Set the name of the active thread.
fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
self.active_thread_mut().thread_name = Some(new_thread_name);
}
/// Get the name of the active thread.
fn get_thread_name(&self) -> &[u8] {
self.active_thread_ref().thread_name()
}
/// Put the thread into the blocked state.
fn block_thread(&mut self, thread: ThreadId) {
let state = &mut self.threads[thread].state;
assert_eq!(*state, ThreadState::Enabled);
*state = ThreadState::BlockedOnSync;
}
/// Put the blocked thread into the enabled state.
fn unblock_thread(&mut self, thread: ThreadId) {
let state = &mut self.threads[thread].state;
assert_eq!(*state, ThreadState::BlockedOnSync);
*state = ThreadState::Enabled;
}
/// Change the active thread to some enabled thread.
fn yield_active_thread(&mut self) {
// We do not yield immediately, as swapping out the current stack while executing a MIR statement
// could lead to all sorts of confusion.
// We should only switch stacks between steps.
self.yield_active_thread = true;
}
/// Register the given `callback` to be called once the `call_time` passes.
///
/// The callback will be called with `thread` being the active thread, and
/// the callback may not change the active thread.
fn register_timeout_callback(
&mut self,
thread: ThreadId,
call_time: Time,
callback: TimeoutCallback<'mir, 'tcx>,
) {
self.timeout_callbacks
.insert(thread, TimeoutCallbackInfo { call_time, callback })
.unwrap_none();
}
/// Unregister the callback for the `thread`.
fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
self.timeout_callbacks.remove(&thread);
}
/// Get a callback that is ready to be called.
fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
// We iterate over all threads in the order of their indices because
// this allows us to have a deterministic scheduler.
for thread in self.threads.indices() {
match self.timeout_callbacks.entry(thread) {
Entry::Occupied(entry) =>
if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
return Some((thread, entry.remove().callback));
},
Entry::Vacant(_) => {}
}
}
None
}
/// Wakes up threads joining on the active one and deallocates thread-local statics.
/// The `AllocId` that can now be freed is returned.
fn thread_terminated(&mut self) -> Vec<AllocId> {
let mut free_tls_statics = Vec::new();
{
let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
if thread != self.active_thread {
// Keep this static around.
return true;
}
// Delete this static from the map and from memory.
// We cannot free directly here as we cannot use `?` in this context.
free_tls_statics.push(alloc_id);
return false;
});
}
// Check if we need to unblock any threads.
for (i, thread) in self.threads.iter_enumerated_mut() {
if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
thread.state = ThreadState::Enabled;
}
}
return free_tls_statics;
}
/// Decide which action to take next and on which thread.
///
/// The currently implemented scheduling policy is the one that is commonly
/// used in stateless model checkers such as Loom: run the active thread as
/// long as we can and switch only when we have to (the active thread was
/// blocked, terminated, or has explicitly asked to be preempted).
fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
// Check whether the thread has **just** terminated (`check_terminated`
// checks whether the thread has popped all its stack and if yes, sets
// the thread state to terminated).
if self.threads[self.active_thread].check_terminated() {
return Ok(SchedulingAction::ExecuteDtors);
}
if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
// The main thread terminated; stop the program.
if self.threads.iter().any(|thread| thread.state != ThreadState::Terminated) {
// FIXME: This check should be either configurable or just emit
// a warning. For example, it seems normal for a program to
// terminate without waiting for its detached threads to
// terminate. However, this case is not trivial to support
// because we also probably do not want to consider the memory
// owned by these threads as leaked.
throw_unsup_format!("the main thread terminated without waiting for other threads");
}
return Ok(SchedulingAction::Stop);
}
// At least for `pthread_cond_timedwait` we need to report timeout when
// the function is called already after the specified time even if a
// signal is received before the thread gets scheduled. Therefore, we
// need to schedule all timeout callbacks before we continue regular
// execution.
//
// Documentation:
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html#
let potential_sleep_time =
self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
if potential_sleep_time == Some(Duration::new(0, 0)) {
return Ok(SchedulingAction::ExecuteTimeoutCallback);
}
// No callbacks scheduled, pick a regular thread to execute.
if self.threads[self.active_thread].state == ThreadState::Enabled
&& !self.yield_active_thread
{
// The currently active thread is still enabled, just continue with it.
return Ok(SchedulingAction::ExecuteStep);
}
// We need to pick a new thread for execution.
for (id, thread) in self.threads.iter_enumerated() {
if thread.state == ThreadState::Enabled {
if !self.yield_active_thread || id != self.active_thread {
self.active_thread = id;
break;
}
}
}
self.yield_active_thread = false;
if self.threads[self.active_thread].state == ThreadState::Enabled {
return Ok(SchedulingAction::ExecuteStep);
}
// We have not found a thread to execute.
if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
unreachable!("all threads terminated without the main thread terminating?!");
} else if let Some(sleep_time) = potential_sleep_time {
// All threads are currently blocked, but we have unexecuted
// timeout_callbacks, which may unblock some of the threads. Hence,
// sleep until the first callback.
std::thread::sleep(sleep_time);
Ok(SchedulingAction::ExecuteTimeoutCallback)
} else {
throw_machine_stop!(TerminationInfo::Deadlock);
}
}
}
// Public interface to thread management.
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
/// Get a thread-specific allocation id for the given thread-local static.
/// If needed, allocate a new one.
fn get_or_create_thread_local_alloc_id(&mut self, def_id: DefId) -> InterpResult<'tcx, AllocId> {
let this = self.eval_context_mut();
let tcx = this.tcx;
if let Some(new_alloc_id) = this.machine.threads.get_thread_local_alloc_id(def_id) {
// We already have a thread-specific allocation id for this
// thread-local static.
Ok(new_alloc_id)
} else {
// We need to allocate a thread-specific allocation id for this
// thread-local static.
// First, we compute the initial value for this static.
if tcx.is_foreign_item(def_id) {
throw_unsup_format!("foreign thread-local statics are not supported");
}
let allocation = tcx.eval_static_initializer(def_id)?;
// Create a fresh allocation with this content.
let new_alloc_id = this.memory.allocate_with(allocation.clone(), MiriMemoryKind::Tls.into()).alloc_id;
this.machine.threads.set_thread_local_alloc_id(def_id, new_alloc_id);
Ok(new_alloc_id)
}
}
#[inline]
fn create_thread(&mut self) -> ThreadId {
let this = self.eval_context_mut();
this.machine.threads.create_thread()
}
#[inline]
fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
this.machine.threads.detach_thread(thread_id)
}
#[inline]
fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
this.machine.threads.join_thread(joined_thread_id)
}
#[inline]
fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
let this = self.eval_context_mut();
this.machine.threads.set_active_thread_id(thread_id)
}
#[inline]
fn get_active_thread(&self) -> ThreadId {
let this = self.eval_context_ref();
this.machine.threads.get_active_thread_id()
}
#[inline]
fn get_total_thread_count(&self) -> usize {
let this = self.eval_context_ref();
this.machine.threads.get_total_thread_count()
}
#[inline]
fn has_terminated(&self, thread_id: ThreadId) -> bool {
let this = self.eval_context_ref();
this.machine.threads.has_terminated(thread_id)
}
#[inline]
fn enable_thread(&mut self, thread_id: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.enable_thread(thread_id);
}
#[inline]
fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
let this = self.eval_context_ref();
this.machine.threads.active_thread_stack()
}
#[inline]
fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
let this = self.eval_context_mut();
this.machine.threads.active_thread_stack_mut()
}
#[inline]
fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
let this = self.eval_context_mut();
this.machine.threads.set_thread_name(new_thread_name);
}
#[inline]
fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
where
'mir: 'c,
{
let this = self.eval_context_ref();
this.machine.threads.get_thread_name()
}
#[inline]
fn block_thread(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.block_thread(thread);
}
#[inline]
fn unblock_thread(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.unblock_thread(thread);
}
#[inline]
fn yield_active_thread(&mut self) {
let this = self.eval_context_mut();
this.machine.threads.yield_active_thread();
}
#[inline]
fn register_timeout_callback(
&mut self,
thread: ThreadId,
call_time: Time,
callback: TimeoutCallback<'mir, 'tcx>,
) {
let this = self.eval_context_mut();
this.machine.threads.register_timeout_callback(thread, call_time, callback);
}
#[inline]
fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
let this = self.eval_context_mut();
this.machine.threads.unregister_timeout_callback_if_exists(thread);
}
/// Execute a timeout callback on the callback's thread.
#[inline]
fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
let (thread, callback) =
this.machine.threads.get_ready_callback().expect("no callback found");
// This back-and-forth with `set_active_thread` is here because of two
// design decisions:
// 1. Make the caller and not the callback responsible for changing
// thread.
// 2. Make the scheduler the only place that can change the active
// thread.
let old_thread = this.set_active_thread(thread);
callback(this)?;
this.set_active_thread(old_thread);
Ok(())
}
/// Decide which action to take next and on which thread.
#[inline]
fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
let this = self.eval_context_mut();
this.machine.threads.schedule()
}
/// Handles thread termination of the active thread: wakes up threads joining on this one,
/// and deallocated thread-local statics.
///
/// This is called from `tls.rs` after handling the TLS dtors.
#[inline]
fn thread_terminated(&mut self) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
for alloc_id in this.machine.threads.thread_terminated() {
let ptr = this.memory.global_base_pointer(alloc_id.into())?;
this.memory.deallocate(ptr, None, MiriMemoryKind::Tls.into())?;
}
Ok(())
}
}
|
//! Traits input types have to implement to work with nom combinators
use crate::error::{ErrorKind, ParseError};
use crate::internal::{Err, IResult, Needed};
use crate::lib::std::iter::{Copied, Enumerate};
use crate::lib::std::ops::{Range, RangeFrom, RangeFull, RangeTo};
use crate::lib::std::slice::Iter;
use crate::lib::std::str::from_utf8;
use crate::lib::std::str::CharIndices;
use crate::lib::std::str::Chars;
use crate::lib::std::str::FromStr;
#[cfg(feature = "alloc")]
use crate::lib::std::string::String;
#[cfg(feature = "alloc")]
use crate::lib::std::vec::Vec;
/// Abstract method to calculate the input length
pub trait InputLength {
/// Calculates the input length, as indicated by its name,
/// and the name of the trait itself
fn input_len(&self) -> usize;
}
impl<'a, T> InputLength for &'a [T] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for &'a str {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for (&'a [u8], usize) {
#[inline]
fn input_len(&self) -> usize {
//println!("bit input length for ({:?}, {}):", self.0, self.1);
//println!("-> {}", self.0.len() * 8 - self.1);
self.0.len() * 8 - self.1
}
}
/// Useful functions to calculate the offset between slices and show a hexdump of a slice
pub trait Offset {
/// Offset between the first byte of self and the first byte of the argument
fn offset(&self, second: &Self) -> usize;
}
impl Offset for [u8] {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl<'a> Offset for &'a [u8] {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl Offset for str {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl<'a> Offset for &'a str {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
/// Helper trait for types that can be viewed as a byte slice
pub trait AsBytes {
/// Casts the input type to a byte slice
fn as_bytes(&self) -> &[u8];
}
impl<'a> AsBytes for &'a str {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
(*self).as_bytes()
}
}
impl AsBytes for str {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self.as_ref()
}
}
impl<'a> AsBytes for &'a [u8] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
*self
}
}
impl AsBytes for [u8] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self
}
}
macro_rules! as_bytes_array_impls {
($($N:expr)+) => {
$(
impl<'a> AsBytes for &'a [u8; $N] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
*self
}
}
impl AsBytes for [u8; $N] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self
}
}
)+
};
}
as_bytes_array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
/// Transforms common types to a char for basic token parsing
pub trait AsChar {
/// makes a char from self
fn as_char(self) -> char;
/// Tests that self is an alphabetic character
///
/// Warning: for `&str` it recognizes alphabetic
/// characters outside of the 52 ASCII letters
fn is_alpha(self) -> bool;
/// Tests that self is an alphabetic character
/// or a decimal digit
fn is_alphanum(self) -> bool;
/// Tests that self is a decimal digit
fn is_dec_digit(self) -> bool;
/// Tests that self is an hex digit
fn is_hex_digit(self) -> bool;
/// Tests that self is an octal digit
fn is_oct_digit(self) -> bool;
/// Gets the len in bytes for self
fn len(self) -> usize;
}
impl AsChar for u8 {
#[inline]
fn as_char(self) -> char {
self as char
}
#[inline]
fn is_alpha(self) -> bool {
(self >= 0x41 && self <= 0x5A) || (self >= 0x61 && self <= 0x7A)
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self >= 0x30 && self <= 0x39
}
#[inline]
fn is_hex_digit(self) -> bool {
(self >= 0x30 && self <= 0x39)
|| (self >= 0x41 && self <= 0x46)
|| (self >= 0x61 && self <= 0x66)
}
#[inline]
fn is_oct_digit(self) -> bool {
self >= 0x30 && self <= 0x37
}
#[inline]
fn len(self) -> usize {
1
}
}
impl<'a> AsChar for &'a u8 {
#[inline]
fn as_char(self) -> char {
*self as char
}
#[inline]
fn is_alpha(self) -> bool {
(*self >= 0x41 && *self <= 0x5A) || (*self >= 0x61 && *self <= 0x7A)
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
*self >= 0x30 && *self <= 0x39
}
#[inline]
fn is_hex_digit(self) -> bool {
(*self >= 0x30 && *self <= 0x39)
|| (*self >= 0x41 && *self <= 0x46)
|| (*self >= 0x61 && *self <= 0x66)
}
#[inline]
fn is_oct_digit(self) -> bool {
*self >= 0x30 && *self <= 0x37
}
#[inline]
fn len(self) -> usize {
1
}
}
impl AsChar for char {
#[inline]
fn as_char(self) -> char {
self
}
#[inline]
fn is_alpha(self) -> bool {
self.is_ascii_alphabetic()
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self.is_ascii_digit()
}
#[inline]
fn is_hex_digit(self) -> bool {
self.is_ascii_hexdigit()
}
#[inline]
fn is_oct_digit(self) -> bool {
self.is_digit(8)
}
#[inline]
fn len(self) -> usize {
self.len_utf8()
}
}
impl<'a> AsChar for &'a char {
#[inline]
fn as_char(self) -> char {
*self
}
#[inline]
fn is_alpha(self) -> bool {
self.is_ascii_alphabetic()
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self.is_ascii_digit()
}
#[inline]
fn is_hex_digit(self) -> bool {
self.is_ascii_hexdigit()
}
#[inline]
fn is_oct_digit(self) -> bool {
self.is_digit(8)
}
#[inline]
fn len(self) -> usize {
self.len_utf8()
}
}
/// Abstracts common iteration operations on the input type
pub trait InputIter {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// An iterator over the input type, producing the item and its position
/// for use with [Slice]. If we're iterating over `&str`, the position
/// corresponds to the byte index of the character
type Iter: Iterator<Item = (usize, Self::Item)>;
/// An iterator over the input type, producing the item
type IterElem: Iterator<Item = Self::Item>;
/// Returns an iterator over the elements and their byte offsets
fn iter_indices(&self) -> Self::Iter;
/// Returns an iterator over the elements
fn iter_elements(&self) -> Self::IterElem;
/// Finds the byte position of the element
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool;
/// Get the byte offset from the element's position in the stream
fn slice_index(&self, count: usize) -> Result<usize, Needed>;
}
/// Abstracts slicing operations
pub trait InputTake: Sized {
/// Returns a slice of `count` bytes. panics if count > length
fn take(&self, count: usize) -> Self;
/// Split the stream at the `count` byte offset. panics if count > length
fn take_split(&self, count: usize) -> (Self, Self);
}
impl<'a> InputIter for &'a [u8] {
type Item = u8;
type Iter = Enumerate<Self::IterElem>;
type IterElem = Copied<Iter<'a, u8>>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.iter_elements().enumerate()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.iter().copied()
}
#[inline]
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool,
{
self.iter().position(|b| predicate(*b))
}
#[inline]
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
if self.len() >= count {
Ok(count)
} else {
Err(Needed::new(count - self.len()))
}
}
}
impl<'a> InputTake for &'a [u8] {
#[inline]
fn take(&self, count: usize) -> Self {
&self[0..count]
}
#[inline]
fn take_split(&self, count: usize) -> (Self, Self) {
let (prefix, suffix) = self.split_at(count);
(suffix, prefix)
}
}
impl<'a> InputIter for &'a str {
type Item = char;
type Iter = CharIndices<'a>;
type IterElem = Chars<'a>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.char_indices()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.chars()
}
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool,
{
for (o, c) in self.char_indices() {
if predicate(c) {
return Some(o);
}
}
None
}
#[inline]
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
let mut cnt = 0;
for (index, _) in self.char_indices() {
if cnt == count {
return Ok(index);
}
cnt += 1;
}
if cnt == count {
return Ok(self.len());
}
Err(Needed::Unknown)
}
}
impl<'a> InputTake for &'a str {
#[inline]
fn take(&self, count: usize) -> Self {
&self[..count]
}
// return byte index
#[inline]
fn take_split(&self, count: usize) -> (Self, Self) {
let (prefix, suffix) = self.split_at(count);
(suffix, prefix)
}
}
/// Dummy trait used for default implementations (currently only used for `InputTakeAtPosition` and `Compare`).
///
/// When implementing a custom input type, it is possible to use directly the
/// default implementation: If the input type implements `InputLength`, `InputIter`,
/// `InputTake` and `Clone`, you can implement `UnspecializedInput` and get
/// a default version of `InputTakeAtPosition` and `Compare`.
///
/// For performance reasons, you might want to write a custom implementation of
/// `InputTakeAtPosition` (like the one for `&[u8]`).
pub trait UnspecializedInput {}
/// Methods to take as much input as possible until the provided function returns true for the current element.
///
/// A large part of nom's basic parsers are built using this trait.
pub trait InputTakeAtPosition: Sized {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// Looks for the first element of the input type for which the condition returns true,
/// and returns the input up to this position.
///
/// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true
/// and returns the input up to this position.
///
/// Fails if the produced slice is empty.
///
/// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true,
/// and returns the input up to this position.
///
/// *complete version*: If no element is found matching the condition, this will return the whole input
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true
/// and returns the input up to this position.
///
/// Fails if the produced slice is empty.
///
/// *complete version*: If no element is found matching the condition, this will return the whole input
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
}
impl<T: InputLength + InputIter + InputTake + Clone + UnspecializedInput> InputTakeAtPosition
for T
{
type Item = <T as InputIter>::Item;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.position(predicate) {
Some(n) => Ok(self.take_split(n)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.position(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(n) => Ok(self.take_split(n)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.split_at_position(predicate) {
Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())),
res => res,
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.split_at_position1(predicate, e) {
Err(Err::Incomplete(_)) => {
if self.input_len() == 0 {
Err(Err::Error(E::from_error_kind(self.clone(), e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
res => res,
}
}
}
impl<'a> InputTakeAtPosition for &'a [u8] {
type Item = u8;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(i) => Ok(self.take_split(i)),
None => Ok(self.take_split(self.input_len())),
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => {
if self.is_empty() {
Err(Err::Error(E::from_error_kind(self, e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
}
}
}
impl<'a> InputTakeAtPosition for &'a str {
type Item = char;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(i) => Ok(self.take_split(i)),
None => Ok(self.take_split(self.input_len())),
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => {
if self.is_empty() {
Err(Err::Error(E::from_error_kind(self, e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
}
}
}
/// Indicates wether a comparison was successful, an error, or
/// if more data was needed
#[derive(Debug, PartialEq)]
pub enum CompareResult {
/// Comparison was successful
Ok,
/// We need more data to be sure
Incomplete,
/// Comparison failed
Error,
}
/// Abstracts comparison operations
pub trait Compare<T> {
/// Compares self to another value for equality
fn compare(&self, t: T) -> CompareResult;
/// Compares self to another value for equality
/// independently of the case.
///
/// Warning: for `&str`, the comparison is done
/// by lowercasing both strings and comparing
/// the result. This is a temporary solution until
/// a better one appears
fn compare_no_case(&self, t: T) -> CompareResult;
}
fn lowercase_byte(c: u8) -> u8 {
match c {
b'A'..=b'Z' => c - b'A' + b'a',
_ => c,
}
}
impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b [u8]) -> CompareResult {
let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);
match pos {
Some(_) => CompareResult::Error,
None => {
if self.len() >= t.len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
/*
let len = self.len();
let blen = t.len();
let m = if len < blen { len } else { blen };
let reduced = &self[..m];
let b = &t[..m];
if reduced != b {
CompareResult::Error
} else if m < blen {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
*/
}
#[inline(always)]
fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
if self
.iter()
.zip(t)
.any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))
{
CompareResult::Error
} else if self.len() < t.len() {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
}
}
impl<
T: InputLength + InputIter<Item = u8> + InputTake + UnspecializedInput,
O: InputLength + InputIter<Item = u8> + InputTake,
> Compare<O> for T
{
#[inline(always)]
fn compare(&self, t: O) -> CompareResult {
let pos = self
.iter_elements()
.zip(t.iter_elements())
.position(|(a, b)| a != b);
match pos {
Some(_) => CompareResult::Error,
None => {
if self.input_len() >= t.input_len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
}
#[inline(always)]
fn compare_no_case(&self, t: O) -> CompareResult {
if self
.iter_elements()
.zip(t.iter_elements())
.any(|(a, b)| lowercase_byte(a) != lowercase_byte(b))
{
CompareResult::Error
} else if self.input_len() < t.input_len() {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
}
}
impl<'a, 'b> Compare<&'b str> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b str) -> CompareResult {
self.compare(AsBytes::as_bytes(t))
}
#[inline(always)]
fn compare_no_case(&self, t: &'b str) -> CompareResult {
self.compare_no_case(AsBytes::as_bytes(t))
}
}
impl<'a, 'b> Compare<&'b str> for &'a str {
#[inline(always)]
fn compare(&self, t: &'b str) -> CompareResult {
self.as_bytes().compare(t.as_bytes())
}
//FIXME: this version is too simple and does not use the current locale
#[inline(always)]
fn compare_no_case(&self, t: &'b str) -> CompareResult {
let pos = self
.chars()
.zip(t.chars())
.position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));
match pos {
Some(_) => CompareResult::Error,
None => {
if self.len() >= t.len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
}
}
/// Look for a token in self
pub trait FindToken<T> {
/// Returns true if self contains the token
fn find_token(&self, token: T) -> bool;
}
impl<'a> FindToken<u8> for &'a [u8] {
fn find_token(&self, token: u8) -> bool {
memchr::memchr(token, self).is_some()
}
}
impl<'a> FindToken<u8> for &'a str {
fn find_token(&self, token: u8) -> bool {
self.as_bytes().find_token(token)
}
}
impl<'a, 'b> FindToken<&'a u8> for &'b [u8] {
fn find_token(&self, token: &u8) -> bool {
self.find_token(*token)
}
}
impl<'a, 'b> FindToken<&'a u8> for &'b str {
fn find_token(&self, token: &u8) -> bool {
self.as_bytes().find_token(token)
}
}
impl<'a> FindToken<char> for &'a [u8] {
fn find_token(&self, token: char) -> bool {
self.iter().any(|i| *i == token as u8)
}
}
impl<'a> FindToken<char> for &'a str {
fn find_token(&self, token: char) -> bool {
self.chars().any(|i| i == token)
}
}
/// Look for a substring in self
pub trait FindSubstring<T> {
/// Returns the byte position of the substring if it is found
fn find_substring(&self, substr: T) -> Option<usize>;
}
impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
if substr.len() > self.len() {
return None;
}
let (&substr_first, substr_rest) = match substr.split_first() {
Some(split) => split,
// an empty substring is found at position 0
// This matches the behavior of str.find("").
None => return Some(0),
};
if substr_rest.is_empty() {
return memchr::memchr(substr_first, self);
}
let mut offset = 0;
let haystack = &self[..self.len() - substr_rest.len()];
while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
offset += position;
let next_offset = offset + 1;
if &self[next_offset..][..substr_rest.len()] == substr_rest {
return Some(offset);
}
offset = next_offset;
}
None
}
}
impl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {
fn find_substring(&self, substr: &'b str) -> Option<usize> {
self.find_substring(AsBytes::as_bytes(substr))
}
}
impl<'a, 'b> FindSubstring<&'b str> for &'a str {
//returns byte index
fn find_substring(&self, substr: &'b str) -> Option<usize> {
self.find(substr)
}
}
/// Used to integrate `str`'s `parse()` method
pub trait ParseTo<R> {
/// Succeeds if `parse()` succeeded. The byte slice implementation
/// will first convert it to a `&str`, then apply the `parse()` function
fn parse_to(&self) -> Option<R>;
}
impl<'a, R: FromStr> ParseTo<R> for &'a [u8] {
fn parse_to(&self) -> Option<R> {
from_utf8(self).ok().and_then(|s| s.parse().ok())
}
}
impl<'a, R: FromStr> ParseTo<R> for &'a str {
fn parse_to(&self) -> Option<R> {
self.parse().ok()
}
}
/// Slicing operations using ranges.
///
/// This trait is loosely based on
/// `Index`, but can actually return
/// something else than a `&[T]` or `&str`
pub trait Slice<R> {
/// Slices self according to the range argument
fn slice(&self, range: R) -> Self;
}
macro_rules! impl_fn_slice {
( $ty:ty ) => {
fn slice(&self, range: $ty) -> Self {
&self[range]
}
};
}
macro_rules! slice_range_impl {
( BitSlice, $ty:ty ) => {
impl<'a, O, T> Slice<$ty> for &'a BitSlice<O, T>
where
O: BitOrder,
T: BitStore,
{
impl_fn_slice!($ty);
}
};
( [ $for_type:ident ], $ty:ty ) => {
impl<'a, $for_type> Slice<$ty> for &'a [$for_type] {
impl_fn_slice!($ty);
}
};
( $for_type:ty, $ty:ty ) => {
impl<'a> Slice<$ty> for &'a $for_type {
impl_fn_slice!($ty);
}
};
}
macro_rules! slice_ranges_impl {
( BitSlice ) => {
slice_range_impl! {BitSlice, Range<usize>}
slice_range_impl! {BitSlice, RangeTo<usize>}
slice_range_impl! {BitSlice, RangeFrom<usize>}
slice_range_impl! {BitSlice, RangeFull}
};
( [ $for_type:ident ] ) => {
slice_range_impl! {[$for_type], Range<usize>}
slice_range_impl! {[$for_type], RangeTo<usize>}
slice_range_impl! {[$for_type], RangeFrom<usize>}
slice_range_impl! {[$for_type], RangeFull}
};
( $for_type:ty ) => {
slice_range_impl! {$for_type, Range<usize>}
slice_range_impl! {$for_type, RangeTo<usize>}
slice_range_impl! {$for_type, RangeFrom<usize>}
slice_range_impl! {$for_type, RangeFull}
};
}
slice_ranges_impl! {str}
slice_ranges_impl! {[T]}
macro_rules! array_impls {
($($N:expr)+) => {
$(
impl InputLength for [u8; $N] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for &'a [u8; $N] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputIter for &'a [u8; $N] {
type Item = u8;
type Iter = Enumerate<Self::IterElem>;
type IterElem = Copied<Iter<'a, u8>>;
fn iter_indices(&self) -> Self::Iter {
(&self[..]).iter_indices()
}
fn iter_elements(&self) -> Self::IterElem {
(&self[..]).iter_elements()
}
fn position<P>(&self, predicate: P) -> Option<usize>
where P: Fn(Self::Item) -> bool {
(&self[..]).position(predicate)
}
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
(&self[..]).slice_index(count)
}
}
impl<'a> Compare<[u8; $N]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: [u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: [u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl<'a,'b> Compare<&'b [u8; $N]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b [u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: &'b [u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl FindToken<u8> for [u8; $N] {
fn find_token(&self, token: u8) -> bool {
memchr::memchr(token, &self[..]).is_some()
}
}
impl<'a> FindToken<&'a u8> for [u8; $N] {
fn find_token(&self, token: &u8) -> bool {
self.find_token(*token)
}
}
)+
};
}
array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
/// Abstracts something which can extend an `Extend`.
/// Used to build modified input slices in `escaped_transform`
pub trait ExtendInto {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// The type that will be produced
type Extender;
/// Create a new `Extend` of the correct type
fn new_builder(&self) -> Self::Extender;
/// Accumulate the input into an accumulator
fn extend_into(&self, acc: &mut Self::Extender);
}
#[cfg(feature = "alloc")]
impl ExtendInto for [u8] {
type Item = u8;
type Extender = Vec<u8>;
#[inline]
fn new_builder(&self) -> Vec<u8> {
Vec::new()
}
#[inline]
fn extend_into(&self, acc: &mut Vec<u8>) {
acc.extend(self.iter().cloned());
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for &[u8] {
type Item = u8;
type Extender = Vec<u8>;
#[inline]
fn new_builder(&self) -> Vec<u8> {
Vec::new()
}
#[inline]
fn extend_into(&self, acc: &mut Vec<u8>) {
acc.extend_from_slice(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for str {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push_str(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for &str {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push_str(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for char {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push(*self);
}
}
/// Helper trait to convert numbers to usize.
///
/// By default, usize implements `From<u8>` and `From<u16>` but not
/// `From<u32>` and `From<u64>` because that would be invalid on some
/// platforms. This trait implements the conversion for platforms
/// with 32 and 64 bits pointer platforms
pub trait ToUsize {
/// converts self to usize
fn to_usize(&self) -> usize;
}
impl ToUsize for u8 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
impl ToUsize for u16 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
impl ToUsize for usize {
#[inline]
fn to_usize(&self) -> usize {
*self
}
}
#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
impl ToUsize for u32 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
#[cfg(target_pointer_width = "64")]
impl ToUsize for u64 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
/// Equivalent From implementation to avoid orphan rules in bits parsers
pub trait ErrorConvert<E> {
/// Transform to another error type
fn convert(self) -> E;
}
impl<I> ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {
fn convert(self) -> (I, ErrorKind) {
((self.0).0, self.1)
}
}
impl<I> ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {
fn convert(self) -> ((I, usize), ErrorKind) {
((self.0, 0), self.1)
}
}
use crate::error;
impl<I> ErrorConvert<error::Error<I>> for error::Error<(I, usize)> {
fn convert(self) -> error::Error<I> {
error::Error {
input: self.input.0,
code: self.code,
}
}
}
impl<I> ErrorConvert<error::Error<(I, usize)>> for error::Error<I> {
fn convert(self) -> error::Error<(I, usize)> {
error::Error {
input: (self.input, 0),
code: self.code,
}
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
impl<I> ErrorConvert<error::VerboseError<I>> for error::VerboseError<(I, usize)> {
fn convert(self) -> error::VerboseError<I> {
error::VerboseError {
errors: self.errors.into_iter().map(|(i, e)| (i.0, e)).collect(),
}
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
impl<I> ErrorConvert<error::VerboseError<(I, usize)>> for error::VerboseError<I> {
fn convert(self) -> error::VerboseError<(I, usize)> {
error::VerboseError {
errors: self.errors.into_iter().map(|(i, e)| ((i, 0), e)).collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_offset_u8() {
let s = b"abcd123";
let a = &s[..];
let b = &a[2..];
let c = &a[..4];
let d = &a[3..5];
assert_eq!(a.offset(b), 2);
assert_eq!(a.offset(c), 0);
assert_eq!(a.offset(d), 3);
}
#[test]
fn test_offset_str() {
let s = "abcřèÂßÇd123";
let a = &s[..];
let b = &a[7..];
let c = &a[..5];
let d = &a[5..9];
assert_eq!(a.offset(b), 7);
assert_eq!(a.offset(c), 0);
assert_eq!(a.offset(d), 5);
}
}
avoid a check to is_char_boundary in split_at_position* for &str
the call to find() returns an index in the slice that is already at a
char boundary, so the check done by split_at is not needed. The
get_unhecked call is needed instead of self.get() to prevent the
reintroduction of bound checks
//! Traits input types have to implement to work with nom combinators
use crate::error::{ErrorKind, ParseError};
use crate::internal::{Err, IResult, Needed};
use crate::lib::std::iter::{Copied, Enumerate};
use crate::lib::std::ops::{Range, RangeFrom, RangeFull, RangeTo};
use crate::lib::std::slice::Iter;
use crate::lib::std::str::from_utf8;
use crate::lib::std::str::CharIndices;
use crate::lib::std::str::Chars;
use crate::lib::std::str::FromStr;
#[cfg(feature = "alloc")]
use crate::lib::std::string::String;
#[cfg(feature = "alloc")]
use crate::lib::std::vec::Vec;
/// Abstract method to calculate the input length
pub trait InputLength {
/// Calculates the input length, as indicated by its name,
/// and the name of the trait itself
fn input_len(&self) -> usize;
}
impl<'a, T> InputLength for &'a [T] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for &'a str {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for (&'a [u8], usize) {
#[inline]
fn input_len(&self) -> usize {
//println!("bit input length for ({:?}, {}):", self.0, self.1);
//println!("-> {}", self.0.len() * 8 - self.1);
self.0.len() * 8 - self.1
}
}
/// Useful functions to calculate the offset between slices and show a hexdump of a slice
pub trait Offset {
/// Offset between the first byte of self and the first byte of the argument
fn offset(&self, second: &Self) -> usize;
}
impl Offset for [u8] {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl<'a> Offset for &'a [u8] {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl Offset for str {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
impl<'a> Offset for &'a str {
fn offset(&self, second: &Self) -> usize {
let fst = self.as_ptr();
let snd = second.as_ptr();
snd as usize - fst as usize
}
}
/// Helper trait for types that can be viewed as a byte slice
pub trait AsBytes {
/// Casts the input type to a byte slice
fn as_bytes(&self) -> &[u8];
}
impl<'a> AsBytes for &'a str {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
(*self).as_bytes()
}
}
impl AsBytes for str {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self.as_ref()
}
}
impl<'a> AsBytes for &'a [u8] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
*self
}
}
impl AsBytes for [u8] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self
}
}
macro_rules! as_bytes_array_impls {
($($N:expr)+) => {
$(
impl<'a> AsBytes for &'a [u8; $N] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
*self
}
}
impl AsBytes for [u8; $N] {
#[inline(always)]
fn as_bytes(&self) -> &[u8] {
self
}
}
)+
};
}
as_bytes_array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
/// Transforms common types to a char for basic token parsing
pub trait AsChar {
/// makes a char from self
fn as_char(self) -> char;
/// Tests that self is an alphabetic character
///
/// Warning: for `&str` it recognizes alphabetic
/// characters outside of the 52 ASCII letters
fn is_alpha(self) -> bool;
/// Tests that self is an alphabetic character
/// or a decimal digit
fn is_alphanum(self) -> bool;
/// Tests that self is a decimal digit
fn is_dec_digit(self) -> bool;
/// Tests that self is an hex digit
fn is_hex_digit(self) -> bool;
/// Tests that self is an octal digit
fn is_oct_digit(self) -> bool;
/// Gets the len in bytes for self
fn len(self) -> usize;
}
impl AsChar for u8 {
#[inline]
fn as_char(self) -> char {
self as char
}
#[inline]
fn is_alpha(self) -> bool {
(self >= 0x41 && self <= 0x5A) || (self >= 0x61 && self <= 0x7A)
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self >= 0x30 && self <= 0x39
}
#[inline]
fn is_hex_digit(self) -> bool {
(self >= 0x30 && self <= 0x39)
|| (self >= 0x41 && self <= 0x46)
|| (self >= 0x61 && self <= 0x66)
}
#[inline]
fn is_oct_digit(self) -> bool {
self >= 0x30 && self <= 0x37
}
#[inline]
fn len(self) -> usize {
1
}
}
impl<'a> AsChar for &'a u8 {
#[inline]
fn as_char(self) -> char {
*self as char
}
#[inline]
fn is_alpha(self) -> bool {
(*self >= 0x41 && *self <= 0x5A) || (*self >= 0x61 && *self <= 0x7A)
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
*self >= 0x30 && *self <= 0x39
}
#[inline]
fn is_hex_digit(self) -> bool {
(*self >= 0x30 && *self <= 0x39)
|| (*self >= 0x41 && *self <= 0x46)
|| (*self >= 0x61 && *self <= 0x66)
}
#[inline]
fn is_oct_digit(self) -> bool {
*self >= 0x30 && *self <= 0x37
}
#[inline]
fn len(self) -> usize {
1
}
}
impl AsChar for char {
#[inline]
fn as_char(self) -> char {
self
}
#[inline]
fn is_alpha(self) -> bool {
self.is_ascii_alphabetic()
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self.is_ascii_digit()
}
#[inline]
fn is_hex_digit(self) -> bool {
self.is_ascii_hexdigit()
}
#[inline]
fn is_oct_digit(self) -> bool {
self.is_digit(8)
}
#[inline]
fn len(self) -> usize {
self.len_utf8()
}
}
impl<'a> AsChar for &'a char {
#[inline]
fn as_char(self) -> char {
*self
}
#[inline]
fn is_alpha(self) -> bool {
self.is_ascii_alphabetic()
}
#[inline]
fn is_alphanum(self) -> bool {
self.is_alpha() || self.is_dec_digit()
}
#[inline]
fn is_dec_digit(self) -> bool {
self.is_ascii_digit()
}
#[inline]
fn is_hex_digit(self) -> bool {
self.is_ascii_hexdigit()
}
#[inline]
fn is_oct_digit(self) -> bool {
self.is_digit(8)
}
#[inline]
fn len(self) -> usize {
self.len_utf8()
}
}
/// Abstracts common iteration operations on the input type
pub trait InputIter {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// An iterator over the input type, producing the item and its position
/// for use with [Slice]. If we're iterating over `&str`, the position
/// corresponds to the byte index of the character
type Iter: Iterator<Item = (usize, Self::Item)>;
/// An iterator over the input type, producing the item
type IterElem: Iterator<Item = Self::Item>;
/// Returns an iterator over the elements and their byte offsets
fn iter_indices(&self) -> Self::Iter;
/// Returns an iterator over the elements
fn iter_elements(&self) -> Self::IterElem;
/// Finds the byte position of the element
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool;
/// Get the byte offset from the element's position in the stream
fn slice_index(&self, count: usize) -> Result<usize, Needed>;
}
/// Abstracts slicing operations
pub trait InputTake: Sized {
/// Returns a slice of `count` bytes. panics if count > length
fn take(&self, count: usize) -> Self;
/// Split the stream at the `count` byte offset. panics if count > length
fn take_split(&self, count: usize) -> (Self, Self);
}
impl<'a> InputIter for &'a [u8] {
type Item = u8;
type Iter = Enumerate<Self::IterElem>;
type IterElem = Copied<Iter<'a, u8>>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.iter_elements().enumerate()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.iter().copied()
}
#[inline]
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool,
{
self.iter().position(|b| predicate(*b))
}
#[inline]
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
if self.len() >= count {
Ok(count)
} else {
Err(Needed::new(count - self.len()))
}
}
}
impl<'a> InputTake for &'a [u8] {
#[inline]
fn take(&self, count: usize) -> Self {
&self[0..count]
}
#[inline]
fn take_split(&self, count: usize) -> (Self, Self) {
let (prefix, suffix) = self.split_at(count);
(suffix, prefix)
}
}
impl<'a> InputIter for &'a str {
type Item = char;
type Iter = CharIndices<'a>;
type IterElem = Chars<'a>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.char_indices()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.chars()
}
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool,
{
for (o, c) in self.char_indices() {
if predicate(c) {
return Some(o);
}
}
None
}
#[inline]
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
let mut cnt = 0;
for (index, _) in self.char_indices() {
if cnt == count {
return Ok(index);
}
cnt += 1;
}
if cnt == count {
return Ok(self.len());
}
Err(Needed::Unknown)
}
}
impl<'a> InputTake for &'a str {
#[inline]
fn take(&self, count: usize) -> Self {
&self[..count]
}
// return byte index
#[inline]
fn take_split(&self, count: usize) -> (Self, Self) {
let (prefix, suffix) = self.split_at(count);
(suffix, prefix)
}
}
/// Dummy trait used for default implementations (currently only used for `InputTakeAtPosition` and `Compare`).
///
/// When implementing a custom input type, it is possible to use directly the
/// default implementation: If the input type implements `InputLength`, `InputIter`,
/// `InputTake` and `Clone`, you can implement `UnspecializedInput` and get
/// a default version of `InputTakeAtPosition` and `Compare`.
///
/// For performance reasons, you might want to write a custom implementation of
/// `InputTakeAtPosition` (like the one for `&[u8]`).
pub trait UnspecializedInput {}
/// Methods to take as much input as possible until the provided function returns true for the current element.
///
/// A large part of nom's basic parsers are built using this trait.
pub trait InputTakeAtPosition: Sized {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// Looks for the first element of the input type for which the condition returns true,
/// and returns the input up to this position.
///
/// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true
/// and returns the input up to this position.
///
/// Fails if the produced slice is empty.
///
/// *streaming version*: If no element is found matching the condition, this will return `Incomplete`
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true,
/// and returns the input up to this position.
///
/// *complete version*: If no element is found matching the condition, this will return the whole input
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
/// Looks for the first element of the input type for which the condition returns true
/// and returns the input up to this position.
///
/// Fails if the produced slice is empty.
///
/// *complete version*: If no element is found matching the condition, this will return the whole input
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
}
impl<T: InputLength + InputIter + InputTake + Clone + UnspecializedInput> InputTakeAtPosition
for T
{
type Item = <T as InputIter>::Item;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.position(predicate) {
Some(n) => Ok(self.take_split(n)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.position(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(n) => Ok(self.take_split(n)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.split_at_position(predicate) {
Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())),
res => res,
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.split_at_position1(predicate, e) {
Err(Err::Incomplete(_)) => {
if self.input_len() == 0 {
Err(Err::Error(E::from_error_kind(self.clone(), e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
res => res,
}
}
}
impl<'a> InputTakeAtPosition for &'a [u8] {
type Item = u8;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(i) => Ok(self.take_split(i)),
None => Ok(self.take_split(self.input_len())),
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.iter().position(|c| predicate(*c)) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
Some(i) => Ok(self.take_split(i)),
None => {
if self.is_empty() {
Err(Err::Error(E::from_error_kind(self, e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
}
}
}
impl<'a> InputTakeAtPosition for &'a str {
type Item = char;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
// find() returns a byte index that is already in the slice at a char boundary
Some(i) => unsafe {Ok((self.get_unchecked(i..), self.get_unchecked(..i)))},
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
// find() returns a byte index that is already in the slice at a char boundary
Some(i) => unsafe {Ok((self.get_unchecked(i..), self.get_unchecked(..i)))},
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
// find() returns a byte index that is already in the slice at a char boundary
Some(i) => unsafe {Ok((self.get_unchecked(i..), self.get_unchecked(..i)))},
// the end of slice is a char boundary
None => unsafe {Ok((self.get_unchecked(self.len()..), self.get_unchecked(..self.len())))},
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self, e))),
// find() returns a byte index that is already in the slice at a char boundary
Some(i) => unsafe {Ok((self.get_unchecked(i..), self.get_unchecked(..i)))},
None => {
if self.is_empty() {
Err(Err::Error(E::from_error_kind(self, e)))
} else {
// the end of slice is a char boundary
unsafe {Ok((self.get_unchecked(self.len()..), self.get_unchecked(..self.len())))}
}
}
}
}
}
/// Indicates wether a comparison was successful, an error, or
/// if more data was needed
#[derive(Debug, PartialEq)]
pub enum CompareResult {
/// Comparison was successful
Ok,
/// We need more data to be sure
Incomplete,
/// Comparison failed
Error,
}
/// Abstracts comparison operations
pub trait Compare<T> {
/// Compares self to another value for equality
fn compare(&self, t: T) -> CompareResult;
/// Compares self to another value for equality
/// independently of the case.
///
/// Warning: for `&str`, the comparison is done
/// by lowercasing both strings and comparing
/// the result. This is a temporary solution until
/// a better one appears
fn compare_no_case(&self, t: T) -> CompareResult;
}
fn lowercase_byte(c: u8) -> u8 {
match c {
b'A'..=b'Z' => c - b'A' + b'a',
_ => c,
}
}
impl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b [u8]) -> CompareResult {
let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);
match pos {
Some(_) => CompareResult::Error,
None => {
if self.len() >= t.len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
/*
let len = self.len();
let blen = t.len();
let m = if len < blen { len } else { blen };
let reduced = &self[..m];
let b = &t[..m];
if reduced != b {
CompareResult::Error
} else if m < blen {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
*/
}
#[inline(always)]
fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {
if self
.iter()
.zip(t)
.any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))
{
CompareResult::Error
} else if self.len() < t.len() {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
}
}
impl<
T: InputLength + InputIter<Item = u8> + InputTake + UnspecializedInput,
O: InputLength + InputIter<Item = u8> + InputTake,
> Compare<O> for T
{
#[inline(always)]
fn compare(&self, t: O) -> CompareResult {
let pos = self
.iter_elements()
.zip(t.iter_elements())
.position(|(a, b)| a != b);
match pos {
Some(_) => CompareResult::Error,
None => {
if self.input_len() >= t.input_len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
}
#[inline(always)]
fn compare_no_case(&self, t: O) -> CompareResult {
if self
.iter_elements()
.zip(t.iter_elements())
.any(|(a, b)| lowercase_byte(a) != lowercase_byte(b))
{
CompareResult::Error
} else if self.input_len() < t.input_len() {
CompareResult::Incomplete
} else {
CompareResult::Ok
}
}
}
impl<'a, 'b> Compare<&'b str> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b str) -> CompareResult {
self.compare(AsBytes::as_bytes(t))
}
#[inline(always)]
fn compare_no_case(&self, t: &'b str) -> CompareResult {
self.compare_no_case(AsBytes::as_bytes(t))
}
}
impl<'a, 'b> Compare<&'b str> for &'a str {
#[inline(always)]
fn compare(&self, t: &'b str) -> CompareResult {
self.as_bytes().compare(t.as_bytes())
}
//FIXME: this version is too simple and does not use the current locale
#[inline(always)]
fn compare_no_case(&self, t: &'b str) -> CompareResult {
let pos = self
.chars()
.zip(t.chars())
.position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));
match pos {
Some(_) => CompareResult::Error,
None => {
if self.len() >= t.len() {
CompareResult::Ok
} else {
CompareResult::Incomplete
}
}
}
}
}
/// Look for a token in self
pub trait FindToken<T> {
/// Returns true if self contains the token
fn find_token(&self, token: T) -> bool;
}
impl<'a> FindToken<u8> for &'a [u8] {
fn find_token(&self, token: u8) -> bool {
memchr::memchr(token, self).is_some()
}
}
impl<'a> FindToken<u8> for &'a str {
fn find_token(&self, token: u8) -> bool {
self.as_bytes().find_token(token)
}
}
impl<'a, 'b> FindToken<&'a u8> for &'b [u8] {
fn find_token(&self, token: &u8) -> bool {
self.find_token(*token)
}
}
impl<'a, 'b> FindToken<&'a u8> for &'b str {
fn find_token(&self, token: &u8) -> bool {
self.as_bytes().find_token(token)
}
}
impl<'a> FindToken<char> for &'a [u8] {
fn find_token(&self, token: char) -> bool {
self.iter().any(|i| *i == token as u8)
}
}
impl<'a> FindToken<char> for &'a str {
fn find_token(&self, token: char) -> bool {
self.chars().any(|i| i == token)
}
}
/// Look for a substring in self
pub trait FindSubstring<T> {
/// Returns the byte position of the substring if it is found
fn find_substring(&self, substr: T) -> Option<usize>;
}
impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
if substr.len() > self.len() {
return None;
}
let (&substr_first, substr_rest) = match substr.split_first() {
Some(split) => split,
// an empty substring is found at position 0
// This matches the behavior of str.find("").
None => return Some(0),
};
if substr_rest.is_empty() {
return memchr::memchr(substr_first, self);
}
let mut offset = 0;
let haystack = &self[..self.len() - substr_rest.len()];
while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
offset += position;
let next_offset = offset + 1;
if &self[next_offset..][..substr_rest.len()] == substr_rest {
return Some(offset);
}
offset = next_offset;
}
None
}
}
impl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {
fn find_substring(&self, substr: &'b str) -> Option<usize> {
self.find_substring(AsBytes::as_bytes(substr))
}
}
impl<'a, 'b> FindSubstring<&'b str> for &'a str {
//returns byte index
fn find_substring(&self, substr: &'b str) -> Option<usize> {
self.find(substr)
}
}
/// Used to integrate `str`'s `parse()` method
pub trait ParseTo<R> {
/// Succeeds if `parse()` succeeded. The byte slice implementation
/// will first convert it to a `&str`, then apply the `parse()` function
fn parse_to(&self) -> Option<R>;
}
impl<'a, R: FromStr> ParseTo<R> for &'a [u8] {
fn parse_to(&self) -> Option<R> {
from_utf8(self).ok().and_then(|s| s.parse().ok())
}
}
impl<'a, R: FromStr> ParseTo<R> for &'a str {
fn parse_to(&self) -> Option<R> {
self.parse().ok()
}
}
/// Slicing operations using ranges.
///
/// This trait is loosely based on
/// `Index`, but can actually return
/// something else than a `&[T]` or `&str`
pub trait Slice<R> {
/// Slices self according to the range argument
fn slice(&self, range: R) -> Self;
}
macro_rules! impl_fn_slice {
( $ty:ty ) => {
fn slice(&self, range: $ty) -> Self {
&self[range]
}
};
}
macro_rules! slice_range_impl {
( BitSlice, $ty:ty ) => {
impl<'a, O, T> Slice<$ty> for &'a BitSlice<O, T>
where
O: BitOrder,
T: BitStore,
{
impl_fn_slice!($ty);
}
};
( [ $for_type:ident ], $ty:ty ) => {
impl<'a, $for_type> Slice<$ty> for &'a [$for_type] {
impl_fn_slice!($ty);
}
};
( $for_type:ty, $ty:ty ) => {
impl<'a> Slice<$ty> for &'a $for_type {
impl_fn_slice!($ty);
}
};
}
macro_rules! slice_ranges_impl {
( BitSlice ) => {
slice_range_impl! {BitSlice, Range<usize>}
slice_range_impl! {BitSlice, RangeTo<usize>}
slice_range_impl! {BitSlice, RangeFrom<usize>}
slice_range_impl! {BitSlice, RangeFull}
};
( [ $for_type:ident ] ) => {
slice_range_impl! {[$for_type], Range<usize>}
slice_range_impl! {[$for_type], RangeTo<usize>}
slice_range_impl! {[$for_type], RangeFrom<usize>}
slice_range_impl! {[$for_type], RangeFull}
};
( $for_type:ty ) => {
slice_range_impl! {$for_type, Range<usize>}
slice_range_impl! {$for_type, RangeTo<usize>}
slice_range_impl! {$for_type, RangeFrom<usize>}
slice_range_impl! {$for_type, RangeFull}
};
}
slice_ranges_impl! {str}
slice_ranges_impl! {[T]}
macro_rules! array_impls {
($($N:expr)+) => {
$(
impl InputLength for [u8; $N] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputLength for &'a [u8; $N] {
#[inline]
fn input_len(&self) -> usize {
self.len()
}
}
impl<'a> InputIter for &'a [u8; $N] {
type Item = u8;
type Iter = Enumerate<Self::IterElem>;
type IterElem = Copied<Iter<'a, u8>>;
fn iter_indices(&self) -> Self::Iter {
(&self[..]).iter_indices()
}
fn iter_elements(&self) -> Self::IterElem {
(&self[..]).iter_elements()
}
fn position<P>(&self, predicate: P) -> Option<usize>
where P: Fn(Self::Item) -> bool {
(&self[..]).position(predicate)
}
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
(&self[..]).slice_index(count)
}
}
impl<'a> Compare<[u8; $N]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: [u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: [u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl<'a,'b> Compare<&'b [u8; $N]> for &'a [u8] {
#[inline(always)]
fn compare(&self, t: &'b [u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: &'b [u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl FindToken<u8> for [u8; $N] {
fn find_token(&self, token: u8) -> bool {
memchr::memchr(token, &self[..]).is_some()
}
}
impl<'a> FindToken<&'a u8> for [u8; $N] {
fn find_token(&self, token: &u8) -> bool {
self.find_token(*token)
}
}
)+
};
}
array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
/// Abstracts something which can extend an `Extend`.
/// Used to build modified input slices in `escaped_transform`
pub trait ExtendInto {
/// The current input type is a sequence of that `Item` type.
///
/// Example: `u8` for `&[u8]` or `char` for `&str`
type Item;
/// The type that will be produced
type Extender;
/// Create a new `Extend` of the correct type
fn new_builder(&self) -> Self::Extender;
/// Accumulate the input into an accumulator
fn extend_into(&self, acc: &mut Self::Extender);
}
#[cfg(feature = "alloc")]
impl ExtendInto for [u8] {
type Item = u8;
type Extender = Vec<u8>;
#[inline]
fn new_builder(&self) -> Vec<u8> {
Vec::new()
}
#[inline]
fn extend_into(&self, acc: &mut Vec<u8>) {
acc.extend(self.iter().cloned());
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for &[u8] {
type Item = u8;
type Extender = Vec<u8>;
#[inline]
fn new_builder(&self) -> Vec<u8> {
Vec::new()
}
#[inline]
fn extend_into(&self, acc: &mut Vec<u8>) {
acc.extend_from_slice(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for str {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push_str(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for &str {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push_str(self);
}
}
#[cfg(feature = "alloc")]
impl ExtendInto for char {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push(*self);
}
}
/// Helper trait to convert numbers to usize.
///
/// By default, usize implements `From<u8>` and `From<u16>` but not
/// `From<u32>` and `From<u64>` because that would be invalid on some
/// platforms. This trait implements the conversion for platforms
/// with 32 and 64 bits pointer platforms
pub trait ToUsize {
/// converts self to usize
fn to_usize(&self) -> usize;
}
impl ToUsize for u8 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
impl ToUsize for u16 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
impl ToUsize for usize {
#[inline]
fn to_usize(&self) -> usize {
*self
}
}
#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
impl ToUsize for u32 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
#[cfg(target_pointer_width = "64")]
impl ToUsize for u64 {
#[inline]
fn to_usize(&self) -> usize {
*self as usize
}
}
/// Equivalent From implementation to avoid orphan rules in bits parsers
pub trait ErrorConvert<E> {
/// Transform to another error type
fn convert(self) -> E;
}
impl<I> ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {
fn convert(self) -> (I, ErrorKind) {
((self.0).0, self.1)
}
}
impl<I> ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {
fn convert(self) -> ((I, usize), ErrorKind) {
((self.0, 0), self.1)
}
}
use crate::error;
impl<I> ErrorConvert<error::Error<I>> for error::Error<(I, usize)> {
fn convert(self) -> error::Error<I> {
error::Error {
input: self.input.0,
code: self.code,
}
}
}
impl<I> ErrorConvert<error::Error<(I, usize)>> for error::Error<I> {
fn convert(self) -> error::Error<(I, usize)> {
error::Error {
input: (self.input, 0),
code: self.code,
}
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
impl<I> ErrorConvert<error::VerboseError<I>> for error::VerboseError<(I, usize)> {
fn convert(self) -> error::VerboseError<I> {
error::VerboseError {
errors: self.errors.into_iter().map(|(i, e)| (i.0, e)).collect(),
}
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "alloc")))]
impl<I> ErrorConvert<error::VerboseError<(I, usize)>> for error::VerboseError<I> {
fn convert(self) -> error::VerboseError<(I, usize)> {
error::VerboseError {
errors: self.errors.into_iter().map(|(i, e)| ((i, 0), e)).collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_offset_u8() {
let s = b"abcd123";
let a = &s[..];
let b = &a[2..];
let c = &a[..4];
let d = &a[3..5];
assert_eq!(a.offset(b), 2);
assert_eq!(a.offset(c), 0);
assert_eq!(a.offset(d), 3);
}
#[test]
fn test_offset_str() {
let s = "abcřèÂßÇd123";
let a = &s[..];
let b = &a[7..];
let c = &a[..5];
let d = &a[5..9];
assert_eq!(a.offset(b), 7);
assert_eq!(a.offset(c), 0);
assert_eq!(a.offset(d), 5);
}
}
|
use std::result;
use analysis::ref_mode::RefMode;
use env::Env;
use library::{self, Nullable};
use nameutil::crate_name;
use super::conversion_type::ConversionType;
use traits::*;
pub type Result = result::Result<String, String>;
impl AsStr for Result {
#[inline]
fn as_str(&self) -> &str {
self.as_ref().unwrap_or_else(|s| s)
}
}
pub fn rust_type(env: &Env, type_id: library::TypeId) -> Result {
rust_type_full(env, type_id, Nullable(false), RefMode::None)
}
fn rust_type_full(env: &Env, type_id: library::TypeId, nullable: Nullable, ref_mode: RefMode) -> Result {
use library::Type::*;
use library::Fundamental::*;
let mut skip_option = false;
let type_ = env.library.type_(type_id);
let mut rust_type = match *type_ {
Fundamental(fund) => {
let ok = |s: &str| Ok(s.into());
let err = |s: &str| Err(s.into());
match fund {
None => err("()"),
Boolean => ok("bool"),
Int8 => ok("i8"),
UInt8 => ok("u8"),
Int16 => ok("i16"),
UInt16 => ok("u16"),
Int32 => ok("i32"),
UInt32 => ok("u32"),
Int64 => ok("i64"),
UInt64 => ok("u64"),
Int => ok("i32"), //maybe dependent on target system
UInt => ok("u32"), //maybe dependent on target system
Float => ok("f32"),
Double => ok("f64"),
UniChar => ok("char"),
Utf8 => if ref_mode.is_ref() { ok("str") } else { ok("String") },
Filename => if ref_mode.is_ref() { ok("str") } else { ok("String") },
Type => ok("glib::types::Type"),
Unsupported => err("Unsupported"),
_ => err(&format!("Fundamental: {:?}", fund)),
}
},
Alias(ref alias) => rust_type_full(env, alias.typ, nullable, ref_mode)
.map_any(|_| alias.name.clone()),
Enumeration(ref enum_) => Ok(enum_.name.clone()),
Bitfield(ref bitfield) => Ok(bitfield.name.clone()),
Record(ref record) => Ok(record.name.clone()),
Interface(ref interface) => Ok(interface.name.clone()),
Class(ref klass) => Ok(klass.name.clone()),
List(inner_tid) |
SList(inner_tid) |
CArray(inner_tid)
if ConversionType::of(&env.library, inner_tid) == ConversionType::Pointer => {
skip_option = true;
rust_type_full(env, inner_tid, Nullable(false), ref_mode)
.map_any(|s| if ref_mode.is_ref() {
format!("[{}]", s)
} else {
format!("Vec<{}>", s)
})
}
_ => Err(format!("Unknown rust type: {:?}", type_.get_name())),
//TODO: check usage library::Type::get_name() when no _ in this
};
if type_id.ns_id != library::MAIN_NAMESPACE && type_id.ns_id != library::INTERNAL_NAMESPACE
&& !implemented_in_main_namespace(&env.library, type_id) {
let rust_type_with_prefix = rust_type.map(|s| format!("{}::{}",
crate_name(&env.library.namespace(type_id.ns_id).name), s));
if env.type_status(&type_id.full_name(&env.library)).ignored() {
rust_type = Err(rust_type_with_prefix.as_str().into());
} else {
rust_type = rust_type_with_prefix;
}
}
match ref_mode {
RefMode::None => {}
RefMode::ByRef | RefMode::ByRefImmut => rust_type = rust_type.map_any(|s| format!("&{}", s)),
RefMode::ByRefMut => rust_type = rust_type.map_any(|s| format!("&mut {}", s)),
}
if *nullable && !skip_option {
match ConversionType::of(&env.library, type_id) {
ConversionType::Pointer
| ConversionType::Scalar => {
rust_type = rust_type.map_any(|s| format!("Option<{}>", s))
}
_ => (),
}
}
rust_type
}
pub fn used_rust_type(env: &Env, type_id: library::TypeId) -> Result {
use library::Type::*;
match *env.library.type_(type_id) {
Fundamental(library::Fundamental::Type) |
Alias(..) |
Bitfield(..) |
Record(..) |
Class(..) |
Enumeration(..) |
Interface(..) => rust_type(env, type_id),
List(inner_tid) |
SList(inner_tid) |
CArray(inner_tid) => used_rust_type(env, inner_tid),
_ => Err("Don't need use".into()),
}
}
pub fn parameter_rust_type(env: &Env, type_id:library::TypeId,
direction: library::ParameterDirection, nullable: Nullable,
ref_mode: RefMode) -> Result {
use library::Type::*;
let type_ = env.library.type_(type_id);
let rust_type = rust_type_full(env, type_id, nullable, ref_mode);
match *type_ {
Fundamental(fund) => {
if fund == library::Fundamental::Utf8 || fund == library::Fundamental::Filename {
match direction {
library::ParameterDirection::In |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
} else {
format_parameter(rust_type, direction)
}
}
Alias(ref alias) => {
let res = format_parameter(rust_type, direction);
if parameter_rust_type(env, alias.typ, direction, nullable, ref_mode).is_ok() {
res
} else {
res.and_then(|s| Err(s))
}
}
Enumeration(..) |
Bitfield(..) => format_parameter(rust_type, direction),
Record(..) => {
if env.type_status(&type_id.full_name(&env.library)).ignored() {
Err(format!("/*Ignored*/{}", rust_type.as_str()))
} else if direction == library::ParameterDirection::InOut {
Err(format!("/*Unimplemented*/{}", rust_type.as_str()))
} else {
rust_type
}
}
Class(..) |
Interface (..) => {
match direction {
_ if env.type_status(&type_id.full_name(&env.library)).ignored() => {
Err(format!("/*Ignored*/{}", rust_type.as_str()))
}
library::ParameterDirection::In |
library::ParameterDirection::Out |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
}
List(..) |
SList(..) |
CArray(..) => {
match direction {
library::ParameterDirection::In |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
}
_ => Err(format!("Unknown rust type: {:?}", type_.get_name())),
//TODO: check usage library::Type::get_name() when no _ in this
}
}
#[inline]
fn format_parameter(rust_type: Result, direction: library::ParameterDirection) -> Result {
if direction.is_out() {
rust_type.map(|s| format!("&mut {}", s))
} else {
rust_type
}
}
fn implemented_in_main_namespace(library: &library::Library, type_id: library::TypeId) -> bool {
if library.namespace(library::MAIN_NAMESPACE).name != "Gtk" {
return false;
}
match &*type_id.full_name(library) {
"Gdk.Rectangle" => true,
_ => false,
}
}
Take slices of objects like `&[Widget]` not like `&[&Widget]`
In some cases it could be very inconvenient to create vectors of references.
use std::result;
use analysis::ref_mode::RefMode;
use env::Env;
use library::{self, Nullable};
use nameutil::crate_name;
use super::conversion_type::ConversionType;
use traits::*;
pub type Result = result::Result<String, String>;
impl AsStr for Result {
#[inline]
fn as_str(&self) -> &str {
self.as_ref().unwrap_or_else(|s| s)
}
}
pub fn rust_type(env: &Env, type_id: library::TypeId) -> Result {
rust_type_full(env, type_id, Nullable(false), RefMode::None)
}
fn rust_type_full(env: &Env, type_id: library::TypeId, nullable: Nullable, ref_mode: RefMode) -> Result {
use library::Type::*;
use library::Fundamental::*;
let mut skip_option = false;
let type_ = env.library.type_(type_id);
let mut rust_type = match *type_ {
Fundamental(fund) => {
let ok = |s: &str| Ok(s.into());
let err = |s: &str| Err(s.into());
match fund {
None => err("()"),
Boolean => ok("bool"),
Int8 => ok("i8"),
UInt8 => ok("u8"),
Int16 => ok("i16"),
UInt16 => ok("u16"),
Int32 => ok("i32"),
UInt32 => ok("u32"),
Int64 => ok("i64"),
UInt64 => ok("u64"),
Int => ok("i32"), //maybe dependent on target system
UInt => ok("u32"), //maybe dependent on target system
Float => ok("f32"),
Double => ok("f64"),
UniChar => ok("char"),
Utf8 => if ref_mode.is_ref() { ok("str") } else { ok("String") },
Filename => if ref_mode.is_ref() { ok("str") } else { ok("String") },
Type => ok("glib::types::Type"),
Unsupported => err("Unsupported"),
_ => err(&format!("Fundamental: {:?}", fund)),
}
},
Alias(ref alias) => rust_type_full(env, alias.typ, nullable, ref_mode)
.map_any(|_| alias.name.clone()),
Enumeration(ref enum_) => Ok(enum_.name.clone()),
Bitfield(ref bitfield) => Ok(bitfield.name.clone()),
Record(ref record) => Ok(record.name.clone()),
Interface(ref interface) => Ok(interface.name.clone()),
Class(ref klass) => Ok(klass.name.clone()),
List(inner_tid) |
SList(inner_tid) |
CArray(inner_tid)
if ConversionType::of(&env.library, inner_tid) == ConversionType::Pointer => {
skip_option = true;
let inner_ref_mode = match *env.library.type_(inner_tid) {
Class(..) |
Interface(..) => RefMode::None,
_ => ref_mode,
};
rust_type_full(env, inner_tid, Nullable(false), inner_ref_mode)
.map_any(|s| if ref_mode.is_ref() {
format!("[{}]", s)
} else {
format!("Vec<{}>", s)
})
}
_ => Err(format!("Unknown rust type: {:?}", type_.get_name())),
//TODO: check usage library::Type::get_name() when no _ in this
};
if type_id.ns_id != library::MAIN_NAMESPACE && type_id.ns_id != library::INTERNAL_NAMESPACE
&& !implemented_in_main_namespace(&env.library, type_id) {
let rust_type_with_prefix = rust_type.map(|s| format!("{}::{}",
crate_name(&env.library.namespace(type_id.ns_id).name), s));
if env.type_status(&type_id.full_name(&env.library)).ignored() {
rust_type = Err(rust_type_with_prefix.as_str().into());
} else {
rust_type = rust_type_with_prefix;
}
}
match ref_mode {
RefMode::None => {}
RefMode::ByRef | RefMode::ByRefImmut => rust_type = rust_type.map_any(|s| format!("&{}", s)),
RefMode::ByRefMut => rust_type = rust_type.map_any(|s| format!("&mut {}", s)),
}
if *nullable && !skip_option {
match ConversionType::of(&env.library, type_id) {
ConversionType::Pointer
| ConversionType::Scalar => {
rust_type = rust_type.map_any(|s| format!("Option<{}>", s))
}
_ => (),
}
}
rust_type
}
pub fn used_rust_type(env: &Env, type_id: library::TypeId) -> Result {
use library::Type::*;
match *env.library.type_(type_id) {
Fundamental(library::Fundamental::Type) |
Alias(..) |
Bitfield(..) |
Record(..) |
Class(..) |
Enumeration(..) |
Interface(..) => rust_type(env, type_id),
List(inner_tid) |
SList(inner_tid) |
CArray(inner_tid) => used_rust_type(env, inner_tid),
_ => Err("Don't need use".into()),
}
}
pub fn parameter_rust_type(env: &Env, type_id:library::TypeId,
direction: library::ParameterDirection, nullable: Nullable,
ref_mode: RefMode) -> Result {
use library::Type::*;
let type_ = env.library.type_(type_id);
let rust_type = rust_type_full(env, type_id, nullable, ref_mode);
match *type_ {
Fundamental(fund) => {
if fund == library::Fundamental::Utf8 || fund == library::Fundamental::Filename {
match direction {
library::ParameterDirection::In |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
} else {
format_parameter(rust_type, direction)
}
}
Alias(ref alias) => {
let res = format_parameter(rust_type, direction);
if parameter_rust_type(env, alias.typ, direction, nullable, ref_mode).is_ok() {
res
} else {
res.and_then(|s| Err(s))
}
}
Enumeration(..) |
Bitfield(..) => format_parameter(rust_type, direction),
Record(..) => {
if env.type_status(&type_id.full_name(&env.library)).ignored() {
Err(format!("/*Ignored*/{}", rust_type.as_str()))
} else if direction == library::ParameterDirection::InOut {
Err(format!("/*Unimplemented*/{}", rust_type.as_str()))
} else {
rust_type
}
}
Class(..) |
Interface (..) => {
match direction {
_ if env.type_status(&type_id.full_name(&env.library)).ignored() => {
Err(format!("/*Ignored*/{}", rust_type.as_str()))
}
library::ParameterDirection::In |
library::ParameterDirection::Out |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
}
List(..) |
SList(..) |
CArray(..) => {
match direction {
library::ParameterDirection::In |
library::ParameterDirection::Return => rust_type,
_ => Err(format!("/*Unimplemented*/{}", rust_type.as_str())),
}
}
_ => Err(format!("Unknown rust type: {:?}", type_.get_name())),
//TODO: check usage library::Type::get_name() when no _ in this
}
}
#[inline]
fn format_parameter(rust_type: Result, direction: library::ParameterDirection) -> Result {
if direction.is_out() {
rust_type.map(|s| format!("&mut {}", s))
} else {
rust_type
}
}
fn implemented_in_main_namespace(library: &library::Library, type_id: library::TypeId) -> bool {
if library.namespace(library::MAIN_NAMESPACE).name != "Gtk" {
return false;
}
match &*type_id.full_name(library) {
"Gdk.Rectangle" => true,
_ => false,
}
}
|
//! Standard symbolic constants and types
//!
use {Errno, Error, Result, NixPath};
use fcntl::{fcntl, OFlag, O_NONBLOCK, O_CLOEXEC, FD_CLOEXEC};
use fcntl::FcntlArg::{F_SETFD, F_SETFL};
use libc::{self, c_char, c_void, c_int, size_t, pid_t, off_t, uid_t, gid_t};
use std::mem;
use std::ffi::CString;
use std::os::unix::io::RawFd;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::linux::*;
#[derive(Clone, Copy)]
pub enum ForkResult {
Parent {
child: pid_t
},
Child
}
impl ForkResult {
#[inline]
pub fn is_child(&self) -> bool {
match *self {
ForkResult::Child => true,
_ => false
}
}
#[inline]
pub fn is_parent(&self) -> bool {
!self.is_child()
}
}
#[inline]
pub fn fork() -> Result<ForkResult> {
use self::ForkResult::*;
let res = unsafe { libc::fork() };
Errno::result(res).map(|res| match res {
0 => Child,
res => Parent { child: res }
})
}
#[inline]
pub fn getpid() -> pid_t {
unsafe { libc::getpid() } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn getppid() -> pid_t {
unsafe { libc::getppid() } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn setpgid(pid: pid_t, pgid: pid_t) -> Result<()> {
let res = unsafe { libc::setpgid(pid, pgid) };
Errno::result(res).map(drop)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[inline]
pub fn gettid() -> pid_t {
unsafe { libc::syscall(libc::SYS_gettid) as pid_t } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn dup(oldfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup(oldfd) };
Errno::result(res)
}
#[inline]
pub fn dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup2(oldfd, newfd) };
Errno::result(res)
}
pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
dup3_polyfill(oldfd, newfd, flags)
}
#[inline]
fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
if oldfd == newfd {
return Err(Error::Sys(Errno::EINVAL));
}
let fd = try!(dup2(oldfd, newfd));
if flags.contains(O_CLOEXEC) {
if let Err(e) = fcntl(fd, F_SETFD(FD_CLOEXEC)) {
let _ = close(fd);
return Err(e);
}
}
Ok(fd)
}
#[inline]
pub fn chdir<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe { libc::chdir(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn chown<P: ?Sized + NixPath>(path: &P, owner: Option<uid_t>, group: Option<gid_t>) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
// We use `0 - 1` to get `-1 : {u,g}id_t` which is specified as the no-op value for chown(3).
unsafe { libc::chown(cstr.as_ptr(), owner.unwrap_or(0 - 1), group.unwrap_or(0 - 1)) }
}));
Errno::result(res).map(drop)
}
fn to_exec_array(args: &[CString]) -> Vec<*const c_char> {
use std::ptr;
use libc::c_char;
let mut args_p: Vec<*const c_char> = args.iter().map(|s| s.as_ptr()).collect();
args_p.push(ptr::null());
args_p
}
#[inline]
pub fn execv(path: &CString, argv: &[CString]) -> Result<()> {
let args_p = to_exec_array(argv);
unsafe {
libc::execv(path.as_ptr(), args_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
#[inline]
pub fn execve(path: &CString, args: &[CString], env: &[CString]) -> Result<()> {
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe {
libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
#[inline]
pub fn execvp(filename: &CString, args: &[CString]) -> Result<()> {
let args_p = to_exec_array(args);
unsafe {
libc::execvp(filename.as_ptr(), args_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> {
let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) };
Errno::result(res).map(drop)
}
pub fn sethostname(name: &[u8]) -> Result<()> {
// Handle some differences in type of the len arg across platforms.
cfg_if! {
if #[cfg(any(target_os = "macos", target_os = "ios"))] {
type sethostname_len_t = c_int;
} else {
type sethostname_len_t = size_t;
}
}
let ptr = name.as_ptr() as *const c_char;
let len = name.len() as sethostname_len_t;
let res = unsafe { libc::sethostname(ptr, len) };
Errno::result(res).map(drop)
}
pub fn gethostname(name: &mut [u8]) -> Result<()> {
let ptr = name.as_mut_ptr() as *mut c_char;
let len = name.len() as size_t;
let res = unsafe { libc::gethostname(ptr, len) };
Errno::result(res).map(drop)
}
pub fn close(fd: RawFd) -> Result<()> {
let res = unsafe { libc::close(fd) };
Errno::result(res).map(drop)
}
pub fn read(fd: RawFd, buf: &mut [u8]) -> Result<usize> {
let res = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) };
Errno::result(res).map(|r| r as usize)
}
pub fn write(fd: RawFd, buf: &[u8]) -> Result<usize> {
let res = unsafe { libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) };
Errno::result(res).map(|r| r as usize)
}
pub fn pipe() -> Result<(RawFd, RawFd)> {
unsafe {
let mut fds: [c_int; 2] = mem::uninitialized();
let res = libc::pipe(fds.as_mut_ptr());
try!(Errno::result(res));
Ok((fds[0], fds[1]))
}
}
pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> {
unsafe {
let mut fds: [c_int; 2] = mem::uninitialized();
let res = libc::pipe(fds.as_mut_ptr());
try!(Errno::result(res));
try!(pipe2_setflags(fds[0], fds[1], flags));
Ok((fds[0], fds[1]))
}
}
fn pipe2_setflags(fd1: RawFd, fd2: RawFd, flags: OFlag) -> Result<()> {
let mut res = Ok(0);
if flags.contains(O_CLOEXEC) {
res = res
.and_then(|_| fcntl(fd1, F_SETFD(FD_CLOEXEC)))
.and_then(|_| fcntl(fd2, F_SETFD(FD_CLOEXEC)));
}
if flags.contains(O_NONBLOCK) {
res = res
.and_then(|_| fcntl(fd1, F_SETFL(O_NONBLOCK)))
.and_then(|_| fcntl(fd2, F_SETFL(O_NONBLOCK)));
}
match res {
Ok(_) => Ok(()),
Err(e) => {
let _ = close(fd1);
let _ = close(fd2);
return Err(e);
}
}
}
pub fn ftruncate(fd: RawFd, len: off_t) -> Result<()> {
Errno::result(unsafe { libc::ftruncate(fd, len) }).map(drop)
}
pub fn isatty(fd: RawFd) -> Result<bool> {
use libc;
unsafe {
// ENOTTY means `fd` is a valid file descriptor, but not a TTY, so
// we return `Ok(false)`
if libc::isatty(fd) == 1 {
Ok(true)
} else {
match Errno::last() {
Errno::ENOTTY => Ok(false),
err => Err(Error::Sys(err)),
}
}
}
}
pub fn unlink<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe {
libc::unlink(cstr.as_ptr())
}
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn chroot<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe { libc::chroot(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn fsync(fd: RawFd) -> Result<()> {
let res = unsafe { libc::fsync(fd) };
Errno::result(res).map(drop)
}
// `fdatasync(2) is in POSIX, but in libc it is only defined in `libc::notbsd`.
// TODO: exclude only Apple systems after https://github.com/rust-lang/libc/pull/211
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "emscripten"))]
#[inline]
pub fn fdatasync(fd: RawFd) -> Result<()> {
let res = unsafe { libc::fdatasync(fd) };
Errno::result(res).map(drop)
}
// POSIX requires that getuid, geteuid, getgid, getegid are always successful,
// so no need to check return value or errno. See:
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getuid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getgid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html
#[inline]
pub fn getuid() -> uid_t {
unsafe { libc::getuid() }
}
#[inline]
pub fn geteuid() -> uid_t {
unsafe { libc::geteuid() }
}
#[inline]
pub fn getgid() -> gid_t {
unsafe { libc::getgid() }
}
#[inline]
pub fn getegid() -> gid_t {
unsafe { libc::getegid() }
}
#[inline]
pub fn setuid(uid: uid_t) -> Result<()> {
let res = unsafe { libc::setuid(uid) };
Errno::result(res).map(drop)
}
#[inline]
pub fn setgid(gid: gid_t) -> Result<()> {
let res = unsafe { libc::setgid(gid) };
Errno::result(res).map(drop)
}
#[inline]
pub fn pause() -> Result<()> {
let res = unsafe { libc::pause() };
Errno::result(res).map(drop)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux {
use sys::syscall::{syscall, SYSPIVOTROOT};
use {Errno, Result, NixPath};
#[cfg(feature = "execvpe")]
use std::ffi::CString;
pub fn pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
new_root: &P1, put_old: &P2) -> Result<()> {
let res = try!(try!(new_root.with_nix_path(|new_root| {
put_old.with_nix_path(|put_old| {
unsafe {
syscall(SYSPIVOTROOT, new_root.as_ptr(), put_old.as_ptr())
}
})
})));
Errno::result(res).map(drop)
}
#[inline]
#[cfg(feature = "execvpe")]
pub fn execvpe(filename: &CString, args: &[CString], env: &[CString]) -> Result<()> {
use std::ptr;
use libc::c_char;
let mut args_p: Vec<*const c_char> = args.iter().map(|s| s.as_ptr()).collect();
args_p.push(ptr::null());
let mut env_p: Vec<*const c_char> = env.iter().map(|s| s.as_ptr()).collect();
env_p.push(ptr::null());
unsafe {
super::ffi::execvpe(filename.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
}
unistd: Add sleep(3)
//! Standard symbolic constants and types
//!
use {Errno, Error, Result, NixPath};
use fcntl::{fcntl, OFlag, O_NONBLOCK, O_CLOEXEC, FD_CLOEXEC};
use fcntl::FcntlArg::{F_SETFD, F_SETFL};
use libc::{self, c_char, c_void, c_int, c_uint, size_t, pid_t, off_t, uid_t, gid_t};
use std::mem;
use std::ffi::CString;
use std::os::unix::io::RawFd;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::linux::*;
#[derive(Clone, Copy)]
pub enum ForkResult {
Parent {
child: pid_t
},
Child
}
impl ForkResult {
#[inline]
pub fn is_child(&self) -> bool {
match *self {
ForkResult::Child => true,
_ => false
}
}
#[inline]
pub fn is_parent(&self) -> bool {
!self.is_child()
}
}
#[inline]
pub fn fork() -> Result<ForkResult> {
use self::ForkResult::*;
let res = unsafe { libc::fork() };
Errno::result(res).map(|res| match res {
0 => Child,
res => Parent { child: res }
})
}
#[inline]
pub fn getpid() -> pid_t {
unsafe { libc::getpid() } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn getppid() -> pid_t {
unsafe { libc::getppid() } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn setpgid(pid: pid_t, pgid: pid_t) -> Result<()> {
let res = unsafe { libc::setpgid(pid, pgid) };
Errno::result(res).map(drop)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[inline]
pub fn gettid() -> pid_t {
unsafe { libc::syscall(libc::SYS_gettid) as pid_t } // no error handling, according to man page: "These functions are always successful."
}
#[inline]
pub fn dup(oldfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup(oldfd) };
Errno::result(res)
}
#[inline]
pub fn dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd> {
let res = unsafe { libc::dup2(oldfd, newfd) };
Errno::result(res)
}
pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
dup3_polyfill(oldfd, newfd, flags)
}
#[inline]
fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
if oldfd == newfd {
return Err(Error::Sys(Errno::EINVAL));
}
let fd = try!(dup2(oldfd, newfd));
if flags.contains(O_CLOEXEC) {
if let Err(e) = fcntl(fd, F_SETFD(FD_CLOEXEC)) {
let _ = close(fd);
return Err(e);
}
}
Ok(fd)
}
#[inline]
pub fn chdir<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe { libc::chdir(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn chown<P: ?Sized + NixPath>(path: &P, owner: Option<uid_t>, group: Option<gid_t>) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
// We use `0 - 1` to get `-1 : {u,g}id_t` which is specified as the no-op value for chown(3).
unsafe { libc::chown(cstr.as_ptr(), owner.unwrap_or(0 - 1), group.unwrap_or(0 - 1)) }
}));
Errno::result(res).map(drop)
}
fn to_exec_array(args: &[CString]) -> Vec<*const c_char> {
use std::ptr;
use libc::c_char;
let mut args_p: Vec<*const c_char> = args.iter().map(|s| s.as_ptr()).collect();
args_p.push(ptr::null());
args_p
}
#[inline]
pub fn execv(path: &CString, argv: &[CString]) -> Result<()> {
let args_p = to_exec_array(argv);
unsafe {
libc::execv(path.as_ptr(), args_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
#[inline]
pub fn execve(path: &CString, args: &[CString], env: &[CString]) -> Result<()> {
let args_p = to_exec_array(args);
let env_p = to_exec_array(env);
unsafe {
libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
#[inline]
pub fn execvp(filename: &CString, args: &[CString]) -> Result<()> {
let args_p = to_exec_array(args);
unsafe {
libc::execvp(filename.as_ptr(), args_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> {
let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) };
Errno::result(res).map(drop)
}
pub fn sethostname(name: &[u8]) -> Result<()> {
// Handle some differences in type of the len arg across platforms.
cfg_if! {
if #[cfg(any(target_os = "macos", target_os = "ios"))] {
type sethostname_len_t = c_int;
} else {
type sethostname_len_t = size_t;
}
}
let ptr = name.as_ptr() as *const c_char;
let len = name.len() as sethostname_len_t;
let res = unsafe { libc::sethostname(ptr, len) };
Errno::result(res).map(drop)
}
pub fn gethostname(name: &mut [u8]) -> Result<()> {
let ptr = name.as_mut_ptr() as *mut c_char;
let len = name.len() as size_t;
let res = unsafe { libc::gethostname(ptr, len) };
Errno::result(res).map(drop)
}
pub fn close(fd: RawFd) -> Result<()> {
let res = unsafe { libc::close(fd) };
Errno::result(res).map(drop)
}
pub fn read(fd: RawFd, buf: &mut [u8]) -> Result<usize> {
let res = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) };
Errno::result(res).map(|r| r as usize)
}
pub fn write(fd: RawFd, buf: &[u8]) -> Result<usize> {
let res = unsafe { libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) };
Errno::result(res).map(|r| r as usize)
}
pub fn pipe() -> Result<(RawFd, RawFd)> {
unsafe {
let mut fds: [c_int; 2] = mem::uninitialized();
let res = libc::pipe(fds.as_mut_ptr());
try!(Errno::result(res));
Ok((fds[0], fds[1]))
}
}
pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> {
unsafe {
let mut fds: [c_int; 2] = mem::uninitialized();
let res = libc::pipe(fds.as_mut_ptr());
try!(Errno::result(res));
try!(pipe2_setflags(fds[0], fds[1], flags));
Ok((fds[0], fds[1]))
}
}
fn pipe2_setflags(fd1: RawFd, fd2: RawFd, flags: OFlag) -> Result<()> {
let mut res = Ok(0);
if flags.contains(O_CLOEXEC) {
res = res
.and_then(|_| fcntl(fd1, F_SETFD(FD_CLOEXEC)))
.and_then(|_| fcntl(fd2, F_SETFD(FD_CLOEXEC)));
}
if flags.contains(O_NONBLOCK) {
res = res
.and_then(|_| fcntl(fd1, F_SETFL(O_NONBLOCK)))
.and_then(|_| fcntl(fd2, F_SETFL(O_NONBLOCK)));
}
match res {
Ok(_) => Ok(()),
Err(e) => {
let _ = close(fd1);
let _ = close(fd2);
return Err(e);
}
}
}
pub fn ftruncate(fd: RawFd, len: off_t) -> Result<()> {
Errno::result(unsafe { libc::ftruncate(fd, len) }).map(drop)
}
pub fn isatty(fd: RawFd) -> Result<bool> {
use libc;
unsafe {
// ENOTTY means `fd` is a valid file descriptor, but not a TTY, so
// we return `Ok(false)`
if libc::isatty(fd) == 1 {
Ok(true)
} else {
match Errno::last() {
Errno::ENOTTY => Ok(false),
err => Err(Error::Sys(err)),
}
}
}
}
pub fn unlink<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe {
libc::unlink(cstr.as_ptr())
}
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn chroot<P: ?Sized + NixPath>(path: &P) -> Result<()> {
let res = try!(path.with_nix_path(|cstr| {
unsafe { libc::chroot(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
#[inline]
pub fn fsync(fd: RawFd) -> Result<()> {
let res = unsafe { libc::fsync(fd) };
Errno::result(res).map(drop)
}
// `fdatasync(2) is in POSIX, but in libc it is only defined in `libc::notbsd`.
// TODO: exclude only Apple systems after https://github.com/rust-lang/libc/pull/211
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "emscripten"))]
#[inline]
pub fn fdatasync(fd: RawFd) -> Result<()> {
let res = unsafe { libc::fdatasync(fd) };
Errno::result(res).map(drop)
}
// POSIX requires that getuid, geteuid, getgid, getegid are always successful,
// so no need to check return value or errno. See:
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getuid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getgid.html
// - http://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html
#[inline]
pub fn getuid() -> uid_t {
unsafe { libc::getuid() }
}
#[inline]
pub fn geteuid() -> uid_t {
unsafe { libc::geteuid() }
}
#[inline]
pub fn getgid() -> gid_t {
unsafe { libc::getgid() }
}
#[inline]
pub fn getegid() -> gid_t {
unsafe { libc::getegid() }
}
#[inline]
pub fn setuid(uid: uid_t) -> Result<()> {
let res = unsafe { libc::setuid(uid) };
Errno::result(res).map(drop)
}
#[inline]
pub fn setgid(gid: gid_t) -> Result<()> {
let res = unsafe { libc::setgid(gid) };
Errno::result(res).map(drop)
}
#[inline]
pub fn pause() -> Result<()> {
let res = unsafe { libc::pause() };
Errno::result(res).map(drop)
}
#[inline]
// Per POSIX, does not fail:
// http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html#tag_03_705_05
pub fn sleep(seconds: libc::c_uint) -> c_uint {
unsafe { libc::sleep(seconds) }
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux {
use sys::syscall::{syscall, SYSPIVOTROOT};
use {Errno, Result, NixPath};
#[cfg(feature = "execvpe")]
use std::ffi::CString;
pub fn pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
new_root: &P1, put_old: &P2) -> Result<()> {
let res = try!(try!(new_root.with_nix_path(|new_root| {
put_old.with_nix_path(|put_old| {
unsafe {
syscall(SYSPIVOTROOT, new_root.as_ptr(), put_old.as_ptr())
}
})
})));
Errno::result(res).map(drop)
}
#[inline]
#[cfg(feature = "execvpe")]
pub fn execvpe(filename: &CString, args: &[CString], env: &[CString]) -> Result<()> {
use std::ptr;
use libc::c_char;
let mut args_p: Vec<*const c_char> = args.iter().map(|s| s.as_ptr()).collect();
args_p.push(ptr::null());
let mut env_p: Vec<*const c_char> = env.iter().map(|s| s.as_ptr()).collect();
env_p.push(ptr::null());
unsafe {
super::ffi::execvpe(filename.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::Sys(Errno::last()))
}
}
|
//! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use glfw;
use std::libc;
use std::io::timer::Timer;
use std::num::Zero;
use std::hashmap::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use extra::time;
use extra::arc::RWArc;
use gl;
use gl::types::*;
use stb_image::image::*;
use nalgebra::na::{Vec2, Vec3, Vec4};
use nalgebra::na;
use camera::{Camera, ArcBall};
use object::Object;
use line_renderer::LineRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use builtin::ObjectMaterial;
use builtin::loader;
use event;
use loader::obj;
use loader::mtl::MtlMaterial;
use light::{Light, Absolute, StickToCamera};
mod error;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window<'a> {
priv window: glfw::Window,
priv max_ms_per_frame: Option<u64>,
priv objects: ~[Object],
priv camera: &'a mut Camera,
priv light_mode: Light,
priv wireframe_mode: bool,
priv geometries: HashMap<~str, Rc<RefCell<Mesh>>>,
priv background: Vec3<GLfloat>,
priv line_renderer: LineRenderer,
priv framebuffer_manager: FramebufferManager,
priv post_processing: Option<&'a mut PostProcessingEffect>,
priv post_process_render_target: RenderTarget,
priv events: RWArc<~[event::Event]>,
priv object_material: Rc<RefCell<~Material>>
}
impl<'a> Window<'a> {
/// Access the glfw window.
pub fn glfw_window<'r>(&'r self) -> &'r glfw::Window {
&self.window
}
/// Sets the current processing effect.
pub fn set_post_processing_effect(&mut self, effect: Option<&'a mut PostProcessingEffect>) {
self.post_processing = effect;
}
/// The window width.
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The current camera.
pub fn camera<'b>(&'b self) -> &'b &'a mut Camera {
&'b self.camera
}
/// The current camera.
pub fn set_camera(&mut self, camera: &'a mut Camera) {
let (w, h) = self.window.get_size();
self.camera = camera;
self.camera.handle_event(&self.window, &event::FramebufferSize(w as f32, h as f32));
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Closes the window.
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
pub fn show(&mut self) {
self.window.show()
}
/// Switch on or off wireframe rendering mode. When set to `true`, everything in the scene will
/// be drawn using wireframes. Wireframe rendering mode cannot be enabled on a per-object basis.
pub fn set_wireframe_mode(&mut self, mode: bool) {
self.wireframe_mode = mode;
}
/// Sets the background color.
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
/// Adds a line to be drawn during the next frame.
pub fn draw_line(&mut self, a: &Vec3<f32>, b: &Vec3<f32>, color: &Vec3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
/// Removes an object from the scene.
pub fn remove(&mut self, o: Object) {
match self.objects.iter().rposition(|e| o == *e) {
Some(i) => {
// XXX: release textures and buffers if nobody else use them
self.objects.swap_remove(i);
},
None => { }
}
}
/// Loads a mesh from an obj file located at `path` and registers its geometry as
/// `geometry_name`.
pub fn load_obj(&mut self, path: &Path, mtl_dir: &Path, geometry_name: &str) -> ~[(~str, Rc<RefCell<Mesh>>, Option<MtlMaterial>)] {
let ms = obj::parse_file(path, mtl_dir, geometry_name).expect("Unable to parse the obj file: " + path.as_str().unwrap());
let mut res = ~[];
for (n, m, mat) in ms.move_iter() {
let m = Rc::new(RefCell::new(m));
self.geometries.insert(geometry_name.to_owned(), m.clone());
res.push((n, m, mat));
}
res
}
/// Gets the geometry named `geometry_name` if it has been already registered.
pub fn get_mesh(&mut self, geometry_name: &str) -> Option<Rc<RefCell<Mesh>>> {
self.geometries.find(&geometry_name.to_owned()).map(|m| m.clone())
}
/// Registers the geometry `mesh` with the name `geometry_name`.
pub fn register_mesh(&mut self, geometry_name: &str, mesh: Mesh) {
self.geometries.insert(geometry_name.to_owned(), Rc::new(RefCell::new(mesh)));
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - uniform scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: GLfloat) -> ~[Object] {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let objs = self.load_obj(path, mtl_dir, path.as_str().unwrap());
println!("Parsing complete.");
let mut res = ~[];
for (_, mesh, mtl) in objs.move_iter() {
let mut object = Object::new(
mesh,
1.0, 1.0, 1.0,
tex.clone(),
scale, scale, scale,
self.object_material.clone()
);
match mtl {
None => { },
Some(mtl) => {
object.set_color(mtl.diffuse.x, mtl.diffuse.y, mtl.diffuse.z);
mtl.diffuse_texture.as_ref().map(|t| {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
});
mtl.ambiant_texture.map(|t| {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
});
}
}
res.push(object.clone());
self.objects.push(object);
}
res
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Mesh, scale: GLfloat) -> Object {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let res = Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add(&mut self, geometry_name: &str, scale: GLfloat) -> Option<Object> {
self.geometries.find(&geometry_name.to_owned()).map(|m| {
let res = Object::new(
m.clone(),
1.0, 1.0, 1.0,
TextureManager::get_global_manager(|tm| tm.get_default()),
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
})
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cube").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
wx, wy, wz,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"sphere").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, r / 0.5, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cone").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cylinder").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"capsule").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a double-sided quad to the scene. The cylinder is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width
/// * `h` - the quad height
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, wsubdivs: uint, hsubdivs: uint) -> Object {
assert!(wsubdivs > 0 && hsubdivs > 0, "The number of subdivisions cannot be zero");
let wstep = w / (wsubdivs as GLfloat);
let hstep = h / (hsubdivs as GLfloat);
let wtexstep = 1.0 / (wsubdivs as GLfloat);
let htexstep = 1.0 / (hsubdivs as GLfloat);
let cw = w / 2.0;
let ch = h / 2.0;
let mut vertices = ~[];
let mut normals = ~[];
let mut triangles = ~[];
let mut tex_coords = ~[];
// create the vertices
for i in range(0u, hsubdivs + 1) {
for j in range(0u, wsubdivs + 1) {
vertices.push(Vec3::new(j as GLfloat * wstep - cw, i as GLfloat * hstep - ch, 0.0));
tex_coords.push(Vec2::new(1.0 - j as GLfloat * wtexstep, 1.0 - i as GLfloat * htexstep))
}
}
// create the normals
((hsubdivs + 1) * (wsubdivs + 1)).times(|| {
{ normals.push(Vec3::new(1.0, 0.0, 0.0)) }
});
// create triangles
fn dl_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new((i + 1) * ws + j, i * ws + j, (i + 1) * ws + j + 1)
}
fn ur_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new(i * ws + j, i * ws + (j + 1), (i + 1) * ws + j + 1)
}
for i in range(0u, hsubdivs) {
for j in range(0u, wsubdivs) {
// build two triangles...
triangles.push(dl_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
triangles.push(ur_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
}
}
let mesh = Mesh::new(vertices, triangles, Some(normals), Some(tex_coords), true);
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
1.0, 1.0, 1.0,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Converts a 3d point to 2d screen coordinates.
pub fn project(&self, world_coord: &Vec3<f32>) -> Vec2<f32> {
let h_world_coord = na::to_homogeneous(world_coord);
let h_normalized_coord = self.camera.transformation() * h_world_coord;
let normalized_coord: Vec3<f32> = na::from_homogeneous(&h_normalized_coord);
let (w, h) = self.window.get_size();
Vec2::new(
(1.0 + normalized_coord.x) * (w as f32) / 2.0,
(1.0 + normalized_coord.y) * (h as f32) / 2.0)
}
/// Converts a point in 2d screen coordinates to a ray (a 3d position and a direction).
pub fn unproject(&self, window_coord: &Vec2<f32>) -> (Vec3<f32>, Vec3<f32>) {
let (w, h) = self.window.get_size();
let normalized_coord = Vec2::new(
2.0 * window_coord.x / (w as f32) - 1.0,
2.0 * -window_coord.y / (h as f32) + 1.0);
let normalized_begin = Vec4::new(normalized_coord.x, normalized_coord.y, -1.0, 1.0);
let normalized_end = Vec4::new(normalized_coord.x, normalized_coord.y, 1.0, 1.0);
let cam = self.camera.inv_transformation();
let h_unprojected_begin = cam * normalized_begin;
let h_unprojected_end = cam * normalized_end;
let unprojected_begin: Vec3<f32> = na::from_homogeneous(&h_unprojected_begin);
let unprojected_end: Vec3<f32> = na::from_homogeneous(&h_unprojected_end);
(unprojected_begin, na::normalize(&(unprojected_end - unprojected_begin)))
}
/// The list of objects on the scene.
pub fn objects<'r>(&'r self) -> &'r [Object] {
let res: &'r [Object] = self.objects;
res
}
/// The list of objects on the scene.
pub fn objects_mut<'r>(&'r mut self) -> &'r mut [Object] {
let res: &'r mut [Object] = self.objects;
res
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline(always)]
pub fn poll_events(&mut self, events_handler: |&mut Window, &event::Event| -> bool) {
// redispatch them
let events = self.events.clone();
events.read(|es| {
for e in es.iter() {
if events_handler(self, e) {
match *e {
event::KeyReleased(key) => {
if key == glfw::KeyEscape {
self.close();
continue
}
},
event::FramebufferSize(w, h) => {
self.update_viewport(w, h);
},
_ => { }
}
self.camera.handle_event(&self.window, e);
}
}
});
// clear the events collector
self.events.write(|c| c.clear());
}
/// Starts an infinite loop polling events, calling an user-defined callback, and drawing the
/// scene.
pub fn render_loop(&mut self, callback: |&mut Window| -> ()) {
let mut timer = Timer::new().unwrap();
let mut curr = time::precise_time_ns();
while !self.window.should_close() {
// collect events
glfw::poll_events();
callback(self);
self.poll_events(|_, _| true);
self.draw(&mut curr, &mut timer)
}
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
// FIXME /// The camera used to render the scene.
// FIXME pub fn camera(&self) -> &Camera {
// FIXME self.camera.clone()
// FIXME }
/// Opens a window and hide it. Once the window is created and before any event pooling, a
/// user-defined callback is called once.
///
/// This method contains an infinite loop and returns when the window is closed.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_hidden(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), true, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window. Once the window is created and before any event pooling,
/// a user-defined callback is called once.
///
/// This method contains an infinite loop and returns when the window is closed.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window with a custom size. Once the window is created and before any event pooling,
/// a user-defined callback is called once.
///
/// This method contains an infinite loop and returns when the window is closed.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_size(title: &str, width: u32, height: u32, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, width, height, callback)
}
fn do_spawn(title: ~str, hide: bool, width: u32, height: u32, callback: proc(&mut Window)) {
glfw::set_error_callback(~ErrorCallback);
do glfw::start {
let window = glfw::Window::create(width, height, title, glfw::Windowed).expect("Unable to open a glfw window.");
window.make_context_current();
verify!(gl::load_with(glfw::get_proc_address));
init_gl();
let builtins = loader::load();
let mut camera = ArcBall::new(-Vec3::z(), Zero::zero());
let mut usr_window = Window {
max_ms_per_frame: None,
window: window,
objects: ~[],
camera: &mut camera as &mut Camera,
light_mode: Absolute(Vec3::new(0.0, 10.0, 0.0)),
wireframe_mode: false,
geometries: builtins,
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
post_processing: None,
post_process_render_target: FramebufferManager::new_render_target(width as uint, height as uint),
framebuffer_manager: FramebufferManager::new(),
events: RWArc::new(~[]),
object_material: Rc::new(RefCell::new(~ObjectMaterial::new() as ~Material))
};
// setup callbacks
let collector = usr_window.events.clone();
usr_window.window.set_framebuffer_size_callback(~FramebufferSizeCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_key_callback(~KeyCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_mouse_button_callback(~MouseButtonCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_cursor_pos_callback(~CursorPosCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_scroll_callback(~ScrollCallback::new(collector));
let (w, h) = usr_window.window.get_size();
usr_window.camera.handle_event(
&usr_window.window,
&event::FramebufferSize(w as f32, h as f32));
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
usr_window.set_light(usr_window.light_mode);
callback(&mut usr_window);
}
}
fn draw(&mut self, curr: &mut u64, timer: &mut Timer) {
self.camera.update(&self.window);
match self.light_mode {
StickToCamera => self.set_light(StickToCamera),
_ => { }
}
if self.post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
// TODO: change to pass_iter when I learn the lingo
for pass in range(0u, self.camera.num_passes()) {
self.camera.start_pass(pass, &self.window);
self.render_scene(pass);
}
self.camera.render_complete(&self.window);
let w = self.width();
let h = self.height();
let (znear, zfar) = self.camera.clip_planes();
match self.post_processing {
Some(ref mut p) => {
// remove the wireframe mode
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - *curr) / 1000000;
if elapsed < ms {
timer.sleep(ms - elapsed);
}
}
}
*curr = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
}
fn render_scene(&mut self, pass: uint) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, self.camera);
}
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE));
}
else {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
for o in self.objects.iter() {
o.render(pass, self.camera, &self.light_mode)
}
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0 as i32, 0 as i32, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
}
//
// Cursor Pos Callback
//
struct ScrollCallback {
collector: RWArc<~[event::Event]>
}
impl ScrollCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> ScrollCallback {
ScrollCallback {
collector: collector
}
}
}
impl glfw::ScrollCallback for ScrollCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::Scroll(x as f32, y as f32)))
}
}
//
// Cursor Pos Callback
//
struct CursorPosCallback {
collector: RWArc<~[event::Event]>
}
impl CursorPosCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> CursorPosCallback {
CursorPosCallback {
collector: collector
}
}
}
impl glfw::CursorPosCallback for CursorPosCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::CursorPos(x as f32, y as f32)))
}
}
//
// Mouse Button Callback
//
struct MouseButtonCallback {
collector: RWArc<~[event::Event]>
}
impl MouseButtonCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> MouseButtonCallback {
MouseButtonCallback {
collector: collector
}
}
}
impl glfw::MouseButtonCallback for MouseButtonCallback {
fn call(&self,
_: &glfw::Window,
button: glfw::MouseButton,
action: glfw::Action,
mods: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::ButtonPressed(button, mods)))
}
else {
self.collector.write(|c| c.push(event::ButtonReleased(button, mods)))
}
}
}
//
// Key callback
//
struct KeyCallback {
collector: RWArc<~[event::Event]>
}
impl KeyCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> KeyCallback {
KeyCallback {
collector: collector
}
}
}
impl glfw::KeyCallback for KeyCallback {
fn call(&self,
_: &glfw::Window,
key: glfw::Key,
_: libc::c_int,
action: glfw::Action,
_: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::KeyPressed(key)))
}
else {
self.collector.write(|c| c.push(event::KeyReleased(key)))
}
}
}
//
// Framebuffer callback
//
struct FramebufferSizeCallback {
collector: RWArc<~[event::Event]>
}
impl FramebufferSizeCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> FramebufferSizeCallback {
FramebufferSizeCallback {
collector: collector
}
}
}
impl glfw::FramebufferSizeCallback for FramebufferSizeCallback {
fn call(&self, _: &glfw::Window, w: i32, h: i32) {
self.collector.write(|c| c.push(event::FramebufferSize(w as f32, h as f32)))
}
}
//
// Error callback
//
struct ErrorCallback;
impl glfw::ErrorCallback for ErrorCallback {
fn call(&self, _: glfw::Error, description: ~str) {
println!("Kiss3d Error: {}", description);
}
}
Fix doc: Window::spawn* does not start the infinite loop any more.
//! The kiss3d window.
/*
* FIXME: this file is too big. Some heavy refactoring need to be done here.
*/
use glfw;
use std::libc;
use std::io::timer::Timer;
use std::num::Zero;
use std::hashmap::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use extra::time;
use extra::arc::RWArc;
use gl;
use gl::types::*;
use stb_image::image::*;
use nalgebra::na::{Vec2, Vec3, Vec4};
use nalgebra::na;
use camera::{Camera, ArcBall};
use object::Object;
use line_renderer::LineRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh, Material};
use builtin::ObjectMaterial;
use builtin::loader;
use event;
use loader::obj;
use loader::mtl::MtlMaterial;
use light::{Light, Absolute, StickToCamera};
mod error;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window<'a> {
priv window: glfw::Window,
priv max_ms_per_frame: Option<u64>,
priv objects: ~[Object],
priv camera: &'a mut Camera,
priv light_mode: Light,
priv wireframe_mode: bool,
priv geometries: HashMap<~str, Rc<RefCell<Mesh>>>,
priv background: Vec3<GLfloat>,
priv line_renderer: LineRenderer,
priv framebuffer_manager: FramebufferManager,
priv post_processing: Option<&'a mut PostProcessingEffect>,
priv post_process_render_target: RenderTarget,
priv events: RWArc<~[event::Event]>,
priv object_material: Rc<RefCell<~Material>>
}
impl<'a> Window<'a> {
/// Access the glfw window.
pub fn glfw_window<'r>(&'r self) -> &'r glfw::Window {
&self.window
}
/// Sets the current processing effect.
pub fn set_post_processing_effect(&mut self, effect: Option<&'a mut PostProcessingEffect>) {
self.post_processing = effect;
}
/// The window width.
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
/// The current camera.
pub fn camera<'b>(&'b self) -> &'b &'a mut Camera {
&'b self.camera
}
/// The current camera.
pub fn set_camera(&mut self, camera: &'a mut Camera) {
let (w, h) = self.window.get_size();
self.camera = camera;
self.camera.handle_event(&self.window, &event::FramebufferSize(w as f32, h as f32));
}
/// Sets the maximum number of frames per second. Cannot be 0. `None` means there is no limit.
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_ms_per_frame = fps.map(|f| { assert!(f != 0); 1000 / f })
}
/// Closes the window.
pub fn close(&mut self) {
self.window.set_should_close(true)
}
/// Hides the window, without closing it. Use `show` to make it visible again.
pub fn hide(&mut self) {
self.window.hide()
}
/// Makes the window visible. Use `hide` to hide it.
pub fn show(&mut self) {
self.window.show()
}
/// Switch on or off wireframe rendering mode. When set to `true`, everything in the scene will
/// be drawn using wireframes. Wireframe rendering mode cannot be enabled on a per-object basis.
pub fn set_wireframe_mode(&mut self, mode: bool) {
self.wireframe_mode = mode;
}
/// Sets the background color.
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
/// Adds a line to be drawn during the next frame.
pub fn draw_line(&mut self, a: &Vec3<f32>, b: &Vec3<f32>, color: &Vec3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
/// Removes an object from the scene.
pub fn remove(&mut self, o: Object) {
match self.objects.iter().rposition(|e| o == *e) {
Some(i) => {
// XXX: release textures and buffers if nobody else use them
self.objects.swap_remove(i);
},
None => { }
}
}
/// Loads a mesh from an obj file located at `path` and registers its geometry as
/// `geometry_name`.
pub fn load_obj(&mut self, path: &Path, mtl_dir: &Path, geometry_name: &str) -> ~[(~str, Rc<RefCell<Mesh>>, Option<MtlMaterial>)] {
let ms = obj::parse_file(path, mtl_dir, geometry_name).expect("Unable to parse the obj file: " + path.as_str().unwrap());
let mut res = ~[];
for (n, m, mat) in ms.move_iter() {
let m = Rc::new(RefCell::new(m));
self.geometries.insert(geometry_name.to_owned(), m.clone());
res.push((n, m, mat));
}
res
}
/// Gets the geometry named `geometry_name` if it has been already registered.
pub fn get_mesh(&mut self, geometry_name: &str) -> Option<Rc<RefCell<Mesh>>> {
self.geometries.find(&geometry_name.to_owned()).map(|m| m.clone())
}
/// Registers the geometry `mesh` with the name `geometry_name`.
pub fn register_mesh(&mut self, geometry_name: &str, mesh: Mesh) {
self.geometries.insert(geometry_name.to_owned(), Rc::new(RefCell::new(mesh)));
}
/// Adds an obj model to the scene.
///
/// # Arguments
/// * `path` - relative path to the obj file.
/// * `scale` - uniform scale to apply to the model.
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: GLfloat) -> ~[Object] {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let objs = self.load_obj(path, mtl_dir, path.as_str().unwrap());
println!("Parsing complete.");
let mut res = ~[];
for (_, mesh, mtl) in objs.move_iter() {
let mut object = Object::new(
mesh,
1.0, 1.0, 1.0,
tex.clone(),
scale, scale, scale,
self.object_material.clone()
);
match mtl {
None => { },
Some(mtl) => {
object.set_color(mtl.diffuse.x, mtl.diffuse.y, mtl.diffuse.z);
mtl.diffuse_texture.as_ref().map(|t| {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
});
mtl.ambiant_texture.map(|t| {
let mut tpath = mtl_dir.clone();
tpath.push(t.as_slice());
object.set_texture(&tpath, tpath.as_str().unwrap())
});
}
}
res.push(object.clone());
self.objects.push(object);
}
res
}
/// Adds an unnamed mesh to the scene.
pub fn add_mesh(&mut self, mesh: Mesh, scale: GLfloat) -> Object {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let res = Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
}
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add(&mut self, geometry_name: &str, scale: GLfloat) -> Option<Object> {
self.geometries.find(&geometry_name.to_owned()).map(|m| {
let res = Object::new(
m.clone(),
1.0, 1.0, 1.0,
TextureManager::get_global_manager(|tm| tm.get_default()),
scale, scale, scale,
self.object_material.clone());
self.objects.push(res.clone());
res
})
}
/// Adds a cube to the scene. The cube is initially axis-aligned and centered at (0, 0, 0).
///
/// # Arguments
/// * `wx` - the cube extent along the z axis
/// * `wy` - the cube extent along the y axis
/// * `wz` - the cube extent along the z axis
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cube").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
wx, wy, wz,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a sphere to the scene. The sphere is initially centered at (0, 0, 0).
///
/// # Arguments
/// * `r` - the sphere radius
pub fn add_sphere(&mut self, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"sphere").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, r / 0.5, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_cone(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cone").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a cylinder to the scene. The cylinder is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the cylinder height
/// * `r` - the cylinder base radius
pub fn add_cylinder(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"cylinder").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a capsule to the scene. The capsule is initially centered at (0, 0, 0) and has its
/// principal axis aligned with the `y` axis.
///
/// # Arguments
/// * `h` - the capsule height
/// * `r` - the capsule caps radius
pub fn add_capsule(&mut self, h: GLfloat, r: GLfloat) -> Object {
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
let geom = self.geometries.find(&~"capsule").unwrap();
Object::new(
geom.clone(),
1.0, 1.0, 1.0,
tex,
r / 0.5, h, r / 0.5,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
/// Adds a double-sided quad to the scene. The cylinder is initially centered at (0, 0, 0). The
/// quad itself is composed of a user-defined number of triangles regularly spaced on a grid.
/// This is the main way to draw height maps.
///
/// # Arguments
/// * `w` - the quad width
/// * `h` - the quad height
/// * `wsubdivs` - number of horizontal subdivisions. This correspond to the number of squares
/// which will be placed horizontally on each line. Must not be `0`
/// * `hsubdivs` - number of vertical subdivisions. This correspond to the number of squares
/// which will be placed vertically on each line. Must not be `0`
/// update.
pub fn add_quad(&mut self, w: f32, h: f32, wsubdivs: uint, hsubdivs: uint) -> Object {
assert!(wsubdivs > 0 && hsubdivs > 0, "The number of subdivisions cannot be zero");
let wstep = w / (wsubdivs as GLfloat);
let hstep = h / (hsubdivs as GLfloat);
let wtexstep = 1.0 / (wsubdivs as GLfloat);
let htexstep = 1.0 / (hsubdivs as GLfloat);
let cw = w / 2.0;
let ch = h / 2.0;
let mut vertices = ~[];
let mut normals = ~[];
let mut triangles = ~[];
let mut tex_coords = ~[];
// create the vertices
for i in range(0u, hsubdivs + 1) {
for j in range(0u, wsubdivs + 1) {
vertices.push(Vec3::new(j as GLfloat * wstep - cw, i as GLfloat * hstep - ch, 0.0));
tex_coords.push(Vec2::new(1.0 - j as GLfloat * wtexstep, 1.0 - i as GLfloat * htexstep))
}
}
// create the normals
((hsubdivs + 1) * (wsubdivs + 1)).times(|| {
{ normals.push(Vec3::new(1.0, 0.0, 0.0)) }
});
// create triangles
fn dl_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new((i + 1) * ws + j, i * ws + j, (i + 1) * ws + j + 1)
}
fn ur_triangle(i: u32, j: u32, ws: u32) -> Vec3<GLuint> {
Vec3::new(i * ws + j, i * ws + (j + 1), (i + 1) * ws + j + 1)
}
for i in range(0u, hsubdivs) {
for j in range(0u, wsubdivs) {
// build two triangles...
triangles.push(dl_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
triangles.push(ur_triangle(i as GLuint, j as GLuint, (wsubdivs + 1) as GLuint));
}
}
let mesh = Mesh::new(vertices, triangles, Some(normals), Some(tex_coords), true);
// FIXME: this weird block indirection are here because of Rust issue #6248
let res = {
let tex = TextureManager::get_global_manager(|tm| tm.get_default());
Object::new(
Rc::new(RefCell::new(mesh)),
1.0, 1.0, 1.0,
tex,
1.0, 1.0, 1.0,
self.object_material.clone())
};
self.objects.push(res.clone());
res
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Converts a 3d point to 2d screen coordinates.
pub fn project(&self, world_coord: &Vec3<f32>) -> Vec2<f32> {
let h_world_coord = na::to_homogeneous(world_coord);
let h_normalized_coord = self.camera.transformation() * h_world_coord;
let normalized_coord: Vec3<f32> = na::from_homogeneous(&h_normalized_coord);
let (w, h) = self.window.get_size();
Vec2::new(
(1.0 + normalized_coord.x) * (w as f32) / 2.0,
(1.0 + normalized_coord.y) * (h as f32) / 2.0)
}
/// Converts a point in 2d screen coordinates to a ray (a 3d position and a direction).
pub fn unproject(&self, window_coord: &Vec2<f32>) -> (Vec3<f32>, Vec3<f32>) {
let (w, h) = self.window.get_size();
let normalized_coord = Vec2::new(
2.0 * window_coord.x / (w as f32) - 1.0,
2.0 * -window_coord.y / (h as f32) + 1.0);
let normalized_begin = Vec4::new(normalized_coord.x, normalized_coord.y, -1.0, 1.0);
let normalized_end = Vec4::new(normalized_coord.x, normalized_coord.y, 1.0, 1.0);
let cam = self.camera.inv_transformation();
let h_unprojected_begin = cam * normalized_begin;
let h_unprojected_end = cam * normalized_end;
let unprojected_begin: Vec3<f32> = na::from_homogeneous(&h_unprojected_begin);
let unprojected_end: Vec3<f32> = na::from_homogeneous(&h_unprojected_end);
(unprojected_begin, na::normalize(&(unprojected_end - unprojected_begin)))
}
/// The list of objects on the scene.
pub fn objects<'r>(&'r self) -> &'r [Object] {
let res: &'r [Object] = self.objects;
res
}
/// The list of objects on the scene.
pub fn objects_mut<'r>(&'r mut self) -> &'r mut [Object] {
let res: &'r mut [Object] = self.objects;
res
}
/// Poll events and pass them to a user-defined function. If the function returns `true`, the
/// default engine event handler (camera, framebuffer size, etc.) is executed, if it returns
/// `false`, the default engine event handler is not executed. Return `false` if you want to
/// override the default engine behaviour.
#[inline(always)]
pub fn poll_events(&mut self, events_handler: |&mut Window, &event::Event| -> bool) {
// redispatch them
let events = self.events.clone();
events.read(|es| {
for e in es.iter() {
if events_handler(self, e) {
match *e {
event::KeyReleased(key) => {
if key == glfw::KeyEscape {
self.close();
continue
}
},
event::FramebufferSize(w, h) => {
self.update_viewport(w, h);
},
_ => { }
}
self.camera.handle_event(&self.window, e);
}
}
});
// clear the events collector
self.events.write(|c| c.clear());
}
/// Starts an infinite loop polling events, calling an user-defined callback, and drawing the
/// scene.
pub fn render_loop(&mut self, callback: |&mut Window| -> ()) {
let mut timer = Timer::new().unwrap();
let mut curr = time::precise_time_ns();
while !self.window.should_close() {
// collect events
glfw::poll_events();
callback(self);
self.poll_events(|_, _| true);
self.draw(&mut curr, &mut timer)
}
}
/// Sets the light mode. Only one light is supported.
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
// FIXME /// The camera used to render the scene.
// FIXME pub fn camera(&self) -> &Camera {
// FIXME self.camera.clone()
// FIXME }
/// Opens a window, hide it then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_hidden(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), true, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn(title: &str, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, DEFAULT_WIDTH, DEFAULT_HEIGHT, callback)
}
/// Opens a window with a custom size then calls a user-defined procedure.
///
/// # Arguments
/// * `title` - the window title
/// * `callback` - a callback called once the window has been created
pub fn spawn_size(title: &str, width: u32, height: u32, callback: proc(&mut Window)) {
Window::do_spawn(title.to_owned(), false, width, height, callback)
}
fn do_spawn(title: ~str, hide: bool, width: u32, height: u32, callback: proc(&mut Window)) {
glfw::set_error_callback(~ErrorCallback);
do glfw::start {
let window = glfw::Window::create(width, height, title, glfw::Windowed).expect("Unable to open a glfw window.");
window.make_context_current();
verify!(gl::load_with(glfw::get_proc_address));
init_gl();
let builtins = loader::load();
let mut camera = ArcBall::new(-Vec3::z(), Zero::zero());
let mut usr_window = Window {
max_ms_per_frame: None,
window: window,
objects: ~[],
camera: &mut camera as &mut Camera,
light_mode: Absolute(Vec3::new(0.0, 10.0, 0.0)),
wireframe_mode: false,
geometries: builtins,
background: Vec3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
post_processing: None,
post_process_render_target: FramebufferManager::new_render_target(width as uint, height as uint),
framebuffer_manager: FramebufferManager::new(),
events: RWArc::new(~[]),
object_material: Rc::new(RefCell::new(~ObjectMaterial::new() as ~Material))
};
// setup callbacks
let collector = usr_window.events.clone();
usr_window.window.set_framebuffer_size_callback(~FramebufferSizeCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_key_callback(~KeyCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_mouse_button_callback(~MouseButtonCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_cursor_pos_callback(~CursorPosCallback::new(collector));
let collector = usr_window.events.clone();
usr_window.window.set_scroll_callback(~ScrollCallback::new(collector));
let (w, h) = usr_window.window.get_size();
usr_window.camera.handle_event(
&usr_window.window,
&event::FramebufferSize(w as f32, h as f32));
if hide {
usr_window.window.hide()
}
// usr_window.framebuffer_size_callback(DEFAULT_WIDTH, DEFAULT_HEIGHT);
usr_window.set_light(usr_window.light_mode);
callback(&mut usr_window);
}
}
fn draw(&mut self, curr: &mut u64, timer: &mut Timer) {
self.camera.update(&self.window);
match self.light_mode {
StickToCamera => self.set_light(StickToCamera),
_ => { }
}
if self.post_processing.is_some() {
// if we need post-processing, render to our own frame buffer
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
// TODO: change to pass_iter when I learn the lingo
for pass in range(0u, self.camera.num_passes()) {
self.camera.start_pass(pass, &self.window);
self.render_scene(pass);
}
self.camera.render_complete(&self.window);
let w = self.width();
let h = self.height();
let (znear, zfar) = self.camera.clip_planes();
match self.post_processing {
Some(ref mut p) => {
// remove the wireframe mode
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
// switch back to the screen framebuffer …
self.framebuffer_manager.select(&FramebufferManager::screen());
// … and execute the post-process
// FIXME: use the real time value instead of 0.016!
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
// We are done: swap buffers
self.window.swap_buffers();
// Limit the fps if needed.
match self.max_ms_per_frame {
None => { },
Some(ms) => {
let elapsed = (time::precise_time_ns() - *curr) / 1000000;
if elapsed < ms {
timer.sleep(ms - elapsed);
}
}
}
*curr = time::precise_time_ns();
// self.transparent_objects.clear();
// self.opaque_objects.clear();
}
fn render_scene(&mut self, pass: uint) {
// Activate the default texture
verify!(gl::ActiveTexture(gl::TEXTURE0));
// Clear the screen to black
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, self.camera);
}
if self.wireframe_mode {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE));
}
else {
verify!(gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL));
}
for o in self.objects.iter() {
o.render(pass, self.camera, &self.light_mode)
}
}
fn update_viewport(&mut self, w: f32, h: f32) {
// Update the viewport
verify!(gl::Scissor(0 as i32, 0 as i32, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
/*
* Misc configurations
*/
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
}
//
// Cursor Pos Callback
//
struct ScrollCallback {
collector: RWArc<~[event::Event]>
}
impl ScrollCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> ScrollCallback {
ScrollCallback {
collector: collector
}
}
}
impl glfw::ScrollCallback for ScrollCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::Scroll(x as f32, y as f32)))
}
}
//
// Cursor Pos Callback
//
struct CursorPosCallback {
collector: RWArc<~[event::Event]>
}
impl CursorPosCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> CursorPosCallback {
CursorPosCallback {
collector: collector
}
}
}
impl glfw::CursorPosCallback for CursorPosCallback {
fn call(&self, _: &glfw::Window, x: f64, y: f64) {
self.collector.write(|c| c.push(event::CursorPos(x as f32, y as f32)))
}
}
//
// Mouse Button Callback
//
struct MouseButtonCallback {
collector: RWArc<~[event::Event]>
}
impl MouseButtonCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> MouseButtonCallback {
MouseButtonCallback {
collector: collector
}
}
}
impl glfw::MouseButtonCallback for MouseButtonCallback {
fn call(&self,
_: &glfw::Window,
button: glfw::MouseButton,
action: glfw::Action,
mods: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::ButtonPressed(button, mods)))
}
else {
self.collector.write(|c| c.push(event::ButtonReleased(button, mods)))
}
}
}
//
// Key callback
//
struct KeyCallback {
collector: RWArc<~[event::Event]>
}
impl KeyCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> KeyCallback {
KeyCallback {
collector: collector
}
}
}
impl glfw::KeyCallback for KeyCallback {
fn call(&self,
_: &glfw::Window,
key: glfw::Key,
_: libc::c_int,
action: glfw::Action,
_: glfw::Modifiers) {
if action == glfw::Press {
self.collector.write(|c| c.push(event::KeyPressed(key)))
}
else {
self.collector.write(|c| c.push(event::KeyReleased(key)))
}
}
}
//
// Framebuffer callback
//
struct FramebufferSizeCallback {
collector: RWArc<~[event::Event]>
}
impl FramebufferSizeCallback {
pub fn new(collector: RWArc<~[event::Event]>) -> FramebufferSizeCallback {
FramebufferSizeCallback {
collector: collector
}
}
}
impl glfw::FramebufferSizeCallback for FramebufferSizeCallback {
fn call(&self, _: &glfw::Window, w: i32, h: i32) {
self.collector.write(|c| c.push(event::FramebufferSize(w as f32, h as f32)))
}
}
//
// Error callback
//
struct ErrorCallback;
impl glfw::ErrorCallback for ErrorCallback {
fn call(&self, _: glfw::Error, description: ~str) {
println!("Kiss3d Error: {}", description);
}
}
|
//! A module to handle `Writer`
use std::io::Write;
use errors::{Error, Result};
use events::Event;
/// XML writer.
///
/// Writes XML `Event`s to a `Write` implementor.
///
/// # Examples
///
/// ```rust
/// # extern crate quick_xml;
/// # fn main() {
/// use quick_xml::{Reader, Writer};
/// use quick_xml::events::{Event, BytesEnd, BytesStart};
/// use std::io::Cursor;
///
/// let xml = r#"<this_tag k1="v1" k2="v2"><child>text</child></this_tag>"#;
/// let mut reader = Reader::from_str(xml);
/// reader.trim_text(true);
/// let mut writer = Writer::new(Cursor::new(Vec::new()));
/// let mut buf = Vec::new();
/// loop {
/// match reader.read_event(&mut buf) {
/// Ok(Event::Start(ref e)) if e.name() == b"this_tag" => {
///
/// // crates a new element ... alternatively we could reuse `e` by calling
/// // `e.into_owned()`
/// let mut elem = BytesStart::owned(b"my_elem".to_vec(), "my_elem".len());
///
/// // collect existing attributes
/// elem.extend_attributes(e.attributes().map(|attr| attr.unwrap()));
///
/// // copy existing attributes, adds a new my-key="some value" attribute
/// elem.push_attribute(("my-key", "some value"));
///
/// // writes the event to the writer
/// assert!(writer.write_event(Event::Start(elem)).is_ok());
/// },
/// Ok(Event::End(ref e)) if e.name() == b"this_tag" => {
/// assert!(writer.write_event(Event::End(BytesEnd::borrowed(b"my_elem"))).is_ok());
/// },
/// Ok(Event::Eof) => break,
/// // we can either move or borrow the event to write, depending on your use-case
/// Ok(e) => assert!(writer.write_event(&e).is_ok()),
/// Err(e) => panic!("{}", e),
/// }
/// buf.clear();
/// }
///
/// let result = writer.into_inner().into_inner();
/// let expected = r#"<my_elem k1="v1" k2="v2" my-key="some value"><child>text</child></my_elem>"#;
/// assert_eq!(result, expected.as_bytes());
/// # }
/// ```
#[derive(Clone)]
pub struct Writer<W: Write> {
/// underlying writer
writer: W,
indent: Option<Indentation>,
}
impl<W: Write> Writer<W> {
/// Creates a Writer from a generic Write
pub fn new(inner: W) -> Writer<W> {
Writer {
writer: inner,
indent: None,
}
}
/// Creates a Writer with configured whitespace indents from a generic Write
pub fn new_with_indent(inner: W, indent_char: u8, indent_size: usize) -> Writer<W> {
Writer {
writer: inner,
indent: Some(Indentation::new(indent_char, indent_size)),
}
}
/// Consumes this `Writer`, returning the underlying writer.
pub fn into_inner(self) -> W {
self.writer
}
/// Get inner writer, keeping ownership
pub fn inner(&mut self) -> &mut W {
&mut self.writer
}
/// Writes the given event to the underlying writer.
pub fn write_event<'a, E: AsRef<Event<'a>>>(&mut self, event: E) -> Result<usize> {
let mut next_should_line_break = true;
let result = match *event.as_ref() {
Event::Start(ref e) => {
let result = self.write_wrapped(b"<", e, b">");
if let Some(i) = self.indent.as_mut() {
i.grow();
}
result
}
Event::End(ref e) => {
if let Some(i) = self.indent.as_mut() {
i.shrink();
}
self.write_wrapped(b"</", e, b">")
}
Event::Empty(ref e) => self.write_wrapped(b"<", e, b"/>"),
Event::Text(ref e) => {
next_should_line_break = false;
self.write(&e.escaped())
}
Event::Comment(ref e) => self.write_wrapped(b"<!--", e, b"-->"),
Event::CData(ref e) => self.write_wrapped(b"<![CDATA[", e, b"]]>"),
Event::Decl(ref e) => self.write_wrapped(b"<?", e, b"?>"),
Event::PI(ref e) => self.write_wrapped(b"<?", e, b"?>"),
Event::DocType(ref e) => self.write_wrapped(b"<!DOCTYPE", e, b">"),
Event::Eof => Ok(0),
};
if let Some(i) = self.indent.as_mut() {
i.should_line_break = next_should_line_break;
}
result
}
/// Writes bytes
#[inline]
pub fn write(&mut self, value: &[u8]) -> Result<usize> {
self.writer.write(value).map_err(Error::Io)
}
#[inline]
fn write_wrapped(&mut self, before: &[u8], value: &[u8], after: &[u8]) -> Result<usize> {
let mut wrote = 0;
if let Some(ref i) = self.indent {
if i.should_line_break {
wrote = self.writer.write(b"\n").map_err(Error::Io)?
+ self
.writer
.write(&i.indents[..i.indents_len])
.map_err(Error::Io)?;
}
}
Ok(wrote + self.write(before)? + self.write(value)? + self.write(after)?)
}
/// Manually write a newline and indentation at the proper level.
///
/// This can be used when the heuristic to line break and indent after any [Event] apart
/// from [Text] fails such as when a [Start] occurs directly after [Text].
/// This method will do nothing if `Writer` was not constructed with `new_with_indent`.
///
/// [Event]: events/enum.Event.html
/// [Text]: events/enum.Event.html#variant.Text
/// [Start]: events/enum.Event.html#variant.Start
pub fn write_indent(&mut self) -> Result<usize> {
let mut wrote = 0;
if let Some(ref i) = self.indent {
wrote = self.writer.write(b"\n").map_err(Error::Io)?
+ self
.writer
.write(&i.indents[..i.indents_len])
.map_err(Error::Io)?;
}
Ok(wrote)
}
}
#[derive(Clone)]
struct Indentation {
should_line_break: bool,
indent_char: u8,
indent_size: usize,
indents: Vec<u8>,
indents_len: usize,
}
impl Indentation {
fn new(indent_char: u8, indent_size: usize) -> Indentation {
Indentation {
should_line_break: false,
indent_char,
indent_size,
indents: vec![indent_char; 128],
indents_len: 0,
}
}
fn grow(&mut self) {
self.indents_len = self.indents_len + self.indent_size;
if self.indents_len > self.indents.len() {
self.indents.resize(self.indents_len, self.indent_char);
}
}
fn shrink(&mut self) {
self.indents_len = match self.indents_len.checked_sub(self.indent_size) {
Some(result) => result,
None => 0,
};
}
}
use write_all instead of write
//! A module to handle `Writer`
use std::io::Write;
use errors::{Error, Result};
use events::Event;
/// XML writer.
///
/// Writes XML `Event`s to a `Write` implementor.
///
/// # Examples
///
/// ```rust
/// # extern crate quick_xml;
/// # fn main() {
/// use quick_xml::{Reader, Writer};
/// use quick_xml::events::{Event, BytesEnd, BytesStart};
/// use std::io::Cursor;
///
/// let xml = r#"<this_tag k1="v1" k2="v2"><child>text</child></this_tag>"#;
/// let mut reader = Reader::from_str(xml);
/// reader.trim_text(true);
/// let mut writer = Writer::new(Cursor::new(Vec::new()));
/// let mut buf = Vec::new();
/// loop {
/// match reader.read_event(&mut buf) {
/// Ok(Event::Start(ref e)) if e.name() == b"this_tag" => {
///
/// // crates a new element ... alternatively we could reuse `e` by calling
/// // `e.into_owned()`
/// let mut elem = BytesStart::owned(b"my_elem".to_vec(), "my_elem".len());
///
/// // collect existing attributes
/// elem.extend_attributes(e.attributes().map(|attr| attr.unwrap()));
///
/// // copy existing attributes, adds a new my-key="some value" attribute
/// elem.push_attribute(("my-key", "some value"));
///
/// // writes the event to the writer
/// assert!(writer.write_event(Event::Start(elem)).is_ok());
/// },
/// Ok(Event::End(ref e)) if e.name() == b"this_tag" => {
/// assert!(writer.write_event(Event::End(BytesEnd::borrowed(b"my_elem"))).is_ok());
/// },
/// Ok(Event::Eof) => break,
/// // we can either move or borrow the event to write, depending on your use-case
/// Ok(e) => assert!(writer.write_event(&e).is_ok()),
/// Err(e) => panic!("{}", e),
/// }
/// buf.clear();
/// }
///
/// let result = writer.into_inner().into_inner();
/// let expected = r#"<my_elem k1="v1" k2="v2" my-key="some value"><child>text</child></my_elem>"#;
/// assert_eq!(result, expected.as_bytes());
/// # }
/// ```
#[derive(Clone)]
pub struct Writer<W: Write> {
/// underlying writer
writer: W,
indent: Option<Indentation>,
}
impl<W: Write> Writer<W> {
/// Creates a Writer from a generic Write
pub fn new(inner: W) -> Writer<W> {
Writer {
writer: inner,
indent: None,
}
}
/// Creates a Writer with configured whitespace indents from a generic Write
pub fn new_with_indent(inner: W, indent_char: u8, indent_size: usize) -> Writer<W> {
Writer {
writer: inner,
indent: Some(Indentation::new(indent_char, indent_size)),
}
}
/// Consumes this `Writer`, returning the underlying writer.
pub fn into_inner(self) -> W {
self.writer
}
/// Get inner writer, keeping ownership
pub fn inner(&mut self) -> &mut W {
&mut self.writer
}
/// Writes the given event to the underlying writer.
pub fn write_event<'a, E: AsRef<Event<'a>>>(&mut self, event: E) -> Result<()> {
let mut next_should_line_break = true;
let result = match *event.as_ref() {
Event::Start(ref e) => {
let result = self.write_wrapped(b"<", e, b">");
if let Some(i) = self.indent.as_mut() {
i.grow();
}
result
}
Event::End(ref e) => {
if let Some(i) = self.indent.as_mut() {
i.shrink();
}
self.write_wrapped(b"</", e, b">")
}
Event::Empty(ref e) => self.write_wrapped(b"<", e, b"/>"),
Event::Text(ref e) => {
next_should_line_break = false;
self.write(&e.escaped())
}
Event::Comment(ref e) => self.write_wrapped(b"<!--", e, b"-->"),
Event::CData(ref e) => self.write_wrapped(b"<![CDATA[", e, b"]]>"),
Event::Decl(ref e) => self.write_wrapped(b"<?", e, b"?>"),
Event::PI(ref e) => self.write_wrapped(b"<?", e, b"?>"),
Event::DocType(ref e) => self.write_wrapped(b"<!DOCTYPE", e, b">"),
Event::Eof => Ok(()),
};
if let Some(i) = self.indent.as_mut() {
i.should_line_break = next_should_line_break;
}
result
}
/// Writes bytes
#[inline]
pub fn write(&mut self, value: &[u8]) -> Result<()> {
self.writer.write_all(value).map_err(Error::Io)
}
#[inline]
fn write_wrapped(&mut self, before: &[u8], value: &[u8], after: &[u8]) -> Result<()> {
if let Some(ref i) = self.indent {
if i.should_line_break {
self.writer.write_all(b"\n").map_err(Error::Io)?;
self
.writer
.write_all(&i.indents[..i.indents_len])
.map_err(Error::Io)?;
}
}
self.write(before)?;
self.write(value)?;
self.write(after)?;
Ok(())
}
/// Manually write a newline and indentation at the proper level.
///
/// This can be used when the heuristic to line break and indent after any [Event] apart
/// from [Text] fails such as when a [Start] occurs directly after [Text].
/// This method will do nothing if `Writer` was not constructed with `new_with_indent`.
///
/// [Event]: events/enum.Event.html
/// [Text]: events/enum.Event.html#variant.Text
/// [Start]: events/enum.Event.html#variant.Start
pub fn write_indent(&mut self) -> Result<()> {
if let Some(ref i) = self.indent {
self.writer.write_all(b"\n").map_err(Error::Io)?;
self
.writer
.write_all(&i.indents[..i.indents_len])
.map_err(Error::Io)?;
}
Ok(())
}
}
#[derive(Clone)]
struct Indentation {
should_line_break: bool,
indent_char: u8,
indent_size: usize,
indents: Vec<u8>,
indents_len: usize,
}
impl Indentation {
fn new(indent_char: u8, indent_size: usize) -> Indentation {
Indentation {
should_line_break: false,
indent_char,
indent_size,
indents: vec![indent_char; 128],
indents_len: 0,
}
}
fn grow(&mut self) {
self.indents_len = self.indents_len + self.indent_size;
if self.indents_len > self.indents.len() {
self.indents.resize(self.indents_len, self.indent_char);
}
}
fn shrink(&mut self) {
self.indents_len = match self.indents_len.checked_sub(self.indent_size) {
Some(result) => result,
None => 0,
};
}
}
|
// Higher level OpenCL wrappers.
use CL;
use CL::*;
use CL::ll::*;
use error::check;
use std::libc;
use std::vec;
use std::ptr;
use std::str;
use std::io;
use std::result;
use std::sys;
use std::cast;
struct Platform {
id: cl_platform_id
}
enum DeviceType {
CPU, GPU
}
fn convert_device_type(device: DeviceType) -> cl_device_type {
match device {
CPU => CL_DEVICE_TYPE_CPU,
GPU => CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR
}
}
impl Platform {
fn get_devices(&self) -> ~[Device]
{
get_devices(*self, CL_DEVICE_TYPE_ALL)
}
fn get_devices_by_types(&self, types: &[DeviceType]) -> ~[Device]
{
let dtype = 0;
for types.each |&t| {
dtype != convert_device_type(t);
}
get_devices(*self, dtype)
}
fn name(&self) -> ~str
{
unsafe
{
let mut size = 0;
clGetPlatformInfo(self.id,
CL_PLATFORM_NAME,
0,
ptr::null(),
ptr::to_mut_unsafe_ptr(&mut size));
let name = " ".repeat(size as uint);
do str::as_buf(name) |p, len| {
clGetPlatformInfo(self.id,
CL_PLATFORM_NAME,
len as libc::size_t,
p as *libc::c_void,
ptr::to_mut_unsafe_ptr(&mut size));
};
name
}
}
}
pub fn get_platforms() -> ~[Platform]
{
let num_platforms = 0;
unsafe
{
// TODO: Check result status
clGetPlatformIDs(0, ptr::null(), ptr::to_unsafe_ptr(&num_platforms));
let ids = vec::from_elem(num_platforms as uint, 0 as cl_platform_id);
do vec::as_imm_buf(ids) |ids, len| {
clGetPlatformIDs(len as cl_uint,
ids, ptr::to_unsafe_ptr(&num_platforms))
};
do ids.map |id| { Platform { id: *id } }
}
}
struct Device {
id: cl_device_id
}
impl Device {
fn name() -> ~str {
let mut size = 0;
let status = clGetDeviceInfo(
self.id,
CL_DEVICE_NAME,
0,
ptr::null(),
ptr::addr_of(&size));
check(status, "Could not determine name length");
let buf = vec::from_elem(size as uint, 0);
do vec::as_imm_buf(buf) |p, len| {
let status = clGetDeviceInfo(
self.id,
CL_DEVICE_NAME,
len as libc::size_t,
p as *libc::c_void,
ptr::null());
check(status, "Could not get device name");
unsafe { str::raw::from_c_str(p) }
}
}
}
pub fn get_devices(platform: Platform, dtype: cl_device_type) -> ~[Device]
{
unsafe
{
let num_devices = 0;
info!("Looking for devices matching %?", dtype);
clGetDeviceIDs(platform.id, dtype, 0, ptr::null(),
ptr::to_unsafe_ptr(&num_devices));
let ids = vec::from_elem(num_devices as uint, 0 as cl_device_id);
do vec::as_imm_buf(ids) |ids, len| {
clGetDeviceIDs(platform.id, dtype, len as cl_uint,
ids, ptr::to_unsafe_ptr(&num_devices));
};
do ids.map |id| { Device {id: *id }}
}
}
struct Context {
ctx: cl_context,
}
impl Drop for Context
{
fn finalize(&self)
{ unsafe { clReleaseContext(self.ctx); } }
}
pub fn create_context(device: Device) -> Context
{
unsafe
{
// TODO: Support for multiple devices
let errcode = 0;
// TODO: Proper error messages
let ctx = clCreateContext(ptr::null(),
1,
ptr::to_unsafe_ptr(&device.id),
cast::transmute(ptr::null::<&fn ()>()),
ptr::null(),
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create opencl context!");
Context { ctx: ctx }
}
}
struct CommandQueue {
cqueue: cl_command_queue,
device: Device,
}
impl Drop for CommandQueue
{
fn finalize(&self)
{ unsafe { clReleaseCommandQueue(self.cqueue); } }
}
pub fn create_command_queue(ctx: & Context, device: Device) -> CommandQueue
{
unsafe
{
let errcode = 0;
let cqueue = clCreateCommandQueue(ctx.ctx, device.id, 0,
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create command queue!");
CommandQueue {
cqueue: cqueue,
device: device
}
}
}
struct Buffer
{
buffer: cl_mem,
size: int,
}
impl Drop for Buffer
{
fn finalize(&self)
{ unsafe { clReleaseMemObject(self.buffer); } }
}
// TODO: How to make this function cleaner and nice
pub fn create_buffer(ctx: & Context, size: int, flags: cl_mem_flags) -> Buffer
{
unsafe
{
let errcode = 0;
let buffer = clCreateBuffer(ctx.ctx, flags, size as libc::size_t, ptr::null(),
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create buffer!");
Buffer { buffer: buffer, size: size }
}
}
struct Program
{
prg: cl_program,
context: Option<@ComputeContext>,
}
impl Drop for Program
{
fn finalize(&self)
{ unsafe { clReleaseProgram(self.prg); } }
}
impl Program
{
fn build(&self, device: Device) -> Result<(), ~str> {
build_program(self, device)
}
fn create_kernel(&self, name: &str) -> Kernel {
create_kernel(self, name)
}
}
// TODO: Support multiple devices
pub fn create_program_with_binary(ctx: & Context, device: Device,
binary_path: & Path) -> Program
{
unsafe
{
let errcode = 0;
let binary = match io::read_whole_file_str(binary_path) {
result::Ok(binary) => binary,
Err(e) => fail!(fmt!("%?", e))
};
let program = do str::as_c_str(binary) |kernel_binary| {
clCreateProgramWithBinary(ctx.ctx, 1, ptr::to_unsafe_ptr(&device.id),
ptr::to_unsafe_ptr(&(binary.len() + 1)) as *libc::size_t,
ptr::to_unsafe_ptr(&kernel_binary) as **libc::c_uchar,
ptr::null(),
ptr::to_unsafe_ptr(&errcode))
};
check(errcode, "Failed to create open cl program with binary!");
Program {
prg: program,
context: None,
}
}
pub fn build_program(program: & Program, device: Device) -> Result<(), ~str>
{
unsafe
{
let ret = clBuildProgram(program.prg, 1, ptr::to_unsafe_ptr(&device.id),
ptr::null(),
cast::transmute(ptr::null::<&fn ()>()),
ptr::null());
if ret == CL_SUCCESS as cl_int {
Ok(())
}
else {
let size = 0 as libc::size_t;
let status = clGetProgramBuildInfo(
program.prg,
device.id,
CL_PROGRAM_BUILD_LOG,
0,
ptr::null(),
ptr::to_unsafe_ptr(&size));
check(status, "Could not get build log");
let buf = vec::from_elem(size as uint, 0u8);
do vec::as_imm_buf(buf) |p, len| {
let status = clGetProgramBuildInfo(
program.prg,
device.id,
CL_PROGRAM_BUILD_LOG,
len as libc::size_t,
p as *libc::c_void,
ptr::null());
check(status, "Could not get build log");
Err(str::raw::from_c_str(p as *libc::c_char))
}
}
}
}
struct Kernel {
kernel: cl_kernel,
context: Option<@ComputeContext>,
impl Drop for Kernel
{
fn finalize(&self)
{ unsafe { clReleaseKernel(self.kernel); } }
}
pub impl Kernel {
fn set_arg<T: KernelArg>(&self, i: uint, x: &T)
{
set_kernel_arg(self, i as CL::cl_uint, x)
}
fn execute<I: KernelIndex>(&self, global: I, local: I) {
match self.context {
Some(ctx)
=> ctx.enqueue_async_kernel(self, global, local).wait(),
None => fail ~"Kernel does not have an associated context."
}
}
fn work_group_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: libc::size_t = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_WORK_GROUP_SIZE,
sys::size_of::<libc::size_t>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
fn local_mem_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: cl_ulong = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_LOCAL_MEM_SIZE,
sys::size_of::<cl_ulong>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
fn private_mem_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: cl_ulong = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_PRIVATE_MEM_SIZE,
sys::size_of::<cl_ulong>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
}
pub fn create_kernel(program: & Program, kernel: & str) -> Kernel
{
unsafe {
let errcode = 0;
// let bytes = str::to_bytes(kernel);
do kernel.as_c_str() |str_ptr|
{
let kernel = clCreateKernel(program.prg,
str_ptr,
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create kernel!");
Kernel {
kernel: kernel,
context: None
}
}
}
}
pub trait KernelArg {
fn get_value(&self) -> (libc::size_t, *libc::c_void);
}
macro_rules! scalar_kernel_arg (
($t:ty) => (impl KernelArg for $t {
fn get_value(&self) -> (libc::size_t, *libc::c_void) {
(sys::size_of::<$t>() as libc::size_t,
ptr::to_unsafe_ptr(self) as *libc::c_void)
}
})
)
scalar_kernel_arg!(int)
scalar_kernel_arg!(uint)
pub fn set_kernel_arg<T: KernelArg>(kernel: & Kernel,
position: cl_uint,
arg: &T)
{
unsafe
{
let (size, p) = arg.get_value();
let ret = clSetKernelArg(kernel.kernel, position,
size,
p);
check(ret, "Failed to set kernel arg!");
}
}
pub fn enqueue_nd_range_kernel(cqueue: & CommandQueue, kernel: & Kernel, work_dim: cl_uint,
_global_work_offset: int, global_work_size: int,
local_work_size: int)
{
unsafe
{
let ret = clEnqueueNDRangeKernel(cqueue.cqueue, kernel.kernel, work_dim,
// ptr::to_unsafe_ptr(&global_work_offset) as *libc::size_t,
ptr::null(),
ptr::to_unsafe_ptr(&global_work_size) as *libc::size_t,
ptr::to_unsafe_ptr(&local_work_size) as *libc::size_t,
0, ptr::null(), ptr::null());
check(ret, "Failed to enqueue nd range kernel!");
}
}
impl KernelArg for Buffer
{
fn get_value(&self) -> (libc::size_t, *libc::c_void)
{
(sys::size_of::<cl_mem>() as libc::size_t,
ptr::to_unsafe_ptr(&self.buffer) as *libc::c_void)
}
}
struct Event
{
event: cl_event,
}
impl Drop for Event
{
fn finalize(&self)
{ unsafe { clReleaseEvent(self.event); } }
}
impl Event {
fn wait(&self)
{
unsafe
{
let status = clWaitForEvents(1, ptr::to_unsafe_ptr(&self.event));
check(status, "Error waiting for event");
}
}
}
/**
This packages an OpenCL context, a device, and a command queue to
simplify handling all these structures.
*/
pub struct ComputeContext
{
ctx: Context,
device: Device,
q: CommandQueue
}
impl ComputeContext
{
fn create_program_from_source(&self, src: &str) -> Program
{
unsafe
{
do str::as_c_str(src) |src| {
let status = CL_SUCCESS as cl_int;
let program = clCreateProgramWithSource(
self.ctx.ctx,
1,
ptr::to_unsafe_ptr(&src),
ptr::null(),
ptr::to_unsafe_ptr(&status));
check(status, "Could not create program");
Program { prg: program }
}
}
}
fn create_program_from_binary(@self, bin: &str) -> Program {
do str::as_c_str(bin) |src| {
let mut status = CL_SUCCESS as cl_int;
let len = bin.len() as libc::size_t;
let program = clCreateProgramWithBinary(
self.ctx.ctx,
1,
ptr::addr_of(&self.device.id),
ptr::addr_of(&len),
ptr::addr_of(&src) as **libc::c_uchar,
ptr::null(),
ptr::addr_of(&status));
check(status, "Could not create program");
Program {
prg: program,
context: Some(self),
}
}
}
fn enqueue_async_kernel<I: KernelIndex>(&self, k: &Kernel, global: I, local: I)
-> Event
{
unsafe
{
let e: cl_event = ptr::null();
let status = clEnqueueNDRangeKernel(
self.q.cqueue,
k.kernel,
KernelIndex::num_dimensions::<I>(),
ptr::null(),
global.get_ptr(),
local.get_ptr(),
0,
ptr::null(),
ptr::to_unsafe_ptr(&e));
check(status, "Error enqueuing kernel.");
Event { event: e }
}
}
fn device_name() -> ~str {
self.device.name()
}
}
pub fn create_compute_context() -> @ComputeContext {
// Enumerate all platforms until we find a device that works.
let platforms = get_platforms();
for platforms.each |p|
{
let devices = p.get_devices();
if devices.len() > 0
{
let device = devices[0];
let ctx = create_context(device);
let q = create_command_queue(&ctx, device);
return @ComputeContext
{
ctx: ctx,
device: device,
q: q
}
}
}
}
pub fn create_compute_context_types(types: &[DeviceType]) -> @ComputeContext {
// Enumerate all platforms until we find a device that works.
for get_platforms().each |p| {
let devices = p.get_devices_by_types(types);
if devices.len() > 0 {
let device = devices[0];
let ctx = create_context(device);
let q = create_commandqueue(&ctx, device);
return @ComputeContext {
ctx: move ctx,
device: move device,
q: move q
}
}
}
}
fail!(~"Could not find an acceptable device.")
}
trait KernelIndex
{
fn num_dimensions() -> cl_uint;
fn get_ptr(&self) -> *libc::size_t;
}
impl KernelIndex for int
{
fn num_dimensions() -> cl_uint { 1 }
fn get_ptr(&self) -> *libc::size_t
{
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for (int, int) {
fn num_dimensions() -> cl_uint { 2 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for uint
{
fn num_dimensions() -> cl_uint { 1 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for (uint, uint)
{
fn num_dimensions() -> cl_uint { 2 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
#[cfg(test)]
mod test {
use hl::*;
use vector::*;
use std::io;
macro_rules! expect (
($test: expr, $expected: expr) => ({
let test = $test;
let expected = $expected;
if test != expected {
fail!(fmt!("Test failure in %s: expected %?, got %?",
stringify!($test),
expected, test))
}
})
)
#[test]
fn program_build() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
}
#[test]
fn simple_kernel() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
enqueue_nd_range_kernel(
&ctx.q,
&k,
1, 0, 1, 1);
let v = v.to_vec();
expect!(v[0], 2);
}
#[test]
fn add_k() {
let src = "__kernel void test(__global int *i, long int k) { \
*i += k; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
k.set_arg(1, &42);
enqueue_nd_range_kernel(
&ctx.q,
&k,
1, 0, 1, 1);
let v = v.to_vec();
expect!(v[0], 43);
}
#[test]
fn simple_kernel_index() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
ctx.enqueue_async_kernel(&k, 1, 1).wait();
let v = v.to_vec();
expect!(v[0], 2);
}
#[test]
fn kernel_2d()
{
let src = "__kernel void test(__global long int *N) { \
int i = get_global_id(0); \
int j = get_global_id(1); \
int s = get_global_size(0); \
N[i * s + j] = i * j;
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
match prog.build(ctx.device) {
Ok(()) => (),
Err(build_log) => {
io::println("Error building program:\n");
io::println(build_log);
fail!("");
}
}
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
k.set_arg(0, &v);
ctx.enqueue_async_kernel(&k, (3, 3), (1, 1)).wait();
let v = v.to_vec();
expect!(v, ~[0, 0, 0, 0, 1, 2, 0, 2, 4]);
}
#[test]
fn kernel_2d_execute() {
let src = "__kernel void test(__global long int *N) { \
int i = get_global_id(0); \
int j = get_global_id(1); \
int s = get_global_size(0); \
N[i * s + j] = i * j;
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
match prog.build(ctx.device) {
Ok(()) => (),
Err(build_log) => {
io::println("Error building program:\n");
io::println(build_log);
fail
}
}
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
k.set_arg(0, &v);
k.execute((3, 3), (1, 1));
let v = v.to_vec();
expect!(v, ~[0, 0, 0, 0, 1, 2, 0, 2, 4]);
}
}
Mostly indentation fixes, added a few missing delimiters.
// Higher level OpenCL wrappers.
use CL;
use CL::*;
use CL::ll::*;
use error::check;
use std::libc;
use std::vec;
use std::ptr;
use std::str;
use std::io;
use std::result;
use std::sys;
use std::cast;
struct Platform {
id: cl_platform_id
}
enum DeviceType {
CPU, GPU
}
fn convert_device_type(device: DeviceType) -> cl_device_type {
match device {
CPU => CL_DEVICE_TYPE_CPU,
GPU => CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR
}
}
impl Platform {
fn get_devices(&self) -> ~[Device]
{
get_devices(*self, CL_DEVICE_TYPE_ALL)
}
fn get_devices_by_types(&self, types: &[DeviceType]) -> ~[Device]
{
let dtype = 0;
for types.each |&t| {
dtype != convert_device_type(t);
}
get_devices(*self, dtype)
}
fn name(&self) -> ~str
{
unsafe
{
let mut size = 0;
clGetPlatformInfo(self.id,
CL_PLATFORM_NAME,
0,
ptr::null(),
ptr::to_mut_unsafe_ptr(&mut size));
let name = " ".repeat(size as uint);
do str::as_buf(name) |p, len| {
clGetPlatformInfo(self.id,
CL_PLATFORM_NAME,
len as libc::size_t,
p as *libc::c_void,
ptr::to_mut_unsafe_ptr(&mut size));
};
name
}
}
}
pub fn get_platforms() -> ~[Platform]
{
let num_platforms = 0;
unsafe
{
// TODO: Check result status
clGetPlatformIDs(0, ptr::null(), ptr::to_unsafe_ptr(&num_platforms));
let ids = vec::from_elem(num_platforms as uint, 0 as cl_platform_id);
do vec::as_imm_buf(ids) |ids, len| {
clGetPlatformIDs(len as cl_uint,
ids, ptr::to_unsafe_ptr(&num_platforms))
};
do ids.map |id| { Platform { id: *id } }
}
}
struct Device {
id: cl_device_id
}
impl Device {
fn name() -> ~str {
let mut size = 0;
let status = clGetDeviceInfo(
self.id,
CL_DEVICE_NAME,
0,
ptr::null(),
ptr::addr_of(&size));
check(status, "Could not determine name length");
let buf = vec::from_elem(size as uint, 0);
do vec::as_imm_buf(buf) |p, len| {
let status = clGetDeviceInfo(
self.id,
CL_DEVICE_NAME,
len as libc::size_t,
p as *libc::c_void,
ptr::null());
check(status, "Could not get device name");
unsafe { str::raw::from_c_str(p) }
}
}
}
pub fn get_devices(platform: Platform, dtype: cl_device_type) -> ~[Device]
{
unsafe
{
let num_devices = 0;
info!("Looking for devices matching %?", dtype);
clGetDeviceIDs(platform.id, dtype, 0, ptr::null(),
ptr::to_unsafe_ptr(&num_devices));
let ids = vec::from_elem(num_devices as uint, 0 as cl_device_id);
do vec::as_imm_buf(ids) |ids, len| {
clGetDeviceIDs(platform.id, dtype, len as cl_uint,
ids, ptr::to_unsafe_ptr(&num_devices));
};
do ids.map |id| { Device {id: *id }}
}
}
struct Context {
ctx: cl_context,
}
impl Drop for Context
{
fn finalize(&self) {
unsafe {
clReleaseContext(self.ctx);
}
}
}
pub fn create_context(device: Device) -> Context
{
unsafe
{
// TODO: Support for multiple devices
let errcode = 0;
// TODO: Proper error messages
let ctx = clCreateContext(ptr::null(),
1,
ptr::to_unsafe_ptr(&device.id),
cast::transmute(ptr::null::<&fn ()>()),
ptr::null(),
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create opencl context!");
Context { ctx: ctx }
}
}
struct CommandQueue {
cqueue: cl_command_queue,
device: Device,
}
impl Drop for CommandQueue
{
fn finalize(&self) {
unsafe {
clReleaseCommandQueue(self.cqueue);
}
}
}
pub fn create_command_queue(ctx: & Context, device: Device) -> CommandQueue
{
unsafe
{
let errcode = 0;
let cqueue = clCreateCommandQueue(ctx.ctx, device.id, 0,
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create command queue!");
CommandQueue {
cqueue: cqueue,
device: device
}
}
}
struct Buffer
{
buffer: cl_mem,
size: int,
}
impl Drop for Buffer
{
fn finalize(&self) {
unsafe {
clReleaseMemObject(self.buffer);
}
}
}
// TODO: How to make this function cleaner and nice
pub fn create_buffer(ctx: & Context, size: int, flags: cl_mem_flags) -> Buffer
{
unsafe
{
let errcode = 0;
let buffer = clCreateBuffer(ctx.ctx, flags,
size as libc::size_t, ptr::null(),
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create buffer!");
Buffer { buffer: buffer, size: size }
}
}
struct Program
{
prg: cl_program,
context: Option<@ComputeContext>,
}
impl Drop for Program
{
fn finalize(&self) {
unsafe {
clReleaseProgram(self.prg);
}
}
}
impl Program
{
fn build(&self, device: Device) -> Result<(), ~str> {
build_program(self, device)
}
fn create_kernel(&self, name: &str) -> Kernel {
create_kernel(self, name)
}
}
// TODO: Support multiple devices
pub fn create_program_with_binary(ctx: & Context, device: Device,
binary_path: & Path) -> Program
{
unsafe
{
let errcode = 0;
let binary = match io::read_whole_file_str(binary_path) {
result::Ok(binary) => binary,
Err(e) => fail!(fmt!("%?", e))
};
let program = do str::as_c_str(binary) |kernel_binary| {
clCreateProgramWithBinary(ctx.ctx, 1, ptr::to_unsafe_ptr(&device.id),
ptr::to_unsafe_ptr(&(binary.len() + 1)) as *libc::size_t,
ptr::to_unsafe_ptr(&kernel_binary) as **libc::c_uchar,
ptr::null(),
ptr::to_unsafe_ptr(&errcode))
};
check(errcode, "Failed to create open cl program with binary!");
Program {
prg: program,
context: None,
}
}
}
pub fn build_program(program: & Program, device: Device) -> Result<(), ~str>
{
unsafe
{
let ret = clBuildProgram(program.prg, 1, ptr::to_unsafe_ptr(&device.id),
ptr::null(),
cast::transmute(ptr::null::<&fn ()>()),
ptr::null());
if ret == CL_SUCCESS as cl_int {
Ok(())
}
else {
let size = 0 as libc::size_t;
let status = clGetProgramBuildInfo(
program.prg,
device.id,
CL_PROGRAM_BUILD_LOG,
0,
ptr::null(),
ptr::to_unsafe_ptr(&size));
check(status, "Could not get build log");
let buf = vec::from_elem(size as uint, 0u8);
do vec::as_imm_buf(buf) |p, len| {
let status = clGetProgramBuildInfo(
program.prg,
device.id,
CL_PROGRAM_BUILD_LOG,
len as libc::size_t,
p as *libc::c_void,
ptr::null());
check(status, "Could not get build log");
Err(str::raw::from_c_str(p as *libc::c_char))
}
}
}
}
struct Kernel {
kernel: cl_kernel,
context: Option<@ComputeContext>,
impl Drop for Kernel
{
fn finalize(&self) {
unsafe {
clReleaseKernel(self.kernel);
}
}
}
}
pub impl Kernel {
fn set_arg<T: KernelArg>(&self, i: uint, x: &T)
{
set_kernel_arg(self, i as CL::cl_uint, x)
}
fn execute<I: KernelIndex>(&self, global: I, local: I) {
match self.context {
Some(ctx)
=> ctx.enqueue_async_kernel(self, global, local).wait(),
None => fail ~"Kernel does not have an associated context."
}
}
fn work_group_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: libc::size_t = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_WORK_GROUP_SIZE,
sys::size_of::<libc::size_t>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
fn local_mem_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: cl_ulong = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_LOCAL_MEM_SIZE,
sys::size_of::<cl_ulong>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
fn private_mem_size(&self) -> uint {
match self.context {
Some(ctx) => {
let mut size: cl_ulong = 0;
let status = clGetKernelWorkGroupInfo(
self.kernel,
ctx.device.id,
CL_KERNEL_PRIVATE_MEM_SIZE,
sys::size_of::<cl_ulong>() as libc::size_t,
ptr::addr_of(&size) as *libc::c_void,
ptr::null());
check(status, "Could not get work group info.");
size as uint
},
None => fail ~"Kernel does not have an associated context."
}
}
}
pub fn create_kernel(program: & Program, kernel: & str) -> Kernel
{
unsafe {
let errcode = 0;
// let bytes = str::to_bytes(kernel);
do kernel.as_c_str() |str_ptr|
{
let kernel = clCreateKernel(program.prg,
str_ptr,
ptr::to_unsafe_ptr(&errcode));
check(errcode, "Failed to create kernel!");
Kernel {
kernel: kernel,
context: None
}
}
}
}
pub trait KernelArg {
fn get_value(&self) -> (libc::size_t, *libc::c_void);
}
macro_rules! scalar_kernel_arg (
($t:ty) => (impl KernelArg for $t {
fn get_value(&self) -> (libc::size_t, *libc::c_void) {
(sys::size_of::<$t>() as libc::size_t,
ptr::to_unsafe_ptr(self) as *libc::c_void)
}
})
)
scalar_kernel_arg!(int)
scalar_kernel_arg!(uint)
pub fn set_kernel_arg<T: KernelArg>(kernel: & Kernel,
position: cl_uint,
arg: &T)
{
unsafe
{
let (size, p) = arg.get_value();
let ret = clSetKernelArg(kernel.kernel, position,
size,
p);
check(ret, "Failed to set kernel arg!");
}
}
pub fn enqueue_nd_range_kernel(cqueue: & CommandQueue, kernel: & Kernel, work_dim: cl_uint,
_global_work_offset: int, global_work_size: int,
local_work_size: int)
{
unsafe
{
let ret = clEnqueueNDRangeKernel(cqueue.cqueue, kernel.kernel, work_dim,
// ptr::to_unsafe_ptr(&global_work_offset) as *libc::size_t,
ptr::null(),
ptr::to_unsafe_ptr(&global_work_size) as *libc::size_t,
ptr::to_unsafe_ptr(&local_work_size) as *libc::size_t,
0, ptr::null(), ptr::null());
check(ret, "Failed to enqueue nd range kernel!");
}
}
impl KernelArg for Buffer
{
fn get_value(&self) -> (libc::size_t, *libc::c_void)
{
(sys::size_of::<cl_mem>() as libc::size_t,
ptr::to_unsafe_ptr(&self.buffer) as *libc::c_void)
}
}
struct Event
{
event: cl_event,
}
impl Drop for Event
{
fn finalize(&self) {
unsafe {
clReleaseEvent(self.event);
}
}
}
impl Event {
fn wait(&self)
{
unsafe
{
let status = clWaitForEvents(1, ptr::to_unsafe_ptr(&self.event));
check(status, "Error waiting for event");
}
}
}
/**
This packages an OpenCL context, a device, and a command queue to
simplify handling all these structures.
*/
pub struct ComputeContext
{
ctx: Context,
device: Device,
q: CommandQueue
}
impl ComputeContext
{
fn create_program_from_source(&self, src: &str) -> Program
{
unsafe
{
do str::as_c_str(src) |src| {
let status = CL_SUCCESS as cl_int;
let program = clCreateProgramWithSource(
self.ctx.ctx,
1,
ptr::to_unsafe_ptr(&src),
ptr::null(),
ptr::to_unsafe_ptr(&status));
check(status, "Could not create program");
Program { prg: program }
}
}
}
fn create_program_from_binary(@self, bin: &str) -> Program {
do str::as_c_str(bin) |src| {
let mut status = CL_SUCCESS as cl_int;
let len = bin.len() as libc::size_t;
let program = clCreateProgramWithBinary(
self.ctx.ctx,
1,
ptr::addr_of(&self.device.id),
ptr::addr_of(&len),
ptr::addr_of(&src) as **libc::c_uchar,
ptr::null(),
ptr::addr_of(&status));
check(status, "Could not create program");
Program {
prg: program,
context: Some(self),
}
}
}
fn enqueue_async_kernel<I: KernelIndex>(&self, k: &Kernel, global: I, local: I)
-> Event
{
unsafe
{
let e: cl_event = ptr::null();
let status = clEnqueueNDRangeKernel(
self.q.cqueue,
k.kernel,
KernelIndex::num_dimensions::<I>(),
ptr::null(),
global.get_ptr(),
local.get_ptr(),
0,
ptr::null(),
ptr::to_unsafe_ptr(&e));
check(status, "Error enqueuing kernel.");
Event { event: e }
}
}
fn device_name() -> ~str {
self.device.name()
}
}
pub fn create_compute_context() -> @ComputeContext {
// Enumerate all platforms until we find a device that works.
let platforms = get_platforms();
for platforms.each |p|
{
let devices = p.get_devices();
if devices.len() > 0
{
let device = devices[0];
let ctx = create_context(device);
let q = create_command_queue(&ctx, device);
return @ComputeContext
{
ctx: ctx,
device: device,
q: q
}
}
}
}
pub fn create_compute_context_types(types: &[DeviceType]) -> @ComputeContext {
// Enumerate all platforms until we find a device that works.
for get_platforms().each |p| {
let devices = p.get_devices_by_types(types);
if devices.len() > 0 {
let device = devices[0];
let ctx = create_context(device);
let q = create_commandqueue(&ctx, device);
return @ComputeContext {
ctx: move ctx,
device: move device,
q: move q
}
}
}
fail!(~"Could not find an acceptable device.")
}
trait KernelIndex
{
fn num_dimensions() -> cl_uint;
fn get_ptr(&self) -> *libc::size_t;
}
impl KernelIndex for int
{
fn num_dimensions() -> cl_uint { 1 }
fn get_ptr(&self) -> *libc::size_t
{
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for (int, int) {
fn num_dimensions() -> cl_uint { 2 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for uint
{
fn num_dimensions() -> cl_uint { 1 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
impl KernelIndex for (uint, uint)
{
fn num_dimensions() -> cl_uint { 2 }
fn get_ptr(&self) -> *libc::size_t {
ptr::to_unsafe_ptr(self) as *libc::size_t
}
}
#[cfg(test)]
mod test {
use hl::*;
use vector::*;
use std::io;
macro_rules! expect (
($test: expr, $expected: expr) => ({
let test = $test;
let expected = $expected;
if test != expected {
fail!(fmt!("Test failure in %s: expected %?, got %?",
stringify!($test),
expected, test))
}
})
)
#[test]
fn program_build() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
}
#[test]
fn simple_kernel() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
enqueue_nd_range_kernel(
&ctx.q,
&k,
1, 0, 1, 1);
let v = v.to_vec();
expect!(v[0], 2);
}
#[test]
fn add_k() {
let src = "__kernel void test(__global int *i, long int k) { \
*i += k; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
k.set_arg(1, &42);
enqueue_nd_range_kernel(
&ctx.q,
&k,
1, 0, 1, 1);
let v = v.to_vec();
expect!(v[0], 43);
}
#[test]
fn simple_kernel_index() {
let src = "__kernel void test(__global int *i) { \
*i += 1; \
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
prog.build(ctx.device);
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1]);
k.set_arg(0, &v);
ctx.enqueue_async_kernel(&k, 1, 1).wait();
let v = v.to_vec();
expect!(v[0], 2);
}
#[test]
fn kernel_2d()
{
let src = "__kernel void test(__global long int *N) { \
int i = get_global_id(0); \
int j = get_global_id(1); \
int s = get_global_size(0); \
N[i * s + j] = i * j;
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
match prog.build(ctx.device) {
Ok(()) => (),
Err(build_log) => {
io::println("Error building program:\n");
io::println(build_log);
fail!("");
}
}
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
k.set_arg(0, &v);
ctx.enqueue_async_kernel(&k, (3, 3), (1, 1)).wait();
let v = v.to_vec();
expect!(v, ~[0, 0, 0, 0, 1, 2, 0, 2, 4]);
}
#[test]
fn kernel_2d_execute() {
let src = "__kernel void test(__global long int *N) { \
int i = get_global_id(0); \
int j = get_global_id(1); \
int s = get_global_size(0); \
N[i * s + j] = i * j;
}";
let ctx = create_compute_context();
let prog = ctx.create_program_from_source(src);
match prog.build(ctx.device) {
Ok(()) => (),
Err(build_log) => {
io::println("Error building program:\n");
io::println(build_log);
fail
}
}
let k = prog.create_kernel("test");
let v = Vector::from_vec(ctx, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
k.set_arg(0, &v);
k.execute((3, 3), (1, 1));
let v = v.to_vec();
expect!(v, ~[0, 0, 0, 0, 1, 2, 0, 2, 4]);
}
}
|
use logging::LogLevel;
use marionette::LogOptions;
use mozprofile::preferences::Pref;
use mozprofile::profile::Profile;
use mozrunner::runner::platform::firefox_default_path;
use mozversion::{self, firefox_version, Version};
use rustc_serialize::base64::FromBase64;
use rustc_serialize::json::Json;
use std::collections::BTreeMap;
use std::default::Default;
use std::error::Error;
use std::fs;
use std::io::BufWriter;
use std::io::Cursor;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use webdriver::capabilities::BrowserCapabilities;
use webdriver::error::{ErrorStatus, WebDriverError, WebDriverResult};
use zip;
pub struct FirefoxCapabilities<'a> {
pub chosen_binary: Option<PathBuf>,
fallback_binary: Option<&'a PathBuf>,
version_cache: BTreeMap<PathBuf, String>,
}
impl <'a> FirefoxCapabilities<'a> {
pub fn new(fallback_binary: Option<&'a PathBuf>) -> FirefoxCapabilities<'a> {
FirefoxCapabilities {
chosen_binary: None,
fallback_binary: fallback_binary,
version_cache: BTreeMap::new()
}
}
fn set_binary(&mut self, capabilities: &BTreeMap<String, Json>) {
self.chosen_binary = capabilities.get("moz:firefoxOptions")
.and_then(|x| x.find("binary"))
.and_then(|x| x.as_string())
.map(|x| PathBuf::from(x))
.or_else(|| self.fallback_binary
.map(|x| x.clone()))
.or_else(|| firefox_default_path())
.and_then(|x| x.canonicalize().ok())
}
fn version(&mut self) -> Result<Option<String>, mozversion::Error> {
if let Some(ref binary) = self.chosen_binary {
if let Some(value) = self.version_cache.get(binary) {
return Ok(Some((*value).clone()))
}
let rv = try!(firefox_version(&*binary))
.version_string;
if let Some(ref version) = rv {
self.version_cache.insert(binary.clone(), version.clone());
}
Ok(rv)
}
else {
//TODO: try launching the binary here to figure out the version
Ok(None)
}
}
}
// TODO: put this in webdriver-rust
fn convert_version_error(err: mozversion::Error) -> WebDriverError {
WebDriverError::new(
ErrorStatus::SessionNotCreated,
err.description().to_string())
}
impl <'a> BrowserCapabilities for FirefoxCapabilities<'a> {
fn init(&mut self, capabilities: &BTreeMap<String, Json>) {
self.set_binary(capabilities);
}
fn browser_name(&mut self, _: &BTreeMap<String, Json>) -> WebDriverResult<Option<String>> {
Ok(Some("firefox".into()))
}
fn browser_version(&mut self, _: &BTreeMap<String, Json>) -> WebDriverResult<Option<String>> {
self.version()
.or_else(|x| Err(convert_version_error(x)))
}
fn platform_name(&mut self, _: &BTreeMap<String, Json>) -> WebDriverResult<Option<String>> {
Ok(if cfg!(target_os="windows") {
Some("windows".into())
} else if cfg!(target_os="macos") {
Some("mac".into())
} else if cfg!(target_os="linux") {
Some("linux".into())
} else {
None
})
}
fn accept_insecure_certs(&mut self, _: &BTreeMap<String, Json>) -> WebDriverResult<bool> {
let version_str = try!(self.version()
.or_else(|x| Err(convert_version_error(x))));
if let Some(x) = version_str {
Ok(try!(Version::from_str(&*x)
.or_else(|x| Err(convert_version_error(x)))).major > 52)
} else {
Ok(false)
}
}
fn compare_browser_version(&mut self, version: &str, comparison: &str) -> WebDriverResult<bool> {
try!(Version::from_str(version)
.or_else(|x| Err(convert_version_error(x))))
.matches(comparison)
.or_else(|x| Err(convert_version_error(x)))
}
fn accept_proxy(&mut self, _: &BTreeMap<String, Json>, _: &BTreeMap<String, Json>) -> WebDriverResult<bool> {
Ok(true)
}
fn validate_custom(&self, name: &str, value: &Json) -> WebDriverResult<()> {
if !name.starts_with("moz:") {
return Ok(())
}
match name {
"moz:firefoxOptions" => {
let data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"moz:firefoxOptions is not an object");
for (key, value) in data.iter() {
match &**key {
"binary" => {
if !value.is_string() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"binary path is not a string"));
}
},
"args" => {
if !try_opt!(value.as_array(),
ErrorStatus::InvalidArgument,
"args is not an array")
.iter()
.all(|value| value.is_string()) {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"args entry is not a string"));
}
},
"profile" => {
if !value.is_string() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"profile is not a string"));
}
},
"log" => {
let log_data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"log value is not an object");
for (log_key, log_value) in log_data.iter() {
match &**log_key {
"level" => {
let level = try_opt!(log_value.as_string(),
ErrorStatus::InvalidArgument,
"log level is not a string");
if LogLevel::from_str(level).is_err() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("{} is not a valid log level",
level)))
}
}
x => return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("Invalid log field {}", x)))
}
}
},
"prefs" => {
let prefs_data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"prefs value is not an object");
if !prefs_data.values()
.all(|x| x.is_string() || x.is_i64() || x.is_boolean()) {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"Preference values not all string or integer or boolean"));
}
}
x => return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("Invalid moz:firefoxOptions field {}", x)))
}
}
}
_ => return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
format!("Unrecognised option {}", name)))
}
Ok(())
}
fn accept_custom(&mut self, _: &str, _: &Json, _: &BTreeMap<String, Json>) -> WebDriverResult<bool> {
Ok(true)
}
}
#[derive(Default)]
pub struct FirefoxOptions {
pub binary: Option<PathBuf>,
pub profile: Option<Profile>,
pub args: Option<Vec<String>>,
pub log: LogOptions,
pub prefs: Vec<(String, Pref)>
}
impl FirefoxOptions {
pub fn new() -> FirefoxOptions {
Default::default()
}
pub fn from_capabilities(binary_path: Option<PathBuf>,
capabilities: &mut BTreeMap<String, Json>)
-> WebDriverResult<FirefoxOptions> {
let mut rv = FirefoxOptions::new();
rv.binary = binary_path;
if let Some(options) = capabilities.remove("moz:firefoxOptions") {
let firefox_options = try!(options
.as_object()
.ok_or(WebDriverError::new(
ErrorStatus::InvalidArgument,
"'moz:firefoxOptions' capability is not an object")));
rv.profile = try!(FirefoxOptions::load_profile(&firefox_options));
rv.args = try!(FirefoxOptions::load_args(&firefox_options));
rv.log = try!(FirefoxOptions::load_log(&firefox_options));
rv.prefs = try!(FirefoxOptions::load_prefs(&firefox_options));
}
Ok(rv)
}
fn load_profile(options: &BTreeMap<String, Json>) -> WebDriverResult<Option<Profile>> {
if let Some(profile_json) = options.get("profile") {
let profile_base64 = try!(profile_json
.as_string()
.ok_or(
WebDriverError::new(ErrorStatus::UnknownError,
"Profile is not a string")));
let profile_zip = &*try!(profile_base64.from_base64());
// Create an emtpy profile directory
let profile = try!(Profile::new(None));
try!(unzip_buffer(profile_zip,
profile.temp_dir
.as_ref()
.expect("Profile doesn't have a path")
.path()));
Ok(Some(profile))
} else {
Ok(None)
}
}
fn load_args(options: &BTreeMap<String, Json>) -> WebDriverResult<Option<Vec<String>>> {
if let Some(args_json) = options.get("args") {
let args_array = try!(args_json.as_array()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,
"Arguments were not an array")));
let args = try!(args_array
.iter()
.map(|x| x.as_string().map(|x| x.to_owned()))
.collect::<Option<Vec<String>>>()
.ok_or(WebDriverError::new(
ErrorStatus::UnknownError,
"Arguments entries were not all strings")));
Ok(Some(args))
} else {
Ok(None)
}
}
fn load_log(options: &BTreeMap<String, Json>) -> WebDriverResult<LogOptions> {
if let Some(json) = options.get("log") {
let log = try!(json.as_object()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument, "Log section is not an object")));
let level = match log.get("level") {
Some(json) => {
let s = try!(json.as_string()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument, "Log level is not a string")));
Some(try!(LogLevel::from_str(s).ok()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument, "Log level is unknown"))))
},
None => None,
};
Ok(LogOptions { level: level })
} else {
Ok(Default::default())
}
}
pub fn load_prefs(options: &BTreeMap<String, Json>) -> WebDriverResult<Vec<(String, Pref)>> {
if let Some(prefs_data) = options.get("prefs") {
let prefs = try!(prefs_data
.as_object()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,"Prefs were not an object")));
let mut rv = Vec::with_capacity(prefs.len());
for (key, value) in prefs.iter() {
rv.push((key.clone(), try!(pref_from_json(value))));
};
Ok(rv)
} else {
Ok(vec![])
}
}
}
fn pref_from_json(value: &Json) -> WebDriverResult<Pref> {
match value {
&Json::String(ref x) => Ok(Pref::new(x.clone())),
&Json::I64(x) => Ok(Pref::new(x)),
&Json::U64(x) => Ok(Pref::new(x as i64)),
&Json::Boolean(x) => Ok(Pref::new(x)),
_ => Err(WebDriverError::new(ErrorStatus::UnknownError,
"Could not convert pref value to string, boolean, or integer"))
}
}
fn unzip_buffer(buf: &[u8], dest_dir: &Path) -> WebDriverResult<()> {
let reader = Cursor::new(buf);
let mut zip = try!(zip::ZipArchive::new(reader).map_err(|_| {
WebDriverError::new(ErrorStatus::UnknownError, "Failed to unzip profile")
}));
for i in 0..zip.len() {
let mut file = try!(zip.by_index(i).map_err(|_| {
WebDriverError::new(ErrorStatus::UnknownError, "Processing profile zip file failed")
}));
let unzip_path = {
let name = file.name();
let is_dir = name.ends_with("/");
let rel_path = Path::new(name);
let dest_path = dest_dir.join(rel_path);
{
let create_dir = if is_dir {
Some(dest_path.as_path())
} else {
dest_path.parent()
};
if let Some(dir) = create_dir {
if !dir.exists() {
debug!("Creating profile directory tree {}", dir.to_string_lossy());
try!(fs::create_dir_all(dir));
}
}
}
if is_dir {
None
} else {
Some(dest_path)
}
};
if let Some(unzip_path) = unzip_path {
debug!("Extracting profile to {}", unzip_path.to_string_lossy());
let dest = try!(fs::File::create(unzip_path));
if file.size() > 0 {
let mut writer = BufWriter::new(dest);
try!(io::copy(&mut file, &mut writer));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
extern crate mozprofile;
extern crate rustc_serialize;
use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use self::mozprofile::preferences::Pref;
use self::rustc_serialize::base64::{ToBase64, Config, CharacterSet, Newline};
use self::rustc_serialize::json::Json;
use webdriver::command::NewSessionParameters;
use marionette::MarionetteHandler;
use super::FirefoxOptions;
fn example_profile() -> Json {
let mut profile_data = Vec::with_capacity(1024);
let mut profile = File::open("src/tests/profile.zip").unwrap();
profile.read_to_end(&mut profile_data).unwrap();
let base64_config = Config {
char_set: CharacterSet::Standard,
newline: Newline::LF,
pad: true,
line_length: None
};
Json::String(profile_data.to_base64(base64_config))
}
fn capabilities() -> NewSessionParameters {
let desired: BTreeMap<String, Json> = BTreeMap::new();
let required: BTreeMap<String, Json> = BTreeMap::new();
NewSessionParameters {
desired: desired,
required: required
}
}
#[test]
fn test_profile() {
let encoded_profile = example_profile();
let mut capabilities = capabilities();
let mut firefox_options: BTreeMap<String, Json> = BTreeMap::new();
firefox_options.insert("profile".into(), encoded_profile);
capabilities.required.insert("moz:firefoxOptions".into(), Json::Object(firefox_options));
let options = FirefoxOptions::from_capabilities(&mut capabilities).unwrap();
let mut profile = options.profile.unwrap();
let prefs = profile.user_prefs().unwrap();
println!("{:?}",prefs.prefs);
assert_eq!(prefs.get("startup.homepage_welcome_url"),
Some(&Pref::new("data:text/html,PASS")));
}
#[test]
fn test_prefs() {
let encoded_profile = example_profile();
let mut capabilities = capabilities();
let mut firefox_options: BTreeMap<String, Json> = BTreeMap::new();
firefox_options.insert("profile".into(), encoded_profile);
let mut prefs: BTreeMap<String, Json> = BTreeMap::new();
prefs.insert("browser.display.background_color".into(), Json::String("#00ff00".into()));
firefox_options.insert("prefs".into(), Json::Object(prefs));
capabilities.required.insert("moz:firefoxOptions".into(), Json::Object(firefox_options));
let options = FirefoxOptions::from_capabilities(&mut capabilities).unwrap();
let mut profile = options.profile.unwrap();
let handler = MarionetteHandler::new(Default::default());
handler.set_prefs(2828, &mut profile, true, options.prefs).unwrap();
let prefs_set = profile.user_prefs().unwrap();
println!("{:?}",prefs_set.prefs);
assert_eq!(prefs_set.get("startup.homepage_welcome_url"),
Some(&Pref::new("data:text/html,PASS")));
assert_eq!(prefs_set.get("browser.display.background_color"),
Some(&Pref::new("#00ff00")));
assert_eq!(prefs_set.get("marionette.defaultPrefs.port"),
Some(&Pref::new(2828)));
}
}
capabilities: fix tests
This change makes the tests compile and makes use of the public typedef
webdriver::capabilities::Capabilities, which reduces the need for type
declarations of BTreeMap.
use logging::LogLevel;
use marionette::LogOptions;
use mozprofile::preferences::Pref;
use mozprofile::profile::Profile;
use mozrunner::runner::platform::firefox_default_path;
use mozversion::{self, firefox_version, Version};
use rustc_serialize::base64::FromBase64;
use rustc_serialize::json::Json;
use std::collections::BTreeMap;
use std::default::Default;
use std::error::Error;
use std::fs;
use std::io::BufWriter;
use std::io::Cursor;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use webdriver::capabilities::{BrowserCapabilities, Capabilities};
use webdriver::error::{ErrorStatus, WebDriverError, WebDriverResult};
use zip;
/// Provides matching of `moz:firefoxOptions` and resolution of which Firefox
/// binary to use.
///
/// `FirefoxCapabilities` is constructed with the fallback binary, should
/// `moz:firefoxOptions` not contain a binary entry. This may either be the
/// system Firefox installation or an override, for example given to the
/// `--binary` flag of geckodriver.
pub struct FirefoxCapabilities<'a> {
pub chosen_binary: Option<PathBuf>,
fallback_binary: Option<&'a PathBuf>,
version_cache: BTreeMap<PathBuf, String>,
}
impl<'a> FirefoxCapabilities<'a> {
pub fn new(fallback_binary: Option<&'a PathBuf>) -> FirefoxCapabilities<'a> {
FirefoxCapabilities {
chosen_binary: None,
fallback_binary: fallback_binary,
version_cache: BTreeMap::new(),
}
}
fn set_binary(&mut self, capabilities: &BTreeMap<String, Json>) {
self.chosen_binary = capabilities
.get("moz:firefoxOptions")
.and_then(|x| x.find("binary"))
.and_then(|x| x.as_string())
.map(|x| PathBuf::from(x))
.or_else(|| self.fallback_binary.map(|x| x.clone()))
.or_else(|| firefox_default_path())
.and_then(|x| x.canonicalize().ok())
}
fn version(&mut self) -> Result<Option<String>, mozversion::Error> {
if let Some(ref binary) = self.chosen_binary {
if let Some(value) = self.version_cache.get(binary) {
return Ok(Some((*value).clone()));
}
let rv = try!(firefox_version(&*binary)).version_string;
if let Some(ref version) = rv {
self.version_cache
.insert(binary.clone(), version.clone());
}
Ok(rv)
} else {
// TODO: try launching the binary here to figure out the version
Ok(None)
}
}
}
// TODO: put this in webdriver-rust
fn convert_version_error(err: mozversion::Error) -> WebDriverError {
WebDriverError::new(
ErrorStatus::SessionNotCreated,
err.description().to_string())
}
impl<'a> BrowserCapabilities for FirefoxCapabilities<'a> {
fn init(&mut self, capabilities: &Capabilities) {
self.set_binary(capabilities);
}
fn browser_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> {
Ok(Some("firefox".into()))
}
fn browser_version(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> {
self.version().or_else(|x| Err(convert_version_error(x)))
}
fn platform_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> {
Ok(if cfg!(target_os = "windows") {
Some("windows".into())
} else if cfg!(target_os = "macos") {
Some("mac".into())
} else if cfg!(target_os = "linux") {
Some("linux".into())
} else {
None
})
}
fn accept_insecure_certs(&mut self, _: &Capabilities) -> WebDriverResult<bool> {
let version_str = try!(self.version().or_else(|x| Err(convert_version_error(x))));
if let Some(x) = version_str {
Ok(try!(Version::from_str(&*x).or_else(|x| Err(convert_version_error(x)))).major > 52)
} else {
Ok(false)
}
}
fn compare_browser_version(&mut self,
version: &str,
comparison: &str)
-> WebDriverResult<bool> {
try!(Version::from_str(version).or_else(|x| Err(convert_version_error(x))))
.matches(comparison)
.or_else(|x| Err(convert_version_error(x)))
}
fn accept_proxy(&mut self, _: &Capabilities, _: &Capabilities) -> WebDriverResult<bool> {
Ok(true)
}
fn validate_custom(&self, name: &str, value: &Json) -> WebDriverResult<()> {
if !name.starts_with("moz:") {
return Ok(())
}
match name {
"moz:firefoxOptions" => {
let data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"moz:firefoxOptions is not an object");
for (key, value) in data.iter() {
match &**key {
"binary" => {
if !value.is_string() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"binary path is not a string"));
}
},
"args" => {
if !try_opt!(value.as_array(),
ErrorStatus::InvalidArgument,
"args is not an array")
.iter()
.all(|value| value.is_string()) {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"args entry is not a string"));
}
},
"profile" => {
if !value.is_string() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"profile is not a string"));
}
},
"log" => {
let log_data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"log value is not an object");
for (log_key, log_value) in log_data.iter() {
match &**log_key {
"level" => {
let level = try_opt!(log_value.as_string(),
ErrorStatus::InvalidArgument,
"log level is not a string");
if LogLevel::from_str(level).is_err() {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("{} is not a valid log level",
level)))
}
}
x => return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("Invalid log field {}", x)))
}
}
},
"prefs" => {
let prefs_data = try_opt!(value.as_object(),
ErrorStatus::InvalidArgument,
"prefs value is not an object");
if !prefs_data.values()
.all(|x| x.is_string() || x.is_i64() || x.is_boolean()) {
return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
"Preference values not all string or integer or boolean"));
}
}
x => return Err(WebDriverError::new(
ErrorStatus::InvalidArgument,
format!("Invalid moz:firefoxOptions field {}", x)))
}
}
}
_ => return Err(WebDriverError::new(ErrorStatus::InvalidArgument,
format!("Unrecognised option {}", name)))
}
Ok(())
}
fn accept_custom(&mut self, _: &str, _: &Json, _: &Capabilities) -> WebDriverResult<bool> {
Ok(true)
}
}
/// Rust representation of `moz:firefoxOptions`.
///
/// Calling `FirefoxOptions::from_capabilities(binary, capabilities)` causes
/// the encoded profile, the binary arguments, log settings, and additional
/// preferences to be checked and unmarshaled from the `moz:firefoxOptions`
/// JSON Object into a Rust representation.
#[derive(Default)]
pub struct FirefoxOptions {
pub binary: Option<PathBuf>,
pub profile: Option<Profile>,
pub args: Option<Vec<String>>,
pub log: LogOptions,
pub prefs: Vec<(String, Pref)>,
}
impl FirefoxOptions {
pub fn new() -> FirefoxOptions {
Default::default()
}
pub fn from_capabilities(binary_path: Option<PathBuf>,
matched: &mut Capabilities)
-> WebDriverResult<FirefoxOptions> {
let mut rv = FirefoxOptions::new();
rv.binary = binary_path;
if let Some(json) = matched.remove("moz:firefoxOptions") {
let options = try!(json.as_object()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument,
"'moz:firefoxOptions' \
capability is not an object")));
rv.profile = try!(FirefoxOptions::load_profile(&options));
rv.args = try!(FirefoxOptions::load_args(&options));
rv.log = try!(FirefoxOptions::load_log(&options));
rv.prefs = try!(FirefoxOptions::load_prefs(&options));
}
Ok(rv)
}
fn load_profile(options: &Capabilities) -> WebDriverResult<Option<Profile>> {
if let Some(profile_json) = options.get("profile") {
let profile_base64 =
try!(profile_json
.as_string()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,
"Profile is not a string")));
let profile_zip = &*try!(profile_base64.from_base64());
// Create an emtpy profile directory
let profile = try!(Profile::new(None));
try!(unzip_buffer(profile_zip,
profile
.temp_dir
.as_ref()
.expect("Profile doesn't have a path")
.path()));
Ok(Some(profile))
} else {
Ok(None)
}
}
fn load_args(options: &Capabilities) -> WebDriverResult<Option<Vec<String>>> {
if let Some(args_json) = options.get("args") {
let args_array = try!(args_json
.as_array()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,
"Arguments were not an \
array")));
let args = try!(args_array
.iter()
.map(|x| x.as_string().map(|x| x.to_owned()))
.collect::<Option<Vec<String>>>()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,
"Arguments entries were not all \
strings")));
Ok(Some(args))
} else {
Ok(None)
}
}
fn load_log(options: &Capabilities) -> WebDriverResult<LogOptions> {
if let Some(json) = options.get("log") {
let log = try!(json.as_object()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument,
"Log section is not an object")));
let level = match log.get("level") {
Some(json) => {
let s = try!(json.as_string()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument,
"Log level is not a string")));
Some(try!(LogLevel::from_str(s)
.ok()
.ok_or(WebDriverError::new(ErrorStatus::InvalidArgument,
"Log level is unknown"))))
}
None => None,
};
Ok(LogOptions { level: level })
} else {
Ok(Default::default())
}
}
pub fn load_prefs(options: &Capabilities) -> WebDriverResult<Vec<(String, Pref)>> {
if let Some(prefs_data) = options.get("prefs") {
let prefs = try!(prefs_data
.as_object()
.ok_or(WebDriverError::new(ErrorStatus::UnknownError,
"Prefs were not an object")));
let mut rv = Vec::with_capacity(prefs.len());
for (key, value) in prefs.iter() {
rv.push((key.clone(), try!(pref_from_json(value))));
}
Ok(rv)
} else {
Ok(vec![])
}
}
}
fn pref_from_json(value: &Json) -> WebDriverResult<Pref> {
match value {
&Json::String(ref x) => Ok(Pref::new(x.clone())),
&Json::I64(x) => Ok(Pref::new(x)),
&Json::U64(x) => Ok(Pref::new(x as i64)),
&Json::Boolean(x) => Ok(Pref::new(x)),
_ => Err(WebDriverError::new(ErrorStatus::UnknownError,
"Could not convert pref value to string, boolean, or integer"))
}
}
fn unzip_buffer(buf: &[u8], dest_dir: &Path) -> WebDriverResult<()> {
let reader = Cursor::new(buf);
let mut zip = try!(zip::ZipArchive::new(reader).map_err(|_| {
WebDriverError::new(ErrorStatus::UnknownError, "Failed to unzip profile")
}));
for i in 0..zip.len() {
let mut file = try!(zip.by_index(i).map_err(|_| {
WebDriverError::new(ErrorStatus::UnknownError, "Processing profile zip file failed")
}));
let unzip_path = {
let name = file.name();
let is_dir = name.ends_with("/");
let rel_path = Path::new(name);
let dest_path = dest_dir.join(rel_path);
{
let create_dir = if is_dir {
Some(dest_path.as_path())
} else {
dest_path.parent()
};
if let Some(dir) = create_dir {
if !dir.exists() {
debug!("Creating profile directory tree {}", dir.to_string_lossy());
try!(fs::create_dir_all(dir));
}
}
}
if is_dir {
None
} else {
Some(dest_path)
}
};
if let Some(unzip_path) = unzip_path {
debug!("Extracting profile to {}", unzip_path.to_string_lossy());
let dest = try!(fs::File::create(unzip_path));
if file.size() > 0 {
let mut writer = BufWriter::new(dest);
try!(io::copy(&mut file, &mut writer));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
extern crate mozprofile;
extern crate rustc_serialize;
use self::mozprofile::preferences::Pref;
use self::rustc_serialize::base64::{CharacterSet, Config, Newline, ToBase64};
use self::rustc_serialize::json::Json;
use super::FirefoxOptions;
use marionette::MarionetteHandler;
use std::collections::BTreeMap;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use webdriver::capabilities::Capabilities;
fn example_profile() -> Json {
let mut profile_data = Vec::with_capacity(1024);
let mut profile = File::open("src/tests/profile.zip").unwrap();
profile.read_to_end(&mut profile_data).unwrap();
let base64_config = Config {
char_set: CharacterSet::Standard,
newline: Newline::LF,
pad: true,
line_length: None,
};
Json::String(profile_data.to_base64(base64_config))
}
fn make_options(firefox_opts: Capabilities) -> FirefoxOptions {
let mut caps = Capabilities::new();
caps.insert("moz:firefoxOptions".into(), Json::Object(firefox_opts));
let binary = None;
FirefoxOptions::from_capabilities(binary, &mut caps).unwrap()
}
#[test]
fn test_profile() {
let encoded_profile = example_profile();
let mut firefox_opts = Capabilities::new();
firefox_opts.insert("profile".into(), encoded_profile);
let opts = make_options(firefox_opts);
let mut profile = opts.profile.unwrap();
let prefs = profile.user_prefs().unwrap();
println!("{:#?}", prefs.prefs);
assert_eq!(prefs.get("startup.homepage_welcome_url"),
Some(&Pref::new("data:text/html,PASS")));
}
#[test]
fn test_prefs() {
let encoded_profile = example_profile();
let mut prefs: BTreeMap<String, Json> = BTreeMap::new();
prefs.insert("browser.display.background_color".into(),
Json::String("#00ff00".into()));
let mut firefox_opts = Capabilities::new();
firefox_opts.insert("profile".into(), encoded_profile);
firefox_opts.insert("prefs".into(), Json::Object(prefs));
let opts = make_options(firefox_opts);
let mut profile = opts.profile.unwrap();
let handler = MarionetteHandler::new(Default::default());
handler
.set_prefs(2828, &mut profile, true, opts.prefs)
.unwrap();
let prefs_set = profile.user_prefs().unwrap();
println!("{:#?}", prefs_set.prefs);
assert_eq!(prefs_set.get("startup.homepage_welcome_url"),
Some(&Pref::new("data:text/html,PASS")));
assert_eq!(prefs_set.get("browser.display.background_color"),
Some(&Pref::new("#00ff00")));
assert_eq!(prefs_set.get("marionette.defaultPrefs.port"),
Some(&Pref::new(2828)));
}
}
|
// Copyright 2014 The Peevee Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs::File;
use std::env;
use super::super::color::Color;
use super::super::password;
use super::super::password::ScrubMemory;
use super::super::rpassword::read_password;
use std::old_io::stdio;
fn stdout_is_piped() -> bool {
true
}
pub fn callback(args: &[String], file: &mut File) {
let ref app_name = args[2];
// We print this to STDERR instead of STDOUT so that the output of the
// command contains *only* the password. This makes it easy to pipe it
// to something like "xclip" which would save the password in the clipboard.
print_stderr!("Type your master password: ");
match read_password() {
Ok(ref mut master_password) => {
match password::get_password(master_password, app_name, file) {
Ok(ref mut password) => {
if stdout_is_piped() {
print!("{}", password.password);
stdio::flush();
} else {
println!("{}", password.password);
}
password.scrub_memory();
},
Err(err) => {
errln!("I couldn't find a password for this app ({:?}).", err);
env::set_exit_status(1);
}
}
master_password.scrub_memory();
},
Err(err) => {
errln!("\nI couldn't read the master password ({:?}).", err);
env::set_exit_status(1);
}
}
}
support piping with "get" command
// Copyright 2014 The Peevee Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs::File;
use std::env;
use super::super::color::Color;
use super::super::password;
use super::super::password::ScrubMemory;
use super::super::rpassword::read_password;
use std::old_io::stdio;
// POSIX fstat related stuff.
use libc::funcs::posix88::stat_::fstat;
use libc::types::os::arch::posix01::stat as stat_struct;
use libc::consts::os::posix88::S_IFIFO;
use libc::consts::os::posix88::STDOUT_FILENO;
use std::mem;
fn stdout_is_piped() -> bool {
// We can safely use this struct uninitialized because `fstat` will
// initialize it for us.
let mut stat: stat_struct = unsafe { mem::uninitialized() };
// If there is an error, we'll just say that the output is piped.
// This should rarely, if ever, happen. And saying the output is piped is
// the least annoying because it allows piping.
if unsafe { fstat(STDOUT_FILENO, &mut stat) } != 0 {
true
} else {
// S_IFIFO is the type "Named pipe".
stat.st_mode & S_IFIFO == S_IFIFO
}
}
pub fn callback(args: &[String], file: &mut File) {
let ref app_name = args[2];
// We print this to STDERR instead of STDOUT so that the output of the
// command contains *only* the password. This makes it easy to pipe it
// to something like "xclip" which would save the password in the clipboard.
print_stderr!("Type your master password: ");
match read_password() {
Ok(ref mut master_password) => {
match password::get_password(master_password, app_name, file) {
Ok(ref mut password) => {
if stdout_is_piped() {
print!("{}", password.password);
stdio::flush();
} else {
println!("{}", password.password);
}
password.scrub_memory();
},
Err(err) => {
errln!("I couldn't find a password for this app ({:?}).", err);
env::set_exit_status(1);
}
}
master_password.scrub_memory();
},
Err(err) => {
errln!("\nI couldn't read the master password ({:?}).", err);
env::set_exit_status(1);
}
}
}
|
use std::cmp::Ordering::*;
#[derive(Debug)]
pub struct BST<T> {
nodes: Vec<Node<T>>,
root: Option<Ptr>,
}
#[derive(Debug, Clone, Copy)]
struct Ptr(usize);
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Color {Red, Black}
#[derive(Debug)]
struct Node<T> {
elem: T,
color: Color,
left: Option<Ptr>,
right: Option<Ptr>,
}
impl<T: Ord> Node<T> {
fn new(elem: T, color: Color) -> Self {
Node { elem: elem, color: color, left: None, right: None }
}
}
impl<T: Ord> BST<T> {
fn deref(&self, i: &Ptr) -> &Node<T> {
&self.nodes[i.0]
}
fn deref_mut(&mut self, i: &Ptr) -> &mut Node<T> {
&mut self.nodes[i.0]
}
pub fn new() -> Self {
BST{ nodes: Vec::new(), root: None }
}
pub fn singleton(elem: T) -> Self {
BST{ nodes: vec![Node::new(elem, Color::Black)], root: Some(Ptr(0))}
}
fn member_impl(&self, ptr: &Option<Ptr>, elem: &T) -> bool {
match *ptr {
None => false,
Some(ref ptr) => {
let node = self.deref(ptr);
match node.elem.cmp(elem) {
Less => self.member_impl(&node.right, elem),
Greater => self.member_impl(&node.left, elem),
Equal => true,
}
}
}
}
pub fn member(&self, elem: &T) -> bool {
self.member_impl(&self.root, elem)
}
fn is_red(&self, ptr: &Option<Ptr>) -> bool {
ptr.as_ref().map_or(false, |p| self.deref(p).color == Color::Red)
}
fn rotate_left(&mut self, h: Ptr) -> Ptr {
let x : Ptr = {self.deref(&h).right.expect("rotate left on node whose left child is nil")};
self.deref_mut(&h).right = {self.deref(&x).left};
self.deref_mut(&x).left = Some(h);
self.deref_mut(&x).color = {self.deref(&h).color};
self.deref_mut(&h).color = Color::Red;
x
// Note to self: the braces on the right of the assignment are to limit
// the scope of the immutable borrow, because we are immediately
// borrowing again mutably.
}
fn rotate_right(&mut self, h: Ptr) -> Ptr {
let x : Ptr = {self.deref(&h).left.expect("rotate right on node whose left child is nil")};
self.deref_mut(&h).left = {self.deref(&x).right};
self.deref_mut(&x).right = Some(h);
self.deref_mut(&x).color = {self.deref(&h).color};
self.deref_mut(&h).color = Color::Red;
x
}
fn move_red_up(&mut self, h: Ptr) {
self.deref_mut(&h).color = Color::Red;
let left : Ptr = {self.deref(&h).left.expect("move red up on node whose left child is nil")};
self.deref_mut(&left).color = Color::Black;
let right: Ptr = {self.deref(&h).right.expect("move red up on node whose right child is nil")};
self.deref_mut(&right).color = Color::Black;
}
fn insert_impl(&mut self, node: Option<Ptr>, elem: T) -> Ptr {
match node {
None => {
self.nodes.push(Node::new(elem, Color::Red));
Ptr(self.nodes.len() - 1)
},
Some(mut node) => {
match self.deref(&node).elem.cmp(&elem) {
Less => {
let right : Option<Ptr> = self.deref(&node).right;
let new_right : Ptr = self.insert_impl(right, elem);
self.deref_mut(&node).right = Some(new_right);
},
Greater => {
let left : Option<Ptr> = self.deref(&node).left;
let new_left : Ptr = self.insert_impl(left, elem);
self.deref_mut(&node).left = Some(new_left);
},
Equal => self.deref_mut(&node).elem = elem,
}
if self.is_red(&self.deref(&node).right) && !self.is_red(&self.deref(&node).left) {
node = self.rotate_left(node);
}
if self.is_red(&self.deref(&node).left) && self.is_red(&self.deref(&self.deref(&node).left.unwrap()).left) {
node = self.rotate_right(node);
}
if self.is_red(&self.deref(&node).left) && self.is_red(&self.deref(&node).right) {
self.move_red_up(node);
}
node
}
}
}
pub fn insert(&mut self, elem: T) {
let old_root : Option<Ptr> = self.root;
let new_root : Ptr = self.insert_impl(old_root, elem);
self.root = Some(new_root);
self.deref_mut(&new_root).color = Color::Black;
}
}
#[cfg(test)]
mod tests {
use super::BST;
#[test]
fn it_works() {
let e: BST<i32> = BST::new();
let s = BST::singleton(2);
assert_eq!(false, e.member(&1));
assert_eq!(false, e.member(&2));
assert_eq!(false, e.member(&3));
assert_eq!(false, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
let mut s = s;
s.insert(1);
assert_eq!(true, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
s.insert(4);
assert_eq!(true, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
assert_eq!(true, s.member(&4));
{
let mut thousand : BST<i32> = BST::new();
for i in 0..1000 {
thousand.insert(i);
}
for i in 0..1000 {
assert_eq!(true, thousand.member(&i));
}
assert_eq!(false, thousand.member(&1000));
}
{
let mut thousand : BST<i32> = BST::new();
for i in 0..1000 {
if i % 2 == 0 {
thousand.insert(i);
}
}
for i in 0..1000 {
assert_eq!(i % 2 == 0, thousand.member(&i));
}
for i in 0..1000 {
if i % 2 == 1 {
thousand.insert(i);
}
}
for i in 0..1000 {
assert_eq!(true, thousand.member(&i));
}
}
}
}
Add tikz visualization
use std::cmp::Ordering::*;
#[derive(Debug)]
pub struct BST<T> {
nodes: Vec<Node<T>>,
root: Option<Ptr>,
}
#[derive(Debug, Clone, Copy)]
struct Ptr(usize);
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Color {Red, Black}
#[derive(Debug)]
struct Node<T> {
elem: T,
color: Color,
left: Option<Ptr>,
right: Option<Ptr>,
}
impl<T: Ord> Node<T> {
fn new(elem: T, color: Color) -> Self {
Node { elem: elem, color: color, left: None, right: None }
}
}
impl<T: Ord> BST<T> {
fn deref(&self, i: &Ptr) -> &Node<T> {
&self.nodes[i.0]
}
fn deref_mut(&mut self, i: &Ptr) -> &mut Node<T> {
&mut self.nodes[i.0]
}
pub fn new() -> Self {
BST{ nodes: Vec::new(), root: None }
}
pub fn singleton(elem: T) -> Self {
BST{ nodes: vec![Node::new(elem, Color::Black)], root: Some(Ptr(0))}
}
fn member_impl(&self, ptr: &Option<Ptr>, elem: &T) -> bool {
match *ptr {
None => false,
Some(ref ptr) => {
let node = self.deref(ptr);
match node.elem.cmp(elem) {
Less => self.member_impl(&node.right, elem),
Greater => self.member_impl(&node.left, elem),
Equal => true,
}
}
}
}
pub fn member(&self, elem: &T) -> bool {
self.member_impl(&self.root, elem)
}
fn is_red(&self, ptr: &Option<Ptr>) -> bool {
ptr.as_ref().map_or(false, |p| self.deref(p).color == Color::Red)
}
fn rotate_left(&mut self, h: Ptr) -> Ptr {
let x : Ptr = {self.deref(&h).right.expect("rotate left on node whose left child is nil")};
self.deref_mut(&h).right = {self.deref(&x).left};
self.deref_mut(&x).left = Some(h);
self.deref_mut(&x).color = {self.deref(&h).color};
self.deref_mut(&h).color = Color::Red;
x
// Note to self: the braces on the right of the assignment are to limit
// the scope of the immutable borrow, because we are immediately
// borrowing again mutably.
}
fn rotate_right(&mut self, h: Ptr) -> Ptr {
let x : Ptr = {self.deref(&h).left.expect("rotate right on node whose left child is nil")};
self.deref_mut(&h).left = {self.deref(&x).right};
self.deref_mut(&x).right = Some(h);
self.deref_mut(&x).color = {self.deref(&h).color};
self.deref_mut(&h).color = Color::Red;
x
}
fn move_red_up(&mut self, h: Ptr) {
self.deref_mut(&h).color = Color::Red;
let left : Ptr = {self.deref(&h).left.expect("move red up on node whose left child is nil")};
self.deref_mut(&left).color = Color::Black;
let right: Ptr = {self.deref(&h).right.expect("move red up on node whose right child is nil")};
self.deref_mut(&right).color = Color::Black;
}
fn insert_impl(&mut self, node: Option<Ptr>, elem: T) -> Ptr {
match node {
None => {
self.nodes.push(Node::new(elem, Color::Red));
Ptr(self.nodes.len() - 1)
},
Some(mut node) => {
match self.deref(&node).elem.cmp(&elem) {
Less => {
let right : Option<Ptr> = self.deref(&node).right;
let new_right : Ptr = self.insert_impl(right, elem);
self.deref_mut(&node).right = Some(new_right);
},
Greater => {
let left : Option<Ptr> = self.deref(&node).left;
let new_left : Ptr = self.insert_impl(left, elem);
self.deref_mut(&node).left = Some(new_left);
},
Equal => self.deref_mut(&node).elem = elem,
}
if self.is_red(&self.deref(&node).right) && !self.is_red(&self.deref(&node).left) {
node = self.rotate_left(node);
}
if self.is_red(&self.deref(&node).left) && self.is_red(&self.deref(&self.deref(&node).left.unwrap()).left) {
node = self.rotate_right(node);
}
if self.is_red(&self.deref(&node).left) && self.is_red(&self.deref(&node).right) {
self.move_red_up(node);
}
node
}
}
}
pub fn insert(&mut self, elem: T) {
let old_root : Option<Ptr> = self.root;
let new_root : Ptr = self.insert_impl(old_root, elem);
self.root = Some(new_root);
self.deref_mut(&new_root).color = Color::Black;
}
fn print_structure_inner(&self, node: Option<Ptr>) {
match node {
None => print!("[missing]"),
Some(node_id) => {
print!("{{ node ");
let node = self.deref(&node_id);
if let Color::Red = node.color {
print!("[draw=red]");
}
print!("{{{:?}}} ", node_id.0); // Prints order of insertion
if let Color::Red = node.color {
print!("edge from parent[red]");
}
print!(" child ");
self.print_structure_inner(node.left);
print!(" child ");
self.print_structure_inner(node.right);
print!(" }}");
}
}
}
pub fn print_structure(&self) {
match self.root {
None => (),
Some(ref node_id) => {
println!("%% Put these in your preamble\n\
\\usepackage{{tikz}}\n\
\\usetikzlibrary{{graphdrawing}}\n\
\\usegdlibrary{{trees}}\n\
\\definecolor{{red}}{{RGB}}{{171,50,37}}\n\n\
%% Put these in the document body\n\
\\tikz [binary tree layout, nodes={{draw,circle}}, font=\\sffamily, semithick] \
\\node");
let node = self.deref(&node_id);
print!("{{{:?}}} child ", node_id.0); // Prints order of insertion
self.print_structure_inner(node.left);
print!(" child ");
self.print_structure_inner(node.right);
println!(";");
}
}
}
}
#[cfg(test)]
mod tests {
use super::BST;
#[test]
fn it_works() {
let e: BST<i32> = BST::new();
let s = BST::singleton(2);
assert_eq!(false, e.member(&1));
assert_eq!(false, e.member(&2));
assert_eq!(false, e.member(&3));
assert_eq!(false, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
let mut s = s;
s.insert(1);
assert_eq!(true, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
s.insert(4);
assert_eq!(true, s.member(&1));
assert_eq!(true, s.member(&2));
assert_eq!(false, s.member(&3));
assert_eq!(true, s.member(&4));
{
let mut thousand : BST<i32> = BST::new();
for i in 0..1000 {
thousand.insert(i);
}
for i in 0..1000 {
assert_eq!(true, thousand.member(&i));
}
assert_eq!(false, thousand.member(&1000));
}
{
let mut thousand : BST<i32> = BST::new();
for i in 0..1000 {
if i % 2 == 0 {
thousand.insert(i);
}
}
for i in 0..1000 {
assert_eq!(i % 2 == 0, thousand.member(&i));
}
for i in 0..1000 {
if i % 2 == 1 {
thousand.insert(i);
}
}
for i in 0..1000 {
assert_eq!(true, thousand.member(&i));
}
}
{
let mut ex : BST<i32> = BST::new();
for c in 0..64 {
ex.insert(c);
ex.print_structure();
println!("");
}
}
{
let mut ex : BST<i32> = BST::new();
let v: [i32; 20] = [14, 9, 12, 6, 2, 10, 1, 18, 16, 5, 8, 17, 13, 3, 11, 15, 7, 19, 4, 20];
for c in &v {
ex.insert(*c);
ex.print_structure();
println!("");
}
}
}
}
|
use cita_types::{Address, H256, U256};
use cita_vm::evm::Error as EvmError;
use std::boxed::Box;
use std::convert::From;
use util::sha3;
use cita_trie::DB;
use cita_vm::evm::DataProvider;
pub trait Serialize {
fn serialize(&self) -> Result<Vec<u8>, EvmError>;
}
pub trait Deserialize: Sized {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError>;
}
impl Serialize for U256 {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
//let mut vec = Vec::with_capacity(64);
let mut vec = vec![0; 32];
self.to_big_endian(&mut vec);
Ok(vec)
}
}
impl Deserialize for U256 {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Ok(U256::from(bytes))
}
}
impl Serialize for String {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
Ok(self.to_owned().into_bytes())
}
}
impl Deserialize for String {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Self::from_utf8(bytes.to_owned()).map_err(|_| EvmError::Internal("dup coin".to_string()))
}
}
impl Serialize for Vec<u8> {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
Ok(self.clone())
}
}
impl Deserialize for Vec<u8> {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Ok(Vec::from(bytes))
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Scalar {
position: H256,
}
impl Scalar {
pub fn new(position: H256) -> Self {
Scalar { position }
}
// single element
pub fn set(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
value: U256,
) -> Result<(), EvmError> {
ext.set_storage(addr, self.position, H256::from(value));
Ok(())
}
pub fn get(self: &Self, ext: &DataProvider, addr: &Address) -> Result<U256, EvmError> {
let value = ext.get_storage(addr, &self.position);
Ok(U256::from(value))
}
// bytes & string
pub fn set_bytes<T>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
value: &T,
) -> Result<(), EvmError>
where
T: Serialize,
{
let encoded = value.serialize()?;
let length = encoded.len();
if length < 32 {
let mut byte32 = [0u8; 32];
byte32[0..encoded.len()].copy_from_slice(&encoded);
byte32[31] = (length * 2) as u8;
ext.set_storage(addr, self.position, H256::from_slice(&byte32));
} else {
ext.set_storage(addr, self.position, H256::from((length * 2 + 1) as u64));
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
for chunk in encoded.chunks(32) {
let value = H256::from(chunk);
ext.set_storage(addr, H256::from(key), value);
key = key + U256::one();
}
}
Ok(())
}
pub fn get_bytes<T>(self: &Self, ext: &DataProvider, addr: &Address) -> Result<Box<T>, EvmError>
where
T: Deserialize,
{
let mut bytes = Vec::<u8>::new();
let first = ext.get_storage(addr, &self.position);
if first[31] % 2 == 0 {
let len = (first[31] / 2) as usize;
bytes.extend_from_slice(&first[0..len]);
let decoded = T::deserialize(&bytes)?;
Ok(Box::new(decoded))
} else {
let mut len = ((first.low_u64() as usize) - 1) / 2;
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
let mut bytes = Vec::new();
while len > 0 {
let v = ext.get_storage(addr, &H256::from(key));
if len > 32 {
bytes.extend_from_slice(v.as_ref());
key = key + U256::one();
len -= 32;
} else {
bytes.extend_from_slice(&v[0..len]);
len = 0;
}
}
Ok(Box::new(T::deserialize(&bytes)?))
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Array {
position: H256,
}
impl Array {
pub fn new(position: H256) -> Self {
Array { position }
}
#[inline]
fn key(&self, index: u64) -> H256 {
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
key = key + U256::from(index);
H256::from(key)
}
pub fn set(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
index: u64,
value: &U256,
) -> Result<(), EvmError> {
let scalar = Scalar::new(self.key(index));
scalar.set(ext, addr, *value)
}
pub fn get(
self: &Self,
ext: &DataProvider,
addr: &Address,
index: u64,
) -> Result<U256, EvmError> {
let scalar = Scalar::new(self.key(index));
scalar.get(ext, addr)
}
pub fn set_bytes<T>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
index: u64,
value: &T,
) -> Result<(), EvmError>
where
T: Serialize,
{
let scalar = Scalar::new(self.key(index));
scalar.set_bytes(ext, addr, value)
}
pub fn get_bytes<T>(
self: &Self,
ext: &DataProvider,
addr: &Address,
index: u64,
) -> Result<Box<T>, EvmError>
where
T: Deserialize,
{
let scalar = Scalar::new(self.key(index));
scalar.get_bytes(ext, addr)
}
pub fn set_len(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
len: u64,
) -> Result<(), EvmError> {
ext.set_storage(addr, self.position, H256::from(len));
Ok(())
}
pub fn get_len(self: &Self, ext: &DataProvider, addr: &Address) -> Result<u64, EvmError> {
let len = ext.get_storage(addr, &self.position);
Ok(len.low_u64())
}
pub fn get_array(self: &mut Self, index: u64) -> Array {
Array::new(self.key(index))
}
pub fn get_map(self: &mut Self, index: u64) -> Map {
Map::new(self.key(index))
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Map {
position: H256,
}
impl Map {
pub fn new(position: H256) -> Self {
Map { position }
}
#[inline]
fn key<Key>(&self, key: &Key) -> Result<H256, EvmError>
where
Key: Serialize,
{
let mut bytes = Vec::new();
bytes.extend_from_slice(&key.serialize()?);
bytes.extend_from_slice(self.position.as_ref());
Ok(H256::from_slice(&sha3::keccak256(&bytes)))
}
pub fn set<Key>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
key: &Key,
value: U256,
) -> Result<(), EvmError>
where
Key: Serialize,
{
Scalar::new(self.key(key)?).set(ext, addr, value)
}
pub fn get<Key>(
self: &Self,
ext: &DataProvider,
addr: &Address,
key: &Key,
) -> Result<U256, EvmError>
where
Key: Serialize,
{
Scalar::new(self.key(key)?).get(ext, addr)
}
pub fn set_bytes<Key, Value>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
key: &Key,
value: &Value,
) -> Result<(), EvmError>
where
Key: Serialize,
Value: Serialize,
{
Scalar::new(self.key(key)?).set_bytes(ext, addr, value)
}
pub fn get_bytes<Key, Value>(
self: &Self,
ext: &DataProvider,
addr: &Address,
key: &Key,
) -> Result<Value, EvmError>
where
Key: Serialize,
Value: Deserialize,
{
Ok(*Scalar::new(self.key(key)?).get_bytes(ext, addr)?)
}
pub fn get_array<Key>(self: &mut Self, key: &Key) -> Result<Array, EvmError>
where
Key: Serialize,
{
Ok(Array::new(self.key(key)?))
}
pub fn get_map<Key>(self: &mut Self, key: &Key) -> Result<Map, EvmError>
where
Key: Serialize,
{
Ok(Map::new(self.key(key)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fake_tests::FakeExt;
#[test]
fn test_scalar_bytes() {
let mut ext = FakeExt::new();
let scalar = Scalar::new(H256::from(0));
// 1) length=30
let expected = format!("012345678901234567890123456789");
assert!(scalar.set_bytes(&mut ext, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 2) length=31
let expected = format!("0123456789012345678901234567890");
assert!(scalar.set_bytes(&mut ext, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 3) length=32
let expected = format!("01234567890123456789012345678901");
assert!(scalar.set_bytes(&mut ext, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 4) length=43
let expected = format!("012345678901234567890123456789012");
assert!(scalar.set_bytes(&mut ext, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
}
#[test]
fn test_scalar_u256() {
let mut ext = FakeExt::new();
let scalar = Scalar::new(H256::from(0));
let expected = U256::from(0x123456);
assert!(scalar.set(&mut ext, expected.clone()).is_ok());
let value = scalar.get(&ext);
assert!(value.is_ok());
assert_eq!(value.unwrap(), expected.clone());
}
#[test]
fn test_array_simple() {
let mut ext = FakeExt::new();
let length = 7u64;
let array = Array {
position: H256::from(0),
};
// 1) length
assert!(array.set_len(&mut ext, length).is_ok());
assert_eq!(array.get_len(&ext).unwrap(), length);
// 2) array[1] = 0x1234
let index = 1;
let expected = U256::from(0x1234);
assert!(array.set(&mut ext, index, &expected).is_ok());
let value = array.get(&ext, index);
assert_eq!(value.unwrap(), expected.clone());
// 3) array[3] = 0x2234
let index = 3;
let expected = U256::from(0x2234);
assert!(array.set(&mut ext, index, &expected).is_ok());
let value = array.get(&ext, index);
assert_eq!(value.unwrap(), expected.clone());
}
#[test]
fn test_array_with_sub_array() {
let mut ext = FakeExt::new();
let mut array = Array::new(H256::from(0));
// 1) length = 7
let length = 7;
assert!(array.set_len(&mut ext, length).is_ok());
assert_eq!(array.get_len(&ext).unwrap(), length);
// 2) array[1].len = 8
let index = 1;
let subarray_length = 8;
let subarray = array.get_array(index);
assert!(subarray.set_len(&mut ext, subarray_length).is_ok());
assert_eq!(subarray.get_len(&mut ext).unwrap(), subarray_length);
// 3) array[1][2] = 0x1234
let index = 2;
let expected = U256::from(0x1234);
assert!(subarray.set(&mut ext, index, &expected).is_ok());
assert_eq!(subarray.get(&ext, index).unwrap(), expected);
// 4) array[1][4] = 0x2234
let index = 4;
let expected = U256::from(0x2234);
assert!(subarray.set(&mut ext, index, &expected).is_ok());
assert_eq!(subarray.get(&ext, index).unwrap(), expected);
}
#[test]
fn test_array_with_sub_map() {
let mut ext = FakeExt::new();
let mut array = Array::new(H256::from(0));
// 1) length = 7
let length = 7;
assert!(array.set_len(&mut ext, length).is_ok());
assert_eq!(array.get_len(&ext).unwrap(), length);
// 2) array[1][2] = 0x1234
let index = 1;
let key = U256::from(2);
let submap = array.get_map(index);
let expected = U256::from(0x1234);
assert!(submap.set(&mut ext, &key, expected).is_ok());
assert_eq!(submap.get::<U256>(&ext, &key).unwrap(), expected);
// 4) array[1]["key"] = "1234"
let key = String::from("key");
let expected = String::from("1234");
assert!(submap
.set_bytes::<String, String>(&mut ext, &key, &expected)
.is_ok());
assert_eq!(
submap.get_bytes::<String, String>(&ext, &key).unwrap(),
expected.clone()
);
}
#[test]
fn test_map_simple() {
let mut ext = FakeExt::new();
let map = Map::new(H256::from(1));
// 1) map["key"] = "value"
let key = U256::from(1);
let value = U256::from(0x1234);
assert!(map.set(&mut ext, &key, value).is_ok());
assert_eq!(map.get(&ext, &key).unwrap(), value);
// 2) map[0] = "1234567890"
let key = U256::from(1);
let value = String::from("1234567890");
assert!(map.set_bytes(&mut ext, &key, &value).is_ok());
assert_eq!(
map.get_bytes::<U256, String>(&ext, &key).unwrap(),
value.clone()
);
// 3) map[0] = "123456789012345678901234567890123"
let key = U256::from(1);
let value = String::from("123456789012345678901234567890123");
assert!(map.set_bytes(&mut ext, &key, &value).is_ok());
assert_eq!(map.get_bytes::<U256, String>(&ext, &key).unwrap(), value);
// 4) map["key"] = 0x1234;
let key = String::from("key");
let value = U256::from(0x1234);
assert!(map.set(&mut ext, &key, value).is_ok());
assert_eq!(map.get(&ext, &key).unwrap(), value);;
}
#[test]
fn test_map_with_sub_array() {
let mut ext = FakeExt::new();
let mut map = Map::new(H256::from(1));
// 1) map["key1"]["key2"] = "1234567890"
let key1 = String::from("key1");
let index = 2u64;
let value = String::from("1234567890");
let sub_array = map.get_array(&key1).unwrap();
assert!(sub_array.set_bytes(&mut ext, index.clone(), &value).is_ok());
assert_eq!(
*sub_array.get_bytes::<String>(&ext, index.clone()).unwrap(),
value.clone()
);
// 2) map["key1"][2] = "1234567890"
let key1 = String::from("key1");
let index = 4u64;
let value = String::from("1234567890");
let sub_array = map.get_array(&key1).unwrap();
assert!(sub_array.set_bytes(&mut ext, index.clone(), &value).is_ok());
assert_eq!(
*sub_array.get_bytes::<String>(&ext, index.clone()).unwrap(),
value.clone()
);
}
#[test]
fn test_map_with_sub_map() {
let mut ext = FakeExt::new();
let mut map = Map::new(H256::from(1));
// 1) map["key1"]["key2"] = "1234567890"
let key1 = String::from("key1");
let key2 = String::from("key2");
let value = String::from("1234567890");
let sub_map = map.get_map(&key1).unwrap();
assert!(sub_map.set_bytes(&mut ext, &key2, &value).is_ok());
assert_eq!(
sub_map.get_bytes::<String, String>(&ext, &key2).unwrap(),
value.clone()
);
// 2) map["key1"][2] = "1234567890"
let key1 = String::from("key1");
let key2 = U256::from(2);
let value = String::from("1234567890");
let sub_map = map.get_map(&key1).unwrap();
assert!(sub_map.set_bytes(&mut ext, &key2, &value).is_ok());
assert_eq!(
sub_map.get_bytes::<_, String>(&ext, &key2).unwrap(),
value.clone()
);
}
}
[test] fix evm storage.rs unit test
use cita_types::{Address, H256, U256};
use cita_vm::evm::Error as EvmError;
use std::boxed::Box;
use std::convert::From;
use util::sha3;
use cita_vm::evm::DataProvider;
pub trait Serialize {
fn serialize(&self) -> Result<Vec<u8>, EvmError>;
}
pub trait Deserialize: Sized {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError>;
}
impl Serialize for U256 {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
//let mut vec = Vec::with_capacity(64);
let mut vec = vec![0; 32];
self.to_big_endian(&mut vec);
Ok(vec)
}
}
impl Deserialize for U256 {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Ok(U256::from(bytes))
}
}
impl Serialize for String {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
Ok(self.to_owned().into_bytes())
}
}
impl Deserialize for String {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Self::from_utf8(bytes.to_owned()).map_err(|_| EvmError::Internal("dup coin".to_string()))
}
}
impl Serialize for Vec<u8> {
fn serialize(&self) -> Result<Vec<u8>, EvmError> {
Ok(self.clone())
}
}
impl Deserialize for Vec<u8> {
fn deserialize(bytes: &[u8]) -> Result<Self, EvmError> {
Ok(Vec::from(bytes))
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Scalar {
position: H256,
}
impl Scalar {
pub fn new(position: H256) -> Self {
Scalar { position }
}
// single element
pub fn set(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
value: U256,
) -> Result<(), EvmError> {
ext.set_storage(addr, self.position, H256::from(value));
Ok(())
}
pub fn get(self: &Self, ext: &DataProvider, addr: &Address) -> Result<U256, EvmError> {
let value = ext.get_storage(addr, &self.position);
Ok(U256::from(value))
}
// bytes & string
pub fn set_bytes<T>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
value: &T,
) -> Result<(), EvmError>
where
T: Serialize,
{
let encoded = value.serialize()?;
let length = encoded.len();
if length < 32 {
let mut byte32 = [0u8; 32];
byte32[0..encoded.len()].copy_from_slice(&encoded);
byte32[31] = (length * 2) as u8;
ext.set_storage(addr, self.position, H256::from_slice(&byte32));
} else {
ext.set_storage(addr, self.position, H256::from((length * 2 + 1) as u64));
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
for chunk in encoded.chunks(32) {
let value = H256::from(chunk);
ext.set_storage(addr, H256::from(key), value);
key = key + U256::one();
}
}
Ok(())
}
pub fn get_bytes<T>(self: &Self, ext: &DataProvider, addr: &Address) -> Result<Box<T>, EvmError>
where
T: Deserialize,
{
let mut bytes = Vec::<u8>::new();
let first = ext.get_storage(addr, &self.position);
if first[31] % 2 == 0 {
let len = (first[31] / 2) as usize;
bytes.extend_from_slice(&first[0..len]);
let decoded = T::deserialize(&bytes)?;
Ok(Box::new(decoded))
} else {
let mut len = ((first.low_u64() as usize) - 1) / 2;
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
let mut bytes = Vec::new();
while len > 0 {
let v = ext.get_storage(addr, &H256::from(key));
if len > 32 {
bytes.extend_from_slice(v.as_ref());
key = key + U256::one();
len -= 32;
} else {
bytes.extend_from_slice(&v[0..len]);
len = 0;
}
}
Ok(Box::new(T::deserialize(&bytes)?))
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Array {
position: H256,
}
impl Array {
pub fn new(position: H256) -> Self {
Array { position }
}
#[inline]
fn key(&self, index: u64) -> H256 {
let mut key = U256::from(H256::from_slice(&sha3::keccak256(&self.position)));
key = key + U256::from(index);
H256::from(key)
}
pub fn set(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
index: u64,
value: &U256,
) -> Result<(), EvmError> {
let scalar = Scalar::new(self.key(index));
scalar.set(ext, addr, *value)
}
pub fn get(
self: &Self,
ext: &DataProvider,
addr: &Address,
index: u64,
) -> Result<U256, EvmError> {
let scalar = Scalar::new(self.key(index));
scalar.get(ext, addr)
}
pub fn set_bytes<T>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
index: u64,
value: &T,
) -> Result<(), EvmError>
where
T: Serialize,
{
let scalar = Scalar::new(self.key(index));
scalar.set_bytes(ext, addr, value)
}
pub fn get_bytes<T>(
self: &Self,
ext: &DataProvider,
addr: &Address,
index: u64,
) -> Result<Box<T>, EvmError>
where
T: Deserialize,
{
let scalar = Scalar::new(self.key(index));
scalar.get_bytes(ext, addr)
}
pub fn set_len(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
len: u64,
) -> Result<(), EvmError> {
ext.set_storage(addr, self.position, H256::from(len));
Ok(())
}
pub fn get_len(self: &Self, ext: &DataProvider, addr: &Address) -> Result<u64, EvmError> {
let len = ext.get_storage(addr, &self.position);
Ok(len.low_u64())
}
pub fn get_array(self: &mut Self, index: u64) -> Array {
Array::new(self.key(index))
}
pub fn get_map(self: &mut Self, index: u64) -> Map {
Map::new(self.key(index))
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Map {
position: H256,
}
impl Map {
pub fn new(position: H256) -> Self {
Map { position }
}
#[inline]
fn key<Key>(&self, key: &Key) -> Result<H256, EvmError>
where
Key: Serialize,
{
let mut bytes = Vec::new();
bytes.extend_from_slice(&key.serialize()?);
bytes.extend_from_slice(self.position.as_ref());
Ok(H256::from_slice(&sha3::keccak256(&bytes)))
}
pub fn set<Key>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
key: &Key,
value: U256,
) -> Result<(), EvmError>
where
Key: Serialize,
{
Scalar::new(self.key(key)?).set(ext, addr, value)
}
pub fn get<Key>(
self: &Self,
ext: &DataProvider,
addr: &Address,
key: &Key,
) -> Result<U256, EvmError>
where
Key: Serialize,
{
Scalar::new(self.key(key)?).get(ext, addr)
}
pub fn set_bytes<Key, Value>(
self: &Self,
ext: &mut DataProvider,
addr: &Address,
key: &Key,
value: &Value,
) -> Result<(), EvmError>
where
Key: Serialize,
Value: Serialize,
{
Scalar::new(self.key(key)?).set_bytes(ext, addr, value)
}
pub fn get_bytes<Key, Value>(
self: &Self,
ext: &DataProvider,
addr: &Address,
key: &Key,
) -> Result<Value, EvmError>
where
Key: Serialize,
Value: Deserialize,
{
Ok(*Scalar::new(self.key(key)?).get_bytes(ext, addr)?)
}
pub fn get_array<Key>(self: &mut Self, key: &Key) -> Result<Array, EvmError>
where
Key: Serialize,
{
Ok(Array::new(self.key(key)?))
}
pub fn get_map<Key>(self: &mut Self, key: &Key) -> Result<Map, EvmError>
where
Key: Serialize,
{
Ok(Map::new(self.key(key)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use cita_vm::evm::extmock::DataProviderMock;
use std::str::FromStr;
#[test]
fn test_scalar_bytes() {
// let mut ext = DataProviderMock::default();
let mut ext = DataProviderMock::default();
let scalar = Scalar::new(H256::from(0));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) length=30
let expected = format!("012345678901234567890123456789");
assert!(scalar.set_bytes(&mut ext, &code_address, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext, &code_address);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 2) length=31
let expected = format!("0123456789012345678901234567890");
assert!(scalar.set_bytes(&mut ext, &code_address, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext, &code_address);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 3) length=32
let expected = format!("01234567890123456789012345678901");
assert!(scalar.set_bytes(&mut ext, &code_address, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext, &code_address);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
// 4) length=43
let expected = format!("012345678901234567890123456789012");
assert!(scalar.set_bytes(&mut ext, &code_address, &expected).is_ok());
let value = scalar.get_bytes::<String>(&ext, &code_address);
assert!(value.is_ok());
assert_eq!(*value.unwrap().as_ref(), expected.clone());
}
#[test]
fn test_scalar_u256() {
let mut ext = DataProviderMock::default();
let scalar = Scalar::new(H256::from(0));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
let expected = U256::from(0x123456);
assert!(scalar
.set(&mut ext, &code_address, expected.clone())
.is_ok());
let value = scalar.get(&ext, &code_address);
assert!(value.is_ok());
assert_eq!(value.unwrap(), expected.clone());
}
#[test]
fn test_array_simple() {
let mut ext = DataProviderMock::default();
let length = 7u64;
let array = Array {
position: H256::from(0),
};
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) length
assert!(array.set_len(&mut ext, &code_address, length).is_ok());
assert_eq!(array.get_len(&ext, &code_address).unwrap(), length);
// 2) array[1] = 0x1234
let index = 1;
let expected = U256::from(0x1234);
assert!(array.set(&mut ext, &code_address, index, &expected).is_ok());
let value = array.get(&ext, &code_address, index);
assert_eq!(value.unwrap(), expected.clone());
// 3) array[3] = 0x2234
let index = 3;
let expected = U256::from(0x2234);
assert!(array.set(&mut ext, &code_address, index, &expected).is_ok());
let value = array.get(&ext, &code_address, index);
assert_eq!(value.unwrap(), expected.clone());
}
#[test]
fn test_array_with_sub_array() {
let mut ext = DataProviderMock::default();
let mut array = Array::new(H256::from(0));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) length = 7
let length = 7;
assert!(array.set_len(&mut ext, &code_address, length).is_ok());
assert_eq!(array.get_len(&ext, &code_address).unwrap(), length);
// 2) array[1].len = 8
let index = 1;
let subarray_length = 8;
let subarray = array.get_array(index);
assert!(subarray
.set_len(&mut ext, &code_address, subarray_length)
.is_ok());
assert_eq!(
subarray.get_len(&mut ext, &code_address).unwrap(),
subarray_length
);
// 3) array[1][2] = 0x1234
let index = 2;
let expected = U256::from(0x1234);
assert!(subarray
.set(&mut ext, &code_address, index, &expected)
.is_ok());
assert_eq!(subarray.get(&ext, &code_address, index).unwrap(), expected);
// 4) array[1][4] = 0x2234
let index = 4;
let expected = U256::from(0x2234);
assert!(subarray
.set(&mut ext, &code_address, index, &expected)
.is_ok());
assert_eq!(subarray.get(&ext, &code_address, index).unwrap(), expected);
}
#[test]
fn test_array_with_sub_map() {
let mut ext = DataProviderMock::default();
let mut array = Array::new(H256::from(0));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) length = 7
let length = 7;
assert!(array.set_len(&mut ext, &code_address, length).is_ok());
assert_eq!(array.get_len(&ext, &code_address).unwrap(), length);
// 2) array[1][2] = 0x1234
let index = 1;
let key = U256::from(2);
let submap = array.get_map(index);
let expected = U256::from(0x1234);
assert!(submap.set(&mut ext, &code_address, &key, expected).is_ok());
assert_eq!(
submap.get::<U256>(&ext, &code_address, &key).unwrap(),
expected
);
// 4) array[1]["key"] = "1234"
let key = String::from("key");
let expected = String::from("1234");
assert!(submap
.set_bytes::<String, String>(&mut ext, &code_address, &key, &expected)
.is_ok());
assert_eq!(
submap
.get_bytes::<String, String>(&ext, &code_address, &key)
.unwrap(),
expected.clone()
);
}
#[test]
fn test_map_simple() {
let mut ext = DataProviderMock::default();
let map = Map::new(H256::from(1));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) map["key"] = "value"
let key = U256::from(1);
let value = U256::from(0x1234);
assert!(map.set(&mut ext, &code_address, &key, value).is_ok());
assert_eq!(map.get(&ext, &code_address, &key).unwrap(), value);
// 2) map[0] = "1234567890"
let key = U256::from(1);
let value = String::from("1234567890");
assert!(map.set_bytes(&mut ext, &code_address, &key, &value).is_ok());
assert_eq!(
map.get_bytes::<U256, String>(&ext, &code_address, &key)
.unwrap(),
value.clone()
);
// 3) map[0] = "123456789012345678901234567890123"
let key = U256::from(1);
let value = String::from("123456789012345678901234567890123");
assert!(map.set_bytes(&mut ext, &code_address, &key, &value).is_ok());
assert_eq!(
map.get_bytes::<U256, String>(&ext, &code_address, &key)
.unwrap(),
value
);
// 4) map["key"] = 0x1234;
let key = String::from("key");
let value = U256::from(0x1234);
assert!(map.set(&mut ext, &code_address, &key, value).is_ok());
assert_eq!(map.get(&ext, &code_address, &key).unwrap(), value);;
}
#[test]
fn test_map_with_sub_array() {
let mut ext = DataProviderMock::default();
let mut map = Map::new(H256::from(1));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) map["key1"]["key2"] = "1234567890"
let key1 = String::from("key1");
let index = 2u64;
let value = String::from("1234567890");
let sub_array = map.get_array(&key1).unwrap();
assert!(sub_array
.set_bytes(&mut ext, &code_address, index.clone(), &value)
.is_ok());
assert_eq!(
*sub_array
.get_bytes::<String>(&ext, &code_address, index.clone())
.unwrap(),
value.clone()
);
// 2) map["key1"][2] = "1234567890"
let key1 = String::from("key1");
let index = 4u64;
let value = String::from("1234567890");
let sub_array = map.get_array(&key1).unwrap();
assert!(sub_array
.set_bytes(&mut ext, &code_address, index.clone(), &value)
.is_ok());
assert_eq!(
*sub_array
.get_bytes::<String>(&ext, &code_address, index.clone())
.unwrap(),
value.clone()
);
}
#[test]
fn test_map_with_sub_map() {
let mut ext = DataProviderMock::default();
let mut map = Map::new(H256::from(1));
let code_address = Address::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
// 1) map["key1"]["key2"] = "1234567890"
let key1 = String::from("key1");
let key2 = String::from("key2");
let value = String::from("1234567890");
let sub_map = map.get_map(&key1).unwrap();
assert!(sub_map
.set_bytes(&mut ext, &code_address, &key2, &value)
.is_ok());
assert_eq!(
sub_map
.get_bytes::<String, String>(&ext, &code_address, &key2)
.unwrap(),
value.clone()
);
// 2) map["key1"][2] = "1234567890"
let key1 = String::from("key1");
let key2 = U256::from(2);
let value = String::from("1234567890");
let sub_map = map.get_map(&key1).unwrap();
assert!(sub_map
.set_bytes(&mut ext, &code_address, &key2, &value)
.is_ok());
assert_eq!(
sub_map
.get_bytes::<_, String>(&ext, &code_address, &key2)
.unwrap(),
value.clone()
);
}
}
|
// Copyright 2013 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.
//! Interfaces to the operating system provided random number
//! generators.
use Rng;
#[cfg(unix)]
use reader::ReaderRng;
#[cfg(unix)]
use std::io::File;
#[cfg(windows)]
use std::cast;
#[cfg(windows)]
use std::libc::{c_long, DWORD, BYTE};
#[cfg(windows)]
type HCRYPTPROV = c_long;
// the extern functions imported from the runtime on Windows are
// implemented so that they either succeed or abort(), so we can just
// assume they work when we call them.
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
#[cfg(unix)]
pub struct OSRng {
priv inner: ReaderRng<File>
}
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
#[cfg(windows)]
pub struct OSRng {
priv hcryptprov: HCRYPTPROV
}
impl OSRng {
/// Create a new `OSRng`.
#[cfg(unix)]
pub fn new() -> OSRng {
let reader = File::open(&Path::new("/dev/urandom"));
let reader = reader.ok().expect("Error opening /dev/urandom");
let reader_rng = ReaderRng::new(reader);
OSRng { inner: reader_rng }
}
/// Create a new `OSRng`.
#[cfg(windows)]
pub fn new() -> OSRng {
extern { fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV); }
let mut hcp = 0;
unsafe {rust_win32_rand_acquire(&mut hcp)};
OSRng { hcryptprov: hcp }
}
}
#[cfg(unix)]
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}
fn fill_bytes(&mut self, v: &mut [u8]) {
self.inner.fill_bytes(v)
}
}
#[cfg(windows)]
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
extern {
fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD,
pbBuffer: *mut BYTE);
}
unsafe {rust_win32_rand_gen(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr())}
}
}
impl Drop for OSRng {
#[cfg(unix)]
fn drop(&mut self) {
// ensure that OSRng is not implicitly copyable on all
// platforms, for consistency.
}
#[cfg(windows)]
fn drop(&mut self) {
extern { fn rust_win32_rand_release(hProv: HCRYPTPROV); }
unsafe {rust_win32_rand_release(self.hcryptprov)}
}
}
#[cfg(test)]
mod test {
use super::OSRng;
use Rng;
use std::task;
#[test]
fn test_os_rng() {
let mut r = OSRng::new();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() {
let mut txs = ~[];
for _ in range(0, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OSRng::new();
task::deschedule();
let mut v = [0u8, .. 1000];
for _ in range(0, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
task::deschedule();
r.fill_bytes(v);
task::deschedule();
}
})
}
// start all the tasks
for tx in txs.iter() {
tx.send(())
}
}
}
rand: Rewrite OsRng in Rust for windows
This removes even more rust_builtin.c code, and allows us to more gracefully
handle errors (not a process panic, but a task failure).
// Copyright 2013 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.
//! Interfaces to the operating system provided random number
//! generators.
pub use self::imp::OSRng;
#[cfg(unix)]
mod imp {
use Rng;
use reader::ReaderRng;
use std::io::File;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
#[cfg(unix)]
pub struct OSRng {
priv inner: ReaderRng<File>
}
impl OSRng {
/// Create a new `OSRng`.
pub fn new() -> OSRng {
let reader = File::open(&Path::new("/dev/urandom"));
let reader = reader.ok().expect("Error opening /dev/urandom");
let reader_rng = ReaderRng::new(reader);
OSRng { inner: reader_rng }
}
}
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}
fn fill_bytes(&mut self, v: &mut [u8]) {
self.inner.fill_bytes(v)
}
}
}
#[cfg(windows)]
mod imp {
use Rng;
use std::cast;
use std::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
use std::os;
type HCRYPTPROV = c_ulong;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
pub struct OSRng {
priv hcryptprov: HCRYPTPROV
}
static PROV_RSA_FULL: DWORD = 1;
static CRYPT_SILENT: DWORD = 64;
static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
extern "system" {
fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
pszContainer: LPCSTR,
pszProvider: LPCSTR,
dwProvType: DWORD,
dwFlags: DWORD) -> BOOL;
fn CryptGenRandom(hProv: HCRYPTPROV,
dwLen: DWORD,
pbBuffer: *mut BYTE) -> BOOL;
fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
}
impl OSRng {
/// Create a new `OSRng`.
pub fn new() -> OSRng {
let mut hcp = 0;
let ret = unsafe {
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
};
if ret == 0 {
fail!("couldn't create context: {}", os::last_os_error());
}
OSRng { hcryptprov: hcp }
}
}
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v.as_mut_ptr())
};
if ret == 0 {
fail!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
impl Drop for OSRng {
fn drop(&mut self) {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
fail!("couldn't release context: {}", os::last_os_error());
}
}
}
}
#[cfg(test)]
mod test {
use super::OSRng;
use Rng;
use std::task;
#[test]
fn test_os_rng() {
let mut r = OSRng::new();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() {
let mut txs = ~[];
for _ in range(0, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OSRng::new();
task::deschedule();
let mut v = [0u8, .. 1000];
for _ in range(0, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
task::deschedule();
r.fill_bytes(v);
task::deschedule();
}
})
}
// start all the tasks
for tx in txs.iter() {
tx.send(())
}
}
}
|
// 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.
//! Interfaces to the operating system provided random number
//! generators.
pub use self::imp::OsRng;
#[cfg(unix, not(target_os = "ios"))]
mod imp {
use io::{IoResult, File};
use path::Path;
use rand::Rng;
use rand::reader::ReaderRng;
use result::{Ok, Err};
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
#[cfg(unix)]
pub struct OsRng {
inner: ReaderRng<File>
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
let reader = try!(File::open(&Path::new("/dev/urandom")));
let reader_rng = ReaderRng::new(reader);
Ok(OsRng { inner: reader_rng })
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}
fn fill_bytes(&mut self, v: &mut [u8]) {
self.inner.fill_bytes(v)
}
}
}
#[cfg(target_os = "ios")]
mod imp {
extern crate libc;
use collections::Collection;
use io::{IoResult};
use kinds::marker;
use mem;
use os;
use rand::Rng;
use result::{Ok};
use self::libc::{c_int, size_t};
use slice::MutableVector;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
pub struct OsRng {
marker: marker::NoCopy
}
struct SecRandom;
static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
#[link(name = "Security", kind = "framework")]
extern "C" {
fn SecRandomCopyBytes(rnd: *const SecRandom,
count: size_t, bytes: *mut u8) -> c_int;
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
Ok(OsRng {marker: marker::NoCopy} )
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
};
if ret == -1 {
fail!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
}
#[cfg(windows)]
mod imp {
extern crate libc;
use core_collections::Collection;
use io::{IoResult, IoError};
use mem;
use ops::Drop;
use os;
use rand::Rng;
use result::{Ok, Err};
use rt::stack;
use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
use slice::MutableVector;
type HCRYPTPROV = c_ulong;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
pub struct OsRng {
hcryptprov: HCRYPTPROV
}
static PROV_RSA_FULL: DWORD = 1;
static CRYPT_SILENT: DWORD = 64;
static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
#[allow(non_snake_case_functions)]
extern "system" {
fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
pszContainer: LPCSTR,
pszProvider: LPCSTR,
dwProvType: DWORD,
dwFlags: DWORD) -> BOOL;
fn CryptGenRandom(hProv: HCRYPTPROV,
dwLen: DWORD,
pbBuffer: *mut BYTE) -> BOOL;
fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
let mut hcp = 0;
let mut ret = unsafe {
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
};
// FIXME #13259:
// It turns out that if we can't acquire a context with the
// NTE_BAD_SIGNATURE error code, the documentation states:
//
// The provider DLL signature could not be verified. Either the
// DLL or the digital signature has been tampered with.
//
// Sounds fishy, no? As it turns out, our signature can be bad
// because our Thread Information Block (TIB) isn't exactly what it
// expects. As to why, I have no idea. The only data we store in the
// TIB is the stack limit for each thread, but apparently that's
// enough to make the signature valid.
//
// Furthermore, this error only happens the *first* time we call
// CryptAcquireContext, so we don't have to worry about future
// calls.
//
// Anyway, the fix employed here is that if we see this error, we
// pray that we're not close to the end of the stack, temporarily
// set the stack limit to 0 (what the TIB originally was), acquire a
// context, and then reset the stack limit.
//
// Again, I'm not sure why this is the fix, nor why we're getting
// this error. All I can say is that this seems to allow libnative
// to progress where it otherwise would be hindered. Who knew?
if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
unsafe {
let limit = stack::get_sp_limit();
stack::record_sp_limit(0);
ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
stack::record_sp_limit(limit);
}
}
if ret == 0 {
Err(IoError::last_error())
} else {
Ok(OsRng { hcryptprov: hcp })
}
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v.as_mut_ptr())
};
if ret == 0 {
fail!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
impl Drop for OsRng {
fn drop(&mut self) {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
fail!("couldn't release context: {}", os::last_os_error());
}
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::OsRng;
use rand::Rng;
use task;
#[test]
fn test_os_rng() {
let mut r = OsRng::new().unwrap();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() {
let mut txs = vec!();
for _ in range(0u, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OsRng::new().unwrap();
task::deschedule();
let mut v = [0u8, .. 1000];
for _ in range(0u, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
task::deschedule();
r.fill_bytes(v);
task::deschedule();
}
})
}
// start all the tasks
for tx in txs.iter() {
tx.send(())
}
}
}
Fix crash in OsRng when compiling with -O.
// 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.
//! Interfaces to the operating system provided random number
//! generators.
pub use self::imp::OsRng;
#[cfg(unix, not(target_os = "ios"))]
mod imp {
use io::{IoResult, File};
use path::Path;
use rand::Rng;
use rand::reader::ReaderRng;
use result::{Ok, Err};
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
#[cfg(unix)]
pub struct OsRng {
inner: ReaderRng<File>
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
let reader = try!(File::open(&Path::new("/dev/urandom")));
let reader_rng = ReaderRng::new(reader);
Ok(OsRng { inner: reader_rng })
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}
fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}
fn fill_bytes(&mut self, v: &mut [u8]) {
self.inner.fill_bytes(v)
}
}
}
#[cfg(target_os = "ios")]
mod imp {
extern crate libc;
use collections::Collection;
use io::{IoResult};
use kinds::marker;
use mem;
use os;
use rand::Rng;
use result::{Ok};
use self::libc::{c_int, size_t};
use slice::MutableVector;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
pub struct OsRng {
marker: marker::NoCopy
}
struct SecRandom;
static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
#[link(name = "Security", kind = "framework")]
extern "C" {
fn SecRandomCopyBytes(rnd: *const SecRandom,
count: size_t, bytes: *mut u8) -> c_int;
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
Ok(OsRng {marker: marker::NoCopy} )
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
};
if ret == -1 {
fail!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
}
#[cfg(windows)]
mod imp {
extern crate libc;
use core_collections::Collection;
use io::{IoResult, IoError};
use mem;
use ops::Drop;
use os;
use rand::Rng;
use result::{Ok, Err};
use rt::stack;
use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
use self::libc::types::os::arch::extra::{LONG_PTR};
use slice::MutableVector;
type HCRYPTPROV = LONG_PTR;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
///
/// This does not block.
pub struct OsRng {
hcryptprov: HCRYPTPROV
}
static PROV_RSA_FULL: DWORD = 1;
static CRYPT_SILENT: DWORD = 64;
static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
#[allow(non_snake_case_functions)]
extern "system" {
fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
pszContainer: LPCSTR,
pszProvider: LPCSTR,
dwProvType: DWORD,
dwFlags: DWORD) -> BOOL;
fn CryptGenRandom(hProv: HCRYPTPROV,
dwLen: DWORD,
pbBuffer: *mut BYTE) -> BOOL;
fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
let mut hcp = 0;
let mut ret = unsafe {
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
};
// FIXME #13259:
// It turns out that if we can't acquire a context with the
// NTE_BAD_SIGNATURE error code, the documentation states:
//
// The provider DLL signature could not be verified. Either the
// DLL or the digital signature has been tampered with.
//
// Sounds fishy, no? As it turns out, our signature can be bad
// because our Thread Information Block (TIB) isn't exactly what it
// expects. As to why, I have no idea. The only data we store in the
// TIB is the stack limit for each thread, but apparently that's
// enough to make the signature valid.
//
// Furthermore, this error only happens the *first* time we call
// CryptAcquireContext, so we don't have to worry about future
// calls.
//
// Anyway, the fix employed here is that if we see this error, we
// pray that we're not close to the end of the stack, temporarily
// set the stack limit to 0 (what the TIB originally was), acquire a
// context, and then reset the stack limit.
//
// Again, I'm not sure why this is the fix, nor why we're getting
// this error. All I can say is that this seems to allow libnative
// to progress where it otherwise would be hindered. Who knew?
if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
unsafe {
let limit = stack::get_sp_limit();
stack::record_sp_limit(0);
ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
stack::record_sp_limit(limit);
}
}
if ret == 0 {
Err(IoError::last_error())
} else {
Ok(OsRng { hcryptprov: hcp })
}
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v.as_mut_ptr())
};
if ret == 0 {
fail!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
impl Drop for OsRng {
fn drop(&mut self) {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
fail!("couldn't release context: {}", os::last_os_error());
}
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::OsRng;
use rand::Rng;
use task;
#[test]
fn test_os_rng() {
let mut r = OsRng::new().unwrap();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() {
let mut txs = vec!();
for _ in range(0u, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OsRng::new().unwrap();
task::deschedule();
let mut v = [0u8, .. 1000];
for _ in range(0u, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
task::deschedule();
r.fill_bytes(v);
task::deschedule();
}
})
}
// start all the tasks
for tx in txs.iter() {
tx.send(())
}
}
}
|
extern crate rusqlite;
use self::rusqlite::Connection;
pub fn hello_from_logic() -> String {
"Hello, I am bookmark dao!".to_string()
}
create connection
extern crate rusqlite;
use self::rusqlite::Connection;
pub fn create_connection() -> bool{
Connection::open_in_memory().unwrap();
return false;
}
pub fn hello_from_logic() -> String {
"Hello, I am bookmark dao!".to_string()
}
|
pub enum Flag {
Set(&'static str),
Clear(&'static str),
NotAffected(&'static str),
Undefined,
}
pub struct FlagsDesc {
pub x: Flag,
pub n: Flag,
pub z: Flag,
pub v: Flag,
pub c: Flag,
}
const FLAGS_ARC: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Set("N - Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow is generated; cleared otherwise."),
c: Flag::Set("C — Set if a carry is generated; cleared otherwise."),
};
const FLAGS_X: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Set("N - Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Cleared if the result is non-zero; unchanged otherwise."),
v: Flag::Set("V — Set if an overflow is generated; cleared otherwise."),
c: Flag::Set("C — Set if a carry is generated; cleared otherwise."),
};
const FLAGS_ABCD: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Undefined,
z: Flag::Clear("Z — Cleared if the result is nonzero; unchanged otherwise"),
v: Flag::Undefined,
c: Flag::Set("C — Set if a decimal carry was generated; cleared otherwise."),
};
const FLAGS_AND: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not Affected"),
n: Flag::Set("N — Set if the most significant bit of the result is set; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_SHIFT: FlagsDesc = FlagsDesc {
x: Flag::Set("X — Set according to the last bit shifted out of the operand; unaffected for a shift count of zero."),
n: Flag::Set("N — Set if the most significant bit of the result is set; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if the most significant bit is changed at any time during the shift operation; cleared otherwise."),
c: Flag::Set("C — Set according to the last bit shifted out of the operand; cleared for a shift count of zero."),
};
const FLAGS_BINST: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::NotAffected("N — Not Affected."),
z: Flag::Set("Z — Set if the bit tested is zero; cleared otherwise."),
v: Flag::NotAffected("V — Not Affected."),
c: Flag::NotAffected("C — Not Affected."),
};
const FLAGS_NOT_AFFECTED: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::NotAffected("N — Not Affected."),
z: Flag::NotAffected("Z — Not Affected."),
v: Flag::NotAffected("V — Not Affected."),
c: Flag::NotAffected("C — Not Affected."),
};
const FLAGS_CLR: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Clear("N — Always cleared."),
z: Flag::Set("Z — Always set."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_CMP: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow occurs; cleared otherwise."),
c: Flag::Set("C — Set if a borrow occurs; cleared otherwise."),
};
const FLAGS_DIV: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Set("N — Set if the quotient is negative; cleared otherwise; undefined if overflow or divide by zero occurs."),
z: Flag::Set("Z — Set if the quotient is zero; cleared otherwise; undefined if overflow or divide by zero occurs."),
v: Flag::Set("V — Set if division overflow occurs; undefined if divide by zero occurs; cleared otherwise."),
c: Flag::Set("C — Always cleared."),
};
pub struct Description {
pub description: &'static str,
pub operation: &'static str,
pub assembler: &'static [&'static str],
pub attributes: &'static str,
pub flags: &'static FlagsDesc,
}
pub const ABCD_DESC: Description = Description {
description: "Adds the source operand to the destination operand along with the extend bit, and stores the result in the destination location. The addition is performed using binary- coded decimal arithmetic. The operands, which are packed binary-coded decimal numbers, can be addressed in two different ways\n
1. Data Register to Data Register: The operands are contained in the data registers specified in the instruction.\n
2. Memory to Memory: The operands are addressed with the predecrement addressing mode using the address registers specified in the instruction.\n
This operation is a byte operation only.",
operation: "Source10 + Destination10 + X → Destination",
assembler: &["abcd < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ABCD,
};
pub const ADD_DESC: Description = Description {
description: "Adds the source operand to the destination operand using binary addition and stores the result in the destination location. The size of the operation may be specified as byte, word, or long. The mode of the instruction indicates which operand is the source and which is the destination, as well as the operand size.",
operation: "Source + Destination → Destination",
assembler: &["Add < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ARC,
};
pub const ADDQ_DESC: Description = Description {
description: "Adds an immediate value of one to eight to the operand at the destination location. The size of the operation may be specified as byte, word, or long. Word and long operations are also allowed on the address registers. When adding to address registers, the condition codes are not altered, and the entire destination address register is used regardless of the operation size.",
operation: "Immidate + Destination → Destination",
assembler: &["addq # < data > , < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ARC,
};
pub const ADDX_DESC: Description = Description {
description: "Adds the source operand and the extend bit to the destination operand and stores the result in the destination location. The operands can be addressed in two different ways:
1. Data register to data register—The data registers specified in the instruction contain the operands.
2. Memory to memory—The address registers specified in the instruction address the operands using the predecrement addressing mode.
The size of the operation can be specified as byte, word, or long.",
operation: "Source + Destination + X → Destination",
assembler: &["addx Dy,Dx", "addx -(Ay),-(Ax)"],
attributes: "Byte, Word, Long",
flags: &FLAGS_X,
};
pub const AND_DESC: Description = Description {
description: "Performs an AND operation of the source operand with the destination operand and stores the result in the destination location. The size of the operation can be specified as byte, word, or long. The contents of an address register may not be used as an operand.",
operation: "Source & Destination → Destination",
assembler: &["and < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_AND,
};
pub const ASL_ASR_DESC: Description = Description {
description: "Arithmetically shifts the bits of the operand in the direction (L or R) specified. The carry bit receives the last bit shifted out of the operand. The shift count for the shifting of a register may be specified in two different ways:
1. Immediate—The shift count is specified in the instruction (shift range, 1 – 8).
2. Register—The shift count is the value in the data register specified in instruction modulo 64.
The size of the operation can be specified as byte, word, or long. An operand in mem- ory can be shifted one bit only, and the operand size is restricted to a word.
For ASL, the operand is shifted left; the number of positions shifted is the shift count. Bits shifted out of the high-order bit go to both the carry and the extend bits; zeros are shifted into the low-order bit. The overflow bit indicates if any sign changes occur dur- ing the shift.",
operation: "Destination Shifted By Count → Destination",
assembler: &["ASd Dx,Dy", "ASd # < data > ,Dy", "ASd < ea >", "where d is direction, L or R"],
attributes: "Byte, Word, Long",
flags: &FLAGS_SHIFT,
};
pub const BCC_DESC: Description = Description {
description: "If the specified condition is true, program execution continues at location (PC) + displacement.
The program counter contains the address of the instruction word for the Bcc instruction plus two.
The displacement is a twos-complement integer that represents the relative distance in bytes from the current program counter to the destination program counter.
If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used.
If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.
Condition code cc specifies one of the following conditional tests.",
operation: "If Condition True Then PC + dn → PC",
assembler: &["bcc < label >"],
attributes: "Byte, Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BCHG_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately, then inverts the specified bit in the destination. When the destination is a data register, any of the 32 bits can be specified by the modulo 32-bit number. When the destination is a memory location, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation may be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < number > of Destination) → Z;
TEST ( < number > of Destination) → < bit number > of Destination",
assembler: &["bchg dn, < ea >", "bchg # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BCLR_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately, then clears the specified bit in the destination. When a data register is the destination, any of the 32 bits can be specified by a modulo 32-bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z; 0 → < bit number > of Destination",
assembler: &["bclr dn, < ea >", "bclr # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BRA_DESC: Description = Description {
description: "Program execution continues at location (PC) + displacement. The program counter contains the address of the instruction word of the BRA instruction plus two. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used. If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.",
operation: "PC + dn → PC",
assembler: &["bra < label >"],
attributes: "Byte, Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BSET_DESC: Description = Description {
description: "Description: Tests a bit in the destination operand and sets the Z condition code appropriately, then sets the specified bit in the destination operand. When a data register is the destination, any of the 32 bits can be specified by a modulo 32-bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in the second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z; 1 → < bit number > of Destination",
assembler: &["btest dn, < ea >", "btest # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BSR_DESC: Description = Description {
description: "Pushes the long-word address of the instruction immediately following the BSR instruction onto the system stack. The program counter contains the address of the instruction word plus two. Program execution then continues at location (PC) + displacement. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used. If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.",
operation: "SP – 4 → SP; PC → (SP); PC + dn → PC",
assembler: &["bsr < label >"],
attributes: "Byte, Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BTST_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately. When a data register is the destination, any of the 32 bits can be specified by a modulo 32- bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z",
assembler: &["btest dn, < ea >", "btest # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const CLR_DESC: Description = Description {
description: "Clears the destination operand to zero. The size of the operation may be specified as byte, word, or long.",
operation: " 0 → Destination",
assembler: &["clr < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CLR,
};
pub const CMP_DESC: Description = Description {
description: "Subtracts the source operand from the destination data register and sets the condition codes according to the result; the data register is not changed. The size of the operation can be byte, word, or long.",
operation: "Destination – Source → cc",
assembler: &["cmp < ea > , Dn"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CMP,
};
pub const CMPM_DESC: Description = Description {
description: "Subtracts the source operand from the destination operand and sets the condition codes according to the results; the destination location is not changed. The operands are always addressed with the postincrement addressing mode, using the address registers specified in the instruction. The size of the operation may be specified as byte, word, or long.",
operation: "Destination – Source → cc",
assembler: &["cmpm (Ay) + ,(Ax) +"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CMP,
};
pub const DBCC_DESC: Description = Description {
description: "Description: Controls a loop of instructions. The parameters are a condition code, a data register (counter), and a displacement value. The instruction first tests the condition for termination; if it is true, no operation is performed. If the termination condition is not true, the low-order 16 bits of the counter data register decrement by one. If the result is – 1, execution continues with the next instruction. If the result is not equal to – 1, execution continues at the location indicated by the current value of the program counter plus the sign-extended 16-bit displacement. The value in the program counter is the address of the instruction word of the DBcc instruction plus two. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. Condition code cc specifies one of the following conditional tests:",
operation: " If Condition False
Then (Dn – 1 → Dn; If Dn not equal – 1 Then PC + dn → PC)",
assembler: &["dbcc dn, < label >"],
attributes: "Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const DIVS_DIVU_DESC: Description = Description {
description: "Divides the signed destination operand by the signed source operand and stores the signed result in the destination. The result is a quotient in the lower word (least significant 16 bits) and a remainder in the upper word (most significant 16 bits). The sign of the remainder is the same as the sign of the dividend.
Two special conditions may arise during the operation:
1. Division by zero causes a trap.
2. Overflow may be detected and set before the instruction completes. If the instruction detects an overflow, it sets the overflow condition code, and the operands are unaffected.",
operation: "Destination / Source → Destination",
assembler: &["DIVS.W < ea > ,Dn32/16 → 16r – 16q"],
attributes: "Word",
flags: &FLAGS_DIV,
};
Description for most 000 instructions
pub enum Flag {
Set(&'static str),
Clear(&'static str),
NotAffected(&'static str),
Undefined,
}
pub struct FlagsDesc {
pub x: Flag,
pub n: Flag,
pub z: Flag,
pub v: Flag,
pub c: Flag,
}
const FLAGS_ARC: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Set("N - Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow is generated; cleared otherwise."),
c: Flag::Set("C — Set if a carry is generated; cleared otherwise."),
};
const FLAGS_X: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Set("N - Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Cleared if the result is non-zero; unchanged otherwise."),
v: Flag::Set("V — Set if an overflow is generated; cleared otherwise."),
c: Flag::Set("C — Set if a carry is generated; cleared otherwise."),
};
const FLAGS_ABCD: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Undefined,
z: Flag::Clear("Z — Cleared if the result is nonzero; unchanged otherwise"),
v: Flag::Undefined,
c: Flag::Set("C — Set if a decimal carry was generated; cleared otherwise."),
};
const FLAGS_AND: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not Affected"),
n: Flag::Set("N — Set if the most significant bit of the result is set; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_SHIFT: FlagsDesc = FlagsDesc {
x: Flag::Set("X — Set according to the last bit shifted out of the operand; unaffected for a shift count of zero."),
n: Flag::Set("N — Set if the most significant bit of the result is set; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if the most significant bit is changed at any time during the shift operation; cleared otherwise."),
c: Flag::Set("C — Set according to the last bit shifted out of the operand; cleared for a shift count of zero."),
};
const FLAGS_BINST: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::NotAffected("N — Not Affected."),
z: Flag::Set("Z — Set if the bit tested is zero; cleared otherwise."),
v: Flag::NotAffected("V — Not Affected."),
c: Flag::NotAffected("C — Not Affected."),
};
const FLAGS_NOT_AFFECTED: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::NotAffected("N — Not Affected."),
z: Flag::NotAffected("Z — Not Affected."),
v: Flag::NotAffected("V — Not Affected."),
c: Flag::NotAffected("C — Not Affected."),
};
const FLAGS_CLR: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Clear("N — Always cleared."),
z: Flag::Set("Z — Always set."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_CMP: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow occurs; cleared otherwise."),
c: Flag::Set("C — Set if a borrow occurs; cleared otherwise."),
};
const FLAGS_DIV: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X — Not Affected."),
n: Flag::Set("N — Set if the quotient is negative; cleared otherwise; undefined if overflow or divide by zero occurs."),
z: Flag::Set("Z — Set if the quotient is zero; cleared otherwise; undefined if overflow or divide by zero occurs."),
v: Flag::Set("V — Set if division overflow occurs; undefined if divide by zero occurs; cleared otherwise."),
c: Flag::Set("C — Always cleared."),
};
const FLAGS_EXT: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not Affected"),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_MUL: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not Affected"),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if overflow; cleared otherwise."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_NEG: FlagsDesc = FlagsDesc {
x: Flag::Set("X — Set the same as the carry bit."),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow occurs; cleared otherwise."),
c: Flag::Set("C — Cleared if the result is zero; set otherwise."),
};
const FLAGS_NEGX: FlagsDesc = FlagsDesc {
x: Flag::Set("X — Set the same as the carry bit."),
n: Flag::Set("N — Set if the result is negative; cleared otherwise."),
z: Flag::Clear("Z — Cleared if the result is nonzero; unchanged otherwise."),
v: Flag::Set("V — Set if an overflow occurs; cleared otherwise."),
c: Flag::Set("C — Set if a borrow occurs; cleared otherwise."),
};
const FLAGS_ROL: FlagsDesc = FlagsDesc {
x: Flag::Set("X — Not affected."),
n: Flag::Set("N — Set if the most significant bit of the result is set; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Clear("V - Always cleared."),
c: Flag::Set("C — Set according to the last bit rotated out of the operand; cleared when the rotate count is zero."),
};
const FLAGS_SUB: FlagsDesc = FlagsDesc {
x: Flag::Set("X - Set the same as carry"),
n: Flag::Set("N - Set if the result is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the result is zero; cleared otherwise."),
v: Flag::Set("V — Set if an overflow is generated; cleared otherwise."),
c: Flag::Set("C — Set if a borrow is generated; cleared otherwise."),
};
const FLAGS_SWAP: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not affected"),
n: Flag::Set("Set if the most significant bit of the 32-bit result is set; cleared otherwise."),
z: Flag::Set("Set if the 32-bit result is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_TAS: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not affected"),
n: Flag::Set("N - Set if the most significant bit of the operand is currently set; cleared otherwise."),
z: Flag::Set("Z - Set if the 32-bit result is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
const FLAGS_TST: FlagsDesc = FlagsDesc {
x: Flag::NotAffected("X - Not affected"),
n: Flag::Set("N — Set if the operand is negative; cleared otherwise."),
z: Flag::Set("Z — Set if the operand is zero; cleared otherwise."),
v: Flag::Clear("V — Always cleared."),
c: Flag::Clear("C — Always cleared."),
};
pub struct Description {
pub description: &'static str,
pub operation: &'static str,
pub assembler: &'static [&'static str],
pub attributes: &'static str,
pub flags: &'static FlagsDesc,
}
pub const ABCD_DESC: Description = Description {
description: "Adds the source operand to the destination operand along with the extend bit, and stores the result in the destination location. The addition is performed using binary- coded decimal arithmetic. The operands, which are packed binary-coded decimal numbers, can be addressed in two different ways\n
1. Data Register to Data Register: The operands are contained in the data registers specified in the instruction.\n
2. Memory to Memory: The operands are addressed with the predecrement addressing mode using the address registers specified in the instruction.\n
This operation is a byte operation only.",
operation: "Source10 + Destination10 + X → Destination",
assembler: &["abcd < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ABCD,
};
pub const ADD_DESC: Description = Description {
description: "Adds the source operand to the destination operand using binary addition and stores the result in the destination location. The size of the operation may be specified as byte, word, or long. The mode of the instruction indicates which operand is the source and which is the destination, as well as the operand size.",
operation: "Source + Destination → Destination",
assembler: &["Add < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ARC,
};
pub const ADDQ_DESC: Description = Description {
description: "Adds an immediate value of one to eight to the operand at the destination location. The size of the operation may be specified as byte, word, or long. Word and long operations are also allowed on the address registers. When adding to address registers, the condition codes are not altered, and the entire destination address register is used regardless of the operation size.",
operation: "Immidate + Destination → Destination",
assembler: &["addq # < data > , < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ARC,
};
pub const ADDX_DESC: Description = Description {
description: "Adds the source operand and the extend bit to the destination operand and stores the result in the destination location. The operands can be addressed in two different ways:
1. Data register to data register—The data registers specified in the instruction contain the operands.
2. Memory to memory—The address registers specified in the instruction address the operands using the predecrement addressing mode.
The size of the operation can be specified as byte, word, or long.",
operation: "Source + Destination + X → Destination",
assembler: &["addx Dy,Dx", "addx -(Ay),-(Ax)"],
attributes: "Byte, Word, Long",
flags: &FLAGS_X,
};
pub const AND_DESC: Description = Description {
description: "Performs an AND operation of the source operand with the destination operand and stores the result in the destination location. The size of the operation can be specified as byte, word, or long. The contents of an address register may not be used as an operand.",
operation: "Source & Destination → Destination",
assembler: &["and < ea > ,Dn", "Add Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_AND,
};
pub const ASL_ASR_DESC: Description = Description {
description: "Arithmetically shifts the bits of the operand in the direction (L or R) specified. The carry bit receives the last bit shifted out of the operand. The shift count for the shifting of a register may be specified in two different ways:
1. Immediate—The shift count is specified in the instruction (shift range, 1 – 8).
2. Register—The shift count is the value in the data register specified in instruction modulo 64.
The size of the operation can be specified as byte, word, or long. An operand in mem- ory can be shifted one bit only, and the operand size is restricted to a word.
For ASL, the operand is shifted left; the number of positions shifted is the shift count. Bits shifted out of the high-order bit go to both the carry and the extend bits; zeros are shifted into the low-order bit. The overflow bit indicates if any sign changes occur dur- ing the shift.",
operation: "Destination Shifted By Count → Destination",
assembler: &["ASd Dx,Dy", "ASd # < data > ,Dy", "ASd < ea >", "where d is direction, L or R"],
attributes: "Byte, Word, Long",
flags: &FLAGS_SHIFT,
};
pub const BCC_DESC: Description = Description {
description: "If the specified condition is true, program execution continues at location (PC) + displacement.
The program counter contains the address of the instruction word for the Bcc instruction plus two.
The displacement is a twos-complement integer that represents the relative distance in bytes from the current program counter to the destination program counter.
If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used.
If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.
Condition code cc specifies one of the following conditional tests.",
operation: "If Condition True Then PC + dn → PC",
assembler: &["bcc < label >"],
attributes: "Byte, Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BCHG_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately, then inverts the specified bit in the destination. When the destination is a data register, any of the 32 bits can be specified by the modulo 32-bit number. When the destination is a memory location, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation may be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < number > of Destination) → Z;
TEST ( < number > of Destination) → < bit number > of Destination",
assembler: &["bchg dn, < ea >", "bchg # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BCLR_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately, then clears the specified bit in the destination. When a data register is the destination, any of the 32 bits can be specified by a modulo 32-bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z; 0 → < bit number > of Destination",
assembler: &["bclr dn, < ea >", "bclr # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BRA_DESC: Description = Description {
description: "Program execution continues at location (PC) + displacement. The program counter contains the address of the instruction word of the BRA instruction plus two. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used. If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.",
operation: "PC + dn → PC",
assembler: &["bra < label >"],
attributes: "Byte, Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BSET_DESC: Description = Description {
description: "Description: Tests a bit in the destination operand and sets the Z condition code appropriately, then sets the specified bit in the destination operand. When a data register is the destination, any of the 32 bits can be specified by a modulo 32-bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in the second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z; 1 → < bit number > of Destination",
assembler: &["btest dn, < ea >", "btest # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const BSR_DESC: Description = Description {
description: "Pushes the long-word address of the instruction immediately following the BSR instruction onto the system stack. The program counter contains the address of the instruction word plus two. Program execution then continues at location (PC) + displacement. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. If the 8-bit displacement field in the instruction word is zero, a 16-bit displacement (the word immediately following the instruction) is used. If the 8-bit displacement field in the instruction word is all ones ($FF), the 32-bit displacement (long word immediately following the instruction) is used.",
operation: "SP – 4 → SP; PC → (SP); PC + dn → PC",
assembler: &["bsr < label >"],
attributes: "Byte, Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const BTST_DESC: Description = Description {
description: "Tests a bit in the destination operand and sets the Z condition code appropriately. When a data register is the destination, any of the 32 bits can be specified by a modulo 32- bit number. When a memory location is the destination, the operation is a byte operation, and the bit number is modulo 8. In all cases, bit zero refers to the least significant bit. The bit number for this operation can be specified in either of two ways:
1. Immediate—The bit number is specified in a second word of the instruction.
2. Register—The specified data register contains the bit number.",
operation: "TEST ( < bit number > of Destination) → Z",
assembler: &["btest dn, < ea >", "btest # < data > , < ea >"],
attributes: "Byte, Long",
flags: &FLAGS_BINST,
};
pub const CLR_DESC: Description = Description {
description: "Clears the destination operand to zero. The size of the operation may be specified as byte, word, or long.",
operation: " 0 → Destination",
assembler: &["clr < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CLR,
};
pub const CMP_DESC: Description = Description {
description: "Subtracts the source operand from the destination data register and sets the condition codes according to the result; the data register is not changed. The size of the operation can be byte, word, or long.",
operation: "Destination – Source → cc",
assembler: &["cmp < ea > , Dn"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CMP,
};
pub const CMPM_DESC: Description = Description {
description: "Subtracts the source operand from the destination operand and sets the condition codes according to the results; the destination location is not changed. The operands are always addressed with the postincrement addressing mode, using the address registers specified in the instruction. The size of the operation may be specified as byte, word, or long.",
operation: "Destination – Source → cc",
assembler: &["cmpm (Ay) + ,(Ax) +"],
attributes: "Byte, Word, Long",
flags: &FLAGS_CMP,
};
pub const DBCC_DESC: Description = Description {
description: "Description: Controls a loop of instructions. The parameters are a condition code, a data register (counter), and a displacement value. The instruction first tests the condition for termination; if it is true, no operation is performed. If the termination condition is not true, the low-order 16 bits of the counter data register decrement by one. If the result is – 1, execution continues with the next instruction. If the result is not equal to – 1, execution continues at the location indicated by the current value of the program counter plus the sign-extended 16-bit displacement. The value in the program counter is the address of the instruction word of the DBcc instruction plus two. The displacement is a twos complement integer that represents the relative distance in bytes from the current program counter to the destination program counter. Condition code cc specifies one of the following conditional tests:",
operation: " If Condition False
Then (Dn – 1 → Dn; If Dn not equal – 1 Then PC + dn → PC)",
assembler: &["dbcc dn, < label >"],
attributes: "Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const DIVS_DIVU_DESC: Description = Description {
description: "Divides the signed destination operand by the signed source operand and stores the signed result in the destination. The result is a quotient in the lower word (least significant 16 bits) and a remainder in the upper word (most significant 16 bits). The sign of the remainder is the same as the sign of the dividend.
Two special conditions may arise during the operation:
1. Division by zero causes a trap.
2. Overflow may be detected and set before the instruction completes. If the instruction detects an overflow, it sets the overflow condition code, and the operands are unaffected.",
operation: "Destination / Source → Destination",
assembler: &["DIVS.W < ea > ,Dn32/16 → 16r – 16q"],
attributes: "Word",
flags: &FLAGS_DIV,
};
pub const EOR_DESC: Description = Description {
description: "Performs an exclusive-OR operation on the destination operand using the source operand and stores the result in the destination location. The size of the operation may be specified to be byte, word, or long. The source operand must be a data register. The destination operand is specified in the effective address field.",
operation: "Destination EOR Source → Destination",
assembler: &["eor Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_AND,
};
pub const EXG_DESC: Description = Description {
description: "Exchanges the contents of two 32-bit registers. The instruction performs three types of exchanges.
1. Exchange data registers.
2. Exchange address registers.
3. Exchange a data register and an address register.",
operation: "Rx ←→ Ry",
assembler: &["exg Dx,Dy", "exg Ax,Ay", "exg Dx,Ay"],
attributes: "Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const EXT_DESC: Description = Description {
description: " Extends a byte in a data register to a word or a long word, or a word in a data register to a long word, by replicating the sign bit to the left. If the operation extends a byte to a word, bit 7 of the designated data register is copied to bits 15 – 8 of that data register. If the operation extends a word to a long word, bit 15 of the designated data register is copied to bits 31 – 16 of the data register.",
operation: "Destination Sign-Extended → Destination",
assembler: &["ext.w Dn - extend byte to word", "ext.l Dn - extend word to long"],
attributes: "Word, Long",
flags: &FLAGS_EXT,
};
pub const JMP_DESC: Description = Description {
description: "Program execution continues at the effective address specified by the instruction. The addressing mode for the effective address must be a control addressing mode.",
operation: "Destination Address → PC",
assembler: &["jmp < ea > "],
attributes: "Unsized",
flags: &FLAGS_NOT_AFFECTED,
};
pub const LEA_DESC: Description = Description {
description: "Loads the effective address into the specified address register. All 32 bits of the address register are affected by this instruction.",
operation: "< ea > → An",
assembler: &["lea < ea >, An "],
attributes: "Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const LINK_DESC: Description = Description {
description: "Pushes the contents of the specified address register onto the stack. Then loads the updated stack pointer into the address register. Finally, adds the displacement value to the stack pointer. For word-size operation, the displacement is the sign-extended word following the operation word. For long size operation, the displacement is the long word following the operation word. The address register occupies one long word on the stack. The user should specify a negative displacement in order to allocate stack area.",
operation: "SP – 4 → SP; An → (SP); SP → An; SP + dn → SP",
assembler: &["link An, # < displacement >"],
attributes: "Word",
flags: &FLAGS_NOT_AFFECTED,
};
pub const LSL_LSR_DESC: Description = Description {
description: "Shifts the bits of the operand in the direction specified (L or R). The carry bit receives the last bit shifted out of the operand. The shift count for the shifting of a register is specified in two different ways:
1. Immediate—The shift count (1 – 8) is specified in the instruction.
2. Register—The shift count is the value in the data register specified in the in- struction modulo 64.
The size of the operation for register destinations may be specified as byte, word, or long. The contents of memory, < ea > , can be shifted one bit only, and the operand size is restricted to a word.
The LSL instruction shifts the operand to the left the number of positions specified as the shift count. Bits shifted out of the high-order bit go to both the carry and the extend bits; zeros are shifted into the low-order bit.",
operation: "Destination Shifted By Count → Destination",
assembler: &["LSd Dx,Dy", "LSd # < data > ,Dy", "LSd < ea >", "where d is direction, L or R"],
attributes: "Byte, Word, Long",
flags: &FLAGS_SHIFT,
};
pub const MOVE_DESC: Description = Description {
description: "Moves the data at the source to the destination location and sets the condition codes according to the data. The size of the operation may be specified as byte, word, or long.",
operation: "Source → Destination",
assembler: &["move < ea >, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_EXT,
};
pub const MOVEM_DESC: Description = Description {
description: "Moves the contents of selected registers to or from consecutive memory locations starting at the location specified by the effective address. A register is selected if the bit in the mask field corresponding to that register is set. The instruction size determines whether 16 or 32 bits of each register are transferred. In the case of a word transfer to either address or data registers, each word is sign-extended to 32 bits, and the resulting long word is loaded into the associated register.
Selecting the addressing mode also selects the mode of operation of the MOVEM instruction, and only the control modes, the predecrement mode, and the postincre- ment mode are valid. If the effective address is specified by one of the control modes, the registers are transferred starting at the specified address, and the address is incre- mented by the operand length (2 or 4) following each transfer. The order of the regis- ters is from D0 to D7, then from A0 to A7.
If the effective address is specified by the predecrement mode, only a register-to-mem- ory operation is allowed. The registers are stored starting at the specified address minus the operand length (2 or 4), and the address is decremented by the operand length following each transfer. The order of storing is from A7 to A0, then from D7 to D0. When the instruction has completed, the decremented address register contains the address of the last operand stored. For the MC68020, MC68030, MC68040, and CPU32, if the addressing register is also moved to memory, the value written is the ini- tial register value decremented by the size of the operation. The MC68000 and MC68010 write the initial register value (not decremented).
If the effective address is specified by the postincrement mode, only a memory-to-reg- ister operation is allowed. The registers are loaded starting at the specified address; the address is incremented by the operand length (2 or 4) following each transfer. The order of loading is the same as that of control mode addressing. When the instruction has completed, the incremented address register contains the address of the last oper- and loaded plus the operand length. If the addressing register is also loaded from memory, the memory value is ignored and the register is written with the postincre- mented effective address.",
operation: "Registers → Destination; Source → Registers",
assembler: &["movem < list >, < ea >", "movem < list >, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const MOVEQ_DESC: Description = Description {
description: "Moves a byte of immediate data to a 32-bit data register. The data in an 8-bit field within the operation word is sign- extended to a long operand in the data register as it is transferred.",
operation: "Immediate Data → Destination",
assembler: &["moveq # < data >, Dn"],
attributes: "Long",
flags: &FLAGS_EXT,
};
pub const MULS_DESC: Description = Description {
description: "Multiplies two signed operands yielding a signed result. The multiplier and multiplicand are both word operands, and the result is a long-word operand. A register operand is the low-order word; the upper word of the register is ignored. All 32 bits of the product are saved in the destination data register.",
operation: "Source * Destination → Destination",
assembler: &["muls.w < ea > ,Dn - 16 x 16 → 32"],
attributes: "Long",
flags: &FLAGS_MUL,
};
pub const MULU_DESC: Description = Description {
description: "Multiplies two signed operands yielding a unsigned result. The multiplier and multiplicand are both word operands, and the result is a long-word operand. A register operand is the low-order word; the upper word of the register is ignored. All 32 bits of the product are saved in the destination data register.",
operation: "Source * Destination → Destination",
assembler: &["muls.w < ea > ,Dn - 16 x 16 → 32"],
attributes: "Long",
flags: &FLAGS_MUL,
};
pub const NEG_DESC: Description = Description {
description: "Subtracts the destination operand from zero and stores the result in the destination location. The size of the operation is specified as byte, word, or long.",
operation: "0 – Destination → Destination",
assembler: &["neg < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_NEG,
};
pub const NEGX_DESC: Description = Description {
description: "Subtracts the destination operand and the extend bit from zero. Stores the result in the destination location. The size of the operation is specified as byte, word, or long.",
operation: "0 – Destination – X → Destination",
assembler: &["negx < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_NEGX,
};
pub const NOP_DESC: Description = Description {
description: "Performs no operation. The processor state, other than the program counter, is unaffected. Execution continues with the instruction following the NOP instruction. The NOP instruction does not begin execution until all pending bus cycles have completed. This synchronizes the pipeline and prevents instruction overlap.",
operation: "None",
assembler: &["nop"],
attributes: "Undefined",
flags: &FLAGS_NOT_AFFECTED,
};
pub const NOT_DESC: Description = Description {
description: "Calculates the ones complement of the destination operand and stores the result in the destination location. The size of the operation is specified as byte, word, or long.",
operation: "~ Destination → Destination",
assembler: &["not < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_EXT,
};
pub const OR_DESC: Description = Description {
description: "Performs an inclusive-OR operation of the source operand with the destination operand and stores the result in the destination location. The size of the operation can be specified as byte, word, or long. The contents of an address register may not be used as an operand.",
operation: "Source | Destination → Destination",
assembler: &["or < ea > ,Dn", "or Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_AND,
};
pub const PEA_DESC: Description = Description {
description: "Computes the effective address and pushes it onto the stack. The effective address is a long address.",
operation: "SP – 4 → SP; < ea > → (SP)",
assembler: &["pea < ea >"],
attributes: "Long",
flags: &FLAGS_NOT_AFFECTED,
};
pub const ROL_ROR_DESC: Description = Description {
description: "Rotates the bits of the operand in the direction specified (L or R). The extend bit is not included in the rotation. The rotate count for the rotation of a register is specified in either of two ways:
1. Immediate—The rotate count (1 – 8) is specified in the instruction.
2. Register—The rotate count is the value in the data register specified in the in- struction, modulo 64.
The size of the operation for register destinations is specified as byte, word, or long. The contents of memory, (ROd < ea > ), can be rotated one bit only, and operand size is restricted to a word.
The ROL instruction rotates the bits of the operand to the left; the rotate count deter- mines the number of bit positions rotated. Bits rotated out of the high-order bit go to the carry bit and also back into the low-order bit.",
operation: "Destination Rotated By Count → Destination",
assembler: &["ROd Dx,Dy", "ROd # < data > ,Dy", "ROd < ea >", "where d is direction, L or R"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ROL,
};
pub const ROXL_ROXR_DESC: Description = Description {
description: "Rotates the bits of the operand in the direction specified (L or R). The extend bit is included in the rotation. The rotate count for the rotation of a register is specified in either of two ways:
1. Immediate—The rotate count (1 – 8) is specified in the instruction.
2. Register—The rotate count is the value in the data register specified in the in- struction, modulo 64.
The size of the operation for register destinations is specified as byte, word, or long. The contents of memory, < ea > , can be rotated one bit only, and operand size is restricted to a word. The ROXL instruction rotates the bits of the operand to the left; the rotate count determines the number of bit positions rotated. Bits rotated out of the high- order bit go to the carry bit and the extend bit; the previous value of the extend bit rotates into the low-order bit.",
operation: "Destination Rotated With X By Count → Destination",
assembler: &["ROXd Dx,Dy", "ROXd # < data > ,Dy", "ROXd < ea >", "where d is direction, L or R"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ROL,
};
pub const RTS_DESC: Description = Description {
description: "Pulls the program counter value from the stack. The previous program counter value is lost.",
operation: "(SP) → PC; SP + 4 → SP",
assembler: &["rts"],
attributes: "Unsized",
flags: &FLAGS_NOT_AFFECTED,
};
pub const SCC_DESC: Description = Description {
description: "Tests the specified condition code; if the condition is true, sets the byte specified by the effective address to TRUE (all ones). Otherwise, sets that byte to FALSE (all zeros).",
operation: "If Condition True
Then 1s → Destination
Else 0s → Destination",
assembler: &["Scc < ea >"],
attributes: "Byte",
flags: &FLAGS_NOT_AFFECTED,
};
pub const SUB_DESC: Description = Description {
description: "Subtracts the source operand from the destination operand and stores the result in the destination. The size of the operation is specified as byte, word, or long. The mode of the instruction indicates which operand is the source, which is the destination, and which is the operand size.",
operation: "Source - Destination → Destination",
assembler: &["sub < ea > ,Dn", "sub Dn, < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_SUB,
};
pub const SUBQ_DESC: Description = Description {
description: "Subtracts the immediate data (1 – 8) from the destination operand. The size of the operation is specified as byte, word, or long. Only word and long operations can be used with address registers, and the condition codes are not affected. When subtracting from address registers, the entire destination address register is used, despite the operation size.",
operation: "Immidate - Destination → Destination",
assembler: &["subq # < data > , < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_ARC,
};
pub const SUBX_DESC: Description = Description {
description: "Subtracts the source operand and the extend bit from the destination operand and stores the result in the destination location.
The instruction has two modes:
1. Data register to data register—the data registers specified in the instruction con- tain the operands.
2. Memory to memory—the address registers specified in the instruction access the operands from memory using the predecrement addressing mode.",
operation: "Source - Destination + X → Destination",
assembler: &["subx Dy,Dx", "subx -(Ay),-(Ax)"],
attributes: "Byte, Word, Long",
flags: &FLAGS_X,
};
pub const SWAP_DESC: Description = Description {
description: "Exchange the 16-bit words (halves) of a data register.",
operation: "Register 31 – 16 ←→ Register 15 – 0",
assembler: &["swap dn"],
attributes: "Word",
flags: &FLAGS_SWAP,
};
pub const TAS_DESC: Description = Description {
description: "Tests and sets the byte operand addressed by the effective address field. The instruction tests the current value of the operand and sets the N and Z condition bits appropriately. TAS also sets the high-order bit of the operand. The operation uses a locked or read-modify-write transfer sequence. This instruction supports use of a flag or semaphore to coordinate several processors.",
operation: "Destination Tested → Condition Codes; 1 → Bit 7 of Destination",
assembler: &["tas < ea >"],
attributes: "Byte",
flags: &FLAGS_TAS,
};
pub const TST_DESC: Description = Description {
description: "Compares the operand with zero and sets the condition codes according to the results of the test. The size of the operation is specified as byte, word, or long.",
operation: "Destination Tested → Condition Codes; 1 → Bit 7 of Destination",
assembler: &["tst < ea >"],
attributes: "Byte, Word, Long",
flags: &FLAGS_TST,
};
pub const UNLK_DESC: Description = Description {
description: "Loads the stack pointer from the specified address register, then loads the address register with the long word pulled from the top of the stack.",
operation: "An → SP; (SP) → An; SP + 4 → SP",
assembler: &["unlk An"],
attributes: "Unsized",
flags: &FLAGS_NOT_AFFECTED,
};
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
counters::{
PROCESSED_STRUCT_LOG_COUNT, SENT_STRUCT_LOG_BYTES, SENT_STRUCT_LOG_COUNT,
STRUCT_LOG_PARSE_ERROR_COUNT, STRUCT_LOG_QUEUE_ERROR_COUNT, STRUCT_LOG_SEND_ERROR_COUNT,
},
logger::Logger,
struct_log::TcpWriter,
Event, Filter, Level, LevelFilter, Metadata,
};
use chrono::{SecondsFormat, Utc};
use diem_infallible::RwLock;
use once_cell::sync::Lazy;
use serde::Serialize;
use std::{
collections::BTreeMap,
env, fmt,
io::Write,
sync::{
mpsc::{self, Receiver, SyncSender},
Arc,
},
thread,
};
const RUST_LOG: &str = "RUST_LOG";
pub const CHANNEL_SIZE: usize = 10000;
const NUM_SEND_RETRIES: u8 = 1;
#[derive(Debug, Serialize)]
pub struct LogEntry {
#[serde(flatten)]
metadata: Metadata,
#[serde(skip_serializing_if = "Option::is_none")]
thread_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
hostname: Option<&'static str>,
timestamp: String,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
data: BTreeMap<&'static str, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
}
impl LogEntry {
fn new(event: &Event, thread_name: Option<&str>) -> Self {
use crate::{Key, Value, Visitor};
struct JsonVisitor<'a>(&'a mut BTreeMap<&'static str, serde_json::Value>);
impl<'a> Visitor for JsonVisitor<'a> {
fn visit_pair(&mut self, key: Key, value: Value<'_>) {
let v = match value {
Value::Debug(d) => serde_json::Value::String(format!("{:?}", d)),
Value::Display(d) => serde_json::Value::String(d.to_string()),
Value::Serde(s) => match serde_json::to_value(s) {
Ok(value) => value,
Err(e) => {
eprintln!("error serializing structured log: {}", e);
return;
}
},
};
self.0.insert(key.as_str(), v);
}
}
let metadata = *event.metadata();
let thread_name = thread_name.map(ToOwned::to_owned);
let message = event.message().map(fmt::format);
static HOSTNAME: Lazy<Option<String>> = Lazy::new(|| {
hostname::get()
.ok()
.and_then(|name| name.into_string().ok())
});
let hostname = HOSTNAME.as_deref();
let mut data = BTreeMap::new();
for schema in event.keys_and_values() {
schema.visit(&mut JsonVisitor(&mut data));
}
Self {
metadata,
thread_name,
hostname,
timestamp: Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
data,
message,
}
}
}
pub struct DiemLoggerBuilder {
channel_size: usize,
level: Level,
remote_level: Level,
address: Option<String>,
printer: Option<Box<dyn Writer>>,
is_async: bool,
}
impl DiemLoggerBuilder {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
channel_size: CHANNEL_SIZE,
level: Level::Info,
remote_level: Level::Info,
address: None,
printer: Some(Box::new(StderrWriter)),
is_async: false,
}
}
pub fn address(&mut self, address: String) -> &mut Self {
self.address = Some(address);
self
}
pub fn read_env(&mut self) -> &mut Self {
if let Ok(address) = env::var("STRUCT_LOG_TCP_ADDR") {
self.address(address);
}
self
}
pub fn level(&mut self, level: Level) -> &mut Self {
self.level = level;
self
}
pub fn remote_level(&mut self, level: Level) -> &mut Self {
self.remote_level = level;
self
}
pub fn channel_size(&mut self, channel_size: usize) -> &mut Self {
self.channel_size = channel_size;
self
}
pub fn printer(&mut self, printer: Box<dyn Writer + Send + Sync + 'static>) -> &mut Self {
self.printer = Some(printer);
self
}
pub fn is_async(&mut self, is_async: bool) -> &mut Self {
self.is_async = is_async;
self
}
pub fn init(&mut self) {
self.build();
}
pub fn build(&mut self) -> Arc<DiemLogger> {
let filter = {
let local_filter = {
let mut filter_builder = Filter::builder();
if env::var(RUST_LOG).is_ok() {
filter_builder.with_env(RUST_LOG);
} else {
filter_builder.filter_level(self.level.into());
}
filter_builder.build()
};
let remote_filter = {
let mut filter_builder = Filter::builder();
if self.is_async && self.address.is_some() {
filter_builder.filter_level(self.remote_level.into());
} else {
filter_builder.filter_level(LevelFilter::Off);
}
filter_builder.build()
};
DiemFilter {
local_filter,
remote_filter,
}
};
let logger = if self.is_async {
let (sender, receiver) = mpsc::sync_channel(self.channel_size);
let logger = Arc::new(DiemLogger {
sender: Some(sender),
printer: None,
filter: RwLock::new(filter),
});
let service = LoggerService {
receiver,
address: self.address.clone(),
printer: self.printer.take(),
facade: logger.clone(),
};
thread::spawn(move || service.run());
logger
} else {
Arc::new(DiemLogger {
sender: None,
printer: self.printer.take(),
filter: RwLock::new(filter),
})
};
crate::logger::set_global_logger(logger.clone());
logger
}
}
struct DiemFilter {
local_filter: Filter,
remote_filter: Filter,
}
impl DiemFilter {
fn enabled(&self, metadata: &Metadata) -> bool {
self.local_filter.enabled(metadata) || self.remote_filter.enabled(metadata)
}
}
pub struct DiemLogger {
sender: Option<SyncSender<LogEntry>>,
printer: Option<Box<dyn Writer>>,
filter: RwLock<DiemFilter>,
}
impl DiemLogger {
pub fn builder() -> DiemLoggerBuilder {
DiemLoggerBuilder::new()
}
#[allow(clippy::new_ret_no_self)]
pub fn new() -> DiemLoggerBuilder {
Self::builder()
}
pub fn init_for_testing() {
if env::var(RUST_LOG).is_err() {
return;
}
Self::builder()
.is_async(false)
.printer(Box::new(StderrWriter))
.build();
}
pub fn set_filter(&self, filter: Filter) {
self.filter.write().local_filter = filter;
}
pub fn set_remote_filter(&self, filter: Filter) {
self.filter.write().remote_filter = filter;
}
fn send_entry(&self, entry: LogEntry) {
if let Some(printer) = &self.printer {
let s = format(&entry).expect("Unable to format");
printer.write(s);
}
if let Some(sender) = &self.sender {
if let Err(e) = sender.try_send(entry) {
STRUCT_LOG_QUEUE_ERROR_COUNT.inc();
eprintln!("Failed to send structured log: {}", e);
}
}
}
}
impl Logger for DiemLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.filter.read().enabled(metadata)
}
fn record(&self, event: &Event) {
let entry = LogEntry::new(event, ::std::thread::current().name());
self.send_entry(entry)
}
}
struct LoggerService {
receiver: Receiver<LogEntry>,
address: Option<String>,
printer: Option<Box<dyn Writer>>,
facade: Arc<DiemLogger>,
}
impl LoggerService {
pub fn run(mut self) {
let mut writer = self.address.take().map(TcpWriter::new);
for entry in self.receiver {
PROCESSED_STRUCT_LOG_COUNT.inc();
if let Some(printer) = &self.printer {
if self
.facade
.filter
.read()
.local_filter
.enabled(&entry.metadata)
{
let s = format(&entry).expect("Unable to format");
printer.write(s)
}
}
if let Some(writer) = &mut writer {
if self
.facade
.filter
.read()
.remote_filter
.enabled(&entry.metadata)
{
Self::write_to_logstash(writer, entry);
}
}
}
}
/// Writes a log line into json_lines logstash format, which has a newline at the end
fn write_to_logstash(stream: &mut TcpWriter, mut entry: LogEntry) {
// XXX Temporary hack to ensure that log lines don't show up empty in kibana when the
// "message" field isn't set.
if entry.message.is_none() {
entry.message = Some(serde_json::to_string(&entry.data).unwrap());
}
let message = if let Ok(json) = serde_json::to_string(&entry) {
json
} else {
STRUCT_LOG_PARSE_ERROR_COUNT.inc();
return;
};
let message = message + "\n";
let bytes = message.as_bytes();
let message_length = bytes.len();
// Attempt to write the log up to NUM_SEND_RETRIES + 1, and then drop it
// Each `write_all` call will attempt to open a connection if one isn't open
let mut result = stream.write_all(bytes);
for _ in 0..NUM_SEND_RETRIES {
if result.is_ok() {
break;
} else {
result = stream.write_all(bytes);
}
}
if let Err(e) = result {
STRUCT_LOG_SEND_ERROR_COUNT.inc();
eprintln!(
"[Logging] Error while sending data to logstash({}): {}",
stream.endpoint(),
e
);
} else {
SENT_STRUCT_LOG_COUNT.inc();
SENT_STRUCT_LOG_BYTES.inc_by(message_length as u64);
}
}
}
/// An trait encapsulating the operations required for writing logs.
pub trait Writer: Send + Sync {
/// Write the log.
fn write(&self, log: String);
}
/// A struct for writing logs to stderr
struct StderrWriter;
impl Writer for StderrWriter {
/// Write log to stderr
fn write(&self, log: String) {
eprintln!("{}", log);
}
}
/// A struct for writing logs to a file
pub struct FileWriter {
log_file: RwLock<std::fs::File>,
}
impl FileWriter {
pub fn new(log_file: std::path::PathBuf) -> Self {
let file = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(log_file)
.expect("Unable to open log file");
Self {
log_file: RwLock::new(file),
}
}
}
impl Writer for FileWriter {
/// Write to file
fn write(&self, log: String) {
if let Err(err) = writeln!(self.log_file.write(), "{}", log) {
eprintln!("Unable to write to log file: {}", err.to_string());
}
}
}
/// Converts a record into a string representation:
/// UNIX_TIMESTAMP LOG_LEVEL [thread_name] FILE:LINE MESSAGE JSON_DATA
/// Example:
/// 2020-03-07 05:03:03 INFO [thread_name] common/diem-logger/src/lib.rs:261 Hello { "world": true }
fn format(entry: &LogEntry) -> Result<String, fmt::Error> {
use std::fmt::Write;
let mut w = String::new();
write!(w, "{}", entry.timestamp)?;
if let Some(thread_name) = &entry.thread_name {
write!(w, " [{}]", thread_name)?;
}
write!(
w,
" {} {}",
entry.metadata.level(),
entry.metadata.location()
)?;
if let Some(message) = &entry.message {
write!(w, " {}", message)?;
}
if !entry.data.is_empty() {
write!(w, " {}", serde_json::to_string(&entry.data).unwrap())?;
}
Ok(w)
}
#[cfg(test)]
mod tests {
use super::LogEntry;
use crate::{
debug, error, info, logger::Logger, trace, warn, Event, Key, KeyValue, Level, Metadata,
Schema, Value, Visitor,
};
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use std::{
sync::{
mpsc::{self, Receiver, SyncSender},
Arc,
},
thread,
};
#[derive(serde::Serialize)]
#[serde(rename_all = "snake_case")]
enum Enum {
FooBar,
}
struct TestSchema<'a> {
foo: usize,
bar: &'a Enum,
}
impl Schema for TestSchema<'_> {
fn visit(&self, visitor: &mut dyn Visitor) {
visitor.visit_pair(Key::new("foo"), Value::from_serde(&self.foo));
visitor.visit_pair(Key::new("bar"), Value::from_serde(&self.bar));
}
}
struct LogStream(SyncSender<LogEntry>);
impl LogStream {
fn new() -> (Self, Receiver<LogEntry>) {
let (sender, receiver) = mpsc::sync_channel(1024);
(Self(sender), receiver)
}
}
impl Logger for LogStream {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Debug
}
fn record(&self, event: &Event) {
let entry = LogEntry::new(event, ::std::thread::current().name());
self.0.send(entry).unwrap();
}
}
fn set_test_logger() -> Receiver<LogEntry> {
let (logger, receiver) = LogStream::new();
let logger = Arc::new(logger);
crate::logger::set_global_logger(logger);
receiver
}
// TODO: Find a better mechanism for testing that allows setting the logger not globally
#[test]
fn basic() {
let receiver = set_test_logger();
let number = 12345;
// Send an info log
let before = Utc::now();
info!(
TestSchema {
foo: 5,
bar: &Enum::FooBar
},
test = true,
category = "name",
KeyValue::new("display", Value::from_display(&number)),
"This is a log"
);
let after = Utc::now();
let entry = receiver.recv().unwrap();
// Ensure standard fields are filled
assert_eq!(entry.metadata.level(), Level::Info);
assert_eq!(
entry.metadata.target(),
module_path!().split("::").next().unwrap()
);
assert_eq!(entry.metadata.module_path(), module_path!());
assert_eq!(entry.metadata.file(), file!());
assert_eq!(entry.message.as_deref(), Some("This is a log"));
// Log time should be the time the structured log entry was created
let timestamp = DateTime::parse_from_rfc3339(&entry.timestamp).unwrap();
let timestamp: DateTime<Utc> = DateTime::from(timestamp);
assert!(before <= timestamp && timestamp <= after);
// Ensure data stored is the right type
assert_eq!(entry.data.get("foo").and_then(JsonValue::as_u64), Some(5));
assert_eq!(
entry.data.get("bar").and_then(JsonValue::as_str),
Some("foo_bar")
);
assert_eq!(
entry.data.get("display").and_then(JsonValue::as_str),
Some(format!("{}", number)).as_deref(),
);
assert_eq!(
entry.data.get("test").and_then(JsonValue::as_bool),
Some(true),
);
assert_eq!(
entry.data.get("category").and_then(JsonValue::as_str),
Some("name"),
);
// Test all log levels work properly
// Tracing should be skipped because the Logger was setup to skip Tracing events
trace!("trace");
debug!("debug");
info!("info");
warn!("warn");
error!("error");
let levels = &[Level::Debug, Level::Info, Level::Warn, Level::Error];
for level in levels {
let entry = receiver.recv().unwrap();
assert_eq!(entry.metadata.level(), *level);
}
// Verify that the thread name is properly included
let handler = thread::Builder::new()
.name("named thread".into())
.spawn(|| info!("thread"))
.unwrap();
handler.join().unwrap();
let entry = receiver.recv().unwrap();
assert_eq!(entry.thread_name.as_deref(), Some("named thread"));
// Test Debug and Display inputs
let debug_struct = DebugStruct {};
let display_struct = DisplayStruct {};
error!(identifier = ?debug_struct, "Debug test");
error!(identifier = ?debug_struct, other = "value", "Debug2 test");
error!(identifier = %display_struct, "Display test");
error!(identifier = %display_struct, other = "value", "Display2 test");
error!("Literal" = ?debug_struct, "Debug test");
error!("Literal" = ?debug_struct, other = "value", "Debug test");
error!("Literal" = %display_struct, "Display test");
error!("Literal" = %display_struct, other = "value", "Display2 test");
error!("Literal" = %display_struct, other = "value", identifier = ?debug_struct, "Mixed test");
}
struct DebugStruct {}
impl std::fmt::Debug for DebugStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DebugStruct!")
}
}
struct DisplayStruct {}
impl std::fmt::Display for DisplayStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DisplayStruct!")
}
}
}
Revert "logger: change default remote log level to info"
This reverts commit 0e67edd3bdfdf6c2f2397d817d50e10c4c98bcc9.
Closes: #6856
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
counters::{
PROCESSED_STRUCT_LOG_COUNT, SENT_STRUCT_LOG_BYTES, SENT_STRUCT_LOG_COUNT,
STRUCT_LOG_PARSE_ERROR_COUNT, STRUCT_LOG_QUEUE_ERROR_COUNT, STRUCT_LOG_SEND_ERROR_COUNT,
},
logger::Logger,
struct_log::TcpWriter,
Event, Filter, Level, LevelFilter, Metadata,
};
use chrono::{SecondsFormat, Utc};
use diem_infallible::RwLock;
use once_cell::sync::Lazy;
use serde::Serialize;
use std::{
collections::BTreeMap,
env, fmt,
io::Write,
sync::{
mpsc::{self, Receiver, SyncSender},
Arc,
},
thread,
};
const RUST_LOG: &str = "RUST_LOG";
pub const CHANNEL_SIZE: usize = 10000;
const NUM_SEND_RETRIES: u8 = 1;
#[derive(Debug, Serialize)]
pub struct LogEntry {
#[serde(flatten)]
metadata: Metadata,
#[serde(skip_serializing_if = "Option::is_none")]
thread_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
hostname: Option<&'static str>,
timestamp: String,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
data: BTreeMap<&'static str, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
}
impl LogEntry {
fn new(event: &Event, thread_name: Option<&str>) -> Self {
use crate::{Key, Value, Visitor};
struct JsonVisitor<'a>(&'a mut BTreeMap<&'static str, serde_json::Value>);
impl<'a> Visitor for JsonVisitor<'a> {
fn visit_pair(&mut self, key: Key, value: Value<'_>) {
let v = match value {
Value::Debug(d) => serde_json::Value::String(format!("{:?}", d)),
Value::Display(d) => serde_json::Value::String(d.to_string()),
Value::Serde(s) => match serde_json::to_value(s) {
Ok(value) => value,
Err(e) => {
eprintln!("error serializing structured log: {}", e);
return;
}
},
};
self.0.insert(key.as_str(), v);
}
}
let metadata = *event.metadata();
let thread_name = thread_name.map(ToOwned::to_owned);
let message = event.message().map(fmt::format);
static HOSTNAME: Lazy<Option<String>> = Lazy::new(|| {
hostname::get()
.ok()
.and_then(|name| name.into_string().ok())
});
let hostname = HOSTNAME.as_deref();
let mut data = BTreeMap::new();
for schema in event.keys_and_values() {
schema.visit(&mut JsonVisitor(&mut data));
}
Self {
metadata,
thread_name,
hostname,
timestamp: Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
data,
message,
}
}
}
pub struct DiemLoggerBuilder {
channel_size: usize,
level: Level,
remote_level: Level,
address: Option<String>,
printer: Option<Box<dyn Writer>>,
is_async: bool,
}
impl DiemLoggerBuilder {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
channel_size: CHANNEL_SIZE,
level: Level::Info,
remote_level: Level::Debug,
address: None,
printer: Some(Box::new(StderrWriter)),
is_async: false,
}
}
pub fn address(&mut self, address: String) -> &mut Self {
self.address = Some(address);
self
}
pub fn read_env(&mut self) -> &mut Self {
if let Ok(address) = env::var("STRUCT_LOG_TCP_ADDR") {
self.address(address);
}
self
}
pub fn level(&mut self, level: Level) -> &mut Self {
self.level = level;
self
}
pub fn remote_level(&mut self, level: Level) -> &mut Self {
self.remote_level = level;
self
}
pub fn channel_size(&mut self, channel_size: usize) -> &mut Self {
self.channel_size = channel_size;
self
}
pub fn printer(&mut self, printer: Box<dyn Writer + Send + Sync + 'static>) -> &mut Self {
self.printer = Some(printer);
self
}
pub fn is_async(&mut self, is_async: bool) -> &mut Self {
self.is_async = is_async;
self
}
pub fn init(&mut self) {
self.build();
}
pub fn build(&mut self) -> Arc<DiemLogger> {
let filter = {
let local_filter = {
let mut filter_builder = Filter::builder();
if env::var(RUST_LOG).is_ok() {
filter_builder.with_env(RUST_LOG);
} else {
filter_builder.filter_level(self.level.into());
}
filter_builder.build()
};
let remote_filter = {
let mut filter_builder = Filter::builder();
if self.is_async && self.address.is_some() {
filter_builder.filter_level(self.remote_level.into());
} else {
filter_builder.filter_level(LevelFilter::Off);
}
filter_builder.build()
};
DiemFilter {
local_filter,
remote_filter,
}
};
let logger = if self.is_async {
let (sender, receiver) = mpsc::sync_channel(self.channel_size);
let logger = Arc::new(DiemLogger {
sender: Some(sender),
printer: None,
filter: RwLock::new(filter),
});
let service = LoggerService {
receiver,
address: self.address.clone(),
printer: self.printer.take(),
facade: logger.clone(),
};
thread::spawn(move || service.run());
logger
} else {
Arc::new(DiemLogger {
sender: None,
printer: self.printer.take(),
filter: RwLock::new(filter),
})
};
crate::logger::set_global_logger(logger.clone());
logger
}
}
struct DiemFilter {
local_filter: Filter,
remote_filter: Filter,
}
impl DiemFilter {
fn enabled(&self, metadata: &Metadata) -> bool {
self.local_filter.enabled(metadata) || self.remote_filter.enabled(metadata)
}
}
pub struct DiemLogger {
sender: Option<SyncSender<LogEntry>>,
printer: Option<Box<dyn Writer>>,
filter: RwLock<DiemFilter>,
}
impl DiemLogger {
pub fn builder() -> DiemLoggerBuilder {
DiemLoggerBuilder::new()
}
#[allow(clippy::new_ret_no_self)]
pub fn new() -> DiemLoggerBuilder {
Self::builder()
}
pub fn init_for_testing() {
if env::var(RUST_LOG).is_err() {
return;
}
Self::builder()
.is_async(false)
.printer(Box::new(StderrWriter))
.build();
}
pub fn set_filter(&self, filter: Filter) {
self.filter.write().local_filter = filter;
}
pub fn set_remote_filter(&self, filter: Filter) {
self.filter.write().remote_filter = filter;
}
fn send_entry(&self, entry: LogEntry) {
if let Some(printer) = &self.printer {
let s = format(&entry).expect("Unable to format");
printer.write(s);
}
if let Some(sender) = &self.sender {
if let Err(e) = sender.try_send(entry) {
STRUCT_LOG_QUEUE_ERROR_COUNT.inc();
eprintln!("Failed to send structured log: {}", e);
}
}
}
}
impl Logger for DiemLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.filter.read().enabled(metadata)
}
fn record(&self, event: &Event) {
let entry = LogEntry::new(event, ::std::thread::current().name());
self.send_entry(entry)
}
}
struct LoggerService {
receiver: Receiver<LogEntry>,
address: Option<String>,
printer: Option<Box<dyn Writer>>,
facade: Arc<DiemLogger>,
}
impl LoggerService {
pub fn run(mut self) {
let mut writer = self.address.take().map(TcpWriter::new);
for entry in self.receiver {
PROCESSED_STRUCT_LOG_COUNT.inc();
if let Some(printer) = &self.printer {
if self
.facade
.filter
.read()
.local_filter
.enabled(&entry.metadata)
{
let s = format(&entry).expect("Unable to format");
printer.write(s)
}
}
if let Some(writer) = &mut writer {
if self
.facade
.filter
.read()
.remote_filter
.enabled(&entry.metadata)
{
Self::write_to_logstash(writer, entry);
}
}
}
}
/// Writes a log line into json_lines logstash format, which has a newline at the end
fn write_to_logstash(stream: &mut TcpWriter, mut entry: LogEntry) {
// XXX Temporary hack to ensure that log lines don't show up empty in kibana when the
// "message" field isn't set.
if entry.message.is_none() {
entry.message = Some(serde_json::to_string(&entry.data).unwrap());
}
let message = if let Ok(json) = serde_json::to_string(&entry) {
json
} else {
STRUCT_LOG_PARSE_ERROR_COUNT.inc();
return;
};
let message = message + "\n";
let bytes = message.as_bytes();
let message_length = bytes.len();
// Attempt to write the log up to NUM_SEND_RETRIES + 1, and then drop it
// Each `write_all` call will attempt to open a connection if one isn't open
let mut result = stream.write_all(bytes);
for _ in 0..NUM_SEND_RETRIES {
if result.is_ok() {
break;
} else {
result = stream.write_all(bytes);
}
}
if let Err(e) = result {
STRUCT_LOG_SEND_ERROR_COUNT.inc();
eprintln!(
"[Logging] Error while sending data to logstash({}): {}",
stream.endpoint(),
e
);
} else {
SENT_STRUCT_LOG_COUNT.inc();
SENT_STRUCT_LOG_BYTES.inc_by(message_length as u64);
}
}
}
/// An trait encapsulating the operations required for writing logs.
pub trait Writer: Send + Sync {
/// Write the log.
fn write(&self, log: String);
}
/// A struct for writing logs to stderr
struct StderrWriter;
impl Writer for StderrWriter {
/// Write log to stderr
fn write(&self, log: String) {
eprintln!("{}", log);
}
}
/// A struct for writing logs to a file
pub struct FileWriter {
log_file: RwLock<std::fs::File>,
}
impl FileWriter {
pub fn new(log_file: std::path::PathBuf) -> Self {
let file = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(log_file)
.expect("Unable to open log file");
Self {
log_file: RwLock::new(file),
}
}
}
impl Writer for FileWriter {
/// Write to file
fn write(&self, log: String) {
if let Err(err) = writeln!(self.log_file.write(), "{}", log) {
eprintln!("Unable to write to log file: {}", err.to_string());
}
}
}
/// Converts a record into a string representation:
/// UNIX_TIMESTAMP LOG_LEVEL [thread_name] FILE:LINE MESSAGE JSON_DATA
/// Example:
/// 2020-03-07 05:03:03 INFO [thread_name] common/diem-logger/src/lib.rs:261 Hello { "world": true }
fn format(entry: &LogEntry) -> Result<String, fmt::Error> {
use std::fmt::Write;
let mut w = String::new();
write!(w, "{}", entry.timestamp)?;
if let Some(thread_name) = &entry.thread_name {
write!(w, " [{}]", thread_name)?;
}
write!(
w,
" {} {}",
entry.metadata.level(),
entry.metadata.location()
)?;
if let Some(message) = &entry.message {
write!(w, " {}", message)?;
}
if !entry.data.is_empty() {
write!(w, " {}", serde_json::to_string(&entry.data).unwrap())?;
}
Ok(w)
}
#[cfg(test)]
mod tests {
use super::LogEntry;
use crate::{
debug, error, info, logger::Logger, trace, warn, Event, Key, KeyValue, Level, Metadata,
Schema, Value, Visitor,
};
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use std::{
sync::{
mpsc::{self, Receiver, SyncSender},
Arc,
},
thread,
};
#[derive(serde::Serialize)]
#[serde(rename_all = "snake_case")]
enum Enum {
FooBar,
}
struct TestSchema<'a> {
foo: usize,
bar: &'a Enum,
}
impl Schema for TestSchema<'_> {
fn visit(&self, visitor: &mut dyn Visitor) {
visitor.visit_pair(Key::new("foo"), Value::from_serde(&self.foo));
visitor.visit_pair(Key::new("bar"), Value::from_serde(&self.bar));
}
}
struct LogStream(SyncSender<LogEntry>);
impl LogStream {
fn new() -> (Self, Receiver<LogEntry>) {
let (sender, receiver) = mpsc::sync_channel(1024);
(Self(sender), receiver)
}
}
impl Logger for LogStream {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Debug
}
fn record(&self, event: &Event) {
let entry = LogEntry::new(event, ::std::thread::current().name());
self.0.send(entry).unwrap();
}
}
fn set_test_logger() -> Receiver<LogEntry> {
let (logger, receiver) = LogStream::new();
let logger = Arc::new(logger);
crate::logger::set_global_logger(logger);
receiver
}
// TODO: Find a better mechanism for testing that allows setting the logger not globally
#[test]
fn basic() {
let receiver = set_test_logger();
let number = 12345;
// Send an info log
let before = Utc::now();
info!(
TestSchema {
foo: 5,
bar: &Enum::FooBar
},
test = true,
category = "name",
KeyValue::new("display", Value::from_display(&number)),
"This is a log"
);
let after = Utc::now();
let entry = receiver.recv().unwrap();
// Ensure standard fields are filled
assert_eq!(entry.metadata.level(), Level::Info);
assert_eq!(
entry.metadata.target(),
module_path!().split("::").next().unwrap()
);
assert_eq!(entry.metadata.module_path(), module_path!());
assert_eq!(entry.metadata.file(), file!());
assert_eq!(entry.message.as_deref(), Some("This is a log"));
// Log time should be the time the structured log entry was created
let timestamp = DateTime::parse_from_rfc3339(&entry.timestamp).unwrap();
let timestamp: DateTime<Utc> = DateTime::from(timestamp);
assert!(before <= timestamp && timestamp <= after);
// Ensure data stored is the right type
assert_eq!(entry.data.get("foo").and_then(JsonValue::as_u64), Some(5));
assert_eq!(
entry.data.get("bar").and_then(JsonValue::as_str),
Some("foo_bar")
);
assert_eq!(
entry.data.get("display").and_then(JsonValue::as_str),
Some(format!("{}", number)).as_deref(),
);
assert_eq!(
entry.data.get("test").and_then(JsonValue::as_bool),
Some(true),
);
assert_eq!(
entry.data.get("category").and_then(JsonValue::as_str),
Some("name"),
);
// Test all log levels work properly
// Tracing should be skipped because the Logger was setup to skip Tracing events
trace!("trace");
debug!("debug");
info!("info");
warn!("warn");
error!("error");
let levels = &[Level::Debug, Level::Info, Level::Warn, Level::Error];
for level in levels {
let entry = receiver.recv().unwrap();
assert_eq!(entry.metadata.level(), *level);
}
// Verify that the thread name is properly included
let handler = thread::Builder::new()
.name("named thread".into())
.spawn(|| info!("thread"))
.unwrap();
handler.join().unwrap();
let entry = receiver.recv().unwrap();
assert_eq!(entry.thread_name.as_deref(), Some("named thread"));
// Test Debug and Display inputs
let debug_struct = DebugStruct {};
let display_struct = DisplayStruct {};
error!(identifier = ?debug_struct, "Debug test");
error!(identifier = ?debug_struct, other = "value", "Debug2 test");
error!(identifier = %display_struct, "Display test");
error!(identifier = %display_struct, other = "value", "Display2 test");
error!("Literal" = ?debug_struct, "Debug test");
error!("Literal" = ?debug_struct, other = "value", "Debug test");
error!("Literal" = %display_struct, "Display test");
error!("Literal" = %display_struct, other = "value", "Display2 test");
error!("Literal" = %display_struct, other = "value", identifier = ?debug_struct, "Mixed test");
}
struct DebugStruct {}
impl std::fmt::Debug for DebugStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DebugStruct!")
}
}
struct DisplayStruct {}
impl std::fmt::Display for DisplayStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DisplayStruct!")
}
}
}
|
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(nll)]
#![feature(once_cell)]
#![recursion_limit = "256"]
#[macro_use]
extern crate tracing;
pub extern crate rustc_plugin_impl as plugin;
use rustc_ast as ast;
use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
use rustc_data_structures::profiling::print_time_passes_entry;
use rustc_data_structures::sync::SeqCst;
use rustc_errors::registry::{InvalidErrorCode, Registry};
use rustc_errors::{ErrorReported, PResult};
use rustc_feature::{find_gated_cfg, UnstableFeatures};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend};
use rustc_interface::{interface, Queries};
use rustc_lint::LintStore;
use rustc_metadata::locator;
use rustc_middle::middle::cstore::MetadataLoader;
use rustc_middle::ty::TyCtxt;
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
use rustc_serialize::json::{self, ToJson};
use rustc_session::config::nightly_options;
use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
use rustc_session::getopts;
use rustc_session::lint::{Lint, LintId};
use rustc_session::{config, DiagnosticOutput, Session};
use rustc_session::{early_error, early_warn};
use rustc_span::source_map::{FileLoader, FileName};
use rustc_span::symbol::sym;
use std::borrow::Cow;
use std::cmp::max;
use std::default::Default;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::lazy::SyncLazy;
use std::mem;
use std::panic::{self, catch_unwind};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
use std::str;
use std::time::Instant;
mod args;
pub mod pretty;
/// Exit status code used for successful compilation and help output.
pub const EXIT_SUCCESS: i32 = 0;
/// Exit status code used for compilation failures and invalid flags.
pub const EXIT_FAILURE: i32 = 1;
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
match result {
Err(..) => {
sess.abort_if_errors();
panic!("error reported but abort_if_errors didn't abort???");
}
Ok(x) => x,
}
}
pub trait Callbacks {
/// Called before creating the compiler instance
fn config(&mut self, _config: &mut interface::Config) {}
/// Called after parsing. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_parsing<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
/// Called after expansion. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_expansion<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
/// Called after analysis. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_analysis<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
}
#[derive(Default)]
pub struct TimePassesCallbacks {
time_passes: bool,
}
impl Callbacks for TimePassesCallbacks {
fn config(&mut self, config: &mut interface::Config) {
// If a --prints=... option has been given, we don't print the "total"
// time because it will mess up the --prints output. See #64339.
self.time_passes = config.opts.prints.is_empty()
&& (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
}
}
pub fn diagnostics_registry() -> Registry {
Registry::new(&rustc_error_codes::DIAGNOSTICS)
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// The FileLoader provides a way to load files from sources other than the file system.
pub fn run_compiler(
at_args: &[String],
callbacks: &mut (dyn Callbacks + Send),
file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
emitter: Option<Box<dyn Write + Send>>,
make_codegen_backend: Option<
Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
>,
) -> interface::Result<()> {
let mut args = Vec::new();
for arg in at_args {
match args::arg_expand(arg.clone()) {
Ok(arg) => args.extend(arg),
Err(err) => early_error(
ErrorOutputType::default(),
&format!("Failed to load argument file: {}", err),
),
}
}
let diagnostic_output =
emitter.map(|emitter| DiagnosticOutput::Raw(emitter)).unwrap_or(DiagnosticOutput::Default);
let matches = match handle_options(&args) {
Some(matches) => matches,
None => return Ok(()),
};
let sopts = config::build_session_options(&matches);
let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
// We wrap `make_codegen_backend` in another `Option` such that `dummy_config` can take
// ownership of it when necessary, while also allowing the non-dummy config to take ownership
// when `dummy_config` is not used.
let mut make_codegen_backend = Some(make_codegen_backend);
let mut dummy_config = |sopts, cfg, diagnostic_output| {
let mut config = interface::Config {
opts: sopts,
crate_cfg: cfg,
input: Input::File(PathBuf::new()),
input_path: None,
output_file: None,
output_dir: None,
file_loader: None,
diagnostic_output,
stderr: None,
crate_name: None,
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
make_codegen_backend: make_codegen_backend.take().unwrap(),
registry: diagnostics_registry(),
};
callbacks.config(&mut config);
config
};
if let Some(ref code) = matches.opt_str("explain") {
handle_explain(diagnostics_registry(), code, sopts.error_format);
return Ok(());
}
let (odir, ofile) = make_output(&matches);
let (input, input_file_path, input_err) = match make_input(&matches.free) {
Some(v) => v,
None => match matches.free.len() {
0 => {
let config = dummy_config(sopts, cfg, diagnostic_output);
interface::run_compiler(config, |compiler| {
let sopts = &compiler.session().opts;
if sopts.describe_lints {
let lint_store = rustc_lint::new_lint_store(
sopts.debugging_opts.no_interleave_lints,
compiler.session().unstable_options(),
);
describe_lints(compiler.session(), &lint_store, false);
return;
}
let should_stop = RustcDefaultCalls::print_crate_info(
&***compiler.codegen_backend(),
compiler.session(),
None,
&odir,
&ofile,
);
if should_stop == Compilation::Stop {
return;
}
early_error(sopts.error_format, "no input filename given")
});
return Ok(());
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error(
sopts.error_format,
&format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1],
),
),
},
};
if let Some(err) = input_err {
// Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8).
interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
compiler.session().err(&err.to_string());
});
return Err(ErrorReported);
}
let mut config = interface::Config {
opts: sopts,
crate_cfg: cfg,
input,
input_path: input_file_path,
output_file: ofile,
output_dir: odir,
file_loader,
diagnostic_output,
stderr: None,
crate_name: None,
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
make_codegen_backend: make_codegen_backend.unwrap(),
registry: diagnostics_registry(),
};
callbacks.config(&mut config);
interface::run_compiler(config, |compiler| {
let sess = compiler.session();
let should_stop = RustcDefaultCalls::print_crate_info(
&***compiler.codegen_backend(),
sess,
Some(compiler.input()),
compiler.output_dir(),
compiler.output_file(),
)
.and_then(|| {
RustcDefaultCalls::list_metadata(
sess,
&*compiler.codegen_backend().metadata_loader(),
&matches,
compiler.input(),
)
})
.and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
if should_stop == Compilation::Stop {
return sess.compile_status();
}
let linker = compiler.enter(|queries| {
let early_exit = || sess.compile_status().map(|_| None);
queries.parse()?;
if let Some(ppm) = &sess.opts.pretty {
if ppm.needs_ast_map() {
queries.global_ctxt()?.peek_mut().enter(|tcx| {
let expanded_crate = queries.expansion()?.take().0;
pretty::print_after_hir_lowering(
tcx,
compiler.input(),
&expanded_crate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
);
Ok(())
})?;
} else {
let krate = queries.parse()?.take();
pretty::print_after_parsing(
sess,
&compiler.input(),
&krate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
);
}
trace!("finished pretty-printing");
return early_exit();
}
if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
return early_exit();
}
if sess.opts.debugging_opts.parse_only
|| sess.opts.debugging_opts.show_span.is_some()
|| sess.opts.debugging_opts.ast_json_noexpand
{
return early_exit();
}
{
let (_, lint_store) = &*queries.register_plugins()?.peek();
// Lint plugins are registered; now we can process command line flags.
if sess.opts.describe_lints {
describe_lints(&sess, &lint_store, true);
return early_exit();
}
}
queries.expansion()?;
if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
return early_exit();
}
queries.prepare_outputs()?;
if sess.opts.output_types.contains_key(&OutputType::DepInfo)
&& sess.opts.output_types.len() == 1
{
return early_exit();
}
queries.global_ctxt()?;
// Drop AST after creating GlobalCtxt to free memory
{
let _timer = sess.prof.generic_activity("drop_ast");
mem::drop(queries.expansion()?.take());
}
if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
return early_exit();
}
if sess.opts.debugging_opts.save_analysis {
let crate_name = queries.crate_name()?.peek().clone();
queries.global_ctxt()?.peek_mut().enter(|tcx| {
let result = tcx.analysis(LOCAL_CRATE);
sess.time("save_analysis", || {
save::process_crate(
tcx,
&crate_name,
&compiler.input(),
None,
DumpHandler::new(
compiler.output_dir().as_ref().map(|p| &**p),
&crate_name,
),
)
});
result
})?;
}
queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
return early_exit();
}
queries.ongoing_codegen()?;
if sess.opts.debugging_opts.print_type_sizes {
sess.code_stats.print_type_sizes();
}
let linker = queries.linker()?;
Ok(Some(linker))
})?;
if let Some(linker) = linker {
let _timer = sess.timer("link");
linker.link()?
}
if sess.opts.debugging_opts.perf_stats {
sess.print_perf_stats();
}
if sess.print_fuel_crate.is_some() {
eprintln!(
"Fuel used by {}: {}",
sess.print_fuel_crate.as_ref().unwrap(),
sess.print_fuel.load(SeqCst)
);
}
Ok(())
})
}
#[cfg(unix)]
pub fn set_sigpipe_handler() {
unsafe {
// Set the SIGPIPE signal handler, so that an EPIPE
// will cause rustc to terminate, as expected.
assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
}
}
#[cfg(windows)]
pub fn set_sigpipe_handler() {}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0];
if ifile == "-" {
let mut src = String::new();
let err = if io::stdin().read_to_string(&mut src).is_err() {
Some(io::Error::new(
io::ErrorKind::InvalidData,
"couldn't read from stdin, as it did not contain valid UTF-8",
))
} else {
None
};
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
);
let line = isize::from_str_radix(&line, 10)
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
return Some((Input::Str { name: file_name, input: src }, None, err));
}
Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next(),
}
}
}
/// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
// FIXME remove these and use winapi 0.3 instead
// Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
#[cfg(unix)]
fn stdout_isatty() -> bool {
unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
}
#[cfg(windows)]
fn stdout_isatty() -> bool {
use winapi::um::consoleapi::GetConsoleMode;
use winapi::um::processenv::GetStdHandle;
use winapi::um::winbase::STD_OUTPUT_HANDLE;
unsafe {
let handle = GetStdHandle(STD_OUTPUT_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out) != 0
}
}
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
let normalised =
if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) };
match registry.try_find_description(&normalised) {
Ok(Some(description)) => {
let mut is_in_code_block = false;
let mut text = String::new();
// Slice off the leading newline and print.
for line in description.lines() {
let indent_level =
line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
let dedented_line = &line[indent_level..];
if dedented_line.starts_with("```") {
is_in_code_block = !is_in_code_block;
text.push_str(&line[..(indent_level + 3)]);
} else if is_in_code_block && dedented_line.starts_with("# ") {
continue;
} else {
text.push_str(line);
}
text.push('\n');
}
if stdout_isatty() {
show_content_with_pager(&text);
} else {
print!("{}", text);
}
}
Ok(None) => {
early_error(output, &format!("no extended information for {}", code));
}
Err(InvalidErrorCode) => {
early_error(output, &format!("{} is not a valid error code", code));
}
}
}
fn show_content_with_pager(content: &String) {
let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
});
let mut fallback_to_println = false;
match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
Ok(mut pager) => {
if let Some(pipe) = pager.stdin.as_mut() {
if pipe.write_all(content.as_bytes()).is_err() {
fallback_to_println = true;
}
}
if pager.wait().is_err() {
fallback_to_println = true;
}
}
Err(_) => {
fallback_to_println = true;
}
}
// If pager fails for whatever reason, we should still print the content
// to standard output
if fallback_to_println {
print!("{}", content);
}
}
impl RustcDefaultCalls {
fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> {
if let Input::File(file) = compiler.input() {
// FIXME: #![crate_type] and #![crate_name] support not implemented yet
let attrs = vec![];
sess.init_crate_types(collect_crate_types(sess, &attrs));
let outputs = compiler.build_output_filenames(&sess, &attrs);
let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
sess.fatal(&format!("failed to read rlink file: {}", err));
});
let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| {
sess.fatal(&format!("failed to decode rlink: {}", err));
});
compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs)
} else {
sess.fatal("rlink must be a file")
}
}
pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
if sess.opts.debugging_opts.link_only {
let result = RustcDefaultCalls::process_rlink(sess, compiler);
abort_on_err(result, sess);
Compilation::Stop
} else {
Compilation::Continue
}
}
pub fn list_metadata(
sess: &Session,
metadata_loader: &dyn MetadataLoader,
matches: &getopts::Matches,
input: &Input,
) -> Compilation {
let r = matches.opt_strs("Z");
if r.iter().any(|s| *s == "ls") {
match *input {
Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v)
.unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
Input::Str { .. } => {
early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
Compilation::Continue
}
fn print_crate_info(
codegen_backend: &dyn CodegenBackend,
sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
) -> Compilation {
use rustc_session::config::PrintRequest::*;
// PrintRequest::NativeStaticLibs is special - printed during linking
// (empty iterator returns true)
if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
return Compilation::Continue;
}
let attrs = match input {
None => None,
Some(input) => {
let result = parse_crate_attrs(sess, input);
match result {
Ok(attrs) => Some(attrs),
Err(mut parse_error) => {
parse_error.emit();
return Compilation::Stop;
}
}
}
};
for req in &sess.opts.prints {
match *req {
TargetList => {
let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
targets.sort();
println!("{}", targets.join("\n"));
}
Sysroot => println!("{}", sess.sysroot.display()),
TargetLibdir => println!(
"{}",
sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display()
),
TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
FileNames | CrateName => {
let input = input.unwrap_or_else(|| {
early_error(ErrorOutputType::default(), "no input file provided")
});
let attrs = attrs.as_ref().unwrap();
let t_outputs = rustc_interface::util::build_output_filenames(
input, odir, ofile, attrs, sess,
);
let id = rustc_session::output::find_crate_name(sess, attrs, input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue;
}
let crate_types = collect_crate_types(sess, attrs);
for &style in &crate_types {
let fname =
rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
println!("{}", fname.file_name().unwrap().to_string_lossy());
}
}
Cfg => {
let allow_unstable_cfg =
UnstableFeatures::from_environment().is_nightly_build();
let mut cfgs = sess
.parse_sess
.config
.iter()
.filter_map(|&(name, value)| {
// Note that crt-static is a specially recognized cfg
// directive that's printed out here as part of
// rust-lang/rust#37406, but in general the
// `target_feature` cfg is gated under
// rust-lang/rust#29717. For now this is just
// specifically allowing the crt-static cfg and that's
// it, this is intended to get into Cargo and then go
// through to build scripts.
if (name != sym::target_feature || value != Some(sym::crt_dash_static))
&& !allow_unstable_cfg
&& find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
{
return None;
}
if let Some(value) = value {
Some(format!("{}=\"{}\"", name, value))
} else {
Some(name.to_string())
}
})
.collect::<Vec<String>>();
cfgs.sort();
for cfg in cfgs {
println!("{}", cfg);
}
}
RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
codegen_backend.print(*req, sess);
}
// Any output here interferes with Cargo's parsing of other printed output
PrintRequest::NativeStaticLibs => {}
}
}
Compilation::Stop
}
}
/// Returns a version string such as "0.12.0-dev".
fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str {
x.unwrap_or("unknown")
}
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
get_builtin_codegen_backend("llvm")().print_version();
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
let mut options = getopts::Options::new();
for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
(option.apply)(&mut options);
}
let message = "Usage: rustc [OPTIONS] INPUT";
let nightly_help = if nightly_options::is_nightly_build() {
"\n -Z help Print unstable compiler options"
} else {
""
};
let verbose_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
let at_path = if verbose && nightly_options::is_nightly_build() {
" @path Read newline separated options from `path`\n"
} else {
""
};
println!(
"{options}{at_path}\nAdditional help:
-C help Print codegen options
-W help \
Print 'lint' options and default settings{nightly}{verbose}\n",
options = options.usage(message),
at_path = at_path,
nightly = nightly_help,
verbose = verbose_help
);
}
fn print_wall_help() {
println!(
"
The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
default. Use `rustc -W help` to see all available lints. It's more common to put
warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
the command line flag directly.
"
);
}
fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
println!(
"
Available lint options:
-W <foo> Warn about <foo>
-A <foo> \
Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> \
(deny <foo> and all attempts to override)
"
);
fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
// The sort doesn't case-fold but it's doubtful we care.
lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
lints
}
fn sort_lint_groups(
lints: Vec<(&'static str, Vec<LintId>, bool)>,
) -> Vec<(&'static str, Vec<LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by_key(|l| l.0);
lints
}
let (plugin, builtin): (Vec<_>, _) =
lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
let plugin = sort_lints(sess, plugin);
let builtin = sort_lints(sess, builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) =
lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len =
plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
let padded = |x: &str| {
let mut s = " ".repeat(max_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = max(
"warnings".len(),
plugin_groups
.iter()
.chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max()
.unwrap_or(0),
);
let padded = |x: &str| {
let mut s = " ".repeat(max_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to
.into_iter()
.map(|x| x.to_string().replace("_", "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded(&name), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!(
"Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename."
);
}
(false, ..) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable options:\n");
print_flag_list("-Z", config::DB_OPTIONS);
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
print_flag_list("-C", config::CG_OPTIONS);
}
fn print_flag_list<T>(
cmdline_opt: &str,
flag_list: &[(&'static str, T, &'static str, &'static str)],
) {
let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
for &(name, _, _, desc) in flag_list {
println!(
" {} {:>width$}=val -- {}",
cmdline_opt,
name.replace("_", "-"),
desc,
width = max_len
);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args,
/// otherwise returns `None`.
///
/// The compiler's handling of options is a little complicated as it ties into
/// our stability story. The current intention of each compiler option is to
/// have one of two modes:
///
/// 1. An option is stable and can be used everywhere.
/// 2. An option is unstable, and can only be used on nightly.
///
/// Like unstable library and language features, however, unstable options have
/// always required a form of "opt in" to indicate that you're using them. This
/// provides the easy ability to scan a code base to check to see if anything
/// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
///
/// All options behind `-Z` are considered unstable by default. Other top-level
/// options can also be considered unstable, and they were unlocked through the
/// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
/// instability in both cases, though.
///
/// So with all that in mind, the comments below have some more detail about the
/// contortions done here to get things to work out correctly.
pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let args = &args[1..];
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
// Parse with *all* options defined in the compiler, we don't worry about
// option stability here we just want to parse as much as possible.
let mut options = getopts::Options::new();
for option in config::rustc_optgroups() {
(option.apply)(&mut options);
}
let matches = options
.parse(args)
.unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string()));
// For all options we just parsed, we check a few aspects:
//
// * If the option is stable, we're all good
// * If the option wasn't passed, we're all good
// * If `-Z unstable-options` wasn't passed (and we're not a -Z option
// ourselves), then we require the `-Z unstable-options` flag to unlock
// this option that was passed.
// * If we're a nightly compiler, then unstable options are now unlocked, so
// we're good to go.
// * Otherwise, if we're an unstable option then we generate an error
// (unstable option being used on stable)
nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
if matches.opt_present("h") || matches.opt_present("help") {
// Only show unstable options in --help if we accept unstable options.
usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
return None;
}
// Handle the special case of -Wall.
let wall = matches.opt_strs("W");
if wall.iter().any(|x| *x == "all") {
print_wall_help();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.iter().any(|x| *x == "no-stack-check") {
early_warn(
ErrorOutputType::default(),
"the --no-stack-check flag is deprecated and does nothing",
);
}
if cg_flags.iter().any(|x| *x == "passes=list") {
get_builtin_codegen_backend("llvm")().print_passes();
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
match input {
Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
name.clone(),
input.clone(),
&sess.parse_sess,
),
}
}
/// Gets a list of extra command-line flags provided by the user, as strings.
///
/// This function is used during ICEs to show more information useful for
/// debugging, since some ICEs only happens with non-default compiler flags
/// (and the users don't always report them).
fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
// Avoid printing help because of empty args. This can suggest the compiler
// itself is not the program root (consider RLS).
if args.len() < 2 {
return None;
}
let matches = handle_options(&args)?;
let mut result = Vec::new();
let mut excluded_cargo_defaults = false;
for flag in ICE_REPORT_COMPILER_FLAGS {
let prefix = if flag.len() == 1 { "-" } else { "--" };
for content in &matches.opt_strs(flag) {
// Split always returns the first element
let name = if let Some(first) = content.split('=').next() { first } else { &content };
let content =
if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
result.push(format!("{}{} {}", prefix, flag, content));
} else {
excluded_cargo_defaults = true;
}
}
}
if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
}
/// Runs a closure and catches unwinds triggered by fatal errors.
///
/// The compiler currently unwinds with a special sentinel value to abort
/// compilation on fatal errors. This function catches that sentinel and turns
/// the panic into a `Result` instead.
pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
if value.is::<rustc_errors::FatalErrorMarker>() {
ErrorReported
} else {
panic::resume_unwind(value);
}
})
}
/// Variant of `catch_fatal_errors` for the `interface::Result` return type
/// that also computes the exit code.
pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
let result = catch_fatal_errors(f).and_then(|result| result);
match result {
Ok(()) => EXIT_SUCCESS,
Err(_) => EXIT_FAILURE,
}
}
static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
SyncLazy::new(|| {
let hook = panic::take_hook();
panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
hook
});
/// Prints the ICE message, including backtrace and query stack.
///
/// The message will point the user at `bug_report_url` to report the ICE.
///
/// When `install_ice_hook` is called, this function will be called as the panic
/// hook.
pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
// Invoke the default handler, which prints the actual panic message and optionally a backtrace
(*DEFAULT_HOOK)(info);
// Separate the output with an empty line
eprintln!();
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
false,
false,
None,
false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !info.payload().is::<rustc_errors::ExplicitBug>() {
let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&d);
}
let mut xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
format!("we would appreciate a bug report: {}", bug_report_url).into(),
format!(
"rustc {} running on {}",
option_env!("CFG_VERSION").unwrap_or("unknown_version"),
config::host_triple()
)
.into(),
];
if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
xs.push(format!("compiler flags: {}", flags.join(" ")).into());
if excluded_cargo_defaults {
xs.push("some of the compiler flags provided by cargo are hidden".into());
}
}
for note in &xs {
handler.note_without_error(¬e);
}
// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
if backtrace {
TyCtxt::try_print_query_stack(&handler);
}
#[cfg(windows)]
unsafe {
if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
// Trigger a debugger if we crashed during bootstrap
winapi::um::debugapi::DebugBreak();
}
}
}
/// Installs a panic hook that will print the ICE message on unexpected panics.
///
/// A custom rustc driver can skip calling this to set up a custom ICE hook.
pub fn install_ice_hook() {
SyncLazy::force(&DEFAULT_HOOK);
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version.
pub fn init_rustc_env_logger() {
init_env_logger("RUSTC_LOG")
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) {
// Don't register a dispatcher if there's no filter to print anything
match std::env::var(env) {
Err(_) => return,
Ok(s) if s.is_empty() => return,
Ok(_) => {}
}
let filter = tracing_subscriber::EnvFilter::from_env(env);
let layer = tracing_tree::HierarchicalLayer::default()
.with_indent_lines(true)
.with_ansi(true)
.with_targets(true)
.with_thread_ids(true)
.with_thread_names(true)
.with_wraparound(10)
.with_verbose_exit(true)
.with_verbose_entry(true)
.with_indent_amount(2);
use tracing_subscriber::layer::SubscriberExt;
let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
pub fn main() -> ! {
let start = Instant::now();
init_rustc_env_logger();
let mut callbacks = TimePassesCallbacks::default();
install_ice_hook();
let exit_code = catch_with_exit_code(|| {
let args = env::args_os()
.enumerate()
.map(|(i, arg)| {
arg.into_string().unwrap_or_else(|arg| {
early_error(
ErrorOutputType::default(),
&format!("Argument {} is not valid Unicode: {:?}", i, arg),
)
})
})
.collect::<Vec<_>>();
run_compiler(&args, &mut callbacks, None, None, None)
});
// The extra `\t` is necessary to align this label with the others.
print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
process::exit(exit_code)
}
Rollup merge of #77673 - heckad:patch-2, r=lcnr
Remove unnecessary lamda on emitter map.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(nll)]
#![feature(once_cell)]
#![recursion_limit = "256"]
#[macro_use]
extern crate tracing;
pub extern crate rustc_plugin_impl as plugin;
use rustc_ast as ast;
use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
use rustc_data_structures::profiling::print_time_passes_entry;
use rustc_data_structures::sync::SeqCst;
use rustc_errors::registry::{InvalidErrorCode, Registry};
use rustc_errors::{ErrorReported, PResult};
use rustc_feature::{find_gated_cfg, UnstableFeatures};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend};
use rustc_interface::{interface, Queries};
use rustc_lint::LintStore;
use rustc_metadata::locator;
use rustc_middle::middle::cstore::MetadataLoader;
use rustc_middle::ty::TyCtxt;
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
use rustc_serialize::json::{self, ToJson};
use rustc_session::config::nightly_options;
use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
use rustc_session::getopts;
use rustc_session::lint::{Lint, LintId};
use rustc_session::{config, DiagnosticOutput, Session};
use rustc_session::{early_error, early_warn};
use rustc_span::source_map::{FileLoader, FileName};
use rustc_span::symbol::sym;
use std::borrow::Cow;
use std::cmp::max;
use std::default::Default;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::lazy::SyncLazy;
use std::mem;
use std::panic::{self, catch_unwind};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
use std::str;
use std::time::Instant;
mod args;
pub mod pretty;
/// Exit status code used for successful compilation and help output.
pub const EXIT_SUCCESS: i32 = 0;
/// Exit status code used for compilation failures and invalid flags.
pub const EXIT_FAILURE: i32 = 1;
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
match result {
Err(..) => {
sess.abort_if_errors();
panic!("error reported but abort_if_errors didn't abort???");
}
Ok(x) => x,
}
}
pub trait Callbacks {
/// Called before creating the compiler instance
fn config(&mut self, _config: &mut interface::Config) {}
/// Called after parsing. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_parsing<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
/// Called after expansion. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_expansion<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
/// Called after analysis. Return value instructs the compiler whether to
/// continue the compilation afterwards (defaults to `Compilation::Continue`)
fn after_analysis<'tcx>(
&mut self,
_compiler: &interface::Compiler,
_queries: &'tcx Queries<'tcx>,
) -> Compilation {
Compilation::Continue
}
}
#[derive(Default)]
pub struct TimePassesCallbacks {
time_passes: bool,
}
impl Callbacks for TimePassesCallbacks {
fn config(&mut self, config: &mut interface::Config) {
// If a --prints=... option has been given, we don't print the "total"
// time because it will mess up the --prints output. See #64339.
self.time_passes = config.opts.prints.is_empty()
&& (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
}
}
pub fn diagnostics_registry() -> Registry {
Registry::new(&rustc_error_codes::DIAGNOSTICS)
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// The FileLoader provides a way to load files from sources other than the file system.
pub fn run_compiler(
at_args: &[String],
callbacks: &mut (dyn Callbacks + Send),
file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
emitter: Option<Box<dyn Write + Send>>,
make_codegen_backend: Option<
Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
>,
) -> interface::Result<()> {
let mut args = Vec::new();
for arg in at_args {
match args::arg_expand(arg.clone()) {
Ok(arg) => args.extend(arg),
Err(err) => early_error(
ErrorOutputType::default(),
&format!("Failed to load argument file: {}", err),
),
}
}
let diagnostic_output = emitter.map_or(DiagnosticOutput::Default, DiagnosticOutput::Raw);
let matches = match handle_options(&args) {
Some(matches) => matches,
None => return Ok(()),
};
let sopts = config::build_session_options(&matches);
let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
// We wrap `make_codegen_backend` in another `Option` such that `dummy_config` can take
// ownership of it when necessary, while also allowing the non-dummy config to take ownership
// when `dummy_config` is not used.
let mut make_codegen_backend = Some(make_codegen_backend);
let mut dummy_config = |sopts, cfg, diagnostic_output| {
let mut config = interface::Config {
opts: sopts,
crate_cfg: cfg,
input: Input::File(PathBuf::new()),
input_path: None,
output_file: None,
output_dir: None,
file_loader: None,
diagnostic_output,
stderr: None,
crate_name: None,
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
make_codegen_backend: make_codegen_backend.take().unwrap(),
registry: diagnostics_registry(),
};
callbacks.config(&mut config);
config
};
if let Some(ref code) = matches.opt_str("explain") {
handle_explain(diagnostics_registry(), code, sopts.error_format);
return Ok(());
}
let (odir, ofile) = make_output(&matches);
let (input, input_file_path, input_err) = match make_input(&matches.free) {
Some(v) => v,
None => match matches.free.len() {
0 => {
let config = dummy_config(sopts, cfg, diagnostic_output);
interface::run_compiler(config, |compiler| {
let sopts = &compiler.session().opts;
if sopts.describe_lints {
let lint_store = rustc_lint::new_lint_store(
sopts.debugging_opts.no_interleave_lints,
compiler.session().unstable_options(),
);
describe_lints(compiler.session(), &lint_store, false);
return;
}
let should_stop = RustcDefaultCalls::print_crate_info(
&***compiler.codegen_backend(),
compiler.session(),
None,
&odir,
&ofile,
);
if should_stop == Compilation::Stop {
return;
}
early_error(sopts.error_format, "no input filename given")
});
return Ok(());
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error(
sopts.error_format,
&format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1],
),
),
},
};
if let Some(err) = input_err {
// Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8).
interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
compiler.session().err(&err.to_string());
});
return Err(ErrorReported);
}
let mut config = interface::Config {
opts: sopts,
crate_cfg: cfg,
input,
input_path: input_file_path,
output_file: ofile,
output_dir: odir,
file_loader,
diagnostic_output,
stderr: None,
crate_name: None,
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
make_codegen_backend: make_codegen_backend.unwrap(),
registry: diagnostics_registry(),
};
callbacks.config(&mut config);
interface::run_compiler(config, |compiler| {
let sess = compiler.session();
let should_stop = RustcDefaultCalls::print_crate_info(
&***compiler.codegen_backend(),
sess,
Some(compiler.input()),
compiler.output_dir(),
compiler.output_file(),
)
.and_then(|| {
RustcDefaultCalls::list_metadata(
sess,
&*compiler.codegen_backend().metadata_loader(),
&matches,
compiler.input(),
)
})
.and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
if should_stop == Compilation::Stop {
return sess.compile_status();
}
let linker = compiler.enter(|queries| {
let early_exit = || sess.compile_status().map(|_| None);
queries.parse()?;
if let Some(ppm) = &sess.opts.pretty {
if ppm.needs_ast_map() {
queries.global_ctxt()?.peek_mut().enter(|tcx| {
let expanded_crate = queries.expansion()?.take().0;
pretty::print_after_hir_lowering(
tcx,
compiler.input(),
&expanded_crate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
);
Ok(())
})?;
} else {
let krate = queries.parse()?.take();
pretty::print_after_parsing(
sess,
&compiler.input(),
&krate,
*ppm,
compiler.output_file().as_ref().map(|p| &**p),
);
}
trace!("finished pretty-printing");
return early_exit();
}
if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
return early_exit();
}
if sess.opts.debugging_opts.parse_only
|| sess.opts.debugging_opts.show_span.is_some()
|| sess.opts.debugging_opts.ast_json_noexpand
{
return early_exit();
}
{
let (_, lint_store) = &*queries.register_plugins()?.peek();
// Lint plugins are registered; now we can process command line flags.
if sess.opts.describe_lints {
describe_lints(&sess, &lint_store, true);
return early_exit();
}
}
queries.expansion()?;
if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
return early_exit();
}
queries.prepare_outputs()?;
if sess.opts.output_types.contains_key(&OutputType::DepInfo)
&& sess.opts.output_types.len() == 1
{
return early_exit();
}
queries.global_ctxt()?;
// Drop AST after creating GlobalCtxt to free memory
{
let _timer = sess.prof.generic_activity("drop_ast");
mem::drop(queries.expansion()?.take());
}
if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
return early_exit();
}
if sess.opts.debugging_opts.save_analysis {
let crate_name = queries.crate_name()?.peek().clone();
queries.global_ctxt()?.peek_mut().enter(|tcx| {
let result = tcx.analysis(LOCAL_CRATE);
sess.time("save_analysis", || {
save::process_crate(
tcx,
&crate_name,
&compiler.input(),
None,
DumpHandler::new(
compiler.output_dir().as_ref().map(|p| &**p),
&crate_name,
),
)
});
result
})?;
}
queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
return early_exit();
}
queries.ongoing_codegen()?;
if sess.opts.debugging_opts.print_type_sizes {
sess.code_stats.print_type_sizes();
}
let linker = queries.linker()?;
Ok(Some(linker))
})?;
if let Some(linker) = linker {
let _timer = sess.timer("link");
linker.link()?
}
if sess.opts.debugging_opts.perf_stats {
sess.print_perf_stats();
}
if sess.print_fuel_crate.is_some() {
eprintln!(
"Fuel used by {}: {}",
sess.print_fuel_crate.as_ref().unwrap(),
sess.print_fuel.load(SeqCst)
);
}
Ok(())
})
}
#[cfg(unix)]
pub fn set_sigpipe_handler() {
unsafe {
// Set the SIGPIPE signal handler, so that an EPIPE
// will cause rustc to terminate, as expected.
assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
}
}
#[cfg(windows)]
pub fn set_sigpipe_handler() {}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0];
if ifile == "-" {
let mut src = String::new();
let err = if io::stdin().read_to_string(&mut src).is_err() {
Some(io::Error::new(
io::ErrorKind::InvalidData,
"couldn't read from stdin, as it did not contain valid UTF-8",
))
} else {
None
};
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
);
let line = isize::from_str_radix(&line, 10)
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
return Some((Input::Str { name: file_name, input: src }, None, err));
}
Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next(),
}
}
}
/// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
// FIXME remove these and use winapi 0.3 instead
// Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
#[cfg(unix)]
fn stdout_isatty() -> bool {
unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
}
#[cfg(windows)]
fn stdout_isatty() -> bool {
use winapi::um::consoleapi::GetConsoleMode;
use winapi::um::processenv::GetStdHandle;
use winapi::um::winbase::STD_OUTPUT_HANDLE;
unsafe {
let handle = GetStdHandle(STD_OUTPUT_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out) != 0
}
}
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
let normalised =
if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) };
match registry.try_find_description(&normalised) {
Ok(Some(description)) => {
let mut is_in_code_block = false;
let mut text = String::new();
// Slice off the leading newline and print.
for line in description.lines() {
let indent_level =
line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
let dedented_line = &line[indent_level..];
if dedented_line.starts_with("```") {
is_in_code_block = !is_in_code_block;
text.push_str(&line[..(indent_level + 3)]);
} else if is_in_code_block && dedented_line.starts_with("# ") {
continue;
} else {
text.push_str(line);
}
text.push('\n');
}
if stdout_isatty() {
show_content_with_pager(&text);
} else {
print!("{}", text);
}
}
Ok(None) => {
early_error(output, &format!("no extended information for {}", code));
}
Err(InvalidErrorCode) => {
early_error(output, &format!("{} is not a valid error code", code));
}
}
}
fn show_content_with_pager(content: &String) {
let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
});
let mut fallback_to_println = false;
match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
Ok(mut pager) => {
if let Some(pipe) = pager.stdin.as_mut() {
if pipe.write_all(content.as_bytes()).is_err() {
fallback_to_println = true;
}
}
if pager.wait().is_err() {
fallback_to_println = true;
}
}
Err(_) => {
fallback_to_println = true;
}
}
// If pager fails for whatever reason, we should still print the content
// to standard output
if fallback_to_println {
print!("{}", content);
}
}
impl RustcDefaultCalls {
fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> {
if let Input::File(file) = compiler.input() {
// FIXME: #![crate_type] and #![crate_name] support not implemented yet
let attrs = vec![];
sess.init_crate_types(collect_crate_types(sess, &attrs));
let outputs = compiler.build_output_filenames(&sess, &attrs);
let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
sess.fatal(&format!("failed to read rlink file: {}", err));
});
let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| {
sess.fatal(&format!("failed to decode rlink: {}", err));
});
compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs)
} else {
sess.fatal("rlink must be a file")
}
}
pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
if sess.opts.debugging_opts.link_only {
let result = RustcDefaultCalls::process_rlink(sess, compiler);
abort_on_err(result, sess);
Compilation::Stop
} else {
Compilation::Continue
}
}
pub fn list_metadata(
sess: &Session,
metadata_loader: &dyn MetadataLoader,
matches: &getopts::Matches,
input: &Input,
) -> Compilation {
let r = matches.opt_strs("Z");
if r.iter().any(|s| *s == "ls") {
match *input {
Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v)
.unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
Input::Str { .. } => {
early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
Compilation::Continue
}
fn print_crate_info(
codegen_backend: &dyn CodegenBackend,
sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
) -> Compilation {
use rustc_session::config::PrintRequest::*;
// PrintRequest::NativeStaticLibs is special - printed during linking
// (empty iterator returns true)
if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
return Compilation::Continue;
}
let attrs = match input {
None => None,
Some(input) => {
let result = parse_crate_attrs(sess, input);
match result {
Ok(attrs) => Some(attrs),
Err(mut parse_error) => {
parse_error.emit();
return Compilation::Stop;
}
}
}
};
for req in &sess.opts.prints {
match *req {
TargetList => {
let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
targets.sort();
println!("{}", targets.join("\n"));
}
Sysroot => println!("{}", sess.sysroot.display()),
TargetLibdir => println!(
"{}",
sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display()
),
TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
FileNames | CrateName => {
let input = input.unwrap_or_else(|| {
early_error(ErrorOutputType::default(), "no input file provided")
});
let attrs = attrs.as_ref().unwrap();
let t_outputs = rustc_interface::util::build_output_filenames(
input, odir, ofile, attrs, sess,
);
let id = rustc_session::output::find_crate_name(sess, attrs, input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue;
}
let crate_types = collect_crate_types(sess, attrs);
for &style in &crate_types {
let fname =
rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
println!("{}", fname.file_name().unwrap().to_string_lossy());
}
}
Cfg => {
let allow_unstable_cfg =
UnstableFeatures::from_environment().is_nightly_build();
let mut cfgs = sess
.parse_sess
.config
.iter()
.filter_map(|&(name, value)| {
// Note that crt-static is a specially recognized cfg
// directive that's printed out here as part of
// rust-lang/rust#37406, but in general the
// `target_feature` cfg is gated under
// rust-lang/rust#29717. For now this is just
// specifically allowing the crt-static cfg and that's
// it, this is intended to get into Cargo and then go
// through to build scripts.
if (name != sym::target_feature || value != Some(sym::crt_dash_static))
&& !allow_unstable_cfg
&& find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
{
return None;
}
if let Some(value) = value {
Some(format!("{}=\"{}\"", name, value))
} else {
Some(name.to_string())
}
})
.collect::<Vec<String>>();
cfgs.sort();
for cfg in cfgs {
println!("{}", cfg);
}
}
RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
codegen_backend.print(*req, sess);
}
// Any output here interferes with Cargo's parsing of other printed output
PrintRequest::NativeStaticLibs => {}
}
}
Compilation::Stop
}
}
/// Returns a version string such as "0.12.0-dev".
fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str {
x.unwrap_or("unknown")
}
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
get_builtin_codegen_backend("llvm")().print_version();
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
let mut options = getopts::Options::new();
for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
(option.apply)(&mut options);
}
let message = "Usage: rustc [OPTIONS] INPUT";
let nightly_help = if nightly_options::is_nightly_build() {
"\n -Z help Print unstable compiler options"
} else {
""
};
let verbose_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
let at_path = if verbose && nightly_options::is_nightly_build() {
" @path Read newline separated options from `path`\n"
} else {
""
};
println!(
"{options}{at_path}\nAdditional help:
-C help Print codegen options
-W help \
Print 'lint' options and default settings{nightly}{verbose}\n",
options = options.usage(message),
at_path = at_path,
nightly = nightly_help,
verbose = verbose_help
);
}
fn print_wall_help() {
println!(
"
The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
default. Use `rustc -W help` to see all available lints. It's more common to put
warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
the command line flag directly.
"
);
}
fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
println!(
"
Available lint options:
-W <foo> Warn about <foo>
-A <foo> \
Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> \
(deny <foo> and all attempts to override)
"
);
fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
// The sort doesn't case-fold but it's doubtful we care.
lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
lints
}
fn sort_lint_groups(
lints: Vec<(&'static str, Vec<LintId>, bool)>,
) -> Vec<(&'static str, Vec<LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by_key(|l| l.0);
lints
}
let (plugin, builtin): (Vec<_>, _) =
lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
let plugin = sort_lints(sess, plugin);
let builtin = sort_lints(sess, builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) =
lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len =
plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
let padded = |x: &str| {
let mut s = " ".repeat(max_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = max(
"warnings".len(),
plugin_groups
.iter()
.chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max()
.unwrap_or(0),
);
let padded = |x: &str| {
let mut s = " ".repeat(max_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to
.into_iter()
.map(|x| x.to_string().replace("_", "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded(&name), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!(
"Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename."
);
}
(false, ..) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable options:\n");
print_flag_list("-Z", config::DB_OPTIONS);
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
print_flag_list("-C", config::CG_OPTIONS);
}
fn print_flag_list<T>(
cmdline_opt: &str,
flag_list: &[(&'static str, T, &'static str, &'static str)],
) {
let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
for &(name, _, _, desc) in flag_list {
println!(
" {} {:>width$}=val -- {}",
cmdline_opt,
name.replace("_", "-"),
desc,
width = max_len
);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args,
/// otherwise returns `None`.
///
/// The compiler's handling of options is a little complicated as it ties into
/// our stability story. The current intention of each compiler option is to
/// have one of two modes:
///
/// 1. An option is stable and can be used everywhere.
/// 2. An option is unstable, and can only be used on nightly.
///
/// Like unstable library and language features, however, unstable options have
/// always required a form of "opt in" to indicate that you're using them. This
/// provides the easy ability to scan a code base to check to see if anything
/// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
///
/// All options behind `-Z` are considered unstable by default. Other top-level
/// options can also be considered unstable, and they were unlocked through the
/// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
/// instability in both cases, though.
///
/// So with all that in mind, the comments below have some more detail about the
/// contortions done here to get things to work out correctly.
pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let args = &args[1..];
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
// Parse with *all* options defined in the compiler, we don't worry about
// option stability here we just want to parse as much as possible.
let mut options = getopts::Options::new();
for option in config::rustc_optgroups() {
(option.apply)(&mut options);
}
let matches = options
.parse(args)
.unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string()));
// For all options we just parsed, we check a few aspects:
//
// * If the option is stable, we're all good
// * If the option wasn't passed, we're all good
// * If `-Z unstable-options` wasn't passed (and we're not a -Z option
// ourselves), then we require the `-Z unstable-options` flag to unlock
// this option that was passed.
// * If we're a nightly compiler, then unstable options are now unlocked, so
// we're good to go.
// * Otherwise, if we're an unstable option then we generate an error
// (unstable option being used on stable)
nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
if matches.opt_present("h") || matches.opt_present("help") {
// Only show unstable options in --help if we accept unstable options.
usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
return None;
}
// Handle the special case of -Wall.
let wall = matches.opt_strs("W");
if wall.iter().any(|x| *x == "all") {
print_wall_help();
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.iter().any(|x| *x == "no-stack-check") {
early_warn(
ErrorOutputType::default(),
"the --no-stack-check flag is deprecated and does nothing",
);
}
if cg_flags.iter().any(|x| *x == "passes=list") {
get_builtin_codegen_backend("llvm")().print_passes();
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
match input {
Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
name.clone(),
input.clone(),
&sess.parse_sess,
),
}
}
/// Gets a list of extra command-line flags provided by the user, as strings.
///
/// This function is used during ICEs to show more information useful for
/// debugging, since some ICEs only happens with non-default compiler flags
/// (and the users don't always report them).
fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
// Avoid printing help because of empty args. This can suggest the compiler
// itself is not the program root (consider RLS).
if args.len() < 2 {
return None;
}
let matches = handle_options(&args)?;
let mut result = Vec::new();
let mut excluded_cargo_defaults = false;
for flag in ICE_REPORT_COMPILER_FLAGS {
let prefix = if flag.len() == 1 { "-" } else { "--" };
for content in &matches.opt_strs(flag) {
// Split always returns the first element
let name = if let Some(first) = content.split('=').next() { first } else { &content };
let content =
if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
result.push(format!("{}{} {}", prefix, flag, content));
} else {
excluded_cargo_defaults = true;
}
}
}
if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
}
/// Runs a closure and catches unwinds triggered by fatal errors.
///
/// The compiler currently unwinds with a special sentinel value to abort
/// compilation on fatal errors. This function catches that sentinel and turns
/// the panic into a `Result` instead.
pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
if value.is::<rustc_errors::FatalErrorMarker>() {
ErrorReported
} else {
panic::resume_unwind(value);
}
})
}
/// Variant of `catch_fatal_errors` for the `interface::Result` return type
/// that also computes the exit code.
pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
let result = catch_fatal_errors(f).and_then(|result| result);
match result {
Ok(()) => EXIT_SUCCESS,
Err(_) => EXIT_FAILURE,
}
}
static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
SyncLazy::new(|| {
let hook = panic::take_hook();
panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
hook
});
/// Prints the ICE message, including backtrace and query stack.
///
/// The message will point the user at `bug_report_url` to report the ICE.
///
/// When `install_ice_hook` is called, this function will be called as the panic
/// hook.
pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
// Invoke the default handler, which prints the actual panic message and optionally a backtrace
(*DEFAULT_HOOK)(info);
// Separate the output with an empty line
eprintln!();
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
false,
false,
None,
false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !info.payload().is::<rustc_errors::ExplicitBug>() {
let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&d);
}
let mut xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
format!("we would appreciate a bug report: {}", bug_report_url).into(),
format!(
"rustc {} running on {}",
option_env!("CFG_VERSION").unwrap_or("unknown_version"),
config::host_triple()
)
.into(),
];
if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
xs.push(format!("compiler flags: {}", flags.join(" ")).into());
if excluded_cargo_defaults {
xs.push("some of the compiler flags provided by cargo are hidden".into());
}
}
for note in &xs {
handler.note_without_error(¬e);
}
// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
if backtrace {
TyCtxt::try_print_query_stack(&handler);
}
#[cfg(windows)]
unsafe {
if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
// Trigger a debugger if we crashed during bootstrap
winapi::um::debugapi::DebugBreak();
}
}
}
/// Installs a panic hook that will print the ICE message on unexpected panics.
///
/// A custom rustc driver can skip calling this to set up a custom ICE hook.
pub fn install_ice_hook() {
SyncLazy::force(&DEFAULT_HOOK);
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version.
pub fn init_rustc_env_logger() {
init_env_logger("RUSTC_LOG")
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) {
// Don't register a dispatcher if there's no filter to print anything
match std::env::var(env) {
Err(_) => return,
Ok(s) if s.is_empty() => return,
Ok(_) => {}
}
let filter = tracing_subscriber::EnvFilter::from_env(env);
let layer = tracing_tree::HierarchicalLayer::default()
.with_indent_lines(true)
.with_ansi(true)
.with_targets(true)
.with_thread_ids(true)
.with_thread_names(true)
.with_wraparound(10)
.with_verbose_exit(true)
.with_verbose_entry(true)
.with_indent_amount(2);
use tracing_subscriber::layer::SubscriberExt;
let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
pub fn main() -> ! {
let start = Instant::now();
init_rustc_env_logger();
let mut callbacks = TimePassesCallbacks::default();
install_ice_hook();
let exit_code = catch_with_exit_code(|| {
let args = env::args_os()
.enumerate()
.map(|(i, arg)| {
arg.into_string().unwrap_or_else(|arg| {
early_error(
ErrorOutputType::default(),
&format!("Argument {} is not valid Unicode: {:?}", i, arg),
)
})
})
.collect::<Vec<_>>();
run_compiler(&args, &mut callbacks, None, None, None)
});
// The extra `\t` is necessary to align this label with the others.
print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
process::exit(exit_code)
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositor_data::{CompositorData, WantsScrollEvents};
use windowing::{MouseWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent};
use windowing::MouseWindowMouseUpEvent;
use geom::length::Length;
use geom::point::{Point2D, TypedPoint2D};
use geom::rect::Rect;
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::layers::Layer;
use script_traits::{ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, SendEventMsg};
use script_traits::{ScriptControlChan};
use servo_msg::compositor_msg::FixedPosition;
use servo_util::geometry::PagePx;
use std::rc::Rc;
use geom::matrix::identity;
trait Clampable {
fn clamp(&self, mn: &Self, mx: &Self) -> Self;
}
impl Clampable for f32 {
/// Returns the number constrained within the range `mn <= self <= mx`.
/// If any of the numbers are `NAN` then `NAN` is returned.
#[inline]
fn clamp(&self, mn: &f32, mx: &f32) -> f32 {
match () {
_ if self.is_nan() => *self,
_ if !(*self <= *mx) => *mx,
_ if !(*self >= *mn) => *mn,
_ => *self,
}
}
}
#[deriving(PartialEq)]
pub enum ScrollEventResult {
ScrollEventUnhandled,
ScrollPositionChanged,
ScrollPositionUnchanged,
}
/// Move the layer's descendants that don't want scroll events and scroll by a relative
/// specified amount in page coordinates. This also takes in a cursor position to see if the
/// mouse is over child layers first. If a layer successfully scrolled, returns true; otherwise
/// returns false, so a parent layer can scroll instead.
pub fn handle_scroll_event(layer: Rc<Layer<CompositorData>>,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, f32>,
window_size: TypedSize2D<DevicePixel, f32>,
scale: ScaleFactor<PagePx, DevicePixel, f32>)
-> ScrollEventResult {
// If this layer doesn't want scroll events, neither it nor its children can handle scroll
// events.
if layer.extra_data.borrow().wants_scroll_events != WantsScrollEvents {
return ScrollEventUnhandled;
}
// Allow children to scroll.
let scroll_offset = layer.extra_data.borrow().scroll_offset;
let scroll_offset_in_device_pixels = scroll_offset * scale;
let new_cursor = cursor - scroll_offset_in_device_pixels;
for child in layer.children().iter() {
let child_bounds = child.bounds.borrow();
if child_bounds.contains(&new_cursor) {
let result = handle_scroll_event(child.clone(),
delta,
new_cursor - child_bounds.origin,
child_bounds.size,
scale);
if result != ScrollEventUnhandled {
return result;
}
}
}
clamp_scroll_offset_and_scroll_layer(layer,
scroll_offset_in_device_pixels + delta,
window_size,
scale)
}
pub fn calculate_content_size_for_layer(layer: Rc<Layer<CompositorData>>)
-> TypedSize2D<DevicePixel, f32> {
layer.children().iter().fold(Rect::zero(),
|unioned_rect, child_rect| {
unioned_rect.union(&*child_rect.bounds.borrow())
}).size
}
pub fn clamp_scroll_offset_and_scroll_layer(layer: Rc<Layer<CompositorData>>,
new_offset: TypedPoint2D<DevicePixel, f32>,
window_size: TypedSize2D<DevicePixel, f32>,
scale: ScaleFactor<PagePx, DevicePixel, f32>)
-> ScrollEventResult {
let layer_size = calculate_content_size_for_layer(layer.clone());
let min_x = (window_size.width - layer_size.width).get().min(0.0);
let min_y = (window_size.height - layer_size.height).get().min(0.0);
let new_offset : TypedPoint2D<DevicePixel, f32> =
Point2D(Length(new_offset.x.get().clamp(&min_x, &0.0)),
Length(new_offset.y.get().clamp(&min_y, &0.0)));
let new_offset_in_page_px = new_offset / scale;
if layer.extra_data.borrow().scroll_offset == new_offset_in_page_px {
return ScrollPositionUnchanged;
}
// The scroll offset is just a record of the scroll position of this scrolling root,
// but scroll_layer_and_all_child_layers actually moves the child layers.
layer.extra_data.borrow_mut().scroll_offset = new_offset_in_page_px;
let mut result = false;
for child in layer.children().iter() {
result |= scroll_layer_and_all_child_layers(child.clone(), new_offset_in_page_px);
}
if result {
return ScrollPositionChanged;
} else {
return ScrollPositionUnchanged;
}
}
fn scroll_layer_and_all_child_layers(layer: Rc<Layer<CompositorData>>,
new_offset: TypedPoint2D<PagePx, f32>)
-> bool {
let mut result = false;
// Only scroll this layer if it's not fixed-positioned.
if layer.extra_data.borrow().scroll_policy != FixedPosition {
let new_offset = new_offset.to_untyped();
*layer.transform.borrow_mut() = identity().translate(new_offset.x,
new_offset.y,
0.0);
*layer.content_offset.borrow_mut() = new_offset;
result = true
}
for child in layer.children().iter() {
result |= scroll_layer_and_all_child_layers(child.clone(), new_offset);
}
return result;
}
// Takes in a MouseWindowEvent, determines if it should be passed to children, and
// sends the event off to the appropriate pipeline. NB: the cursor position is in
// page coordinates.
pub fn send_mouse_event(layer: Rc<Layer<CompositorData>>,
event: MouseWindowEvent,
cursor: TypedPoint2D<DevicePixel, f32>,
device_pixels_per_page_px: ScaleFactor<PagePx, DevicePixel, f32>) {
let content_offset = *layer.content_offset.borrow() * device_pixels_per_page_px.get();
let content_offset : TypedPoint2D<DevicePixel, f32> = Point2D::from_untyped(&content_offset);
let cursor = cursor - content_offset;
for child in layer.children().iter() {
let child_bounds = child.bounds.borrow();
if child_bounds.contains(&cursor) {
send_mouse_event(child.clone(),
event,
cursor - child_bounds.origin,
device_pixels_per_page_px);
return;
}
}
// This mouse event is mine!
let cursor = cursor / device_pixels_per_page_px;
let message = match event {
MouseWindowClickEvent(button, _) => ClickEvent(button, cursor.to_untyped()),
MouseWindowMouseDownEvent(button, _) => MouseDownEvent(button, cursor.to_untyped()),
MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, cursor.to_untyped()),
};
let ScriptControlChan(ref chan) = layer.extra_data.borrow().pipeline.script_chan;
let _ = chan.send_opt(SendEventMsg(layer.extra_data.borrow().pipeline.id.clone(), message));
}
pub fn send_mouse_move_event(layer: Rc<Layer<CompositorData>>,
cursor: TypedPoint2D<PagePx, f32>) {
let message = MouseMoveEvent(cursor.to_untyped());
let ScriptControlChan(ref chan) = layer.extra_data.borrow().pipeline.script_chan;
let _ = chan.send_opt(SendEventMsg(layer.extra_data.borrow().pipeline.id.clone(), message));
}
Compound scrolling offsets when setting content offset
When traversing the layer tree to assign content offset, the new offset
needs to take into account any additional offset from children that are
also scrolling roots. This means that when you scroll a parent frame, it
doesn't override the scroll position of its children, but adds to it.
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use compositor_data::{CompositorData, WantsScrollEvents};
use windowing::{MouseWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent};
use windowing::MouseWindowMouseUpEvent;
use geom::length::Length;
use geom::point::{Point2D, TypedPoint2D};
use geom::rect::Rect;
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::layers::Layer;
use script_traits::{ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, SendEventMsg};
use script_traits::{ScriptControlChan};
use servo_msg::compositor_msg::FixedPosition;
use servo_util::geometry::PagePx;
use std::rc::Rc;
use geom::matrix::identity;
trait Clampable {
fn clamp(&self, mn: &Self, mx: &Self) -> Self;
}
impl Clampable for f32 {
/// Returns the number constrained within the range `mn <= self <= mx`.
/// If any of the numbers are `NAN` then `NAN` is returned.
#[inline]
fn clamp(&self, mn: &f32, mx: &f32) -> f32 {
match () {
_ if self.is_nan() => *self,
_ if !(*self <= *mx) => *mx,
_ if !(*self >= *mn) => *mn,
_ => *self,
}
}
}
#[deriving(PartialEq)]
pub enum ScrollEventResult {
ScrollEventUnhandled,
ScrollPositionChanged,
ScrollPositionUnchanged,
}
/// Move the layer's descendants that don't want scroll events and scroll by a relative
/// specified amount in page coordinates. This also takes in a cursor position to see if the
/// mouse is over child layers first. If a layer successfully scrolled, returns true; otherwise
/// returns false, so a parent layer can scroll instead.
pub fn handle_scroll_event(layer: Rc<Layer<CompositorData>>,
delta: TypedPoint2D<DevicePixel, f32>,
cursor: TypedPoint2D<DevicePixel, f32>,
window_size: TypedSize2D<DevicePixel, f32>,
scale: ScaleFactor<PagePx, DevicePixel, f32>)
-> ScrollEventResult {
// If this layer doesn't want scroll events, neither it nor its children can handle scroll
// events.
if layer.extra_data.borrow().wants_scroll_events != WantsScrollEvents {
return ScrollEventUnhandled;
}
// Allow children to scroll.
let scroll_offset = layer.extra_data.borrow().scroll_offset;
let scroll_offset_in_device_pixels = scroll_offset * scale;
let new_cursor = cursor - scroll_offset_in_device_pixels;
for child in layer.children().iter() {
let child_bounds = child.bounds.borrow();
if child_bounds.contains(&new_cursor) {
let result = handle_scroll_event(child.clone(),
delta,
new_cursor - child_bounds.origin,
child_bounds.size,
scale);
if result != ScrollEventUnhandled {
return result;
}
}
}
clamp_scroll_offset_and_scroll_layer(layer,
scroll_offset_in_device_pixels + delta,
window_size,
scale)
}
pub fn calculate_content_size_for_layer(layer: Rc<Layer<CompositorData>>)
-> TypedSize2D<DevicePixel, f32> {
layer.children().iter().fold(Rect::zero(),
|unioned_rect, child_rect| {
unioned_rect.union(&*child_rect.bounds.borrow())
}).size
}
pub fn clamp_scroll_offset_and_scroll_layer(layer: Rc<Layer<CompositorData>>,
new_offset: TypedPoint2D<DevicePixel, f32>,
window_size: TypedSize2D<DevicePixel, f32>,
scale: ScaleFactor<PagePx, DevicePixel, f32>)
-> ScrollEventResult {
let layer_size = calculate_content_size_for_layer(layer.clone());
let min_x = (window_size.width - layer_size.width).get().min(0.0);
let min_y = (window_size.height - layer_size.height).get().min(0.0);
let new_offset : TypedPoint2D<DevicePixel, f32> =
Point2D(Length(new_offset.x.get().clamp(&min_x, &0.0)),
Length(new_offset.y.get().clamp(&min_y, &0.0)));
let new_offset_in_page_px = new_offset / scale;
if layer.extra_data.borrow().scroll_offset == new_offset_in_page_px {
return ScrollPositionUnchanged;
}
// The scroll offset is just a record of the scroll position of this scrolling root,
// but scroll_layer_and_all_child_layers actually moves the child layers.
layer.extra_data.borrow_mut().scroll_offset = new_offset_in_page_px;
let mut result = false;
for child in layer.children().iter() {
result |= scroll_layer_and_all_child_layers(child.clone(), new_offset_in_page_px);
}
if result {
return ScrollPositionChanged;
} else {
return ScrollPositionUnchanged;
}
}
fn scroll_layer_and_all_child_layers(layer: Rc<Layer<CompositorData>>,
new_offset: TypedPoint2D<PagePx, f32>)
-> bool {
let mut result = false;
// Only scroll this layer if it's not fixed-positioned.
if layer.extra_data.borrow().scroll_policy != FixedPosition {
let new_offset = new_offset.to_untyped();
*layer.transform.borrow_mut() = identity().translate(new_offset.x,
new_offset.y,
0.0);
*layer.content_offset.borrow_mut() = new_offset;
result = true
}
let offset_for_children = new_offset + layer.extra_data.borrow().scroll_offset;
for child in layer.children().iter() {
result |= scroll_layer_and_all_child_layers(child.clone(), offset_for_children);
}
return result;
}
// Takes in a MouseWindowEvent, determines if it should be passed to children, and
// sends the event off to the appropriate pipeline. NB: the cursor position is in
// page coordinates.
pub fn send_mouse_event(layer: Rc<Layer<CompositorData>>,
event: MouseWindowEvent,
cursor: TypedPoint2D<DevicePixel, f32>,
device_pixels_per_page_px: ScaleFactor<PagePx, DevicePixel, f32>) {
let content_offset = *layer.content_offset.borrow() * device_pixels_per_page_px.get();
let content_offset : TypedPoint2D<DevicePixel, f32> = Point2D::from_untyped(&content_offset);
let cursor = cursor - content_offset;
for child in layer.children().iter() {
let child_bounds = child.bounds.borrow();
if child_bounds.contains(&cursor) {
send_mouse_event(child.clone(),
event,
cursor - child_bounds.origin,
device_pixels_per_page_px);
return;
}
}
// This mouse event is mine!
let cursor = cursor / device_pixels_per_page_px;
let message = match event {
MouseWindowClickEvent(button, _) => ClickEvent(button, cursor.to_untyped()),
MouseWindowMouseDownEvent(button, _) => MouseDownEvent(button, cursor.to_untyped()),
MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, cursor.to_untyped()),
};
let ScriptControlChan(ref chan) = layer.extra_data.borrow().pipeline.script_chan;
let _ = chan.send_opt(SendEventMsg(layer.extra_data.borrow().pipeline.id.clone(), message));
}
pub fn send_mouse_move_event(layer: Rc<Layer<CompositorData>>,
cursor: TypedPoint2D<PagePx, f32>) {
let message = MouseMoveEvent(cursor.to_untyped());
let ScriptControlChan(ref chan) = layer.extra_data.borrow().pipeline.script_chan;
let _ = chan.send_opt(SendEventMsg(layer.extra_data.borrow().pipeline.id.clone(), message));
}
|
#![allow(non_camel_case_types, non_snake_case)]
use libc:: c_void;
#[cfg(target_env = "msvc")]
mod win {
use kernel32;
use libc::{c_int, c_long, c_uchar, c_void};
use std::ffi::CString;
use std::mem;
use std::ptr;
use schannel::cert_context::ValidUses;
use schannel::cert_store::CertStore;
use winapi;
fn lookup(module: Option<&str>, symbol: &str) -> Option<*const ::std::os::raw::c_void> {
let symbol = CString::new(symbol).unwrap();
unsafe {
let mut mod_buf: Vec<u16>;
let mod_ptr: *mut u16 = if let Some(module) = module {
mod_buf = module.encode_utf16().collect();
mod_buf.push(0);
mod_buf.as_mut_ptr()
} else {
ptr::null_mut()
};
let handle = kernel32::GetModuleHandleW(mod_ptr);
let n = kernel32::GetProcAddress(handle, symbol.as_ptr());
if n == ptr::null() {
None
} else {
Some(n)
}
}
}
pub enum X509_STORE {}
pub enum X509 {}
pub enum SSL_CTX {}
type d2i_X509_fn = unsafe extern "C" fn(
a: *mut *mut X509,
pp: *mut *const c_uchar,
length: c_long,
) -> *mut X509;
type X509_free_fn = unsafe extern "C" fn(x: *mut X509);
type X509_STORE_add_cert_fn = unsafe extern "C" fn(store: *mut X509_STORE, x: *mut X509)
-> c_int;
type SSL_CTX_get_cert_store_fn = unsafe extern "C" fn(ctx: *const SSL_CTX)
-> *mut X509_STORE;
struct OpenSSL {
d2i_X509: d2i_X509_fn,
X509_free: X509_free_fn,
X509_STORE_add_cert: X509_STORE_add_cert_fn,
SSL_CTX_get_cert_store: SSL_CTX_get_cert_store_fn,
}
fn lookup_functions(crypto_module: Option<&str>, ssl_module: Option<&str>) -> Option<OpenSSL> {
let d2i_X509 = lookup(crypto_module, "d2i_X509");
let X509_free = lookup(crypto_module, "X509_free");
let X509_STORE_add_cert = lookup(crypto_module, "X509_STORE_add_cert");
let SSL_CTX_get_cert_store = lookup(ssl_module, "SSL_CTX_get_cert_store");
if d2i_X509.is_some() && X509_free.is_some() && X509_STORE_add_cert.is_some() &&
SSL_CTX_get_cert_store.is_some()
{
unsafe {
Some(OpenSSL {
d2i_X509: mem::transmute(d2i_X509.unwrap()),
X509_free: mem::transmute(X509_free.unwrap()),
X509_STORE_add_cert: mem::transmute(X509_STORE_add_cert.unwrap()),
SSL_CTX_get_cert_store: mem::transmute(SSL_CTX_get_cert_store.unwrap()),
})
}
} else {
None
}
}
pub fn add_certs_to_context(ssl_ctx: *mut c_void) {
unsafe {
let openssl = if let Some(o) = lookup_functions(None, None) {
o
} else if let Some(o) = lookup_functions(Some("libcrypto"), Some("libssl")) {
o
} else if let Some(o) = lookup_functions(Some("libeay32"), Some("ssleay32")) {
o
} else {
return;
};
let openssl_store = (openssl.SSL_CTX_get_cert_store)(ssl_ctx as *const SSL_CTX);
let mut store = if let Ok(s) = CertStore::open_current_user("ROOT") {
s
} else {
return;
};
for cert in store.certs() {
let valid_uses = if let Ok(v) = cert.valid_uses() {
v
} else {
return;
};
// check the extended key usage for the "Server Authentication" OID
let is_server_auth = match valid_uses {
ValidUses::All => true,
ValidUses::OIDs(ref oids) => {
oids.contains(&winapi::wincrypt::szOID_PKIX_KP_SERVER_AUTH.to_owned())
}
};
if !is_server_auth {
continue;
}
let der = cert.to_der();
let x509 =
(openssl.d2i_X509)(ptr::null_mut(), &mut der.as_ptr(), der.len() as c_long);
if !x509.is_null() {
(openssl.X509_STORE_add_cert)(openssl_store, x509);
(openssl.X509_free)(x509);
}
}
}
}
}
#[cfg(target_env = "msvc")]
pub fn add_certs_to_context(ssl_ctx: *mut c_void) {
win::add_certs_to_context(ssl_ctx)
}
#[cfg(not(target_env = "msvc"))]
pub fn add_certs_to_context(_: *mut c_void) {}
check for a supported version of openssl before trying to add certificates to the store
#![allow(non_camel_case_types, non_snake_case)]
use libc::c_void;
#[cfg(target_env = "msvc")]
mod win {
use curl_sys;
use kernel32;
use libc::{c_int, c_long, c_uchar, c_void};
use std::ffi::{CStr, CString};
use std::mem;
use std::ptr;
use schannel::cert_context::ValidUses;
use schannel::cert_store::CertStore;
use winapi;
fn lookup(module: Option<&str>, symbol: &str) -> Option<*const ::std::os::raw::c_void> {
let symbol = CString::new(symbol).unwrap();
unsafe {
let mut mod_buf: Vec<u16>;
let mod_ptr: *mut u16 = if let Some(module) = module {
mod_buf = module.encode_utf16().collect();
mod_buf.push(0);
mod_buf.as_mut_ptr()
} else {
ptr::null_mut()
};
let handle = kernel32::GetModuleHandleW(mod_ptr);
let n = kernel32::GetProcAddress(handle, symbol.as_ptr());
if n == ptr::null() {
None
} else {
Some(n)
}
}
}
pub enum X509_STORE {}
pub enum X509 {}
pub enum SSL_CTX {}
type d2i_X509_fn = unsafe extern "C" fn(
a: *mut *mut X509,
pp: *mut *const c_uchar,
length: c_long,
) -> *mut X509;
type X509_free_fn = unsafe extern "C" fn(x: *mut X509);
type X509_STORE_add_cert_fn = unsafe extern "C" fn(store: *mut X509_STORE, x: *mut X509)
-> c_int;
type SSL_CTX_get_cert_store_fn = unsafe extern "C" fn(ctx: *const SSL_CTX)
-> *mut X509_STORE;
struct OpenSSL {
d2i_X509: d2i_X509_fn,
X509_free: X509_free_fn,
X509_STORE_add_cert: X509_STORE_add_cert_fn,
SSL_CTX_get_cert_store: SSL_CTX_get_cert_store_fn,
}
fn lookup_functions(crypto_module: Option<&str>, ssl_module: Option<&str>) -> Option<OpenSSL> {
let d2i_X509 = lookup(crypto_module, "d2i_X509");
let X509_free = lookup(crypto_module, "X509_free");
let X509_STORE_add_cert = lookup(crypto_module, "X509_STORE_add_cert");
let SSL_CTX_get_cert_store = lookup(ssl_module, "SSL_CTX_get_cert_store");
if d2i_X509.is_some() && X509_free.is_some() && X509_STORE_add_cert.is_some() &&
SSL_CTX_get_cert_store.is_some()
{
unsafe {
Some(OpenSSL {
d2i_X509: mem::transmute(d2i_X509.unwrap()),
X509_free: mem::transmute(X509_free.unwrap()),
X509_STORE_add_cert: mem::transmute(X509_STORE_add_cert.unwrap()),
SSL_CTX_get_cert_store: mem::transmute(SSL_CTX_get_cert_store.unwrap()),
})
}
} else {
None
}
}
pub fn add_certs_to_context(ssl_ctx: *mut c_void) {
unsafe {
let curl_ver = curl_sys::curl_version_info(curl_sys::CURLVERSION_NOW);
let ssl_ver = CStr::from_ptr((*curl_ver).ssl_version).to_string_lossy();
let openssl = if ssl_ver.starts_with("OpenSSL/1.1.0") {
lookup_functions(Some("libcrypto"), Some("libssl"))
} else if ssl_ver.starts_with("OpenSSL/1.0.2") {
lookup_functions(Some("libeay32"), Some("ssleay32"))
} else {
return;
};
if openssl.is_none() {
return;
}
let openssl = openssl.unwrap();
let openssl_store = (openssl.SSL_CTX_get_cert_store)(ssl_ctx as *const SSL_CTX);
let mut store = if let Ok(s) = CertStore::open_current_user("ROOT") {
s
} else {
return;
};
for cert in store.certs() {
let valid_uses = if let Ok(v) = cert.valid_uses() {
v
} else {
return;
};
// check the extended key usage for the "Server Authentication" OID
let is_server_auth = match valid_uses {
ValidUses::All => true,
ValidUses::OIDs(ref oids) => {
oids.contains(&winapi::wincrypt::szOID_PKIX_KP_SERVER_AUTH.to_owned())
}
};
if !is_server_auth {
continue;
}
let der = cert.to_der();
let x509 =
(openssl.d2i_X509)(ptr::null_mut(), &mut der.as_ptr(), der.len() as c_long);
if !x509.is_null() {
(openssl.X509_STORE_add_cert)(openssl_store, x509);
(openssl.X509_free)(x509);
}
}
}
}
}
#[cfg(target_env = "msvc")]
pub fn add_certs_to_context(ssl_ctx: *mut c_void) {
win::add_certs_to_context(ssl_ctx)
}
#[cfg(not(target_env = "msvc"))]
pub fn add_certs_to_context(_: *mut c_void) {}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The layout task. Performs layout on the DOM, builds display lists and sends them to be
//! painted.
#![allow(unsafe_code)]
use animation;
use app_units::Au;
use azure::azure::AzColor;
use canvas_traits::CanvasMsg;
use construct::ConstructionResult;
use context::{SharedLayoutContext, StylistWrapper, heap_size_of_local_context};
use data::LayoutDataWrapper;
use display_list_builder::ToGfxColor;
use euclid::Matrix4;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::Size2D;
use flow::{self, Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils};
use flow_ref::{self, FlowRef};
use fnv::FnvHasher;
use gfx::display_list::{ClippingRegion, DisplayList, LayerInfo, OpaqueNode, StackingContext};
use gfx::font_cache_task::FontCacheTask;
use gfx::font_context;
use gfx::paint_task::{LayoutToPaintMsg, PaintLayer};
use gfx_traits::color;
use incremental::{LayoutDamageComputation, REFLOW, REFLOW_ENTIRE_DOCUMENT, REPAINT};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use layout_debug;
use layout_traits::LayoutTaskFactory;
use log;
use msg::compositor_msg::{Epoch, LayerId, ScrollPolicy};
use msg::constellation_msg::ScriptMsg as ConstellationMsg;
use msg::constellation_msg::{ConstellationChan, Failure, PipelineId};
use net_traits::image_cache_task::{ImageCacheChan, ImageCacheResult, ImageCacheTask};
use parallel::{self, WorkQueueData};
use profile_traits::mem::{self, Report, ReportKind, ReportsChan};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
use profile_traits::time::{self, TimerMetadata, profile};
use query::{LayoutRPCImpl, process_content_box_request, process_content_boxes_request};
use query::{process_node_geometry_request, process_offset_parent_query, process_resolved_style_request};
use script::dom::node::LayoutData;
use script::layout_interface::Animation;
use script::layout_interface::{LayoutRPC, OffsetParentResponse};
use script::layout_interface::{Msg, NewLayoutTaskInfo, Reflow, ReflowGoal, ReflowQueryType};
use script::layout_interface::{ScriptLayoutChan, ScriptReflow};
use script::reporter::CSSErrorReporter;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, OpaqueScriptLayoutChannel};
use sequential;
use serde_json;
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::mem::transmute;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::sync::{Arc, Mutex, MutexGuard, RwLock};
use style::computed_values::{filter, mix_blend_mode};
use style::media_queries::{Device, MediaType};
use style::selector_matching::{Stylist, USER_OR_USER_AGENT_STYLESHEETS};
use style::stylesheets::{CSSRuleIteratorExt, Stylesheet};
use style_traits::ParseErrorReporter;
use url::Url;
use util::geometry::MAX_RECT;
use util::ipc::OptionalIpcSender;
use util::logical_geometry::LogicalPoint;
use util::mem::HeapSizeOf;
use util::opts;
use util::task;
use util::task_state;
use util::workqueue::WorkQueue;
use wrapper::{LayoutDocument, LayoutElement, LayoutNode};
use wrapper::{ServoLayoutNode, ThreadSafeLayoutNode};
/// The number of screens of data we're allowed to generate display lists for in each direction.
pub const DISPLAY_PORT_SIZE_FACTOR: i32 = 8;
/// The number of screens we have to traverse before we decide to generate new display lists.
const DISPLAY_PORT_THRESHOLD_SIZE_FACTOR: i32 = 4;
/// Mutable data belonging to the LayoutTask.
///
/// This needs to be protected by a mutex so we can do fast RPCs.
pub struct LayoutTaskData {
/// The channel on which messages can be sent to the constellation.
pub constellation_chan: ConstellationChan<ConstellationMsg>,
/// The root stacking context.
pub stacking_context: Option<Arc<StackingContext>>,
/// Performs CSS selector matching and style resolution.
pub stylist: Box<Stylist>,
/// A queued response for the union of the content boxes of a node.
pub content_box_response: Rect<Au>,
/// A queued response for the content boxes of a node.
pub content_boxes_response: Vec<Rect<Au>>,
/// A queued response for the client {top, left, width, height} of a node in pixels.
pub client_rect_response: Rect<i32>,
/// A queued response for the resolved style property of an element.
pub resolved_style_response: Option<String>,
/// A queued response for the offset parent/rect of a node.
pub offset_parent_response: OffsetParentResponse,
}
/// Information needed by the layout task.
pub struct LayoutTask {
/// The ID of the pipeline that we belong to.
id: PipelineId,
/// The URL of the pipeline that we belong to.
url: RefCell<Url>,
/// Is the current reflow of an iframe, as opposed to a root window?
is_iframe: bool,
/// The port on which we receive messages from the script task.
port: Receiver<Msg>,
/// The port on which we receive messages from the constellation.
pipeline_port: Receiver<LayoutControlMsg>,
/// The port on which we receive messages from the image cache
image_cache_receiver: Receiver<ImageCacheResult>,
/// The channel on which the image cache can send messages to ourself.
image_cache_sender: ImageCacheChan,
/// The port on which we receive messages from the font cache task.
font_cache_receiver: Receiver<()>,
/// The channel on which the font cache can send messages to us.
font_cache_sender: IpcSender<()>,
/// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan<ConstellationMsg>,
/// The channel on which messages can be sent to the script task.
script_chan: IpcSender<ConstellationControlMsg>,
/// The channel on which messages can be sent to the painting task.
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
/// The channel on which messages can be sent to the time profiler.
time_profiler_chan: time::ProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
mem_profiler_chan: mem::ProfilerChan,
/// The channel on which messages can be sent to the image cache.
image_cache_task: ImageCacheTask,
/// Public interface to the font cache task.
font_cache_task: FontCacheTask,
/// Is this the first reflow in this LayoutTask?
first_reflow: bool,
/// To receive a canvas renderer associated to a layer, this message is propagated
/// to the paint chan
canvas_layers_receiver: Receiver<(LayerId, IpcSender<CanvasMsg>)>,
canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>,
/// The workers that we use for parallel operation.
parallel_traversal: Option<WorkQueue<SharedLayoutContext, WorkQueueData>>,
/// Starts at zero, and increased by one every time a layout completes.
/// This can be used to easily check for invalid stale data.
generation: u32,
/// A channel on which new animations that have been triggered by style recalculation can be
/// sent.
new_animations_sender: Sender<Animation>,
/// Receives newly-discovered animations.
new_animations_receiver: Receiver<Animation>,
/// The number of Web fonts that have been requested but not yet loaded.
outstanding_web_fonts: Arc<AtomicUsize>,
/// The root of the flow tree.
root_flow: Option<FlowRef>,
/// The position and size of the visible rect for each layer. We do not build display lists
/// for any areas more than `DISPLAY_PORT_SIZE_FACTOR` screens away from this area.
visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>,
/// The list of currently-running animations.
running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// A counter for epoch messages
epoch: Epoch,
/// The size of the viewport. This may be different from the size of the screen due to viewport
/// constraints.
viewport_size: Size2D<Au>,
/// A mutex to allow for fast, read-only RPC of layout's internal data
/// structures, while still letting the LayoutTask modify them.
///
/// All the other elements of this struct are read-only.
rw_data: Arc<Mutex<LayoutTaskData>>,
/// The CSS error reporter for all CSS loaded in this layout thread
error_reporter: CSSErrorReporter,
}
impl LayoutTaskFactory for LayoutTask {
/// Spawns a new layout task.
fn create(_phantom: Option<&mut LayoutTask>,
id: PipelineId,
url: Url,
is_iframe: bool,
chan: OpaqueScriptLayoutChannel,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan<ConstellationMsg>,
failure_msg: Failure,
script_chan: IpcSender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
shutdown_chan: IpcSender<()>,
content_process_shutdown_chan: IpcSender<()>) {
let ConstellationChan(con_chan) = constellation_chan.clone();
task::spawn_named_with_send_on_failure(format!("LayoutTask {:?}", id),
task_state::LAYOUT,
move || {
{ // Ensures layout task is destroyed before we send shutdown message
let sender = chan.sender();
let layout = LayoutTask::new(id,
url,
is_iframe,
chan.receiver(),
pipeline_port,
constellation_chan,
script_chan,
paint_chan,
image_cache_task,
font_cache_task,
time_profiler_chan,
mem_profiler_chan.clone());
let reporter_name = format!("layout-reporter-{}", id);
mem_profiler_chan.run_with_memory_reporting(|| {
layout.start();
}, reporter_name, sender, Msg::CollectReports);
}
let _ = shutdown_chan.send(());
let _ = content_process_shutdown_chan.send(());
}, ConstellationMsg::Failure(failure_msg), con_chan);
}
}
/// The `LayoutTask` `rw_data` lock must remain locked until the first reflow,
/// as RPC calls don't make sense until then. Use this in combination with
/// `LayoutTask::lock_rw_data` and `LayoutTask::return_rw_data`.
pub enum RWGuard<'a> {
/// If the lock was previously held, from when the task started.
Held(MutexGuard<'a, LayoutTaskData>),
/// If the lock was just used, and has been returned since there has been
/// a reflow already.
Used(MutexGuard<'a, LayoutTaskData>),
}
impl<'a> Deref for RWGuard<'a> {
type Target = LayoutTaskData;
fn deref(&self) -> &LayoutTaskData {
match *self {
RWGuard::Held(ref x) => &**x,
RWGuard::Used(ref x) => &**x,
}
}
}
impl<'a> DerefMut for RWGuard<'a> {
fn deref_mut(&mut self) -> &mut LayoutTaskData {
match *self {
RWGuard::Held(ref mut x) => &mut **x,
RWGuard::Used(ref mut x) => &mut **x,
}
}
}
struct RwData<'a, 'b: 'a> {
rw_data: &'b Arc<Mutex<LayoutTaskData>>,
possibly_locked_rw_data: &'a mut Option<MutexGuard<'b, LayoutTaskData>>,
}
impl<'a, 'b: 'a> RwData<'a, 'b> {
/// If no reflow has happened yet, this will just return the lock in
/// `possibly_locked_rw_data`. Otherwise, it will acquire the `rw_data` lock.
///
/// If you do not wish RPCs to remain blocked, just drop the `RWGuard`
/// returned from this function. If you _do_ wish for them to remain blocked,
/// use `block`.
fn lock(&mut self) -> RWGuard<'b> {
match self.possibly_locked_rw_data.take() {
None => RWGuard::Used(self.rw_data.lock().unwrap()),
Some(x) => RWGuard::Held(x),
}
}
/// If no reflow has ever been triggered, this will keep the lock, locked
/// (and saved in `possibly_locked_rw_data`). If it has been, the lock will
/// be unlocked.
fn block(&mut self, rw_data: RWGuard<'b>) {
match rw_data {
RWGuard::Used(x) => drop(x),
RWGuard::Held(x) => *self.possibly_locked_rw_data = Some(x),
}
}
}
fn add_font_face_rules(stylesheet: &Stylesheet,
device: &Device,
font_cache_task: &FontCacheTask,
font_cache_sender: &IpcSender<()>,
outstanding_web_fonts_counter: &Arc<AtomicUsize>) {
for font_face in stylesheet.effective_rules(&device).font_face() {
for source in &font_face.sources {
if opts::get().load_webfonts_synchronously {
let (sender, receiver) = ipc::channel().unwrap();
font_cache_task.add_web_font(font_face.family.clone(),
(*source).clone(),
sender);
receiver.recv().unwrap();
} else {
outstanding_web_fonts_counter.fetch_add(1, Ordering::SeqCst);
font_cache_task.add_web_font(font_face.family.clone(),
(*source).clone(),
(*font_cache_sender).clone());
}
}
}
}
impl LayoutTask {
/// Creates a new `LayoutTask` structure.
fn new(id: PipelineId,
url: Url,
is_iframe: bool,
port: Receiver<Msg>,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan<ConstellationMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan)
-> LayoutTask {
let device = Device::new(
MediaType::Screen,
opts::get().initial_window_size.as_f32() * ScaleFactor::new(1.0));
let parallel_traversal = if opts::get().layout_threads != 1 {
Some(WorkQueue::new("LayoutWorker", task_state::LAYOUT,
opts::get().layout_threads))
} else {
None
};
// Create the channel on which new animations can be sent.
let (new_animations_sender, new_animations_receiver) = channel();
let (canvas_layers_sender, canvas_layers_receiver) = channel();
// Proxy IPC messages from the pipeline to the layout thread.
let pipeline_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(pipeline_port);
// Ask the router to proxy IPC messages from the image cache task to the layout thread.
let (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap();
let image_cache_receiver =
ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_image_cache_receiver);
// Ask the router to proxy IPC messages from the font cache task to the layout thread.
let (ipc_font_cache_sender, ipc_font_cache_receiver) = ipc::channel().unwrap();
let font_cache_receiver =
ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_font_cache_receiver);
let stylist = box Stylist::new(device);
let outstanding_web_fonts_counter = Arc::new(AtomicUsize::new(0));
for stylesheet in &*USER_OR_USER_AGENT_STYLESHEETS {
add_font_face_rules(stylesheet,
&stylist.device,
&font_cache_task,
&ipc_font_cache_sender,
&outstanding_web_fonts_counter);
}
LayoutTask {
id: id,
url: RefCell::new(url),
is_iframe: is_iframe,
port: port,
pipeline_port: pipeline_receiver,
script_chan: script_chan,
constellation_chan: constellation_chan.clone(),
paint_chan: paint_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
first_reflow: true,
image_cache_receiver: image_cache_receiver,
image_cache_sender: ImageCacheChan(ipc_image_cache_sender),
font_cache_receiver: font_cache_receiver,
font_cache_sender: ipc_font_cache_sender,
canvas_layers_receiver: canvas_layers_receiver,
canvas_layers_sender: canvas_layers_sender,
parallel_traversal: parallel_traversal,
generation: 0,
new_animations_sender: new_animations_sender,
new_animations_receiver: new_animations_receiver,
outstanding_web_fonts: outstanding_web_fonts_counter,
root_flow: None,
visible_rects: Arc::new(HashMap::with_hash_state(Default::default())),
running_animations: Arc::new(RwLock::new(HashMap::new())),
expired_animations: Arc::new(RwLock::new(HashMap::new())),
epoch: Epoch(0),
viewport_size: Size2D::new(Au(0), Au(0)),
rw_data: Arc::new(Mutex::new(
LayoutTaskData {
constellation_chan: constellation_chan,
stacking_context: None,
stylist: stylist,
content_box_response: Rect::zero(),
content_boxes_response: Vec::new(),
client_rect_response: Rect::zero(),
resolved_style_response: None,
offset_parent_response: OffsetParentResponse::empty(),
})),
error_reporter: CSSErrorReporter,
}
}
/// Starts listening on the port.
fn start(mut self) {
let rw_data = self.rw_data.clone();
let mut possibly_locked_rw_data = Some(rw_data.lock().unwrap());
let mut rw_data = RwData {
rw_data: &rw_data,
possibly_locked_rw_data: &mut possibly_locked_rw_data,
};
while self.handle_request(&mut rw_data) {
// Loop indefinitely.
}
}
// Create a layout context for use in building display lists, hit testing, &c.
fn build_shared_layout_context(&self,
rw_data: &LayoutTaskData,
screen_size_changed: bool,
url: &Url,
goal: ReflowGoal)
-> SharedLayoutContext {
SharedLayoutContext {
image_cache_task: self.image_cache_task.clone(),
image_cache_sender: Mutex::new(self.image_cache_sender.clone()),
viewport_size: self.viewport_size.clone(),
screen_size_changed: screen_size_changed,
font_cache_task: Mutex::new(self.font_cache_task.clone()),
canvas_layers_sender: Mutex::new(self.canvas_layers_sender.clone()),
stylist: StylistWrapper(&*rw_data.stylist),
url: (*url).clone(),
visible_rects: self.visible_rects.clone(),
generation: self.generation,
new_animations_sender: Mutex::new(self.new_animations_sender.clone()),
goal: goal,
running_animations: self.running_animations.clone(),
expired_animations: self.expired_animations.clone(),
error_reporter: self.error_reporter.clone(),
}
}
/// Receives and dispatches messages from the script and constellation tasks
fn handle_request<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) -> bool {
enum Request {
FromPipeline(LayoutControlMsg),
FromScript(Msg),
FromImageCache,
FromFontCache,
}
let request = {
let port_from_script = &self.port;
let port_from_pipeline = &self.pipeline_port;
let port_from_image_cache = &self.image_cache_receiver;
let port_from_font_cache = &self.font_cache_receiver;
select! {
msg = port_from_pipeline.recv() => {
Request::FromPipeline(msg.unwrap())
},
msg = port_from_script.recv() => {
Request::FromScript(msg.unwrap())
},
msg = port_from_image_cache.recv() => {
msg.unwrap();
Request::FromImageCache
},
msg = port_from_font_cache.recv() => {
msg.unwrap();
Request::FromFontCache
}
}
};
match request {
Request::FromPipeline(LayoutControlMsg::SetVisibleRects(new_visible_rects)) => {
self.handle_request_helper(Msg::SetVisibleRects(new_visible_rects),
possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::TickAnimations) => {
self.handle_request_helper(Msg::TickAnimations, possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::GetCurrentEpoch(sender)) => {
self.handle_request_helper(Msg::GetCurrentEpoch(sender), possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::GetWebFontLoadState(sender)) => {
self.handle_request_helper(Msg::GetWebFontLoadState(sender),
possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::ExitNow) => {
self.handle_request_helper(Msg::ExitNow, possibly_locked_rw_data)
},
Request::FromScript(msg) => {
self.handle_request_helper(msg, possibly_locked_rw_data)
},
Request::FromImageCache => {
self.repaint(possibly_locked_rw_data)
},
Request::FromFontCache => {
let _rw_data = possibly_locked_rw_data.lock();
self.outstanding_web_fonts.fetch_sub(1, Ordering::SeqCst);
font_context::invalidate_font_caches();
self.script_chan.send(ConstellationControlMsg::WebFontLoaded(self.id)).unwrap();
true
},
}
}
/// Repaint the scene, without performing style matching. This is typically
/// used when an image arrives asynchronously and triggers a relayout and
/// repaint.
/// TODO: In the future we could detect if the image size hasn't changed
/// since last time and avoid performing a complete layout pass.
fn repaint<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) -> bool {
let mut rw_data = possibly_locked_rw_data.lock();
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
true
}
/// Receives and dispatches messages from other tasks.
fn handle_request_helper<'a, 'b>(&mut self,
request: Msg,
possibly_locked_rw_data: &mut RwData<'a, 'b>)
-> bool {
match request {
Msg::AddStylesheet(style_info) => {
self.handle_add_stylesheet(style_info, possibly_locked_rw_data)
}
Msg::SetQuirksMode => self.handle_set_quirks_mode(possibly_locked_rw_data),
Msg::GetRPC(response_chan) => {
response_chan.send(box LayoutRPCImpl(self.rw_data.clone()) as
Box<LayoutRPC + Send>).unwrap();
},
Msg::Reflow(data) => {
profile(time::ProfilerCategory::LayoutPerform,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| self.handle_reflow(&data, possibly_locked_rw_data));
},
Msg::TickAnimations => self.tick_all_animations(possibly_locked_rw_data),
Msg::ReflowWithNewlyLoadedWebFont => {
self.reflow_with_newly_loaded_web_font(possibly_locked_rw_data)
}
Msg::SetVisibleRects(new_visible_rects) => {
self.set_visible_rects(new_visible_rects, possibly_locked_rw_data);
}
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
}
Msg::CollectReports(reports_chan) => {
self.collect_reports(reports_chan, possibly_locked_rw_data);
},
Msg::GetCurrentEpoch(sender) => {
let _rw_data = possibly_locked_rw_data.lock();
sender.send(self.epoch).unwrap();
},
Msg::GetWebFontLoadState(sender) => {
let _rw_data = possibly_locked_rw_data.lock();
let outstanding_web_fonts = self.outstanding_web_fonts.load(Ordering::SeqCst);
sender.send(outstanding_web_fonts != 0).unwrap();
},
Msg::CreateLayoutTask(info) => {
self.create_layout_task(info)
}
Msg::SetFinalUrl(final_url) => {
let mut url_ref_cell = self.url.borrow_mut();
*url_ref_cell = final_url;
},
Msg::PrepareToExit(response_chan) => {
self.prepare_to_exit(response_chan);
return false
},
Msg::ExitNow => {
debug!("layout: ExitNow received");
self.exit_now();
return false
}
}
true
}
fn collect_reports<'a, 'b>(&self,
reports_chan: ReportsChan,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut reports = vec![];
// FIXME(njn): Just measuring the display tree for now.
let rw_data = possibly_locked_rw_data.lock();
let stacking_context = rw_data.stacking_context.as_ref();
let ref formatted_url = format!("url({})", *self.url.borrow());
reports.push(Report {
path: path![formatted_url, "layout-task", "display-list"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: stacking_context.map_or(0, |sc| sc.heap_size_of_children()),
});
// The LayoutTask has a context in TLS...
reports.push(Report {
path: path![formatted_url, "layout-task", "local-context"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: heap_size_of_local_context(),
});
// ... as do each of the LayoutWorkers, if present.
if let Some(ref traversal) = self.parallel_traversal {
let sizes = traversal.heap_size_of_tls(heap_size_of_local_context);
for (i, size) in sizes.iter().enumerate() {
reports.push(Report {
path: path![formatted_url,
format!("layout-worker-{}-local-context", i)],
kind: ReportKind::ExplicitJemallocHeapSize,
size: *size,
});
}
}
reports_chan.send(reports);
}
fn create_layout_task(&self, info: NewLayoutTaskInfo) {
LayoutTaskFactory::create(None::<&mut LayoutTask>,
info.id,
info.url.clone(),
info.is_parent,
info.layout_pair,
info.pipeline_port,
info.constellation_chan,
info.failure,
info.script_chan.clone(),
info.paint_chan.to::<LayoutToPaintMsg>(),
self.image_cache_task.clone(),
self.font_cache_task.clone(),
self.time_profiler_chan.clone(),
self.mem_profiler_chan.clone(),
info.layout_shutdown_chan,
info.content_process_shutdown_chan);
}
/// Enters a quiescent state in which no new messages will be processed until an `ExitNow` is
/// received. A pong is immediately sent on the given response channel.
fn prepare_to_exit(&mut self, response_chan: Sender<()>) {
response_chan.send(()).unwrap();
loop {
match self.port.recv().unwrap() {
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
}
Msg::ExitNow => {
debug!("layout task is exiting...");
self.exit_now();
break
}
Msg::CollectReports(_) => {
// Just ignore these messages at this point.
}
_ => {
panic!("layout: unexpected message received after `PrepareToExitMsg`")
}
}
}
}
/// Shuts down the layout task now. If there are any DOM nodes left, layout will now (safely)
/// crash.
fn exit_now<'a, 'b>(&mut self) {
if let Some(ref mut traversal) = self.parallel_traversal {
traversal.shutdown()
}
let (response_chan, response_port) = ipc::channel().unwrap();
self.paint_chan.send(LayoutToPaintMsg::Exit(response_chan)).unwrap();
response_port.recv().unwrap()
}
fn handle_add_stylesheet<'a, 'b>(&self,
stylesheet: Arc<Stylesheet>,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
// Find all font-face rules and notify the font cache of them.
// GWTODO: Need to handle unloading web fonts.
let rw_data = possibly_locked_rw_data.lock();
if stylesheet.is_effective_for_device(&rw_data.stylist.device) {
add_font_face_rules(&*stylesheet,
&rw_data.stylist.device,
&self.font_cache_task,
&self.font_cache_sender,
&self.outstanding_web_fonts);
}
possibly_locked_rw_data.block(rw_data);
}
/// Sets quirks mode for the document, causing the quirks mode stylesheet to be used.
fn handle_set_quirks_mode<'a, 'b>(&self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
rw_data.stylist.set_quirks_mode(true);
possibly_locked_rw_data.block(rw_data);
}
fn try_get_layout_root<'ln, N: LayoutNode<'ln>>(&self, node: N) -> Option<FlowRef> {
let mut layout_data_ref = node.mutate_layout_data();
let layout_data =
match layout_data_ref.as_mut() {
None => return None,
Some(layout_data) => layout_data,
};
let result = layout_data.data.flow_construction_result.swap_out();
let mut flow = match result {
ConstructionResult::Flow(mut flow, abs_descendants) => {
// Note: Assuming that the root has display 'static' (as per
// CSS Section 9.3.1). Otherwise, if it were absolutely
// positioned, it would return a reference to itself in
// `abs_descendants` and would lead to a circular reference.
// Set Root as CB for any remaining absolute descendants.
flow.set_absolute_descendants(abs_descendants);
flow
}
_ => return None,
};
flow_ref::deref_mut(&mut flow).mark_as_root();
Some(flow)
}
/// Performs layout constraint solving.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints(layout_root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints");
sequential::traverse_flow_tree_preorder(layout_root, shared_layout_context);
}
/// Performs layout constraint solving in parallel.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints_parallel(traversal: &mut WorkQueue<SharedLayoutContext, WorkQueueData>,
layout_root: &mut FlowRef,
profiler_metadata: Option<TimerMetadata>,
time_profiler_chan: time::ProfilerChan,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints_parallel");
// NOTE: this currently computes borders, so any pruning should separate that
// operation out.
parallel::traverse_flow_tree_preorder(layout_root,
profiler_metadata,
time_profiler_chan,
shared_layout_context,
traversal);
}
fn compute_abs_pos_and_build_display_list(&mut self,
data: &Reflow,
layout_root: &mut FlowRef,
shared_layout_context: &mut SharedLayoutContext,
rw_data: &mut LayoutTaskData) {
let writing_mode = flow::base(&**layout_root).writing_mode;
let (metadata, sender) = (self.profiler_metadata(), self.time_profiler_chan.clone());
profile(time::ProfilerCategory::LayoutDispListBuild,
metadata.clone(),
sender.clone(),
|| {
flow::mut_base(flow_ref::deref_mut(layout_root)).stacking_relative_position =
LogicalPoint::zero(writing_mode).to_physical(writing_mode,
self.viewport_size);
flow::mut_base(flow_ref::deref_mut(layout_root)).clip =
ClippingRegion::from_rect(&data.page_clip_rect);
match (&mut self.parallel_traversal, opts::get().parallel_display_list_building) {
(&mut Some(ref mut traversal), true) => {
parallel::build_display_list_for_subtree(layout_root,
metadata,
sender,
shared_layout_context,
traversal);
}
_ => {
sequential::build_display_list_for_subtree(layout_root,
shared_layout_context);
}
}
if data.goal == ReflowGoal::ForDisplay {
debug!("Done building display list.");
let root_background_color = get_root_flow_background_color(
flow_ref::deref_mut(layout_root));
let root_size = {
let root_flow = flow::base(&**layout_root);
if rw_data.stylist.viewport_constraints().is_some() {
root_flow.position.size.to_physical(root_flow.writing_mode)
} else {
root_flow.overflow.size
}
};
let mut display_list = box DisplayList::new();
display_list.append_from(&mut flow::mut_base(flow_ref::deref_mut(layout_root))
.display_list_building_result);
let origin = Rect::new(Point2D::new(Au(0), Au(0)), root_size);
let stacking_context = Arc::new(StackingContext::new(display_list,
&origin,
&origin,
0,
filter::T::new(Vec::new()),
mix_blend_mode::T::normal,
Matrix4::identity(),
Matrix4::identity(),
true,
false,
None));
if opts::get().dump_display_list {
stacking_context.print("DisplayList".to_owned());
}
if opts::get().dump_display_list_json {
println!("{}", serde_json::to_string_pretty(&stacking_context).unwrap());
}
rw_data.stacking_context = Some(stacking_context.clone());
let layer_info = LayerInfo::new(layout_root.layer_id(),
ScrollPolicy::Scrollable,
None);
let paint_layer = PaintLayer::new_with_stacking_context(layer_info,
stacking_context,
root_background_color);
debug!("Layout done!");
self.epoch.next();
self.paint_chan
.send(LayoutToPaintMsg::PaintInit(self.epoch, paint_layer))
.unwrap();
}
});
}
/// The high-level routine that performs layout tasks.
fn handle_reflow<'a, 'b>(&mut self,
data: &ScriptReflow,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let document = unsafe { ServoLayoutNode::new(&data.document) };
let document = document.as_document().unwrap();
debug!("layout: received layout request for: {}", self.url.serialize());
let mut rw_data = possibly_locked_rw_data.lock();
let node: ServoLayoutNode = match document.root_node() {
None => {
// Since we cannot compute anything, give spec-required placeholders.
debug!("layout: No root node: bailing");
match data.query_type {
ReflowQueryType::ContentBoxQuery(_) => {
rw_data.content_box_response = Rect::zero();
},
ReflowQueryType::ContentBoxesQuery(_) => {
rw_data.content_boxes_response = Vec::new();
},
ReflowQueryType::NodeGeometryQuery(_) => {
rw_data.client_rect_response = Rect::zero();
},
ReflowQueryType::ResolvedStyleQuery(_, _, _) => {
rw_data.resolved_style_response = None;
},
ReflowQueryType::OffsetParentQuery(_) => {
rw_data.offset_parent_response = OffsetParentResponse::empty();
},
ReflowQueryType::NoQuery => {}
}
return;
},
Some(x) => x,
};
debug!("layout: received layout request for: {}",
self.url.borrow().serialize());
if log_enabled!(log::LogLevel::Debug) {
node.dump();
}
let stylesheets: Vec<&Stylesheet> = data.document_stylesheets.iter().map(|entry| &**entry)
.collect();
let stylesheets_changed = data.stylesheets_changed;
let initial_viewport = data.window_size.initial_viewport;
let old_viewport_size = self.viewport_size;
let current_screen_size = Size2D::new(Au::from_f32_px(initial_viewport.width.get()),
Au::from_f32_px(initial_viewport.height.get()));
// Calculate the actual viewport as per DEVICE-ADAPT § 6
let device = Device::new(MediaType::Screen, initial_viewport);
rw_data.stylist.set_device(device, &stylesheets);
let constraints = rw_data.stylist.viewport_constraints().clone();
self.viewport_size = match constraints {
Some(ref constraints) => {
debug!("Viewport constraints: {:?}", constraints);
// other rules are evaluated against the actual viewport
Size2D::new(Au::from_f32_px(constraints.size.width.get()),
Au::from_f32_px(constraints.size.height.get()))
}
None => current_screen_size,
};
// Handle conditions where the entire flow tree is invalid.
let viewport_size_changed = self.viewport_size != old_viewport_size;
if viewport_size_changed {
if let Some(constraints) = constraints {
// let the constellation know about the viewport constraints
let ConstellationChan(ref constellation_chan) = rw_data.constellation_chan;
constellation_chan.send(ConstellationMsg::ViewportConstrained(
self.id, constraints)).unwrap();
}
}
// If the entire flow tree is invalid, then it will be reflowed anyhow.
let needs_dirtying = rw_data.stylist.update(&stylesheets, stylesheets_changed);
let needs_reflow = viewport_size_changed && !needs_dirtying;
unsafe {
if needs_dirtying {
LayoutTask::dirty_all_nodes(node);
}
}
if needs_reflow {
if let Some(mut flow) = self.try_get_layout_root(node) {
LayoutTask::reflow_all_nodes(flow_ref::deref_mut(&mut flow));
}
}
let modified_elements = document.drain_modified_elements();
if !needs_dirtying {
for (el, snapshot) in modified_elements {
let hint = rw_data.stylist.compute_restyle_hint(&el, &snapshot, el.get_state());
el.note_restyle_hint(hint);
}
}
// Create a layout context for use throughout the following passes.
let mut shared_layout_context = self.build_shared_layout_context(&*rw_data,
viewport_size_changed,
&self.url.borrow(),
data.reflow_info.goal);
if node.is_dirty() || node.has_dirty_descendants() {
// Recalculate CSS styles and rebuild flows and fragments.
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
// Perform CSS selector matching and flow construction.
match self.parallel_traversal {
None => {
sequential::traverse_dom_preorder(node, &shared_layout_context);
}
Some(ref mut traversal) => {
parallel::traverse_dom_preorder(node, &shared_layout_context, traversal);
}
}
});
// Retrieve the (possibly rebuilt) root flow.
self.root_flow = self.try_get_layout_root(node);
}
// Send new canvas renderers to the paint task
while let Ok((layer_id, renderer)) = self.canvas_layers_receiver.try_recv() {
// Just send if there's an actual renderer
self.paint_chan.send(LayoutToPaintMsg::CanvasLayer(layer_id, renderer)).unwrap();
}
// Perform post-style recalculation layout passes.
self.perform_post_style_recalc_layout_passes(&data.reflow_info,
&mut rw_data,
&mut shared_layout_context);
if let Some(mut root_flow) = self.root_flow.clone() {
match data.query_type {
ReflowQueryType::ContentBoxQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.content_box_response = process_content_box_request(node, &mut root_flow);
},
ReflowQueryType::ContentBoxesQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.content_boxes_response = process_content_boxes_request(node, &mut root_flow);
},
ReflowQueryType::NodeGeometryQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.client_rect_response = process_node_geometry_request(node, &mut root_flow);
},
ReflowQueryType::ResolvedStyleQuery(node, ref pseudo, ref property) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.resolved_style_response =
process_resolved_style_request(node, pseudo, property, &mut root_flow);
},
ReflowQueryType::OffsetParentQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.offset_parent_response = process_offset_parent_query(node, &mut root_flow);
},
ReflowQueryType::NoQuery => {}
}
}
}
fn set_visible_rects<'a, 'b>(&mut self,
new_visible_rects: Vec<(LayerId, Rect<Au>)>,
possibly_locked_rw_data: &mut RwData<'a, 'b>)
-> bool {
let mut rw_data = possibly_locked_rw_data.lock();
// First, determine if we need to regenerate the display lists. This will happen if the
// layers have moved more than `DISPLAY_PORT_THRESHOLD_SIZE_FACTOR` away from their last
// positions.
let mut must_regenerate_display_lists = false;
let mut old_visible_rects = HashMap::with_hash_state(Default::default());
let inflation_amount =
Size2D::new(self.viewport_size.width * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR,
self.viewport_size.height * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR);
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
match self.visible_rects.get(layer_id) {
None => {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
Some(old_visible_rect) => {
old_visible_rects.insert(*layer_id, *old_visible_rect);
if !old_visible_rect.inflate(inflation_amount.width, inflation_amount.height)
.intersects(new_visible_rect) {
must_regenerate_display_lists = true;
}
}
}
}
if !must_regenerate_display_lists {
// Update `visible_rects` in case there are new layers that were discovered.
self.visible_rects = Arc::new(old_visible_rects);
return true
}
debug!("regenerating display lists!");
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
self.visible_rects = Arc::new(old_visible_rects);
// Regenerate the display lists.
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
url_clone,
reflow_info.goal);
self.perform_post_main_layout_passes(&reflow_info, &mut *rw_data, &mut layout_context);
true
}
fn tick_all_animations<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
self.tick_animations(&mut rw_data);
self.script_chan
.send(ConstellationControlMsg::TickAllAnimations(self.id))
.unwrap();
}
pub fn tick_animations(&mut self, rw_data: &mut LayoutTaskData) {
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
if let Some(mut root_flow) = self.root_flow.clone() {
// Perform an abbreviated style recalc that operates without access to the DOM.
let animations = self.running_animations.read().unwrap();
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
animation::recalc_style_for_animations(flow_ref::deref_mut(&mut root_flow),
&*animations)
});
}
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
}
fn reflow_with_newly_loaded_web_font<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
font_context::invalidate_font_caches();
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url,
reflow_info.goal);
// No need to do a style recalc here.
if self.root_flow.is_none() {
return
}
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
}
fn perform_post_style_recalc_layout_passes(&mut self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
if let Some(mut root_flow) = self.root_flow.clone() {
// Kick off animations if any were triggered, expire completed ones.
animation::update_animation_state(&self.constellation_chan,
&mut *self.running_animations.write().unwrap(),
&mut *self.expired_animations.write().unwrap(),
&self.new_animations_receiver,
self.id);
profile(time::ProfilerCategory::LayoutRestyleDamagePropagation,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
if opts::get().nonincremental_layout ||
flow_ref::deref_mut(&mut root_flow).compute_layout_damage()
.contains(REFLOW_ENTIRE_DOCUMENT) {
flow_ref::deref_mut(&mut root_flow).reflow_entire_document()
}
});
if opts::get().trace_layout {
layout_debug::begin_trace(root_flow.clone());
}
// Resolve generated content.
profile(time::ProfilerCategory::LayoutGeneratedContent,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| sequential::resolve_generated_content(&mut root_flow, &layout_context));
// Perform the primary layout passes over the flow tree to compute the locations of all
// the boxes.
profile(time::ProfilerCategory::LayoutMain,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
let profiler_metadata = self.profiler_metadata();
match self.parallel_traversal {
None => {
// Sequential mode.
LayoutTask::solve_constraints(&mut root_flow, &layout_context)
}
Some(ref mut parallel) => {
// Parallel mode.
LayoutTask::solve_constraints_parallel(parallel,
&mut root_flow,
profiler_metadata,
self.time_profiler_chan.clone(),
&*layout_context);
}
}
});
self.perform_post_main_layout_passes(data, rw_data, layout_context);
}
}
fn perform_post_main_layout_passes(&mut self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
// Build the display list if necessary, and send it to the painter.
if let Some(mut root_flow) = self.root_flow.clone() {
self.compute_abs_pos_and_build_display_list(data,
&mut root_flow,
&mut *layout_context,
rw_data);
self.first_reflow = false;
if opts::get().trace_layout {
layout_debug::end_trace();
}
if opts::get().dump_flow_tree {
root_flow.print("Post layout flow tree".to_owned());
}
self.generation += 1;
}
}
unsafe fn dirty_all_nodes<'ln, N: LayoutNode<'ln>>(node: N) {
for node in node.traverse_preorder() {
// TODO(cgaebel): mark nodes which are sensitive to media queries as
// "changed":
// > node.set_changed(true);
node.set_dirty(true);
node.set_dirty_descendants(true);
}
}
fn reflow_all_nodes(flow: &mut Flow) {
debug!("reflowing all nodes!");
flow::mut_base(flow).restyle_damage.insert(REFLOW | REPAINT);
for child in flow::child_iter(flow) {
LayoutTask::reflow_all_nodes(child);
}
}
/// Handles a message to destroy layout data. Layout data must be destroyed on *this* task
/// because the struct type is transmuted to a different type on the script side.
unsafe fn handle_reap_layout_data(&self, layout_data: LayoutData) {
let _: LayoutDataWrapper = transmute(layout_data);
}
/// Returns profiling information which is passed to the time profiler.
fn profiler_metadata(&self) -> Option<TimerMetadata> {
Some(TimerMetadata {
url: self.url.serialize(),
iframe: if self.is_iframe {
TimerMetadataFrameType::IFrame
} else {
TimerMetadataFrameType::RootWindow
},
incremental: if self.first_reflow {
TimerMetadataReflowType::FirstReflow
} else {
TimerMetadataReflowType::Incremental
},
})
}
}
// The default computed value for background-color is transparent (see
// http://dev.w3.org/csswg/css-backgrounds/#background-color). However, we
// need to propagate the background color from the root HTML/Body
// element (http://dev.w3.org/csswg/css-backgrounds/#special-backgrounds) if
// it is non-transparent. The phrase in the spec "If the canvas background
// is not opaque, what shows through is UA-dependent." is handled by rust-layers
// clearing the frame buffer to white. This ensures that setting a background
// color on an iframe element, while the iframe content itself has a default
// transparent background color is handled correctly.
fn get_root_flow_background_color(flow: &mut Flow) -> AzColor {
if !flow.is_block_like() {
return color::transparent()
}
let block_flow = flow.as_mut_block();
let kid = match block_flow.base.children.iter_mut().next() {
None => return color::transparent(),
Some(kid) => kid,
};
if !kid.is_block_like() {
return color::transparent()
}
let kid_block_flow = kid.as_block();
kid_block_flow.fragment
.style
.resolve_color(kid_block_flow.fragment.style.get_background().background_color)
.to_gfx_color()
}
Fix build errors after rebasing and address review comments
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The layout task. Performs layout on the DOM, builds display lists and sends them to be
//! painted.
#![allow(unsafe_code)]
use animation;
use app_units::Au;
use azure::azure::AzColor;
use canvas_traits::CanvasMsg;
use construct::ConstructionResult;
use context::{SharedLayoutContext, StylistWrapper, heap_size_of_local_context};
use data::LayoutDataWrapper;
use display_list_builder::ToGfxColor;
use euclid::Matrix4;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::Size2D;
use flow::{self, Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils};
use flow_ref::{self, FlowRef};
use fnv::FnvHasher;
use gfx::display_list::{ClippingRegion, DisplayList, LayerInfo, OpaqueNode, StackingContext};
use gfx::font_cache_task::FontCacheTask;
use gfx::font_context;
use gfx::paint_task::{LayoutToPaintMsg, PaintLayer};
use gfx_traits::color;
use incremental::{LayoutDamageComputation, REFLOW, REFLOW_ENTIRE_DOCUMENT, REPAINT};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use layout_debug;
use layout_traits::LayoutTaskFactory;
use log;
use msg::compositor_msg::{Epoch, LayerId, ScrollPolicy};
use msg::constellation_msg::ScriptMsg as ConstellationMsg;
use msg::constellation_msg::{ConstellationChan, Failure, PipelineId};
use net_traits::image_cache_task::{ImageCacheChan, ImageCacheResult, ImageCacheTask};
use parallel::{self, WorkQueueData};
use profile_traits::mem::{self, Report, ReportKind, ReportsChan};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
use profile_traits::time::{self, TimerMetadata, profile};
use query::{LayoutRPCImpl, process_content_box_request, process_content_boxes_request};
use query::{process_node_geometry_request, process_offset_parent_query, process_resolved_style_request};
use script::dom::node::LayoutData;
use script::layout_interface::Animation;
use script::layout_interface::{LayoutRPC, OffsetParentResponse};
use script::layout_interface::{Msg, NewLayoutTaskInfo, Reflow, ReflowGoal, ReflowQueryType};
use script::layout_interface::{ScriptLayoutChan, ScriptReflow};
use script::reporter::CSSErrorReporter;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, OpaqueScriptLayoutChannel};
use sequential;
use serde_json;
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::mem::transmute;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::sync::{Arc, Mutex, MutexGuard, RwLock};
use style::computed_values::{filter, mix_blend_mode};
use style::media_queries::{Device, MediaType};
use style::selector_matching::{Stylist, USER_OR_USER_AGENT_STYLESHEETS};
use style::stylesheets::{CSSRuleIteratorExt, Stylesheet};
use style_traits::ParseErrorReporter;
use url::Url;
use util::geometry::MAX_RECT;
use util::ipc::OptionalIpcSender;
use util::logical_geometry::LogicalPoint;
use util::mem::HeapSizeOf;
use util::opts;
use util::task;
use util::task_state;
use util::workqueue::WorkQueue;
use wrapper::{LayoutDocument, LayoutElement, LayoutNode};
use wrapper::{ServoLayoutNode, ThreadSafeLayoutNode};
/// The number of screens of data we're allowed to generate display lists for in each direction.
pub const DISPLAY_PORT_SIZE_FACTOR: i32 = 8;
/// The number of screens we have to traverse before we decide to generate new display lists.
const DISPLAY_PORT_THRESHOLD_SIZE_FACTOR: i32 = 4;
/// Mutable data belonging to the LayoutTask.
///
/// This needs to be protected by a mutex so we can do fast RPCs.
pub struct LayoutTaskData {
/// The channel on which messages can be sent to the constellation.
pub constellation_chan: ConstellationChan<ConstellationMsg>,
/// The root stacking context.
pub stacking_context: Option<Arc<StackingContext>>,
/// Performs CSS selector matching and style resolution.
pub stylist: Box<Stylist>,
/// A queued response for the union of the content boxes of a node.
pub content_box_response: Rect<Au>,
/// A queued response for the content boxes of a node.
pub content_boxes_response: Vec<Rect<Au>>,
/// A queued response for the client {top, left, width, height} of a node in pixels.
pub client_rect_response: Rect<i32>,
/// A queued response for the resolved style property of an element.
pub resolved_style_response: Option<String>,
/// A queued response for the offset parent/rect of a node.
pub offset_parent_response: OffsetParentResponse,
}
/// Information needed by the layout task.
pub struct LayoutTask {
/// The ID of the pipeline that we belong to.
id: PipelineId,
/// The URL of the pipeline that we belong to.
url: RefCell<Url>,
/// Is the current reflow of an iframe, as opposed to a root window?
is_iframe: bool,
/// The port on which we receive messages from the script task.
port: Receiver<Msg>,
/// The port on which we receive messages from the constellation.
pipeline_port: Receiver<LayoutControlMsg>,
/// The port on which we receive messages from the image cache
image_cache_receiver: Receiver<ImageCacheResult>,
/// The channel on which the image cache can send messages to ourself.
image_cache_sender: ImageCacheChan,
/// The port on which we receive messages from the font cache task.
font_cache_receiver: Receiver<()>,
/// The channel on which the font cache can send messages to us.
font_cache_sender: IpcSender<()>,
/// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan<ConstellationMsg>,
/// The channel on which messages can be sent to the script task.
script_chan: IpcSender<ConstellationControlMsg>,
/// The channel on which messages can be sent to the painting task.
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
/// The channel on which messages can be sent to the time profiler.
time_profiler_chan: time::ProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
mem_profiler_chan: mem::ProfilerChan,
/// The channel on which messages can be sent to the image cache.
image_cache_task: ImageCacheTask,
/// Public interface to the font cache task.
font_cache_task: FontCacheTask,
/// Is this the first reflow in this LayoutTask?
first_reflow: bool,
/// To receive a canvas renderer associated to a layer, this message is propagated
/// to the paint chan
canvas_layers_receiver: Receiver<(LayerId, IpcSender<CanvasMsg>)>,
canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>,
/// The workers that we use for parallel operation.
parallel_traversal: Option<WorkQueue<SharedLayoutContext, WorkQueueData>>,
/// Starts at zero, and increased by one every time a layout completes.
/// This can be used to easily check for invalid stale data.
generation: u32,
/// A channel on which new animations that have been triggered by style recalculation can be
/// sent.
new_animations_sender: Sender<Animation>,
/// Receives newly-discovered animations.
new_animations_receiver: Receiver<Animation>,
/// The number of Web fonts that have been requested but not yet loaded.
outstanding_web_fonts: Arc<AtomicUsize>,
/// The root of the flow tree.
root_flow: Option<FlowRef>,
/// The position and size of the visible rect for each layer. We do not build display lists
/// for any areas more than `DISPLAY_PORT_SIZE_FACTOR` screens away from this area.
visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>,
/// The list of currently-running animations.
running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// A counter for epoch messages
epoch: Epoch,
/// The size of the viewport. This may be different from the size of the screen due to viewport
/// constraints.
viewport_size: Size2D<Au>,
/// A mutex to allow for fast, read-only RPC of layout's internal data
/// structures, while still letting the LayoutTask modify them.
///
/// All the other elements of this struct are read-only.
rw_data: Arc<Mutex<LayoutTaskData>>,
/// The CSS error reporter for all CSS loaded in this layout thread
error_reporter: CSSErrorReporter,
}
impl LayoutTaskFactory for LayoutTask {
/// Spawns a new layout task.
fn create(_phantom: Option<&mut LayoutTask>,
id: PipelineId,
url: Url,
is_iframe: bool,
chan: OpaqueScriptLayoutChannel,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan<ConstellationMsg>,
failure_msg: Failure,
script_chan: IpcSender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
shutdown_chan: IpcSender<()>,
content_process_shutdown_chan: IpcSender<()>) {
let ConstellationChan(con_chan) = constellation_chan.clone();
task::spawn_named_with_send_on_failure(format!("LayoutTask {:?}", id),
task_state::LAYOUT,
move || {
{ // Ensures layout task is destroyed before we send shutdown message
let sender = chan.sender();
let layout = LayoutTask::new(id,
url,
is_iframe,
chan.receiver(),
pipeline_port,
constellation_chan,
script_chan,
paint_chan,
image_cache_task,
font_cache_task,
time_profiler_chan,
mem_profiler_chan.clone());
let reporter_name = format!("layout-reporter-{}", id);
mem_profiler_chan.run_with_memory_reporting(|| {
layout.start();
}, reporter_name, sender, Msg::CollectReports);
}
let _ = shutdown_chan.send(());
let _ = content_process_shutdown_chan.send(());
}, ConstellationMsg::Failure(failure_msg), con_chan);
}
}
/// The `LayoutTask` `rw_data` lock must remain locked until the first reflow,
/// as RPC calls don't make sense until then. Use this in combination with
/// `LayoutTask::lock_rw_data` and `LayoutTask::return_rw_data`.
pub enum RWGuard<'a> {
/// If the lock was previously held, from when the task started.
Held(MutexGuard<'a, LayoutTaskData>),
/// If the lock was just used, and has been returned since there has been
/// a reflow already.
Used(MutexGuard<'a, LayoutTaskData>),
}
impl<'a> Deref for RWGuard<'a> {
type Target = LayoutTaskData;
fn deref(&self) -> &LayoutTaskData {
match *self {
RWGuard::Held(ref x) => &**x,
RWGuard::Used(ref x) => &**x,
}
}
}
impl<'a> DerefMut for RWGuard<'a> {
fn deref_mut(&mut self) -> &mut LayoutTaskData {
match *self {
RWGuard::Held(ref mut x) => &mut **x,
RWGuard::Used(ref mut x) => &mut **x,
}
}
}
struct RwData<'a, 'b: 'a> {
rw_data: &'b Arc<Mutex<LayoutTaskData>>,
possibly_locked_rw_data: &'a mut Option<MutexGuard<'b, LayoutTaskData>>,
}
impl<'a, 'b: 'a> RwData<'a, 'b> {
/// If no reflow has happened yet, this will just return the lock in
/// `possibly_locked_rw_data`. Otherwise, it will acquire the `rw_data` lock.
///
/// If you do not wish RPCs to remain blocked, just drop the `RWGuard`
/// returned from this function. If you _do_ wish for them to remain blocked,
/// use `block`.
fn lock(&mut self) -> RWGuard<'b> {
match self.possibly_locked_rw_data.take() {
None => RWGuard::Used(self.rw_data.lock().unwrap()),
Some(x) => RWGuard::Held(x),
}
}
/// If no reflow has ever been triggered, this will keep the lock, locked
/// (and saved in `possibly_locked_rw_data`). If it has been, the lock will
/// be unlocked.
fn block(&mut self, rw_data: RWGuard<'b>) {
match rw_data {
RWGuard::Used(x) => drop(x),
RWGuard::Held(x) => *self.possibly_locked_rw_data = Some(x),
}
}
}
fn add_font_face_rules(stylesheet: &Stylesheet,
device: &Device,
font_cache_task: &FontCacheTask,
font_cache_sender: &IpcSender<()>,
outstanding_web_fonts_counter: &Arc<AtomicUsize>) {
for font_face in stylesheet.effective_rules(&device).font_face() {
for source in &font_face.sources {
if opts::get().load_webfonts_synchronously {
let (sender, receiver) = ipc::channel().unwrap();
font_cache_task.add_web_font(font_face.family.clone(),
(*source).clone(),
sender);
receiver.recv().unwrap();
} else {
outstanding_web_fonts_counter.fetch_add(1, Ordering::SeqCst);
font_cache_task.add_web_font(font_face.family.clone(),
(*source).clone(),
(*font_cache_sender).clone());
}
}
}
}
impl LayoutTask {
/// Creates a new `LayoutTask` structure.
fn new(id: PipelineId,
url: Url,
is_iframe: bool,
port: Receiver<Msg>,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan<ConstellationMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan)
-> LayoutTask {
let device = Device::new(
MediaType::Screen,
opts::get().initial_window_size.as_f32() * ScaleFactor::new(1.0));
let parallel_traversal = if opts::get().layout_threads != 1 {
Some(WorkQueue::new("LayoutWorker", task_state::LAYOUT,
opts::get().layout_threads))
} else {
None
};
// Create the channel on which new animations can be sent.
let (new_animations_sender, new_animations_receiver) = channel();
let (canvas_layers_sender, canvas_layers_receiver) = channel();
// Proxy IPC messages from the pipeline to the layout thread.
let pipeline_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(pipeline_port);
// Ask the router to proxy IPC messages from the image cache task to the layout thread.
let (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap();
let image_cache_receiver =
ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_image_cache_receiver);
// Ask the router to proxy IPC messages from the font cache task to the layout thread.
let (ipc_font_cache_sender, ipc_font_cache_receiver) = ipc::channel().unwrap();
let font_cache_receiver =
ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_font_cache_receiver);
let stylist = box Stylist::new(device);
let outstanding_web_fonts_counter = Arc::new(AtomicUsize::new(0));
for stylesheet in &*USER_OR_USER_AGENT_STYLESHEETS {
add_font_face_rules(stylesheet,
&stylist.device,
&font_cache_task,
&ipc_font_cache_sender,
&outstanding_web_fonts_counter);
}
LayoutTask {
id: id,
url: RefCell::new(url),
is_iframe: is_iframe,
port: port,
pipeline_port: pipeline_receiver,
script_chan: script_chan,
constellation_chan: constellation_chan.clone(),
paint_chan: paint_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
image_cache_task: image_cache_task,
font_cache_task: font_cache_task,
first_reflow: true,
image_cache_receiver: image_cache_receiver,
image_cache_sender: ImageCacheChan(ipc_image_cache_sender),
font_cache_receiver: font_cache_receiver,
font_cache_sender: ipc_font_cache_sender,
canvas_layers_receiver: canvas_layers_receiver,
canvas_layers_sender: canvas_layers_sender,
parallel_traversal: parallel_traversal,
generation: 0,
new_animations_sender: new_animations_sender,
new_animations_receiver: new_animations_receiver,
outstanding_web_fonts: outstanding_web_fonts_counter,
root_flow: None,
visible_rects: Arc::new(HashMap::with_hash_state(Default::default())),
running_animations: Arc::new(RwLock::new(HashMap::new())),
expired_animations: Arc::new(RwLock::new(HashMap::new())),
epoch: Epoch(0),
viewport_size: Size2D::new(Au(0), Au(0)),
rw_data: Arc::new(Mutex::new(
LayoutTaskData {
constellation_chan: constellation_chan,
stacking_context: None,
stylist: stylist,
content_box_response: Rect::zero(),
content_boxes_response: Vec::new(),
client_rect_response: Rect::zero(),
resolved_style_response: None,
offset_parent_response: OffsetParentResponse::empty(),
})),
error_reporter: CSSErrorReporter,
}
}
/// Starts listening on the port.
fn start(mut self) {
let rw_data = self.rw_data.clone();
let mut possibly_locked_rw_data = Some(rw_data.lock().unwrap());
let mut rw_data = RwData {
rw_data: &rw_data,
possibly_locked_rw_data: &mut possibly_locked_rw_data,
};
while self.handle_request(&mut rw_data) {
// Loop indefinitely.
}
}
// Create a layout context for use in building display lists, hit testing, &c.
fn build_shared_layout_context(&self,
rw_data: &LayoutTaskData,
screen_size_changed: bool,
url: &Url,
goal: ReflowGoal)
-> SharedLayoutContext {
SharedLayoutContext {
image_cache_task: self.image_cache_task.clone(),
image_cache_sender: Mutex::new(self.image_cache_sender.clone()),
viewport_size: self.viewport_size.clone(),
screen_size_changed: screen_size_changed,
font_cache_task: Mutex::new(self.font_cache_task.clone()),
canvas_layers_sender: Mutex::new(self.canvas_layers_sender.clone()),
stylist: StylistWrapper(&*rw_data.stylist),
url: (*url).clone(),
visible_rects: self.visible_rects.clone(),
generation: self.generation,
new_animations_sender: Mutex::new(self.new_animations_sender.clone()),
goal: goal,
running_animations: self.running_animations.clone(),
expired_animations: self.expired_animations.clone(),
error_reporter: self.error_reporter.clone(),
}
}
/// Receives and dispatches messages from the script and constellation tasks
fn handle_request<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) -> bool {
enum Request {
FromPipeline(LayoutControlMsg),
FromScript(Msg),
FromImageCache,
FromFontCache,
}
let request = {
let port_from_script = &self.port;
let port_from_pipeline = &self.pipeline_port;
let port_from_image_cache = &self.image_cache_receiver;
let port_from_font_cache = &self.font_cache_receiver;
select! {
msg = port_from_pipeline.recv() => {
Request::FromPipeline(msg.unwrap())
},
msg = port_from_script.recv() => {
Request::FromScript(msg.unwrap())
},
msg = port_from_image_cache.recv() => {
msg.unwrap();
Request::FromImageCache
},
msg = port_from_font_cache.recv() => {
msg.unwrap();
Request::FromFontCache
}
}
};
match request {
Request::FromPipeline(LayoutControlMsg::SetVisibleRects(new_visible_rects)) => {
self.handle_request_helper(Msg::SetVisibleRects(new_visible_rects),
possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::TickAnimations) => {
self.handle_request_helper(Msg::TickAnimations, possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::GetCurrentEpoch(sender)) => {
self.handle_request_helper(Msg::GetCurrentEpoch(sender), possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::GetWebFontLoadState(sender)) => {
self.handle_request_helper(Msg::GetWebFontLoadState(sender),
possibly_locked_rw_data)
},
Request::FromPipeline(LayoutControlMsg::ExitNow) => {
self.handle_request_helper(Msg::ExitNow, possibly_locked_rw_data)
},
Request::FromScript(msg) => {
self.handle_request_helper(msg, possibly_locked_rw_data)
},
Request::FromImageCache => {
self.repaint(possibly_locked_rw_data)
},
Request::FromFontCache => {
let _rw_data = possibly_locked_rw_data.lock();
self.outstanding_web_fonts.fetch_sub(1, Ordering::SeqCst);
font_context::invalidate_font_caches();
self.script_chan.send(ConstellationControlMsg::WebFontLoaded(self.id)).unwrap();
true
},
}
}
/// Repaint the scene, without performing style matching. This is typically
/// used when an image arrives asynchronously and triggers a relayout and
/// repaint.
/// TODO: In the future we could detect if the image size hasn't changed
/// since last time and avoid performing a complete layout pass.
fn repaint<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) -> bool {
let mut rw_data = possibly_locked_rw_data.lock();
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
true
}
/// Receives and dispatches messages from other tasks.
fn handle_request_helper<'a, 'b>(&mut self,
request: Msg,
possibly_locked_rw_data: &mut RwData<'a, 'b>)
-> bool {
match request {
Msg::AddStylesheet(style_info) => {
self.handle_add_stylesheet(style_info, possibly_locked_rw_data)
}
Msg::SetQuirksMode => self.handle_set_quirks_mode(possibly_locked_rw_data),
Msg::GetRPC(response_chan) => {
response_chan.send(box LayoutRPCImpl(self.rw_data.clone()) as
Box<LayoutRPC + Send>).unwrap();
},
Msg::Reflow(data) => {
profile(time::ProfilerCategory::LayoutPerform,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| self.handle_reflow(&data, possibly_locked_rw_data));
},
Msg::TickAnimations => self.tick_all_animations(possibly_locked_rw_data),
Msg::ReflowWithNewlyLoadedWebFont => {
self.reflow_with_newly_loaded_web_font(possibly_locked_rw_data)
}
Msg::SetVisibleRects(new_visible_rects) => {
self.set_visible_rects(new_visible_rects, possibly_locked_rw_data);
}
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
}
Msg::CollectReports(reports_chan) => {
self.collect_reports(reports_chan, possibly_locked_rw_data);
},
Msg::GetCurrentEpoch(sender) => {
let _rw_data = possibly_locked_rw_data.lock();
sender.send(self.epoch).unwrap();
},
Msg::GetWebFontLoadState(sender) => {
let _rw_data = possibly_locked_rw_data.lock();
let outstanding_web_fonts = self.outstanding_web_fonts.load(Ordering::SeqCst);
sender.send(outstanding_web_fonts != 0).unwrap();
},
Msg::CreateLayoutTask(info) => {
self.create_layout_task(info)
}
Msg::SetFinalUrl(final_url) => {
*self.url.borrow_mut() = final_url;
},
Msg::PrepareToExit(response_chan) => {
self.prepare_to_exit(response_chan);
return false
},
Msg::ExitNow => {
debug!("layout: ExitNow received");
self.exit_now();
return false
}
}
true
}
fn collect_reports<'a, 'b>(&self,
reports_chan: ReportsChan,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut reports = vec![];
// FIXME(njn): Just measuring the display tree for now.
let rw_data = possibly_locked_rw_data.lock();
let stacking_context = rw_data.stacking_context.as_ref();
let ref formatted_url = format!("url({})", *self.url.borrow());
reports.push(Report {
path: path![formatted_url, "layout-task", "display-list"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: stacking_context.map_or(0, |sc| sc.heap_size_of_children()),
});
// The LayoutTask has a context in TLS...
reports.push(Report {
path: path![formatted_url, "layout-task", "local-context"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: heap_size_of_local_context(),
});
// ... as do each of the LayoutWorkers, if present.
if let Some(ref traversal) = self.parallel_traversal {
let sizes = traversal.heap_size_of_tls(heap_size_of_local_context);
for (i, size) in sizes.iter().enumerate() {
reports.push(Report {
path: path![formatted_url,
format!("layout-worker-{}-local-context", i)],
kind: ReportKind::ExplicitJemallocHeapSize,
size: *size,
});
}
}
reports_chan.send(reports);
}
fn create_layout_task(&self, info: NewLayoutTaskInfo) {
LayoutTaskFactory::create(None::<&mut LayoutTask>,
info.id,
info.url.clone(),
info.is_parent,
info.layout_pair,
info.pipeline_port,
info.constellation_chan,
info.failure,
info.script_chan.clone(),
info.paint_chan.to::<LayoutToPaintMsg>(),
self.image_cache_task.clone(),
self.font_cache_task.clone(),
self.time_profiler_chan.clone(),
self.mem_profiler_chan.clone(),
info.layout_shutdown_chan,
info.content_process_shutdown_chan);
}
/// Enters a quiescent state in which no new messages will be processed until an `ExitNow` is
/// received. A pong is immediately sent on the given response channel.
fn prepare_to_exit(&mut self, response_chan: Sender<()>) {
response_chan.send(()).unwrap();
loop {
match self.port.recv().unwrap() {
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
}
Msg::ExitNow => {
debug!("layout task is exiting...");
self.exit_now();
break
}
Msg::CollectReports(_) => {
// Just ignore these messages at this point.
}
_ => {
panic!("layout: unexpected message received after `PrepareToExitMsg`")
}
}
}
}
/// Shuts down the layout task now. If there are any DOM nodes left, layout will now (safely)
/// crash.
fn exit_now<'a, 'b>(&mut self) {
if let Some(ref mut traversal) = self.parallel_traversal {
traversal.shutdown()
}
let (response_chan, response_port) = ipc::channel().unwrap();
self.paint_chan.send(LayoutToPaintMsg::Exit(response_chan)).unwrap();
response_port.recv().unwrap()
}
fn handle_add_stylesheet<'a, 'b>(&self,
stylesheet: Arc<Stylesheet>,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
// Find all font-face rules and notify the font cache of them.
// GWTODO: Need to handle unloading web fonts.
let rw_data = possibly_locked_rw_data.lock();
if stylesheet.is_effective_for_device(&rw_data.stylist.device) {
add_font_face_rules(&*stylesheet,
&rw_data.stylist.device,
&self.font_cache_task,
&self.font_cache_sender,
&self.outstanding_web_fonts);
}
possibly_locked_rw_data.block(rw_data);
}
/// Sets quirks mode for the document, causing the quirks mode stylesheet to be used.
fn handle_set_quirks_mode<'a, 'b>(&self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
rw_data.stylist.set_quirks_mode(true);
possibly_locked_rw_data.block(rw_data);
}
fn try_get_layout_root<'ln, N: LayoutNode<'ln>>(&self, node: N) -> Option<FlowRef> {
let mut layout_data_ref = node.mutate_layout_data();
let layout_data =
match layout_data_ref.as_mut() {
None => return None,
Some(layout_data) => layout_data,
};
let result = layout_data.data.flow_construction_result.swap_out();
let mut flow = match result {
ConstructionResult::Flow(mut flow, abs_descendants) => {
// Note: Assuming that the root has display 'static' (as per
// CSS Section 9.3.1). Otherwise, if it were absolutely
// positioned, it would return a reference to itself in
// `abs_descendants` and would lead to a circular reference.
// Set Root as CB for any remaining absolute descendants.
flow.set_absolute_descendants(abs_descendants);
flow
}
_ => return None,
};
flow_ref::deref_mut(&mut flow).mark_as_root();
Some(flow)
}
/// Performs layout constraint solving.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints(layout_root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints");
sequential::traverse_flow_tree_preorder(layout_root, shared_layout_context);
}
/// Performs layout constraint solving in parallel.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints_parallel(traversal: &mut WorkQueue<SharedLayoutContext, WorkQueueData>,
layout_root: &mut FlowRef,
profiler_metadata: Option<TimerMetadata>,
time_profiler_chan: time::ProfilerChan,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints_parallel");
// NOTE: this currently computes borders, so any pruning should separate that
// operation out.
parallel::traverse_flow_tree_preorder(layout_root,
profiler_metadata,
time_profiler_chan,
shared_layout_context,
traversal);
}
fn compute_abs_pos_and_build_display_list(&mut self,
data: &Reflow,
layout_root: &mut FlowRef,
shared_layout_context: &mut SharedLayoutContext,
rw_data: &mut LayoutTaskData) {
let writing_mode = flow::base(&**layout_root).writing_mode;
let (metadata, sender) = (self.profiler_metadata(), self.time_profiler_chan.clone());
profile(time::ProfilerCategory::LayoutDispListBuild,
metadata.clone(),
sender.clone(),
|| {
flow::mut_base(flow_ref::deref_mut(layout_root)).stacking_relative_position =
LogicalPoint::zero(writing_mode).to_physical(writing_mode,
self.viewport_size);
flow::mut_base(flow_ref::deref_mut(layout_root)).clip =
ClippingRegion::from_rect(&data.page_clip_rect);
match (&mut self.parallel_traversal, opts::get().parallel_display_list_building) {
(&mut Some(ref mut traversal), true) => {
parallel::build_display_list_for_subtree(layout_root,
metadata,
sender,
shared_layout_context,
traversal);
}
_ => {
sequential::build_display_list_for_subtree(layout_root,
shared_layout_context);
}
}
if data.goal == ReflowGoal::ForDisplay {
debug!("Done building display list.");
let root_background_color = get_root_flow_background_color(
flow_ref::deref_mut(layout_root));
let root_size = {
let root_flow = flow::base(&**layout_root);
if rw_data.stylist.viewport_constraints().is_some() {
root_flow.position.size.to_physical(root_flow.writing_mode)
} else {
root_flow.overflow.size
}
};
let mut display_list = box DisplayList::new();
display_list.append_from(&mut flow::mut_base(flow_ref::deref_mut(layout_root))
.display_list_building_result);
let origin = Rect::new(Point2D::new(Au(0), Au(0)), root_size);
let stacking_context = Arc::new(StackingContext::new(display_list,
&origin,
&origin,
0,
filter::T::new(Vec::new()),
mix_blend_mode::T::normal,
Matrix4::identity(),
Matrix4::identity(),
true,
false,
None));
if opts::get().dump_display_list {
stacking_context.print("DisplayList".to_owned());
}
if opts::get().dump_display_list_json {
println!("{}", serde_json::to_string_pretty(&stacking_context).unwrap());
}
rw_data.stacking_context = Some(stacking_context.clone());
let layer_info = LayerInfo::new(layout_root.layer_id(),
ScrollPolicy::Scrollable,
None);
let paint_layer = PaintLayer::new_with_stacking_context(layer_info,
stacking_context,
root_background_color);
debug!("Layout done!");
self.epoch.next();
self.paint_chan
.send(LayoutToPaintMsg::PaintInit(self.epoch, paint_layer))
.unwrap();
}
});
}
/// The high-level routine that performs layout tasks.
fn handle_reflow<'a, 'b>(&mut self,
data: &ScriptReflow,
possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let document = unsafe { ServoLayoutNode::new(&data.document) };
let document = document.as_document().unwrap();
debug!("layout: received layout request for: {}", self.url.borrow().serialize());
let mut rw_data = possibly_locked_rw_data.lock();
let node: ServoLayoutNode = match document.root_node() {
None => {
// Since we cannot compute anything, give spec-required placeholders.
debug!("layout: No root node: bailing");
match data.query_type {
ReflowQueryType::ContentBoxQuery(_) => {
rw_data.content_box_response = Rect::zero();
},
ReflowQueryType::ContentBoxesQuery(_) => {
rw_data.content_boxes_response = Vec::new();
},
ReflowQueryType::NodeGeometryQuery(_) => {
rw_data.client_rect_response = Rect::zero();
},
ReflowQueryType::ResolvedStyleQuery(_, _, _) => {
rw_data.resolved_style_response = None;
},
ReflowQueryType::OffsetParentQuery(_) => {
rw_data.offset_parent_response = OffsetParentResponse::empty();
},
ReflowQueryType::NoQuery => {}
}
return;
},
Some(x) => x,
};
debug!("layout: received layout request for: {}",
self.url.borrow().serialize());
if log_enabled!(log::LogLevel::Debug) {
node.dump();
}
let stylesheets: Vec<&Stylesheet> = data.document_stylesheets.iter().map(|entry| &**entry)
.collect();
let stylesheets_changed = data.stylesheets_changed;
let initial_viewport = data.window_size.initial_viewport;
let old_viewport_size = self.viewport_size;
let current_screen_size = Size2D::new(Au::from_f32_px(initial_viewport.width.get()),
Au::from_f32_px(initial_viewport.height.get()));
// Calculate the actual viewport as per DEVICE-ADAPT § 6
let device = Device::new(MediaType::Screen, initial_viewport);
rw_data.stylist.set_device(device, &stylesheets);
let constraints = rw_data.stylist.viewport_constraints().clone();
self.viewport_size = match constraints {
Some(ref constraints) => {
debug!("Viewport constraints: {:?}", constraints);
// other rules are evaluated against the actual viewport
Size2D::new(Au::from_f32_px(constraints.size.width.get()),
Au::from_f32_px(constraints.size.height.get()))
}
None => current_screen_size,
};
// Handle conditions where the entire flow tree is invalid.
let viewport_size_changed = self.viewport_size != old_viewport_size;
if viewport_size_changed {
if let Some(constraints) = constraints {
// let the constellation know about the viewport constraints
let ConstellationChan(ref constellation_chan) = rw_data.constellation_chan;
constellation_chan.send(ConstellationMsg::ViewportConstrained(
self.id, constraints)).unwrap();
}
}
// If the entire flow tree is invalid, then it will be reflowed anyhow.
let needs_dirtying = rw_data.stylist.update(&stylesheets, stylesheets_changed);
let needs_reflow = viewport_size_changed && !needs_dirtying;
unsafe {
if needs_dirtying {
LayoutTask::dirty_all_nodes(node);
}
}
if needs_reflow {
if let Some(mut flow) = self.try_get_layout_root(node) {
LayoutTask::reflow_all_nodes(flow_ref::deref_mut(&mut flow));
}
}
let modified_elements = document.drain_modified_elements();
if !needs_dirtying {
for (el, snapshot) in modified_elements {
let hint = rw_data.stylist.compute_restyle_hint(&el, &snapshot, el.get_state());
el.note_restyle_hint(hint);
}
}
// Create a layout context for use throughout the following passes.
let mut shared_layout_context = self.build_shared_layout_context(&*rw_data,
viewport_size_changed,
&self.url.borrow(),
data.reflow_info.goal);
if node.is_dirty() || node.has_dirty_descendants() {
// Recalculate CSS styles and rebuild flows and fragments.
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
// Perform CSS selector matching and flow construction.
match self.parallel_traversal {
None => {
sequential::traverse_dom_preorder(node, &shared_layout_context);
}
Some(ref mut traversal) => {
parallel::traverse_dom_preorder(node, &shared_layout_context, traversal);
}
}
});
// Retrieve the (possibly rebuilt) root flow.
self.root_flow = self.try_get_layout_root(node);
}
// Send new canvas renderers to the paint task
while let Ok((layer_id, renderer)) = self.canvas_layers_receiver.try_recv() {
// Just send if there's an actual renderer
self.paint_chan.send(LayoutToPaintMsg::CanvasLayer(layer_id, renderer)).unwrap();
}
// Perform post-style recalculation layout passes.
self.perform_post_style_recalc_layout_passes(&data.reflow_info,
&mut rw_data,
&mut shared_layout_context);
if let Some(mut root_flow) = self.root_flow.clone() {
match data.query_type {
ReflowQueryType::ContentBoxQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.content_box_response = process_content_box_request(node, &mut root_flow);
},
ReflowQueryType::ContentBoxesQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.content_boxes_response = process_content_boxes_request(node, &mut root_flow);
},
ReflowQueryType::NodeGeometryQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.client_rect_response = process_node_geometry_request(node, &mut root_flow);
},
ReflowQueryType::ResolvedStyleQuery(node, ref pseudo, ref property) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.resolved_style_response =
process_resolved_style_request(node, pseudo, property, &mut root_flow);
},
ReflowQueryType::OffsetParentQuery(node) => {
let node = unsafe { ServoLayoutNode::new(&node) };
rw_data.offset_parent_response = process_offset_parent_query(node, &mut root_flow);
},
ReflowQueryType::NoQuery => {}
}
}
}
fn set_visible_rects<'a, 'b>(&mut self,
new_visible_rects: Vec<(LayerId, Rect<Au>)>,
possibly_locked_rw_data: &mut RwData<'a, 'b>)
-> bool {
let mut rw_data = possibly_locked_rw_data.lock();
// First, determine if we need to regenerate the display lists. This will happen if the
// layers have moved more than `DISPLAY_PORT_THRESHOLD_SIZE_FACTOR` away from their last
// positions.
let mut must_regenerate_display_lists = false;
let mut old_visible_rects = HashMap::with_hash_state(Default::default());
let inflation_amount =
Size2D::new(self.viewport_size.width * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR,
self.viewport_size.height * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR);
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
match self.visible_rects.get(layer_id) {
None => {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
Some(old_visible_rect) => {
old_visible_rects.insert(*layer_id, *old_visible_rect);
if !old_visible_rect.inflate(inflation_amount.width, inflation_amount.height)
.intersects(new_visible_rect) {
must_regenerate_display_lists = true;
}
}
}
}
if !must_regenerate_display_lists {
// Update `visible_rects` in case there are new layers that were discovered.
self.visible_rects = Arc::new(old_visible_rects);
return true
}
debug!("regenerating display lists!");
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
self.visible_rects = Arc::new(old_visible_rects);
// Regenerate the display lists.
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
self.perform_post_main_layout_passes(&reflow_info, &mut *rw_data, &mut layout_context);
true
}
fn tick_all_animations<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
self.tick_animations(&mut rw_data);
self.script_chan
.send(ConstellationControlMsg::TickAllAnimations(self.id))
.unwrap();
}
pub fn tick_animations(&mut self, rw_data: &mut LayoutTaskData) {
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
if let Some(mut root_flow) = self.root_flow.clone() {
// Perform an abbreviated style recalc that operates without access to the DOM.
let animations = self.running_animations.read().unwrap();
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
animation::recalc_style_for_animations(flow_ref::deref_mut(&mut root_flow),
&*animations)
});
}
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
}
fn reflow_with_newly_loaded_web_font<'a, 'b>(&mut self, possibly_locked_rw_data: &mut RwData<'a, 'b>) {
let mut rw_data = possibly_locked_rw_data.lock();
font_context::invalidate_font_caches();
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
&self.url.borrow(),
reflow_info.goal);
// No need to do a style recalc here.
if self.root_flow.is_none() {
return
}
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
}
fn perform_post_style_recalc_layout_passes(&mut self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
if let Some(mut root_flow) = self.root_flow.clone() {
// Kick off animations if any were triggered, expire completed ones.
animation::update_animation_state(&self.constellation_chan,
&mut *self.running_animations.write().unwrap(),
&mut *self.expired_animations.write().unwrap(),
&self.new_animations_receiver,
self.id);
profile(time::ProfilerCategory::LayoutRestyleDamagePropagation,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
if opts::get().nonincremental_layout ||
flow_ref::deref_mut(&mut root_flow).compute_layout_damage()
.contains(REFLOW_ENTIRE_DOCUMENT) {
flow_ref::deref_mut(&mut root_flow).reflow_entire_document()
}
});
if opts::get().trace_layout {
layout_debug::begin_trace(root_flow.clone());
}
// Resolve generated content.
profile(time::ProfilerCategory::LayoutGeneratedContent,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| sequential::resolve_generated_content(&mut root_flow, &layout_context));
// Perform the primary layout passes over the flow tree to compute the locations of all
// the boxes.
profile(time::ProfilerCategory::LayoutMain,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
let profiler_metadata = self.profiler_metadata();
match self.parallel_traversal {
None => {
// Sequential mode.
LayoutTask::solve_constraints(&mut root_flow, &layout_context)
}
Some(ref mut parallel) => {
// Parallel mode.
LayoutTask::solve_constraints_parallel(parallel,
&mut root_flow,
profiler_metadata,
self.time_profiler_chan.clone(),
&*layout_context);
}
}
});
self.perform_post_main_layout_passes(data, rw_data, layout_context);
}
}
fn perform_post_main_layout_passes(&mut self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
// Build the display list if necessary, and send it to the painter.
if let Some(mut root_flow) = self.root_flow.clone() {
self.compute_abs_pos_and_build_display_list(data,
&mut root_flow,
&mut *layout_context,
rw_data);
self.first_reflow = false;
if opts::get().trace_layout {
layout_debug::end_trace();
}
if opts::get().dump_flow_tree {
root_flow.print("Post layout flow tree".to_owned());
}
self.generation += 1;
}
}
unsafe fn dirty_all_nodes<'ln, N: LayoutNode<'ln>>(node: N) {
for node in node.traverse_preorder() {
// TODO(cgaebel): mark nodes which are sensitive to media queries as
// "changed":
// > node.set_changed(true);
node.set_dirty(true);
node.set_dirty_descendants(true);
}
}
fn reflow_all_nodes(flow: &mut Flow) {
debug!("reflowing all nodes!");
flow::mut_base(flow).restyle_damage.insert(REFLOW | REPAINT);
for child in flow::child_iter(flow) {
LayoutTask::reflow_all_nodes(child);
}
}
/// Handles a message to destroy layout data. Layout data must be destroyed on *this* task
/// because the struct type is transmuted to a different type on the script side.
unsafe fn handle_reap_layout_data(&self, layout_data: LayoutData) {
let _: LayoutDataWrapper = transmute(layout_data);
}
/// Returns profiling information which is passed to the time profiler.
fn profiler_metadata(&self) -> Option<TimerMetadata> {
Some(TimerMetadata {
url: self.url.borrow().serialize(),
iframe: if self.is_iframe {
TimerMetadataFrameType::IFrame
} else {
TimerMetadataFrameType::RootWindow
},
incremental: if self.first_reflow {
TimerMetadataReflowType::FirstReflow
} else {
TimerMetadataReflowType::Incremental
},
})
}
}
// The default computed value for background-color is transparent (see
// http://dev.w3.org/csswg/css-backgrounds/#background-color). However, we
// need to propagate the background color from the root HTML/Body
// element (http://dev.w3.org/csswg/css-backgrounds/#special-backgrounds) if
// it is non-transparent. The phrase in the spec "If the canvas background
// is not opaque, what shows through is UA-dependent." is handled by rust-layers
// clearing the frame buffer to white. This ensures that setting a background
// color on an iframe element, while the iframe content itself has a default
// transparent background color is handled correctly.
fn get_root_flow_background_color(flow: &mut Flow) -> AzColor {
if !flow.is_block_like() {
return color::transparent()
}
let block_flow = flow.as_mut_block();
let kid = match block_flow.base.children.iter_mut().next() {
None => return color::transparent(),
Some(kid) => kid,
};
if !kid.is_block_like() {
return color::transparent()
}
let kid_block_flow = kid.as_block();
kid_block_flow.fragment
.style
.resolve_color(kid_block_flow.fragment.style.get_background().background_color)
.to_gfx_color()
}
|
// Copyright 2016-2017 The Servo 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.
//! A crate for measuring the heap usage of data structures in a way that
//! integrates with Firefox's memory reporting, particularly the use of
//! mozjemalloc and DMD. In particular, it has the following features.
//! - It isn't bound to a particular heap allocator.
//! - It provides traits for both "shallow" and "deep" measurement, which gives
//! flexibility in the cases where the traits can't be used.
//! - It allows for measuring blocks even when only an interior pointer can be
//! obtained for heap allocations, e.g. `HashSet` and `HashMap`. (This relies
//! on the heap allocator having suitable support, which mozjemalloc has.)
//! - It allows handling of types like `Rc` and `Arc` by providing traits that
//! are different to the ones for non-graph structures.
//!
//! Suggested uses are as follows.
//! - When possible, use the `MallocSizeOf` trait. (Deriving support is
//! provided by the `malloc_size_of_derive` crate.)
//! - If you need an additional synchronization argument, provide a function
//! that is like the standard trait method, but with the extra argument.
//! - If you need multiple measurements for a type, provide a function named
//! `add_size_of` that takes a mutable reference to a struct that contains
//! the multiple measurement fields.
//! - When deep measurement (via `MallocSizeOf`) cannot be implemented for a
//! type, shallow measurement (via `MallocShallowSizeOf`) in combination with
//! iteration can be a useful substitute.
//! - `Rc` and `Arc` are always tricky, which is why `MallocSizeOf` is not (and
//! should not be) implemented for them.
//! - If an `Rc` or `Arc` is known to be a "primary" reference and can always
//! be measured, it should be measured via the `MallocUnconditionalSizeOf`
//! trait.
//! - If an `Rc` or `Arc` should be measured only if it hasn't been seen
//! before, it should be measured via the `MallocConditionalSizeOf` trait.
//! - Using universal function call syntax is a good idea when measuring boxed
//! fields in structs, because it makes it clear that the Box is being
//! measured as well as the thing it points to. E.g.
//! `<Box<_> as MallocSizeOf>::size_of(field, ops)`.
extern crate app_units;
extern crate cssparser;
extern crate euclid;
extern crate hashglobe;
#[cfg(feature = "servo")]
extern crate hyper;
#[cfg(feature = "servo")]
extern crate hyper_serde;
#[cfg(feature = "servo")]
extern crate mozjs as js;
extern crate selectors;
#[cfg(feature = "servo")]
extern crate serde;
#[cfg(feature = "servo")]
extern crate serde_bytes;
extern crate servo_arc;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")]
extern crate string_cache;
extern crate thin_slice;
#[cfg(feature = "servo")]
extern crate time;
#[cfg(feature = "url")]
extern crate url;
extern crate void;
#[cfg(feature = "webrender_api")]
extern crate webrender_api;
#[cfg(feature = "servo")]
extern crate xml5ever;
#[cfg(feature = "servo")]
use serde_bytes::ByteBuf;
use std::hash::{BuildHasher, Hash};
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ops::Range;
use std::os::raw::c_void;
use void::Void;
/// A C function that takes a pointer to a heap allocation and returns its size.
type VoidPtrToSizeFn = unsafe extern "C" fn(ptr: *const c_void) -> usize;
/// A closure implementing a stateful predicate on pointers.
type VoidPtrToBoolFnMut = FnMut(*const c_void) -> bool;
/// Operations used when measuring heap usage of data structures.
pub struct MallocSizeOfOps {
/// A function that returns the size of a heap allocation.
size_of_op: VoidPtrToSizeFn,
/// Like `size_of_op`, but can take an interior pointer. Optional because
/// not all allocators support this operation. If it's not provided, some
/// memory measurements will actually be computed estimates rather than
/// real and accurate measurements.
enclosing_size_of_op: Option<VoidPtrToSizeFn>,
/// Check if a pointer has been seen before, and remember it for next time.
/// Useful when measuring `Rc`s and `Arc`s. Optional, because many places
/// don't need it.
have_seen_ptr_op: Option<Box<VoidPtrToBoolFnMut>>,
}
impl MallocSizeOfOps {
pub fn new(size_of: VoidPtrToSizeFn,
malloc_enclosing_size_of: Option<VoidPtrToSizeFn>,
have_seen_ptr: Option<Box<VoidPtrToBoolFnMut>>) -> Self {
MallocSizeOfOps {
size_of_op: size_of,
enclosing_size_of_op: malloc_enclosing_size_of,
have_seen_ptr_op: have_seen_ptr,
}
}
/// Check if an allocation is empty. This relies on knowledge of how Rust
/// handles empty allocations, which may change in the future.
fn is_empty<T: ?Sized>(ptr: *const T) -> bool {
// The correct condition is this:
// `ptr as usize <= ::std::mem::align_of::<T>()`
// But we can't call align_of() on a ?Sized T. So we approximate it
// with the following. 256 is large enough that it should always be
// larger than the required alignment, but small enough that it is
// always in the first page of memory and therefore not a legitimate
// address.
return ptr as *const usize as usize <= 256
}
/// Call `size_of_op` on `ptr`, first checking that the allocation isn't
/// empty, because some types (such as `Vec`) utilize empty allocations.
pub unsafe fn malloc_size_of<T: ?Sized>(&self, ptr: *const T) -> usize {
if MallocSizeOfOps::is_empty(ptr) {
0
} else {
(self.size_of_op)(ptr as *const c_void)
}
}
/// Is an `enclosing_size_of_op` available?
pub fn has_malloc_enclosing_size_of(&self) -> bool {
self.enclosing_size_of_op.is_some()
}
/// Call `enclosing_size_of_op`, which must be available, on `ptr`, which
/// must not be empty.
pub unsafe fn malloc_enclosing_size_of<T>(&self, ptr: *const T) -> usize {
assert!(!MallocSizeOfOps::is_empty(ptr));
(self.enclosing_size_of_op.unwrap())(ptr as *const c_void)
}
/// Call `have_seen_ptr_op` on `ptr`.
pub fn have_seen_ptr<T>(&mut self, ptr: *const T) -> bool {
let have_seen_ptr_op = self.have_seen_ptr_op.as_mut().expect("missing have_seen_ptr_op");
have_seen_ptr_op(ptr as *const c_void)
}
}
/// Trait for measuring the "deep" heap usage of a data structure. This is the
/// most commonly-used of the traits.
pub trait MallocSizeOf {
/// Measure the heap usage of all descendant heap-allocated structures, but
/// not the space taken up by the value itself.
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Trait for measuring the "shallow" heap usage of a container.
pub trait MallocShallowSizeOf {
/// Measure the heap usage of immediate heap-allocated descendant
/// structures, but not the space taken up by the value itself. Anything
/// beyond the immediate descendants must be measured separately, using
/// iteration.
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Like `MallocSizeOf`, but with a different name so it cannot be used
/// accidentally with derive(MallocSizeOf). For use with types like `Rc` and
/// `Arc` when appropriate (e.g. when measuring a "primary" reference).
pub trait MallocUnconditionalSizeOf {
/// Measure the heap usage of all heap-allocated descendant structures, but
/// not the space taken up by the value itself.
fn unconditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// `MallocUnconditionalSizeOf` combined with `MallocShallowSizeOf`.
pub trait MallocUnconditionalShallowSizeOf {
/// `unconditional_size_of` combined with `shallow_size_of`.
fn unconditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Like `MallocSizeOf`, but only measures if the value hasn't already been
/// measured. For use with types like `Rc` and `Arc` when appropriate (e.g.
/// when there is no "primary" reference).
pub trait MallocConditionalSizeOf {
/// Measure the heap usage of all heap-allocated descendant structures, but
/// not the space taken up by the value itself, and only if that heap usage
/// hasn't already been measured.
fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// `MallocConditionalSizeOf` combined with `MallocShallowSizeOf`.
pub trait MallocConditionalShallowSizeOf {
/// `conditional_size_of` combined with `shallow_size_of`.
fn conditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
impl MallocSizeOf for String {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
impl<'a, T: ?Sized> MallocSizeOf for &'a T {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
// Zero makes sense for a non-owning reference.
0
}
}
impl<T: ?Sized> MallocShallowSizeOf for Box<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(&**self) }
}
}
impl<T: MallocSizeOf + ?Sized> MallocSizeOf for Box<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl<T> MallocShallowSizeOf for thin_slice::ThinBoxedSlice<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
unsafe {
n += thin_slice::ThinBoxedSlice::spilled_storage(self)
.map_or(0, |ptr| ops.malloc_size_of(ptr));
n += ops.malloc_size_of(&**self);
}
n
}
}
impl<T: MallocSizeOf> MallocSizeOf for thin_slice::ThinBoxedSlice<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl MallocSizeOf for () {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
impl<T1, T2> MallocSizeOf for (T1, T2)
where T1: MallocSizeOf, T2: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops)
}
}
impl<T1, T2, T3> MallocSizeOf for (T1, T2, T3)
where T1: MallocSizeOf, T2: MallocSizeOf, T3: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops) + self.2.size_of(ops)
}
}
impl<T1, T2, T3, T4> MallocSizeOf for (T1, T2, T3, T4)
where T1: MallocSizeOf, T2: MallocSizeOf, T3: MallocSizeOf, T4: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops) + self.2.size_of(ops) + self.3.size_of(ops)
}
}
impl<T: MallocSizeOf> MallocSizeOf for Option<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if let Some(val) = self.as_ref() {
val.size_of(ops)
} else {
0
}
}
}
impl<T: MallocSizeOf, E: MallocSizeOf> MallocSizeOf for Result<T, E> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
Ok(ref x) => x.size_of(ops),
Err(ref e) => e.size_of(ops),
}
}
}
impl<T: MallocSizeOf + Copy> MallocSizeOf for std::cell::Cell<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.get().size_of(ops)
}
}
impl<T: MallocSizeOf> MallocSizeOf for std::cell::RefCell<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.borrow().size_of(ops)
}
}
impl<'a, B: ?Sized + ToOwned> MallocSizeOf for std::borrow::Cow<'a, B>
where B::Owned: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
std::borrow::Cow::Borrowed(_) => 0,
std::borrow::Cow::Owned(ref b) => b.size_of(ops),
}
}
}
impl<T: MallocSizeOf> MallocSizeOf for [T] {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
#[cfg(feature = "servo")]
impl MallocShallowSizeOf for ByteBuf {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for ByteBuf {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T> MallocShallowSizeOf for Vec<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
impl<T: MallocSizeOf> MallocSizeOf for Vec<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T> MallocShallowSizeOf for std::collections::VecDeque<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.has_malloc_enclosing_size_of() {
if let Some(front) = self.front() {
// The front element is an interior pointer.
unsafe { ops.malloc_enclosing_size_of(&*front) }
} else {
// This assumes that no memory is allocated when the VecDeque is empty.
0
}
} else {
// An estimate.
self.capacity() * size_of::<T>()
}
}
}
impl<T: MallocSizeOf> MallocSizeOf for std::collections::VecDeque<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<A: smallvec::Array> MallocShallowSizeOf for smallvec::SmallVec<A> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if self.spilled() {
unsafe { ops.malloc_size_of(self.as_ptr()) }
} else {
0
}
}
}
impl<A> MallocSizeOf for smallvec::SmallVec<A>
where A: smallvec::Array,
A::Item: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for std::collections::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.has_malloc_enclosing_size_of() {
// The first value from the iterator gives us an interior pointer.
// `ops.malloc_enclosing_size_of()` then gives us the storage size.
// This assumes that the `HashSet`'s contents (values and hashes)
// are all stored in a single contiguous heap allocation.
self.iter().next().map_or(0, |t| unsafe { ops.malloc_enclosing_size_of(t) })
} else {
// An estimate.
self.capacity() * (size_of::<T>() + size_of::<usize>())
}
}
}
impl<T, S> MallocSizeOf for std::collections::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for t in self.iter() {
n += t.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for hashglobe::hash_set::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.iter().next().map_or(0, |t| unsafe { ops.malloc_enclosing_size_of(t) })
} else {
self.capacity() * (size_of::<T>() + size_of::<usize>())
}
}
}
impl<T, S> MallocSizeOf for hashglobe::hash_set::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for t in self.iter() {
n += t.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for hashglobe::fake::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher,
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().shallow_size_of(ops)
}
}
impl<T, S> MallocSizeOf for hashglobe::fake::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().size_of(ops)
}
}
impl<K, V, S> MallocShallowSizeOf for std::collections::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.values().next().map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) })
} else {
self.capacity() * (size_of::<V>() + size_of::<K>() + size_of::<usize>())
}
}
}
impl<K, V, S> MallocSizeOf for std::collections::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for (k, v) in self.iter() {
n += k.size_of(ops);
n += v.size_of(ops);
}
n
}
}
impl<K, V, S> MallocShallowSizeOf for hashglobe::hash_map::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.values().next().map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) })
} else {
self.capacity() * (size_of::<V>() + size_of::<K>() + size_of::<usize>())
}
}
}
impl<K, V, S> MallocSizeOf for hashglobe::hash_map::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for (k, v) in self.iter() {
n += k.size_of(ops);
n += v.size_of(ops);
}
n
}
}
impl<K, V, S> MallocShallowSizeOf for hashglobe::fake::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher,
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().shallow_size_of(ops)
}
}
impl<K, V, S> MallocSizeOf for hashglobe::fake::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().size_of(ops)
}
}
// PhantomData is always 0.
impl<T> MallocSizeOf for std::marker::PhantomData<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
// XXX: we don't want MallocSizeOf to be defined for Rc and Arc. If negative
// trait bounds are ever allowed, this code should be uncommented.
// (We do have a compile-fail test for this:
// rc_arc_must_not_derive_malloc_size_of.rs)
//impl<T> !MallocSizeOf for Arc<T> { }
//impl<T> !MallocShallowSizeOf for Arc<T> { }
impl<T> MallocUnconditionalShallowSizeOf for servo_arc::Arc<T> {
fn unconditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.heap_ptr()) }
}
}
impl<T: MallocSizeOf> MallocUnconditionalSizeOf for servo_arc::Arc<T> {
fn unconditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.unconditional_shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl<T> MallocConditionalShallowSizeOf for servo_arc::Arc<T> {
fn conditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.have_seen_ptr(self.heap_ptr()) {
0
} else {
self.unconditional_shallow_size_of(ops)
}
}
}
impl<T: MallocSizeOf> MallocConditionalSizeOf for servo_arc::Arc<T> {
fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.have_seen_ptr(self.heap_ptr()) {
0
} else {
self.unconditional_size_of(ops)
}
}
}
/// If a mutex is stored directly as a member of a data type that is being measured,
/// it is the unique owner of its contents and deserves to be measured.
///
/// If a mutex is stored inside of an Arc value as a member of a data type that is being measured,
/// the Arc will not be automatically measured so there is no risk of overcounting the mutex's
/// contents.
impl<T: MallocSizeOf> MallocSizeOf for std::sync::Mutex<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
(*self.lock().unwrap()).size_of(ops)
}
}
impl MallocSizeOf for smallbitvec::SmallBitVec {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if let Some(ptr) = self.heap_ptr() {
unsafe { ops.malloc_size_of(ptr) }
} else {
0
}
}
}
impl<T: MallocSizeOf, Unit> MallocSizeOf for euclid::Length<T, Unit> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedScale<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedPoint2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.x.size_of(ops) + self.y.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedRect<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.origin.size_of(ops) + self.size.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedSideOffsets2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.top.size_of(ops) + self.right.size_of(ops) +
self.bottom.size_of(ops) + self.left.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedSize2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.width.size_of(ops) + self.height.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedTransform2D<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.m11.size_of(ops) + self.m12.size_of(ops) +
self.m21.size_of(ops) + self.m22.size_of(ops) +
self.m31.size_of(ops) + self.m32.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedTransform3D<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.m11.size_of(ops) + self.m12.size_of(ops) +
self.m13.size_of(ops) + self.m14.size_of(ops) +
self.m21.size_of(ops) + self.m22.size_of(ops) +
self.m23.size_of(ops) + self.m24.size_of(ops) +
self.m31.size_of(ops) + self.m32.size_of(ops) +
self.m33.size_of(ops) + self.m34.size_of(ops) +
self.m41.size_of(ops) + self.m42.size_of(ops) +
self.m43.size_of(ops) + self.m44.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedVector2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.x.size_of(ops) + self.y.size_of(ops)
}
}
impl MallocSizeOf for selectors::parser::AncestorHashes {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let selectors::parser::AncestorHashes { ref packed_hashes } = *self;
packed_hashes.size_of(ops)
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::parser::Selector<Impl>
where
Impl::NonTSPseudoClass: MallocSizeOf,
Impl::PseudoElement: MallocSizeOf,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
// It's OK to measure this ThinArc directly because it's the
// "primary" reference. (The secondary references are on the
// Stylist.)
n += unsafe { ops.malloc_size_of(self.thin_arc_heap_ptr()) };
for component in self.iter_raw_match_order() {
n += component.size_of(ops);
}
n
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::parser::Component<Impl>
where
Impl::NonTSPseudoClass: MallocSizeOf,
Impl::PseudoElement: MallocSizeOf,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use selectors::parser::Component;
match self {
Component::AttributeOther(ref attr_selector) => {
attr_selector.size_of(ops)
}
Component::Negation(ref components) => {
components.size_of(ops)
}
Component::NonTSPseudoClass(ref pseudo) => {
(*pseudo).size_of(ops)
}
Component::Slotted(ref selector) |
Component::Host(Some(ref selector)) => {
selector.size_of(ops)
}
Component::PseudoElement(ref pseudo) => {
(*pseudo).size_of(ops)
}
Component::Combinator(..) |
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(..) |
Component::Namespace(..) |
Component::ExplicitUniversalType |
Component::LocalName(..) |
Component::ID(..) |
Component::Class(..) |
Component::AttributeInNoNamespaceExists { .. } |
Component::AttributeInNoNamespace { .. } |
Component::FirstChild |
Component::LastChild |
Component::OnlyChild |
Component::Root |
Component::Empty |
Component::Scope |
Component::NthChild(..) |
Component::NthLastChild(..) |
Component::NthOfType(..) |
Component::NthLastOfType(..) |
Component::FirstOfType |
Component::LastOfType |
Component::OnlyOfType |
Component::Host(None) => 0,
}
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::attr::AttrSelectorWithOptionalNamespace<Impl>
{
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
impl MallocSizeOf for Void {
#[inline]
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
void::unreachable(*self)
}
}
#[cfg(feature = "servo")]
impl<Static: string_cache::StaticAtomSet> MallocSizeOf for string_cache::Atom<Static> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
// This is measured properly by the heap measurement implemented in
// SpiderMonkey.
#[cfg(feature = "servo")]
impl<T: Copy + js::rust::GCMethods> MallocSizeOf for js::jsapi::Heap<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
/// For use on types where size_of() returns 0.
#[macro_export]
macro_rules! malloc_size_of_is_0(
($($ty:ty),+) => (
$(
impl $crate::MallocSizeOf for $ty {
#[inline(always)]
fn size_of(&self, _: &mut $crate::MallocSizeOfOps) -> usize {
0
}
}
)+
);
($($ty:ident<$($gen:ident),+>),+) => (
$(
impl<$($gen: $crate::MallocSizeOf),+> $crate::MallocSizeOf for $ty<$($gen),+> {
#[inline(always)]
fn size_of(&self, _: &mut $crate::MallocSizeOfOps) -> usize {
0
}
}
)+
);
);
malloc_size_of_is_0!(bool, char, str);
malloc_size_of_is_0!(u8, u16, u32, u64, usize);
malloc_size_of_is_0!(i8, i16, i32, i64, isize);
malloc_size_of_is_0!(f32, f64);
malloc_size_of_is_0!(std::sync::atomic::AtomicBool);
malloc_size_of_is_0!(std::sync::atomic::AtomicIsize, std::sync::atomic::AtomicUsize);
malloc_size_of_is_0!(Range<u8>, Range<u16>, Range<u32>, Range<u64>, Range<usize>);
malloc_size_of_is_0!(Range<i8>, Range<i16>, Range<i32>, Range<i64>, Range<isize>);
malloc_size_of_is_0!(Range<f32>, Range<f64>);
malloc_size_of_is_0!(app_units::Au);
malloc_size_of_is_0!(cssparser::RGBA, cssparser::TokenSerializationType);
#[cfg(feature = "url")]
impl MallocSizeOf for url::Host {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
url::Host::Domain(ref s) => s.size_of(ops),
_ => 0,
}
}
}
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderRadius);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderStyle);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderWidths);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BoxShadowClipMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ClipAndScrollInfo);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ColorF);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ComplexClipRegion);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ExtendMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::FilterOp);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ExternalScrollId);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::FontInstanceKey);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::GradientStop);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::GlyphInstance);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::NinePatchBorder);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ImageKey);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ImageRendering);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::LineStyle);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::MixBlendMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::NormalBorder);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::RepeatMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ScrollSensitivity);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::StickyOffsetBounds);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::TransformStyle);
#[cfg(feature = "servo")]
impl MallocSizeOf for xml5ever::QualName {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.prefix.size_of(ops) +
self.ns.size_of(ops) +
self.local.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::header::Headers {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.iter().fold(0, |acc, x| {
let name = x.name();
let raw = self.get_raw(name);
acc + raw.size_of(ops)
})
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::header::ContentType {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Mime {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) +
self.1.size_of(ops) +
self.2.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Attr {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
hyper::mime::Attr::Ext(ref s) => s.size_of(ops),
_ => 0,
}
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Value {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
self.len() // Length of string value in bytes (not the char length of a string)!
}
}
#[cfg(feature = "servo")]
malloc_size_of_is_0!(time::Duration);
#[cfg(feature = "servo")]
malloc_size_of_is_0!(time::Tm);
#[cfg(feature = "servo")]
impl<T> MallocSizeOf for hyper_serde::Serde<T> where
for <'de> hyper_serde::De<T>: serde::Deserialize<'de>,
for <'a> hyper_serde::Ser<'a, T>: serde::Serialize,
T: MallocSizeOf {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
// Placeholder for unique case where internals of Sender cannot be measured.
// malloc size of is 0 macro complains about type supplied!
impl<T> MallocSizeOf for std::sync::mpsc::Sender<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::status::StatusCode {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
hyper::status::StatusCode::Unregistered(u) => u.size_of(ops),
_ => 0,
}
}
}
/// Measurable that defers to inner value and used to verify MallocSizeOf implementation in a
/// struct.
#[derive(Clone)]
pub struct Measurable<T: MallocSizeOf> (pub T);
impl<T: MallocSizeOf> Deref for Measurable<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: MallocSizeOf> DerefMut for Measurable<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
style: Add MallocSizeOf impls for 128-bit integers.
Differential Revision: https://phabricator.services.mozilla.com/D3947
// Copyright 2016-2017 The Servo 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.
//! A crate for measuring the heap usage of data structures in a way that
//! integrates with Firefox's memory reporting, particularly the use of
//! mozjemalloc and DMD. In particular, it has the following features.
//! - It isn't bound to a particular heap allocator.
//! - It provides traits for both "shallow" and "deep" measurement, which gives
//! flexibility in the cases where the traits can't be used.
//! - It allows for measuring blocks even when only an interior pointer can be
//! obtained for heap allocations, e.g. `HashSet` and `HashMap`. (This relies
//! on the heap allocator having suitable support, which mozjemalloc has.)
//! - It allows handling of types like `Rc` and `Arc` by providing traits that
//! are different to the ones for non-graph structures.
//!
//! Suggested uses are as follows.
//! - When possible, use the `MallocSizeOf` trait. (Deriving support is
//! provided by the `malloc_size_of_derive` crate.)
//! - If you need an additional synchronization argument, provide a function
//! that is like the standard trait method, but with the extra argument.
//! - If you need multiple measurements for a type, provide a function named
//! `add_size_of` that takes a mutable reference to a struct that contains
//! the multiple measurement fields.
//! - When deep measurement (via `MallocSizeOf`) cannot be implemented for a
//! type, shallow measurement (via `MallocShallowSizeOf`) in combination with
//! iteration can be a useful substitute.
//! - `Rc` and `Arc` are always tricky, which is why `MallocSizeOf` is not (and
//! should not be) implemented for them.
//! - If an `Rc` or `Arc` is known to be a "primary" reference and can always
//! be measured, it should be measured via the `MallocUnconditionalSizeOf`
//! trait.
//! - If an `Rc` or `Arc` should be measured only if it hasn't been seen
//! before, it should be measured via the `MallocConditionalSizeOf` trait.
//! - Using universal function call syntax is a good idea when measuring boxed
//! fields in structs, because it makes it clear that the Box is being
//! measured as well as the thing it points to. E.g.
//! `<Box<_> as MallocSizeOf>::size_of(field, ops)`.
extern crate app_units;
extern crate cssparser;
extern crate euclid;
extern crate hashglobe;
#[cfg(feature = "servo")]
extern crate hyper;
#[cfg(feature = "servo")]
extern crate hyper_serde;
#[cfg(feature = "servo")]
extern crate mozjs as js;
extern crate selectors;
#[cfg(feature = "servo")]
extern crate serde;
#[cfg(feature = "servo")]
extern crate serde_bytes;
extern crate servo_arc;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")]
extern crate string_cache;
extern crate thin_slice;
#[cfg(feature = "servo")]
extern crate time;
#[cfg(feature = "url")]
extern crate url;
extern crate void;
#[cfg(feature = "webrender_api")]
extern crate webrender_api;
#[cfg(feature = "servo")]
extern crate xml5ever;
#[cfg(feature = "servo")]
use serde_bytes::ByteBuf;
use std::hash::{BuildHasher, Hash};
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ops::Range;
use std::os::raw::c_void;
use void::Void;
/// A C function that takes a pointer to a heap allocation and returns its size.
type VoidPtrToSizeFn = unsafe extern "C" fn(ptr: *const c_void) -> usize;
/// A closure implementing a stateful predicate on pointers.
type VoidPtrToBoolFnMut = FnMut(*const c_void) -> bool;
/// Operations used when measuring heap usage of data structures.
pub struct MallocSizeOfOps {
/// A function that returns the size of a heap allocation.
size_of_op: VoidPtrToSizeFn,
/// Like `size_of_op`, but can take an interior pointer. Optional because
/// not all allocators support this operation. If it's not provided, some
/// memory measurements will actually be computed estimates rather than
/// real and accurate measurements.
enclosing_size_of_op: Option<VoidPtrToSizeFn>,
/// Check if a pointer has been seen before, and remember it for next time.
/// Useful when measuring `Rc`s and `Arc`s. Optional, because many places
/// don't need it.
have_seen_ptr_op: Option<Box<VoidPtrToBoolFnMut>>,
}
impl MallocSizeOfOps {
pub fn new(size_of: VoidPtrToSizeFn,
malloc_enclosing_size_of: Option<VoidPtrToSizeFn>,
have_seen_ptr: Option<Box<VoidPtrToBoolFnMut>>) -> Self {
MallocSizeOfOps {
size_of_op: size_of,
enclosing_size_of_op: malloc_enclosing_size_of,
have_seen_ptr_op: have_seen_ptr,
}
}
/// Check if an allocation is empty. This relies on knowledge of how Rust
/// handles empty allocations, which may change in the future.
fn is_empty<T: ?Sized>(ptr: *const T) -> bool {
// The correct condition is this:
// `ptr as usize <= ::std::mem::align_of::<T>()`
// But we can't call align_of() on a ?Sized T. So we approximate it
// with the following. 256 is large enough that it should always be
// larger than the required alignment, but small enough that it is
// always in the first page of memory and therefore not a legitimate
// address.
return ptr as *const usize as usize <= 256
}
/// Call `size_of_op` on `ptr`, first checking that the allocation isn't
/// empty, because some types (such as `Vec`) utilize empty allocations.
pub unsafe fn malloc_size_of<T: ?Sized>(&self, ptr: *const T) -> usize {
if MallocSizeOfOps::is_empty(ptr) {
0
} else {
(self.size_of_op)(ptr as *const c_void)
}
}
/// Is an `enclosing_size_of_op` available?
pub fn has_malloc_enclosing_size_of(&self) -> bool {
self.enclosing_size_of_op.is_some()
}
/// Call `enclosing_size_of_op`, which must be available, on `ptr`, which
/// must not be empty.
pub unsafe fn malloc_enclosing_size_of<T>(&self, ptr: *const T) -> usize {
assert!(!MallocSizeOfOps::is_empty(ptr));
(self.enclosing_size_of_op.unwrap())(ptr as *const c_void)
}
/// Call `have_seen_ptr_op` on `ptr`.
pub fn have_seen_ptr<T>(&mut self, ptr: *const T) -> bool {
let have_seen_ptr_op = self.have_seen_ptr_op.as_mut().expect("missing have_seen_ptr_op");
have_seen_ptr_op(ptr as *const c_void)
}
}
/// Trait for measuring the "deep" heap usage of a data structure. This is the
/// most commonly-used of the traits.
pub trait MallocSizeOf {
/// Measure the heap usage of all descendant heap-allocated structures, but
/// not the space taken up by the value itself.
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Trait for measuring the "shallow" heap usage of a container.
pub trait MallocShallowSizeOf {
/// Measure the heap usage of immediate heap-allocated descendant
/// structures, but not the space taken up by the value itself. Anything
/// beyond the immediate descendants must be measured separately, using
/// iteration.
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Like `MallocSizeOf`, but with a different name so it cannot be used
/// accidentally with derive(MallocSizeOf). For use with types like `Rc` and
/// `Arc` when appropriate (e.g. when measuring a "primary" reference).
pub trait MallocUnconditionalSizeOf {
/// Measure the heap usage of all heap-allocated descendant structures, but
/// not the space taken up by the value itself.
fn unconditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// `MallocUnconditionalSizeOf` combined with `MallocShallowSizeOf`.
pub trait MallocUnconditionalShallowSizeOf {
/// `unconditional_size_of` combined with `shallow_size_of`.
fn unconditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// Like `MallocSizeOf`, but only measures if the value hasn't already been
/// measured. For use with types like `Rc` and `Arc` when appropriate (e.g.
/// when there is no "primary" reference).
pub trait MallocConditionalSizeOf {
/// Measure the heap usage of all heap-allocated descendant structures, but
/// not the space taken up by the value itself, and only if that heap usage
/// hasn't already been measured.
fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
/// `MallocConditionalSizeOf` combined with `MallocShallowSizeOf`.
pub trait MallocConditionalShallowSizeOf {
/// `conditional_size_of` combined with `shallow_size_of`.
fn conditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize;
}
impl MallocSizeOf for String {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
impl<'a, T: ?Sized> MallocSizeOf for &'a T {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
// Zero makes sense for a non-owning reference.
0
}
}
impl<T: ?Sized> MallocShallowSizeOf for Box<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(&**self) }
}
}
impl<T: MallocSizeOf + ?Sized> MallocSizeOf for Box<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl<T> MallocShallowSizeOf for thin_slice::ThinBoxedSlice<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
unsafe {
n += thin_slice::ThinBoxedSlice::spilled_storage(self)
.map_or(0, |ptr| ops.malloc_size_of(ptr));
n += ops.malloc_size_of(&**self);
}
n
}
}
impl<T: MallocSizeOf> MallocSizeOf for thin_slice::ThinBoxedSlice<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl MallocSizeOf for () {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
impl<T1, T2> MallocSizeOf for (T1, T2)
where T1: MallocSizeOf, T2: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops)
}
}
impl<T1, T2, T3> MallocSizeOf for (T1, T2, T3)
where T1: MallocSizeOf, T2: MallocSizeOf, T3: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops) + self.2.size_of(ops)
}
}
impl<T1, T2, T3, T4> MallocSizeOf for (T1, T2, T3, T4)
where T1: MallocSizeOf, T2: MallocSizeOf, T3: MallocSizeOf, T4: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) + self.1.size_of(ops) + self.2.size_of(ops) + self.3.size_of(ops)
}
}
impl<T: MallocSizeOf> MallocSizeOf for Option<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if let Some(val) = self.as_ref() {
val.size_of(ops)
} else {
0
}
}
}
impl<T: MallocSizeOf, E: MallocSizeOf> MallocSizeOf for Result<T, E> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
Ok(ref x) => x.size_of(ops),
Err(ref e) => e.size_of(ops),
}
}
}
impl<T: MallocSizeOf + Copy> MallocSizeOf for std::cell::Cell<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.get().size_of(ops)
}
}
impl<T: MallocSizeOf> MallocSizeOf for std::cell::RefCell<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.borrow().size_of(ops)
}
}
impl<'a, B: ?Sized + ToOwned> MallocSizeOf for std::borrow::Cow<'a, B>
where B::Owned: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
std::borrow::Cow::Borrowed(_) => 0,
std::borrow::Cow::Owned(ref b) => b.size_of(ops),
}
}
}
impl<T: MallocSizeOf> MallocSizeOf for [T] {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
#[cfg(feature = "servo")]
impl MallocShallowSizeOf for ByteBuf {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for ByteBuf {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T> MallocShallowSizeOf for Vec<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.as_ptr()) }
}
}
impl<T: MallocSizeOf> MallocSizeOf for Vec<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T> MallocShallowSizeOf for std::collections::VecDeque<T> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.has_malloc_enclosing_size_of() {
if let Some(front) = self.front() {
// The front element is an interior pointer.
unsafe { ops.malloc_enclosing_size_of(&*front) }
} else {
// This assumes that no memory is allocated when the VecDeque is empty.
0
}
} else {
// An estimate.
self.capacity() * size_of::<T>()
}
}
}
impl<T: MallocSizeOf> MallocSizeOf for std::collections::VecDeque<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<A: smallvec::Array> MallocShallowSizeOf for smallvec::SmallVec<A> {
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if self.spilled() {
unsafe { ops.malloc_size_of(self.as_ptr()) }
} else {
0
}
}
}
impl<A> MallocSizeOf for smallvec::SmallVec<A>
where A: smallvec::Array,
A::Item: MallocSizeOf
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for elem in self.iter() {
n += elem.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for std::collections::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.has_malloc_enclosing_size_of() {
// The first value from the iterator gives us an interior pointer.
// `ops.malloc_enclosing_size_of()` then gives us the storage size.
// This assumes that the `HashSet`'s contents (values and hashes)
// are all stored in a single contiguous heap allocation.
self.iter().next().map_or(0, |t| unsafe { ops.malloc_enclosing_size_of(t) })
} else {
// An estimate.
self.capacity() * (size_of::<T>() + size_of::<usize>())
}
}
}
impl<T, S> MallocSizeOf for std::collections::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for t in self.iter() {
n += t.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for hashglobe::hash_set::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.iter().next().map_or(0, |t| unsafe { ops.malloc_enclosing_size_of(t) })
} else {
self.capacity() * (size_of::<T>() + size_of::<usize>())
}
}
}
impl<T, S> MallocSizeOf for hashglobe::hash_set::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for t in self.iter() {
n += t.size_of(ops);
}
n
}
}
impl<T, S> MallocShallowSizeOf for hashglobe::fake::HashSet<T, S>
where T: Eq + Hash,
S: BuildHasher,
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().shallow_size_of(ops)
}
}
impl<T, S> MallocSizeOf for hashglobe::fake::HashSet<T, S>
where T: Eq + Hash + MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().size_of(ops)
}
}
impl<K, V, S> MallocShallowSizeOf for std::collections::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.values().next().map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) })
} else {
self.capacity() * (size_of::<V>() + size_of::<K>() + size_of::<usize>())
}
}
}
impl<K, V, S> MallocSizeOf for std::collections::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for (k, v) in self.iter() {
n += k.size_of(ops);
n += v.size_of(ops);
}
n
}
}
impl<K, V, S> MallocShallowSizeOf for hashglobe::hash_map::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
// See the implementation for std::collections::HashSet for details.
if ops.has_malloc_enclosing_size_of() {
self.values().next().map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) })
} else {
self.capacity() * (size_of::<V>() + size_of::<K>() + size_of::<usize>())
}
}
}
impl<K, V, S> MallocSizeOf for hashglobe::hash_map::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.shallow_size_of(ops);
for (k, v) in self.iter() {
n += k.size_of(ops);
n += v.size_of(ops);
}
n
}
}
impl<K, V, S> MallocShallowSizeOf for hashglobe::fake::HashMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher,
{
fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().shallow_size_of(ops)
}
}
impl<K, V, S> MallocSizeOf for hashglobe::fake::HashMap<K, V, S>
where K: Eq + Hash + MallocSizeOf,
V: MallocSizeOf,
S: BuildHasher,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use std::ops::Deref;
self.deref().size_of(ops)
}
}
// PhantomData is always 0.
impl<T> MallocSizeOf for std::marker::PhantomData<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
// XXX: we don't want MallocSizeOf to be defined for Rc and Arc. If negative
// trait bounds are ever allowed, this code should be uncommented.
// (We do have a compile-fail test for this:
// rc_arc_must_not_derive_malloc_size_of.rs)
//impl<T> !MallocSizeOf for Arc<T> { }
//impl<T> !MallocShallowSizeOf for Arc<T> { }
impl<T> MallocUnconditionalShallowSizeOf for servo_arc::Arc<T> {
fn unconditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
unsafe { ops.malloc_size_of(self.heap_ptr()) }
}
}
impl<T: MallocSizeOf> MallocUnconditionalSizeOf for servo_arc::Arc<T> {
fn unconditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.unconditional_shallow_size_of(ops) + (**self).size_of(ops)
}
}
impl<T> MallocConditionalShallowSizeOf for servo_arc::Arc<T> {
fn conditional_shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.have_seen_ptr(self.heap_ptr()) {
0
} else {
self.unconditional_shallow_size_of(ops)
}
}
}
impl<T: MallocSizeOf> MallocConditionalSizeOf for servo_arc::Arc<T> {
fn conditional_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if ops.have_seen_ptr(self.heap_ptr()) {
0
} else {
self.unconditional_size_of(ops)
}
}
}
/// If a mutex is stored directly as a member of a data type that is being measured,
/// it is the unique owner of its contents and deserves to be measured.
///
/// If a mutex is stored inside of an Arc value as a member of a data type that is being measured,
/// the Arc will not be automatically measured so there is no risk of overcounting the mutex's
/// contents.
impl<T: MallocSizeOf> MallocSizeOf for std::sync::Mutex<T> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
(*self.lock().unwrap()).size_of(ops)
}
}
impl MallocSizeOf for smallbitvec::SmallBitVec {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
if let Some(ptr) = self.heap_ptr() {
unsafe { ops.malloc_size_of(ptr) }
} else {
0
}
}
}
impl<T: MallocSizeOf, Unit> MallocSizeOf for euclid::Length<T, Unit> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedScale<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedPoint2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.x.size_of(ops) + self.y.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedRect<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.origin.size_of(ops) + self.size.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedSideOffsets2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.top.size_of(ops) + self.right.size_of(ops) +
self.bottom.size_of(ops) + self.left.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedSize2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.width.size_of(ops) + self.height.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedTransform2D<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.m11.size_of(ops) + self.m12.size_of(ops) +
self.m21.size_of(ops) + self.m22.size_of(ops) +
self.m31.size_of(ops) + self.m32.size_of(ops)
}
}
impl<T: MallocSizeOf, Src, Dst> MallocSizeOf for euclid::TypedTransform3D<T, Src, Dst> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.m11.size_of(ops) + self.m12.size_of(ops) +
self.m13.size_of(ops) + self.m14.size_of(ops) +
self.m21.size_of(ops) + self.m22.size_of(ops) +
self.m23.size_of(ops) + self.m24.size_of(ops) +
self.m31.size_of(ops) + self.m32.size_of(ops) +
self.m33.size_of(ops) + self.m34.size_of(ops) +
self.m41.size_of(ops) + self.m42.size_of(ops) +
self.m43.size_of(ops) + self.m44.size_of(ops)
}
}
impl<T: MallocSizeOf, U> MallocSizeOf for euclid::TypedVector2D<T, U> {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.x.size_of(ops) + self.y.size_of(ops)
}
}
impl MallocSizeOf for selectors::parser::AncestorHashes {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let selectors::parser::AncestorHashes { ref packed_hashes } = *self;
packed_hashes.size_of(ops)
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::parser::Selector<Impl>
where
Impl::NonTSPseudoClass: MallocSizeOf,
Impl::PseudoElement: MallocSizeOf,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
let mut n = 0;
// It's OK to measure this ThinArc directly because it's the
// "primary" reference. (The secondary references are on the
// Stylist.)
n += unsafe { ops.malloc_size_of(self.thin_arc_heap_ptr()) };
for component in self.iter_raw_match_order() {
n += component.size_of(ops);
}
n
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::parser::Component<Impl>
where
Impl::NonTSPseudoClass: MallocSizeOf,
Impl::PseudoElement: MallocSizeOf,
{
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
use selectors::parser::Component;
match self {
Component::AttributeOther(ref attr_selector) => {
attr_selector.size_of(ops)
}
Component::Negation(ref components) => {
components.size_of(ops)
}
Component::NonTSPseudoClass(ref pseudo) => {
(*pseudo).size_of(ops)
}
Component::Slotted(ref selector) |
Component::Host(Some(ref selector)) => {
selector.size_of(ops)
}
Component::PseudoElement(ref pseudo) => {
(*pseudo).size_of(ops)
}
Component::Combinator(..) |
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(..) |
Component::Namespace(..) |
Component::ExplicitUniversalType |
Component::LocalName(..) |
Component::ID(..) |
Component::Class(..) |
Component::AttributeInNoNamespaceExists { .. } |
Component::AttributeInNoNamespace { .. } |
Component::FirstChild |
Component::LastChild |
Component::OnlyChild |
Component::Root |
Component::Empty |
Component::Scope |
Component::NthChild(..) |
Component::NthLastChild(..) |
Component::NthOfType(..) |
Component::NthLastOfType(..) |
Component::FirstOfType |
Component::LastOfType |
Component::OnlyOfType |
Component::Host(None) => 0,
}
}
}
impl<Impl: selectors::parser::SelectorImpl> MallocSizeOf
for selectors::attr::AttrSelectorWithOptionalNamespace<Impl>
{
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
impl MallocSizeOf for Void {
#[inline]
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
void::unreachable(*self)
}
}
#[cfg(feature = "servo")]
impl<Static: string_cache::StaticAtomSet> MallocSizeOf for string_cache::Atom<Static> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
// This is measured properly by the heap measurement implemented in
// SpiderMonkey.
#[cfg(feature = "servo")]
impl<T: Copy + js::rust::GCMethods> MallocSizeOf for js::jsapi::Heap<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
/// For use on types where size_of() returns 0.
#[macro_export]
macro_rules! malloc_size_of_is_0(
($($ty:ty),+) => (
$(
impl $crate::MallocSizeOf for $ty {
#[inline(always)]
fn size_of(&self, _: &mut $crate::MallocSizeOfOps) -> usize {
0
}
}
)+
);
($($ty:ident<$($gen:ident),+>),+) => (
$(
impl<$($gen: $crate::MallocSizeOf),+> $crate::MallocSizeOf for $ty<$($gen),+> {
#[inline(always)]
fn size_of(&self, _: &mut $crate::MallocSizeOfOps) -> usize {
0
}
}
)+
);
);
malloc_size_of_is_0!(bool, char, str);
malloc_size_of_is_0!(u8, u16, u32, u64, u128, usize);
malloc_size_of_is_0!(i8, i16, i32, i64, i128, isize);
malloc_size_of_is_0!(f32, f64);
malloc_size_of_is_0!(std::sync::atomic::AtomicBool);
malloc_size_of_is_0!(std::sync::atomic::AtomicIsize, std::sync::atomic::AtomicUsize);
malloc_size_of_is_0!(Range<u8>, Range<u16>, Range<u32>, Range<u64>, Range<usize>);
malloc_size_of_is_0!(Range<i8>, Range<i16>, Range<i32>, Range<i64>, Range<isize>);
malloc_size_of_is_0!(Range<f32>, Range<f64>);
malloc_size_of_is_0!(app_units::Au);
malloc_size_of_is_0!(cssparser::RGBA, cssparser::TokenSerializationType);
#[cfg(feature = "url")]
impl MallocSizeOf for url::Host {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
url::Host::Domain(ref s) => s.size_of(ops),
_ => 0,
}
}
}
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderRadius);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderStyle);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BorderWidths);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::BoxShadowClipMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ClipAndScrollInfo);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ColorF);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ComplexClipRegion);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ExtendMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::FilterOp);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ExternalScrollId);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::FontInstanceKey);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::GradientStop);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::GlyphInstance);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::NinePatchBorder);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ImageKey);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ImageRendering);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::LineStyle);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::MixBlendMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::NormalBorder);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::RepeatMode);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::ScrollSensitivity);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::StickyOffsetBounds);
#[cfg(feature = "webrender_api")]
malloc_size_of_is_0!(webrender_api::TransformStyle);
#[cfg(feature = "servo")]
impl MallocSizeOf for xml5ever::QualName {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.prefix.size_of(ops) +
self.ns.size_of(ops) +
self.local.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::header::Headers {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.iter().fold(0, |acc, x| {
let name = x.name();
let raw = self.get_raw(name);
acc + raw.size_of(ops)
})
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::header::ContentType {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Mime {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops) +
self.1.size_of(ops) +
self.2.size_of(ops)
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Attr {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
hyper::mime::Attr::Ext(ref s) => s.size_of(ops),
_ => 0,
}
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::mime::Value {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
self.len() // Length of string value in bytes (not the char length of a string)!
}
}
#[cfg(feature = "servo")]
malloc_size_of_is_0!(time::Duration);
#[cfg(feature = "servo")]
malloc_size_of_is_0!(time::Tm);
#[cfg(feature = "servo")]
impl<T> MallocSizeOf for hyper_serde::Serde<T> where
for <'de> hyper_serde::De<T>: serde::Deserialize<'de>,
for <'a> hyper_serde::Ser<'a, T>: serde::Serialize,
T: MallocSizeOf {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
// Placeholder for unique case where internals of Sender cannot be measured.
// malloc size of is 0 macro complains about type supplied!
impl<T> MallocSizeOf for std::sync::mpsc::Sender<T> {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
#[cfg(feature = "servo")]
impl MallocSizeOf for hyper::status::StatusCode {
fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
match *self {
hyper::status::StatusCode::Unregistered(u) => u.size_of(ops),
_ => 0,
}
}
}
/// Measurable that defers to inner value and used to verify MallocSizeOf implementation in a
/// struct.
#[derive(Clone)]
pub struct Measurable<T: MallocSizeOf> (pub T);
impl<T: MallocSizeOf> Deref for Measurable<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: MallocSizeOf> DerefMut for Measurable<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Element nodes.
use devtools_traits::AttrInfo;
use dom::activation::Activatable;
use dom::attr::{Attr, AttrHelpersForLayout};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::ElementBinding;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type};
use dom::bindings::xmlname::XMLName::InvalidXMLName;
use dom::characterdata::CharacterData;
use dom::create::create_element;
use dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReaction};
use dom::document::{Document, LayoutDocumentHelpers};
use dom::documentfragment::DocumentFragment;
use dom::domrect::DOMRect;
use dom::domtokenlist::DOMTokenList;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers};
use dom::htmlbuttonelement::HTMLButtonElement;
use dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers};
use dom::htmlformelement::FormControlElementHelpers;
use dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers};
use dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods};
use dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers};
use dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers};
use dom::htmllabelelement::HTMLLabelElement;
use dom::htmllegendelement::HTMLLegendElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::htmlobjectelement::HTMLObjectElement;
use dom::htmloptgroupelement::HTMLOptGroupElement;
use dom::htmlselectelement::HTMLSelectElement;
use dom::htmlstyleelement::HTMLStyleElement;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers};
use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers};
use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers};
use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers};
use dom::htmltemplateelement::HTMLTemplateElement;
use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::namednodemap::NamedNodeMap;
use dom::node::{CLICK_IN_PROGRESS, ChildrenMutation, LayoutNodeHelpers, Node};
use dom::node::{NodeDamage, SEQUENTIALLY_FOCUSABLE, UnbindContext};
use dom::node::{document_from_node, window_from_node};
use dom::nodelist::NodeList;
use dom::promise::Promise;
use dom::servoparser::ServoParser;
use dom::text::Text;
use dom::validation::Validatable;
use dom::virtualmethods::{VirtualMethods, vtable_for};
use dom::window::ReflowReason;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace, QualName};
use html5ever::serialize;
use html5ever::serialize::SerializeOpts;
use html5ever::serialize::TraversalScope;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use js::jsapi::Heap;
use js::jsval::JSVal;
use net_traits::request::CorsSettings;
use ref_filter_map::ref_filter_map;
use script_layout_interface::message::ReflowGoal;
use script_thread::ScriptThread;
use selectors::Element as SelectorsElement;
use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
use selectors::matching::{ElementSelectorFlags, MatchingContext, MatchingMode, RelevantLinkStatus};
use selectors::matching::{HAS_EDGE_CHILD_SELECTOR, HAS_SLOW_SELECTOR, HAS_SLOW_SELECTOR_LATER_SIBLINGS};
use selectors::sink::Push;
use servo_arc::Arc;
use servo_atoms::Atom;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::cell::{Cell, Ref};
use std::default::Default;
use std::fmt;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use style::CaseSensitivityExt;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use style::context::QuirksMode;
use style::dom_apis;
use style::element_state::*;
use style::invalidation::element::restyle_hints::RESTYLE_SELF;
use style::properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, parse_style_attribute};
use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size, overflow_x};
use style::rule_tree::CascadeLevel;
use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser};
use style::selector_parser::extended_filtering;
use style::shared_lock::{SharedRwLock, Locked};
use style::thread_state;
use style::values::{CSSFloat, Either};
use style::values::{specified, computed};
use stylesheet_loader::StylesheetOwner;
use task::TaskOnce;
use xml5ever::serialize as xmlSerialize;
use xml5ever::serialize::SerializeOpts as XmlSerializeOpts;
use xml5ever::serialize::TraversalScope as XmlTraversalScope;
use xml5ever::serialize::TraversalScope::ChildrenOnly as XmlChildrenOnly;
use xml5ever::serialize::TraversalScope::IncludeNode as XmlIncludeNode;
// TODO: Update focus state when the top-level browsing context gains or loses system focus,
// and when the element enters or leaves a browsing context container.
// https://html.spec.whatwg.org/multipage/#selector-focus
#[dom_struct]
pub struct Element {
node: Node,
local_name: LocalName,
tag_name: TagName,
namespace: Namespace,
prefix: DomRefCell<Option<Prefix>>,
attrs: DomRefCell<Vec<Dom<Attr>>>,
id_attribute: DomRefCell<Option<Atom>>,
is: DomRefCell<Option<LocalName>>,
#[ignore_heap_size_of = "Arc"]
style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
attr_list: MutNullableDom<NamedNodeMap>,
class_list: MutNullableDom<DOMTokenList>,
state: Cell<ElementState>,
/// These flags are set by the style system to indicate the that certain
/// operations may require restyling this element or its descendants. The
/// flags are not atomic, so the style system takes care of only set them
/// when it has exclusive access to the element.
#[ignore_heap_size_of = "bitflags defined in rust-selectors"]
selector_flags: Cell<ElementSelectorFlags>,
/// https://html.spec.whatwg.org/multipage/#custom-element-reaction-queue
custom_element_reaction_queue: DomRefCell<Vec<CustomElementReaction>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-definition
#[ignore_heap_size_of = "Rc"]
custom_element_definition: DomRefCell<Option<Rc<CustomElementDefinition>>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-state
custom_element_state: Cell<CustomElementState>,
}
impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}", self.local_name)?;
if let Some(ref id) = *self.id_attribute.borrow() {
write!(f, " id={}", id)?;
}
write!(f, ">")
}
}
impl fmt::Debug for DomRoot<Element> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
#[derive(HeapSizeOf, PartialEq)]
pub enum ElementCreator {
ParserCreated(u64),
ScriptCreated,
}
pub enum CustomElementCreationMode {
Synchronous,
Asynchronous,
}
/// https://dom.spec.whatwg.org/#concept-element-custom-element-state
#[derive(Clone, Copy, Eq, HeapSizeOf, JSTraceable, PartialEq)]
pub enum CustomElementState {
Undefined,
Failed,
Uncustomized,
Custom,
}
impl ElementCreator {
pub fn is_parser_created(&self) -> bool {
match *self {
ElementCreator::ParserCreated(_) => true,
ElementCreator::ScriptCreated => false,
}
}
pub fn return_line_number(&self) -> u64 {
match *self {
ElementCreator::ParserCreated(l) => l,
ElementCreator::ScriptCreated => 1,
}
}
}
pub enum AdjacentPosition {
BeforeBegin,
AfterEnd,
AfterBegin,
BeforeEnd,
}
impl FromStr for AdjacentPosition {
type Err = Error;
fn from_str(position: &str) -> Result<Self, Self::Err> {
match_ignore_ascii_case! { &*position,
"beforebegin" => Ok(AdjacentPosition::BeforeBegin),
"afterbegin" => Ok(AdjacentPosition::AfterBegin),
"beforeend" => Ok(AdjacentPosition::BeforeEnd),
"afterend" => Ok(AdjacentPosition::AfterEnd),
_ => Err(Error::Syntax)
}
}
}
//
// Element methods
//
impl Element {
pub fn create(name: QualName,
is: Option<LocalName>,
document: &Document,
creator: ElementCreator,
mode: CustomElementCreationMode)
-> DomRoot<Element> {
create_element(name, is, document, creator, mode)
}
pub fn new_inherited(local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document) -> Element {
Element::new_inherited_with_state(ElementState::empty(), local_name,
namespace, prefix, document)
}
pub fn new_inherited_with_state(state: ElementState, local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document)
-> Element {
Element {
node: Node::new_inherited(document),
local_name: local_name,
tag_name: TagName::new(),
namespace: namespace,
prefix: DomRefCell::new(prefix),
attrs: DomRefCell::new(vec![]),
id_attribute: DomRefCell::new(None),
is: DomRefCell::new(None),
style_attribute: DomRefCell::new(None),
attr_list: Default::default(),
class_list: Default::default(),
state: Cell::new(state),
selector_flags: Cell::new(ElementSelectorFlags::empty()),
custom_element_reaction_queue: Default::default(),
custom_element_definition: Default::default(),
custom_element_state: Cell::new(CustomElementState::Uncustomized),
}
}
pub fn new(local_name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<Element> {
Node::reflect_node(
Box::new(Element::new_inherited(local_name, namespace, prefix, document)),
document,
ElementBinding::Wrap)
}
pub fn restyle(&self, damage: NodeDamage) {
let doc = self.node.owner_doc();
let mut restyle = doc.ensure_pending_restyle(self);
// FIXME(bholley): I think we should probably only do this for
// NodeStyleDamaged, but I'm preserving existing behavior.
restyle.hint.insert(RESTYLE_SELF);
if damage == NodeDamage::OtherNodeDamage {
restyle.damage = RestyleDamage::rebuild_and_reflow();
}
}
pub fn set_is(&self, is: LocalName) {
*self.is.borrow_mut() = Some(is);
}
pub fn get_is(&self) -> Option<LocalName> {
self.is.borrow().clone()
}
pub fn set_custom_element_state(&self, state: CustomElementState) {
self.custom_element_state.set(state);
}
pub fn get_custom_element_state(&self) -> CustomElementState {
self.custom_element_state.get()
}
pub fn set_custom_element_definition(&self, definition: Rc<CustomElementDefinition>) {
*self.custom_element_definition.borrow_mut() = Some(definition);
}
pub fn get_custom_element_definition(&self) -> Option<Rc<CustomElementDefinition>> {
(*self.custom_element_definition.borrow()).clone()
}
pub fn push_callback_reaction(&self, function: Rc<Function>, args: Box<[Heap<JSVal>]>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Callback(function, args));
}
pub fn push_upgrade_reaction(&self, definition: Rc<CustomElementDefinition>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Upgrade(definition));
}
pub fn clear_reaction_queue(&self) {
self.custom_element_reaction_queue.borrow_mut().clear();
}
pub fn invoke_reactions(&self) {
// TODO: This is not spec compliant, as this will allow some reactions to be processed
// after clear_reaction_queue has been called.
rooted_vec!(let mut reactions);
while !self.custom_element_reaction_queue.borrow().is_empty() {
mem::swap(&mut *reactions, &mut *self.custom_element_reaction_queue.borrow_mut());
for reaction in reactions.iter() {
reaction.invoke(self);
}
reactions.clear();
}
}
// https://drafts.csswg.org/cssom-view/#css-layout-box
// Elements that have a computed value of the display property
// that is table-column or table-column-group
// FIXME: Currently, it is assumed to be true always
fn has_css_layout_box(&self) -> bool {
true
}
// https://drafts.csswg.org/cssom-view/#potentially-scrollable
fn potentially_scrollable(&self) -> bool {
self.has_css_layout_box() &&
!self.overflow_x_is_visible() &&
!self.overflow_y_is_visible()
}
// used value of overflow-x is "visible"
fn overflow_x_is_visible(&self) -> bool {
let window = window_from_node(self);
let overflow_pair = window.overflow_query(self.upcast::<Node>().to_trusted_node_address());
overflow_pair.x == overflow_x::computed_value::T::visible
}
// used value of overflow-y is "visible"
fn overflow_y_is_visible(&self) -> bool {
let window = window_from_node(self);
let overflow_pair = window.overflow_query(self.upcast::<Node>().to_trusted_node_address());
overflow_pair.y != overflow_x::computed_value::T::visible
}
}
#[allow(unsafe_code)]
pub trait RawLayoutElementHelpers {
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue>;
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str>;
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue>;
}
#[inline]
#[allow(unsafe_code)]
pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName)
-> Option<LayoutDom<Attr>> {
// cast to point to T in RefCell<T> directly
let attrs = elem.attrs.borrow_for_layout();
attrs.iter().find(|attr| {
let attr = attr.to_layout();
*name == attr.local_name_atom_forever() &&
(*attr.unsafe_get()).namespace() == namespace
}).map(|attr| attr.to_layout())
}
#[allow(unsafe_code)]
impl RawLayoutElementHelpers for Element {
#[inline]
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_forever()
})
}
#[inline]
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_ref_forever()
})
}
#[inline]
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue> {
let attrs = self.attrs.borrow_for_layout();
attrs.iter().filter_map(|attr| {
let attr = attr.to_layout();
if *name == attr.local_name_atom_forever() {
Some(attr.value_forever())
} else {
None
}
}).collect()
}
}
pub trait LayoutElementHelpers {
#[allow(unsafe_code)]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
#[allow(unsafe_code)]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]>;
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: Push<ApplicableDeclarationBlock>;
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn html_element_in_html_document_for_layout(&self) -> bool;
fn id_attribute(&self) -> *const Option<Atom>;
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>>;
fn local_name(&self) -> &LocalName;
fn namespace(&self) -> &Namespace;
fn get_lang_for_layout(&self) -> String;
fn get_checked_state_for_layout(&self) -> bool;
fn get_indeterminate_state_for_layout(&self) -> bool;
fn get_state_for_layout(&self) -> ElementState;
fn insert_selector_flags(&self, flags: ElementSelectorFlags);
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
}
impl LayoutElementHelpers for LayoutDom<Element> {
#[allow(unsafe_code)]
#[inline]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value_tokens_forever().unwrap().iter().any(|atom| case_sensitivity.eq_atom(atom, name))
})
}
#[allow(unsafe_code)]
#[inline]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]> {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class"))
.map(|attr| attr.value_tokens_forever().unwrap())
}
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V)
where V: Push<ApplicableDeclarationBlock>
{
// FIXME(emilio): Just a single PDB should be enough.
#[inline]
fn from_declaration(shared_lock: &SharedRwLock, declaration: PropertyDeclaration)
-> ApplicableDeclarationBlock {
ApplicableDeclarationBlock::from_declarations(
Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
declaration, Importance::Normal
))),
CascadeLevel::PresHints)
}
let document = self.upcast::<Node>().owner_doc_for_layout();
let shared_lock = document.style_shared_lock();
let bgcolor = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableRowElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableSectionElement>() {
this.get_background_color()
} else {
None
};
if let Some(color) = bgcolor {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundColor(color.into())
));
}
let background = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background()
} else {
None
};
if let Some(url) = background {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundImage(
background_image::SpecifiedValue(vec![
Either::Second(specified::Image::for_cascade(url.into()))
]))));
}
let color = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_color()
} else if let Some(this) = self.downcast::<HTMLBodyElement>() {
// https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20
this.get_color()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5
this.get_color()
} else {
None
};
if let Some(color) = color {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Color(
longhands::color::SpecifiedValue(color.into())
)
));
}
let font_family = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_face()
} else {
None
};
if let Some(font_family) = font_family {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontFamily(
font_family::SpecifiedValue::Values(
font_family::computed_value::FontFamilyList::new(vec![
font_family::computed_value::FontFamily::from_atom(
font_family)])))));
}
let font_size = self.downcast::<HTMLFontElement>().and_then(|this| this.get_size());
if let Some(font_size) = font_size {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontSize(
font_size::SpecifiedValue::from_html_size(font_size as u8)
)
))
}
let cellspacing = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_cellspacing()
} else {
None
};
if let Some(cellspacing) = cellspacing {
let width_value = specified::Length::from_px(cellspacing as f32);
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderSpacing(
Box::new(border_spacing::SpecifiedValue::new(
width_value.clone().into(),
width_value.into()
))
)
));
}
let size = if let Some(this) = self.downcast::<HTMLInputElement>() {
// FIXME(pcwalton): More use of atoms, please!
match (*self.unsafe_get()).get_attr_val_for_layout(&ns!(), &local_name!("type")) {
// Not text entry widget
Some("hidden") | Some("date") | Some("month") | Some("week") |
Some("time") | Some("datetime-local") | Some("number") | Some("range") |
Some("color") | Some("checkbox") | Some("radio") | Some("file") |
Some("submit") | Some("image") | Some("reset") | Some("button") => {
None
},
// Others
_ => {
match this.size_for_layout() {
0 => None,
s => Some(s as i32),
}
},
}
} else {
None
};
if let Some(size) = size {
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(
specified::LengthOrPercentageOrAuto::Length(value))));
}
let width = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width
this.get_width()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_width()
} else {
LengthOrPercentageOrAuto::Auto
};
// FIXME(emilio): Use from_computed value here and below.
match width {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let width_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let width_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
}
let height = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_height()
} else {
LengthOrPercentageOrAuto::Auto
};
match height {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let height_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let height_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
}
let cols = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_cols() {
0 => None,
c => Some(c as i32),
}
} else {
None
};
if let Some(cols) = cols {
// TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but
// the math for <textarea> is a little different since we need to take
// scrollbar size into consideration (but we don't have a scrollbar yet!)
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-width
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value))));
}
let rows = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_rows() {
0 => None,
r => Some(r as i32),
}
} else {
None
};
if let Some(rows) = rows {
// TODO(mttr) This should take scrollbar size into consideration.
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-height
let value = specified::NoCalcLength::FontRelative(specified::FontRelativeLength::Em(rows as CSSFloat));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value))));
}
let border = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_border()
} else {
None
};
if let Some(border) = border {
let width_value = specified::BorderSideWidth::Length(specified::Length::from_px(border as f32));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderTopWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderLeftWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderBottomWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderRightWidth(width_value)));
}
}
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_colspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_rowspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[inline]
#[allow(unsafe_code)]
unsafe fn html_element_in_html_document_for_layout(&self) -> bool {
if (*self.unsafe_get()).namespace != ns!(html) {
return false;
}
self.upcast::<Node>().owner_doc_for_layout().is_html_document_for_layout()
}
#[allow(unsafe_code)]
fn id_attribute(&self) -> *const Option<Atom> {
unsafe {
(*self.unsafe_get()).id_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>> {
unsafe {
(*self.unsafe_get()).style_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn local_name(&self) -> &LocalName {
unsafe {
&(*self.unsafe_get()).local_name
}
}
#[allow(unsafe_code)]
fn namespace(&self) -> &Namespace {
unsafe {
&(*self.unsafe_get()).namespace
}
}
#[allow(unsafe_code)]
fn get_lang_for_layout(&self) -> String {
unsafe {
let mut current_node = Some(self.upcast::<Node>());
while let Some(node) = current_node {
current_node = node.parent_node_ref();
match node.downcast::<Element>().map(|el| el.unsafe_get()) {
Some(elem) => {
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) {
return attr.to_owned();
}
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(), &local_name!("lang")) {
return attr.to_owned();
}
}
None => continue
}
}
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
String::new()
}
}
#[inline]
#[allow(unsafe_code)]
fn get_checked_state_for_layout(&self) -> bool {
// TODO option and menuitem can also have a checked state.
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.checked_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_indeterminate_state_for_layout(&self) -> bool {
// TODO progress elements can also be matched with :indeterminate
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.indeterminate_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_state_for_layout(&self) -> ElementState {
unsafe {
(*self.unsafe_get()).state.get()
}
}
#[inline]
#[allow(unsafe_code)]
fn insert_selector_flags(&self, flags: ElementSelectorFlags) {
debug_assert!(thread_state::get().is_layout());
unsafe {
let f = &(*self.unsafe_get()).selector_flags;
f.set(f.get() | flags);
}
}
#[inline]
#[allow(unsafe_code)]
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool {
unsafe {
(*self.unsafe_get()).selector_flags.get().contains(flags)
}
}
}
impl Element {
pub fn html_element_in_html_document(&self) -> bool {
self.namespace == ns!(html) && self.upcast::<Node>().is_in_html_doc()
}
pub fn local_name(&self) -> &LocalName {
&self.local_name
}
pub fn parsed_name(&self, mut name: DOMString) -> LocalName {
if self.html_element_in_html_document() {
name.make_ascii_lowercase();
}
LocalName::from(name)
}
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
pub fn prefix(&self) -> Ref<Option<Prefix>> {
self.prefix.borrow()
}
pub fn set_prefix(&self, prefix: Option<Prefix>) {
*self.prefix.borrow_mut() = prefix;
}
pub fn attrs(&self) -> Ref<[Dom<Attr>]> {
Ref::map(self.attrs.borrow(), |attrs| &**attrs)
}
// Element branch of https://dom.spec.whatwg.org/#locate-a-namespace
pub fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace {
let prefix = prefix.map(String::from).map(LocalName::from);
let inclusive_ancestor_elements =
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast::<Self>);
// Steps 3-4.
for element in inclusive_ancestor_elements {
// Step 1.
if element.namespace() != &ns!() &&
element.prefix().as_ref().map(|p| &**p) == prefix.as_ref().map(|p| &**p)
{
return element.namespace().clone();
}
// Step 2.
let attr = ref_filter_map(self.attrs(), |attrs| {
attrs.iter().find(|attr| {
if attr.namespace() != &ns!(xmlns) {
return false;
}
match (attr.prefix(), prefix.as_ref()) {
(Some(&namespace_prefix!("xmlns")), Some(prefix)) => {
attr.local_name() == prefix
},
(None, None) => attr.local_name() == &local_name!("xmlns"),
_ => false,
}
})
});
if let Some(attr) = attr {
return (**attr.value()).into();
}
}
ns!()
}
pub fn style_attribute(&self) -> &DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>> {
&self.style_attribute
}
pub fn summarize(&self) -> Vec<AttrInfo> {
self.attrs.borrow().iter()
.map(|attr| attr.summarize())
.collect()
}
pub fn is_void(&self) -> bool {
if self.namespace != ns!(html) {
return false
}
match self.local_name {
/* List of void elements from
https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */
local_name!("area") | local_name!("base") | local_name!("basefont") |
local_name!("bgsound") | local_name!("br") |
local_name!("col") | local_name!("embed") | local_name!("frame") |
local_name!("hr") | local_name!("img") |
local_name!("input") | local_name!("keygen") | local_name!("link") |
local_name!("menuitem") | local_name!("meta") |
local_name!("param") | local_name!("source") | local_name!("track") |
local_name!("wbr") => true,
_ => false
}
}
pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match serialize(&mut writer,
&self.upcast::<Node>(),
SerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
// FIXME(ajeffrey): Directly convert UTF8 to DOMString
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn xmlSerialize(&self, traversal_scope: XmlTraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match xmlSerialize::serialize(&mut writer,
&self.upcast::<Node>(),
XmlSerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn root_element(&self) -> DomRoot<Element> {
if self.node.is_in_doc() {
self.upcast::<Node>()
.owner_doc()
.GetDocumentElement()
.unwrap()
} else {
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast)
.last()
.expect("We know inclusive_ancestors will return `self` which is an element")
}
}
// https://dom.spec.whatwg.org/#locate-a-namespace-prefix
pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> {
for node in self.upcast::<Node>().inclusive_ancestors() {
match node.downcast::<Element>() {
Some(element) => {
// Step 1.
if *element.namespace() == namespace {
if let Some(prefix) = element.GetPrefix() {
return Some(prefix);
}
}
// Step 2.
for attr in element.attrs.borrow().iter() {
if attr.prefix() == Some(&namespace_prefix!("xmlns")) &&
**attr.value() == *namespace {
return Some(attr.LocalName());
}
}
},
None => return None,
}
}
None
}
pub fn is_focusable_area(&self) -> bool {
if self.is_actually_disabled() {
return false;
}
// TODO: Check whether the element is being rendered (i.e. not hidden).
let node = self.upcast::<Node>();
if node.get_flag(SEQUENTIALLY_FOCUSABLE) {
return true;
}
// https://html.spec.whatwg.org/multipage/#specially-focusable
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
true
}
_ => false,
}
}
pub fn is_actually_disabled(&self) -> bool {
let node = self.upcast::<Node>();
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => {
self.disabled_state()
}
// TODO:
// an optgroup element that has a disabled attribute
// a menuitem element that has a disabled attribute
// a fieldset element that is a disabled fieldset
_ => false,
}
}
pub fn push_new_attribute(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>) {
let window = window_from_node(self);
let attr = Attr::new(&window,
local_name,
value,
name,
namespace,
prefix,
Some(self));
self.push_attribute(&attr);
}
pub fn push_attribute(&self, attr: &Attr) {
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let value = DOMString::from(&**attr.value());
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: value.clone(),
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
if self.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, None, Some(value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
assert!(attr.GetOwnerElement().r() == Some(self));
self.will_mutate_attr(attr);
self.attrs.borrow_mut().push(Dom::from_ref(attr));
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None));
}
}
pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.attrs
.borrow()
.iter()
.find(|attr| attr.local_name() == local_name && attr.namespace() == namespace)
.map(|js| DomRoot::from_ref(&**js))
}
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
pub fn get_attribute_by_name(&self, name: DOMString) -> Option<DomRoot<Attr>> {
let name = &self.parsed_name(name);
self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| DomRoot::from_ref(&**js))
}
pub fn set_attribute_from_parser(&self,
qname: QualName,
value: DOMString,
prefix: Option<Prefix>) {
// Don't set if the attribute already exists, so we can handle add_attrs_if_missing
if self.attrs
.borrow()
.iter()
.any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) {
return;
}
let name = match prefix {
None => qname.local.clone(),
Some(ref prefix) => {
let name = format!("{}:{}", &**prefix, &*qname.local);
LocalName::from(name)
},
};
let value = self.parse_attribute(&qname.ns, &qname.local, value);
self.push_new_attribute(qname.local, value, name, qname.ns, prefix);
}
pub fn set_attribute(&self, name: &LocalName, value: AttrValue) {
assert!(name == &name.to_ascii_lowercase());
assert!(!name.contains(":"));
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| attr.local_name() == name);
}
// https://html.spec.whatwg.org/multipage/#attr-data-*
pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if let InvalidXMLName = xml_name_type(&name) {
return Err(Error::InvalidCharacter);
}
// Steps 2-5.
let name = LocalName::from(name);
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| {
*attr.name() == name && *attr.namespace() == ns!()
});
Ok(())
}
fn set_first_matching_attribute<F>(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
find: F)
where F: Fn(&Attr) -> bool
{
let attr = self.attrs
.borrow()
.iter()
.find(|attr| find(&attr))
.map(|js| DomRoot::from_ref(&**js));
if let Some(attr) = attr {
attr.set_value(value, self);
} else {
self.push_new_attribute(local_name, value, name, namespace, prefix);
};
}
pub fn parse_attribute(&self,
namespace: &Namespace,
local_name: &LocalName,
value: DOMString)
-> AttrValue {
if *namespace == ns!() {
vtable_for(self.upcast()).parse_plain_attribute(local_name, value)
} else {
AttrValue::String(value.into())
}
}
pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| {
attr.namespace() == namespace && attr.local_name() == local_name
})
}
pub fn remove_attribute_by_name(&self, name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| attr.name() == name)
}
fn remove_first_matching_attribute<F>(&self, find: F) -> Option<DomRoot<Attr>>
where F: Fn(&Attr) -> bool {
let idx = self.attrs.borrow().iter().position(|attr| find(&attr));
idx.map(|idx| {
let attr = DomRoot::from_ref(&*(*self.attrs.borrow())[idx]);
self.will_mutate_attr(&attr);
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let old_value = DOMString::from(&**attr.value());
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), None, namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
self.attrs.borrow_mut().remove(idx);
attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Removed);
}
attr
})
}
pub fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.get_attribute(&ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value().as_tokens().iter().any(|atom| case_sensitivity.eq_atom(name, atom))
})
}
pub fn set_atomic_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
let value = AttrValue::from_atomic(value.into());
self.set_attribute(local_name, value);
}
pub fn has_attribute(&self, local_name: &LocalName) -> bool {
assert!(local_name.bytes().all(|b| b.to_ascii_lowercase() == b));
self.attrs
.borrow()
.iter()
.any(|attr| attr.local_name() == local_name && attr.namespace() == &ns!())
}
pub fn set_bool_attribute(&self, local_name: &LocalName, value: bool) {
if self.has_attribute(local_name) == value {
return;
}
if value {
self.set_string_attribute(local_name, DOMString::new());
} else {
self.remove_attribute(&ns!(), local_name);
}
}
pub fn get_url_attribute(&self, local_name: &LocalName) -> DOMString {
assert!(*local_name == local_name.to_ascii_lowercase());
let attr = match self.get_attribute(&ns!(), local_name) {
Some(attr) => attr,
None => return DOMString::new(),
};
let value = &**attr.value();
// XXXManishearth this doesn't handle `javascript:` urls properly
let base = document_from_node(self).base_url();
let value = base.join(value)
.map(|parsed| parsed.into_string())
.unwrap_or_else(|_| value.to_owned());
DOMString::from(value)
}
pub fn get_string_attribute(&self, local_name: &LocalName) -> DOMString {
match self.get_attribute(&ns!(), local_name) {
Some(x) => x.Value(),
None => DOMString::new(),
}
}
pub fn set_string_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::String(value.into()));
}
pub fn get_tokenlist_attribute(&self, local_name: &LocalName) -> Vec<Atom> {
self.get_attribute(&ns!(), local_name).map(|attr| {
attr.value()
.as_tokens()
.to_vec()
}).unwrap_or(vec!())
}
pub fn set_tokenlist_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name,
AttrValue::from_serialized_tokenlist(value.into()));
}
pub fn set_atomic_tokenlist_attribute(&self, local_name: &LocalName, tokens: Vec<Atom>) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::from_atomic_tokens(tokens));
}
pub fn get_int_attribute(&self, local_name: &LocalName, default: i32) -> i32 {
// TODO: Is this assert necessary?
assert!(local_name.chars().all(|ch| {
!ch.is_ascii() || ch.to_ascii_lowercase() == ch
}));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::Int(_, value) => value,
_ => panic!("Expected an AttrValue::Int: \
implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_int_attribute(&self, local_name: &LocalName, value: i32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::Int(value.to_string(), value));
}
pub fn get_uint_attribute(&self, local_name: &LocalName, default: u32) -> u32 {
assert!(local_name.chars().all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::UInt(_, value) => value,
_ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_uint_attribute(&self, local_name: &LocalName, value: u32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::UInt(value.to_string(), value));
}
pub fn will_mutate_attr(&self, attr: &Attr) {
let node = self.upcast::<Node>();
node.owner_doc().element_attr_will_change(self, attr);
}
// https://dom.spec.whatwg.org/#insert-adjacent
pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node)
-> Fallible<Option<DomRoot<Node>>> {
let self_node = self.upcast::<Node>();
match where_ {
AdjacentPosition::BeforeBegin => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, Some(self_node)).map(Some)
} else {
Ok(None)
}
}
AdjacentPosition::AfterBegin => {
Node::pre_insert(node, &self_node, self_node.GetFirstChild().r()).map(Some)
}
AdjacentPosition::BeforeEnd => {
Node::pre_insert(node, &self_node, None).map(Some)
}
AdjacentPosition::AfterEnd => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, self_node.GetNextSibling().r()).map(Some)
} else {
Ok(None)
}
}
}
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
pub fn scroll(&self, x_: f64, y_: f64, behavior: ScrollBehavior) {
// Step 1.2 or 2.3
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(x, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, y, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, x, y, behavior);
}
// https://w3c.github.io/DOM-Parsing/#parsing
pub fn parse_fragment(&self, markup: DOMString) -> Fallible<DomRoot<DocumentFragment>> {
// Steps 1-2.
let context_document = document_from_node(self);
// TODO(#11995): XML case.
let new_children = ServoParser::parse_html_fragment(self, markup);
// Step 3.
let fragment = DocumentFragment::new(&context_document);
// Step 4.
for child in new_children {
fragment.upcast::<Node>().AppendChild(&child).unwrap();
}
// Step 5.
Ok(fragment)
}
pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> DomRoot<Self> {
match element {
Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => {
DomRoot::from_ref(elem)
},
_ => {
DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc))
}
}
}
// https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check
pub fn fullscreen_element_ready_check(&self) -> bool {
if !self.is_connected() {
return false
}
let document = document_from_node(self);
document.get_allow_fullscreen()
}
// https://html.spec.whatwg.org/multipage/#home-subtree
pub fn is_in_same_home_subtree<T>(&self, other: &T) -> bool
where T: DerivedFrom<Element> + DomObject
{
let other = other.upcast::<Element>();
self.root_element() == other.root_element()
}
}
impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
Node::namespace_to_string(self.namespace.clone())
}
// https://dom.spec.whatwg.org/#dom-element-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): Convert directly from LocalName to DOMString
DOMString::from(&*self.local_name)
}
// https://dom.spec.whatwg.org/#dom-element-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix.borrow().as_ref().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-element-tagname
fn TagName(&self) -> DOMString {
let name = self.tag_name.or_init(|| {
let qualified_name = match *self.prefix.borrow() {
Some(ref prefix) => {
Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name))
},
None => Cow::Borrowed(&*self.local_name)
};
if self.html_element_in_html_document() {
LocalName::from(qualified_name.to_ascii_uppercase())
} else {
LocalName::from(qualified_name)
}
});
DOMString::from(&*name)
}
// https://dom.spec.whatwg.org/#dom-element-id
fn Id(&self) -> DOMString {
self.get_string_attribute(&local_name!("id"))
}
// https://dom.spec.whatwg.org/#dom-element-id
fn SetId(&self, id: DOMString) {
self.set_atomic_attribute(&local_name!("id"), id);
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn ClassName(&self) -> DOMString {
self.get_string_attribute(&local_name!("class"))
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn SetClassName(&self, class: DOMString) {
self.set_tokenlist_attribute(&local_name!("class"), class);
}
// https://dom.spec.whatwg.org/#dom-element-classlist
fn ClassList(&self) -> DomRoot<DOMTokenList> {
self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class")))
}
// https://dom.spec.whatwg.org/#dom-element-attributes
fn Attributes(&self) -> DomRoot<NamedNodeMap> {
self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self))
}
// https://dom.spec.whatwg.org/#dom-element-hasattributes
fn HasAttributes(&self) -> bool {
!self.attrs.borrow().is_empty()
}
// https://dom.spec.whatwg.org/#dom-element-getattributenames
fn GetAttributeNames(&self) -> Vec<DOMString> {
self.attrs.borrow().iter().map(|attr| attr.Name()).collect()
}
// https://dom.spec.whatwg.org/#dom-element-getattribute
fn GetAttribute(&self, name: DOMString) -> Option<DOMString> {
self.GetAttributeNode(name)
.map(|s| s.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributens
fn GetAttributeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DOMString> {
self.GetAttributeNodeNS(namespace, local_name)
.map(|attr| attr.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributenode
fn GetAttributeNode(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-element-getattributenodens
fn GetAttributeNodeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DomRoot<Attr>> {
let namespace = &namespace_from_domstring(namespace);
self.get_attribute(namespace, &LocalName::from(local_name))
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if xml_name_type(&name) == InvalidXMLName {
return Err(Error::InvalidCharacter);
}
// Step 2.
let name = self.parsed_name(name);
// Step 3-5.
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(
name.clone(), value, name.clone(), ns!(), None,
|attr| *attr.name() == name);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributens
fn SetAttributeNS(&self,
namespace: Option<DOMString>,
qualified_name: DOMString,
value: DOMString) -> ErrorResult {
let (namespace, prefix, local_name) =
validate_and_extract(namespace, &qualified_name)?;
let qualified_name = LocalName::from(qualified_name);
let value = self.parse_attribute(&namespace, &local_name, value);
self.set_first_matching_attribute(
local_name.clone(), value, qualified_name, namespace.clone(), prefix,
|attr| *attr.local_name() == local_name && *attr.namespace() == namespace);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributenode
fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
// Step 1.
if let Some(owner) = attr.GetOwnerElement() {
if &*owner != self {
return Err(Error::InUseAttribute);
}
}
let vtable = vtable_for(self.upcast());
// This ensures that the attribute is of the expected kind for this
// specific element. This is inefficient and should probably be done
// differently.
attr.swap_value(
&mut vtable.parse_plain_attribute(attr.local_name(), attr.Value()),
);
// Step 2.
let position = self.attrs.borrow().iter().position(|old_attr| {
attr.namespace() == old_attr.namespace() && attr.local_name() == old_attr.local_name()
});
if let Some(position) = position {
let old_attr = DomRoot::from_ref(&*self.attrs.borrow()[position]);
// Step 3.
if &*old_attr == attr {
return Ok(Some(DomRoot::from_ref(attr)));
}
// Step 4.
if self.get_custom_element_definition().is_some() {
let old_name = old_attr.local_name().clone();
let old_value = DOMString::from(&**old_attr.value());
let new_value = DOMString::from(&**attr.value());
let namespace = old_attr.namespace().clone();
let reaction = CallbackReaction::AttributeChanged(old_name, Some(old_value),
Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
self.will_mutate_attr(attr);
attr.set_owner(Some(self));
self.attrs.borrow_mut()[position] = Dom::from_ref(attr);
old_attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable.attribute_mutated(
&attr, AttributeMutation::Set(Some(&old_attr.value())));
}
// Step 6.
Ok(Some(old_attr))
} else {
// Step 5.
attr.set_owner(Some(self));
self.push_attribute(attr);
// Step 6.
Ok(None)
}
}
// https://dom.spec.whatwg.org/#dom-element-setattributenodens
fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
self.SetAttributeNode(attr)
}
// https://dom.spec.whatwg.org/#dom-element-removeattribute
fn RemoveAttribute(&self, name: DOMString) {
let name = self.parsed_name(name);
self.remove_attribute_by_name(&name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributens
fn RemoveAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) {
let namespace = namespace_from_domstring(namespace);
let local_name = LocalName::from(local_name);
self.remove_attribute(&namespace, &local_name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributenode
fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<DomRoot<Attr>> {
self.remove_first_matching_attribute(|a| a == attr)
.ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-element-hasattribute
fn HasAttribute(&self, name: DOMString) -> bool {
self.GetAttribute(name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-hasattributens
fn HasAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> bool {
self.GetAttributeNS(namespace, local_name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagname
fn GetElementsByTagName(&self, localname: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname))
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens
fn GetElementsByTagNameNS(&self,
maybe_ns: Option<DOMString>,
localname: DOMString)
-> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns)
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_class_name(&window, self.upcast(), classes)
}
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
fn GetClientRects(&self) -> Vec<DomRoot<DOMRect>> {
let win = window_from_node(self);
let raw_rects = self.upcast::<Node>().content_boxes();
raw_rects.iter().map(|rect| {
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}).collect()
}
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
fn GetBoundingClientRect(&self) -> DomRoot<DOMRect> {
let win = window_from_node(self);
let rect = self.upcast::<Node>().bounding_content_box_or_zero();
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll(&self, options: &ScrollToOptions) {
// Step 1
let left = options.left.unwrap_or(self.ScrollLeft());
let top = options.top.unwrap_or(self.ScrollTop());
self.scroll(left, top, options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll_(&self, x: f64, y: f64) {
self.scroll(x, y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo(&self, options: &ScrollToOptions) {
self.Scroll(options);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo_(&self, x: f64, y: f64) {
self.Scroll_(x, y);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy(&self, options: &ScrollToOptions) {
// Step 2
let delta_left = options.left.unwrap_or(0.0f64);
let delta_top = options.top.unwrap_or(0.0f64);
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + delta_left, top + delta_top,
options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy_(&self, x: f64, y: f64) {
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + x, top + y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollTop(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return 0.0;
}
// Step 6
return win.ScrollY() as f64;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollY() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.y.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn SetScrollTop(&self, y_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(win.ScrollX() as f64, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(win.ScrollX() as f64, y, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, self.ScrollLeft(), y, behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollLeft(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
// Step 6
return win.ScrollX() as f64;
}
return 0.0;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollX() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.x.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollleft
fn SetScrollLeft(&self, x_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return;
}
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, x, self.ScrollTop(), behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth
fn ScrollWidth(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollheight
fn ScrollHeight(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.height
}
// https://drafts.csswg.org/cssom-view/#dom-element-clienttop
fn ClientTop(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.y
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientleft
fn ClientLeft(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.x
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientwidth
fn ClientWidth(&self) -> i32 {
self.upcast::<Node>().client_rect().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientheight
fn ClientHeight(&self) -> i32 {
self.upcast::<Node>().client_rect().size.height
}
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
fn GetInnerHTML(&self) -> Fallible<DOMString> {
let qname = QualName::new(self.prefix().clone(),
self.namespace().clone(),
self.local_name().clone());
if document_from_node(self).is_html_document() {
return self.serialize(ChildrenOnly(Some(qname)));
} else {
return self.xmlSerialize(XmlChildrenOnly(Some(qname)));
}
}
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
fn SetInnerHTML(&self, value: DOMString) -> ErrorResult {
// Step 1.
let frag = self.parse_fragment(value)?;
// Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
DomRoot::upcast(template.Content())
} else {
DomRoot::from_ref(self.upcast())
};
Node::replace_all(Some(frag.upcast()), &target);
Ok(())
}
// https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML
fn GetOuterHTML(&self) -> Fallible<DOMString> {
if document_from_node(self).is_html_document() {
return self.serialize(IncludeNode);
} else {
return self.xmlSerialize(XmlIncludeNode);
}
}
// https://w3c.github.io/DOM-Parsing/#dom-element-outerhtml
fn SetOuterHTML(&self, value: DOMString) -> ErrorResult {
let context_document = document_from_node(self);
let context_node = self.upcast::<Node>();
// Step 1.
let context_parent = match context_node.GetParentNode() {
None => {
// Step 2.
return Ok(());
},
Some(parent) => parent,
};
let parent = match context_parent.type_id() {
// Step 3.
NodeTypeId::Document(_) => return Err(Error::NoModificationAllowed),
// Step 4.
NodeTypeId::DocumentFragment => {
let body_elem = Element::create(QualName::new(None, ns!(html), local_name!("body")),
None,
&context_document,
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous);
DomRoot::upcast(body_elem)
},
_ => context_node.GetParentElement().unwrap()
};
// Step 5.
let frag = parent.parse_fragment(value)?;
// Step 6.
context_parent.ReplaceChild(frag.upcast(), context_node)?;
Ok(())
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::children(&window, self.upcast())
}
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().child_elements().next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
fn ChildElementCount(&self) -> u32 {
self.upcast::<Node>().child_elements().count() as u32
}
// https://dom.spec.whatwg.org/#dom-parentnode-prepend
fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().prepend(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-append
fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().append(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let root = self.upcast::<Node>();
root.query_selector(selectors)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> {
let root = self.upcast::<Node>();
root.query_selector_all(selectors)
}
// https://dom.spec.whatwg.org/#dom-childnode-before
fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().before(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().after(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-replacewith
fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().replace_with(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) {
self.upcast::<Node>().remove_self();
}
// https://dom.spec.whatwg.org/#dom-element-matches
fn Matches(&self, selectors: DOMString) -> Fallible<bool> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
let element = DomRoot::from_ref(self);
Ok(dom_apis::element_matches(&element, &selectors, quirks_mode))
}
// https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector
fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> {
self.Matches(selectors)
}
// https://dom.spec.whatwg.org/#dom-element-closest
fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
Ok(dom_apis::element_closest(
DomRoot::from_ref(self),
&selectors,
quirks_mode,
))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
fn InsertAdjacentElement(&self, where_: DOMString, element: &Element)
-> Fallible<Option<DomRoot<Element>>> {
let where_ = where_.parse::<AdjacentPosition>()?;
let inserted_node = self.insert_adjacent(where_, element.upcast())?;
Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap()))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
fn InsertAdjacentText(&self, where_: DOMString, data: DOMString)
-> ErrorResult {
// Step 1.
let text = Text::new(data, &document_from_node(self));
// Step 2.
let where_ = where_.parse::<AdjacentPosition>()?;
self.insert_adjacent(where_, text.upcast()).map(|_| ())
}
// https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml
fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString)
-> ErrorResult {
// Step 1.
let position = position.parse::<AdjacentPosition>()?;
let context = match position {
AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
match self.upcast::<Node>().GetParentNode() {
Some(ref node) if node.is::<Document>() => {
return Err(Error::NoModificationAllowed)
}
None => return Err(Error::NoModificationAllowed),
Some(node) => node,
}
}
AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
DomRoot::from_ref(self.upcast::<Node>())
}
};
// Step 2.
let context = Element::fragment_parsing_context(
&context.owner_doc(), context.downcast::<Element>());
// Step 3.
let fragment = context.parse_fragment(text)?;
// Step 4.
self.insert_adjacent(position, fragment.upcast()).map(|_| ())
}
// check-tidy: no specs after this line
fn EnterFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.enter_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
fn ExitFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.exit_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
// https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
#[allow(unrooted_must_root)]
fn RequestFullscreen(&self) -> Rc<Promise> {
let doc = document_from_node(self);
doc.enter_fullscreen(self)
}
}
impl VirtualMethods for Element {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<Node>() as &VirtualMethods)
}
fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
// FIXME: This should be more fine-grained, not all elements care about these.
if attr.local_name() == &local_name!("width") ||
attr.local_name() == &local_name!("height") {
return true;
}
self.super_type().unwrap().attribute_affects_presentational_hints(attr)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
let node = self.upcast::<Node>();
let doc = node.owner_doc();
match attr.local_name() {
&local_name!("style") => {
// Modifying the `style` attribute might change style.
*self.style_attribute.borrow_mut() = match mutation {
AttributeMutation::Set(..) => {
// This is the fast path we use from
// CSSStyleDeclaration.
//
// Juggle a bit to keep the borrow checker happy
// while avoiding the extra clone.
let is_declaration = match *attr.value() {
AttrValue::Declaration(..) => true,
_ => false,
};
let block = if is_declaration {
let mut value = AttrValue::String(String::new());
attr.swap_value(&mut value);
let (serialization, block) = match value {
AttrValue::Declaration(s, b) => (s, b),
_ => unreachable!(),
};
let mut value = AttrValue::String(serialization);
attr.swap_value(&mut value);
block
} else {
let win = window_from_node(self);
Arc::new(doc.style_shared_lock().wrap(parse_style_attribute(
&attr.value(),
&doc.base_url(),
win.css_error_reporter(),
doc.quirks_mode())))
};
Some(block)
}
AttributeMutation::Removed => {
None
}
};
},
&local_name!("id") => {
*self.id_attribute.borrow_mut() =
mutation.new_value(attr).and_then(|value| {
let value = value.as_atom();
if value != &atom!("") {
Some(value.clone())
} else {
None
}
});
if node.is_in_doc() {
let value = attr.value().as_atom().clone();
match mutation {
AttributeMutation::Set(old_value) => {
if let Some(old_value) = old_value {
let old_value = old_value.as_atom().clone();
doc.unregister_named_element(self, old_value);
}
if value != atom!("") {
doc.register_named_element(self, value);
}
},
AttributeMutation::Removed => {
if value != atom!("") {
doc.unregister_named_element(self, value);
}
}
}
}
},
_ => {
// FIXME(emilio): This is pretty dubious, and should be done in
// the relevant super-classes.
if attr.namespace() == &ns!() &&
attr.local_name() == &local_name!("src") {
node.dirty(NodeDamage::OtherNodeDamage);
}
},
};
// Make sure we rev the version even if we didn't dirty the node. If we
// don't do this, various attribute-dependent htmlcollections (like those
// generated by getElementsByClassName) might become stale.
node.rev_version();
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("id") => AttrValue::from_atomic(value.into()),
&local_name!("class") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if let Some(f) = self.as_maybe_form_control() {
f.bind_form_control_to_tree();
}
if !tree_in_doc {
return;
}
let doc = document_from_node(self);
if let Some(ref value) = *self.id_attribute.borrow() {
doc.register_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.increment_dom_count();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
if let Some(f) = self.as_maybe_form_control() {
f.unbind_form_control_from_tree();
}
if !context.tree_in_doc {
return;
}
let doc = document_from_node(self);
let fullscreen = doc.GetFullscreenElement();
if fullscreen.r() == Some(self) {
doc.exit_fullscreen();
}
if let Some(ref value) = *self.id_attribute.borrow() {
doc.unregister_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.decrement_dom_count();
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
let flags = self.selector_flags.get();
if flags.intersects(HAS_SLOW_SELECTOR) {
// All children of this node need to be restyled when any child changes.
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
} else {
if flags.intersects(HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
if let Some(next_child) = mutation.next_child() {
for child in next_child.inclusively_following_siblings() {
if child.is::<Element>() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
if flags.intersects(HAS_EDGE_CHILD_SELECTOR) {
if let Some(child) = mutation.modified_edge_element() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
fn adopting_steps(&self, old_doc: &Document) {
self.super_type().unwrap().adopting_steps(old_doc);
if document_from_node(self).is_html_document() != old_doc.is_html_document() {
self.tag_name.clear();
}
}
}
impl<'a> SelectorsElement for DomRoot<Element> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.reflector().get_jsobject().get())
}
fn parent_element(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().GetParentElement()
}
fn match_pseudo_element(&self,
_pseudo: &PseudoElement,
_context: &mut MatchingContext)
-> bool
{
false
}
fn first_child_element(&self) -> Option<DomRoot<Element>> {
self.node.child_elements().next()
}
fn last_child_element(&self) -> Option<DomRoot<Element>> {
self.node.rev_children().filter_map(DomRoot::downcast).next()
}
fn prev_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.preceding_siblings().filter_map(DomRoot::downcast).next()
}
fn next_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.following_siblings().filter_map(DomRoot::downcast).next()
}
fn attr_matches(&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&String>)
-> bool {
match *ns {
NamespaceConstraint::Specific(ref ns) => {
self.get_attribute(ns, local_name)
.map_or(false, |attr| attr.value().eval_selector(operation))
}
NamespaceConstraint::Any => {
self.attrs.borrow().iter().any(|attr| {
attr.local_name() == local_name &&
attr.value().eval_selector(operation)
})
}
}
}
fn is_root(&self) -> bool {
match self.node.GetParentNode() {
None => false,
Some(node) => node.is::<Document>(),
}
}
fn is_empty(&self) -> bool {
self.node.children().all(|node| !node.is::<Element>() && match node.downcast::<Text>() {
None => true,
Some(text) => text.upcast::<CharacterData>().data().is_empty()
})
}
fn get_local_name(&self) -> &LocalName {
self.local_name()
}
fn get_namespace(&self) -> &Namespace {
self.namespace()
}
fn match_non_ts_pseudo_class<F>(&self,
pseudo_class: &NonTSPseudoClass,
_: &mut MatchingContext,
_: &RelevantLinkStatus,
_: &mut F)
-> bool
where F: FnMut(&Self, ElementSelectorFlags),
{
match *pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::Link |
NonTSPseudoClass::AnyLink => self.is_link(),
NonTSPseudoClass::Visited => false,
NonTSPseudoClass::ServoNonZeroBorder => {
match self.downcast::<HTMLTableElement>() {
None => false,
Some(this) => {
match this.get_border() {
None | Some(0) => false,
Some(_) => true,
}
}
}
},
NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => {
self.get_attribute(&ns!(), &local_name!("type"))
.map_or(false, |attr| attr.value().eq(expected_value))
}
// FIXME(heycam): This is wrong, since extended_filtering accepts
// a string containing commas (separating each language tag in
// a list) but the pseudo-class instead should be parsing and
// storing separate <ident> or <string>s for each language tag.
NonTSPseudoClass::Lang(ref lang) => extended_filtering(&*self.get_lang(), &*lang),
NonTSPseudoClass::ReadOnly =>
!Element::state(self).contains(pseudo_class.state_flag()),
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::Indeterminate |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::PlaceholderShown |
NonTSPseudoClass::Target =>
Element::state(self).contains(pseudo_class.state_flag()),
}
}
fn is_link(&self) -> bool {
// FIXME: This is HTML only.
let node = self.upcast::<Node>();
match node.type_id() {
// https://html.spec.whatwg.org/multipage/#selector-link
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => {
self.has_attribute(&local_name!("href"))
},
_ => false,
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.id_attribute.borrow().as_ref().map_or(false, |atom| case_sensitivity.eq_atom(id, atom))
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
Element::has_class(&**self, name, case_sensitivity)
}
fn is_html_element_in_html_document(&self) -> bool {
self.html_element_in_html_document()
}
}
impl Element {
pub fn as_maybe_activatable(&self) -> Option<&Activatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => {
let element = self.downcast::<HTMLAnchorElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => {
let element = self.downcast::<HTMLLabelElement>().unwrap();
Some(element as &Activatable)
},
_ => {
None
}
};
element.and_then(|elem| {
if elem.is_instance_activatable() {
Some(elem)
} else {
None
}
})
}
pub fn as_stylesheet_owner(&self) -> Option<&StylesheetOwner> {
if let Some(s) = self.downcast::<HTMLStyleElement>() {
return Some(s as &StylesheetOwner)
}
if let Some(l) = self.downcast::<HTMLLinkElement>() {
return Some(l as &StylesheetOwner)
}
None
}
// https://html.spec.whatwg.org/multipage/#category-submit
pub fn as_maybe_validatable(&self) -> Option<&Validatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => {
let element = self.downcast::<HTMLObjectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => {
let element = self.downcast::<HTMLSelectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
let element = self.downcast::<HTMLTextAreaElement>().unwrap();
Some(element as &Validatable)
},
_ => {
None
}
};
element
}
pub fn click_in_progress(&self) -> bool {
self.upcast::<Node>().get_flag(CLICK_IN_PROGRESS)
}
pub fn set_click_in_progress(&self, click: bool) {
self.upcast::<Node>().set_flag(CLICK_IN_PROGRESS, click)
}
// https://html.spec.whatwg.org/multipage/#nearest-activatable-element
pub fn nearest_activable_element(&self) -> Option<DomRoot<Element>> {
match self.as_maybe_activatable() {
Some(el) => Some(DomRoot::from_ref(el.as_element())),
None => {
let node = self.upcast::<Node>();
for node in node.ancestors() {
if let Some(node) = node.downcast::<Element>() {
if node.as_maybe_activatable().is_some() {
return Some(DomRoot::from_ref(node));
}
}
}
None
}
}
}
/// Please call this method *only* for real click events
///
/// https://html.spec.whatwg.org/multipage/#run-authentic-click-activation-steps
///
/// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks.
/// If the spec says otherwise, check with Manishearth first
pub fn authentic_click_activation(&self, event: &Event) {
// Not explicitly part of the spec, however this helps enforce the invariants
// required to save state between pre-activation and post-activation
// since we cannot nest authentic clicks (unlike synthetic click activation, where
// the script can generate more click events from the handler)
assert!(!self.click_in_progress());
let target = self.upcast();
// Step 2 (requires canvas support)
// Step 3
self.set_click_in_progress(true);
// Step 4
let e = self.nearest_activable_element();
match e {
Some(ref el) => match el.as_maybe_activatable() {
Some(elem) => {
// Step 5-6
elem.pre_click_activation();
event.fire(target);
if !event.DefaultPrevented() {
// post click activation
elem.activation_behavior(event, target);
} else {
elem.canceled_activation();
}
}
// Step 6
None => {
event.fire(target);
}
},
// Step 6
None => {
event.fire(target);
}
}
// Step 7
self.set_click_in_progress(false);
}
// https://html.spec.whatwg.org/multipage/#language
pub fn get_lang(&self) -> String {
self.upcast::<Node>().inclusive_ancestors().filter_map(|node| {
node.downcast::<Element>().and_then(|el| {
el.get_attribute(&ns!(xml), &local_name!("lang")).or_else(|| {
el.get_attribute(&ns!(), &local_name!("lang"))
}).map(|attr| String::from(attr.Value()))
})
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
}).next().unwrap_or(String::new())
}
pub fn state(&self) -> ElementState {
self.state.get()
}
pub fn set_state(&self, which: ElementState, value: bool) {
let mut state = self.state.get();
if state.contains(which) == value {
return;
}
let node = self.upcast::<Node>();
node.owner_doc().element_state_will_change(self);
if value {
state.insert(which);
} else {
state.remove(which);
}
self.state.set(state);
}
pub fn active_state(&self) -> bool {
self.state.get().contains(IN_ACTIVE_STATE)
}
/// https://html.spec.whatwg.org/multipage/#concept-selector-active
pub fn set_active_state(&self, value: bool) {
self.set_state(IN_ACTIVE_STATE, value);
if let Some(parent) = self.upcast::<Node>().GetParentElement() {
parent.set_active_state(value);
}
}
pub fn focus_state(&self) -> bool {
self.state.get().contains(IN_FOCUS_STATE)
}
pub fn set_focus_state(&self, value: bool) {
self.set_state(IN_FOCUS_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
pub fn hover_state(&self) -> bool {
self.state.get().contains(IN_HOVER_STATE)
}
pub fn set_hover_state(&self, value: bool) {
self.set_state(IN_HOVER_STATE, value)
}
pub fn enabled_state(&self) -> bool {
self.state.get().contains(IN_ENABLED_STATE)
}
pub fn set_enabled_state(&self, value: bool) {
self.set_state(IN_ENABLED_STATE, value)
}
pub fn disabled_state(&self) -> bool {
self.state.get().contains(IN_DISABLED_STATE)
}
pub fn set_disabled_state(&self, value: bool) {
self.set_state(IN_DISABLED_STATE, value)
}
pub fn read_write_state(&self) -> bool {
self.state.get().contains(IN_READ_WRITE_STATE)
}
pub fn set_read_write_state(&self, value: bool) {
self.set_state(IN_READ_WRITE_STATE, value)
}
pub fn placeholder_shown_state(&self) -> bool {
self.state.get().contains(IN_PLACEHOLDER_SHOWN_STATE)
}
pub fn set_placeholder_shown_state(&self, value: bool) {
if self.placeholder_shown_state() != value {
self.set_state(IN_PLACEHOLDER_SHOWN_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
}
pub fn target_state(&self) -> bool {
self.state.get().contains(IN_TARGET_STATE)
}
pub fn set_target_state(&self, value: bool) {
self.set_state(IN_TARGET_STATE, value)
}
pub fn fullscreen_state(&self) -> bool {
self.state.get().contains(IN_FULLSCREEN_STATE)
}
pub fn set_fullscreen_state(&self, value: bool) {
self.set_state(IN_FULLSCREEN_STATE, value)
}
/// https://dom.spec.whatwg.org/#connected
pub fn is_connected(&self) -> bool {
let node = self.upcast::<Node>();
let root = node.GetRootNode();
root.is::<Document>()
}
}
impl Element {
pub fn check_ancestors_disabled_state_for_form_control(&self) {
let node = self.upcast::<Node>();
if self.disabled_state() {
return;
}
for ancestor in node.ancestors() {
if !ancestor.is::<HTMLFieldSetElement>() {
continue;
}
if !ancestor.downcast::<Element>().unwrap().disabled_state() {
continue;
}
if ancestor.is_parent_of(node) {
self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
if let Some(ref legend) = ancestor.children().find(|n| n.is::<HTMLLegendElement>()) {
// XXXabinader: should we save previous ancestor to avoid this iteration?
if node.ancestors().any(|ancestor| ancestor == *legend) {
continue;
}
}
self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
}
pub fn check_parent_disabled_state_for_option(&self) {
if self.disabled_state() {
return;
}
let node = self.upcast::<Node>();
if let Some(ref parent) = node.GetParentNode() {
if parent.is::<HTMLOptGroupElement>() &&
parent.downcast::<Element>().unwrap().disabled_state() {
self.set_disabled_state(true);
self.set_enabled_state(false);
}
}
}
pub fn check_disabled_attribute(&self) {
let has_disabled_attrib = self.has_attribute(&local_name!("disabled"));
self.set_disabled_state(has_disabled_attrib);
self.set_enabled_state(!has_disabled_attrib);
}
}
#[derive(Clone, Copy)]
pub enum AttributeMutation<'a> {
/// The attribute is set, keep track of old value.
/// https://dom.spec.whatwg.org/#attribute-is-set
Set(Option<&'a AttrValue>),
/// The attribute is removed.
/// https://dom.spec.whatwg.org/#attribute-is-removed
Removed,
}
impl<'a> AttributeMutation<'a> {
pub fn is_removal(&self) -> bool {
match *self {
AttributeMutation::Removed => true,
AttributeMutation::Set(..) => false,
}
}
pub fn new_value<'b>(&self, attr: &'b Attr) -> Option<Ref<'b, AttrValue>> {
match *self {
AttributeMutation::Set(_) => Some(attr.value()),
AttributeMutation::Removed => None,
}
}
}
/// A holder for an element's "tag name", which will be lazily
/// resolved and cached. Should be reset when the document
/// owner changes.
#[derive(HeapSizeOf, JSTraceable)]
struct TagName {
ptr: DomRefCell<Option<LocalName>>,
}
impl TagName {
fn new() -> TagName {
TagName { ptr: DomRefCell::new(None) }
}
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
fn or_init<F>(&self, cb: F) -> LocalName
where F: FnOnce() -> LocalName
{
match &mut *self.ptr.borrow_mut() {
&mut Some(ref name) => name.clone(),
ptr => {
let name = cb();
*ptr = Some(name.clone());
name
}
}
}
/// Clear the cached tag name, so that it will be re-calculated the
/// next time that `or_init()` is called.
fn clear(&self) {
*self.ptr.borrow_mut() = None;
}
}
pub struct ElementPerformFullscreenEnter {
element: Trusted<Element>,
promise: TrustedPromise,
error: bool,
}
impl ElementPerformFullscreenEnter {
pub fn new(element: Trusted<Element>, promise: TrustedPromise, error: bool) -> Box<ElementPerformFullscreenEnter> {
Box::new(ElementPerformFullscreenEnter {
element: element,
promise: promise,
error: error,
})
}
}
impl TaskOnce for ElementPerformFullscreenEnter {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let promise = self.promise.root();
let document = document_from_node(element.r());
// Step 7.1
if self.error || !element.fullscreen_element_ready_check() {
document.upcast::<EventTarget>().fire_event(atom!("fullscreenerror"));
promise.reject_error(Error::Type(String::from("fullscreen is not connected")));
return
}
// TODO Step 7.2-4
// Step 7.5
element.set_fullscreen_state(true);
document.set_fullscreen_element(Some(&element));
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
// Step 7.6
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 7.7
promise.resolve_native(&());
}
}
pub struct ElementPerformFullscreenExit {
element: Trusted<Element>,
promise: TrustedPromise,
}
impl ElementPerformFullscreenExit {
pub fn new(element: Trusted<Element>, promise: TrustedPromise) -> Box<ElementPerformFullscreenExit> {
Box::new(ElementPerformFullscreenExit {
element: element,
promise: promise,
})
}
}
impl TaskOnce for ElementPerformFullscreenExit {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let document = document_from_node(element.r());
// TODO Step 9.1-5
// Step 9.6
element.set_fullscreen_state(false);
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
document.set_fullscreen_element(None);
// Step 9.8
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 9.10
self.promise.root().resolve_native(&());
}
}
pub fn reflect_cross_origin_attribute(element: &Element) -> Option<DOMString> {
let attr = element.get_attribute(&ns!(), &local_name!("crossorigin"));
if let Some(mut val) = attr.map(|v| v.Value()) {
val.make_ascii_lowercase();
if val == "anonymous" || val == "use-credentials" {
return Some(val);
}
return Some(DOMString::from("anonymous"));
}
None
}
pub fn set_cross_origin_attribute(element: &Element, value: Option<DOMString>) {
match value {
Some(val) => element.set_string_attribute(&local_name!("crossorigin"), val),
None => {
element.remove_attribute(&ns!(), &local_name!("crossorigin"));
}
}
}
pub fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> {
reflect_cross_origin_attribute(element).map_or(None, |attr| {
match &*attr {
"anonymous" => Some(CorsSettings::Anonymous),
"use-credentials" => Some(CorsSettings::UseCredentials),
_ => unreachable!()
}
})
}
fix unused warning
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Element nodes.
use devtools_traits::AttrInfo;
use dom::activation::Activatable;
use dom::attr::{Attr, AttrHelpersForLayout};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::ElementBinding;
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type};
use dom::bindings::xmlname::XMLName::InvalidXMLName;
use dom::characterdata::CharacterData;
use dom::create::create_element;
use dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReaction};
use dom::document::{Document, LayoutDocumentHelpers};
use dom::documentfragment::DocumentFragment;
use dom::domrect::DOMRect;
use dom::domtokenlist::DOMTokenList;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers};
use dom::htmlbuttonelement::HTMLButtonElement;
use dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers};
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers};
use dom::htmlformelement::FormControlElementHelpers;
use dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers};
use dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods};
use dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers};
use dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers};
use dom::htmllabelelement::HTMLLabelElement;
use dom::htmllegendelement::HTMLLegendElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::htmlobjectelement::HTMLObjectElement;
use dom::htmloptgroupelement::HTMLOptGroupElement;
use dom::htmlselectelement::HTMLSelectElement;
use dom::htmlstyleelement::HTMLStyleElement;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers};
use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers};
use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers};
use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers};
use dom::htmltemplateelement::HTMLTemplateElement;
use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::namednodemap::NamedNodeMap;
use dom::node::{CLICK_IN_PROGRESS, ChildrenMutation, LayoutNodeHelpers, Node};
use dom::node::{NodeDamage, SEQUENTIALLY_FOCUSABLE, UnbindContext};
use dom::node::{document_from_node, window_from_node};
use dom::nodelist::NodeList;
use dom::promise::Promise;
use dom::servoparser::ServoParser;
use dom::text::Text;
use dom::validation::Validatable;
use dom::virtualmethods::{VirtualMethods, vtable_for};
use dom::window::ReflowReason;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace, QualName};
use html5ever::serialize;
use html5ever::serialize::SerializeOpts;
use html5ever::serialize::TraversalScope;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use js::jsapi::Heap;
use js::jsval::JSVal;
use net_traits::request::CorsSettings;
use ref_filter_map::ref_filter_map;
use script_layout_interface::message::ReflowGoal;
use script_thread::ScriptThread;
use selectors::Element as SelectorsElement;
use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
use selectors::matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus};
use selectors::matching::{HAS_EDGE_CHILD_SELECTOR, HAS_SLOW_SELECTOR, HAS_SLOW_SELECTOR_LATER_SIBLINGS};
use selectors::sink::Push;
use servo_arc::Arc;
use servo_atoms::Atom;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::cell::{Cell, Ref};
use std::default::Default;
use std::fmt;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use style::CaseSensitivityExt;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use style::context::QuirksMode;
use style::dom_apis;
use style::element_state::*;
use style::invalidation::element::restyle_hints::RESTYLE_SELF;
use style::properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, parse_style_attribute};
use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size, overflow_x};
use style::rule_tree::CascadeLevel;
use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser};
use style::selector_parser::extended_filtering;
use style::shared_lock::{SharedRwLock, Locked};
use style::thread_state;
use style::values::{CSSFloat, Either};
use style::values::{specified, computed};
use stylesheet_loader::StylesheetOwner;
use task::TaskOnce;
use xml5ever::serialize as xmlSerialize;
use xml5ever::serialize::SerializeOpts as XmlSerializeOpts;
use xml5ever::serialize::TraversalScope as XmlTraversalScope;
use xml5ever::serialize::TraversalScope::ChildrenOnly as XmlChildrenOnly;
use xml5ever::serialize::TraversalScope::IncludeNode as XmlIncludeNode;
// TODO: Update focus state when the top-level browsing context gains or loses system focus,
// and when the element enters or leaves a browsing context container.
// https://html.spec.whatwg.org/multipage/#selector-focus
#[dom_struct]
pub struct Element {
node: Node,
local_name: LocalName,
tag_name: TagName,
namespace: Namespace,
prefix: DomRefCell<Option<Prefix>>,
attrs: DomRefCell<Vec<Dom<Attr>>>,
id_attribute: DomRefCell<Option<Atom>>,
is: DomRefCell<Option<LocalName>>,
#[ignore_heap_size_of = "Arc"]
style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
attr_list: MutNullableDom<NamedNodeMap>,
class_list: MutNullableDom<DOMTokenList>,
state: Cell<ElementState>,
/// These flags are set by the style system to indicate the that certain
/// operations may require restyling this element or its descendants. The
/// flags are not atomic, so the style system takes care of only set them
/// when it has exclusive access to the element.
#[ignore_heap_size_of = "bitflags defined in rust-selectors"]
selector_flags: Cell<ElementSelectorFlags>,
/// https://html.spec.whatwg.org/multipage/#custom-element-reaction-queue
custom_element_reaction_queue: DomRefCell<Vec<CustomElementReaction>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-definition
#[ignore_heap_size_of = "Rc"]
custom_element_definition: DomRefCell<Option<Rc<CustomElementDefinition>>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-state
custom_element_state: Cell<CustomElementState>,
}
impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}", self.local_name)?;
if let Some(ref id) = *self.id_attribute.borrow() {
write!(f, " id={}", id)?;
}
write!(f, ">")
}
}
impl fmt::Debug for DomRoot<Element> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
#[derive(HeapSizeOf, PartialEq)]
pub enum ElementCreator {
ParserCreated(u64),
ScriptCreated,
}
pub enum CustomElementCreationMode {
Synchronous,
Asynchronous,
}
/// https://dom.spec.whatwg.org/#concept-element-custom-element-state
#[derive(Clone, Copy, Eq, HeapSizeOf, JSTraceable, PartialEq)]
pub enum CustomElementState {
Undefined,
Failed,
Uncustomized,
Custom,
}
impl ElementCreator {
pub fn is_parser_created(&self) -> bool {
match *self {
ElementCreator::ParserCreated(_) => true,
ElementCreator::ScriptCreated => false,
}
}
pub fn return_line_number(&self) -> u64 {
match *self {
ElementCreator::ParserCreated(l) => l,
ElementCreator::ScriptCreated => 1,
}
}
}
pub enum AdjacentPosition {
BeforeBegin,
AfterEnd,
AfterBegin,
BeforeEnd,
}
impl FromStr for AdjacentPosition {
type Err = Error;
fn from_str(position: &str) -> Result<Self, Self::Err> {
match_ignore_ascii_case! { &*position,
"beforebegin" => Ok(AdjacentPosition::BeforeBegin),
"afterbegin" => Ok(AdjacentPosition::AfterBegin),
"beforeend" => Ok(AdjacentPosition::BeforeEnd),
"afterend" => Ok(AdjacentPosition::AfterEnd),
_ => Err(Error::Syntax)
}
}
}
//
// Element methods
//
impl Element {
pub fn create(name: QualName,
is: Option<LocalName>,
document: &Document,
creator: ElementCreator,
mode: CustomElementCreationMode)
-> DomRoot<Element> {
create_element(name, is, document, creator, mode)
}
pub fn new_inherited(local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document) -> Element {
Element::new_inherited_with_state(ElementState::empty(), local_name,
namespace, prefix, document)
}
pub fn new_inherited_with_state(state: ElementState, local_name: LocalName,
namespace: Namespace, prefix: Option<Prefix>,
document: &Document)
-> Element {
Element {
node: Node::new_inherited(document),
local_name: local_name,
tag_name: TagName::new(),
namespace: namespace,
prefix: DomRefCell::new(prefix),
attrs: DomRefCell::new(vec![]),
id_attribute: DomRefCell::new(None),
is: DomRefCell::new(None),
style_attribute: DomRefCell::new(None),
attr_list: Default::default(),
class_list: Default::default(),
state: Cell::new(state),
selector_flags: Cell::new(ElementSelectorFlags::empty()),
custom_element_reaction_queue: Default::default(),
custom_element_definition: Default::default(),
custom_element_state: Cell::new(CustomElementState::Uncustomized),
}
}
pub fn new(local_name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<Element> {
Node::reflect_node(
Box::new(Element::new_inherited(local_name, namespace, prefix, document)),
document,
ElementBinding::Wrap)
}
pub fn restyle(&self, damage: NodeDamage) {
let doc = self.node.owner_doc();
let mut restyle = doc.ensure_pending_restyle(self);
// FIXME(bholley): I think we should probably only do this for
// NodeStyleDamaged, but I'm preserving existing behavior.
restyle.hint.insert(RESTYLE_SELF);
if damage == NodeDamage::OtherNodeDamage {
restyle.damage = RestyleDamage::rebuild_and_reflow();
}
}
pub fn set_is(&self, is: LocalName) {
*self.is.borrow_mut() = Some(is);
}
pub fn get_is(&self) -> Option<LocalName> {
self.is.borrow().clone()
}
pub fn set_custom_element_state(&self, state: CustomElementState) {
self.custom_element_state.set(state);
}
pub fn get_custom_element_state(&self) -> CustomElementState {
self.custom_element_state.get()
}
pub fn set_custom_element_definition(&self, definition: Rc<CustomElementDefinition>) {
*self.custom_element_definition.borrow_mut() = Some(definition);
}
pub fn get_custom_element_definition(&self) -> Option<Rc<CustomElementDefinition>> {
(*self.custom_element_definition.borrow()).clone()
}
pub fn push_callback_reaction(&self, function: Rc<Function>, args: Box<[Heap<JSVal>]>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Callback(function, args));
}
pub fn push_upgrade_reaction(&self, definition: Rc<CustomElementDefinition>) {
self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Upgrade(definition));
}
pub fn clear_reaction_queue(&self) {
self.custom_element_reaction_queue.borrow_mut().clear();
}
pub fn invoke_reactions(&self) {
// TODO: This is not spec compliant, as this will allow some reactions to be processed
// after clear_reaction_queue has been called.
rooted_vec!(let mut reactions);
while !self.custom_element_reaction_queue.borrow().is_empty() {
mem::swap(&mut *reactions, &mut *self.custom_element_reaction_queue.borrow_mut());
for reaction in reactions.iter() {
reaction.invoke(self);
}
reactions.clear();
}
}
// https://drafts.csswg.org/cssom-view/#css-layout-box
// Elements that have a computed value of the display property
// that is table-column or table-column-group
// FIXME: Currently, it is assumed to be true always
fn has_css_layout_box(&self) -> bool {
true
}
// https://drafts.csswg.org/cssom-view/#potentially-scrollable
fn potentially_scrollable(&self) -> bool {
self.has_css_layout_box() &&
!self.overflow_x_is_visible() &&
!self.overflow_y_is_visible()
}
// used value of overflow-x is "visible"
fn overflow_x_is_visible(&self) -> bool {
let window = window_from_node(self);
let overflow_pair = window.overflow_query(self.upcast::<Node>().to_trusted_node_address());
overflow_pair.x == overflow_x::computed_value::T::visible
}
// used value of overflow-y is "visible"
fn overflow_y_is_visible(&self) -> bool {
let window = window_from_node(self);
let overflow_pair = window.overflow_query(self.upcast::<Node>().to_trusted_node_address());
overflow_pair.y != overflow_x::computed_value::T::visible
}
}
#[allow(unsafe_code)]
pub trait RawLayoutElementHelpers {
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue>;
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str>;
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue>;
}
#[inline]
#[allow(unsafe_code)]
pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName)
-> Option<LayoutDom<Attr>> {
// cast to point to T in RefCell<T> directly
let attrs = elem.attrs.borrow_for_layout();
attrs.iter().find(|attr| {
let attr = attr.to_layout();
*name == attr.local_name_atom_forever() &&
(*attr.unsafe_get()).namespace() == namespace
}).map(|attr| attr.to_layout())
}
#[allow(unsafe_code)]
impl RawLayoutElementHelpers for Element {
#[inline]
unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a AttrValue> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_forever()
})
}
#[inline]
unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName)
-> Option<&'a str> {
get_attr_for_layout(self, namespace, name).map(|attr| {
attr.value_ref_forever()
})
}
#[inline]
unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue> {
let attrs = self.attrs.borrow_for_layout();
attrs.iter().filter_map(|attr| {
let attr = attr.to_layout();
if *name == attr.local_name_atom_forever() {
Some(attr.value_forever())
} else {
None
}
}).collect()
}
}
pub trait LayoutElementHelpers {
#[allow(unsafe_code)]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
#[allow(unsafe_code)]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]>;
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: Push<ApplicableDeclarationBlock>;
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32;
#[allow(unsafe_code)]
unsafe fn html_element_in_html_document_for_layout(&self) -> bool;
fn id_attribute(&self) -> *const Option<Atom>;
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>>;
fn local_name(&self) -> &LocalName;
fn namespace(&self) -> &Namespace;
fn get_lang_for_layout(&self) -> String;
fn get_checked_state_for_layout(&self) -> bool;
fn get_indeterminate_state_for_layout(&self) -> bool;
fn get_state_for_layout(&self) -> ElementState;
fn insert_selector_flags(&self, flags: ElementSelectorFlags);
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
}
impl LayoutElementHelpers for LayoutDom<Element> {
#[allow(unsafe_code)]
#[inline]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value_tokens_forever().unwrap().iter().any(|atom| case_sensitivity.eq_atom(atom, name))
})
}
#[allow(unsafe_code)]
#[inline]
unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]> {
get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class"))
.map(|attr| attr.value_tokens_forever().unwrap())
}
#[allow(unsafe_code)]
unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V)
where V: Push<ApplicableDeclarationBlock>
{
// FIXME(emilio): Just a single PDB should be enough.
#[inline]
fn from_declaration(shared_lock: &SharedRwLock, declaration: PropertyDeclaration)
-> ApplicableDeclarationBlock {
ApplicableDeclarationBlock::from_declarations(
Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
declaration, Importance::Normal
))),
CascadeLevel::PresHints)
}
let document = self.upcast::<Node>().owner_doc_for_layout();
let shared_lock = document.style_shared_lock();
let bgcolor = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableRowElement>() {
this.get_background_color()
} else if let Some(this) = self.downcast::<HTMLTableSectionElement>() {
this.get_background_color()
} else {
None
};
if let Some(color) = bgcolor {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundColor(color.into())
));
}
let background = if let Some(this) = self.downcast::<HTMLBodyElement>() {
this.get_background()
} else {
None
};
if let Some(url) = background {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BackgroundImage(
background_image::SpecifiedValue(vec![
Either::Second(specified::Image::for_cascade(url.into()))
]))));
}
let color = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_color()
} else if let Some(this) = self.downcast::<HTMLBodyElement>() {
// https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20
this.get_color()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5
this.get_color()
} else {
None
};
if let Some(color) = color {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Color(
longhands::color::SpecifiedValue(color.into())
)
));
}
let font_family = if let Some(this) = self.downcast::<HTMLFontElement>() {
this.get_face()
} else {
None
};
if let Some(font_family) = font_family {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontFamily(
font_family::SpecifiedValue::Values(
font_family::computed_value::FontFamilyList::new(vec![
font_family::computed_value::FontFamily::from_atom(
font_family)])))));
}
let font_size = self.downcast::<HTMLFontElement>().and_then(|this| this.get_size());
if let Some(font_size) = font_size {
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::FontSize(
font_size::SpecifiedValue::from_html_size(font_size as u8)
)
))
}
let cellspacing = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_cellspacing()
} else {
None
};
if let Some(cellspacing) = cellspacing {
let width_value = specified::Length::from_px(cellspacing as f32);
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderSpacing(
Box::new(border_spacing::SpecifiedValue::new(
width_value.clone().into(),
width_value.into()
))
)
));
}
let size = if let Some(this) = self.downcast::<HTMLInputElement>() {
// FIXME(pcwalton): More use of atoms, please!
match (*self.unsafe_get()).get_attr_val_for_layout(&ns!(), &local_name!("type")) {
// Not text entry widget
Some("hidden") | Some("date") | Some("month") | Some("week") |
Some("time") | Some("datetime-local") | Some("number") | Some("range") |
Some("color") | Some("checkbox") | Some("radio") | Some("file") |
Some("submit") | Some("image") | Some("reset") | Some("button") => {
None
},
// Others
_ => {
match this.size_for_layout() {
0 => None,
s => Some(s as i32),
}
},
}
} else {
None
};
if let Some(size) = size {
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(
specified::LengthOrPercentageOrAuto::Length(value))));
}
let width = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_width()
} else if let Some(this) = self.downcast::<HTMLHRElement>() {
// https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width
this.get_width()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_width()
} else {
LengthOrPercentageOrAuto::Auto
};
// FIXME(emilio): Use from_computed value here and below.
match width {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let width_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let width_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(width_value)));
}
}
let height = if let Some(this) = self.downcast::<HTMLIFrameElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLImageElement>() {
this.get_height()
} else if let Some(this) = self.downcast::<HTMLCanvasElement>() {
this.get_height()
} else {
LengthOrPercentageOrAuto::Auto
};
match height {
LengthOrPercentageOrAuto::Auto => {}
LengthOrPercentageOrAuto::Percentage(percentage) => {
let height_value =
specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
LengthOrPercentageOrAuto::Length(length) => {
let height_value = specified::LengthOrPercentageOrAuto::Length(
specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(height_value)));
}
}
let cols = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_cols() {
0 => None,
c => Some(c as i32),
}
} else {
None
};
if let Some(cols) = cols {
// TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but
// the math for <textarea> is a little different since we need to take
// scrollbar size into consideration (but we don't have a scrollbar yet!)
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-width
let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value))));
}
let rows = if let Some(this) = self.downcast::<HTMLTextAreaElement>() {
match this.get_rows() {
0 => None,
r => Some(r as i32),
}
} else {
None
};
if let Some(rows) = rows {
// TODO(mttr) This should take scrollbar size into consideration.
//
// https://html.spec.whatwg.org/multipage/#textarea-effective-height
let value = specified::NoCalcLength::FontRelative(specified::FontRelativeLength::Em(rows as CSSFloat));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value))));
}
let border = if let Some(this) = self.downcast::<HTMLTableElement>() {
this.get_border()
} else {
None
};
if let Some(border) = border {
let width_value = specified::BorderSideWidth::Length(specified::Length::from_px(border as f32));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderTopWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderLeftWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderBottomWidth(width_value.clone())));
hints.push(from_declaration(
shared_lock,
PropertyDeclaration::BorderRightWidth(width_value)));
}
}
#[allow(unsafe_code)]
unsafe fn get_colspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_colspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[allow(unsafe_code)]
unsafe fn get_rowspan(self) -> u32 {
if let Some(this) = self.downcast::<HTMLTableCellElement>() {
this.get_rowspan().unwrap_or(1)
} else {
// Don't panic since `display` can cause this to be called on arbitrary
// elements.
1
}
}
#[inline]
#[allow(unsafe_code)]
unsafe fn html_element_in_html_document_for_layout(&self) -> bool {
if (*self.unsafe_get()).namespace != ns!(html) {
return false;
}
self.upcast::<Node>().owner_doc_for_layout().is_html_document_for_layout()
}
#[allow(unsafe_code)]
fn id_attribute(&self) -> *const Option<Atom> {
unsafe {
(*self.unsafe_get()).id_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>> {
unsafe {
(*self.unsafe_get()).style_attribute.borrow_for_layout()
}
}
#[allow(unsafe_code)]
fn local_name(&self) -> &LocalName {
unsafe {
&(*self.unsafe_get()).local_name
}
}
#[allow(unsafe_code)]
fn namespace(&self) -> &Namespace {
unsafe {
&(*self.unsafe_get()).namespace
}
}
#[allow(unsafe_code)]
fn get_lang_for_layout(&self) -> String {
unsafe {
let mut current_node = Some(self.upcast::<Node>());
while let Some(node) = current_node {
current_node = node.parent_node_ref();
match node.downcast::<Element>().map(|el| el.unsafe_get()) {
Some(elem) => {
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) {
return attr.to_owned();
}
if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(), &local_name!("lang")) {
return attr.to_owned();
}
}
None => continue
}
}
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
String::new()
}
}
#[inline]
#[allow(unsafe_code)]
fn get_checked_state_for_layout(&self) -> bool {
// TODO option and menuitem can also have a checked state.
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.checked_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_indeterminate_state_for_layout(&self) -> bool {
// TODO progress elements can also be matched with :indeterminate
match self.downcast::<HTMLInputElement>() {
Some(input) => unsafe {
input.indeterminate_state_for_layout()
},
None => false,
}
}
#[inline]
#[allow(unsafe_code)]
fn get_state_for_layout(&self) -> ElementState {
unsafe {
(*self.unsafe_get()).state.get()
}
}
#[inline]
#[allow(unsafe_code)]
fn insert_selector_flags(&self, flags: ElementSelectorFlags) {
debug_assert!(thread_state::get().is_layout());
unsafe {
let f = &(*self.unsafe_get()).selector_flags;
f.set(f.get() | flags);
}
}
#[inline]
#[allow(unsafe_code)]
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool {
unsafe {
(*self.unsafe_get()).selector_flags.get().contains(flags)
}
}
}
impl Element {
pub fn html_element_in_html_document(&self) -> bool {
self.namespace == ns!(html) && self.upcast::<Node>().is_in_html_doc()
}
pub fn local_name(&self) -> &LocalName {
&self.local_name
}
pub fn parsed_name(&self, mut name: DOMString) -> LocalName {
if self.html_element_in_html_document() {
name.make_ascii_lowercase();
}
LocalName::from(name)
}
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
pub fn prefix(&self) -> Ref<Option<Prefix>> {
self.prefix.borrow()
}
pub fn set_prefix(&self, prefix: Option<Prefix>) {
*self.prefix.borrow_mut() = prefix;
}
pub fn attrs(&self) -> Ref<[Dom<Attr>]> {
Ref::map(self.attrs.borrow(), |attrs| &**attrs)
}
// Element branch of https://dom.spec.whatwg.org/#locate-a-namespace
pub fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace {
let prefix = prefix.map(String::from).map(LocalName::from);
let inclusive_ancestor_elements =
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast::<Self>);
// Steps 3-4.
for element in inclusive_ancestor_elements {
// Step 1.
if element.namespace() != &ns!() &&
element.prefix().as_ref().map(|p| &**p) == prefix.as_ref().map(|p| &**p)
{
return element.namespace().clone();
}
// Step 2.
let attr = ref_filter_map(self.attrs(), |attrs| {
attrs.iter().find(|attr| {
if attr.namespace() != &ns!(xmlns) {
return false;
}
match (attr.prefix(), prefix.as_ref()) {
(Some(&namespace_prefix!("xmlns")), Some(prefix)) => {
attr.local_name() == prefix
},
(None, None) => attr.local_name() == &local_name!("xmlns"),
_ => false,
}
})
});
if let Some(attr) = attr {
return (**attr.value()).into();
}
}
ns!()
}
pub fn style_attribute(&self) -> &DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>> {
&self.style_attribute
}
pub fn summarize(&self) -> Vec<AttrInfo> {
self.attrs.borrow().iter()
.map(|attr| attr.summarize())
.collect()
}
pub fn is_void(&self) -> bool {
if self.namespace != ns!(html) {
return false
}
match self.local_name {
/* List of void elements from
https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */
local_name!("area") | local_name!("base") | local_name!("basefont") |
local_name!("bgsound") | local_name!("br") |
local_name!("col") | local_name!("embed") | local_name!("frame") |
local_name!("hr") | local_name!("img") |
local_name!("input") | local_name!("keygen") | local_name!("link") |
local_name!("menuitem") | local_name!("meta") |
local_name!("param") | local_name!("source") | local_name!("track") |
local_name!("wbr") => true,
_ => false
}
}
pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match serialize(&mut writer,
&self.upcast::<Node>(),
SerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
// FIXME(ajeffrey): Directly convert UTF8 to DOMString
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn xmlSerialize(&self, traversal_scope: XmlTraversalScope) -> Fallible<DOMString> {
let mut writer = vec![];
match xmlSerialize::serialize(&mut writer,
&self.upcast::<Node>(),
XmlSerializeOpts {
traversal_scope: traversal_scope,
..Default::default()
}) {
Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
pub fn root_element(&self) -> DomRoot<Element> {
if self.node.is_in_doc() {
self.upcast::<Node>()
.owner_doc()
.GetDocumentElement()
.unwrap()
} else {
self.upcast::<Node>()
.inclusive_ancestors()
.filter_map(DomRoot::downcast)
.last()
.expect("We know inclusive_ancestors will return `self` which is an element")
}
}
// https://dom.spec.whatwg.org/#locate-a-namespace-prefix
pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> {
for node in self.upcast::<Node>().inclusive_ancestors() {
match node.downcast::<Element>() {
Some(element) => {
// Step 1.
if *element.namespace() == namespace {
if let Some(prefix) = element.GetPrefix() {
return Some(prefix);
}
}
// Step 2.
for attr in element.attrs.borrow().iter() {
if attr.prefix() == Some(&namespace_prefix!("xmlns")) &&
**attr.value() == *namespace {
return Some(attr.LocalName());
}
}
},
None => return None,
}
}
None
}
pub fn is_focusable_area(&self) -> bool {
if self.is_actually_disabled() {
return false;
}
// TODO: Check whether the element is being rendered (i.e. not hidden).
let node = self.upcast::<Node>();
if node.get_flag(SEQUENTIALLY_FOCUSABLE) {
return true;
}
// https://html.spec.whatwg.org/multipage/#specially-focusable
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
true
}
_ => false,
}
}
pub fn is_actually_disabled(&self) -> bool {
let node = self.upcast::<Node>();
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => {
self.disabled_state()
}
// TODO:
// an optgroup element that has a disabled attribute
// a menuitem element that has a disabled attribute
// a fieldset element that is a disabled fieldset
_ => false,
}
}
pub fn push_new_attribute(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>) {
let window = window_from_node(self);
let attr = Attr::new(&window,
local_name,
value,
name,
namespace,
prefix,
Some(self));
self.push_attribute(&attr);
}
pub fn push_attribute(&self, attr: &Attr) {
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let value = DOMString::from(&**attr.value());
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: value.clone(),
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
if self.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, None, Some(value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
assert!(attr.GetOwnerElement().r() == Some(self));
self.will_mutate_attr(attr);
self.attrs.borrow_mut().push(Dom::from_ref(attr));
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None));
}
}
pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.attrs
.borrow()
.iter()
.find(|attr| attr.local_name() == local_name && attr.namespace() == namespace)
.map(|js| DomRoot::from_ref(&**js))
}
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
pub fn get_attribute_by_name(&self, name: DOMString) -> Option<DomRoot<Attr>> {
let name = &self.parsed_name(name);
self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| DomRoot::from_ref(&**js))
}
pub fn set_attribute_from_parser(&self,
qname: QualName,
value: DOMString,
prefix: Option<Prefix>) {
// Don't set if the attribute already exists, so we can handle add_attrs_if_missing
if self.attrs
.borrow()
.iter()
.any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) {
return;
}
let name = match prefix {
None => qname.local.clone(),
Some(ref prefix) => {
let name = format!("{}:{}", &**prefix, &*qname.local);
LocalName::from(name)
},
};
let value = self.parse_attribute(&qname.ns, &qname.local, value);
self.push_new_attribute(qname.local, value, name, qname.ns, prefix);
}
pub fn set_attribute(&self, name: &LocalName, value: AttrValue) {
assert!(name == &name.to_ascii_lowercase());
assert!(!name.contains(":"));
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| attr.local_name() == name);
}
// https://html.spec.whatwg.org/multipage/#attr-data-*
pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if let InvalidXMLName = xml_name_type(&name) {
return Err(Error::InvalidCharacter);
}
// Steps 2-5.
let name = LocalName::from(name);
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(name.clone(),
value,
name.clone(),
ns!(),
None,
|attr| {
*attr.name() == name && *attr.namespace() == ns!()
});
Ok(())
}
fn set_first_matching_attribute<F>(&self,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
find: F)
where F: Fn(&Attr) -> bool
{
let attr = self.attrs
.borrow()
.iter()
.find(|attr| find(&attr))
.map(|js| DomRoot::from_ref(&**js));
if let Some(attr) = attr {
attr.set_value(value, self);
} else {
self.push_new_attribute(local_name, value, name, namespace, prefix);
};
}
pub fn parse_attribute(&self,
namespace: &Namespace,
local_name: &LocalName,
value: DOMString)
-> AttrValue {
if *namespace == ns!() {
vtable_for(self.upcast()).parse_plain_attribute(local_name, value)
} else {
AttrValue::String(value.into())
}
}
pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| {
attr.namespace() == namespace && attr.local_name() == local_name
})
}
pub fn remove_attribute_by_name(&self, name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| attr.name() == name)
}
fn remove_first_matching_attribute<F>(&self, find: F) -> Option<DomRoot<Attr>>
where F: Fn(&Attr) -> bool {
let idx = self.attrs.borrow().iter().position(|attr| find(&attr));
idx.map(|idx| {
let attr = DomRoot::from_ref(&*(*self.attrs.borrow())[idx]);
self.will_mutate_attr(&attr);
let name = attr.local_name().clone();
let namespace = attr.namespace().clone();
let old_value = DOMString::from(&**attr.value());
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(&self.node, mutation);
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), None, namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
self.attrs.borrow_mut().remove(idx);
attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Removed);
}
attr
})
}
pub fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.get_attribute(&ns!(), &local_name!("class")).map_or(false, |attr| {
attr.value().as_tokens().iter().any(|atom| case_sensitivity.eq_atom(name, atom))
})
}
pub fn set_atomic_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
let value = AttrValue::from_atomic(value.into());
self.set_attribute(local_name, value);
}
pub fn has_attribute(&self, local_name: &LocalName) -> bool {
assert!(local_name.bytes().all(|b| b.to_ascii_lowercase() == b));
self.attrs
.borrow()
.iter()
.any(|attr| attr.local_name() == local_name && attr.namespace() == &ns!())
}
pub fn set_bool_attribute(&self, local_name: &LocalName, value: bool) {
if self.has_attribute(local_name) == value {
return;
}
if value {
self.set_string_attribute(local_name, DOMString::new());
} else {
self.remove_attribute(&ns!(), local_name);
}
}
pub fn get_url_attribute(&self, local_name: &LocalName) -> DOMString {
assert!(*local_name == local_name.to_ascii_lowercase());
let attr = match self.get_attribute(&ns!(), local_name) {
Some(attr) => attr,
None => return DOMString::new(),
};
let value = &**attr.value();
// XXXManishearth this doesn't handle `javascript:` urls properly
let base = document_from_node(self).base_url();
let value = base.join(value)
.map(|parsed| parsed.into_string())
.unwrap_or_else(|_| value.to_owned());
DOMString::from(value)
}
pub fn get_string_attribute(&self, local_name: &LocalName) -> DOMString {
match self.get_attribute(&ns!(), local_name) {
Some(x) => x.Value(),
None => DOMString::new(),
}
}
pub fn set_string_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::String(value.into()));
}
pub fn get_tokenlist_attribute(&self, local_name: &LocalName) -> Vec<Atom> {
self.get_attribute(&ns!(), local_name).map(|attr| {
attr.value()
.as_tokens()
.to_vec()
}).unwrap_or(vec!())
}
pub fn set_tokenlist_attribute(&self, local_name: &LocalName, value: DOMString) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name,
AttrValue::from_serialized_tokenlist(value.into()));
}
pub fn set_atomic_tokenlist_attribute(&self, local_name: &LocalName, tokens: Vec<Atom>) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::from_atomic_tokens(tokens));
}
pub fn get_int_attribute(&self, local_name: &LocalName, default: i32) -> i32 {
// TODO: Is this assert necessary?
assert!(local_name.chars().all(|ch| {
!ch.is_ascii() || ch.to_ascii_lowercase() == ch
}));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::Int(_, value) => value,
_ => panic!("Expected an AttrValue::Int: \
implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_int_attribute(&self, local_name: &LocalName, value: i32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::Int(value.to_string(), value));
}
pub fn get_uint_attribute(&self, local_name: &LocalName, default: u32) -> u32 {
assert!(local_name.chars().all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch));
let attribute = self.get_attribute(&ns!(), local_name);
match attribute {
Some(ref attribute) => {
match *attribute.value() {
AttrValue::UInt(_, value) => value,
_ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"),
}
}
None => default,
}
}
pub fn set_uint_attribute(&self, local_name: &LocalName, value: u32) {
assert!(*local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::UInt(value.to_string(), value));
}
pub fn will_mutate_attr(&self, attr: &Attr) {
let node = self.upcast::<Node>();
node.owner_doc().element_attr_will_change(self, attr);
}
// https://dom.spec.whatwg.org/#insert-adjacent
pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node)
-> Fallible<Option<DomRoot<Node>>> {
let self_node = self.upcast::<Node>();
match where_ {
AdjacentPosition::BeforeBegin => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, Some(self_node)).map(Some)
} else {
Ok(None)
}
}
AdjacentPosition::AfterBegin => {
Node::pre_insert(node, &self_node, self_node.GetFirstChild().r()).map(Some)
}
AdjacentPosition::BeforeEnd => {
Node::pre_insert(node, &self_node, None).map(Some)
}
AdjacentPosition::AfterEnd => {
if let Some(parent) = self_node.GetParentNode() {
Node::pre_insert(node, &parent, self_node.GetNextSibling().r()).map(Some)
} else {
Ok(None)
}
}
}
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
pub fn scroll(&self, x_: f64, y_: f64, behavior: ScrollBehavior) {
// Step 1.2 or 2.3
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(x, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, y, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, x, y, behavior);
}
// https://w3c.github.io/DOM-Parsing/#parsing
pub fn parse_fragment(&self, markup: DOMString) -> Fallible<DomRoot<DocumentFragment>> {
// Steps 1-2.
let context_document = document_from_node(self);
// TODO(#11995): XML case.
let new_children = ServoParser::parse_html_fragment(self, markup);
// Step 3.
let fragment = DocumentFragment::new(&context_document);
// Step 4.
for child in new_children {
fragment.upcast::<Node>().AppendChild(&child).unwrap();
}
// Step 5.
Ok(fragment)
}
pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> DomRoot<Self> {
match element {
Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => {
DomRoot::from_ref(elem)
},
_ => {
DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc))
}
}
}
// https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check
pub fn fullscreen_element_ready_check(&self) -> bool {
if !self.is_connected() {
return false
}
let document = document_from_node(self);
document.get_allow_fullscreen()
}
// https://html.spec.whatwg.org/multipage/#home-subtree
pub fn is_in_same_home_subtree<T>(&self, other: &T) -> bool
where T: DerivedFrom<Element> + DomObject
{
let other = other.upcast::<Element>();
self.root_element() == other.root_element()
}
}
impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
Node::namespace_to_string(self.namespace.clone())
}
// https://dom.spec.whatwg.org/#dom-element-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): Convert directly from LocalName to DOMString
DOMString::from(&*self.local_name)
}
// https://dom.spec.whatwg.org/#dom-element-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix.borrow().as_ref().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-element-tagname
fn TagName(&self) -> DOMString {
let name = self.tag_name.or_init(|| {
let qualified_name = match *self.prefix.borrow() {
Some(ref prefix) => {
Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name))
},
None => Cow::Borrowed(&*self.local_name)
};
if self.html_element_in_html_document() {
LocalName::from(qualified_name.to_ascii_uppercase())
} else {
LocalName::from(qualified_name)
}
});
DOMString::from(&*name)
}
// https://dom.spec.whatwg.org/#dom-element-id
fn Id(&self) -> DOMString {
self.get_string_attribute(&local_name!("id"))
}
// https://dom.spec.whatwg.org/#dom-element-id
fn SetId(&self, id: DOMString) {
self.set_atomic_attribute(&local_name!("id"), id);
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn ClassName(&self) -> DOMString {
self.get_string_attribute(&local_name!("class"))
}
// https://dom.spec.whatwg.org/#dom-element-classname
fn SetClassName(&self, class: DOMString) {
self.set_tokenlist_attribute(&local_name!("class"), class);
}
// https://dom.spec.whatwg.org/#dom-element-classlist
fn ClassList(&self) -> DomRoot<DOMTokenList> {
self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class")))
}
// https://dom.spec.whatwg.org/#dom-element-attributes
fn Attributes(&self) -> DomRoot<NamedNodeMap> {
self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self))
}
// https://dom.spec.whatwg.org/#dom-element-hasattributes
fn HasAttributes(&self) -> bool {
!self.attrs.borrow().is_empty()
}
// https://dom.spec.whatwg.org/#dom-element-getattributenames
fn GetAttributeNames(&self) -> Vec<DOMString> {
self.attrs.borrow().iter().map(|attr| attr.Name()).collect()
}
// https://dom.spec.whatwg.org/#dom-element-getattribute
fn GetAttribute(&self, name: DOMString) -> Option<DOMString> {
self.GetAttributeNode(name)
.map(|s| s.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributens
fn GetAttributeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DOMString> {
self.GetAttributeNodeNS(namespace, local_name)
.map(|attr| attr.Value())
}
// https://dom.spec.whatwg.org/#dom-element-getattributenode
fn GetAttributeNode(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.get_attribute_by_name(name)
}
// https://dom.spec.whatwg.org/#dom-element-getattributenodens
fn GetAttributeNodeNS(&self,
namespace: Option<DOMString>,
local_name: DOMString)
-> Option<DomRoot<Attr>> {
let namespace = &namespace_from_domstring(namespace);
self.get_attribute(namespace, &LocalName::from(local_name))
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult {
// Step 1.
if xml_name_type(&name) == InvalidXMLName {
return Err(Error::InvalidCharacter);
}
// Step 2.
let name = self.parsed_name(name);
// Step 3-5.
let value = self.parse_attribute(&ns!(), &name, value);
self.set_first_matching_attribute(
name.clone(), value, name.clone(), ns!(), None,
|attr| *attr.name() == name);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributens
fn SetAttributeNS(&self,
namespace: Option<DOMString>,
qualified_name: DOMString,
value: DOMString) -> ErrorResult {
let (namespace, prefix, local_name) =
validate_and_extract(namespace, &qualified_name)?;
let qualified_name = LocalName::from(qualified_name);
let value = self.parse_attribute(&namespace, &local_name, value);
self.set_first_matching_attribute(
local_name.clone(), value, qualified_name, namespace.clone(), prefix,
|attr| *attr.local_name() == local_name && *attr.namespace() == namespace);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-element-setattributenode
fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
// Step 1.
if let Some(owner) = attr.GetOwnerElement() {
if &*owner != self {
return Err(Error::InUseAttribute);
}
}
let vtable = vtable_for(self.upcast());
// This ensures that the attribute is of the expected kind for this
// specific element. This is inefficient and should probably be done
// differently.
attr.swap_value(
&mut vtable.parse_plain_attribute(attr.local_name(), attr.Value()),
);
// Step 2.
let position = self.attrs.borrow().iter().position(|old_attr| {
attr.namespace() == old_attr.namespace() && attr.local_name() == old_attr.local_name()
});
if let Some(position) = position {
let old_attr = DomRoot::from_ref(&*self.attrs.borrow()[position]);
// Step 3.
if &*old_attr == attr {
return Ok(Some(DomRoot::from_ref(attr)));
}
// Step 4.
if self.get_custom_element_definition().is_some() {
let old_name = old_attr.local_name().clone();
let old_value = DOMString::from(&**old_attr.value());
let new_value = DOMString::from(&**attr.value());
let namespace = old_attr.namespace().clone();
let reaction = CallbackReaction::AttributeChanged(old_name, Some(old_value),
Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(self, reaction, None);
}
self.will_mutate_attr(attr);
attr.set_owner(Some(self));
self.attrs.borrow_mut()[position] = Dom::from_ref(attr);
old_attr.set_owner(None);
if attr.namespace() == &ns!() {
vtable.attribute_mutated(
&attr, AttributeMutation::Set(Some(&old_attr.value())));
}
// Step 6.
Ok(Some(old_attr))
} else {
// Step 5.
attr.set_owner(Some(self));
self.push_attribute(attr);
// Step 6.
Ok(None)
}
}
// https://dom.spec.whatwg.org/#dom-element-setattributenodens
fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
self.SetAttributeNode(attr)
}
// https://dom.spec.whatwg.org/#dom-element-removeattribute
fn RemoveAttribute(&self, name: DOMString) {
let name = self.parsed_name(name);
self.remove_attribute_by_name(&name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributens
fn RemoveAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) {
let namespace = namespace_from_domstring(namespace);
let local_name = LocalName::from(local_name);
self.remove_attribute(&namespace, &local_name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributenode
fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<DomRoot<Attr>> {
self.remove_first_matching_attribute(|a| a == attr)
.ok_or(Error::NotFound)
}
// https://dom.spec.whatwg.org/#dom-element-hasattribute
fn HasAttribute(&self, name: DOMString) -> bool {
self.GetAttribute(name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-hasattributens
fn HasAttributeNS(&self, namespace: Option<DOMString>, local_name: DOMString) -> bool {
self.GetAttributeNS(namespace, local_name).is_some()
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagname
fn GetElementsByTagName(&self, localname: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname))
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens
fn GetElementsByTagNameNS(&self,
maybe_ns: Option<DOMString>,
localname: DOMString)
-> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns)
}
// https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::by_class_name(&window, self.upcast(), classes)
}
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
fn GetClientRects(&self) -> Vec<DomRoot<DOMRect>> {
let win = window_from_node(self);
let raw_rects = self.upcast::<Node>().content_boxes();
raw_rects.iter().map(|rect| {
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}).collect()
}
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
fn GetBoundingClientRect(&self) -> DomRoot<DOMRect> {
let win = window_from_node(self);
let rect = self.upcast::<Node>().bounding_content_box_or_zero();
DOMRect::new(win.upcast(),
rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(),
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px())
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll(&self, options: &ScrollToOptions) {
// Step 1
let left = options.left.unwrap_or(self.ScrollLeft());
let top = options.top.unwrap_or(self.ScrollTop());
self.scroll(left, top, options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
fn Scroll_(&self, x: f64, y: f64) {
self.scroll(x, y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo(&self, options: &ScrollToOptions) {
self.Scroll(options);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollto
fn ScrollTo_(&self, x: f64, y: f64) {
self.Scroll_(x, y);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy(&self, options: &ScrollToOptions) {
// Step 2
let delta_left = options.left.unwrap_or(0.0f64);
let delta_top = options.top.unwrap_or(0.0f64);
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + delta_left, top + delta_top,
options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollby
fn ScrollBy_(&self, x: f64, y: f64) {
let left = self.ScrollLeft();
let top = self.ScrollTop();
self.scroll(left + x, top + y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollTop(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return 0.0;
}
// Step 6
return win.ScrollY() as f64;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollY() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.y.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn SetScrollTop(&self, y_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let y = if y_.is_finite() { y_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
win.scroll(win.ScrollX() as f64, y, behavior);
}
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(win.ScrollX() as f64, y, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, self.ScrollLeft(), y, behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
fn ScrollLeft(&self) -> f64 {
let node = self.upcast::<Node>();
// Step 1
let doc = node.owner_doc();
// Step 2
if !doc.is_fully_active() {
return 0.0;
}
// Step 3
let win = match doc.GetDefaultView() {
None => return 0.0,
Some(win) => win,
};
// Step 5
if *self.root_element() == *self {
if doc.quirks_mode() != QuirksMode::Quirks {
// Step 6
return win.ScrollX() as f64;
}
return 0.0;
}
// Step 7
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
return win.ScrollX() as f64;
}
// Step 8
if !self.has_css_layout_box() {
return 0.0;
}
// Step 9
let point = node.scroll_offset();
return point.x.abs() as f64;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollleft
fn SetScrollLeft(&self, x_: f64) {
let behavior = ScrollBehavior::Auto;
// Step 1, 2
let x = if x_.is_finite() { x_ } else { 0.0f64 };
let node = self.upcast::<Node>();
// Step 3
let doc = node.owner_doc();
// Step 4
if !doc.is_fully_active() {
return;
}
// Step 5
let win = match doc.GetDefaultView() {
None => return,
Some(win) => win,
};
// Step 7
if *self.root_element() == *self {
if doc.quirks_mode() == QuirksMode::Quirks {
return;
}
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 9
if doc.GetBody().r() == self.downcast::<HTMLElement>() &&
doc.quirks_mode() == QuirksMode::Quirks &&
!self.potentially_scrollable() {
win.scroll(x, win.ScrollY() as f64, behavior);
return;
}
// Step 10 (TODO)
// Step 11
win.scroll_node(node, x, self.ScrollTop(), behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth
fn ScrollWidth(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrollheight
fn ScrollHeight(&self) -> i32 {
self.upcast::<Node>().scroll_area().size.height
}
// https://drafts.csswg.org/cssom-view/#dom-element-clienttop
fn ClientTop(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.y
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientleft
fn ClientLeft(&self) -> i32 {
self.upcast::<Node>().client_rect().origin.x
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientwidth
fn ClientWidth(&self) -> i32 {
self.upcast::<Node>().client_rect().size.width
}
// https://drafts.csswg.org/cssom-view/#dom-element-clientheight
fn ClientHeight(&self) -> i32 {
self.upcast::<Node>().client_rect().size.height
}
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
fn GetInnerHTML(&self) -> Fallible<DOMString> {
let qname = QualName::new(self.prefix().clone(),
self.namespace().clone(),
self.local_name().clone());
if document_from_node(self).is_html_document() {
return self.serialize(ChildrenOnly(Some(qname)));
} else {
return self.xmlSerialize(XmlChildrenOnly(Some(qname)));
}
}
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
fn SetInnerHTML(&self, value: DOMString) -> ErrorResult {
// Step 1.
let frag = self.parse_fragment(value)?;
// Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
DomRoot::upcast(template.Content())
} else {
DomRoot::from_ref(self.upcast())
};
Node::replace_all(Some(frag.upcast()), &target);
Ok(())
}
// https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML
fn GetOuterHTML(&self) -> Fallible<DOMString> {
if document_from_node(self).is_html_document() {
return self.serialize(IncludeNode);
} else {
return self.xmlSerialize(XmlIncludeNode);
}
}
// https://w3c.github.io/DOM-Parsing/#dom-element-outerhtml
fn SetOuterHTML(&self, value: DOMString) -> ErrorResult {
let context_document = document_from_node(self);
let context_node = self.upcast::<Node>();
// Step 1.
let context_parent = match context_node.GetParentNode() {
None => {
// Step 2.
return Ok(());
},
Some(parent) => parent,
};
let parent = match context_parent.type_id() {
// Step 3.
NodeTypeId::Document(_) => return Err(Error::NoModificationAllowed),
// Step 4.
NodeTypeId::DocumentFragment => {
let body_elem = Element::create(QualName::new(None, ns!(html), local_name!("body")),
None,
&context_document,
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous);
DomRoot::upcast(body_elem)
},
_ => context_node.GetParentElement().unwrap()
};
// Step 5.
let frag = parent.parse_fragment(value)?;
// Step 6.
context_parent.ReplaceChild(frag.upcast(), context_node)?;
Ok(())
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);
HTMLCollection::children(&window, self.upcast())
}
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().child_elements().next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
fn ChildElementCount(&self) -> u32 {
self.upcast::<Node>().child_elements().count() as u32
}
// https://dom.spec.whatwg.org/#dom-parentnode-prepend
fn Prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().prepend(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-append
fn Append(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().append(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let root = self.upcast::<Node>();
root.query_selector(selectors)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> {
let root = self.upcast::<Node>();
root.query_selector_all(selectors)
}
// https://dom.spec.whatwg.org/#dom-childnode-before
fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().before(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().after(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-replacewith
fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().replace_with(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) {
self.upcast::<Node>().remove_self();
}
// https://dom.spec.whatwg.org/#dom-element-matches
fn Matches(&self, selectors: DOMString) -> Fallible<bool> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
let element = DomRoot::from_ref(self);
Ok(dom_apis::element_matches(&element, &selectors, quirks_mode))
}
// https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector
fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> {
self.Matches(selectors)
}
// https://dom.spec.whatwg.org/#dom-element-closest
fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let selectors =
match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => return Err(Error::Syntax),
Ok(selectors) => selectors,
};
let quirks_mode = document_from_node(self).quirks_mode();
Ok(dom_apis::element_closest(
DomRoot::from_ref(self),
&selectors,
quirks_mode,
))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
fn InsertAdjacentElement(&self, where_: DOMString, element: &Element)
-> Fallible<Option<DomRoot<Element>>> {
let where_ = where_.parse::<AdjacentPosition>()?;
let inserted_node = self.insert_adjacent(where_, element.upcast())?;
Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap()))
}
// https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
fn InsertAdjacentText(&self, where_: DOMString, data: DOMString)
-> ErrorResult {
// Step 1.
let text = Text::new(data, &document_from_node(self));
// Step 2.
let where_ = where_.parse::<AdjacentPosition>()?;
self.insert_adjacent(where_, text.upcast()).map(|_| ())
}
// https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml
fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString)
-> ErrorResult {
// Step 1.
let position = position.parse::<AdjacentPosition>()?;
let context = match position {
AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
match self.upcast::<Node>().GetParentNode() {
Some(ref node) if node.is::<Document>() => {
return Err(Error::NoModificationAllowed)
}
None => return Err(Error::NoModificationAllowed),
Some(node) => node,
}
}
AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
DomRoot::from_ref(self.upcast::<Node>())
}
};
// Step 2.
let context = Element::fragment_parsing_context(
&context.owner_doc(), context.downcast::<Element>());
// Step 3.
let fragment = context.parse_fragment(text)?;
// Step 4.
self.insert_adjacent(position, fragment.upcast()).map(|_| ())
}
// check-tidy: no specs after this line
fn EnterFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.enter_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
fn ExitFormalActivationState(&self) -> ErrorResult {
match self.as_maybe_activatable() {
Some(a) => {
a.exit_formal_activation_state();
return Ok(());
},
None => return Err(Error::NotSupported)
}
}
// https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
#[allow(unrooted_must_root)]
fn RequestFullscreen(&self) -> Rc<Promise> {
let doc = document_from_node(self);
doc.enter_fullscreen(self)
}
}
impl VirtualMethods for Element {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<Node>() as &VirtualMethods)
}
fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
// FIXME: This should be more fine-grained, not all elements care about these.
if attr.local_name() == &local_name!("width") ||
attr.local_name() == &local_name!("height") {
return true;
}
self.super_type().unwrap().attribute_affects_presentational_hints(attr)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
let node = self.upcast::<Node>();
let doc = node.owner_doc();
match attr.local_name() {
&local_name!("style") => {
// Modifying the `style` attribute might change style.
*self.style_attribute.borrow_mut() = match mutation {
AttributeMutation::Set(..) => {
// This is the fast path we use from
// CSSStyleDeclaration.
//
// Juggle a bit to keep the borrow checker happy
// while avoiding the extra clone.
let is_declaration = match *attr.value() {
AttrValue::Declaration(..) => true,
_ => false,
};
let block = if is_declaration {
let mut value = AttrValue::String(String::new());
attr.swap_value(&mut value);
let (serialization, block) = match value {
AttrValue::Declaration(s, b) => (s, b),
_ => unreachable!(),
};
let mut value = AttrValue::String(serialization);
attr.swap_value(&mut value);
block
} else {
let win = window_from_node(self);
Arc::new(doc.style_shared_lock().wrap(parse_style_attribute(
&attr.value(),
&doc.base_url(),
win.css_error_reporter(),
doc.quirks_mode())))
};
Some(block)
}
AttributeMutation::Removed => {
None
}
};
},
&local_name!("id") => {
*self.id_attribute.borrow_mut() =
mutation.new_value(attr).and_then(|value| {
let value = value.as_atom();
if value != &atom!("") {
Some(value.clone())
} else {
None
}
});
if node.is_in_doc() {
let value = attr.value().as_atom().clone();
match mutation {
AttributeMutation::Set(old_value) => {
if let Some(old_value) = old_value {
let old_value = old_value.as_atom().clone();
doc.unregister_named_element(self, old_value);
}
if value != atom!("") {
doc.register_named_element(self, value);
}
},
AttributeMutation::Removed => {
if value != atom!("") {
doc.unregister_named_element(self, value);
}
}
}
}
},
_ => {
// FIXME(emilio): This is pretty dubious, and should be done in
// the relevant super-classes.
if attr.namespace() == &ns!() &&
attr.local_name() == &local_name!("src") {
node.dirty(NodeDamage::OtherNodeDamage);
}
},
};
// Make sure we rev the version even if we didn't dirty the node. If we
// don't do this, various attribute-dependent htmlcollections (like those
// generated by getElementsByClassName) might become stale.
node.rev_version();
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("id") => AttrValue::from_atomic(value.into()),
&local_name!("class") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if let Some(f) = self.as_maybe_form_control() {
f.bind_form_control_to_tree();
}
if !tree_in_doc {
return;
}
let doc = document_from_node(self);
if let Some(ref value) = *self.id_attribute.borrow() {
doc.register_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.increment_dom_count();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
if let Some(f) = self.as_maybe_form_control() {
f.unbind_form_control_from_tree();
}
if !context.tree_in_doc {
return;
}
let doc = document_from_node(self);
let fullscreen = doc.GetFullscreenElement();
if fullscreen.r() == Some(self) {
doc.exit_fullscreen();
}
if let Some(ref value) = *self.id_attribute.borrow() {
doc.unregister_named_element(self, value.clone());
}
// This is used for layout optimization.
doc.decrement_dom_count();
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
let flags = self.selector_flags.get();
if flags.intersects(HAS_SLOW_SELECTOR) {
// All children of this node need to be restyled when any child changes.
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
} else {
if flags.intersects(HAS_SLOW_SELECTOR_LATER_SIBLINGS) {
if let Some(next_child) = mutation.next_child() {
for child in next_child.inclusively_following_siblings() {
if child.is::<Element>() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
if flags.intersects(HAS_EDGE_CHILD_SELECTOR) {
if let Some(child) = mutation.modified_edge_element() {
child.dirty(NodeDamage::OtherNodeDamage);
}
}
}
}
fn adopting_steps(&self, old_doc: &Document) {
self.super_type().unwrap().adopting_steps(old_doc);
if document_from_node(self).is_html_document() != old_doc.is_html_document() {
self.tag_name.clear();
}
}
}
impl<'a> SelectorsElement for DomRoot<Element> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.reflector().get_jsobject().get())
}
fn parent_element(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().GetParentElement()
}
fn match_pseudo_element(&self,
_pseudo: &PseudoElement,
_context: &mut MatchingContext)
-> bool
{
false
}
fn first_child_element(&self) -> Option<DomRoot<Element>> {
self.node.child_elements().next()
}
fn last_child_element(&self) -> Option<DomRoot<Element>> {
self.node.rev_children().filter_map(DomRoot::downcast).next()
}
fn prev_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.preceding_siblings().filter_map(DomRoot::downcast).next()
}
fn next_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.following_siblings().filter_map(DomRoot::downcast).next()
}
fn attr_matches(&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&String>)
-> bool {
match *ns {
NamespaceConstraint::Specific(ref ns) => {
self.get_attribute(ns, local_name)
.map_or(false, |attr| attr.value().eval_selector(operation))
}
NamespaceConstraint::Any => {
self.attrs.borrow().iter().any(|attr| {
attr.local_name() == local_name &&
attr.value().eval_selector(operation)
})
}
}
}
fn is_root(&self) -> bool {
match self.node.GetParentNode() {
None => false,
Some(node) => node.is::<Document>(),
}
}
fn is_empty(&self) -> bool {
self.node.children().all(|node| !node.is::<Element>() && match node.downcast::<Text>() {
None => true,
Some(text) => text.upcast::<CharacterData>().data().is_empty()
})
}
fn get_local_name(&self) -> &LocalName {
self.local_name()
}
fn get_namespace(&self) -> &Namespace {
self.namespace()
}
fn match_non_ts_pseudo_class<F>(&self,
pseudo_class: &NonTSPseudoClass,
_: &mut MatchingContext,
_: &RelevantLinkStatus,
_: &mut F)
-> bool
where F: FnMut(&Self, ElementSelectorFlags),
{
match *pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::Link |
NonTSPseudoClass::AnyLink => self.is_link(),
NonTSPseudoClass::Visited => false,
NonTSPseudoClass::ServoNonZeroBorder => {
match self.downcast::<HTMLTableElement>() {
None => false,
Some(this) => {
match this.get_border() {
None | Some(0) => false,
Some(_) => true,
}
}
}
},
NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => {
self.get_attribute(&ns!(), &local_name!("type"))
.map_or(false, |attr| attr.value().eq(expected_value))
}
// FIXME(heycam): This is wrong, since extended_filtering accepts
// a string containing commas (separating each language tag in
// a list) but the pseudo-class instead should be parsing and
// storing separate <ident> or <string>s for each language tag.
NonTSPseudoClass::Lang(ref lang) => extended_filtering(&*self.get_lang(), &*lang),
NonTSPseudoClass::ReadOnly =>
!Element::state(self).contains(pseudo_class.state_flag()),
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::Indeterminate |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::PlaceholderShown |
NonTSPseudoClass::Target =>
Element::state(self).contains(pseudo_class.state_flag()),
}
}
fn is_link(&self) -> bool {
// FIXME: This is HTML only.
let node = self.upcast::<Node>();
match node.type_id() {
// https://html.spec.whatwg.org/multipage/#selector-link
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => {
self.has_attribute(&local_name!("href"))
},
_ => false,
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
self.id_attribute.borrow().as_ref().map_or(false, |atom| case_sensitivity.eq_atom(id, atom))
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
Element::has_class(&**self, name, case_sensitivity)
}
fn is_html_element_in_html_document(&self) -> bool {
self.html_element_in_html_document()
}
}
impl Element {
pub fn as_maybe_activatable(&self) -> Option<&Activatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => {
let element = self.downcast::<HTMLAnchorElement>().unwrap();
Some(element as &Activatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => {
let element = self.downcast::<HTMLLabelElement>().unwrap();
Some(element as &Activatable)
},
_ => {
None
}
};
element.and_then(|elem| {
if elem.is_instance_activatable() {
Some(elem)
} else {
None
}
})
}
pub fn as_stylesheet_owner(&self) -> Option<&StylesheetOwner> {
if let Some(s) = self.downcast::<HTMLStyleElement>() {
return Some(s as &StylesheetOwner)
}
if let Some(l) = self.downcast::<HTMLLinkElement>() {
return Some(l as &StylesheetOwner)
}
None
}
// https://html.spec.whatwg.org/multipage/#category-submit
pub fn as_maybe_validatable(&self) -> Option<&Validatable> {
let element = match self.upcast::<Node>().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = self.downcast::<HTMLButtonElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => {
let element = self.downcast::<HTMLObjectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => {
let element = self.downcast::<HTMLSelectElement>().unwrap();
Some(element as &Validatable)
},
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
let element = self.downcast::<HTMLTextAreaElement>().unwrap();
Some(element as &Validatable)
},
_ => {
None
}
};
element
}
pub fn click_in_progress(&self) -> bool {
self.upcast::<Node>().get_flag(CLICK_IN_PROGRESS)
}
pub fn set_click_in_progress(&self, click: bool) {
self.upcast::<Node>().set_flag(CLICK_IN_PROGRESS, click)
}
// https://html.spec.whatwg.org/multipage/#nearest-activatable-element
pub fn nearest_activable_element(&self) -> Option<DomRoot<Element>> {
match self.as_maybe_activatable() {
Some(el) => Some(DomRoot::from_ref(el.as_element())),
None => {
let node = self.upcast::<Node>();
for node in node.ancestors() {
if let Some(node) = node.downcast::<Element>() {
if node.as_maybe_activatable().is_some() {
return Some(DomRoot::from_ref(node));
}
}
}
None
}
}
}
/// Please call this method *only* for real click events
///
/// https://html.spec.whatwg.org/multipage/#run-authentic-click-activation-steps
///
/// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks.
/// If the spec says otherwise, check with Manishearth first
pub fn authentic_click_activation(&self, event: &Event) {
// Not explicitly part of the spec, however this helps enforce the invariants
// required to save state between pre-activation and post-activation
// since we cannot nest authentic clicks (unlike synthetic click activation, where
// the script can generate more click events from the handler)
assert!(!self.click_in_progress());
let target = self.upcast();
// Step 2 (requires canvas support)
// Step 3
self.set_click_in_progress(true);
// Step 4
let e = self.nearest_activable_element();
match e {
Some(ref el) => match el.as_maybe_activatable() {
Some(elem) => {
// Step 5-6
elem.pre_click_activation();
event.fire(target);
if !event.DefaultPrevented() {
// post click activation
elem.activation_behavior(event, target);
} else {
elem.canceled_activation();
}
}
// Step 6
None => {
event.fire(target);
}
},
// Step 6
None => {
event.fire(target);
}
}
// Step 7
self.set_click_in_progress(false);
}
// https://html.spec.whatwg.org/multipage/#language
pub fn get_lang(&self) -> String {
self.upcast::<Node>().inclusive_ancestors().filter_map(|node| {
node.downcast::<Element>().and_then(|el| {
el.get_attribute(&ns!(xml), &local_name!("lang")).or_else(|| {
el.get_attribute(&ns!(), &local_name!("lang"))
}).map(|attr| String::from(attr.Value()))
})
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
}).next().unwrap_or(String::new())
}
pub fn state(&self) -> ElementState {
self.state.get()
}
pub fn set_state(&self, which: ElementState, value: bool) {
let mut state = self.state.get();
if state.contains(which) == value {
return;
}
let node = self.upcast::<Node>();
node.owner_doc().element_state_will_change(self);
if value {
state.insert(which);
} else {
state.remove(which);
}
self.state.set(state);
}
pub fn active_state(&self) -> bool {
self.state.get().contains(IN_ACTIVE_STATE)
}
/// https://html.spec.whatwg.org/multipage/#concept-selector-active
pub fn set_active_state(&self, value: bool) {
self.set_state(IN_ACTIVE_STATE, value);
if let Some(parent) = self.upcast::<Node>().GetParentElement() {
parent.set_active_state(value);
}
}
pub fn focus_state(&self) -> bool {
self.state.get().contains(IN_FOCUS_STATE)
}
pub fn set_focus_state(&self, value: bool) {
self.set_state(IN_FOCUS_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
pub fn hover_state(&self) -> bool {
self.state.get().contains(IN_HOVER_STATE)
}
pub fn set_hover_state(&self, value: bool) {
self.set_state(IN_HOVER_STATE, value)
}
pub fn enabled_state(&self) -> bool {
self.state.get().contains(IN_ENABLED_STATE)
}
pub fn set_enabled_state(&self, value: bool) {
self.set_state(IN_ENABLED_STATE, value)
}
pub fn disabled_state(&self) -> bool {
self.state.get().contains(IN_DISABLED_STATE)
}
pub fn set_disabled_state(&self, value: bool) {
self.set_state(IN_DISABLED_STATE, value)
}
pub fn read_write_state(&self) -> bool {
self.state.get().contains(IN_READ_WRITE_STATE)
}
pub fn set_read_write_state(&self, value: bool) {
self.set_state(IN_READ_WRITE_STATE, value)
}
pub fn placeholder_shown_state(&self) -> bool {
self.state.get().contains(IN_PLACEHOLDER_SHOWN_STATE)
}
pub fn set_placeholder_shown_state(&self, value: bool) {
if self.placeholder_shown_state() != value {
self.set_state(IN_PLACEHOLDER_SHOWN_STATE, value);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
}
pub fn target_state(&self) -> bool {
self.state.get().contains(IN_TARGET_STATE)
}
pub fn set_target_state(&self, value: bool) {
self.set_state(IN_TARGET_STATE, value)
}
pub fn fullscreen_state(&self) -> bool {
self.state.get().contains(IN_FULLSCREEN_STATE)
}
pub fn set_fullscreen_state(&self, value: bool) {
self.set_state(IN_FULLSCREEN_STATE, value)
}
/// https://dom.spec.whatwg.org/#connected
pub fn is_connected(&self) -> bool {
let node = self.upcast::<Node>();
let root = node.GetRootNode();
root.is::<Document>()
}
}
impl Element {
pub fn check_ancestors_disabled_state_for_form_control(&self) {
let node = self.upcast::<Node>();
if self.disabled_state() {
return;
}
for ancestor in node.ancestors() {
if !ancestor.is::<HTMLFieldSetElement>() {
continue;
}
if !ancestor.downcast::<Element>().unwrap().disabled_state() {
continue;
}
if ancestor.is_parent_of(node) {
self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
if let Some(ref legend) = ancestor.children().find(|n| n.is::<HTMLLegendElement>()) {
// XXXabinader: should we save previous ancestor to avoid this iteration?
if node.ancestors().any(|ancestor| ancestor == *legend) {
continue;
}
}
self.set_disabled_state(true);
self.set_enabled_state(false);
return;
}
}
pub fn check_parent_disabled_state_for_option(&self) {
if self.disabled_state() {
return;
}
let node = self.upcast::<Node>();
if let Some(ref parent) = node.GetParentNode() {
if parent.is::<HTMLOptGroupElement>() &&
parent.downcast::<Element>().unwrap().disabled_state() {
self.set_disabled_state(true);
self.set_enabled_state(false);
}
}
}
pub fn check_disabled_attribute(&self) {
let has_disabled_attrib = self.has_attribute(&local_name!("disabled"));
self.set_disabled_state(has_disabled_attrib);
self.set_enabled_state(!has_disabled_attrib);
}
}
#[derive(Clone, Copy)]
pub enum AttributeMutation<'a> {
/// The attribute is set, keep track of old value.
/// https://dom.spec.whatwg.org/#attribute-is-set
Set(Option<&'a AttrValue>),
/// The attribute is removed.
/// https://dom.spec.whatwg.org/#attribute-is-removed
Removed,
}
impl<'a> AttributeMutation<'a> {
pub fn is_removal(&self) -> bool {
match *self {
AttributeMutation::Removed => true,
AttributeMutation::Set(..) => false,
}
}
pub fn new_value<'b>(&self, attr: &'b Attr) -> Option<Ref<'b, AttrValue>> {
match *self {
AttributeMutation::Set(_) => Some(attr.value()),
AttributeMutation::Removed => None,
}
}
}
/// A holder for an element's "tag name", which will be lazily
/// resolved and cached. Should be reset when the document
/// owner changes.
#[derive(HeapSizeOf, JSTraceable)]
struct TagName {
ptr: DomRefCell<Option<LocalName>>,
}
impl TagName {
fn new() -> TagName {
TagName { ptr: DomRefCell::new(None) }
}
/// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first.
fn or_init<F>(&self, cb: F) -> LocalName
where F: FnOnce() -> LocalName
{
match &mut *self.ptr.borrow_mut() {
&mut Some(ref name) => name.clone(),
ptr => {
let name = cb();
*ptr = Some(name.clone());
name
}
}
}
/// Clear the cached tag name, so that it will be re-calculated the
/// next time that `or_init()` is called.
fn clear(&self) {
*self.ptr.borrow_mut() = None;
}
}
pub struct ElementPerformFullscreenEnter {
element: Trusted<Element>,
promise: TrustedPromise,
error: bool,
}
impl ElementPerformFullscreenEnter {
pub fn new(element: Trusted<Element>, promise: TrustedPromise, error: bool) -> Box<ElementPerformFullscreenEnter> {
Box::new(ElementPerformFullscreenEnter {
element: element,
promise: promise,
error: error,
})
}
}
impl TaskOnce for ElementPerformFullscreenEnter {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let promise = self.promise.root();
let document = document_from_node(element.r());
// Step 7.1
if self.error || !element.fullscreen_element_ready_check() {
document.upcast::<EventTarget>().fire_event(atom!("fullscreenerror"));
promise.reject_error(Error::Type(String::from("fullscreen is not connected")));
return
}
// TODO Step 7.2-4
// Step 7.5
element.set_fullscreen_state(true);
document.set_fullscreen_element(Some(&element));
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
// Step 7.6
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 7.7
promise.resolve_native(&());
}
}
pub struct ElementPerformFullscreenExit {
element: Trusted<Element>,
promise: TrustedPromise,
}
impl ElementPerformFullscreenExit {
pub fn new(element: Trusted<Element>, promise: TrustedPromise) -> Box<ElementPerformFullscreenExit> {
Box::new(ElementPerformFullscreenExit {
element: element,
promise: promise,
})
}
}
impl TaskOnce for ElementPerformFullscreenExit {
#[allow(unrooted_must_root)]
fn run_once(self) {
let element = self.element.root();
let document = document_from_node(element.r());
// TODO Step 9.1-5
// Step 9.6
element.set_fullscreen_state(false);
document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged);
document.set_fullscreen_element(None);
// Step 9.8
document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange"));
// Step 9.10
self.promise.root().resolve_native(&());
}
}
pub fn reflect_cross_origin_attribute(element: &Element) -> Option<DOMString> {
let attr = element.get_attribute(&ns!(), &local_name!("crossorigin"));
if let Some(mut val) = attr.map(|v| v.Value()) {
val.make_ascii_lowercase();
if val == "anonymous" || val == "use-credentials" {
return Some(val);
}
return Some(DOMString::from("anonymous"));
}
None
}
pub fn set_cross_origin_attribute(element: &Element, value: Option<DOMString>) {
match value {
Some(val) => element.set_string_attribute(&local_name!("crossorigin"), val),
None => {
element.remove_attribute(&ns!(), &local_name!("crossorigin"));
}
}
}
pub fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> {
reflect_cross_origin_attribute(element).map_or(None, |attr| {
match &*attr {
"anonymous" => Some(CorsSettings::Anonymous),
"use-credentials" => Some(CorsSettings::UseCredentials),
_ => unreachable!()
}
})
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout tasks.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyStateValues};
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, EventTargetCast, NodeCast, EventCast};
use dom::bindings::conversions::{FromJSValConvertible, Empty};
use dom::bindings::global;
use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalRootable};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap};
use dom::document::{Document, HTMLDocument, DocumentHelpers, FromParser};
use dom::element::{Element, HTMLButtonElementTypeId, HTMLInputElementTypeId};
use dom::element::{HTMLSelectElementTypeId, HTMLTextAreaElementTypeId, HTMLOptionElementTypeId, ActivationElementHelpers};
use dom::event::{Event, EventHelpers, Bubbles, DoesNotBubble, Cancelable, NotCancelable};
use dom::uievent::UIEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::keyboardevent::KeyboardEvent;
use dom::node;
use dom::node::{ElementNodeTypeId, Node, NodeHelpers};
use dom::window::{Window, WindowHelpers};
use dom::worker::{Worker, TrustedWorkerAddress};
use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress};
use parse::html::{InputString, InputUrl, parse_html};
use layout_interface::{ScriptLayoutChan, LayoutChan, NoQuery, ReflowForDisplay};
use layout_interface;
use page::{Page, IterablePage, Frame};
use timers::TimerId;
use devtools;
use devtools_traits::{DevtoolsControlChan, DevtoolsControlPort, NewGlobal, GetRootNode};
use devtools_traits::{DevtoolScriptControlMsg, EvaluateJS, GetDocumentElement};
use devtools_traits::{GetChildren, GetLayout, ModifyAttribute};
use script_traits::{CompositorEvent, ResizeEvent, ReflowEvent, ClickEvent, MouseDownEvent};
use script_traits::{MouseMoveEvent, MouseUpEvent, ConstellationControlMsg, ScriptTaskFactory};
use script_traits::{ResizeMsg, AttachLayoutMsg, LoadMsg, ViewportMsg, SendEventMsg};
use script_traits::{ResizeInactiveMsg, ExitPipelineMsg, NewLayoutInfo, OpaqueScriptLayoutChannel};
use script_traits::{ScriptControlChan, ReflowCompleteMsg, UntrustedNodeAddress, KeyEvent};
use servo_msg::compositor_msg::{FinishedLoading, LayerId, Loading};
use servo_msg::compositor_msg::{ScriptListener};
use servo_msg::constellation_msg::{ConstellationChan, LoadCompleteMsg, LoadUrlMsg, NavigationDirection};
use servo_msg::constellation_msg::{LoadData, PipelineId, Failure, FailureMsg, WindowSizeData, Key, KeyState};
use servo_msg::constellation_msg::{KeyModifiers, SUPER, SHIFT, CONTROL, ALT, Repeated, Pressed};
use servo_msg::constellation_msg::{Released};
use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::{ResourceTask, Load};
use servo_net::resource_task::LoadData as NetLoadData;
use servo_net::storage_task::StorageTask;
use servo_util::geometry::to_frac_px;
use servo_util::smallvec::{SmallVec1, SmallVec};
use servo_util::task::spawn_named_with_send_on_failure;
use servo_util::task_state;
use geom::point::Point2D;
use hyper::header::{Header, HeaderFormat};
use hyper::header::common::util as header_util;
use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC};
use js::jsapi::{JSContext, JSRuntime, JSTracer};
use js::jsapi::{JS_SetGCParameter, JSGC_MAX_BYTES};
use js::jsapi::{JS_SetGCCallback, JSGCStatus, JSGC_BEGIN, JSGC_END};
use js::rust::{Cx, RtUtils};
use js;
use url::Url;
use libc::size_t;
use std::any::{Any, AnyRefExt};
use std::collections::HashSet;
use std::comm::{channel, Sender, Receiver, Select};
use std::fmt::{mod, Show};
use std::mem::replace;
use std::rc::Rc;
use std::u32;
use time::{Tm, strptime};
local_data_key!(pub StackRoots: *const RootCollection)
pub enum TimerSource {
FromWindow(PipelineId),
FromWorker
}
/// Messages used to control script event loops, such as ScriptTask and
/// DedicatedWorkerGlobalScope.
pub enum ScriptMsg {
/// Acts on a fragment URL load on the specified pipeline (only dispatched
/// to ScriptTask).
TriggerFragmentMsg(PipelineId, Url),
/// Begins a content-initiated load on the specified pipeline (only
/// dispatched to ScriptTask).
TriggerLoadMsg(PipelineId, LoadData),
/// Instructs the script task to send a navigate message to
/// the constellation (only dispatched to ScriptTask).
NavigateMsg(NavigationDirection),
/// Fires a JavaScript timeout
/// TimerSource must be FromWindow when dispatched to ScriptTask and
/// must be FromWorker when dispatched to a DedicatedGlobalWorkerScope
FireTimerMsg(TimerSource, TimerId),
/// Notifies the script that a window associated with a particular pipeline
/// should be closed (only dispatched to ScriptTask).
ExitWindowMsg(PipelineId),
/// Notifies the script of progress on a fetch (dispatched to all tasks).
XHRProgressMsg(TrustedXHRAddress, XHRProgress),
/// Releases one reference to the XHR object (dispatched to all tasks).
XHRReleaseMsg(TrustedXHRAddress),
/// Message sent through Worker.postMessage (only dispatched to
/// DedicatedWorkerGlobalScope).
DOMMessage(*mut u64, size_t),
/// Posts a message to the Worker object (dispatched to all tasks).
WorkerPostMessage(TrustedWorkerAddress, *mut u64, size_t),
/// Releases one reference to the Worker object (dispatched to all tasks).
WorkerRelease(TrustedWorkerAddress),
}
/// Encapsulates internal communication within the script task.
#[deriving(Clone)]
pub struct ScriptChan(pub Sender<ScriptMsg>);
no_jsmanaged_fields!(ScriptChan)
impl ScriptChan {
/// Creates a new script chan.
pub fn new() -> (Receiver<ScriptMsg>, ScriptChan) {
let (chan, port) = channel();
(port, ScriptChan(chan))
}
}
pub struct StackRootTLS;
impl StackRootTLS {
pub fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *const RootCollection));
StackRootTLS
}
}
impl Drop for StackRootTLS {
fn drop(&mut self) {
let _ = StackRoots.replace(None);
}
}
/// Information for an entire page. Pages are top-level browsing contexts and can contain multiple
/// frames.
///
/// FIXME: Rename to `Page`, following WebKit?
pub struct ScriptTask {
/// A handle to the information pertaining to page layout
page: DOMRefCell<Rc<Page>>,
/// A handle to the image cache task.
image_cache_task: ImageCacheTask,
/// A handle to the resource task.
resource_task: ResourceTask,
/// The port on which the script task receives messages (load URL, exit, etc.)
port: Receiver<ScriptMsg>,
/// A channel to hand out to script task-based entities that need to be able to enqueue
/// events in the event queue.
chan: ScriptChan,
/// A channel to hand out to tasks that need to respond to a message from the script task.
control_chan: ScriptControlChan,
/// The port on which the constellation and layout tasks can communicate with the
/// script task.
control_port: Receiver<ConstellationControlMsg>,
/// For communicating load url messages to the constellation
constellation_chan: ConstellationChan,
/// A handle to the compositor for communicating ready state messages.
compositor: DOMRefCell<Box<ScriptListener+'static>>,
/// For providing instructions to an optional devtools server.
devtools_chan: Option<DevtoolsControlChan>,
/// For receiving commands from an optional devtools server. Will be ignored if
/// no such server exists.
devtools_port: DevtoolsControlPort,
/// The JavaScript runtime.
js_runtime: js::rust::rt,
/// The JSContext.
js_context: DOMRefCell<Option<Rc<Cx>>>,
mouse_over_targets: DOMRefCell<Option<Vec<JS<Node>>>>
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
/// when the script task fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
/// to forcibly tear down the JS compartments for pages associated with the failing ScriptTask.
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop for ScriptMemoryFailsafe<'a> {
fn drop(&mut self) {
match self.owner {
Some(owner) => {
let page = owner.page.borrow_mut();
for page in page.iter() {
*page.mut_js_info() = None;
}
*owner.js_context.borrow_mut() = None;
}
None => (),
}
}
}
trait PrivateScriptTaskHelpers {
fn click_event_filter_by_disabled_state(&self) -> bool;
}
impl<'a> PrivateScriptTaskHelpers for JSRef<'a, Node> {
fn click_event_filter_by_disabled_state(&self) -> bool {
match self.type_id() {
ElementNodeTypeId(HTMLButtonElementTypeId) |
ElementNodeTypeId(HTMLInputElementTypeId) |
// ElementNodeTypeId(HTMLKeygenElementTypeId) |
ElementNodeTypeId(HTMLOptionElementTypeId) |
ElementNodeTypeId(HTMLSelectElementTypeId) |
ElementNodeTypeId(HTMLTextAreaElementTypeId) if self.get_disabled_state() => true,
_ => false
}
}
}
impl ScriptTaskFactory for ScriptTask {
fn create_layout_channel(_phantom: Option<&mut ScriptTask>) -> OpaqueScriptLayoutChannel {
let (chan, port) = channel();
ScriptLayoutChan::new(chan, port)
}
fn clone_layout_channel(_phantom: Option<&mut ScriptTask>, pair: &OpaqueScriptLayoutChannel) -> Box<Any+Send> {
box pair.sender() as Box<Any+Send>
}
fn create<C>(_phantom: Option<&mut ScriptTask>,
id: PipelineId,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_chan: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: WindowSizeData)
where C: ScriptListener + Send + 'static {
let ConstellationChan(const_chan) = constellation_chan.clone();
let (script_chan, script_port) = channel();
let layout_chan = LayoutChan(layout_chan.sender());
spawn_named_with_send_on_failure("ScriptTask", task_state::SCRIPT, proc() {
let script_task = ScriptTask::new(id,
box compositor as Box<ScriptListener>,
layout_chan,
script_port,
ScriptChan(script_chan),
control_chan,
control_port,
constellation_chan,
resource_task,
storage_task,
image_cache_task,
devtools_chan,
window_size);
let mut failsafe = ScriptMemoryFailsafe::new(&script_task);
script_task.start();
// This must always be the very last operation performed before the task completes
failsafe.neuter();
}, FailureMsg(failure_msg), const_chan, false);
}
}
unsafe extern "C" fn debug_gc_callback(_rt: *mut JSRuntime, status: JSGCStatus) {
match status {
JSGC_BEGIN => task_state::enter(task_state::IN_GC),
JSGC_END => task_state::exit(task_state::IN_GC),
_ => (),
}
}
impl ScriptTask {
/// Creates a new script task.
pub fn new(id: PipelineId,
compositor: Box<ScriptListener+'static>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_chan: ConstellationChan,
resource_task: ResourceTask,
storage_task: StorageTask,
img_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: WindowSizeData)
-> ScriptTask {
let (js_runtime, js_context) = ScriptTask::new_rt_and_cx();
unsafe {
// JS_SetWrapObjectCallbacks clobbers the existing wrap callback,
// and JSCompartment::wrap crashes if that happens. The only way
// to retrieve the default callback is as the result of
// JS_SetWrapObjectCallbacks, which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
JS_SetWrapObjectCallbacks((*js_runtime).ptr,
callback,
Some(wrap_for_same_compartment),
Some(pre_wrap));
}
let page = Page::new(id, None, layout_chan, window_size,
resource_task.clone(),
storage_task,
constellation_chan.clone(),
js_context.clone());
// Notify devtools that a new script global exists.
//FIXME: Move this into handle_load after we create a window instead.
let (devtools_sender, devtools_receiver) = channel();
devtools_chan.as_ref().map(|chan| {
chan.send(NewGlobal(id, devtools_sender.clone()));
});
ScriptTask {
page: DOMRefCell::new(Rc::new(page)),
image_cache_task: img_cache_task,
resource_task: resource_task,
port: port,
chan: chan,
control_chan: control_chan,
control_port: control_port,
constellation_chan: constellation_chan,
compositor: DOMRefCell::new(compositor),
devtools_chan: devtools_chan,
devtools_port: devtools_receiver,
js_runtime: js_runtime,
js_context: DOMRefCell::new(Some(js_context)),
mouse_over_targets: DOMRefCell::new(None)
}
}
pub fn new_rt_and_cx() -> (js::rust::rt, Rc<Cx>) {
let js_runtime = js::rust::rt();
assert!({
let ptr: *mut JSRuntime = (*js_runtime).ptr;
ptr.is_not_null()
});
// Unconstrain the runtime's threshold on nominal heap size, to avoid
// triggering GC too often if operating continuously near an arbitrary
// finite threshold. This leaves the maximum-JS_malloc-bytes threshold
// still in effect to cause periodical, and we hope hygienic,
// last-ditch GCs from within the GC's allocator.
unsafe {
JS_SetGCParameter(js_runtime.ptr, JSGC_MAX_BYTES, u32::MAX);
}
let js_context = js_runtime.cx();
assert!({
let ptr: *mut JSContext = (*js_context).ptr;
ptr.is_not_null()
});
js_context.set_default_options_and_version();
js_context.set_logging_error_reporter();
unsafe {
JS_SetGCZeal((*js_context).ptr, 0, JS_DEFAULT_ZEAL_FREQ);
}
// Needed for debug assertions about whether GC is running.
if !cfg!(ndebug) {
unsafe {
JS_SetGCCallback(js_runtime.ptr, Some(debug_gc_callback));
}
}
(js_runtime, js_context)
}
pub fn get_cx(&self) -> *mut JSContext {
(**self.js_context.borrow().as_ref().unwrap()).ptr
}
/// Starts the script task. After calling this method, the script task will loop receiving
/// messages on its port.
pub fn start(&self) {
while self.handle_msgs() {
// Go on...
}
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
{
let page = self.page.borrow_mut();
for page in page.iter() {
// Only process a resize if layout is idle.
let layout_join_port = page.layout_join_port.borrow();
if layout_join_port.is_none() {
let mut resize_event = page.resize_event.get();
match resize_event.take() {
Some(size) => resizes.push((page.id, size)),
None => ()
}
page.resize_event.set(None);
}
}
}
for (id, size) in resizes.into_iter() {
self.handle_event(id, ResizeEvent(size));
}
enum MixedMessage {
FromConstellation(ConstellationControlMsg),
FromScript(ScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
}
// Store new resizes, and gather all other events.
let mut sequential = vec!();
// Receive at least one message so we don't spinloop.
let mut event = {
let sel = Select::new();
let mut port1 = sel.handle(&self.port);
let mut port2 = sel.handle(&self.control_port);
let mut port3 = sel.handle(&self.devtools_port);
unsafe {
port1.add();
port2.add();
if self.devtools_chan.is_some() {
port3.add();
}
}
let ret = sel.wait();
if ret == port1.id() {
FromScript(self.port.recv())
} else if ret == port2.id() {
FromConstellation(self.control_port.recv())
} else if ret == port3.id() {
FromDevtools(self.devtools_port.recv())
} else {
panic!("unexpected select result")
}
};
let mut needs_reflow = HashSet::new();
// Squash any pending resize and reflow events in the queue.
loop {
match event {
// This has to be handled before the ResizeMsg below,
// otherwise the page may not have been added to the
// child list yet, causing the find() to fail.
FromConstellation(AttachLayoutMsg(new_layout_info)) => {
self.handle_new_layout(new_layout_info);
}
FromConstellation(ResizeMsg(id, size)) => {
let page = self.page.borrow_mut();
let page = page.find(id).expect("resize sent to nonexistent pipeline");
page.resize_event.set(Some(size));
}
FromConstellation(SendEventMsg(id, ReflowEvent(node_addresses))) => {
let page = self.page.borrow_mut();
let inner_page = page.find(id).expect("Reflow sent to nonexistent pipeline");
let mut pending = inner_page.pending_dirty_nodes.borrow_mut();
pending.push_all_move(node_addresses);
needs_reflow.insert(id);
}
FromConstellation(ViewportMsg(id, rect)) => {
let page = self.page.borrow_mut();
let inner_page = page.find(id).expect("Page rect message sent to nonexistent pipeline");
if inner_page.set_page_clip_rect_with_new_viewport(rect) {
needs_reflow.insert(id);
}
}
_ => {
sequential.push(event);
}
}
// If any of our input sources has an event pending, we'll perform another iteration
// and check for more resize events. If there are no events pending, we'll move
// on and execute the sequential non-resize events we've seen.
match self.control_port.try_recv() {
Err(_) => match self.port.try_recv() {
Err(_) => match self.devtools_port.try_recv() {
Err(_) => break,
Ok(ev) => event = FromDevtools(ev),
},
Ok(ev) => event = FromScript(ev),
},
Ok(ev) => event = FromConstellation(ev),
}
}
// Process the gathered events.
for msg in sequential.into_iter() {
match msg {
// TODO(tkuehn) need to handle auxiliary layouts for iframes
FromConstellation(AttachLayoutMsg(_)) => panic!("should have handled AttachLayoutMsg already"),
FromConstellation(LoadMsg(id, load_data)) => self.load(id, load_data),
FromScript(TriggerLoadMsg(id, load_data)) => self.trigger_load(id, load_data),
FromScript(TriggerFragmentMsg(id, url)) => self.trigger_fragment(id, url),
FromConstellation(SendEventMsg(id, event)) => self.handle_event(id, event),
FromScript(FireTimerMsg(FromWindow(id), timer_id)) => self.handle_fire_timer_msg(id, timer_id),
FromScript(FireTimerMsg(FromWorker, _)) => panic!("Worker timeouts must not be sent to script task"),
FromScript(NavigateMsg(direction)) => self.handle_navigate_msg(direction),
FromConstellation(ReflowCompleteMsg(id, reflow_id)) => self.handle_reflow_complete_msg(id, reflow_id),
FromConstellation(ResizeInactiveMsg(id, new_size)) => self.handle_resize_inactive_msg(id, new_size),
FromConstellation(ExitPipelineMsg(id)) => if self.handle_exit_pipeline_msg(id) { return false },
FromConstellation(ViewportMsg(..)) => panic!("should have handled ViewportMsg already"),
FromScript(ExitWindowMsg(id)) => self.handle_exit_window_msg(id),
FromConstellation(ResizeMsg(..)) => panic!("should have handled ResizeMsg already"),
FromScript(XHRProgressMsg(addr, progress)) => XMLHttpRequest::handle_progress(addr, progress),
FromScript(XHRReleaseMsg(addr)) => XMLHttpRequest::handle_release(addr),
FromScript(DOMMessage(..)) => panic!("unexpected message"),
FromScript(WorkerPostMessage(addr, data, nbytes)) => Worker::handle_message(addr, data, nbytes),
FromScript(WorkerRelease(addr)) => Worker::handle_release(addr),
FromDevtools(EvaluateJS(id, s, reply)) => devtools::handle_evaluate_js(&*self.page.borrow(), id, s, reply),
FromDevtools(GetRootNode(id, reply)) => devtools::handle_get_root_node(&*self.page.borrow(), id, reply),
FromDevtools(GetDocumentElement(id, reply)) => devtools::handle_get_document_element(&*self.page.borrow(), id, reply),
FromDevtools(GetChildren(id, node_id, reply)) => devtools::handle_get_children(&*self.page.borrow(), id, node_id, reply),
FromDevtools(GetLayout(id, node_id, reply)) => devtools::handle_get_layout(&*self.page.borrow(), id, node_id, reply),
FromDevtools(ModifyAttribute(id, node_id, modifications)) => devtools::handle_modify_attribute(&*self.page.borrow(), id, node_id, modifications),
}
}
// Now process any pending reflows.
for id in needs_reflow.into_iter() {
self.handle_event(id, ReflowEvent(SmallVec1::new()));
}
true
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) {
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let page = self.page.borrow_mut();
let parent_page = page.find(old_pipeline_id).expect("ScriptTask: received a layout
whose parent has a PipelineId which does not correspond to a pipeline in the script
task's page tree. This is a bug.");
let new_page = {
let window_size = parent_page.window_size.get();
Page::new(new_pipeline_id, Some(subpage_id),
LayoutChan(layout_chan.downcast_ref::<Sender<layout_interface::Msg>>().unwrap().clone()),
window_size,
parent_page.resource_task.clone(),
parent_page.storage_task.clone(),
self.constellation_chan.clone(),
self.js_context.borrow().as_ref().unwrap().clone())
};
parent_page.children.borrow_mut().push(Rc::new(new_page));
}
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for a
pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame();
let window = frame.as_ref().unwrap().window.root();
window.handle_fire_timer(timer_id);
}
/// Handles a notification that reflow completed.
fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) {
debug!("Script: Reflow {} complete for {}", reflow_id, pipeline_id);
let page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect(
"ScriptTask: received a load message for a layout channel that is not associated \
with this script task. This is a bug.");
let last_reflow_id = page.last_reflow_id.get();
if last_reflow_id == reflow_id {
let mut layout_join_port = page.layout_join_port.borrow_mut();
*layout_join_port = None;
}
self.compositor.borrow_mut().set_ready_state(pipeline_id, FinishedLoading);
if page.pending_reflows.get() > 0 {
page.pending_reflows.set(0);
self.force_reflow(&*page);
}
}
/// Handles a navigate forward or backward message.
/// TODO(tkuehn): is it ever possible to navigate only on a subframe?
fn handle_navigate_msg(&self, direction: NavigationDirection) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::NavigateMsg(direction));
}
/// Window was resized, but this script was not active, so don't reflow yet
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let page = self.page.borrow_mut();
let page = page.find(id).expect("Received resize message for PipelineId not associated
with a page in the page tree. This is a bug.");
page.window_size.set(new_size);
match &mut *page.mut_url() {
&Some((_, ref mut needs_reflow)) => *needs_reflow = true,
&None => (),
}
}
/// We have gotten a window.close from script, which we pass on to the compositor.
/// We do not shut down the script task now, because the compositor will ask the
/// constellation to shut down the pipeline, which will clean everything up
/// normally. If we do exit, we will tear down the DOM nodes, possibly at a point
/// where layout is still accessing them.
fn handle_exit_window_msg(&self, _: PipelineId) {
debug!("script task handling exit window msg");
// TODO(tkuehn): currently there is only one window,
// so this can afford to be naive and just shut down the
// compositor. In the future it'll need to be smarter.
self.compositor.borrow_mut().close();
}
/// Handles a request to exit the script task and shut down layout.
/// Returns true if the script task should shut down and false otherwise.
fn handle_exit_pipeline_msg(&self, id: PipelineId) -> bool {
// If root is being exited, shut down all pages
let page = self.page.borrow_mut();
if page.id == id {
debug!("shutting down layout for root page {}", id);
*self.js_context.borrow_mut() = None;
shut_down_layout(&*page, (*self.js_runtime).ptr);
return true
}
// otherwise find just the matching page and exit all sub-pages
match page.remove(id) {
Some(ref mut page) => {
shut_down_layout(&*page, (*self.js_runtime).ptr);
false
}
// TODO(tkuehn): pipeline closing is currently duplicated across
// script and constellation, which can cause this to happen. Constellation
// needs to be smarter about exiting pipelines.
None => false,
}
}
/// The entry point to document loading. Defines bindings, sets up the window and document
/// objects, parses HTML and CSS, and kicks off initial layout.
fn load(&self, pipeline_id: PipelineId, load_data: LoadData) {
let mut url = load_data.url.clone();
debug!("ScriptTask: loading {} on page {}", url, pipeline_id);
let page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. This
is a bug.");
let last_url = match &mut *page.mut_url() {
&Some((ref mut loaded, ref mut needs_reflow)) if *loaded == url => {
if replace(needs_reflow, false) {
self.force_reflow(&*page);
}
return;
},
url => replace(url, None).map(|(loaded, _)| loaded),
};
let is_javascript = url.scheme.as_slice() == "javascript";
let cx = self.js_context.borrow();
let cx = cx.as_ref().unwrap();
// Create the window and document objects.
let window = Window::new(cx.ptr,
page.clone(),
self.chan.clone(),
self.control_chan.clone(),
self.compositor.borrow_mut().dup(),
self.image_cache_task.clone()).root();
let doc_url = if is_javascript {
let doc_url = last_url.unwrap_or_else(|| {
Url::parse("about:blank").unwrap()
});
*page.mut_url() = Some((doc_url.clone(), true));
doc_url
} else {
url.clone()
};
let document = Document::new(*window, Some(doc_url.clone()), HTMLDocument,
None, FromParser).root();
window.init_browser_context(*document);
self.compositor.borrow_mut().set_ready_state(pipeline_id, Loading);
{
// Create the root frame.
let mut frame = page.mut_frame();
*frame = Some(Frame {
document: JS::from_rooted(*document),
window: JS::from_rooted(*window),
});
}
let (parser_input, base_url) = if !is_javascript {
// Wait for the LoadResponse so that the parser knows the final URL.
let (input_chan, input_port) = channel();
self.resource_task.send(Load(NetLoadData {
url: url,
method: load_data.method,
headers: load_data.headers,
data: load_data.data,
cors: None,
consumer: input_chan,
}));
let load_response = input_port.recv();
load_response.metadata.headers.as_ref().map(|headers| {
headers.get().map(|&LastModified(ref tm)| {
document.set_last_modified(dom_last_modified(tm));
});
});
let base_url = load_response.metadata.final_url.clone();
{
// Store the final URL before we start parsing, so that DOM routines
// (e.g. HTMLImageElement::update_image) can resolve relative URLs
// correctly.
*page.mut_url() = Some((base_url.clone(), true));
}
(InputUrl(load_response), base_url)
} else {
let evalstr = load_data.url.non_relative_scheme_data().unwrap();
let jsval = window.evaluate_js_with_result(evalstr);
let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, Empty);
(InputString(strval.unwrap_or("".to_string())), doc_url)
};
parse_html(*document, parser_input, base_url);
url = page.get_url().clone();
document.set_ready_state(DocumentReadyStateValues::Interactive);
// Kick off the initial reflow of the page.
debug!("kicking off initial reflow of {}", url);
document.content_changed(NodeCast::from_ref(*document));
window.flush_layout();
{
// No more reflow required
let mut page_url = page.mut_url();
*page_url = Some((url.clone(), false));
}
// https://html.spec.whatwg.org/multipage/#the-end step 4
let event = Event::new(global::Window(*window), "DOMContentLoaded".to_string(),
DoesNotBubble, NotCancelable).root();
let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(*document);
let _ = doctarget.DispatchEvent(*event);
// We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during
// the initial load.
// https://html.spec.whatwg.org/multipage/#the-end step 7
document.set_ready_state(DocumentReadyStateValues::Complete);
let event = Event::new(global::Window(*window), "load".to_string(), DoesNotBubble, NotCancelable).root();
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window);
let _ = wintarget.dispatch_event_with_target(Some(doctarget), *event);
*page.fragment_name.borrow_mut() = url.fragment;
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(LoadCompleteMsg);
}
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: JSRef<Element>) {
let node: JSRef<Node> = NodeCast::from_ref(node);
let rect = node.get_bounding_content_box();
let point = Point2D(to_frac_px(rect.origin.x).to_f32().unwrap(),
to_frac_px(rect.origin.y).to_f32().unwrap());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
self.compositor.borrow_mut().scroll_fragment_point(pipeline_id, LayerId::null(), point);
}
fn force_reflow(&self, page: &Page) {
{
let mut pending = page.pending_dirty_nodes.borrow_mut();
let js_runtime = self.js_runtime.deref().ptr;
for untrusted_node in pending.into_iter() {
let node = node::from_untrusted_node_address(js_runtime, untrusted_node).root();
node.dirty();
}
}
page.damage();
page.reflow(ReflowForDisplay,
self.control_chan.clone(),
&mut **self.compositor.borrow_mut(),
NoQuery);
}
/// This is the main entry point for receiving and dispatching DOM events.
///
/// TODO: Actually perform DOM event dispatch.
fn handle_event(&self, pipeline_id: PipelineId, event: CompositorEvent) {
match event {
ResizeEvent(new_size) => {
self.handle_resize_event(pipeline_id, new_size);
}
// FIXME(pcwalton): This reflows the entire document and is not incremental-y.
ReflowEvent(to_dirty) => {
self.handle_reflow_event(pipeline_id, to_dirty);
}
ClickEvent(_button, point) => {
self.handle_click_event(pipeline_id, _button, point);
}
MouseDownEvent(..) => {}
MouseUpEvent(..) => {}
MouseMoveEvent(point) => {
self.handle_mouse_move_event(pipeline_id, point);
}
KeyEvent(key, state, modifiers) => {
self.dispatch_key_event(key, state, modifiers, pipeline_id);
}
}
}
/// The entry point for all key processing for web content
fn dispatch_key_event(&self, key: Key,
state: KeyState,
modifiers: KeyModifiers,
pipeline_id: PipelineId) {
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
let window = frame.as_ref().unwrap().window.root();
let doc = window.Document().root();
let focused = doc.get_focused_element().root();
let body = doc.GetBody().root();
let target: JSRef<EventTarget> = match (&focused, &body) {
(&Some(ref focused), _) => EventTargetCast::from_ref(**focused),
(&None, &Some(ref body)) => EventTargetCast::from_ref(**body),
(&None, &None) => EventTargetCast::from_ref(*window),
};
let ctrl = modifiers.contains(CONTROL);
let alt = modifiers.contains(ALT);
let shift = modifiers.contains(SHIFT);
let meta = modifiers.contains(SUPER);
let is_composing = false;
let is_repeating = state == Repeated;
let ev_type = match state {
Pressed | Repeated => "keydown",
Released => "keyup",
}.to_string();
let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(*window, ev_type, true, true, Some(*window), 0,
props.key.to_string(), props.code.to_string(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
None, props.key_code).root();
let event = EventCast::from_ref(*keyevent);
let _ = target.DispatchEvent(event);
let mut prevented = event.DefaultPrevented();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(*window, "keypress".to_string(), true, true, Some(*window),
0, props.key.to_string(), props.code.to_string(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
props.char_code, 0).root();
let _ = target.DispatchEvent(EventCast::from_ref(*event));
let ev = EventCast::from_ref(*event);
prevented = ev.DefaultPrevented();
// TODO: if keypress event is canceled, prevent firing input events
}
// This behavior is unspecced
// We are supposed to dispatch synthetic click activation for Space and/or Return,
// however *when* we do it is up to us
// I'm dispatching it after the key event so the script has a chance to cancel it
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337
match key {
Key::KeySpace if !prevented && state == Released => {
let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target);
maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.synthetic_click_activation(ctrl, alt, shift, meta)));
}
Key::KeyEnter if !prevented && state == Released => {
let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target);
maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.implicit_submission(ctrl, alt, shift, meta)));
}
_ => ()
}
window.flush_layout();
}
/// The entry point for content to notify that a new load has been requested
/// for the given pipeline.
fn trigger_load(&self, pipeline_id: PipelineId, load_data: LoadData) {
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(LoadUrlMsg(pipeline_id, load_data));
}
/// The entry point for content to notify that a fragment url has been requested
/// for the given pipeline.
fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => {
self.scroll_fragment_point(pipeline_id, *node);
}
None => {}
}
}
fn handle_resize_event(&self, pipeline_id: PipelineId, new_size: WindowSizeData) {
let window = {
let page = get_page(&*self.page.borrow(), pipeline_id);
page.window_size.set(new_size);
let frame = page.frame();
if frame.is_some() {
self.force_reflow(&*page);
}
let fragment_node =
page.fragment_name
.borrow_mut()
.take()
.and_then(|name| page.find_fragment_node(name))
.root();
match fragment_node {
Some(node) => self.scroll_fragment_point(pipeline_id, *node),
None => {}
}
frame.as_ref().map(|frame| Temporary::new(frame.window.clone()))
};
match window.root() {
Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(window.clone(),
"resize".to_string(), false,
false, Some(window.clone()),
0i32).root();
let event: JSRef<Event> = EventCast::from_ref(*uievent);
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window);
let _ = wintarget.dispatch_event_with_target(None, event);
}
None => ()
}
}
fn handle_reflow_event(&self, pipeline_id: PipelineId, to_dirty: SmallVec1<UntrustedNodeAddress>) {
debug!("script got reflow event");
assert_eq!(to_dirty.len(), 0);
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
if frame.is_some() {
let in_layout = page.layout_join_port.borrow().is_some();
if in_layout {
page.pending_reflows.set(page.pending_reflows.get() + 1);
} else {
self.force_reflow(&*page);
}
}
}
fn handle_click_event(&self, pipeline_id: PipelineId, _button: uint, point: Point2D<f32>) {
debug!("ClickEvent: clicked at {}", point);
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.hit_test(&point) {
Some(node_address) => {
debug!("node address is {}", node_address);
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.ptr, node_address).root();
let maybe_node = if !temp_node.is_element() {
temp_node.ancestors().find(|node| node.is_element())
} else {
Some(*temp_node)
};
match maybe_node {
Some(node) => {
debug!("clicked on {:s}", node.debug_str());
// Prevent click event if form control element is disabled.
if node.click_event_filter_by_disabled_state() { return; }
match *page.frame() {
Some(ref frame) => {
let window = frame.window.root();
let doc = window.Document().root();
doc.begin_focus_transaction();
let event =
Event::new(global::Window(*window),
"click".to_string(),
Bubbles, Cancelable).root();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events
event.set_trusted(true);
// https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps
let el = ElementCast::to_ref(node).unwrap(); // is_element() check already exists above
el.authentic_click_activation(*event);
doc.commit_focus_transaction();
window.flush_layout();
}
None => {}
}
}
None => {}
}
}
None => {}
}
}
fn handle_mouse_move_event(&self, pipeline_id: PipelineId, point: Point2D<f32>) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.get_nodes_under_mouse(&point) {
Some(node_address) => {
let mut target_list = vec!();
let mut target_compare = false;
let mouse_over_targets = &mut *self.mouse_over_targets.borrow_mut();
match *mouse_over_targets {
Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.iter_mut() {
let node = node.root();
node.set_hover_state(false);
}
}
None => {}
}
for node_address in node_address.iter() {
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.ptr, *node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
node.set_hover_state(true);
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if !target_compare {
target_compare = !mouse_over_targets.contains(&JS::from_rooted(node));
}
}
None => {}
}
target_list.push(JS::from_rooted(node));
}
None => {}
}
}
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if mouse_over_targets.len() != target_list.len() {
target_compare = true;
}
}
None => { target_compare = true; }
}
if target_compare {
if mouse_over_targets.is_some() {
self.force_reflow(&*page);
}
*mouse_over_targets = Some(target_list);
}
}
None => {}
}
}
}
/// Shuts down layout for the given page tree.
fn shut_down_layout(page_tree: &Rc<Page>, rt: *mut JSRuntime) {
for page in page_tree.iter() {
page.join_layout();
// Tell the layout task to begin shutting down, and wait until it
// processed this message.
let (response_chan, response_port) = channel();
let LayoutChan(ref chan) = page.layout_chan;
chan.send(layout_interface::PrepareToExitMsg(response_chan));
response_port.recv();
}
// Remove our references to the DOM objects in this page tree.
for page in page_tree.iter() {
*page.mut_frame() = None;
}
// Drop our references to the JSContext, potentially triggering a GC.
for page in page_tree.iter() {
*page.mut_js_info() = None;
}
// Force a GC to make sure that our DOM reflectors are released before we tell
// layout to exit.
unsafe {
JS_GC(rt);
}
// Destroy the layout task. If there were node leaks, layout will now crash safely.
for page in page_tree.iter() {
let LayoutChan(ref chan) = page.layout_chan;
chan.send(layout_interface::ExitNowMsg);
}
}
pub fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> {
page.find(pipeline_id).expect("ScriptTask: received an event \
message for a layout channel that is not associated with this script task.\
This is a bug.")
}
//FIXME(seanmonstar): uplift to Hyper
#[deriving(Clone)]
struct LastModified(pub Tm);
impl Header for LastModified {
#[inline]
fn header_name(_: Option<LastModified>) -> &'static str {
"Last-Modified"
}
// Parses an RFC 2616 compliant date/time string,
fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> {
header_util::from_one_raw_str(raw).and_then(|s: String| {
let s = s.as_slice();
strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
strptime(s, "%A, %d-%b-%y %T %Z")
}).or_else(|_| {
strptime(s, "%c")
}).ok().map(|tm| LastModified(tm))
})
}
}
impl HeaderFormat for LastModified {
// a localized date/time string in a format suitable
// for document.lastModified.
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
let LastModified(ref tm) = *self;
match tm.tm_gmtoff {
0 => tm.rfc822().fmt(f),
_ => tm.to_utc().rfc822().fmt(f)
}
}
}
fn dom_last_modified(tm: &Tm) -> String {
tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap()
}
Rename base_url to final_url in ScriptTask::load.
This seems like a clearer name, as it's used for more than just as a base url.
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing
//! and layout tasks.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyStateValues};
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, EventTargetCast, NodeCast, EventCast};
use dom::bindings::conversions::{FromJSValConvertible, Empty};
use dom::bindings::global;
use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalRootable};
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap};
use dom::document::{Document, HTMLDocument, DocumentHelpers, FromParser};
use dom::element::{Element, HTMLButtonElementTypeId, HTMLInputElementTypeId};
use dom::element::{HTMLSelectElementTypeId, HTMLTextAreaElementTypeId, HTMLOptionElementTypeId, ActivationElementHelpers};
use dom::event::{Event, EventHelpers, Bubbles, DoesNotBubble, Cancelable, NotCancelable};
use dom::uievent::UIEvent;
use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::keyboardevent::KeyboardEvent;
use dom::node;
use dom::node::{ElementNodeTypeId, Node, NodeHelpers};
use dom::window::{Window, WindowHelpers};
use dom::worker::{Worker, TrustedWorkerAddress};
use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress};
use parse::html::{InputString, InputUrl, parse_html};
use layout_interface::{ScriptLayoutChan, LayoutChan, NoQuery, ReflowForDisplay};
use layout_interface;
use page::{Page, IterablePage, Frame};
use timers::TimerId;
use devtools;
use devtools_traits::{DevtoolsControlChan, DevtoolsControlPort, NewGlobal, GetRootNode};
use devtools_traits::{DevtoolScriptControlMsg, EvaluateJS, GetDocumentElement};
use devtools_traits::{GetChildren, GetLayout, ModifyAttribute};
use script_traits::{CompositorEvent, ResizeEvent, ReflowEvent, ClickEvent, MouseDownEvent};
use script_traits::{MouseMoveEvent, MouseUpEvent, ConstellationControlMsg, ScriptTaskFactory};
use script_traits::{ResizeMsg, AttachLayoutMsg, LoadMsg, ViewportMsg, SendEventMsg};
use script_traits::{ResizeInactiveMsg, ExitPipelineMsg, NewLayoutInfo, OpaqueScriptLayoutChannel};
use script_traits::{ScriptControlChan, ReflowCompleteMsg, UntrustedNodeAddress, KeyEvent};
use servo_msg::compositor_msg::{FinishedLoading, LayerId, Loading};
use servo_msg::compositor_msg::{ScriptListener};
use servo_msg::constellation_msg::{ConstellationChan, LoadCompleteMsg, LoadUrlMsg, NavigationDirection};
use servo_msg::constellation_msg::{LoadData, PipelineId, Failure, FailureMsg, WindowSizeData, Key, KeyState};
use servo_msg::constellation_msg::{KeyModifiers, SUPER, SHIFT, CONTROL, ALT, Repeated, Pressed};
use servo_msg::constellation_msg::{Released};
use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::{ResourceTask, Load};
use servo_net::resource_task::LoadData as NetLoadData;
use servo_net::storage_task::StorageTask;
use servo_util::geometry::to_frac_px;
use servo_util::smallvec::{SmallVec1, SmallVec};
use servo_util::task::spawn_named_with_send_on_failure;
use servo_util::task_state;
use geom::point::Point2D;
use hyper::header::{Header, HeaderFormat};
use hyper::header::common::util as header_util;
use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC};
use js::jsapi::{JSContext, JSRuntime, JSTracer};
use js::jsapi::{JS_SetGCParameter, JSGC_MAX_BYTES};
use js::jsapi::{JS_SetGCCallback, JSGCStatus, JSGC_BEGIN, JSGC_END};
use js::rust::{Cx, RtUtils};
use js;
use url::Url;
use libc::size_t;
use std::any::{Any, AnyRefExt};
use std::collections::HashSet;
use std::comm::{channel, Sender, Receiver, Select};
use std::fmt::{mod, Show};
use std::mem::replace;
use std::rc::Rc;
use std::u32;
use time::{Tm, strptime};
local_data_key!(pub StackRoots: *const RootCollection)
pub enum TimerSource {
FromWindow(PipelineId),
FromWorker
}
/// Messages used to control script event loops, such as ScriptTask and
/// DedicatedWorkerGlobalScope.
pub enum ScriptMsg {
/// Acts on a fragment URL load on the specified pipeline (only dispatched
/// to ScriptTask).
TriggerFragmentMsg(PipelineId, Url),
/// Begins a content-initiated load on the specified pipeline (only
/// dispatched to ScriptTask).
TriggerLoadMsg(PipelineId, LoadData),
/// Instructs the script task to send a navigate message to
/// the constellation (only dispatched to ScriptTask).
NavigateMsg(NavigationDirection),
/// Fires a JavaScript timeout
/// TimerSource must be FromWindow when dispatched to ScriptTask and
/// must be FromWorker when dispatched to a DedicatedGlobalWorkerScope
FireTimerMsg(TimerSource, TimerId),
/// Notifies the script that a window associated with a particular pipeline
/// should be closed (only dispatched to ScriptTask).
ExitWindowMsg(PipelineId),
/// Notifies the script of progress on a fetch (dispatched to all tasks).
XHRProgressMsg(TrustedXHRAddress, XHRProgress),
/// Releases one reference to the XHR object (dispatched to all tasks).
XHRReleaseMsg(TrustedXHRAddress),
/// Message sent through Worker.postMessage (only dispatched to
/// DedicatedWorkerGlobalScope).
DOMMessage(*mut u64, size_t),
/// Posts a message to the Worker object (dispatched to all tasks).
WorkerPostMessage(TrustedWorkerAddress, *mut u64, size_t),
/// Releases one reference to the Worker object (dispatched to all tasks).
WorkerRelease(TrustedWorkerAddress),
}
/// Encapsulates internal communication within the script task.
#[deriving(Clone)]
pub struct ScriptChan(pub Sender<ScriptMsg>);
no_jsmanaged_fields!(ScriptChan)
impl ScriptChan {
/// Creates a new script chan.
pub fn new() -> (Receiver<ScriptMsg>, ScriptChan) {
let (chan, port) = channel();
(port, ScriptChan(chan))
}
}
pub struct StackRootTLS;
impl StackRootTLS {
pub fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *const RootCollection));
StackRootTLS
}
}
impl Drop for StackRootTLS {
fn drop(&mut self) {
let _ = StackRoots.replace(None);
}
}
/// Information for an entire page. Pages are top-level browsing contexts and can contain multiple
/// frames.
///
/// FIXME: Rename to `Page`, following WebKit?
pub struct ScriptTask {
/// A handle to the information pertaining to page layout
page: DOMRefCell<Rc<Page>>,
/// A handle to the image cache task.
image_cache_task: ImageCacheTask,
/// A handle to the resource task.
resource_task: ResourceTask,
/// The port on which the script task receives messages (load URL, exit, etc.)
port: Receiver<ScriptMsg>,
/// A channel to hand out to script task-based entities that need to be able to enqueue
/// events in the event queue.
chan: ScriptChan,
/// A channel to hand out to tasks that need to respond to a message from the script task.
control_chan: ScriptControlChan,
/// The port on which the constellation and layout tasks can communicate with the
/// script task.
control_port: Receiver<ConstellationControlMsg>,
/// For communicating load url messages to the constellation
constellation_chan: ConstellationChan,
/// A handle to the compositor for communicating ready state messages.
compositor: DOMRefCell<Box<ScriptListener+'static>>,
/// For providing instructions to an optional devtools server.
devtools_chan: Option<DevtoolsControlChan>,
/// For receiving commands from an optional devtools server. Will be ignored if
/// no such server exists.
devtools_port: DevtoolsControlPort,
/// The JavaScript runtime.
js_runtime: js::rust::rt,
/// The JSContext.
js_context: DOMRefCell<Option<Rc<Cx>>>,
mouse_over_targets: DOMRefCell<Option<Vec<JS<Node>>>>
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
/// are no reachable, owning pointers to the DOM memory, so it never gets freed by default
/// when the script task fails. The ScriptMemoryFailsafe uses the destructor bomb pattern
/// to forcibly tear down the JS compartments for pages associated with the failing ScriptTask.
struct ScriptMemoryFailsafe<'a> {
owner: Option<&'a ScriptTask>,
}
impl<'a> ScriptMemoryFailsafe<'a> {
fn neuter(&mut self) {
self.owner = None;
}
fn new(owner: &'a ScriptTask) -> ScriptMemoryFailsafe<'a> {
ScriptMemoryFailsafe {
owner: Some(owner),
}
}
}
#[unsafe_destructor]
impl<'a> Drop for ScriptMemoryFailsafe<'a> {
fn drop(&mut self) {
match self.owner {
Some(owner) => {
let page = owner.page.borrow_mut();
for page in page.iter() {
*page.mut_js_info() = None;
}
*owner.js_context.borrow_mut() = None;
}
None => (),
}
}
}
trait PrivateScriptTaskHelpers {
fn click_event_filter_by_disabled_state(&self) -> bool;
}
impl<'a> PrivateScriptTaskHelpers for JSRef<'a, Node> {
fn click_event_filter_by_disabled_state(&self) -> bool {
match self.type_id() {
ElementNodeTypeId(HTMLButtonElementTypeId) |
ElementNodeTypeId(HTMLInputElementTypeId) |
// ElementNodeTypeId(HTMLKeygenElementTypeId) |
ElementNodeTypeId(HTMLOptionElementTypeId) |
ElementNodeTypeId(HTMLSelectElementTypeId) |
ElementNodeTypeId(HTMLTextAreaElementTypeId) if self.get_disabled_state() => true,
_ => false
}
}
}
impl ScriptTaskFactory for ScriptTask {
fn create_layout_channel(_phantom: Option<&mut ScriptTask>) -> OpaqueScriptLayoutChannel {
let (chan, port) = channel();
ScriptLayoutChan::new(chan, port)
}
fn clone_layout_channel(_phantom: Option<&mut ScriptTask>, pair: &OpaqueScriptLayoutChannel) -> Box<Any+Send> {
box pair.sender() as Box<Any+Send>
}
fn create<C>(_phantom: Option<&mut ScriptTask>,
id: PipelineId,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_chan: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: WindowSizeData)
where C: ScriptListener + Send + 'static {
let ConstellationChan(const_chan) = constellation_chan.clone();
let (script_chan, script_port) = channel();
let layout_chan = LayoutChan(layout_chan.sender());
spawn_named_with_send_on_failure("ScriptTask", task_state::SCRIPT, proc() {
let script_task = ScriptTask::new(id,
box compositor as Box<ScriptListener>,
layout_chan,
script_port,
ScriptChan(script_chan),
control_chan,
control_port,
constellation_chan,
resource_task,
storage_task,
image_cache_task,
devtools_chan,
window_size);
let mut failsafe = ScriptMemoryFailsafe::new(&script_task);
script_task.start();
// This must always be the very last operation performed before the task completes
failsafe.neuter();
}, FailureMsg(failure_msg), const_chan, false);
}
}
unsafe extern "C" fn debug_gc_callback(_rt: *mut JSRuntime, status: JSGCStatus) {
match status {
JSGC_BEGIN => task_state::enter(task_state::IN_GC),
JSGC_END => task_state::exit(task_state::IN_GC),
_ => (),
}
}
impl ScriptTask {
/// Creates a new script task.
pub fn new(id: PipelineId,
compositor: Box<ScriptListener+'static>,
layout_chan: LayoutChan,
port: Receiver<ScriptMsg>,
chan: ScriptChan,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_chan: ConstellationChan,
resource_task: ResourceTask,
storage_task: StorageTask,
img_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: WindowSizeData)
-> ScriptTask {
let (js_runtime, js_context) = ScriptTask::new_rt_and_cx();
unsafe {
// JS_SetWrapObjectCallbacks clobbers the existing wrap callback,
// and JSCompartment::wrap crashes if that happens. The only way
// to retrieve the default callback is as the result of
// JS_SetWrapObjectCallbacks, which is why we call it twice.
let callback = JS_SetWrapObjectCallbacks((*js_runtime).ptr,
None,
Some(wrap_for_same_compartment),
None);
JS_SetWrapObjectCallbacks((*js_runtime).ptr,
callback,
Some(wrap_for_same_compartment),
Some(pre_wrap));
}
let page = Page::new(id, None, layout_chan, window_size,
resource_task.clone(),
storage_task,
constellation_chan.clone(),
js_context.clone());
// Notify devtools that a new script global exists.
//FIXME: Move this into handle_load after we create a window instead.
let (devtools_sender, devtools_receiver) = channel();
devtools_chan.as_ref().map(|chan| {
chan.send(NewGlobal(id, devtools_sender.clone()));
});
ScriptTask {
page: DOMRefCell::new(Rc::new(page)),
image_cache_task: img_cache_task,
resource_task: resource_task,
port: port,
chan: chan,
control_chan: control_chan,
control_port: control_port,
constellation_chan: constellation_chan,
compositor: DOMRefCell::new(compositor),
devtools_chan: devtools_chan,
devtools_port: devtools_receiver,
js_runtime: js_runtime,
js_context: DOMRefCell::new(Some(js_context)),
mouse_over_targets: DOMRefCell::new(None)
}
}
pub fn new_rt_and_cx() -> (js::rust::rt, Rc<Cx>) {
let js_runtime = js::rust::rt();
assert!({
let ptr: *mut JSRuntime = (*js_runtime).ptr;
ptr.is_not_null()
});
// Unconstrain the runtime's threshold on nominal heap size, to avoid
// triggering GC too often if operating continuously near an arbitrary
// finite threshold. This leaves the maximum-JS_malloc-bytes threshold
// still in effect to cause periodical, and we hope hygienic,
// last-ditch GCs from within the GC's allocator.
unsafe {
JS_SetGCParameter(js_runtime.ptr, JSGC_MAX_BYTES, u32::MAX);
}
let js_context = js_runtime.cx();
assert!({
let ptr: *mut JSContext = (*js_context).ptr;
ptr.is_not_null()
});
js_context.set_default_options_and_version();
js_context.set_logging_error_reporter();
unsafe {
JS_SetGCZeal((*js_context).ptr, 0, JS_DEFAULT_ZEAL_FREQ);
}
// Needed for debug assertions about whether GC is running.
if !cfg!(ndebug) {
unsafe {
JS_SetGCCallback(js_runtime.ptr, Some(debug_gc_callback));
}
}
(js_runtime, js_context)
}
pub fn get_cx(&self) -> *mut JSContext {
(**self.js_context.borrow().as_ref().unwrap()).ptr
}
/// Starts the script task. After calling this method, the script task will loop receiving
/// messages on its port.
pub fn start(&self) {
while self.handle_msgs() {
// Go on...
}
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
{
let page = self.page.borrow_mut();
for page in page.iter() {
// Only process a resize if layout is idle.
let layout_join_port = page.layout_join_port.borrow();
if layout_join_port.is_none() {
let mut resize_event = page.resize_event.get();
match resize_event.take() {
Some(size) => resizes.push((page.id, size)),
None => ()
}
page.resize_event.set(None);
}
}
}
for (id, size) in resizes.into_iter() {
self.handle_event(id, ResizeEvent(size));
}
enum MixedMessage {
FromConstellation(ConstellationControlMsg),
FromScript(ScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
}
// Store new resizes, and gather all other events.
let mut sequential = vec!();
// Receive at least one message so we don't spinloop.
let mut event = {
let sel = Select::new();
let mut port1 = sel.handle(&self.port);
let mut port2 = sel.handle(&self.control_port);
let mut port3 = sel.handle(&self.devtools_port);
unsafe {
port1.add();
port2.add();
if self.devtools_chan.is_some() {
port3.add();
}
}
let ret = sel.wait();
if ret == port1.id() {
FromScript(self.port.recv())
} else if ret == port2.id() {
FromConstellation(self.control_port.recv())
} else if ret == port3.id() {
FromDevtools(self.devtools_port.recv())
} else {
panic!("unexpected select result")
}
};
let mut needs_reflow = HashSet::new();
// Squash any pending resize and reflow events in the queue.
loop {
match event {
// This has to be handled before the ResizeMsg below,
// otherwise the page may not have been added to the
// child list yet, causing the find() to fail.
FromConstellation(AttachLayoutMsg(new_layout_info)) => {
self.handle_new_layout(new_layout_info);
}
FromConstellation(ResizeMsg(id, size)) => {
let page = self.page.borrow_mut();
let page = page.find(id).expect("resize sent to nonexistent pipeline");
page.resize_event.set(Some(size));
}
FromConstellation(SendEventMsg(id, ReflowEvent(node_addresses))) => {
let page = self.page.borrow_mut();
let inner_page = page.find(id).expect("Reflow sent to nonexistent pipeline");
let mut pending = inner_page.pending_dirty_nodes.borrow_mut();
pending.push_all_move(node_addresses);
needs_reflow.insert(id);
}
FromConstellation(ViewportMsg(id, rect)) => {
let page = self.page.borrow_mut();
let inner_page = page.find(id).expect("Page rect message sent to nonexistent pipeline");
if inner_page.set_page_clip_rect_with_new_viewport(rect) {
needs_reflow.insert(id);
}
}
_ => {
sequential.push(event);
}
}
// If any of our input sources has an event pending, we'll perform another iteration
// and check for more resize events. If there are no events pending, we'll move
// on and execute the sequential non-resize events we've seen.
match self.control_port.try_recv() {
Err(_) => match self.port.try_recv() {
Err(_) => match self.devtools_port.try_recv() {
Err(_) => break,
Ok(ev) => event = FromDevtools(ev),
},
Ok(ev) => event = FromScript(ev),
},
Ok(ev) => event = FromConstellation(ev),
}
}
// Process the gathered events.
for msg in sequential.into_iter() {
match msg {
// TODO(tkuehn) need to handle auxiliary layouts for iframes
FromConstellation(AttachLayoutMsg(_)) => panic!("should have handled AttachLayoutMsg already"),
FromConstellation(LoadMsg(id, load_data)) => self.load(id, load_data),
FromScript(TriggerLoadMsg(id, load_data)) => self.trigger_load(id, load_data),
FromScript(TriggerFragmentMsg(id, url)) => self.trigger_fragment(id, url),
FromConstellation(SendEventMsg(id, event)) => self.handle_event(id, event),
FromScript(FireTimerMsg(FromWindow(id), timer_id)) => self.handle_fire_timer_msg(id, timer_id),
FromScript(FireTimerMsg(FromWorker, _)) => panic!("Worker timeouts must not be sent to script task"),
FromScript(NavigateMsg(direction)) => self.handle_navigate_msg(direction),
FromConstellation(ReflowCompleteMsg(id, reflow_id)) => self.handle_reflow_complete_msg(id, reflow_id),
FromConstellation(ResizeInactiveMsg(id, new_size)) => self.handle_resize_inactive_msg(id, new_size),
FromConstellation(ExitPipelineMsg(id)) => if self.handle_exit_pipeline_msg(id) { return false },
FromConstellation(ViewportMsg(..)) => panic!("should have handled ViewportMsg already"),
FromScript(ExitWindowMsg(id)) => self.handle_exit_window_msg(id),
FromConstellation(ResizeMsg(..)) => panic!("should have handled ResizeMsg already"),
FromScript(XHRProgressMsg(addr, progress)) => XMLHttpRequest::handle_progress(addr, progress),
FromScript(XHRReleaseMsg(addr)) => XMLHttpRequest::handle_release(addr),
FromScript(DOMMessage(..)) => panic!("unexpected message"),
FromScript(WorkerPostMessage(addr, data, nbytes)) => Worker::handle_message(addr, data, nbytes),
FromScript(WorkerRelease(addr)) => Worker::handle_release(addr),
FromDevtools(EvaluateJS(id, s, reply)) => devtools::handle_evaluate_js(&*self.page.borrow(), id, s, reply),
FromDevtools(GetRootNode(id, reply)) => devtools::handle_get_root_node(&*self.page.borrow(), id, reply),
FromDevtools(GetDocumentElement(id, reply)) => devtools::handle_get_document_element(&*self.page.borrow(), id, reply),
FromDevtools(GetChildren(id, node_id, reply)) => devtools::handle_get_children(&*self.page.borrow(), id, node_id, reply),
FromDevtools(GetLayout(id, node_id, reply)) => devtools::handle_get_layout(&*self.page.borrow(), id, node_id, reply),
FromDevtools(ModifyAttribute(id, node_id, modifications)) => devtools::handle_modify_attribute(&*self.page.borrow(), id, node_id, modifications),
}
}
// Now process any pending reflows.
for id in needs_reflow.into_iter() {
self.handle_event(id, ReflowEvent(SmallVec1::new()));
}
true
}
fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) {
let NewLayoutInfo {
old_pipeline_id,
new_pipeline_id,
subpage_id,
layout_chan
} = new_layout_info;
let page = self.page.borrow_mut();
let parent_page = page.find(old_pipeline_id).expect("ScriptTask: received a layout
whose parent has a PipelineId which does not correspond to a pipeline in the script
task's page tree. This is a bug.");
let new_page = {
let window_size = parent_page.window_size.get();
Page::new(new_pipeline_id, Some(subpage_id),
LayoutChan(layout_chan.downcast_ref::<Sender<layout_interface::Msg>>().unwrap().clone()),
window_size,
parent_page.resource_task.clone(),
parent_page.storage_task.clone(),
self.constellation_chan.clone(),
self.js_context.borrow().as_ref().unwrap().clone())
};
parent_page.children.borrow_mut().push(Rc::new(new_page));
}
/// Handles a timer that fired.
fn handle_fire_timer_msg(&self, id: PipelineId, timer_id: TimerId) {
let page = self.page.borrow_mut();
let page = page.find(id).expect("ScriptTask: received fire timer msg for a
pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame();
let window = frame.as_ref().unwrap().window.root();
window.handle_fire_timer(timer_id);
}
/// Handles a notification that reflow completed.
fn handle_reflow_complete_msg(&self, pipeline_id: PipelineId, reflow_id: uint) {
debug!("Script: Reflow {} complete for {}", reflow_id, pipeline_id);
let page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect(
"ScriptTask: received a load message for a layout channel that is not associated \
with this script task. This is a bug.");
let last_reflow_id = page.last_reflow_id.get();
if last_reflow_id == reflow_id {
let mut layout_join_port = page.layout_join_port.borrow_mut();
*layout_join_port = None;
}
self.compositor.borrow_mut().set_ready_state(pipeline_id, FinishedLoading);
if page.pending_reflows.get() > 0 {
page.pending_reflows.set(0);
self.force_reflow(&*page);
}
}
/// Handles a navigate forward or backward message.
/// TODO(tkuehn): is it ever possible to navigate only on a subframe?
fn handle_navigate_msg(&self, direction: NavigationDirection) {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(constellation_msg::NavigateMsg(direction));
}
/// Window was resized, but this script was not active, so don't reflow yet
fn handle_resize_inactive_msg(&self, id: PipelineId, new_size: WindowSizeData) {
let page = self.page.borrow_mut();
let page = page.find(id).expect("Received resize message for PipelineId not associated
with a page in the page tree. This is a bug.");
page.window_size.set(new_size);
match &mut *page.mut_url() {
&Some((_, ref mut needs_reflow)) => *needs_reflow = true,
&None => (),
}
}
/// We have gotten a window.close from script, which we pass on to the compositor.
/// We do not shut down the script task now, because the compositor will ask the
/// constellation to shut down the pipeline, which will clean everything up
/// normally. If we do exit, we will tear down the DOM nodes, possibly at a point
/// where layout is still accessing them.
fn handle_exit_window_msg(&self, _: PipelineId) {
debug!("script task handling exit window msg");
// TODO(tkuehn): currently there is only one window,
// so this can afford to be naive and just shut down the
// compositor. In the future it'll need to be smarter.
self.compositor.borrow_mut().close();
}
/// Handles a request to exit the script task and shut down layout.
/// Returns true if the script task should shut down and false otherwise.
fn handle_exit_pipeline_msg(&self, id: PipelineId) -> bool {
// If root is being exited, shut down all pages
let page = self.page.borrow_mut();
if page.id == id {
debug!("shutting down layout for root page {}", id);
*self.js_context.borrow_mut() = None;
shut_down_layout(&*page, (*self.js_runtime).ptr);
return true
}
// otherwise find just the matching page and exit all sub-pages
match page.remove(id) {
Some(ref mut page) => {
shut_down_layout(&*page, (*self.js_runtime).ptr);
false
}
// TODO(tkuehn): pipeline closing is currently duplicated across
// script and constellation, which can cause this to happen. Constellation
// needs to be smarter about exiting pipelines.
None => false,
}
}
/// The entry point to document loading. Defines bindings, sets up the window and document
/// objects, parses HTML and CSS, and kicks off initial layout.
fn load(&self, pipeline_id: PipelineId, load_data: LoadData) {
let mut url = load_data.url.clone();
debug!("ScriptTask: loading {} on page {}", url, pipeline_id);
let page = self.page.borrow_mut();
let page = page.find(pipeline_id).expect("ScriptTask: received a load
message for a layout channel that is not associated with this script task. This
is a bug.");
let last_url = match &mut *page.mut_url() {
&Some((ref mut loaded, ref mut needs_reflow)) if *loaded == url => {
if replace(needs_reflow, false) {
self.force_reflow(&*page);
}
return;
},
url => replace(url, None).map(|(loaded, _)| loaded),
};
let is_javascript = url.scheme.as_slice() == "javascript";
let cx = self.js_context.borrow();
let cx = cx.as_ref().unwrap();
// Create the window and document objects.
let window = Window::new(cx.ptr,
page.clone(),
self.chan.clone(),
self.control_chan.clone(),
self.compositor.borrow_mut().dup(),
self.image_cache_task.clone()).root();
let doc_url = if is_javascript {
let doc_url = last_url.unwrap_or_else(|| {
Url::parse("about:blank").unwrap()
});
*page.mut_url() = Some((doc_url.clone(), true));
doc_url
} else {
url.clone()
};
let document = Document::new(*window, Some(doc_url.clone()), HTMLDocument,
None, FromParser).root();
window.init_browser_context(*document);
self.compositor.borrow_mut().set_ready_state(pipeline_id, Loading);
{
// Create the root frame.
let mut frame = page.mut_frame();
*frame = Some(Frame {
document: JS::from_rooted(*document),
window: JS::from_rooted(*window),
});
}
let (parser_input, final_url) = if !is_javascript {
// Wait for the LoadResponse so that the parser knows the final URL.
let (input_chan, input_port) = channel();
self.resource_task.send(Load(NetLoadData {
url: url,
method: load_data.method,
headers: load_data.headers,
data: load_data.data,
cors: None,
consumer: input_chan,
}));
let load_response = input_port.recv();
load_response.metadata.headers.as_ref().map(|headers| {
headers.get().map(|&LastModified(ref tm)| {
document.set_last_modified(dom_last_modified(tm));
});
});
let final_url = load_response.metadata.final_url.clone();
{
// Store the final URL before we start parsing, so that DOM routines
// (e.g. HTMLImageElement::update_image) can resolve relative URLs
// correctly.
*page.mut_url() = Some((final_url.clone(), true));
}
(InputUrl(load_response), final_url)
} else {
let evalstr = load_data.url.non_relative_scheme_data().unwrap();
let jsval = window.evaluate_js_with_result(evalstr);
let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, Empty);
(InputString(strval.unwrap_or("".to_string())), doc_url)
};
parse_html(*document, parser_input, final_url);
url = page.get_url().clone();
document.set_ready_state(DocumentReadyStateValues::Interactive);
// Kick off the initial reflow of the page.
debug!("kicking off initial reflow of {}", url);
document.content_changed(NodeCast::from_ref(*document));
window.flush_layout();
{
// No more reflow required
let mut page_url = page.mut_url();
*page_url = Some((url.clone(), false));
}
// https://html.spec.whatwg.org/multipage/#the-end step 4
let event = Event::new(global::Window(*window), "DOMContentLoaded".to_string(),
DoesNotBubble, NotCancelable).root();
let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(*document);
let _ = doctarget.DispatchEvent(*event);
// We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during
// the initial load.
// https://html.spec.whatwg.org/multipage/#the-end step 7
document.set_ready_state(DocumentReadyStateValues::Complete);
let event = Event::new(global::Window(*window), "load".to_string(), DoesNotBubble, NotCancelable).root();
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window);
let _ = wintarget.dispatch_event_with_target(Some(doctarget), *event);
*page.fragment_name.borrow_mut() = url.fragment;
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(LoadCompleteMsg);
}
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: JSRef<Element>) {
let node: JSRef<Node> = NodeCast::from_ref(node);
let rect = node.get_bounding_content_box();
let point = Point2D(to_frac_px(rect.origin.x).to_f32().unwrap(),
to_frac_px(rect.origin.y).to_f32().unwrap());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
self.compositor.borrow_mut().scroll_fragment_point(pipeline_id, LayerId::null(), point);
}
fn force_reflow(&self, page: &Page) {
{
let mut pending = page.pending_dirty_nodes.borrow_mut();
let js_runtime = self.js_runtime.deref().ptr;
for untrusted_node in pending.into_iter() {
let node = node::from_untrusted_node_address(js_runtime, untrusted_node).root();
node.dirty();
}
}
page.damage();
page.reflow(ReflowForDisplay,
self.control_chan.clone(),
&mut **self.compositor.borrow_mut(),
NoQuery);
}
/// This is the main entry point for receiving and dispatching DOM events.
///
/// TODO: Actually perform DOM event dispatch.
fn handle_event(&self, pipeline_id: PipelineId, event: CompositorEvent) {
match event {
ResizeEvent(new_size) => {
self.handle_resize_event(pipeline_id, new_size);
}
// FIXME(pcwalton): This reflows the entire document and is not incremental-y.
ReflowEvent(to_dirty) => {
self.handle_reflow_event(pipeline_id, to_dirty);
}
ClickEvent(_button, point) => {
self.handle_click_event(pipeline_id, _button, point);
}
MouseDownEvent(..) => {}
MouseUpEvent(..) => {}
MouseMoveEvent(point) => {
self.handle_mouse_move_event(pipeline_id, point);
}
KeyEvent(key, state, modifiers) => {
self.dispatch_key_event(key, state, modifiers, pipeline_id);
}
}
}
/// The entry point for all key processing for web content
fn dispatch_key_event(&self, key: Key,
state: KeyState,
modifiers: KeyModifiers,
pipeline_id: PipelineId) {
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
let window = frame.as_ref().unwrap().window.root();
let doc = window.Document().root();
let focused = doc.get_focused_element().root();
let body = doc.GetBody().root();
let target: JSRef<EventTarget> = match (&focused, &body) {
(&Some(ref focused), _) => EventTargetCast::from_ref(**focused),
(&None, &Some(ref body)) => EventTargetCast::from_ref(**body),
(&None, &None) => EventTargetCast::from_ref(*window),
};
let ctrl = modifiers.contains(CONTROL);
let alt = modifiers.contains(ALT);
let shift = modifiers.contains(SHIFT);
let meta = modifiers.contains(SUPER);
let is_composing = false;
let is_repeating = state == Repeated;
let ev_type = match state {
Pressed | Repeated => "keydown",
Released => "keyup",
}.to_string();
let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(*window, ev_type, true, true, Some(*window), 0,
props.key.to_string(), props.code.to_string(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
None, props.key_code).root();
let event = EventCast::from_ref(*keyevent);
let _ = target.DispatchEvent(event);
let mut prevented = event.DefaultPrevented();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(*window, "keypress".to_string(), true, true, Some(*window),
0, props.key.to_string(), props.code.to_string(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
props.char_code, 0).root();
let _ = target.DispatchEvent(EventCast::from_ref(*event));
let ev = EventCast::from_ref(*event);
prevented = ev.DefaultPrevented();
// TODO: if keypress event is canceled, prevent firing input events
}
// This behavior is unspecced
// We are supposed to dispatch synthetic click activation for Space and/or Return,
// however *when* we do it is up to us
// I'm dispatching it after the key event so the script has a chance to cancel it
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337
match key {
Key::KeySpace if !prevented && state == Released => {
let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target);
maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.synthetic_click_activation(ctrl, alt, shift, meta)));
}
Key::KeyEnter if !prevented && state == Released => {
let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target);
maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.implicit_submission(ctrl, alt, shift, meta)));
}
_ => ()
}
window.flush_layout();
}
/// The entry point for content to notify that a new load has been requested
/// for the given pipeline.
fn trigger_load(&self, pipeline_id: PipelineId, load_data: LoadData) {
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(LoadUrlMsg(pipeline_id, load_data));
}
/// The entry point for content to notify that a fragment url has been requested
/// for the given pipeline.
fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => {
self.scroll_fragment_point(pipeline_id, *node);
}
None => {}
}
}
fn handle_resize_event(&self, pipeline_id: PipelineId, new_size: WindowSizeData) {
let window = {
let page = get_page(&*self.page.borrow(), pipeline_id);
page.window_size.set(new_size);
let frame = page.frame();
if frame.is_some() {
self.force_reflow(&*page);
}
let fragment_node =
page.fragment_name
.borrow_mut()
.take()
.and_then(|name| page.find_fragment_node(name))
.root();
match fragment_node {
Some(node) => self.scroll_fragment_point(pipeline_id, *node),
None => {}
}
frame.as_ref().map(|frame| Temporary::new(frame.window.clone()))
};
match window.root() {
Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(window.clone(),
"resize".to_string(), false,
false, Some(window.clone()),
0i32).root();
let event: JSRef<Event> = EventCast::from_ref(*uievent);
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window);
let _ = wintarget.dispatch_event_with_target(None, event);
}
None => ()
}
}
fn handle_reflow_event(&self, pipeline_id: PipelineId, to_dirty: SmallVec1<UntrustedNodeAddress>) {
debug!("script got reflow event");
assert_eq!(to_dirty.len(), 0);
let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame();
if frame.is_some() {
let in_layout = page.layout_join_port.borrow().is_some();
if in_layout {
page.pending_reflows.set(page.pending_reflows.get() + 1);
} else {
self.force_reflow(&*page);
}
}
}
fn handle_click_event(&self, pipeline_id: PipelineId, _button: uint, point: Point2D<f32>) {
debug!("ClickEvent: clicked at {}", point);
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.hit_test(&point) {
Some(node_address) => {
debug!("node address is {}", node_address);
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.ptr, node_address).root();
let maybe_node = if !temp_node.is_element() {
temp_node.ancestors().find(|node| node.is_element())
} else {
Some(*temp_node)
};
match maybe_node {
Some(node) => {
debug!("clicked on {:s}", node.debug_str());
// Prevent click event if form control element is disabled.
if node.click_event_filter_by_disabled_state() { return; }
match *page.frame() {
Some(ref frame) => {
let window = frame.window.root();
let doc = window.Document().root();
doc.begin_focus_transaction();
let event =
Event::new(global::Window(*window),
"click".to_string(),
Bubbles, Cancelable).root();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events
event.set_trusted(true);
// https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps
let el = ElementCast::to_ref(node).unwrap(); // is_element() check already exists above
el.authentic_click_activation(*event);
doc.commit_focus_transaction();
window.flush_layout();
}
None => {}
}
}
None => {}
}
}
None => {}
}
}
fn handle_mouse_move_event(&self, pipeline_id: PipelineId, point: Point2D<f32>) {
let page = get_page(&*self.page.borrow(), pipeline_id);
match page.get_nodes_under_mouse(&point) {
Some(node_address) => {
let mut target_list = vec!();
let mut target_compare = false;
let mouse_over_targets = &mut *self.mouse_over_targets.borrow_mut();
match *mouse_over_targets {
Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.iter_mut() {
let node = node.root();
node.set_hover_state(false);
}
}
None => {}
}
for node_address in node_address.iter() {
let temp_node =
node::from_untrusted_node_address(
self.js_runtime.ptr, *node_address);
let maybe_node = temp_node.root().ancestors().find(|node| node.is_element());
match maybe_node {
Some(node) => {
node.set_hover_state(true);
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if !target_compare {
target_compare = !mouse_over_targets.contains(&JS::from_rooted(node));
}
}
None => {}
}
target_list.push(JS::from_rooted(node));
}
None => {}
}
}
match *mouse_over_targets {
Some(ref mouse_over_targets) => {
if mouse_over_targets.len() != target_list.len() {
target_compare = true;
}
}
None => { target_compare = true; }
}
if target_compare {
if mouse_over_targets.is_some() {
self.force_reflow(&*page);
}
*mouse_over_targets = Some(target_list);
}
}
None => {}
}
}
}
/// Shuts down layout for the given page tree.
fn shut_down_layout(page_tree: &Rc<Page>, rt: *mut JSRuntime) {
for page in page_tree.iter() {
page.join_layout();
// Tell the layout task to begin shutting down, and wait until it
// processed this message.
let (response_chan, response_port) = channel();
let LayoutChan(ref chan) = page.layout_chan;
chan.send(layout_interface::PrepareToExitMsg(response_chan));
response_port.recv();
}
// Remove our references to the DOM objects in this page tree.
for page in page_tree.iter() {
*page.mut_frame() = None;
}
// Drop our references to the JSContext, potentially triggering a GC.
for page in page_tree.iter() {
*page.mut_js_info() = None;
}
// Force a GC to make sure that our DOM reflectors are released before we tell
// layout to exit.
unsafe {
JS_GC(rt);
}
// Destroy the layout task. If there were node leaks, layout will now crash safely.
for page in page_tree.iter() {
let LayoutChan(ref chan) = page.layout_chan;
chan.send(layout_interface::ExitNowMsg);
}
}
pub fn get_page(page: &Rc<Page>, pipeline_id: PipelineId) -> Rc<Page> {
page.find(pipeline_id).expect("ScriptTask: received an event \
message for a layout channel that is not associated with this script task.\
This is a bug.")
}
//FIXME(seanmonstar): uplift to Hyper
#[deriving(Clone)]
struct LastModified(pub Tm);
impl Header for LastModified {
#[inline]
fn header_name(_: Option<LastModified>) -> &'static str {
"Last-Modified"
}
// Parses an RFC 2616 compliant date/time string,
fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> {
header_util::from_one_raw_str(raw).and_then(|s: String| {
let s = s.as_slice();
strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
strptime(s, "%A, %d-%b-%y %T %Z")
}).or_else(|_| {
strptime(s, "%c")
}).ok().map(|tm| LastModified(tm))
})
}
}
impl HeaderFormat for LastModified {
// a localized date/time string in a format suitable
// for document.lastModified.
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
let LastModified(ref tm) = *self;
match tm.tm_gmtoff {
0 => tm.rfc822().fmt(f),
_ => tm.to_utc().rfc822().fmt(f)
}
}
}
fn dom_last_modified(tm: &Tm) -> String {
tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap()
}
|
use nom::{
be_u8, be_u16,
IResult,
ErrorCode, Err,
};
use frame::{
ChannelAssignment, NumberType,
Frame,
Header, Footer,
};
use metadata::StreamInfo;
use utility::{crc8, crc16, to_u32};
pub fn frame_parser<'a>(input: &'a [u8], stream_info: &StreamInfo)
-> IResult<'a, &'a [u8], Frame> {
let result = chain!(input,
frame_header: apply!(header, stream_info) ~
frame_footer: footer,
|| {
Frame {
header: frame_header,
footer: frame_footer,
}
}
);
match result {
IResult::Done(i, frame) => {
// All frame bytes before the crc-16
let end = (input.len() - i.len()) - 2;
let Footer(crc) = frame.footer;
if crc16(&input[0..end]) == crc {
IResult::Done(i, frame)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn blocking_strategy(input: &[u8]) -> IResult<&[u8], bool> {
match take!(input, 2) {
IResult::Done(i, bytes) => {
let sync_code = ((bytes[0] as u16) << 6) +
(bytes[1] as u16) >> 2;
let is_valid = ((bytes[1] >> 1) & 0b01) == 0;
if sync_code == 0b11111111111110 && is_valid {
let is_variable_block_size = (bytes[1] & 0b01) == 1;
IResult::Done(i, is_variable_block_size)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn block_sample(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
match take!(input, 1) {
IResult::Done(i, bytes) => {
let sample_byte = bytes[0] & 0x0f;
if sample_byte != 0x0f {
let block_byte = bytes[0] >> 4;
IResult::Done(i, (block_byte, sample_byte))
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn channel_bits(input: &[u8]) -> IResult<&[u8], (ChannelAssignment, u8)> {
match take!(input, 1) {
IResult::Done(i, bytes) => {
let channel_assignment = match bytes[0] >> 4 {
0b0000...0b0111 => ChannelAssignment::Independent,
0b1000 => ChannelAssignment::LeftSide,
0b1001 => ChannelAssignment::RightSide,
0b1010 => ChannelAssignment::MiddleSide,
_ => ChannelAssignment::Independent,
};
let size_byte = (bytes[0] >> 1) & 0b0111;
let is_valid = (bytes[0] & 0b01) == 0;
if is_valid {
IResult::Done(i, (channel_assignment, size_byte))
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn utf8_size(input: &[u8], is_u64: bool)
-> IResult<&[u8], Option<(usize, u8)>> {
map!(input, be_u8, |utf8_header| {
match utf8_header {
0b00000000...0b01111111 => Some((0, utf8_header)),
0b11000000...0b11011111 => Some((1, utf8_header & 0b00011111)),
0b11100000...0b11101111 => Some((2, utf8_header & 0b00001111)),
0b11110000...0b11110111 => Some((3, utf8_header & 0b00000111)),
0b11111000...0b11111011 => Some((4, utf8_header & 0b00000011)),
0b11111100...0b11111101 => Some((5, utf8_header & 0b00000001)),
0b11111110 => if is_u64 { Some((6, 0)) } else { None },
_ => None,
}
})
}
fn sample_or_frame_number(input: &[u8], is_sample: bool,
(size, value): (usize, u8))
-> IResult<&[u8], NumberType> {
let mut result = value as u64;
let mut is_error = false;
match take!(input, size) {
IResult::Done(i, bytes) => {
for i in 0..size {
let byte = bytes[i] as u64;
if byte >= 0b10000000 && byte <= 0b10111111 {
result = (result << 6) + (byte & 0b00111111);
} else {
is_error = true;
break;
}
}
if is_error {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
} else if is_sample {
IResult::Done(i, NumberType::Sample(result))
} else {
IResult::Done(i, NumberType::Frame(result as u32))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn secondary_block_size(input: &[u8], block_byte: u8)
-> IResult<&[u8], Option<u32>> {
match block_byte {
0b0110 => opt!(input, map!(take!(1), to_u32)),
0b0111 => opt!(input, map!(take!(2), to_u32)),
_ => IResult::Done(input, None)
}
}
fn secondary_sample_rate(input: &[u8], sample_byte: u8)
-> IResult<&[u8], Option<u32>> {
match sample_byte {
0b1100 => opt!(input, map!(take!(1), to_u32)),
0b1101 => opt!(input, map!(take!(2), to_u32)),
0b1110 => opt!(input, map!(take!(2), to_u32)),
_ => IResult::Done(input, None)
}
}
fn header<'a>(input: &'a [u8], stream_info: &StreamInfo)
-> IResult<'a, &'a [u8], Header> {
let result = chain!(input,
is_variable_block_size: blocking_strategy ~
tuple0: block_sample ~
tuple1: channel_bits ~
number_opt: apply!(utf8_size, is_variable_block_size) ~
number_length: expr_opt!(number_opt) ~
number: apply!(sample_or_frame_number, is_variable_block_size,
number_length) ~
alt_block_size: apply!(secondary_block_size, tuple0.0) ~
alt_sample_rate: apply!(secondary_sample_rate, tuple0.1) ~
crc: be_u8,
|| {
let (block_byte, sample_byte) = tuple0;
let (channel_assignment, size_byte) = tuple1;
let block_size = match block_byte {
0b0000 => 0,
0b0001 => 192,
0b0010...0b0101 => 576 * 2_u32.pow(block_byte as u32 - 2),
0b0110 | 0b0111 => alt_block_size.unwrap() + 1,
0b1000...0b1111 => 256 * 2_u32.pow(block_byte as u32 - 8),
_ => unreachable!(),
};
let sample_rate = match sample_byte {
0b0000 => stream_info.sample_rate,
0b0001 => 88200,
0b0010 => 176400,
0b0011 => 192000,
0b0100 => 8000,
0b0101 => 16000,
0b0110 => 22050,
0b0111 => 24000,
0b1000 => 32000,
0b1001 => 44100,
0b1010 => 48000,
0b1011 => 96000,
0b1100 => alt_sample_rate.unwrap() * 1000,
0b1101 => alt_sample_rate.unwrap(),
0b1110 => alt_sample_rate.unwrap() * 10,
0b1111 => 0,
_ => unreachable!(),
};
let bits_per_sample = match size_byte {
0b0000 => stream_info.bits_per_sample as usize,
0b0001 => 8,
0b0010 => 12,
0b0011 => 0,
0b0100 => 16,
0b0101 => 20,
0b0110 => 24,
0b0111 => 0,
_ => unreachable!(),
};
Header {
block_size: block_size,
sample_rate: sample_rate,
channel_assignment: channel_assignment,
bits_per_sample: bits_per_sample,
number: number,
crc: crc,
}
}
);
match result {
IResult::Done(i, frame_header) => {
// All header bytes before the crc-8
let end = (input.len() - i.len()) - 1;
if crc8(&input[0..end]) == frame_header.crc {
IResult::Done(i, frame_header)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
named!(footer <&[u8], Footer>, map!(be_u16, Footer));
Add checking the validity of block_byte
use nom::{
be_u8, be_u16,
IResult,
ErrorCode, Err,
};
use frame::{
ChannelAssignment, NumberType,
Frame,
Header, Footer,
};
use metadata::StreamInfo;
use utility::{crc8, crc16, to_u32};
pub fn frame_parser<'a>(input: &'a [u8], stream_info: &StreamInfo)
-> IResult<'a, &'a [u8], Frame> {
let result = chain!(input,
frame_header: apply!(header, stream_info) ~
frame_footer: footer,
|| {
Frame {
header: frame_header,
footer: frame_footer,
}
}
);
match result {
IResult::Done(i, frame) => {
// All frame bytes before the crc-16
let end = (input.len() - i.len()) - 2;
let Footer(crc) = frame.footer;
if crc16(&input[0..end]) == crc {
IResult::Done(i, frame)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn blocking_strategy(input: &[u8]) -> IResult<&[u8], bool> {
match take!(input, 2) {
IResult::Done(i, bytes) => {
let sync_code = ((bytes[0] as u16) << 6) +
(bytes[1] as u16) >> 2;
let is_valid = ((bytes[1] >> 1) & 0b01) == 0;
if sync_code == 0b11111111111110 && is_valid {
let is_variable_block_size = (bytes[1] & 0b01) == 1;
IResult::Done(i, is_variable_block_size)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn block_sample(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
match take!(input, 1) {
IResult::Done(i, bytes) => {
let block_byte = bytes[0] >> 4;
let sample_byte = bytes[0] & 0x0f;
let is_valid = block_byte != 0b0000 && sample_byte != 0b1111;
if is_valid {
IResult::Done(i, (block_byte, sample_byte))
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn channel_bits(input: &[u8]) -> IResult<&[u8], (ChannelAssignment, u8)> {
match take!(input, 1) {
IResult::Done(i, bytes) => {
let channel_assignment = match bytes[0] >> 4 {
0b0000...0b0111 => ChannelAssignment::Independent,
0b1000 => ChannelAssignment::LeftSide,
0b1001 => ChannelAssignment::RightSide,
0b1010 => ChannelAssignment::MiddleSide,
_ => ChannelAssignment::Independent,
};
let size_byte = (bytes[0] >> 1) & 0b0111;
let is_valid = (bytes[0] & 0b01) == 0;
if is_valid {
IResult::Done(i, (channel_assignment, size_byte))
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn utf8_size(input: &[u8], is_u64: bool)
-> IResult<&[u8], Option<(usize, u8)>> {
map!(input, be_u8, |utf8_header| {
match utf8_header {
0b00000000...0b01111111 => Some((0, utf8_header)),
0b11000000...0b11011111 => Some((1, utf8_header & 0b00011111)),
0b11100000...0b11101111 => Some((2, utf8_header & 0b00001111)),
0b11110000...0b11110111 => Some((3, utf8_header & 0b00000111)),
0b11111000...0b11111011 => Some((4, utf8_header & 0b00000011)),
0b11111100...0b11111101 => Some((5, utf8_header & 0b00000001)),
0b11111110 => if is_u64 { Some((6, 0)) } else { None },
_ => None,
}
})
}
fn sample_or_frame_number(input: &[u8], is_sample: bool,
(size, value): (usize, u8))
-> IResult<&[u8], NumberType> {
let mut result = value as u64;
let mut is_error = false;
match take!(input, size) {
IResult::Done(i, bytes) => {
for i in 0..size {
let byte = bytes[i] as u64;
if byte >= 0b10000000 && byte <= 0b10111111 {
result = (result << 6) + (byte & 0b00111111);
} else {
is_error = true;
break;
}
}
if is_error {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
} else if is_sample {
IResult::Done(i, NumberType::Sample(result))
} else {
IResult::Done(i, NumberType::Frame(result as u32))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
fn secondary_block_size(input: &[u8], block_byte: u8)
-> IResult<&[u8], Option<u32>> {
match block_byte {
0b0110 => opt!(input, map!(take!(1), to_u32)),
0b0111 => opt!(input, map!(take!(2), to_u32)),
_ => IResult::Done(input, None)
}
}
fn secondary_sample_rate(input: &[u8], sample_byte: u8)
-> IResult<&[u8], Option<u32>> {
match sample_byte {
0b1100 => opt!(input, map!(take!(1), to_u32)),
0b1101 => opt!(input, map!(take!(2), to_u32)),
0b1110 => opt!(input, map!(take!(2), to_u32)),
_ => IResult::Done(input, None)
}
}
fn header<'a>(input: &'a [u8], stream_info: &StreamInfo)
-> IResult<'a, &'a [u8], Header> {
let result = chain!(input,
is_variable_block_size: blocking_strategy ~
tuple0: block_sample ~
tuple1: channel_bits ~
number_opt: apply!(utf8_size, is_variable_block_size) ~
number_length: expr_opt!(number_opt) ~
number: apply!(sample_or_frame_number, is_variable_block_size,
number_length) ~
alt_block_size: apply!(secondary_block_size, tuple0.0) ~
alt_sample_rate: apply!(secondary_sample_rate, tuple0.1) ~
crc: be_u8,
|| {
let (block_byte, sample_byte) = tuple0;
let (channel_assignment, size_byte) = tuple1;
let block_size = match block_byte {
0b0000 => 0,
0b0001 => 192,
0b0010...0b0101 => 576 * 2_u32.pow(block_byte as u32 - 2),
0b0110 | 0b0111 => alt_block_size.unwrap() + 1,
0b1000...0b1111 => 256 * 2_u32.pow(block_byte as u32 - 8),
_ => unreachable!(),
};
let sample_rate = match sample_byte {
0b0000 => stream_info.sample_rate,
0b0001 => 88200,
0b0010 => 176400,
0b0011 => 192000,
0b0100 => 8000,
0b0101 => 16000,
0b0110 => 22050,
0b0111 => 24000,
0b1000 => 32000,
0b1001 => 44100,
0b1010 => 48000,
0b1011 => 96000,
0b1100 => alt_sample_rate.unwrap() * 1000,
0b1101 => alt_sample_rate.unwrap(),
0b1110 => alt_sample_rate.unwrap() * 10,
0b1111 => 0,
_ => unreachable!(),
};
let bits_per_sample = match size_byte {
0b0000 => stream_info.bits_per_sample as usize,
0b0001 => 8,
0b0010 => 12,
0b0011 => 0,
0b0100 => 16,
0b0101 => 20,
0b0110 => 24,
0b0111 => 0,
_ => unreachable!(),
};
Header {
block_size: block_size,
sample_rate: sample_rate,
channel_assignment: channel_assignment,
bits_per_sample: bits_per_sample,
number: number,
crc: crc,
}
}
);
match result {
IResult::Done(i, frame_header) => {
// All header bytes before the crc-8
let end = (input.len() - i.len()) - 1;
if crc8(&input[0..end]) == frame_header.crc {
IResult::Done(i, frame_header)
} else {
IResult::Error(Err::Position(ErrorCode::Digit as u32, input))
}
}
IResult::Error(error) => IResult::Error(error),
IResult::Incomplete(need) => IResult::Incomplete(need),
}
}
named!(footer <&[u8], Footer>, map!(be_u16, Footer));
|
//! Mesh generation from primitives like cubes and spheres.
//!
//! This module provides unit primitives that can be used to form complex
//! iterator expressions to generate meshes via a stream of topology and
//! geometry. This data can be collected into simple buffers for rendering or a
//! graph (half-edge) for further manipulation.
//!
//! Iterator expressions begin with a unit primitive and manipulate its
//! components like vertices, lines, and polygons. Generation and decomposition
//! operations are exposed via traits.
//!
//! # Examples
//!
//! Generating position and index buffers for a scaled sphere:
//!
//! ```
//! use plexus::generate::{IndexedPolygons, SpatialVertices, Triangulate, Vertices};
//! use plexus::generate::sphere::UVSphere;
//!
//! let sphere = UVSphere::<f32>::with_unit_radius(16, 16);
//! let positions: Vec<_> = sphere
//! .spatial_vertices() // Generate the unique set of positional vertices.
//! .map(|(x, y, z)| (x * 10.0, y * 10.0, z * 10.0)) // Scale the positions by 10.
//! .collect();
//! let indeces: Vec<_> = sphere
//! .indexed_polygons() // Generate polygons indexing the unique set of vertices.
//! .triangulate() // Decompose the polygons into triangles.
//! .vertices() // Decompose the triangles into vertices (indeces).
//! .collect();
//! ```
// TODO: Primitives are parameterized over the type of scalars used for spatial
// data. This can be interpreted as the vector space and affects the
// internal data describing the primitive. See the `Unit` trait. Other
// data, like texture coordinates, are not parameterized at all. It may
// be more consistent to parameterize all of this data, either as
// individual type parameters or via a trait (like `Geometry`). Default
// type parameters are also provided.
pub mod cube;
mod decompose;
mod generate;
mod geometry;
mod index;
pub mod sphere;
mod topology;
pub use self::decompose::{IntoLines, IntoSubdivisions, IntoTetrahedrons, IntoTriangles,
IntoVertices, Lines, Subdivide, Tetrahedrons, Triangulate, Vertices};
pub use self::generate::{IndexedPolygons, SpatialPolygons, SpatialVertices, TexturedPolygons};
pub use self::index::{HashIndexer, IndexVertices};
pub use self::topology::{Line, MapVertices, Polygon, Polygonal, Quad, Rotate, Topological,
Triangle};
Only re-export direct conversion traits within crate.
//! Mesh generation from primitives like cubes and spheres.
//!
//! This module provides unit primitives that can be used to form complex
//! iterator expressions to generate meshes via a stream of topology and
//! geometry. This data can be collected into simple buffers for rendering or a
//! graph (half-edge) for further manipulation.
//!
//! Iterator expressions begin with a unit primitive and manipulate its
//! components like vertices, lines, and polygons. Generation and decomposition
//! operations are exposed via traits.
//!
//! # Examples
//!
//! Generating position and index buffers for a scaled sphere:
//!
//! ```
//! use plexus::generate::{IndexedPolygons, SpatialVertices, Triangulate, Vertices};
//! use plexus::generate::sphere::UVSphere;
//!
//! let sphere = UVSphere::<f32>::with_unit_radius(16, 16);
//! let positions: Vec<_> = sphere
//! .spatial_vertices() // Generate the unique set of positional vertices.
//! .map(|(x, y, z)| (x * 10.0, y * 10.0, z * 10.0)) // Scale the positions by 10.
//! .collect();
//! let indeces: Vec<_> = sphere
//! .indexed_polygons() // Generate polygons indexing the unique set of vertices.
//! .triangulate() // Decompose the polygons into triangles.
//! .vertices() // Decompose the triangles into vertices (indeces).
//! .collect();
//! ```
// TODO: Primitives are parameterized over the type of scalars used for spatial
// data. This can be interpreted as the vector space and affects the
// internal data describing the primitive. See the `Unit` trait. Other
// data, like texture coordinates, are not parameterized at all. It may
// be more consistent to parameterize all of this data, either as
// individual type parameters or via a trait (like `Geometry`). Default
// type parameters are also provided.
pub mod cube;
mod decompose;
mod generate;
mod geometry;
mod index;
pub mod sphere;
mod topology;
pub(crate) use self::decompose::{IntoTriangles, IntoVertices};
pub use self::decompose::{Lines, Subdivide, Tetrahedrons, Triangulate, Vertices};
pub use self::generate::{IndexedPolygons, SpatialPolygons, SpatialVertices, TexturedPolygons};
pub use self::index::{HashIndexer, IndexVertices};
pub use self::topology::{Line, MapVertices, Polygon, Polygonal, Quad, Rotate, Topological,
Triangle};
|
//! The `graphics` module performs the actual drawing of images, text, and other
//! objects with the `Drawable` trait. It also handles basic loading of images
//! and text.
//!
//! This module also manages graphics state, coordinate systems, etc.
//! The default coordinate system has the origin in the upper-left
//! corner of the screen.
use std::fmt;
use std::path;
use std::convert::From;
use std::collections::HashMap;
use std::io::Read;
use std::u16;
use sdl2;
use image;
use gfx;
use gfx::texture;
use gfx::traits::Device;
use gfx::traits::FactoryExt;
use gfx_device_gl;
use gfx_window_sdl;
use gfx::Factory;
use context::Context;
use GameError;
use GameResult;
mod text;
mod types;
pub mod spritebatch;
pub use self::text::*;
pub use self::types::*;
const GL_MAJOR_VERSION: u8 = 3;
const GL_MINOR_VERSION: u8 = 2;
const QUAD_VERTS: [Vertex; 4] = [
Vertex {
pos: [-0.5, -0.5],
uv: [0.0, 0.0],
},
Vertex {
pos: [0.5, -0.5],
uv: [1.0, 0.0],
},
Vertex {
pos: [0.5, 0.5],
uv: [1.0, 1.0],
},
Vertex {
pos: [-0.5, 0.5],
uv: [0.0, 1.0],
},
];
const QUAD_INDICES: [u16; 6] = [0, 1, 2, 0, 2, 3];
type ColorFormat = gfx::format::Srgba8;
// I don't know why this gives a dead code warning
// since this type is definitely used... oh well.
#[allow(dead_code)]
type DepthFormat = gfx::format::DepthStencil;
gfx_defines!{
/// Internal structure containing vertex data.
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
}
/// Internal structure containing global shader state.
constant Globals {
transform: [[f32; 4];4] = "u_Transform",
color: [f32; 4] = "u_Color",
}
/// Internal structure containing values that are different for each rect.
constant RectProperties {
src: [f32; 4] = "u_Src",
dest: [f32; 2] = "u_Dest",
scale: [f32;2] = "u_Scale",
offset: [f32;2] = "u_Offset",
shear: [f32;2] = "u_Shear",
rotation: f32 = "u_Rotation",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
tex: gfx::TextureSampler<[f32; 4]> = "t_Texture",
globals: gfx::ConstantBuffer<Globals> = "Globals",
rect_properties: gfx::ConstantBuffer<RectProperties> = "RectProperties",
out: gfx::BlendTarget<ColorFormat> =
("Target0", gfx::state::MASK_ALL, gfx::preset::blend::ALPHA),
}
}
impl Default for RectProperties {
fn default() -> Self {
RectProperties {
src: [0.0, 0.0, 1.0, 1.0],
dest: [0.0, 0.0],
scale: [1.0, 1.0],
offset: [0.0, 0.0],
shear: [0.0, 0.0],
rotation: 0.0,
}
}
}
impl From<DrawParam> for RectProperties {
fn from(p: DrawParam) -> Self {
RectProperties {
src: p.src.into(),
dest: p.dest.into(),
scale: [p.scale.x, p.scale.y],
offset: p.offset.into(),
shear: p.shear.into(),
rotation: p.rotation,
}
}
}
/// A structure for conveniently storing Sampler's, based off
/// their `SamplerInfo`.
///
/// Making this generic is tricky 'cause it has methods that depend
/// on the generic Factory trait, it seems, so for now we just kind
/// of hack it.
struct SamplerCache<R>
where
R: gfx::Resources,
{
samplers: HashMap<texture::SamplerInfo, gfx::handle::Sampler<R>>,
}
impl<R> SamplerCache<R>
where
R: gfx::Resources,
{
fn new() -> Self {
SamplerCache {
samplers: HashMap::new(),
}
}
fn get_or_insert<F>(
&mut self,
info: texture::SamplerInfo,
factory: &mut F,
) -> gfx::handle::Sampler<R>
where
F: gfx::Factory<R>,
{
let sampler = self.samplers
.entry(info)
.or_insert_with(|| factory.create_sampler(info));
sampler.clone()
}
}
/// A structure that contains graphics state.
/// For instance, background and foreground colors,
/// window info, DPI, rendering pipeline state, etc.
///
/// As an end-user you shouldn't ever have to touch this, but it goes
/// into part of the `Context` and so has to be public, at least
/// until the `pub(restricted)` feature is stable.
pub struct GraphicsContextGeneric<R, F, C, D>
where
R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>,
{
background_color: Color,
shader_globals: Globals,
white_image: Image,
line_width: f32,
point_size: f32,
screen_rect: Rect,
dpi: (f32, f32, f32),
window: sdl2::video::Window,
#[allow(dead_code)]
gl_context: sdl2::video::GLContext,
device: Box<D>,
factory: Box<F>,
encoder: gfx::Encoder<R, C>,
// color_view: gfx::handle::RenderTargetView<R, gfx::format::Srgba8>,
#[allow(dead_code)]
depth_view: gfx::handle::DepthStencilView<R, gfx::format::DepthStencil>,
pso: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
quad_slice: gfx::Slice<R>,
quad_vertex_buffer: gfx::handle::Buffer<R, Vertex>,
default_sampler_info: texture::SamplerInfo,
samplers: SamplerCache<R>,
}
impl<R, F, C, D> fmt::Debug for GraphicsContextGeneric<R, F, C, D>
where
R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "<GraphicsContext: {:p}>", self)
}
}
/// A concrete graphics context for GL rendering.
pub type GraphicsContext = GraphicsContextGeneric<
gfx_device_gl::Resources,
gfx_device_gl::Factory,
gfx_device_gl::CommandBuffer,
gfx_device_gl::Device,
>;
/// This can probably be removed but might be
/// handy to keep around a bit longer. Just in case something else
/// crazy happens.
#[allow(unused)]
fn test_opengl_versions(video: &sdl2::VideoSubsystem) {
let mut major_versions = [4u8, 3u8, 2u8, 1u8];
let minor_versions = [5u8, 4u8, 3u8, 2u8, 1u8, 0u8];
major_versions.reverse();
for major in &major_versions {
for minor in &minor_versions {
let gl = video.gl_attr();
gl.set_context_version(*major, *minor);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
print!("Requesting GL {}.{}... ", major, minor);
let window_builder = video.window("so full of hate", 640, 480);
let result = gfx_window_sdl::init::<ColorFormat, DepthFormat>(window_builder);
match result {
Ok(_) => println!(
"Ok, got GL {}.{}.",
gl.context_major_version(),
gl.context_minor_version()
),
Err(res) => println!("Request failed: {:?}", res),
}
}
}
}
impl GraphicsContext {
pub fn new(
video: sdl2::VideoSubsystem,
window_title: &str,
screen_width: u32,
screen_height: u32,
vsync: bool,
resize: bool,
) -> GameResult<GraphicsContext> {
// WINDOW SETUP
let gl = video.gl_attr();
gl.set_context_version(GL_MAJOR_VERSION, GL_MINOR_VERSION);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
let mut window_builder = video.window(window_title, screen_width, screen_height);
if resize {
window_builder.resizable();
}
let (window, gl_context, device, mut factory, color_view, depth_view) =
gfx_window_sdl::init(window_builder)?;
// println!("Vsync enabled: {}", vsync);
let vsync_int = if vsync { 1 } else { 0 };
video.gl_set_swap_interval(vsync_int);
let display_index = window.display_index()?;
let dpi = window.subsystem().display_dpi(display_index)?;
// GFX SETUP
let encoder: gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> =
factory.create_command_buffer().into();
let pso = factory.create_pipeline_simple(
include_bytes!("shader/basic_150.glslv"),
include_bytes!("shader/basic_150.glslf"),
pipe::new(),
)?;
let (quad_vertex_buffer, quad_slice) =
factory.create_vertex_buffer_with_slice(&QUAD_VERTS, &QUAD_INDICES[..]);
let rect_props = factory.create_constant_buffer(1);
let globals_buffer = factory.create_constant_buffer(1);
let mut samplers: SamplerCache<gfx_device_gl::Resources> = SamplerCache::new();
let sampler_info =
texture::SamplerInfo::new(texture::FilterMethod::Bilinear, texture::WrapMode::Clamp);
let sampler = samplers.get_or_insert(sampler_info, &mut factory);
let white_image =
Image::make_raw(&mut factory, &sampler_info, 1, 1, &[255, 255, 255, 255])?;
let texture = white_image.texture.clone();
let data = pipe::Data {
vbuf: quad_vertex_buffer.clone(),
tex: (texture, sampler),
rect_properties: rect_props,
globals: globals_buffer,
out: color_view,
};
// Set initial uniform values
let left = 0.0;
let right = screen_width as f32;
let top = 0.0;
let bottom = screen_height as f32;
let globals = Globals {
transform: ortho(left, right, top, bottom, 1.0, -1.0),
color: types::WHITE.into(),
};
let mut gfx = GraphicsContext {
background_color: Color::new(0.1, 0.2, 0.3, 1.0),
shader_globals: globals,
line_width: 1.0,
point_size: 1.0,
white_image: white_image,
screen_rect: Rect::new(left, bottom, (right - left), (top - bottom)),
dpi: dpi,
window: window,
gl_context: gl_context,
device: Box::new(device),
factory: Box::new(factory),
encoder: encoder,
depth_view: depth_view,
pso: pso,
data: data,
quad_slice: quad_slice,
quad_vertex_buffer: quad_vertex_buffer,
default_sampler_info: sampler_info,
samplers: samplers,
};
gfx.update_globals()?;
Ok(gfx)
}
fn update_globals(&mut self) -> GameResult<()> {
self.encoder
.update_buffer(&self.data.globals, &[self.shader_globals], 0)?;
Ok(())
}
fn update_rect_properties(&mut self, draw_params: DrawParam) -> GameResult<()> {
let properties = draw_params.into();
self.encoder
.update_buffer(&self.data.rect_properties, &[properties], 0)?;
Ok(())
}
/// Returns a reference to the SDL window.
/// Ideally you should not need to use this because ggez
/// would provide all the functions you need without having
/// to dip into SDL itself. But life isn't always ideal.
pub fn get_window(&self) -> &sdl2::video::Window {
&self.window
}
/// Returns a mutable reference to the SDL window.
pub fn get_window_mut(&mut self) -> &mut sdl2::video::Window {
&mut self.window
}
/// Returns the size of the window in pixels as (height, width).
pub fn get_size(&self) -> (u32, u32) {
self.window.size()
}
/// Returns the size of the window's underlaying drawable in pixels as (height, width).
/// This may return a different value than `get_size()` when run on a platform with high-DPI support
pub fn get_drawable_size(&self) -> (u32, u32) {
self.window.drawable_size()
}
/// EXPERIMENTAL function to get the gfx-rs `Factory` object.
pub fn get_factory(&mut self) -> &mut gfx_device_gl::Factory {
&mut self.factory
}
/// EXPERIMENTAL function to get the gfx-rs `Device` object.
pub fn get_device(&mut self) -> &mut gfx_device_gl::Device {
self.device.as_mut()
}
/// EXPERIMENTAL function to get the gfx-rs `Encoder` object.
pub fn get_encoder(
&mut self,
) -> &mut gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> {
&mut self.encoder
}
/// EXPERIMENTAL function to get the gfx-rs depth view
pub fn get_depth_view(
&self,
) -> gfx::handle::DepthStencilView<gfx_device_gl::Resources, gfx::format::DepthStencil> {
self.depth_view.clone()
}
/// EXPERIMENTAL function to get the gfx-rs color view
pub fn get_color_view(
&self,
) -> gfx::handle::RenderTargetView<
gfx_device_gl::Resources,
(gfx::format::R8_G8_B8_A8, gfx::format::Srgb),
> {
self.data.out.clone()
}
}
/// Creates an orthographic projection matrix.
///
/// Rather than create a dependency on cgmath or nalgebra for this one function,
/// we're just going to define it ourselves.
fn ortho(left: f32, right: f32, top: f32, bottom: f32, far: f32, near: f32) -> [[f32; 4]; 4] {
let c0r0 = 2.0 / (right - left);
let c0r1 = 0.0;
let c0r2 = 0.0;
let c0r3 = 0.0;
let c1r0 = 0.0;
let c1r1 = 2.0 / (top - bottom);
let c1r2 = 0.0;
let c1r3 = 0.0;
let c2r0 = 0.0;
let c2r1 = 0.0;
let c2r2 = -2.0 / (far - near);
let c2r3 = 0.0;
let c3r0 = -(right + left) / (right - left);
let c3r1 = -(top + bottom) / (top - bottom);
let c3r2 = -(far + near) / (far - near);
let c3r3 = 1.0;
[
[c0r0, c1r0, c2r0, c3r0],
[c0r1, c1r1, c2r1, c3r1],
[c0r2, c1r2, c2r2, c3r2],
[c0r3, c1r3, c2r3, c3r3],
]
}
// **********************************************************************
// DRAWING
// **********************************************************************
/// Clear the screen to the background color.
pub fn clear(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
gfx.encoder
.clear(&gfx.data.out, gfx.background_color.into());
}
/// Draws the given `Drawable` object to the screen by calling its
/// `draw()` method.
pub fn draw(ctx: &mut Context, drawable: &Drawable, dest: Point, rotation: f32) -> GameResult<()> {
drawable.draw(ctx, dest, rotation)
}
/// Draws the given `Drawable` object to the screen by calling its `draw_ex()` method.
pub fn draw_ex(ctx: &mut Context, drawable: &Drawable, params: DrawParam) -> GameResult<()> {
drawable.draw_ex(ctx, params)
}
/// Tells the graphics system to actually put everything on the screen.
/// Call this at the end of your `EventHandler`'s `draw()` method.
pub fn present(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
// We might want to give the user more control over when the
// encoder gets flushed eventually, if we want them to be able
// to do their own gfx drawing. HOWEVER, the whole pipeline type
// thing is a bigger hurdle, so this is fine for now.
gfx.encoder.flush(&mut *gfx.device);
gfx.window.gl_swap_window();
gfx.device.cleanup();
}
/*
// Draw an arc.
// Punting on this until later.
pub fn arc(_ctx: &mut Context,
_mode: DrawMode,
_point: Point,
_radius: f32,
_angle1: f32,
_angle2: f32,
_segments: u32)
-> GameResult<()> {
unimplemented!();
}
*/
/// Draw a circle.
pub fn circle(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
tolerance: f32,
) -> GameResult<()> {
let m = Mesh::new_circle(ctx, mode, point, radius, tolerance)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draw an ellipse.
pub fn ellipse(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
tolerance: f32,
) -> GameResult<()> {
let m = Mesh::new_ellipse(ctx, mode, point, radius1, radius2, tolerance)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draws a line of one or more connected segments.
pub fn line(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_line(ctx, points, w)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draws points.
pub fn points(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let size = ctx.gfx_context.point_size;
for p in points {
let r = Rect::new(p.x, p.y, size, size);
rectangle(ctx, DrawMode::Fill, r)?;
}
Ok(())
}
/// Draws a closed polygon
pub fn polygon(ctx: &mut Context, mode: DrawMode, vertices: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_polygon(ctx, mode, vertices, w)?;
m.draw(ctx, Point::default(), 0.0)
}
// Renders text with the default font.
// Not terribly efficient as it re-renders the text with each call,
// but good enough for debugging.
// Doesn't actually work, double-borrow on ctx. Bah.
// pub fn print(ctx: &mut Context, dest: Point, text: &str) -> GameResult<()> {
// let rendered_text = {
// let font = &ctx.default_font;
// text::Text::new(ctx, text, font)?
// };
// draw(ctx, &rendered_text, dest, 0.0)
// }
/// Draws a rectangle.
pub fn rectangle(ctx: &mut Context, mode: DrawMode, rect: Rect) -> GameResult<()> {
let x = rect.x;
let y = rect.y;
let w = rect.w;
let h = rect.h;
let x1 = x - (w / 2.0);
let x2 = x + (w / 2.0);
let y1 = y - (h / 2.0);
let y2 = y + (h / 2.0);
let pts = [
[x1, y1].into(),
[x2, y1].into(),
[x2, y2].into(),
[x1, y2].into(),
];
polygon(ctx, mode, &pts)
}
// **********************************************************************
// GRAPHICS STATE
// **********************************************************************
/// Returns the current background color.
pub fn get_background_color(ctx: &Context) -> Color {
ctx.gfx_context.background_color
}
/// Returns the current foreground color.
pub fn get_color(ctx: &Context) -> Color {
ctx.gfx_context.shader_globals.color.into()
}
/// Get the default filter mode for new images.
pub fn get_default_filter(ctx: &Context) -> FilterMode {
let gfx = &ctx.gfx_context;
gfx.default_sampler_info.filter.into()
}
/// Get the current width for drawing lines and stroked polygons.
pub fn get_line_width(ctx: &Context) -> f32 {
ctx.gfx_context.line_width
}
/// Get the current size for drawing points.
pub fn get_point_size(ctx: &Context) -> f32 {
ctx.gfx_context.point_size
}
/// Returns a string that tells a little about the obtained rendering mode.
/// It is supposed to be human-readable and will change; do not try to parse
/// information out of it!
pub fn get_renderer_info(ctx: &Context) -> GameResult<String> {
let video = ctx.sdl_context.video()?;
let gl = video.gl_attr();
Ok(format!(
"Requested GL {}.{} Core profile, actually got GL {}.{} {:?} profile.",
GL_MAJOR_VERSION,
GL_MINOR_VERSION,
gl.context_major_version(),
gl.context_minor_version(),
gl.context_profile()
))
}
/// Returns a rectangle defining the coordinate system of the screen.
/// It will be `Rect { x: left, y: bottom, w: width, h: height }`
///
/// If the Y axis increases downwards, the `height` of the Rect
/// will be negative.
pub fn get_screen_coordinates(ctx: &Context) -> Rect {
ctx.gfx_context.screen_rect
}
/// Sets the background color. Default: blue.
pub fn set_background_color(ctx: &mut Context, color: Color) {
ctx.gfx_context.background_color = color;
}
/// Sets the foreground color, which will be used for drawing
/// rectangles, lines, etc. Default: white.
pub fn set_color(ctx: &mut Context, color: Color) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.shader_globals.color = color.into();
gfx.update_globals()
}
/// Sets the default filter mode used to scale images.
///
/// This does not apply retroactively to already created images.
pub fn set_default_filter(ctx: &mut Context, mode: FilterMode) {
let gfx = &mut ctx.gfx_context;
let new_mode = mode.into();
let sampler_info = texture::SamplerInfo::new(new_mode, texture::WrapMode::Clamp);
// We create the sampler now so we don't end up creating it at some
// random-ass time while we're trying to draw stuff.
let _sampler = gfx.samplers.get_or_insert(sampler_info, &mut *gfx.factory);
gfx.default_sampler_info = sampler_info;
}
/// Set the current width for drawing lines and stroked polygons.
pub fn set_line_width(ctx: &mut Context, width: f32) {
ctx.gfx_context.line_width = width;
}
/// Set the current size for drawing points.
pub fn set_point_size(ctx: &mut Context, size: f32) {
ctx.gfx_context.point_size = size;
}
/// Sets the bounds of the screen viewport.
///
/// The default coordinate system has (0,0) at the top-left corner
/// with X increasing to the right and Y increasing down, with the
/// viewport scaled such that one coordinate unit is one pixel on the
/// screen. This function lets you change this coordinate system to
/// be whatever you prefer.
pub fn set_screen_coordinates(
context: &mut Context,
rect: Rect,
) -> GameResult<()> {
let gfx = &mut context.gfx_context;
gfx.screen_rect = rect;
gfx.shader_globals.transform = ortho(rect.x, rect.w + rect.x, rect.h + rect.y, rect.y, 1.0, -1.0);
gfx.update_globals()
}
/// Sets the window mode, such as the size and other properties.
///
/// Setting the window mode may have side effects, such as clearing
/// the screen or setting the screen coordinates viewport to some undefined value.
/// It is recommended to call `set_screen_coordinates()` after changing the window
/// size to make sure everything is what you want it to be.
pub fn set_mode(
context: &mut Context,
width: u32,
height: u32,
mode: WindowMode,
) -> GameResult<()> {
{
let window = &mut context.gfx_context.get_window_mut();
window.set_size(width, height)?;
// SDL sets "bordered" but Love2D does "not bordered";
// we use the Love2D convention.
window.set_bordered(!mode.borderless);
window.set_fullscreen(mode.fullscreen_type)?;
let (min_w, min_h) = mode.min_dimensions;
window.set_minimum_size(min_w, min_h)?;
let (max_w, max_h) = mode.max_dimensions;
window.set_maximum_size(max_w, max_h)?;
}
{
let video = context.sdl_context.video()?;
let vsync_int = if mode.vsync { 1 } else { 0 };
video.gl_set_swap_interval(vsync_int);
}
Ok(())
}
/// Returns a `Vec` of `(width, height)` tuples describing what
/// fullscreen resolutions are available for the given display.
pub fn get_fullscreen_modes(context: &Context, display_idx: i32) -> GameResult<Vec<(u32, u32)>> {
let video = context.sdl_context.video()?;
let display_count = video.num_video_displays()?;
assert!(display_idx < display_count);
let num_modes = video.num_display_modes(display_idx)?;
(0..num_modes)
.map(|i| video.display_mode(display_idx, i))
.map(|ires| ires.map_err(GameError::VideoError))
.map(|gres| {
gres.map(|dispmode| (dispmode.w as u32, dispmode.h as u32))
})
.collect()
}
/// Returns the number of connected displays.
pub fn get_display_count(context: &Context) -> GameResult<i32> {
let video = context.sdl_context.video()?;
video.num_video_displays().map_err(GameError::VideoError)
}
// **********************************************************************
// TYPES
// **********************************************************************
/// A struct containing all the necessary info for drawing a Drawable.
///
/// * `src` - a portion of the drawable to clip, as a fraction of the whole image.
/// Defaults to the whole image (1.0) if omitted.
/// * `dest` - the position to draw the graphic expressed as a `Point`.
/// * `rotation` - orientation of the graphic in radians.
/// * `scale` - x/y scale factors expressed as a `Point`.
/// * `offset` - specifies an offset from the center for transform operations like scale/rotation.
/// * `shear` - x/y shear factors expressed as a `Point`.
///
/// This struct implements the `Default` trait, so you can just do:
///
/// `graphics::draw_ex(ctx, drawable, DrawParam{ dest: my_dest, .. Default::default()} )`
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct DrawParam {
pub src: Rect,
pub dest: Point,
pub rotation: f32,
pub scale: Point,
pub offset: Point,
pub shear: Point,
}
impl Default for DrawParam {
fn default() -> Self {
DrawParam {
src: Rect::one(),
dest: Point::zero(),
rotation: 0.0,
scale: Point::new(1.0, 1.0),
offset: Point::new(0.0, 0.0),
shear: Point::new(0.0, 0.0),
}
}
}
/// All types that can be drawn on the screen implement the `Drawable` trait.
pub trait Drawable {
/// Actually draws the object to the screen.
///
/// This is the most general version of the operation, which is all that
/// is required for implementing this trait.
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()>;
/// Draws the drawable onto the rendering target.
///
/// It just is a shortcut that calls `draw_ex()` with some sane defaults.
///
/// * `ctx` - The `Context` this graphic will be rendered to.
/// * `dest` - the position to draw the graphic expressed as a `Point`.
/// * `rotation` - orientation of the graphic in radians.
///
fn draw(&self, ctx: &mut Context, dest: Point, rotation: f32) -> GameResult<()> {
self.draw_ex(
ctx,
DrawParam {
dest: dest,
rotation: rotation,
..Default::default()
},
)
}
}
/// Generic in-GPU-memory image data available to be drawn on the screen.
#[derive(Clone)]
pub struct ImageGeneric<R>
where
R: gfx::Resources,
{
texture: gfx::handle::ShaderResourceView<R, [f32; 4]>,
sampler_info: gfx::texture::SamplerInfo,
width: u32,
height: u32,
}
/// In-GPU-memory image data available to be drawn on the screen,
/// using the OpenGL backend.
pub type Image = ImageGeneric<gfx_device_gl::Resources>;
/// Copies an 2D (RGBA) buffer into one that is the next
/// power of two size up in both dimensions. All data is
/// retained and kept closest to [0,0]; anything extra is
/// filled with 0
fn scale_rgba_up_to_power_of_2(width: u16, height: u16, rgba: &[u8]) -> (u16, u16, Vec<u8>) {
let width = width as usize;
let height = height as usize;
let w2 = width.next_power_of_two();
let h2 = height.next_power_of_two();
// println!("Scaling from {}x{} to {}x{}", width, height, w2, h2);
let num_vals = w2 * h2 * 4;
let mut v: Vec<u8> = Vec::with_capacity(num_vals);
// This is a little wasteful because we will be replacing
// many if not most of these 0's with the actual image data.
// But it's much simpler to resize the thing once than to blit
// each row, resize it out to fill the rest of the row with zeroes,
// etc.
v.resize(num_vals, 0);
// Blit each row of the old image into the new array.
for i in 0..h2 {
if i < height {
let src_start = i * width * 4;
let src_end = src_start + width * 4;
let dest_start = i * w2 * 4;
let dest_end = dest_start + width * 4;
let slice = &mut v[dest_start..dest_end];
slice.copy_from_slice(&rgba[src_start..src_end]);
}
}
(w2 as u16, h2 as u16, v)
}
impl Image {
/// Load a new image from the file at the given path.
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Image> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (width, height) = img.dimensions();
Image::from_rgba8(context, width as u16, height as u16, &img)
}
/// Creates a new `Image` from the given buffer of `u8` RGBA values.
pub fn from_rgba8(
context: &mut Context,
width: u16,
height: u16,
rgba: &[u8],
) -> GameResult<Image> {
Image::make_raw(
&mut context.gfx_context.factory,
&context.gfx_context.default_sampler_info,
width,
height,
rgba,
)
}
/// A helper function that just takes a factory directly so we can make an image
/// without needing the full context object, so we can create an Image while still
/// creating the GraphicsContext.
fn make_raw(
factory: &mut gfx_device_gl::Factory,
sampler_info: &texture::SamplerInfo,
width: u16,
height: u16,
rgba: &[u8],
) -> GameResult<Image> {
// Check if the texture is not power of 2, and if not, pad it out.
let view = if false {
// let view = if !(width.is_power_of_two() && height.is_power_of_two()) {
let (width, height, rgba) = scale_rgba_up_to_power_of_2(width, height, rgba);
let rgba = &rgba;
assert_eq!((width as usize) * (height as usize) * 4, rgba.len());
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
// The slice containing rgba is NOT rows x columns, it is a slice of
// MIPMAP LEVELS. Augh!
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
} else {
if width == 0 || height == 0 {
let msg = format!(
"Tried to create a texture of size {}x{}, each dimension must \
be >0",
width,
height
);
return Err(GameError::ResourceLoadError(msg));
}
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
};
Ok(Image {
texture: view,
sampler_info: *sampler_info,
width: width as u32,
height: height as u32,
})
}
/// A little helper function that creates a new Image that is just
/// a solid square of the given size and color. Mainly useful for
/// debugging.
pub fn solid(context: &mut Context, size: u16, color: Color) -> GameResult<Image> {
let pixel_array: [u8; 4] = color.into();
let size_squared = size as usize * size as usize;
let mut buffer = Vec::with_capacity(size_squared);
for _i in 0..size_squared {
buffer.extend(&pixel_array[..]);
}
Image::from_rgba8(context, size, size, &buffer)
}
/// Return the width of the image.
pub fn width(&self) -> u32 {
self.width
}
/// Return the height of the image.
pub fn height(&self) -> u32 {
self.height
}
/// Get the filter mode for the image.
pub fn get_filter(&self) -> FilterMode {
self.sampler_info.filter.into()
}
/// Set the filter mode for the image.
pub fn set_filter(&mut self, mode: FilterMode) {
self.sampler_info.filter = mode.into();
}
/// Returns the dimensions of the image.
pub fn get_dimensions(&self) -> Rect {
Rect::new(0.0, 0.0, self.width() as f32, self.height() as f32)
}
/// Gets the `Image`'s `WrapMode` along the X and Y axes.
pub fn get_wrap(&self) -> (WrapMode, WrapMode) {
(self.sampler_info.wrap_mode.0, self.sampler_info.wrap_mode.1)
}
/// Sets the `Image`'s `WrapMode` along the X and Y axes.
pub fn set_wrap(&mut self, wrap_x: WrapMode, wrap_y: WrapMode) {
self.sampler_info.wrap_mode.0 = wrap_x;
self.sampler_info.wrap_mode.1 = wrap_y;
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"<Image: {}x{}, {:p}, texture address {:p}, sampler: {:?}>",
self.width(),
self.height(),
self,
&self.texture,
&self.sampler_info
)
}
}
impl Drawable for Image {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
let src_width = param.src.w;
let src_height = param.src.h;
// We have to mess with the scale to make everything
// be its-unit-size-in-pixels.
// We also invert the Y scale if our screen coordinates
// are "upside down", because by default we present the
// illusion that the screen is addressed in pixels.
// BUGGO: Which I rather regret now.
let invert_y = if gfx.screen_rect.h < 0.0 { 1.0 } else { -1.0 };
let real_scale = Point {
x: src_width * param.scale.x * self.width as f32,
y: src_height * param.scale.y * self.height as f32 * invert_y,
};
let mut new_param = param;
new_param.scale = real_scale;
// Not entirely sure why the inversion is necessary, but oh well.
new_param.offset.x *= -1.0 * param.scale.x;
new_param.offset.y *= param.scale.y;
gfx.update_rect_properties(new_param)?;
let sampler = gfx.samplers
.get_or_insert(self.sampler_info, gfx.factory.as_mut());
gfx.data.vbuf = gfx.quad_vertex_buffer.clone();
gfx.data.tex = (self.texture.clone(), sampler);
gfx.encoder.draw(&gfx.quad_slice, &gfx.pso, &gfx.data);
Ok(())
}
}
/// 2D polygon mesh
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh {
buffer: gfx::handle::Buffer<gfx_device_gl::Resources, Vertex>,
slice: gfx::Slice<gfx_device_gl::Resources>,
}
use lyon::tessellation as t;
struct VertexBuilder;
impl t::VertexConstructor<t::FillVertex, Vertex> for VertexBuilder {
fn new_vertex(&mut self, vertex: t::FillVertex) -> Vertex {
Vertex {
pos: [vertex.position.x, vertex.position.y],
uv: [0.0, 0.0],
}
}
}
impl t::VertexConstructor<t::StrokeVertex, Vertex> for VertexBuilder {
fn new_vertex(&mut self, vertex: t::StrokeVertex) -> Vertex {
Vertex {
pos: [vertex.position.x, vertex.position.y],
uv: [0.0, 0.0],
}
}
}
impl Mesh {
fn from_vbuf(
ctx: &mut Context,
buffer: &t::geometry_builder::VertexBuffers<Vertex>,
) -> GameResult<Mesh> {
let (vbuf, slice) = ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&buffer.vertices[..], &buffer.indices[..]);
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
/// Create a new mesh for a line of one or more connected segments.
/// WIP, sorry
pub fn new_line(ctx: &mut Context, points: &[Point], width: f32) -> GameResult<Mesh> {
Mesh::new_polyline(ctx, DrawMode::Line, points, width)
}
/// Create a new mesh for a circle.
/// Stroked circles are still WIP, sorry.
pub fn new_circle(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
tolerance: f32,
) -> GameResult<Mesh> {
{
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
t::basic_shapes::fill_circle(
t::math::point(point.x, point.y),
radius,
tolerance,
builder,
);
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(ctx.gfx_context.line_width)
.with_tolerance(tolerance);
t::basic_shapes::stroke_circle(
t::math::point(point.x, point.y),
radius,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
}
/// Create a new mesh for an ellipse.
/// Stroked ellipses are still WIP, sorry.
pub fn new_ellipse(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
tolerance: f32,
) -> GameResult<Mesh> {
use euclid::Length;
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
t::basic_shapes::fill_ellipse(
t::math::point(point.x, point.y),
t::math::vec2(radius1, radius2),
Length::new(0.0),
tolerance,
builder,
);
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(ctx.gfx_context.line_width)
.with_tolerance(tolerance);
t::basic_shapes::stroke_ellipse(
t::math::point(point.x, point.y),
t::math::vec2(radius1, radius2),
Length::new(0.0),
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new mesh for series of connected lines
pub fn new_polyline(
ctx: &mut Context,
mode: DrawMode,
points: &[Point],
width: f32)
-> GameResult<Mesh> {
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
let points = points
.into_iter()
.map(|ggezpoint| t::math::point(ggezpoint.x, ggezpoint.y));
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let tessellator = &mut t::FillTessellator::new();
let options = t::FillOptions::default();
t::basic_shapes::fill_polyline(
points,
tessellator,
&options,
builder,
).unwrap();
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(width);
t::basic_shapes::stroke_polyline(
points,
false,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new mesh for closed polygon
pub fn new_polygon(
ctx: &mut Context,
mode: DrawMode,
points: &[Point],
width: f32)
-> GameResult<Mesh> {
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
let points = points
.into_iter()
.map(|ggezpoint| t::math::point(ggezpoint.x, ggezpoint.y));
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let tessellator = &mut t::FillTessellator::new();
let options = t::FillOptions::default();
t::basic_shapes::fill_polyline(
points,
tessellator,
&options,
builder,
).unwrap();
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(width);
t::basic_shapes::stroke_polyline(
points,
true,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new `Mesh` from a raw list of triangles.
///
/// Currently does not support UV's or indices.
pub fn from_triangles(ctx: &mut Context, triangles: &[Point]) -> GameResult<Mesh> {
// This is kind of non-ideal but works for now.
let points: Vec<Vertex> = triangles
.into_iter()
.map(|p| {
Vertex {
pos: (*p).into(),
uv: (*p).into(),
}
})
.collect();
let (vbuf, slice) = ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&points[..], ());
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
}
impl Drawable for Mesh {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.update_rect_properties(param)?;
gfx.data.vbuf = self.buffer.clone();
gfx.data.tex.0 = gfx.white_image.texture.clone();
gfx.encoder.draw(&self.slice, &gfx.pso, &gfx.data);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_scaling_up() {
let mut from: Vec<u8> = Vec::new();
const WIDTH: u16 = 5;
const HEIGHT: u16 = 11;
for i in 0..HEIGHT {
let v = vec![i as u8; WIDTH as usize * 4];
from.extend(v.iter());
}
assert_eq!(from.len(), WIDTH as usize * HEIGHT as usize * 4);
let (width, height, res) = scale_rgba_up_to_power_of_2(WIDTH, HEIGHT, &from);
assert_eq!(width, WIDTH.next_power_of_two());
assert_eq!(height, HEIGHT.next_power_of_two());
for i in 0..HEIGHT.next_power_of_two() {
for j in 0..WIDTH.next_power_of_two() {
let offset_within_row = (j * 4) as usize;
let src_row_offset = (i * WIDTH * 4) as usize;
let dst_row_offset = (i * width * 4) as usize;
println!("{} {}", i, j);
if i < HEIGHT && j < WIDTH {
assert_eq!(
res[dst_row_offset + offset_within_row],
from[src_row_offset + offset_within_row]
);
} else {
assert_eq!(res[dst_row_offset + offset_within_row], 0);
}
}
}
}
}
Resolved issue #93 and #115
//! The `graphics` module performs the actual drawing of images, text, and other
//! objects with the `Drawable` trait. It also handles basic loading of images
//! and text.
//!
//! This module also manages graphics state, coordinate systems, etc.
//! The default coordinate system has the origin in the upper-left
//! corner of the screen.
use std::fmt;
use std::path;
use std::convert::From;
use std::collections::HashMap;
use std::io::Read;
use std::u16;
use sdl2;
use image;
use gfx;
use gfx::texture;
use gfx::traits::Device;
use gfx::traits::FactoryExt;
use gfx_device_gl;
use gfx_window_sdl;
use gfx::Factory;
use context::Context;
use GameError;
use GameResult;
mod text;
mod types;
pub mod spritebatch;
pub use self::text::*;
pub use self::types::*;
const GL_MAJOR_VERSION: u8 = 3;
const GL_MINOR_VERSION: u8 = 2;
const QUAD_VERTS: [Vertex; 4] = [
Vertex {
pos: [-0.5, -0.5],
uv: [0.0, 0.0],
},
Vertex {
pos: [0.5, -0.5],
uv: [1.0, 0.0],
},
Vertex {
pos: [0.5, 0.5],
uv: [1.0, 1.0],
},
Vertex {
pos: [-0.5, 0.5],
uv: [0.0, 1.0],
},
];
const QUAD_INDICES: [u16; 6] = [0, 1, 2, 0, 2, 3];
type ColorFormat = gfx::format::Srgba8;
// I don't know why this gives a dead code warning
// since this type is definitely used... oh well.
#[allow(dead_code)]
type DepthFormat = gfx::format::DepthStencil;
gfx_defines!{
/// Internal structure containing vertex data.
vertex Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
}
/// Internal structure containing global shader state.
constant Globals {
transform: [[f32; 4];4] = "u_Transform",
color: [f32; 4] = "u_Color",
}
/// Internal structure containing values that are different for each rect.
constant RectProperties {
src: [f32; 4] = "u_Src",
dest: [f32; 2] = "u_Dest",
scale: [f32;2] = "u_Scale",
offset: [f32;2] = "u_Offset",
shear: [f32;2] = "u_Shear",
rotation: f32 = "u_Rotation",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
tex: gfx::TextureSampler<[f32; 4]> = "t_Texture",
globals: gfx::ConstantBuffer<Globals> = "Globals",
rect_properties: gfx::ConstantBuffer<RectProperties> = "RectProperties",
out: gfx::BlendTarget<ColorFormat> =
("Target0", gfx::state::MASK_ALL, gfx::preset::blend::ALPHA),
}
}
impl Default for RectProperties {
fn default() -> Self {
RectProperties {
src: [0.0, 0.0, 1.0, 1.0],
dest: [0.0, 0.0],
scale: [1.0, 1.0],
offset: [0.0, 0.0],
shear: [0.0, 0.0],
rotation: 0.0,
}
}
}
impl From<DrawParam> for RectProperties {
fn from(p: DrawParam) -> Self {
RectProperties {
src: p.src.into(),
dest: p.dest.into(),
scale: [p.scale.x, p.scale.y],
offset: p.offset.into(),
shear: p.shear.into(),
rotation: p.rotation,
}
}
}
/// A structure for conveniently storing Sampler's, based off
/// their `SamplerInfo`.
///
/// Making this generic is tricky 'cause it has methods that depend
/// on the generic Factory trait, it seems, so for now we just kind
/// of hack it.
struct SamplerCache<R>
where
R: gfx::Resources,
{
samplers: HashMap<texture::SamplerInfo, gfx::handle::Sampler<R>>,
}
impl<R> SamplerCache<R>
where
R: gfx::Resources,
{
fn new() -> Self {
SamplerCache {
samplers: HashMap::new(),
}
}
fn get_or_insert<F>(
&mut self,
info: texture::SamplerInfo,
factory: &mut F,
) -> gfx::handle::Sampler<R>
where
F: gfx::Factory<R>,
{
let sampler = self.samplers
.entry(info)
.or_insert_with(|| factory.create_sampler(info));
sampler.clone()
}
}
/// A structure that contains graphics state.
/// For instance, background and foreground colors,
/// window info, DPI, rendering pipeline state, etc.
///
/// As an end-user you shouldn't ever have to touch this, but it goes
/// into part of the `Context` and so has to be public, at least
/// until the `pub(restricted)` feature is stable.
pub struct GraphicsContextGeneric<R, F, C, D>
where
R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>,
{
background_color: Color,
shader_globals: Globals,
white_image: Image,
line_width: f32,
point_size: f32,
screen_rect: Rect,
dpi: (f32, f32, f32),
window: sdl2::video::Window,
#[allow(dead_code)]
gl_context: sdl2::video::GLContext,
device: Box<D>,
factory: Box<F>,
encoder: gfx::Encoder<R, C>,
// color_view: gfx::handle::RenderTargetView<R, gfx::format::Srgba8>,
#[allow(dead_code)]
depth_view: gfx::handle::DepthStencilView<R, gfx::format::DepthStencil>,
pso: gfx::PipelineState<R, pipe::Meta>,
data: pipe::Data<R>,
quad_slice: gfx::Slice<R>,
quad_vertex_buffer: gfx::handle::Buffer<R, Vertex>,
default_sampler_info: texture::SamplerInfo,
samplers: SamplerCache<R>,
}
impl<R, F, C, D> fmt::Debug for GraphicsContextGeneric<R, F, C, D>
where
R: gfx::Resources,
F: gfx::Factory<R>,
C: gfx::CommandBuffer<R>,
D: gfx::Device<Resources = R, CommandBuffer = C>,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "<GraphicsContext: {:p}>", self)
}
}
/// A concrete graphics context for GL rendering.
pub type GraphicsContext = GraphicsContextGeneric<
gfx_device_gl::Resources,
gfx_device_gl::Factory,
gfx_device_gl::CommandBuffer,
gfx_device_gl::Device,
>;
/// This can probably be removed but might be
/// handy to keep around a bit longer. Just in case something else
/// crazy happens.
#[allow(unused)]
fn test_opengl_versions(video: &sdl2::VideoSubsystem) {
let mut major_versions = [4u8, 3u8, 2u8, 1u8];
let minor_versions = [5u8, 4u8, 3u8, 2u8, 1u8, 0u8];
major_versions.reverse();
for major in &major_versions {
for minor in &minor_versions {
let gl = video.gl_attr();
gl.set_context_version(*major, *minor);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
print!("Requesting GL {}.{}... ", major, minor);
let window_builder = video.window("so full of hate", 640, 480);
let result = gfx_window_sdl::init::<ColorFormat, DepthFormat>(window_builder);
match result {
Ok(_) => println!(
"Ok, got GL {}.{}.",
gl.context_major_version(),
gl.context_minor_version()
),
Err(res) => println!("Request failed: {:?}", res),
}
}
}
}
impl GraphicsContext {
pub fn new(
video: sdl2::VideoSubsystem,
window_title: &str,
screen_width: u32,
screen_height: u32,
vsync: bool,
resize: bool,
) -> GameResult<GraphicsContext> {
// WINDOW SETUP
let gl = video.gl_attr();
gl.set_context_version(GL_MAJOR_VERSION, GL_MINOR_VERSION);
gl.set_context_profile(sdl2::video::GLProfile::Core);
gl.set_red_size(5);
gl.set_green_size(5);
gl.set_blue_size(5);
gl.set_alpha_size(8);
let mut window_builder = video.window(window_title, screen_width, screen_height);
if resize {
window_builder.resizable();
}
let (window, gl_context, device, mut factory, color_view, depth_view) =
gfx_window_sdl::init(window_builder)?;
// println!("Vsync enabled: {}", vsync);
let vsync_int = if vsync { 1 } else { 0 };
video.gl_set_swap_interval(vsync_int);
let display_index = window.display_index()?;
let dpi = window.subsystem().display_dpi(display_index)?;
// GFX SETUP
let encoder: gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> =
factory.create_command_buffer().into();
let pso = factory.create_pipeline_simple(
include_bytes!("shader/basic_150.glslv"),
include_bytes!("shader/basic_150.glslf"),
pipe::new(),
)?;
let (quad_vertex_buffer, quad_slice) =
factory.create_vertex_buffer_with_slice(&QUAD_VERTS, &QUAD_INDICES[..]);
let rect_props = factory.create_constant_buffer(1);
let globals_buffer = factory.create_constant_buffer(1);
let mut samplers: SamplerCache<gfx_device_gl::Resources> = SamplerCache::new();
let sampler_info =
texture::SamplerInfo::new(texture::FilterMethod::Bilinear, texture::WrapMode::Clamp);
let sampler = samplers.get_or_insert(sampler_info, &mut factory);
let white_image =
Image::make_raw(&mut factory, &sampler_info, 1, 1, &[255, 255, 255, 255])?;
let texture = white_image.texture.clone();
let data = pipe::Data {
vbuf: quad_vertex_buffer.clone(),
tex: (texture, sampler),
rect_properties: rect_props,
globals: globals_buffer,
out: color_view,
};
// Set initial uniform values
let left = 0.0;
let right = screen_width as f32;
let top = 0.0;
let bottom = screen_height as f32;
let globals = Globals {
transform: ortho(left, right, top, bottom, 1.0, -1.0),
color: types::WHITE.into(),
};
let mut gfx = GraphicsContext {
background_color: Color::new(0.1, 0.2, 0.3, 1.0),
shader_globals: globals,
line_width: 1.0,
point_size: 1.0,
white_image: white_image,
screen_rect: Rect::new(left, bottom, (right - left), (top - bottom)),
dpi: dpi,
window: window,
gl_context: gl_context,
device: Box::new(device),
factory: Box::new(factory),
encoder: encoder,
depth_view: depth_view,
pso: pso,
data: data,
quad_slice: quad_slice,
quad_vertex_buffer: quad_vertex_buffer,
default_sampler_info: sampler_info,
samplers: samplers,
};
let w = screen_width as f32;
let h = screen_height as f32;
let rect = Rect {
x: (w / 2.0),
y: (h / 2.0),
w: w,
h: -h,
};
gfx.set_graphics_rect(rect);
gfx.update_globals()?;
Ok(gfx)
}
fn update_globals(&mut self) -> GameResult<()> {
self.encoder
.update_buffer(&self.data.globals, &[self.shader_globals], 0)?;
Ok(())
}
fn update_rect_properties(&mut self, draw_params: DrawParam) -> GameResult<()> {
let properties = draw_params.into();
self.encoder
.update_buffer(&self.data.rect_properties, &[properties], 0)?;
Ok(())
}
/// Returns a reference to the SDL window.
/// Ideally you should not need to use this because ggez
/// would provide all the functions you need without having
/// to dip into SDL itself. But life isn't always ideal.
pub fn get_window(&self) -> &sdl2::video::Window {
&self.window
}
/// Returns a mutable reference to the SDL window.
pub fn get_window_mut(&mut self) -> &mut sdl2::video::Window {
&mut self.window
}
/// Returns the size of the window in pixels as (height, width).
pub fn get_size(&self) -> (u32, u32) {
self.window.size()
}
/// Returns the size of the window's underlaying drawable in pixels as (height, width).
/// This may return a different value than `get_size()` when run on a platform with high-DPI support
pub fn get_drawable_size(&self) -> (u32, u32) {
self.window.drawable_size()
}
/// EXPERIMENTAL function to get the gfx-rs `Factory` object.
pub fn get_factory(&mut self) -> &mut gfx_device_gl::Factory {
&mut self.factory
}
/// EXPERIMENTAL function to get the gfx-rs `Device` object.
pub fn get_device(&mut self) -> &mut gfx_device_gl::Device {
self.device.as_mut()
}
/// EXPERIMENTAL function to get the gfx-rs `Encoder` object.
pub fn get_encoder(
&mut self,
) -> &mut gfx::Encoder<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer> {
&mut self.encoder
}
/// EXPERIMENTAL function to get the gfx-rs depth view
pub fn get_depth_view(
&self,
) -> gfx::handle::DepthStencilView<gfx_device_gl::Resources, gfx::format::DepthStencil> {
self.depth_view.clone()
}
/// EXPERIMENTAL function to get the gfx-rs color view
pub fn get_color_view(
&self,
) -> gfx::handle::RenderTargetView<
gfx_device_gl::Resources,
(gfx::format::R8_G8_B8_A8, gfx::format::Srgb),
> {
self.data.out.clone()
}
/// Shortcut function to set the screen rect ortho mode
/// to a given `Rect`.
///
/// Call `update_globals()` to apply them after calling this.
fn set_graphics_rect(&mut self, rect: Rect) {
self.screen_rect = rect;
let half_width = rect.w / 2.0;
let half_height = rect.h / 2.0;
self.shader_globals.transform = ortho(
rect.x - half_width, rect.x + half_width,
rect.y + half_height, rect.y - half_height,
1.0, -1.0
);
}
}
/// Creates an orthographic projection matrix.
///
/// Rather than create a dependency on cgmath or nalgebra for this one function,
/// we're just going to define it ourselves.
fn ortho(left: f32, right: f32, top: f32, bottom: f32, far: f32, near: f32) -> [[f32; 4]; 4] {
let c0r0 = 2.0 / (right - left);
let c0r1 = 0.0;
let c0r2 = 0.0;
let c0r3 = 0.0;
let c1r0 = 0.0;
let c1r1 = 2.0 / (top - bottom);
let c1r2 = 0.0;
let c1r3 = 0.0;
let c2r0 = 0.0;
let c2r1 = 0.0;
let c2r2 = -2.0 / (far - near);
let c2r3 = 0.0;
let c3r0 = -(right + left) / (right - left);
let c3r1 = -(top + bottom) / (top - bottom);
let c3r2 = -(far + near) / (far - near);
let c3r3 = 1.0;
[
[c0r0, c1r0, c2r0, c3r0],
[c0r1, c1r1, c2r1, c3r1],
[c0r2, c1r2, c2r2, c3r2],
[c0r3, c1r3, c2r3, c3r3],
]
}
// **********************************************************************
// DRAWING
// **********************************************************************
/// Clear the screen to the background color.
pub fn clear(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
gfx.encoder
.clear(&gfx.data.out, gfx.background_color.into());
}
/// Draws the given `Drawable` object to the screen by calling its
/// `draw()` method.
pub fn draw(ctx: &mut Context, drawable: &Drawable, dest: Point, rotation: f32) -> GameResult<()> {
drawable.draw(ctx, dest, rotation)
}
/// Draws the given `Drawable` object to the screen by calling its `draw_ex()` method.
pub fn draw_ex(ctx: &mut Context, drawable: &Drawable, params: DrawParam) -> GameResult<()> {
drawable.draw_ex(ctx, params)
}
/// Tells the graphics system to actually put everything on the screen.
/// Call this at the end of your `EventHandler`'s `draw()` method.
pub fn present(ctx: &mut Context) {
let gfx = &mut ctx.gfx_context;
// We might want to give the user more control over when the
// encoder gets flushed eventually, if we want them to be able
// to do their own gfx drawing. HOWEVER, the whole pipeline type
// thing is a bigger hurdle, so this is fine for now.
gfx.encoder.flush(&mut *gfx.device);
gfx.window.gl_swap_window();
gfx.device.cleanup();
}
/*
// Draw an arc.
// Punting on this until later.
pub fn arc(_ctx: &mut Context,
_mode: DrawMode,
_point: Point,
_radius: f32,
_angle1: f32,
_angle2: f32,
_segments: u32)
-> GameResult<()> {
unimplemented!();
}
*/
/// Draw a circle.
pub fn circle(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
tolerance: f32,
) -> GameResult<()> {
let m = Mesh::new_circle(ctx, mode, point, radius, tolerance)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draw an ellipse.
pub fn ellipse(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
tolerance: f32,
) -> GameResult<()> {
let m = Mesh::new_ellipse(ctx, mode, point, radius1, radius2, tolerance)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draws a line of one or more connected segments.
pub fn line(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_line(ctx, points, w)?;
m.draw(ctx, Point::default(), 0.0)
}
/// Draws points.
pub fn points(ctx: &mut Context, points: &[Point]) -> GameResult<()> {
let size = ctx.gfx_context.point_size;
for p in points {
let r = Rect::new(p.x, p.y, size, size);
rectangle(ctx, DrawMode::Fill, r)?;
}
Ok(())
}
/// Draws a closed polygon
pub fn polygon(ctx: &mut Context, mode: DrawMode, vertices: &[Point]) -> GameResult<()> {
let w = ctx.gfx_context.line_width;
let m = Mesh::new_polygon(ctx, mode, vertices, w)?;
m.draw(ctx, Point::default(), 0.0)
}
// Renders text with the default font.
// Not terribly efficient as it re-renders the text with each call,
// but good enough for debugging.
// Doesn't actually work, double-borrow on ctx. Bah.
// pub fn print(ctx: &mut Context, dest: Point, text: &str) -> GameResult<()> {
// let rendered_text = {
// let font = &ctx.default_font;
// text::Text::new(ctx, text, font)?
// };
// draw(ctx, &rendered_text, dest, 0.0)
// }
/// Draws a rectangle.
pub fn rectangle(ctx: &mut Context, mode: DrawMode, rect: Rect) -> GameResult<()> {
let x = rect.x;
let y = rect.y;
let w = rect.w;
let h = rect.h;
let x1 = x - (w / 2.0);
let x2 = x + (w / 2.0);
let y1 = y - (h / 2.0);
let y2 = y + (h / 2.0);
let pts = [
[x1, y1].into(),
[x2, y1].into(),
[x2, y2].into(),
[x1, y2].into(),
];
polygon(ctx, mode, &pts)
}
// **********************************************************************
// GRAPHICS STATE
// **********************************************************************
/// Returns the current background color.
pub fn get_background_color(ctx: &Context) -> Color {
ctx.gfx_context.background_color
}
/// Returns the current foreground color.
pub fn get_color(ctx: &Context) -> Color {
ctx.gfx_context.shader_globals.color.into()
}
/// Get the default filter mode for new images.
pub fn get_default_filter(ctx: &Context) -> FilterMode {
let gfx = &ctx.gfx_context;
gfx.default_sampler_info.filter.into()
}
/// Get the current width for drawing lines and stroked polygons.
pub fn get_line_width(ctx: &Context) -> f32 {
ctx.gfx_context.line_width
}
/// Get the current size for drawing points.
pub fn get_point_size(ctx: &Context) -> f32 {
ctx.gfx_context.point_size
}
/// Returns a string that tells a little about the obtained rendering mode.
/// It is supposed to be human-readable and will change; do not try to parse
/// information out of it!
pub fn get_renderer_info(ctx: &Context) -> GameResult<String> {
let video = ctx.sdl_context.video()?;
let gl = video.gl_attr();
Ok(format!(
"Requested GL {}.{} Core profile, actually got GL {}.{} {:?} profile.",
GL_MAJOR_VERSION,
GL_MINOR_VERSION,
gl.context_major_version(),
gl.context_minor_version(),
gl.context_profile()
))
}
/// Returns a rectangle defining the coordinate system of the screen.
/// It will be `Rect { x: center_x, y: cenyer_y, w: width, h: height }`
///
/// If the Y axis increases downwards, the `height` of the Rect
/// will be negative.
pub fn get_screen_coordinates(ctx: &Context) -> Rect {
ctx.gfx_context.screen_rect
}
/// Sets the background color. Default: blue.
pub fn set_background_color(ctx: &mut Context, color: Color) {
ctx.gfx_context.background_color = color;
}
/// Sets the foreground color, which will be used for drawing
/// rectangles, lines, etc. Default: white.
pub fn set_color(ctx: &mut Context, color: Color) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.shader_globals.color = color.into();
gfx.update_globals()
}
/// Sets the default filter mode used to scale images.
///
/// This does not apply retroactively to already created images.
pub fn set_default_filter(ctx: &mut Context, mode: FilterMode) {
let gfx = &mut ctx.gfx_context;
let new_mode = mode.into();
let sampler_info = texture::SamplerInfo::new(new_mode, texture::WrapMode::Clamp);
// We create the sampler now so we don't end up creating it at some
// random-ass time while we're trying to draw stuff.
let _sampler = gfx.samplers.get_or_insert(sampler_info, &mut *gfx.factory);
gfx.default_sampler_info = sampler_info;
}
/// Set the current width for drawing lines and stroked polygons.
pub fn set_line_width(ctx: &mut Context, width: f32) {
ctx.gfx_context.line_width = width;
}
/// Set the current size for drawing points.
pub fn set_point_size(ctx: &mut Context, size: f32) {
ctx.gfx_context.point_size = size;
}
/// Sets the bounds of the screen viewport.
///
/// The default coordinate system has (0,0) at the top-left corner
/// with X increasing to the right and Y increasing down, with the
/// viewport scaled such that one coordinate unit is one pixel on the
/// screen. This function lets you change this coordinate system to
/// be whatever you prefer.
///
/// Recall that a `Rect` currently the x and y coordinates at the center,
/// so if you wanted a coordinate system from (0,0) at the bottom-left
/// to (640, 480) at the top-right, you would call this function with
/// a `Rect{x: 320, y: 240, w: 640, h: 480}`
pub fn set_screen_coordinates(
context: &mut Context,
rect: Rect,
) -> GameResult<()> {
let gfx = &mut context.gfx_context;
gfx.set_graphics_rect(rect);
gfx.update_globals()
}
/// Sets the window mode, such as the size and other properties.
///
/// Setting the window mode may have side effects, such as clearing
/// the screen or setting the screen coordinates viewport to some undefined value.
/// It is recommended to call `set_screen_coordinates()` after changing the window
/// size to make sure everything is what you want it to be.
pub fn set_mode(
context: &mut Context,
width: u32,
height: u32,
mode: WindowMode,
) -> GameResult<()> {
{
let window = &mut context.gfx_context.get_window_mut();
window.set_size(width, height)?;
// SDL sets "bordered" but Love2D does "not bordered";
// we use the Love2D convention.
window.set_bordered(!mode.borderless);
window.set_fullscreen(mode.fullscreen_type)?;
let (min_w, min_h) = mode.min_dimensions;
window.set_minimum_size(min_w, min_h)?;
let (max_w, max_h) = mode.max_dimensions;
window.set_maximum_size(max_w, max_h)?;
}
{
let video = context.sdl_context.video()?;
let vsync_int = if mode.vsync { 1 } else { 0 };
video.gl_set_swap_interval(vsync_int);
}
Ok(())
}
/// Returns a `Vec` of `(width, height)` tuples describing what
/// fullscreen resolutions are available for the given display.
pub fn get_fullscreen_modes(context: &Context, display_idx: i32) -> GameResult<Vec<(u32, u32)>> {
let video = context.sdl_context.video()?;
let display_count = video.num_video_displays()?;
assert!(display_idx < display_count);
let num_modes = video.num_display_modes(display_idx)?;
(0..num_modes)
.map(|i| video.display_mode(display_idx, i))
.map(|ires| ires.map_err(GameError::VideoError))
.map(|gres| {
gres.map(|dispmode| (dispmode.w as u32, dispmode.h as u32))
})
.collect()
}
/// Returns the number of connected displays.
pub fn get_display_count(context: &Context) -> GameResult<i32> {
let video = context.sdl_context.video()?;
video.num_video_displays().map_err(GameError::VideoError)
}
// **********************************************************************
// TYPES
// **********************************************************************
/// A struct containing all the necessary info for drawing a Drawable.
///
/// * `src` - a portion of the drawable to clip, as a fraction of the whole image.
/// Defaults to the whole image (1.0) if omitted.
/// * `dest` - the position to draw the graphic expressed as a `Point`.
/// * `rotation` - orientation of the graphic in radians.
/// * `scale` - x/y scale factors expressed as a `Point`.
/// * `offset` - specifies an offset from the center for transform operations like scale/rotation.
/// * `shear` - x/y shear factors expressed as a `Point`.
///
/// This struct implements the `Default` trait, so you can just do:
///
/// `graphics::draw_ex(ctx, drawable, DrawParam{ dest: my_dest, .. Default::default()} )`
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct DrawParam {
pub src: Rect,
pub dest: Point,
pub rotation: f32,
pub scale: Point,
pub offset: Point,
pub shear: Point,
}
impl Default for DrawParam {
fn default() -> Self {
DrawParam {
src: Rect::one(),
dest: Point::zero(),
rotation: 0.0,
scale: Point::new(1.0, 1.0),
offset: Point::new(0.0, 0.0),
shear: Point::new(0.0, 0.0),
}
}
}
/// All types that can be drawn on the screen implement the `Drawable` trait.
pub trait Drawable {
/// Actually draws the object to the screen.
///
/// This is the most general version of the operation, which is all that
/// is required for implementing this trait.
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()>;
/// Draws the drawable onto the rendering target.
///
/// It just is a shortcut that calls `draw_ex()` with some sane defaults.
///
/// * `ctx` - The `Context` this graphic will be rendered to.
/// * `dest` - the position to draw the graphic expressed as a `Point`.
/// * `rotation` - orientation of the graphic in radians.
///
fn draw(&self, ctx: &mut Context, dest: Point, rotation: f32) -> GameResult<()> {
self.draw_ex(
ctx,
DrawParam {
dest: dest,
rotation: rotation,
..Default::default()
},
)
}
}
/// Generic in-GPU-memory image data available to be drawn on the screen.
#[derive(Clone)]
pub struct ImageGeneric<R>
where
R: gfx::Resources,
{
texture: gfx::handle::ShaderResourceView<R, [f32; 4]>,
sampler_info: gfx::texture::SamplerInfo,
width: u32,
height: u32,
}
/// In-GPU-memory image data available to be drawn on the screen,
/// using the OpenGL backend.
pub type Image = ImageGeneric<gfx_device_gl::Resources>;
/// Copies an 2D (RGBA) buffer into one that is the next
/// power of two size up in both dimensions. All data is
/// retained and kept closest to [0,0]; anything extra is
/// filled with 0
fn scale_rgba_up_to_power_of_2(width: u16, height: u16, rgba: &[u8]) -> (u16, u16, Vec<u8>) {
let width = width as usize;
let height = height as usize;
let w2 = width.next_power_of_two();
let h2 = height.next_power_of_two();
// println!("Scaling from {}x{} to {}x{}", width, height, w2, h2);
let num_vals = w2 * h2 * 4;
let mut v: Vec<u8> = Vec::with_capacity(num_vals);
// This is a little wasteful because we will be replacing
// many if not most of these 0's with the actual image data.
// But it's much simpler to resize the thing once than to blit
// each row, resize it out to fill the rest of the row with zeroes,
// etc.
v.resize(num_vals, 0);
// Blit each row of the old image into the new array.
for i in 0..h2 {
if i < height {
let src_start = i * width * 4;
let src_end = src_start + width * 4;
let dest_start = i * w2 * 4;
let dest_end = dest_start + width * 4;
let slice = &mut v[dest_start..dest_end];
slice.copy_from_slice(&rgba[src_start..src_end]);
}
}
(w2 as u16, h2 as u16, v)
}
impl Image {
/// Load a new image from the file at the given path.
pub fn new<P: AsRef<path::Path>>(context: &mut Context, path: P) -> GameResult<Image> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (width, height) = img.dimensions();
Image::from_rgba8(context, width as u16, height as u16, &img)
}
/// Creates a new `Image` from the given buffer of `u8` RGBA values.
pub fn from_rgba8(
context: &mut Context,
width: u16,
height: u16,
rgba: &[u8],
) -> GameResult<Image> {
Image::make_raw(
&mut context.gfx_context.factory,
&context.gfx_context.default_sampler_info,
width,
height,
rgba,
)
}
/// A helper function that just takes a factory directly so we can make an image
/// without needing the full context object, so we can create an Image while still
/// creating the GraphicsContext.
fn make_raw(
factory: &mut gfx_device_gl::Factory,
sampler_info: &texture::SamplerInfo,
width: u16,
height: u16,
rgba: &[u8],
) -> GameResult<Image> {
// Check if the texture is not power of 2, and if not, pad it out.
let view = if false {
// let view = if !(width.is_power_of_two() && height.is_power_of_two()) {
let (width, height, rgba) = scale_rgba_up_to_power_of_2(width, height, rgba);
let rgba = &rgba;
assert_eq!((width as usize) * (height as usize) * 4, rgba.len());
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
// The slice containing rgba is NOT rows x columns, it is a slice of
// MIPMAP LEVELS. Augh!
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
} else {
if width == 0 || height == 0 {
let msg = format!(
"Tried to create a texture of size {}x{}, each dimension must \
be >0",
width,
height
);
return Err(GameError::ResourceLoadError(msg));
}
let kind = gfx::texture::Kind::D2(width, height, gfx::texture::AaMode::Single);
let (_, view) = factory
.create_texture_immutable_u8::<gfx::format::Srgba8>(kind, &[rgba])?;
view
};
Ok(Image {
texture: view,
sampler_info: *sampler_info,
width: width as u32,
height: height as u32,
})
}
/// A little helper function that creates a new Image that is just
/// a solid square of the given size and color. Mainly useful for
/// debugging.
pub fn solid(context: &mut Context, size: u16, color: Color) -> GameResult<Image> {
let pixel_array: [u8; 4] = color.into();
let size_squared = size as usize * size as usize;
let mut buffer = Vec::with_capacity(size_squared);
for _i in 0..size_squared {
buffer.extend(&pixel_array[..]);
}
Image::from_rgba8(context, size, size, &buffer)
}
/// Return the width of the image.
pub fn width(&self) -> u32 {
self.width
}
/// Return the height of the image.
pub fn height(&self) -> u32 {
self.height
}
/// Get the filter mode for the image.
pub fn get_filter(&self) -> FilterMode {
self.sampler_info.filter.into()
}
/// Set the filter mode for the image.
pub fn set_filter(&mut self, mode: FilterMode) {
self.sampler_info.filter = mode.into();
}
/// Returns the dimensions of the image.
pub fn get_dimensions(&self) -> Rect {
Rect::new(0.0, 0.0, self.width() as f32, self.height() as f32)
}
/// Gets the `Image`'s `WrapMode` along the X and Y axes.
pub fn get_wrap(&self) -> (WrapMode, WrapMode) {
(self.sampler_info.wrap_mode.0, self.sampler_info.wrap_mode.1)
}
/// Sets the `Image`'s `WrapMode` along the X and Y axes.
pub fn set_wrap(&mut self, wrap_x: WrapMode, wrap_y: WrapMode) {
self.sampler_info.wrap_mode.0 = wrap_x;
self.sampler_info.wrap_mode.1 = wrap_y;
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"<Image: {}x{}, {:p}, texture address {:p}, sampler: {:?}>",
self.width(),
self.height(),
self,
&self.texture,
&self.sampler_info
)
}
}
impl Drawable for Image {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
let src_width = param.src.w;
let src_height = param.src.h;
// We have to mess with the scale to make everything
// be its-unit-size-in-pixels.
// We also invert the Y scale if our screen coordinates
// are "upside down", because by default we present the
// illusion that the screen is addressed in pixels.
// BUGGO: Which I rather regret now.
let invert_y = if gfx.screen_rect.h < 0.0 { 1.0 } else { -1.0 };
let real_scale = Point {
x: src_width * param.scale.x * self.width as f32,
y: src_height * param.scale.y * self.height as f32 * invert_y,
};
let mut new_param = param;
new_param.scale = real_scale;
// Not entirely sure why the inversion is necessary, but oh well.
new_param.offset.x *= -1.0 * param.scale.x;
new_param.offset.y *= param.scale.y;
gfx.update_rect_properties(new_param)?;
let sampler = gfx.samplers
.get_or_insert(self.sampler_info, gfx.factory.as_mut());
gfx.data.vbuf = gfx.quad_vertex_buffer.clone();
gfx.data.tex = (self.texture.clone(), sampler);
gfx.encoder.draw(&gfx.quad_slice, &gfx.pso, &gfx.data);
Ok(())
}
}
/// 2D polygon mesh
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh {
buffer: gfx::handle::Buffer<gfx_device_gl::Resources, Vertex>,
slice: gfx::Slice<gfx_device_gl::Resources>,
}
use lyon::tessellation as t;
struct VertexBuilder;
impl t::VertexConstructor<t::FillVertex, Vertex> for VertexBuilder {
fn new_vertex(&mut self, vertex: t::FillVertex) -> Vertex {
Vertex {
pos: [vertex.position.x, vertex.position.y],
uv: [0.0, 0.0],
}
}
}
impl t::VertexConstructor<t::StrokeVertex, Vertex> for VertexBuilder {
fn new_vertex(&mut self, vertex: t::StrokeVertex) -> Vertex {
Vertex {
pos: [vertex.position.x, vertex.position.y],
uv: [0.0, 0.0],
}
}
}
impl Mesh {
fn from_vbuf(
ctx: &mut Context,
buffer: &t::geometry_builder::VertexBuffers<Vertex>,
) -> GameResult<Mesh> {
let (vbuf, slice) = ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&buffer.vertices[..], &buffer.indices[..]);
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
/// Create a new mesh for a line of one or more connected segments.
/// WIP, sorry
pub fn new_line(ctx: &mut Context, points: &[Point], width: f32) -> GameResult<Mesh> {
Mesh::new_polyline(ctx, DrawMode::Line, points, width)
}
/// Create a new mesh for a circle.
/// Stroked circles are still WIP, sorry.
pub fn new_circle(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius: f32,
tolerance: f32,
) -> GameResult<Mesh> {
{
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
t::basic_shapes::fill_circle(
t::math::point(point.x, point.y),
radius,
tolerance,
builder,
);
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(ctx.gfx_context.line_width)
.with_tolerance(tolerance);
t::basic_shapes::stroke_circle(
t::math::point(point.x, point.y),
radius,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
}
/// Create a new mesh for an ellipse.
/// Stroked ellipses are still WIP, sorry.
pub fn new_ellipse(
ctx: &mut Context,
mode: DrawMode,
point: Point,
radius1: f32,
radius2: f32,
tolerance: f32,
) -> GameResult<Mesh> {
use euclid::Length;
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
t::basic_shapes::fill_ellipse(
t::math::point(point.x, point.y),
t::math::vec2(radius1, radius2),
Length::new(0.0),
tolerance,
builder,
);
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(ctx.gfx_context.line_width)
.with_tolerance(tolerance);
t::basic_shapes::stroke_ellipse(
t::math::point(point.x, point.y),
t::math::vec2(radius1, radius2),
Length::new(0.0),
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new mesh for series of connected lines
pub fn new_polyline(
ctx: &mut Context,
mode: DrawMode,
points: &[Point],
width: f32)
-> GameResult<Mesh> {
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
let points = points
.into_iter()
.map(|ggezpoint| t::math::point(ggezpoint.x, ggezpoint.y));
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let tessellator = &mut t::FillTessellator::new();
let options = t::FillOptions::default();
t::basic_shapes::fill_polyline(
points,
tessellator,
&options,
builder,
).unwrap();
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(width);
t::basic_shapes::stroke_polyline(
points,
false,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new mesh for closed polygon
pub fn new_polygon(
ctx: &mut Context,
mode: DrawMode,
points: &[Point],
width: f32)
-> GameResult<Mesh> {
let buffers: &mut t::geometry_builder::VertexBuffers<_> = &mut t::VertexBuffers::new();
let points = points
.into_iter()
.map(|ggezpoint| t::math::point(ggezpoint.x, ggezpoint.y));
match mode {
DrawMode::Fill => {
// These builders have to be in separate match arms 'cause they're actually
// different types; one is GeometryBuilder<StrokeVertex> and the other is
// GeometryBuilder<FillVertex>
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let tessellator = &mut t::FillTessellator::new();
let options = t::FillOptions::default();
t::basic_shapes::fill_polyline(
points,
tessellator,
&options,
builder,
).unwrap();
}
DrawMode::Line => {
let builder = &mut t::BuffersBuilder::new(buffers, VertexBuilder);
let options = t::StrokeOptions::default()
.with_line_width(width);
t::basic_shapes::stroke_polyline(
points,
true,
&options,
builder,
);
}
};
Mesh::from_vbuf(ctx, buffers)
}
/// Create a new `Mesh` from a raw list of triangles.
///
/// Currently does not support UV's or indices.
pub fn from_triangles(ctx: &mut Context, triangles: &[Point]) -> GameResult<Mesh> {
// This is kind of non-ideal but works for now.
let points: Vec<Vertex> = triangles
.into_iter()
.map(|p| {
Vertex {
pos: (*p).into(),
uv: (*p).into(),
}
})
.collect();
let (vbuf, slice) = ctx.gfx_context
.factory
.create_vertex_buffer_with_slice(&points[..], ());
Ok(Mesh {
buffer: vbuf,
slice: slice,
})
}
}
impl Drawable for Mesh {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
let gfx = &mut ctx.gfx_context;
gfx.update_rect_properties(param)?;
gfx.data.vbuf = self.buffer.clone();
gfx.data.tex.0 = gfx.white_image.texture.clone();
gfx.encoder.draw(&self.slice, &gfx.pso, &gfx.data);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_scaling_up() {
let mut from: Vec<u8> = Vec::new();
const WIDTH: u16 = 5;
const HEIGHT: u16 = 11;
for i in 0..HEIGHT {
let v = vec![i as u8; WIDTH as usize * 4];
from.extend(v.iter());
}
assert_eq!(from.len(), WIDTH as usize * HEIGHT as usize * 4);
let (width, height, res) = scale_rgba_up_to_power_of_2(WIDTH, HEIGHT, &from);
assert_eq!(width, WIDTH.next_power_of_two());
assert_eq!(height, HEIGHT.next_power_of_two());
for i in 0..HEIGHT.next_power_of_two() {
for j in 0..WIDTH.next_power_of_two() {
let offset_within_row = (j * 4) as usize;
let src_row_offset = (i * WIDTH * 4) as usize;
let dst_row_offset = (i * width * 4) as usize;
println!("{} {}", i, j);
if i < HEIGHT && j < WIDTH {
assert_eq!(
res[dst_row_offset + offset_within_row],
from[src_row_offset + offset_within_row]
);
} else {
assert_eq!(res[dst_row_offset + offset_within_row], 0);
}
}
}
}
}
|
use super::cpu::*;
use num::FromPrimitive;
pub trait Instruction {
fn execute(&self, &mut Cpu);
}
struct Unsupported;
impl Instruction for Unsupported {
fn execute(&self, cpu: &mut Cpu) {
info!("{:?}", cpu);
panic!("Unsupported instruction {:#x} at address {:#06x}", cpu.read_word(cpu.get_pc()), cpu.get_pc());
}
}
struct Nop;
impl Instruction for Nop {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
info!("{:#06x}: NOP", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct AdcAN ;
struct AdcHlSs { r: Reg16 }
impl Instruction for AdcAN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = a.wrapping_add(n).wrapping_add(c);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x8000 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0FFF + n & 0x0FFF + c > 0x0FFF );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n ^ 0x8000) & (a ^ res ^ 0x8000) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u32 + n as u32 + c as u32 > 0xFFFF );
info!("{:#06x}: ADC A, {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AdcHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL);
let ss = cpu.read_reg16(self.r);
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = hl.wrapping_add(ss).wrapping_add(c);
cpu.write_reg16(Reg16::HL, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x8000 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , hl & 0x0FFF + ss & 0x0FFF + c > 0x0FFF );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (hl ^ ss ^ 0x8000) & (hl ^ res ^ 0x8000) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , hl as u32 + ss as u32 + c as u32 > 0xFFFF );
info!("{:#06x}: ADC HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
struct AddAN ;
struct AddAR { r: Reg8 }
struct AddHlSs { r: Reg16 }
struct AddAMemIyD ;
impl Instruction for AddAN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a.wrapping_add(n);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + n & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + n as u16 > 0xFF );
info!("{:#06x}: ADD A, {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AddAR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a.wrapping_add(r);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + r & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + r as u16 > 0xFF );
info!("{:#06x}: ADD A, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AddHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL);
let ss = cpu.read_reg16(self.r);
let res = hl.wrapping_add(ss);
cpu.write_reg16(Reg16::HL, res);
cpu.cond_flag ( HALF_CARRY_FLAG , hl & 0x0FFF + ss & 0x0FFF > 0x0FFF );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , hl as u32 + ss as u32 > 0xFFFF );
info!("{:#06x}: ADD HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
impl Instruction for AddAMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OIY));
let a = cpu.read_reg8(Reg8::A);
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
let res = a.wrapping_add(memval);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + memval & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + memval as u16 > 0xFF );
if d < 0 {
info!("{:#06x}: ADD A, (IY-{:#04X})", cpu.get_pc() - 1, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: ADD A, (IY+{:#04X})", cpu.get_pc() - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
struct AndR { r: Reg8 }
struct AndN ;
impl Instruction for AndR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a & r;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: AND {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AndN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a & n;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: AND {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
struct BitBMemIyD { b: u8 }
impl Instruction for BitBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OIY));
let d = cpu.read_word(cpu.get_pc()) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
cpu.cond_flag ( ZERO_FLAG , memval & (1 << self.b) == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
if d < 0 {
info!("{:#06x}: BIT {}, (IY-{:#04X})", cpu.get_pc() - 2, self.b, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: BIT {}, (IY+{:#04X})", cpu.get_pc() - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
struct CallNn ;
struct CallCcNn { cond: FlagCond }
impl Instruction for CallNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let curr_pc = cpu.get_pc();
let nn = (cpu.read_word(curr_pc + 1) as u16) |
((cpu.read_word(curr_pc + 2) as u16) << 8);
let curr_sp = cpu.read_reg16(Reg16::SP);
cpu.write_word(curr_sp - 1, (((curr_pc + 3) & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, ((curr_pc + 3) & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: CALL {:#06X}", curr_pc, nn);
cpu.set_pc(nn);
debug!("{}", cpu.output(OSP));
}
}
impl Instruction for CallCcNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OF));
let curr_pc = cpu.get_pc();
let nn = (cpu.read_word(curr_pc + 1) as u16) |
((cpu.read_word(curr_pc + 2) as u16) << 8);
let curr_sp = cpu.read_reg16(Reg16::SP);
let cc = cpu.check_cond(self.cond);
info!("{:#06x}: CALL {:?}, {:#06X}", curr_pc, self.cond, nn);
if cc {
cpu.write_word(curr_sp - 1, (((curr_pc + 3) & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, ((curr_pc + 3) & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
cpu.set_pc(nn);
} else {
cpu.inc_pc(3);
}
debug!("{}", cpu.output(OSP));
}
}
struct Ccf;
impl Instruction for Ccf {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let c = cpu.get_flag(CARRY_FLAG);
cpu.cond_flag ( HALF_CARRY_FLAG , c );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , !c );
info!("{:#06x}: CCF", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
struct CpR { r: Reg8 }
struct CpN ;
struct CpMemHl ;
struct CpMemIyD ;
impl Instruction for CpR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OA|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a - r;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < r & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r) & (r ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < r );
info!("{:#06x}: CP {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a - n;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < n & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n) & (n ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < n );
info!("{:#06x}: CP {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OH|OL));
let a = cpu.read_reg8(Reg8::A);
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
let res = a - memval;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < memval & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval) & (memval ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < memval );
info!("{:#06x}: CP (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OIY));
let a = cpu.read_reg8(Reg8::A);
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
let res = a - memval;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < memval & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval) & (memval ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < memval );
if d < 0 {
info!("{:#06x}: CP (IY-{:#04X})", cpu.get_pc() - 1, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: CP (IY+{:#04X})", cpu.get_pc() - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
struct DecSs { r: Reg16 }
struct DecR { r: Reg8 }
struct DecIyD ;
impl Instruction for DecSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let decval = cpu.read_reg16(self.r).wrapping_sub(1);
cpu.write_reg16(self.r, decval);
info!("{:#06x}: DEC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for DecR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let decval = cpu.read_reg8(self.r).wrapping_sub(1);
cpu.write_reg8(self.r, decval);
cpu.set_flag(ADD_SUBTRACT_FLAG);
if decval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if decval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if decval & 0b00001111 == 0 { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
if decval == 0x7F { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
info!("{:#06x}: DEC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for DecIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OIY));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc + 1) as i8 as i16;
let addr = ((cpu.get_iy() as i16) + d) as u16;
let decval = cpu.read_word(addr).wrapping_sub(1);
cpu.write_word(addr, decval);
if decval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if decval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if decval & 0b00001111 == 0 { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
if decval == 0x7F { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
cpu.set_flag(ADD_SUBTRACT_FLAG);
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: DEC (IY-{:#04X})", curr_pc - 1, d);
} else {
info!("{:#06x}: DEC (IY+{:#04X})", curr_pc - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF|OIY));
}
}
struct Di;
impl Instruction for Di {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.clear_iff1();
cpu.clear_iff2();
info!("{:#06x}: DI", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct Djnz;
impl Instruction for Djnz {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OB));
let bval = cpu.read_reg8(Reg8::B) - 1;
cpu.write_reg8(Reg8::B, bval);
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: DJNZ {:#06X}", cpu.get_pc(), target);
if bval != 0 {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(OF|OB));
}
}
struct Ei;
impl Instruction for Ei {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.set_iff1();
cpu.set_iff2();
info!("{:#06x}: EI", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct ExAfAfAlt;
struct ExMemSpHl;
struct ExDeHl;
impl Instruction for ExAfAfAlt {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OA_ALT|OF_ALT));
let afval = cpu.read_reg16qq(Reg16qq::AF);
let afaltval = cpu.read_reg16qq(Reg16qq::AF_ALT);
cpu.write_reg16qq(Reg16qq::AF, afaltval);
cpu.write_reg16qq(Reg16qq::AF_ALT, afval);
info!("{:#06x}: EX AF, AF'", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF|OA_ALT|OF_ALT));
}
}
impl Instruction for ExMemSpHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OH|OL));
let spval = cpu.read_reg16(Reg16::SP);
let hlval = cpu.read_reg16(Reg16::HL);
let (hlhigh, hllow) = (((hlval & 0xFF00) >> 8) as u8,
((hlval & 0x00FF) as u8));
let memval = (cpu.read_word(spval ) as u16) |
((cpu.read_word(spval + 1) as u16) << 8);
cpu.write_reg16(Reg16::HL, memval);
cpu.write_word(spval, hllow);
cpu.write_word(spval + 1, hlhigh);
info!("{:#06x}: EX (SP), HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP|OH|OL));
}
}
impl Instruction for ExDeHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OD|OE|OH|OL));
let deval = cpu.read_reg16(Reg16::DE);
let hlval = cpu.read_reg16(Reg16::HL);
cpu.write_reg16(Reg16::DE, hlval);
cpu.write_reg16(Reg16::HL, deval);
info!("{:#06x}: EX DE, HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OD|OE|OH|OL));
}
}
struct Exx;
impl Instruction for Exx {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OB_ALT|OC_ALT|OD_ALT|OE_ALT|OH_ALT|OL_ALT));
let bcval = cpu.read_reg16(Reg16::BC);
let deval = cpu.read_reg16(Reg16::DE);
let hlval = cpu.read_reg16(Reg16::HL);
let bcaltval = cpu.read_reg16(Reg16::BC_ALT);
let dealtval = cpu.read_reg16(Reg16::DE_ALT);
let hlaltval = cpu.read_reg16(Reg16::HL_ALT);
cpu.write_reg16(Reg16::BC, bcaltval);
cpu.write_reg16(Reg16::DE, dealtval);
cpu.write_reg16(Reg16::HL, hlaltval);
cpu.write_reg16(Reg16::BC_ALT, bcval);
cpu.write_reg16(Reg16::DE_ALT, deval);
cpu.write_reg16(Reg16::HL_ALT, hlval);
info!("{:#06x}: EXX", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OB_ALT|OC_ALT|OD_ALT|OE_ALT|OH_ALT|OL_ALT));
}
}
struct Im { mode: u8 }
impl Instruction for Im {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.set_im(self.mode);
info!("{:#06x}: IM {}", cpu.get_pc() - 1, self.mode);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct InAPortN;
impl Instruction for InAPortN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let n = cpu.read_word(cpu.get_pc() + 1);
let port = Port::from_u8(n).unwrap();
let portval = cpu.read_port(port);
cpu.write_reg8(Reg8::A, portval);
info!("{:#06x}: IN A, ({:#04X})", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA));
}
}
struct IncR { r: Reg8 }
struct IncSs { r: Reg16 }
struct IncMemHl;
impl Instruction for IncR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let rval = cpu.read_reg8(self.r);
let incval = rval.wrapping_add(1);
cpu.write_reg8(self.r, incval);
if incval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if incval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if incval & 0b00001111 == 0 { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
if rval == 0x7F { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: INC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for IncSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let incval = cpu.read_reg16(self.r).wrapping_add(1);
cpu.write_reg16(self.r, incval);
info!("{:#06x}: INC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for IncMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
let incval = cpu.read_word(hlval).wrapping_add(1);
cpu.write_word(hlval, incval);
if incval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if incval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if incval & 0b00001111 == 0 { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
if hlval == 0x7F { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: INC (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL));
}
}
struct JpMemHl;
struct JpNn ;
struct JpCcNn { cond: FlagCond }
impl Instruction for JpMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
info!("{:#06x}: JP (HL)", cpu.get_pc());
cpu.set_pc(hlval);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JpNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
info!("{:#06x}: JP {:#06X}", cpu.get_pc(), nn);
cpu.set_pc(nn);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JpCcNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let condval = match self.cond {
FlagCond::NZ => cpu.get_flag(ZERO_FLAG) == false,
FlagCond::Z => cpu.get_flag(ZERO_FLAG) == true,
FlagCond::NC => cpu.get_flag(CARRY_FLAG) == false,
FlagCond::C => cpu.get_flag(CARRY_FLAG) == true,
FlagCond::PO => cpu.get_flag(PARITY_OVERFLOW_FLAG) == false,
FlagCond::PE => cpu.get_flag(PARITY_OVERFLOW_FLAG) == true,
FlagCond::P => cpu.get_flag(SIGN_FLAG) == false,
FlagCond::M => cpu.get_flag(SIGN_FLAG) == true
};
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
info!("{:#06x}: JP {:?}, {:#06X}", cpu.get_pc(), self.cond, nn);
if condval {
cpu.set_pc(nn);
} else {
cpu.inc_pc(3);
}
debug!("{}", cpu.output(ONONE));
}
}
struct JrZ ;
struct JrNz;
struct JrNcE;
struct JrCE;
struct JrE ;
impl Instruction for JrZ {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: JR Z, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(ZERO_FLAG) {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrNz {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: JR NZ, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(ZERO_FLAG) {
cpu.inc_pc(2);
} else {
cpu.set_pc(target);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrNcE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: JR NC, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(CARRY_FLAG) {
cpu.inc_pc(2);
} else {
cpu.set_pc(target);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrCE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: JR C, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(CARRY_FLAG) {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let curr_pc = cpu.get_pc();
let offset = cpu.read_word(curr_pc + 1) as i8 + 2;
let target = (curr_pc as i16 + offset as i16) as u16;
info!("{:#06x}: JR {:#06X}", cpu.get_pc(), target);
cpu.set_pc(target);
debug!("{}", cpu.output(ONONE));
}
}
struct LdRN { r: Reg8 }
struct LdDdNn { r: Reg16 }
struct LdDdMemNn { r: Reg16 }
struct LdHlMemNn ;
struct LdMemHlN ;
struct LdRMemIyD { r: Reg8 }
struct LdMemIyDN ;
struct LdSpHl ;
struct LdIxNn ;
struct LdIxMemNn ;
struct LdMemNnIx ;
struct LdMemIxDN ;
struct LdRR { rt: Reg8, rs: Reg8 }
struct LdMemNnDd { r: Reg16 }
struct LdMemHlR { r: Reg8 }
struct LdMemNnA ;
struct LdRMemHl { r: Reg8 }
struct LdMemNnHl ;
struct LdAMemNn ;
struct LdAMemDe ;
struct LdMemDeA ;
struct LdIyNn ;
impl Instruction for LdRN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let n = cpu.read_word(cpu.get_pc() + 1);
cpu.write_reg8(self.r, n);
info!("{:#06x}: LD {:?}, {:#04X}", cpu.get_pc(), self.r, n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdDdNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_reg16(self.r, nn);
info!("{:#06x}: LD {:?}, {:#06X}", cpu.get_pc(), self.r, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdDdMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.write_reg16(self.r, nnmemval);
info!("{:#06x}: LD {:?}, ({:#06X})", cpu.get_pc(), self.r, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdHlMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.write_reg16(Reg16::HL, nnmemval);
info!("{:#06x}: LD HL, ({:#06X})", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OH|OL));
}
}
impl Instruction for LdMemHlN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
let n = cpu.read_word(cpu.get_pc() + 1);
cpu.write_word(hlval, n);
info!("{:#06x}: LD (HL), {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY|OutputRegisters::from(self.r)));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc + 1);
let addr = cpu.get_iy() as i16 + d as i16;
let memval = cpu.read_word(addr as u16);
cpu.write_reg8(self.r, memval);
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: LD {:?}, (IY-{:#04X})", curr_pc - 1, self.r, d);
} else {
info!("{:#06x}: LD {:?}, (IY+{:#04X})", curr_pc - 1, self.r, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdMemIyDN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc + 1);
let n = cpu.read_word(curr_pc + 2);
let addr = cpu.get_iy() as i16 + d as i16;
cpu.write_word(addr as u16, n);
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: LD (IY-{:#04X}), {:#04X}", curr_pc - 1, d, n);
} else {
info!("{:#06x}: LD (IY+{:#04X}), {:#04X}", curr_pc - 1, d, n);
}
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdSpHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
cpu.write_reg16(Reg16::SP, hlval);
info!("{:#06x}: LD SP, HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP|OH|OL));
}
}
impl Instruction for LdIxNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.set_ix(nn);
info!("{:#06x}: LD IX, {:#06X}", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdIxMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.set_ix(nnmemval);
info!("{:#06x}: LD IX, TODO {:#06X}", cpu.get_pc() - 1, nnmemval);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemNnIx {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let (ixhigh, ixlow) = (((cpu.get_ix() & 0xFF00) >> 8) as u8,
((cpu.get_ix() & 0x00FF) as u8));
cpu.write_word(nn, ixlow);
cpu.write_word(nn + 1, ixhigh);
info!("{:#06x}: LD ({:#06X}), IX", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemIxDN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc + 1);
let n = cpu.read_word(curr_pc + 2);
let addr = cpu.get_ix() as i16 + d as i16;
cpu.write_word(addr as u16, n);
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: LD (IX-{:#04X}), {:#04X}", curr_pc - 1, d, n);
} else {
info!("{:#06x}: LD (IX+{:#04X}), {:#04X}", curr_pc - 1, d, n);
}
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.rt) | OutputRegisters::from(self.rs)));
let rsval = cpu.read_reg8(self.rs);
cpu.write_reg8(self.rt, rsval);
info!("{:#06x}: LD {:?}, {:?}", cpu.get_pc(), self.rt, self.rs);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.rt) | OutputRegisters::from(self.rs)));
}
}
impl Instruction for LdMemNnDd {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let rval = cpu.read_reg16(self.r);
let (rhigh, rlow) = (((rval & 0xFF00) >> 8) as u8,
((rval & 0x00FF) as u8));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_word(nn, rlow);
cpu.write_word(nn + 1, rhigh);
info!("{:#06x}: LD ({:#06X}), {:?}", cpu.get_pc() - 1, nn, self.r);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemHlR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OutputRegisters::from(self.r)));
let val = cpu.read_reg8(self.r);
let addr = cpu.read_reg16(Reg16::HL);
cpu.write_word(addr, val);
info!("{:#06x}: LD (HL), {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemNnA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let aval = cpu.read_reg8(Reg8::A);
cpu.write_word(nn, aval);
info!("{:#06x}: LD ({:#06X}), A", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)|OH|OL));
let hlmemval = cpu.read_word(cpu.read_reg16(Reg16::HL));
cpu.write_reg8(self.r, hlmemval);
info!("{:#06x}: LD {:?}, (HL)", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdMemNnHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
let (hlhigh, hllow) = (((hlval & 0xFF00) >> 8) as u8,
((hlval & 0x00FF) as u8));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_word(nn, hllow);
cpu.write_word(nn + 1, hlhigh);
info!("{:#06x}: LD ({:#06X}), HL", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdAMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let memval = cpu.read_word(nn);
cpu.write_reg8(Reg8::A, memval);
info!("{:#06x}: LD A, ({:#06X})", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OA));
}
}
impl Instruction for LdAMemDe {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OD|OE));
let deval = cpu.read_reg16(Reg16::DE);
let memval = cpu.read_word(deval);
cpu.write_reg8(Reg8::A, memval);
info!("{:#06x}: LD A, (DE)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA));
}
}
impl Instruction for LdMemDeA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let deval = cpu.read_reg16(Reg16::DE);
let aval = cpu.read_reg8(Reg8::A);
cpu.write_word(deval, aval);
info!("{:#06x}: LD (DE), A", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdIyNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.set_iy(nn);
info!("{:#06x}: LD IY, {:#06X}", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OIY));
}
}
struct Lddr;
impl Instruction for Lddr {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
let mut counter = cpu.read_reg16(Reg16::BC);
while counter > 0 {
let deval = cpu.read_reg16(Reg16::DE);
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
cpu.write_word(deval, memval);
cpu.write_reg16(Reg16::DE, deval.wrapping_sub(1));
cpu.write_reg16(Reg16::HL, hlval.wrapping_sub(1));
counter -= 1;
cpu.write_reg16(Reg16::BC, counter);
}
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(PARITY_OVERFLOW_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: LDDR", cpu.get_pc() - 1);
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
}
}
struct Ldir;
impl Instruction for Ldir {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
let mut counter = cpu.read_reg16(Reg16::BC);
while counter > 0 {
debug!(" Counter is: {}", counter);
let deval = cpu.read_reg16(Reg16::DE);
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
cpu.write_word(deval, memval);
cpu.write_reg16(Reg16::DE, deval.wrapping_add(1));
cpu.write_reg16(Reg16::HL, hlval.wrapping_add(1));
counter -= 1;
cpu.write_reg16(Reg16::BC, counter);
}
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(PARITY_OVERFLOW_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: LDIR", cpu.get_pc() - 1);
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
}
}
struct OrR { r: Reg8 }
struct OrN ;
struct OrMemHl;
impl Instruction for OrR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let orval = cpu.read_reg8(self.r) | cpu.read_reg8(Reg8::A);
cpu.write_reg8(Reg8::A, orval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if orval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
if orval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if orval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
info!("{:#06x}: OR {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for OrN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let n = cpu.read_word(cpu.get_pc() + 1);
let orval = n | cpu.read_reg8(Reg8::A);
cpu.write_reg8(Reg8::A, orval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if orval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
if orval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if orval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
info!("{:#06x}: OR {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for OrMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OH|OL|OF));
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
let orval = memval | cpu.read_reg8(Reg8::A);
cpu.write_reg8(Reg8::A, orval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if orval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
if orval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if orval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
info!("{:#06x}: OR (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
struct OutPortCR { r: Reg8 }
struct OutPortNA ;
impl Instruction for OutPortCR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OutputRegisters::from(self.r)));
let rval = cpu.read_reg8(self.r);
let port = Port::from_u16(cpu.read_reg16(Reg16::BC)).unwrap();
cpu.write_port(port, rval);
info!("{:#06x}: OUT (C), {:?}", cpu.get_pc() - 1, self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for OutPortNA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let n = cpu.read_word(cpu.get_pc() + 1);
let port = Port::from_u8(n).unwrap();
let accval = cpu.read_reg8(Reg8::A);
cpu.write_port(port, accval);
info!("{:#06x}: OUT ({:#04X}), A", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
struct PopQq { r: Reg16qq }
impl Instruction for PopQq {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OutputRegisters::from(self.r)));
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16qq(self.r, ((high as u16) << 8 ) | low as u16);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
info!("{:#06x}: POP {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP|OutputRegisters::from(self.r)));
}
}
struct PushQq { r: Reg16qq }
impl Instruction for PushQq {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)|OSP));
let curr_sp = cpu.read_reg16(Reg16::SP);
let rval = cpu.read_reg16qq(self.r);
cpu.write_word(curr_sp - 1, ((rval & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, (rval & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: PUSH {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP));
}
}
struct ResBMemIyD { b: u8 }
struct ResBMemHl { b: u8 }
impl Instruction for ResBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc) as i16;
let addr = ((cpu.get_iy() as i16) + d) as u16;
let memval = cpu.read_word(addr);
cpu.write_word(addr, memval & !(1 << self.b));
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: RES {}, (IY-{:#04X})", curr_pc - 2, self.b, d);
} else {
info!("{:#06x}: RES {}, (IY+{:#04X})", curr_pc - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for ResBMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
cpu.write_word(hlval, memval & !(1 << self.b));
info!("{:#06x}: RES {}, (HL)", cpu.get_pc() - 1, self.b);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct Ret ;
struct RetCc { cond: FlagCond }
impl Instruction for Ret {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
info!("{:#06x}: RET", cpu.get_pc());
cpu.set_pc(((high as u16) << 8 ) | low as u16);
debug!("{}", cpu.output(OSP));
}
}
impl Instruction for RetCc {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OF));
let condval = match self.cond {
FlagCond::NZ => cpu.get_flag(ZERO_FLAG) == false,
FlagCond::Z => cpu.get_flag(ZERO_FLAG) == true,
FlagCond::NC => cpu.get_flag(CARRY_FLAG) == false,
FlagCond::C => cpu.get_flag(CARRY_FLAG) == true,
FlagCond::PO => cpu.get_flag(PARITY_OVERFLOW_FLAG) == false,
FlagCond::PE => cpu.get_flag(PARITY_OVERFLOW_FLAG) == true,
FlagCond::P => cpu.get_flag(SIGN_FLAG) == false,
FlagCond::M => cpu.get_flag(SIGN_FLAG) == true
};
info!("{:#06x}: RET {:?}", cpu.get_pc(), self.cond);
if condval {
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
cpu.set_pc(((high as u16) << 8 ) | low as u16);
} else {
cpu.inc_pc(1);
}
debug!("{}", cpu.output(OSP));
}
}
struct RlR { r: Reg8 }
struct RlcA ;
impl Instruction for RlR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let rval = cpu.read_reg8(self.r);
let mut rlval = rval.rotate_left(1);
if cpu.get_flag(CARRY_FLAG) { rlval |= 0x01; } else { rlval &= 0xFE; }
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if rval & 0x80 != 0 { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
cpu.write_reg8(self.r, rlval);
info!("{:#06x}: RL {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for RlcA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let aval = cpu.read_reg8(Reg8::A);
let mut rlval = aval.rotate_left(1);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if aval & 0x80 != 0 { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
cpu.write_reg8(Reg8::A, rlval);
info!("{:#06x}: RLCA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct RrA;
struct RrcA;
impl Instruction for RrA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let aval = cpu.read_reg8(Reg8::A);
let mut rrval = aval.rotate_right(1);
if cpu.get_flag(CARRY_FLAG) { rrval |= 0x80; } else { rrval &= 0x7F; }
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if aval & 0x01 != 0 { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
cpu.write_reg8(Reg8::A, rrval);
info!("{:#06x}: RRA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for RrcA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let aval = cpu.read_reg8(Reg8::A);
let rrval = aval.rotate_right(1);
cpu.write_reg8(Reg8::A, rrval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if rrval & 0b10000000 != 0 { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
info!("{:#06x}: RRCA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct Rst { addr: u8 }
impl Instruction for Rst {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let next_pc = cpu.get_pc() + 1;
let curr_sp = cpu.read_reg16(Reg16::SP);
cpu.write_word(curr_sp - 1, ((next_pc & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, (next_pc & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: RST {:#04X}", cpu.get_pc(), self.addr);
cpu.set_pc(self.addr as u16);
debug!("{}", cpu.output(OSP));
}
}
struct Scf;
impl Instruction for Scf {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
cpu.set_flag(CARRY_FLAG);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: SCF", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
struct SetBMemIyD { b: u8 }
struct SetBMemHl { b: u8 }
impl Instruction for SetBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let curr_pc = cpu.get_pc();
let d = cpu.read_word(curr_pc) as i16;
let addr = ((cpu.get_iy() as i16) + d) as u16;
let memval = cpu.read_word(addr);
cpu.write_word(addr, memval | (1 << self.b));
let mut d = d as i8;
if d & 0b10000000 != 0 {
d = (d ^ 0xFF) + 1;
info!("{:#06x}: SET {}, (IY-{:#04X})", curr_pc - 2, self.b, d);
} else {
info!("{:#06x}: SET {}, (IY+{:#04X})", curr_pc - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for SetBMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
cpu.write_word(hlval, memval | (1 << self.b));
info!("{:#06x}: SET {}, (HL)", cpu.get_pc() - 1, self.b);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct SbcR { r: Reg8 }
struct SbcHlSs { r: Reg16 }
impl Instruction for SbcR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let aval = cpu.read_reg8(Reg8::A) as i8;
let rval = cpu.read_reg8(self.r) as i8;
let mut subval = aval.wrapping_sub(rval);
if cpu.get_flag(CARRY_FLAG) { subval = subval.wrapping_sub(1); }
cpu.write_reg8(Reg8::A, subval as u8);
if subval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if subval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if aval & 0x0F < rval & 0x0F { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
match (aval & 0b10000000 != 0,
rval & 0b10000000 != 0,
subval & 0b10000000 != 0) {
(true, false, false) | (false, true, true) => cpu.set_flag(PARITY_OVERFLOW_FLAG),
_ => cpu.clear_flag(PARITY_OVERFLOW_FLAG)
};
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if aval < rval { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
info!("{:#06x}: SBC A, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for SbcHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hlval = cpu.read_reg16(Reg16::HL) as i16;
let rval = cpu.read_reg16(self.r) as i16;
let mut subval = hlval.wrapping_sub(rval);
if cpu.get_flag(CARRY_FLAG) { subval = subval.wrapping_sub(1); }
cpu.write_reg16(Reg16::HL, subval as u16);
if subval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if subval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if hlval & 0x0F < rval & 0x0F { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
match (hlval & 0b10000000 != 0,
rval & 0b10000000 != 0,
subval & 0b10000000 != 0) {
(true, false, false) | (false, true, true) => cpu.set_flag(PARITY_OVERFLOW_FLAG),
_ => cpu.clear_flag(PARITY_OVERFLOW_FLAG)
};
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if hlval < rval { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
info!("{:#06x}: SBC HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
struct SubR { r: Reg8 }
struct SubN ;
impl Instruction for SubN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let aval = cpu.read_reg8(Reg8::A) as i8;
let n = cpu.read_word(cpu.get_pc() + 1) as i8;
let subval = aval.wrapping_sub(n);
cpu.write_reg8(Reg8::A, subval as u8);
if subval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if subval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if aval & 0x0F < n & 0x0F { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
match (aval & 0b10000000 != 0,
n & 0b10000000 != 0,
subval & 0b10000000 != 0) {
(true, false, false) | (false, true, true) => cpu.set_flag(PARITY_OVERFLOW_FLAG),
_ => cpu.clear_flag(PARITY_OVERFLOW_FLAG)
};
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if aval < n { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
info!("{:#06x}: SUB {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for SubR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let aval = cpu.read_reg8(Reg8::A) as i8;
let r = cpu.read_reg8(self.r) as i8;
let subval = aval.wrapping_sub(r);
cpu.write_reg8(Reg8::A, subval as u8);
if subval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if subval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if aval & 0x0F < r & 0x0F { cpu.set_flag(HALF_CARRY_FLAG); } else { cpu.clear_flag(HALF_CARRY_FLAG); }
match (aval & 0b10000000 != 0,
r & 0b10000000 != 0,
subval & 0b10000000 != 0) {
(true, false, false) | (false, true, true) => cpu.set_flag(PARITY_OVERFLOW_FLAG),
_ => cpu.clear_flag(PARITY_OVERFLOW_FLAG)
};
cpu.clear_flag(ADD_SUBTRACT_FLAG);
if aval < r { cpu.set_flag(CARRY_FLAG); } else { cpu.clear_flag(CARRY_FLAG); }
info!("{:#06x}: SUB {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct XorR { r: Reg8 }
struct XorN ;
struct XorMemHl ;
impl Instruction for XorR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let xorval = cpu.read_reg8(self.r) ^ cpu.read_reg8(Reg8::A);
cpu.write_reg8(Reg8::A, xorval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if xorval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if xorval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if xorval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
info!("{:#06x}: XOR {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for XorN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let n = cpu.read_word(cpu.get_pc() + 1);
let xorval = cpu.read_reg8(Reg8::A) ^ n;
cpu.write_reg8(Reg8::A, xorval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if xorval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if xorval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if xorval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
info!("{:#06x}: XOR {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for XorMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
let xorval = cpu.read_reg8(Reg8::A) ^ memval;
cpu.write_reg8(Reg8::A, xorval);
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
cpu.clear_flag(CARRY_FLAG);
if xorval & 0b10000000 != 0 { cpu.set_flag(SIGN_FLAG); } else { cpu.clear_flag(SIGN_FLAG); }
if xorval == 0 { cpu.set_flag(ZERO_FLAG); } else { cpu.clear_flag(ZERO_FLAG); }
if xorval.count_ones() % 2 == 0 { cpu.set_flag(PARITY_OVERFLOW_FLAG); } else { cpu.clear_flag(PARITY_OVERFLOW_FLAG); }
info!("{:#06x}: XOR (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
pub const INSTR_TABLE_CB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&RlR{r:Reg8::B}, &RlR{r:Reg8::C}, &RlR{r:Reg8::D}, &RlR{r:Reg8::E}, &RlR{r:Reg8::H}, &RlR{r:Reg8::L}, &Unsupported, &RlR{r:Reg8::A},
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:0}, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:1}, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:2}, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:3}, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:4}, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:5}, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:6}, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:7}, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:0}, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:1}, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:2}, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:3}, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:4}, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:5}, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:6}, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:7}, &Unsupported
];
pub const INSTR_TABLE_DD: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &LdIxNn , &LdMemNnIx , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &LdIxMemNn , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdMemIxDN , &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &PopQq{r:Reg16qq::IX}, &Unsupported, &Unsupported, &Unsupported, &PushQq{r:Reg16qq::IX}, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_ED: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &OutPortCR{r:Reg8::B}, &SbcHlSs{r:Reg16::BC}, &LdMemNnDd{r:Reg16::BC}, &Unsupported, &Unsupported, &Im{mode:0} , &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &OutPortCR{r:Reg8::C}, &AdcHlSs{r:Reg16::BC}, &LdDdMemNn{r:Reg16::BC}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &OutPortCR{r:Reg8::D}, &SbcHlSs{r:Reg16::DE}, &LdMemNnDd{r:Reg16::DE}, &Unsupported, &Unsupported, &Im{mode:1} , &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &OutPortCR{r:Reg8::E}, &AdcHlSs{r:Reg16::DE}, &LdDdMemNn{r:Reg16::DE}, &Unsupported, &Unsupported, &Im{mode:2}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &OutPortCR{r:Reg8::H}, &SbcHlSs{r:Reg16::HL}, &LdMemNnDd{r:Reg16::HL}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &OutPortCR{r:Reg8::L}, &AdcHlSs{r:Reg16::HL}, &LdDdMemNn{r:Reg16::HL}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported , &SbcHlSs{r:Reg16::SP}, &LdMemNnDd{r:Reg16::SP}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &OutPortCR{r:Reg8::A}, &AdcHlSs{r:Reg16::SP}, &LdDdMemNn{r:Reg16::SP}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Ldir , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Lddr , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_FD: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &LdIyNn , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &DecIyD , &LdMemIyDN, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::B}, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::C}, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::D}, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::E}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::H}, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::L}, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported , &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::A}, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &AddAMemIyD , &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &CpMemIyD , &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &PopQq{r:Reg16qq::IY}, &Unsupported, &Unsupported, &Unsupported, &PushQq{r:Reg16qq::IY}, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_DDCB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_FDCB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:0}, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:1}, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:2}, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:3}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:4}, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:5}, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:6}, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:7}, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:0}, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:1}, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:2}, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:3}, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:4}, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:5}, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:6}, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:7}, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:0}, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:1}, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:2}, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:3}, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:4}, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:5}, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:6}, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:7}, &Unsupported
];
pub const INSTR_TABLE: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Nop , &LdDdNn{r:Reg16::BC} , &Unsupported, &IncSs{r:Reg16::BC}, &IncR{r:Reg8::B}, &DecR{r:Reg8::B}, &LdRN{r:Reg8::B}, &RlcA ,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&ExAfAfAlt , &AddHlSs{r:Reg16::BC}, &Unsupported, &DecSs{r:Reg16::BC}, &IncR{r:Reg8::C}, &DecR{r:Reg8::C}, &LdRN{r:Reg8::C}, &RrcA ,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Djnz , &LdDdNn{r:Reg16::DE} , &LdMemDeA , &IncSs{r:Reg16::DE}, &IncR{r:Reg8::D}, &DecR{r:Reg8::D}, &LdRN{r:Reg8::D}, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&JrE , &AddHlSs{r:Reg16::DE}, &LdAMemDe , &DecSs{r:Reg16::DE}, &IncR{r:Reg8::E}, &DecR{r:Reg8::E}, &LdRN{r:Reg8::E}, &RrA ,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&JrNz , &LdDdNn{r:Reg16::HL} , &LdMemNnHl , &IncSs{r:Reg16::HL}, &IncR{r:Reg8::H}, &DecR{r:Reg8::H}, &LdRN{r:Reg8::H}, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&JrZ , &AddHlSs{r:Reg16::HL}, &LdHlMemNn , &DecSs{r:Reg16::HL}, &IncR{r:Reg8::L}, &DecR{r:Reg8::L}, &LdRN{r:Reg8::L}, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&JrNcE , &LdDdNn{r:Reg16::SP} , &LdMemNnA , &IncSs{r:Reg16::SP}, &IncMemHl , &Unsupported , &LdMemHlN , &Scf ,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&JrCE , &AddHlSs{r:Reg16::SP}, &LdAMemNn , &DecSs{r:Reg16::SP}, &IncR{r:Reg8::A}, &DecR{r:Reg8::A}, &LdRN{r:Reg8::A}, &Ccf ,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */
&LdRR{rt:Reg8::B,rs:Reg8::B} , &LdRR{rt:Reg8::B,rs:Reg8::C} , &LdRR{rt:Reg8::B,rs:Reg8::D} , &LdRR{rt:Reg8::B,rs:Reg8::E},
/* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&LdRR{rt:Reg8::B,rs:Reg8::H} , &LdRR{rt:Reg8::B,rs:Reg8::L} , &LdRMemHl{r:Reg8::B} , &LdRR{rt:Reg8::B,rs:Reg8::A},
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */
&LdRR{rt:Reg8::C,rs:Reg8::B} , &LdRR{rt:Reg8::C,rs:Reg8::C} , &LdRR{rt:Reg8::C,rs:Reg8::D} , &LdRR{rt:Reg8::C,rs:Reg8::E},
/* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&LdRR{rt:Reg8::C,rs:Reg8::H} , &LdRR{rt:Reg8::C,rs:Reg8::L} , &LdRMemHl{r:Reg8::C} , &LdRR{rt:Reg8::C,rs:Reg8::A},
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */
&LdRR{rt:Reg8::D,rs:Reg8::B} , &LdRR{rt:Reg8::D,rs:Reg8::C} , &LdRR{rt:Reg8::D,rs:Reg8::D} , &LdRR{rt:Reg8::D,rs:Reg8::E},
/* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&LdRR{rt:Reg8::D,rs:Reg8::H} , &LdRR{rt:Reg8::D,rs:Reg8::L} , &LdRMemHl{r:Reg8::D} , &LdRR{rt:Reg8::D,rs:Reg8::A},
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */
&LdRR{rt:Reg8::E,rs:Reg8::B} , &LdRR{rt:Reg8::E,rs:Reg8::C} , &LdRR{rt:Reg8::E,rs:Reg8::D} , &LdRR{rt:Reg8::E,rs:Reg8::E},
/* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&LdRR{rt:Reg8::E,rs:Reg8::H} , &LdRR{rt:Reg8::E,rs:Reg8::L} , &LdRMemHl{r:Reg8::E} , &LdRR{rt:Reg8::E,rs:Reg8::A},
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */
&LdRR{rt:Reg8::H,rs:Reg8::B} , &LdRR{rt:Reg8::H,rs:Reg8::C} , &LdRR{rt:Reg8::H,rs:Reg8::D} , &LdRR{rt:Reg8::H,rs:Reg8::E},
/* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&LdRR{rt:Reg8::H,rs:Reg8::H} , &LdRR{rt:Reg8::H,rs:Reg8::L} , &LdRMemHl{r:Reg8::H} , &LdRR{rt:Reg8::H,rs:Reg8::A},
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */
&LdRR{rt:Reg8::L,rs:Reg8::B} , &LdRR{rt:Reg8::L,rs:Reg8::C} , &LdRR{rt:Reg8::L,rs:Reg8::D} , &LdRR{rt:Reg8::L,rs:Reg8::E},
/* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&LdRR{rt:Reg8::L,rs:Reg8::H} , &LdRR{rt:Reg8::L,rs:Reg8::L} , &LdRMemHl{r:Reg8::L} , &LdRR{rt:Reg8::L,rs:Reg8::A},
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */
&LdMemHlR{r:Reg8::B} , &LdMemHlR{r:Reg8::C} , &LdMemHlR{r:Reg8::D} , &LdMemHlR{r:Reg8::E},
/* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&LdMemHlR{r:Reg8::H} , &LdMemHlR{r:Reg8::L} , &Unsupported , &LdMemHlR{r:Reg8::A},
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */
&LdRR{rt:Reg8::A,rs:Reg8::B} , &LdRR{rt:Reg8::A,rs:Reg8::C} , &LdRR{rt:Reg8::A,rs:Reg8::D} , &LdRR{rt:Reg8::A,rs:Reg8::E},
/* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&LdRR{rt:Reg8::A,rs:Reg8::H} , &LdRR{rt:Reg8::A,rs:Reg8::L} , &LdRMemHl{r:Reg8::A} , &LdRR{rt:Reg8::A,rs:Reg8::A},
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&AddAR{r:Reg8::B}, &AddAR{r:Reg8::C}, &AddAR{r:Reg8::D}, &AddAR{r:Reg8::E}, &AddAR{r:Reg8::H}, &AddAR{r:Reg8::L}, &Unsupported, &AddAR{r:Reg8::A},
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported, &Unsupported ,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&SubR{r:Reg8::B} , &SubR{r:Reg8::C} , &SubR{r:Reg8::D} , &SubR{r:Reg8::E} , &SubR{r:Reg8::H} , &SubR{r:Reg8::L} , &Unsupported, &SubR{r:Reg8::A} ,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&SbcR{r:Reg8::B} , &SbcR{r:Reg8::C} , &SbcR{r:Reg8::D} , &SbcR{r:Reg8::E} , &SbcR{r:Reg8::H} , &SbcR{r:Reg8::L} , &Unsupported, &SbcR{r:Reg8::A} ,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&AndR{r:Reg8::B} , &AndR{r:Reg8::C} , &AndR{r:Reg8::D} , &AndR{r:Reg8::E} , &AndR{r:Reg8::H} , &AndR{r:Reg8::L} , &Unsupported, &AndR{r:Reg8::A} ,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&XorR{r:Reg8::B} , &XorR{r:Reg8::C} , &XorR{r:Reg8::D} , &XorR{r:Reg8::E} , &XorR{r:Reg8::H} , &XorR{r:Reg8::L} , &XorMemHl , &XorR{r:Reg8::A} ,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&OrR{r:Reg8::B} , &OrR{r:Reg8::C} , &OrR{r:Reg8::D} , &OrR{r:Reg8::E} , &OrR{r:Reg8::H} , &OrR{r:Reg8::L} , &OrMemHl , &OrR{r:Reg8::A} ,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&CpR{r:Reg8::B} , &CpR{r:Reg8::C} , &CpR{r:Reg8::D} , &CpR{r:Reg8::E} , &CpR{r:Reg8::H} , &CpR{r:Reg8::L} , &CpMemHl , &CpR{r:Reg8::A} ,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&RetCc{cond:FlagCond::NZ}, &PopQq{r:Reg16qq::BC}, &JpCcNn{cond:FlagCond::NZ}, &JpNn , &CallCcNn{cond:FlagCond::NZ}, &PushQq{r:Reg16qq::BC}, &AddAN , &Rst{addr:0x00},
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&RetCc{cond:FlagCond::Z} , &Ret , &JpCcNn{cond:FlagCond::Z} , &Unsupported, &CallCcNn{cond:FlagCond::Z} , &CallNn , &AdcAN , &Rst{addr:0x08},
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&RetCc{cond:FlagCond::NC}, &PopQq{r:Reg16qq::DE}, &JpCcNn{cond:FlagCond::NC}, &OutPortNA , &CallCcNn{cond:FlagCond::NC}, &PushQq{r:Reg16qq::DE}, &SubN , &Rst{addr:0x10},
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&RetCc{cond:FlagCond::C} , &Exx , &JpCcNn{cond:FlagCond::C} , &InAPortN , &CallCcNn{cond:FlagCond::C} , &Unsupported , &Unsupported, &Rst{addr:0x18},
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&RetCc{cond:FlagCond::PO}, &PopQq{r:Reg16qq::HL}, &JpCcNn{cond:FlagCond::PO}, &ExMemSpHl , &CallCcNn{cond:FlagCond::PO}, &PushQq{r:Reg16qq::HL}, &AndN , &Rst{addr:0x20},
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&RetCc{cond:FlagCond::PE}, &JpMemHl , &JpCcNn{cond:FlagCond::PE}, &ExDeHl , &CallCcNn{cond:FlagCond::PE}, &Unsupported , &XorN , &Rst{addr:0x28},
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&RetCc{cond:FlagCond::P} , &PopQq{r:Reg16qq::AF}, &JpCcNn{cond:FlagCond::P} , &Di , &CallCcNn{cond:FlagCond::P} , &PushQq{r:Reg16qq::AF}, &OrN , &Rst{addr:0x30},
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&RetCc{cond:FlagCond::M} , &LdSpHl , &JpCcNn{cond:FlagCond::M} , &Ei , &CallCcNn{cond:FlagCond::M} , &Unsupported , &CpN , &Rst{addr:0x38}
];
Finalize cleanup and refactoring
use super::cpu::*;
use num::FromPrimitive;
pub trait Instruction {
fn execute(&self, &mut Cpu);
}
struct Unsupported;
impl Instruction for Unsupported {
fn execute(&self, cpu: &mut Cpu) {
info!("{:?}", cpu);
panic!("Unsupported instruction {:#x} at address {:#06x}", cpu.read_word(cpu.get_pc()), cpu.get_pc());
}
}
struct Nop;
impl Instruction for Nop {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
info!("{:#06x}: NOP", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct AdcAN ;
struct AdcHlSs { r: Reg16 }
impl Instruction for AdcAN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = a.wrapping_add(n).wrapping_add(c);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x8000 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0FFF + n & 0x0FFF + c > 0x0FFF );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n ^ 0x8000) & (a ^ res ^ 0x8000) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u32 + n as u32 + c as u32 > 0xFFFF );
info!("{:#06x}: ADC A, {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AdcHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL);
let ss = cpu.read_reg16(self.r);
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = hl.wrapping_add(ss).wrapping_add(c);
cpu.write_reg16(Reg16::HL, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x8000 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , hl & 0x0FFF + ss & 0x0FFF + c > 0x0FFF );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (hl ^ ss ^ 0x8000) & (hl ^ res ^ 0x8000) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , hl as u32 + ss as u32 + c as u32 > 0xFFFF );
info!("{:#06x}: ADC HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
struct AddAN ;
struct AddAR { r: Reg8 }
struct AddHlSs { r: Reg16 }
struct AddAMemIyD ;
impl Instruction for AddAN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a.wrapping_add(n);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + n & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + n as u16 > 0xFF );
info!("{:#06x}: ADD A, {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AddAR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a.wrapping_add(r);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + r & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + r as u16 > 0xFF );
info!("{:#06x}: ADD A, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AddHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL);
let ss = cpu.read_reg16(self.r);
let res = hl.wrapping_add(ss);
cpu.write_reg16(Reg16::HL, res);
cpu.cond_flag ( HALF_CARRY_FLAG , hl & 0x0FFF + ss & 0x0FFF > 0x0FFF );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , hl as u32 + ss as u32 > 0xFFFF );
info!("{:#06x}: ADD HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
impl Instruction for AddAMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OIY));
let a = cpu.read_reg8(Reg8::A);
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
let res = a.wrapping_add(memval);
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F + memval & 0x0F > 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval ^ 0x80) & (a ^ res ^ 0x80) != 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as u16 + memval as u16 > 0xFF );
if d < 0 {
info!("{:#06x}: ADD A, (IY-{:#04X})", cpu.get_pc() - 1, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: ADD A, (IY+{:#04X})", cpu.get_pc() - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
struct AndR { r: Reg8 }
struct AndN ;
impl Instruction for AndR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a & r;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: AND {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for AndN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a & n;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: AND {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
struct BitBMemIyD { b: u8 }
impl Instruction for BitBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OIY));
let d = cpu.read_word(cpu.get_pc()) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
cpu.cond_flag ( ZERO_FLAG , memval & (1 << self.b) == 0 );
cpu.set_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
if d < 0 {
info!("{:#06x}: BIT {}, (IY-{:#04X})", cpu.get_pc() - 2, self.b, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: BIT {}, (IY+{:#04X})", cpu.get_pc() - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
struct CallNn ;
struct CallCcNn { cond: FlagCond }
impl Instruction for CallNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let curr_pc = cpu.get_pc();
let nn = (cpu.read_word(curr_pc + 1) as u16) |
((cpu.read_word(curr_pc + 2) as u16) << 8);
let curr_sp = cpu.read_reg16(Reg16::SP);
cpu.write_word(curr_sp - 1, (((curr_pc + 3) & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, ((curr_pc + 3) & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: CALL {:#06X}", curr_pc, nn);
cpu.set_pc(nn);
debug!("{}", cpu.output(OSP));
}
}
impl Instruction for CallCcNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OF));
let curr_pc = cpu.get_pc();
let nn = (cpu.read_word(curr_pc + 1) as u16) |
((cpu.read_word(curr_pc + 2) as u16) << 8);
let curr_sp = cpu.read_reg16(Reg16::SP);
let cc = cpu.check_cond(self.cond);
info!("{:#06x}: CALL {:?}, {:#06X}", curr_pc, self.cond, nn);
if cc {
cpu.write_word(curr_sp - 1, (((curr_pc + 3) & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, ((curr_pc + 3) & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
cpu.set_pc(nn);
} else {
cpu.inc_pc(3);
}
debug!("{}", cpu.output(OSP));
}
}
struct Ccf;
impl Instruction for Ccf {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let c = cpu.get_flag(CARRY_FLAG);
cpu.cond_flag ( HALF_CARRY_FLAG , c );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , !c );
info!("{:#06x}: CCF", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
struct CpR { r: Reg8 }
struct CpN ;
struct CpMemHl ;
struct CpMemIyD ;
impl Instruction for CpR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OA|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a - r;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < r & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r) & (r ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < r );
info!("{:#06x}: CP {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a - n;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < n & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n) & (n ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < n );
info!("{:#06x}: CP {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OH|OL));
let a = cpu.read_reg8(Reg8::A);
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
let res = a - memval;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < memval & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval) & (memval ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < memval );
info!("{:#06x}: CP (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
impl Instruction for CpMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OIY));
let a = cpu.read_reg8(Reg8::A);
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
let res = a - memval;
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < memval & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ memval) & (memval ^ res) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < memval );
if d < 0 {
info!("{:#06x}: CP (IY-{:#04X})", cpu.get_pc() - 1, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: CP (IY+{:#04X})", cpu.get_pc() - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
struct DecSs { r: Reg16 }
struct DecR { r: Reg8 }
struct DecIyD ;
impl Instruction for DecSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let r = cpu.read_reg16(self.r);
let res = r.wrapping_sub(1);
cpu.write_reg16(self.r, res);
info!("{:#06x}: DEC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for DecR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let r = cpu.read_reg8(self.r);
let res = r.wrapping_sub(1);
cpu.write_reg8(self.r, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , res & 0x0F == 0 );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res == 0x7F );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
info!("{:#06x}: DEC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for DecIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OIY));
let d = cpu.read_word(cpu.get_pc()) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let res = cpu.read_word(addr).wrapping_sub(1);
cpu.write_word(addr, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , res & 0x0F == 0 );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res == 0x7F );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
if d < 0 {
info!("{:#06x}: DEC (IY-{:#04X})", cpu.get_pc() - 1, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: DEC (IY+{:#04X})", cpu.get_pc() - 1, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OF));
}
}
struct Di;
impl Instruction for Di {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.clear_iff1();
cpu.clear_iff2();
info!("{:#06x}: DI", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct Djnz;
impl Instruction for Djnz {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB));
let b = cpu.read_reg8(Reg8::B);
cpu.write_reg8(Reg8::B, b.wrapping_sub(1));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: DJNZ {:#06X}", cpu.get_pc(), target);
if b != 0 {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(OB));
}
}
struct Ei;
impl Instruction for Ei {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.set_iff1();
cpu.set_iff2();
info!("{:#06x}: EI", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct ExAfAfAlt;
struct ExMemSpHl;
struct ExDeHl;
impl Instruction for ExAfAfAlt {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OA_ALT|OF_ALT));
let af = cpu.read_reg16qq(Reg16qq::AF);
let afalt = cpu.read_reg16qq(Reg16qq::AF_ALT);
cpu.write_reg16qq(Reg16qq::AF, afalt);
cpu.write_reg16qq(Reg16qq::AF_ALT, af);
info!("{:#06x}: EX AF, AF'", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF|OA_ALT|OF_ALT));
}
}
impl Instruction for ExMemSpHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OH|OL));
let sp = cpu.read_reg16(Reg16::SP);
let hl = cpu.read_reg16(Reg16::HL);
let (hlhigh, hllow) = (((hl & 0xFF00) >> 8) as u8,
((hl & 0x00FF) as u8));
let spval = (cpu.read_word(sp ) as u16) |
((cpu.read_word(sp + 1) as u16) << 8);
cpu.write_reg16(Reg16::HL, spval);
cpu.write_word(spval, hllow);
cpu.write_word(spval + 1, hlhigh);
info!("{:#06x}: EX (SP), HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP|OH|OL));
}
}
impl Instruction for ExDeHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OD|OE|OH|OL));
let de = cpu.read_reg16(Reg16::DE);
let hl = cpu.read_reg16(Reg16::HL);
cpu.write_reg16(Reg16::DE, hl);
cpu.write_reg16(Reg16::HL, de);
info!("{:#06x}: EX DE, HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OD|OE|OH|OL));
}
}
struct Exx;
impl Instruction for Exx {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OB_ALT|OC_ALT|OD_ALT|OE_ALT|OH_ALT|OL_ALT));
let bc = cpu.read_reg16(Reg16::BC);
let de = cpu.read_reg16(Reg16::DE);
let hl = cpu.read_reg16(Reg16::HL);
let bcalt = cpu.read_reg16(Reg16::BC_ALT);
let dealt = cpu.read_reg16(Reg16::DE_ALT);
let hlalt = cpu.read_reg16(Reg16::HL_ALT);
cpu.write_reg16(Reg16::BC, bcalt);
cpu.write_reg16(Reg16::DE, dealt);
cpu.write_reg16(Reg16::HL, hlalt);
cpu.write_reg16(Reg16::BC_ALT, bc);
cpu.write_reg16(Reg16::DE_ALT, de);
cpu.write_reg16(Reg16::HL_ALT, hl);
info!("{:#06x}: EXX", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OB_ALT|OC_ALT|OD_ALT|OE_ALT|OH_ALT|OL_ALT));
}
}
struct Im { mode: u8 }
impl Instruction for Im {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
cpu.set_im(self.mode);
info!("{:#06x}: IM {}", cpu.get_pc() - 1, self.mode);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct InAPortN;
impl Instruction for InAPortN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let n = cpu.read_word(cpu.get_pc() + 1);
let port = Port::from_u8(n).unwrap();
let portval = cpu.read_port(port);
cpu.write_reg8(Reg8::A, portval);
info!("{:#06x}: IN A, ({:#04X})", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA));
}
}
struct IncR { r: Reg8 }
struct IncSs { r: Reg16 }
struct IncMemHl;
impl Instruction for IncR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let r = cpu.read_reg8(self.r);
let res = r.wrapping_add(1);
cpu.write_reg8(self.r, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , res & 0x0F == 0 );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res == 0x80 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
info!("{:#06x}: INC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for IncSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let r = cpu.read_reg16(self.r);
let res = r.wrapping_add(1);
cpu.write_reg16(self.r, res);
info!("{:#06x}: INC {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for IncMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF));
let hl = cpu.read_reg16(Reg16::HL);
let res = cpu.read_word(hl).wrapping_add(1);
cpu.write_word(hl, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , res & 0x0F == 0 );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res == 0x80 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
info!("{:#06x}: INC (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
struct JpMemHl;
struct JpNn ;
struct JpCcNn { cond: FlagCond }
impl Instruction for JpMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
info!("{:#06x}: JP (HL)", cpu.get_pc());
cpu.set_pc(hl);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JpNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(ONONE));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
info!("{:#06x}: JP {:#06X}", cpu.get_pc(), nn);
cpu.set_pc(nn);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JpCcNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let cc = cpu.check_cond(self.cond);
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
info!("{:#06x}: JP {:?}, {:#06X}", cpu.get_pc(), self.cond, nn);
if cc {
cpu.set_pc(nn);
} else {
cpu.inc_pc(3);
}
debug!("{}", cpu.output(ONONE));
}
}
struct JrZ ;
struct JrNz;
struct JrNcE;
struct JrCE;
struct JrE ;
impl Instruction for JrZ {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: JR Z, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(ZERO_FLAG) {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrNz {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: JR NZ, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(ZERO_FLAG) {
cpu.inc_pc(2);
} else {
cpu.set_pc(target);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrNcE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: JR NC, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(CARRY_FLAG) {
cpu.inc_pc(2);
} else {
cpu.set_pc(target);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrCE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: JR C, {:#06X}", cpu.get_pc(), target);
if cpu.get_flag(CARRY_FLAG) {
cpu.set_pc(target);
} else {
cpu.inc_pc(2);
}
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for JrE {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
let offset = cpu.read_word(cpu.get_pc() + 1) as i8 + 2;
let target = (cpu.get_pc() as i16 + offset as i16) as u16;
info!("{:#06x}: JR {:#06X}", cpu.get_pc(), target);
cpu.set_pc(target);
debug!("{}", cpu.output(ONONE));
}
}
struct LdRN { r: Reg8 }
struct LdDdNn { r: Reg16 }
struct LdDdMemNn { r: Reg16 }
struct LdHlMemNn ;
struct LdMemHlN ;
struct LdRMemIyD { r: Reg8 }
struct LdMemIyDN ;
struct LdSpHl ;
struct LdIxNn ;
struct LdIxMemNn ;
struct LdMemNnIx ;
struct LdMemIxDN ;
struct LdRR { rt: Reg8, rs: Reg8 }
struct LdMemNnDd { r: Reg16 }
struct LdMemHlR { r: Reg8 }
struct LdMemNnA ;
struct LdRMemHl { r: Reg8 }
struct LdMemNnHl ;
struct LdAMemNn ;
struct LdAMemDe ;
struct LdMemDeA ;
struct LdIyNn ;
impl Instruction for LdRN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let n = cpu.read_word(cpu.get_pc() + 1);
cpu.write_reg8(self.r, n);
info!("{:#06x}: LD {:?}, {:#04X}", cpu.get_pc(), self.r, n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdDdNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_reg16(self.r, nn);
info!("{:#06x}: LD {:?}, {:#06X}", cpu.get_pc(), self.r, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdDdMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.write_reg16(self.r, nnmemval);
info!("{:#06x}: LD {:?}, ({:#06X})", cpu.get_pc(), self.r, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdHlMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.write_reg16(Reg16::HL, nnmemval);
info!("{:#06x}: LD HL, ({:#06X})", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OH|OL));
}
}
impl Instruction for LdMemHlN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
let n = cpu.read_word(cpu.get_pc() + 1);
cpu.write_word(hl, n);
info!("{:#06x}: LD (HL), {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY|OutputRegisters::from(self.r)));
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
cpu.write_reg8(self.r, memval);
if d < 0 {
info!("{:#06x}: LD {:?}, (IY-{:#04X})", cpu.get_pc() - 1, self.r, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: LD {:?}, (IY+{:#04X})", cpu.get_pc() - 1, self.r, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdMemIyDN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let n = cpu.read_word(cpu.get_pc() + 2);
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
cpu.write_word(addr, n);
if d < 0 {
info!("{:#06x}: LD (IY-{:#04X}), {:#04X}", cpu.get_pc() - 1, (d ^ 0xFF) + 1, n);
} else {
info!("{:#06x}: LD (IY+{:#04X}), {:#04X}", cpu.get_pc() - 1, d, n);
}
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdSpHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
cpu.write_reg16(Reg16::SP, hl);
info!("{:#06x}: LD SP, HL", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP));
}
}
impl Instruction for LdIxNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.set_ix(nn);
info!("{:#06x}: LD IX, {:#06X}", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OIX));
}
}
impl Instruction for LdIxMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let nnmemval = (cpu.read_word(nn ) as u16) |
((cpu.read_word(nn + 1) as u16) << 8);
cpu.set_ix(nnmemval);
info!("{:#06x}: LD IX, TODO {:#06X}", cpu.get_pc() - 1, nnmemval);
cpu.inc_pc(3);
debug!("{}", cpu.output(OIX));
}
}
impl Instruction for LdMemNnIx {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let (ixhigh, ixlow) = (((cpu.get_ix() & 0xFF00) >> 8) as u8,
((cpu.get_ix() & 0x00FF) as u8));
cpu.write_word(nn, ixlow);
cpu.write_word(nn + 1, ixhigh);
info!("{:#06x}: LD ({:#06X}), IX", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemIxDN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIX));
let d = cpu.read_word(cpu.get_pc() + 1) as i8;
let n = cpu.read_word(cpu.get_pc() + 2);
let addr = ((cpu.get_ix() as i16) + d as i16) as u16;
cpu.write_word(addr, n);
if d < 0 {
info!("{:#06x}: LD (IX-{:#04X}), {:#04X}", cpu.get_pc() - 1, (d ^ 0xFF) + 1, n);
} else {
info!("{:#06x}: LD (IX+{:#04X}), {:#04X}", cpu.get_pc() - 1, d, n);
}
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.rt) | OutputRegisters::from(self.rs)));
let rs = cpu.read_reg8(self.rs);
cpu.write_reg8(self.rt, rs);
info!("{:#06x}: LD {:?}, {:?}", cpu.get_pc(), self.rt, self.rs);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.rt) | OutputRegisters::from(self.rs)));
}
}
impl Instruction for LdMemNnDd {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
let r = cpu.read_reg16(self.r);
let (rhigh, rlow) = (((r & 0xFF00) >> 8) as u8,
((r & 0x00FF) as u8));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_word(nn, rlow);
cpu.write_word(nn + 1, rhigh);
info!("{:#06x}: LD ({:#06X}), {:?}", cpu.get_pc() - 1, nn, self.r);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemHlR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL);
let r = cpu.read_reg8(self.r);
cpu.write_word(hl, r);
info!("{:#06x}: LD (HL), {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdMemNnA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let a = cpu.read_reg8(Reg8::A);
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_word(nn, a);
info!("{:#06x}: LD ({:#06X}), A", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdRMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)|OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
cpu.write_reg8(self.r, memval);
info!("{:#06x}: LD {:?}, (HL)", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OutputRegisters::from(self.r)));
}
}
impl Instruction for LdMemNnHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
let (hlhigh, hllow) = (((hl & 0xFF00) >> 8) as u8,
((hl & 0x00FF) as u8));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.write_word(nn, hllow);
cpu.write_word(nn + 1, hlhigh);
info!("{:#06x}: LD ({:#06X}), HL", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdAMemNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
let memval = cpu.read_word(nn);
cpu.write_reg8(Reg8::A, memval);
info!("{:#06x}: LD A, ({:#06X})", cpu.get_pc(), nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OA));
}
}
impl Instruction for LdAMemDe {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OD|OE));
let de = cpu.read_reg16(Reg16::DE);
let memval = cpu.read_word(de);
cpu.write_reg8(Reg8::A, memval);
info!("{:#06x}: LD A, (DE)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA));
}
}
impl Instruction for LdMemDeA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OD|OE));
let de = cpu.read_reg16(Reg16::DE);
let a = cpu.read_reg8(Reg8::A);
cpu.write_word(de, a);
info!("{:#06x}: LD (DE), A", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for LdIyNn {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let nn = (cpu.read_word(cpu.get_pc() + 1) as u16) |
((cpu.read_word(cpu.get_pc() + 2) as u16) << 8);
cpu.set_iy(nn);
info!("{:#06x}: LD IY, {:#06X}", cpu.get_pc() - 1, nn);
cpu.inc_pc(3);
debug!("{}", cpu.output(OIY));
}
}
struct Lddr;
impl Instruction for Lddr {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
let mut counter = cpu.read_reg16(Reg16::BC);
while counter > 0 {
let deval = cpu.read_reg16(Reg16::DE);
let hlval = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hlval);
cpu.write_word(deval, memval);
cpu.write_reg16(Reg16::DE, deval.wrapping_sub(1));
cpu.write_reg16(Reg16::HL, hlval.wrapping_sub(1));
counter -= 1;
cpu.write_reg16(Reg16::BC, counter);
}
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(PARITY_OVERFLOW_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: LDDR", cpu.get_pc() - 1);
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
}
}
struct Ldir;
impl Instruction for Ldir {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
let mut counter = cpu.read_reg16(Reg16::BC);
while counter > 0 {
debug!(" Counter is: {}", counter);
let de = cpu.read_reg16(Reg16::DE);
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
cpu.write_word(de, memval);
cpu.write_reg16(Reg16::DE, de.wrapping_add(1));
cpu.write_reg16(Reg16::HL, hl.wrapping_add(1));
counter -= 1;
cpu.write_reg16(Reg16::BC, counter);
}
cpu.clear_flag(HALF_CARRY_FLAG);
cpu.clear_flag(PARITY_OVERFLOW_FLAG);
cpu.clear_flag(ADD_SUBTRACT_FLAG);
info!("{:#06x}: LDIR", cpu.get_pc() - 1);
cpu.inc_pc(1);
debug!("{}", cpu.output(OB|OC|OD|OE|OH|OL|OF));
}
}
struct OrR { r: Reg8 }
struct OrN ;
struct OrMemHl;
impl Instruction for OrR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a | r;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: OR {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for OrN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a | n;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: OR {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for OrMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OH|OL));
let a = cpu.read_reg8(Reg8::A);
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
let res = a | memval;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: OR (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct OutPortCR { r: Reg8 }
struct OutPortNA ;
impl Instruction for OutPortCR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OB|OC|OutputRegisters::from(self.r)));
let r = cpu.read_reg8(self.r);
let bc = cpu.read_reg16(Reg16::BC);
let port = Port::from_u16(bc).unwrap();
cpu.write_port(port, r);
info!("{:#06x}: OUT (C), {:?}", cpu.get_pc() - 1, self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for OutPortNA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let port = Port::from_u8(n).unwrap();
cpu.write_port(port, a);
info!("{:#06x}: OUT ({:#04X}), A", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
struct PopQq { r: Reg16qq }
impl Instruction for PopQq {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OutputRegisters::from(self.r)));
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16qq(self.r, ((high as u16) << 8 ) | low as u16);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
info!("{:#06x}: POP {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP|OutputRegisters::from(self.r)));
}
}
struct PushQq { r: Reg16qq }
impl Instruction for PushQq {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OutputRegisters::from(self.r)|OSP));
let curr_sp = cpu.read_reg16(Reg16::SP);
let r = cpu.read_reg16qq(self.r);
cpu.write_word(curr_sp - 1, ((r & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, (r & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: PUSH {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OSP));
}
}
struct ResBMemIyD { b: u8 }
struct ResBMemHl { b: u8 }
impl Instruction for ResBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let d = cpu.read_word(cpu.get_pc()) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
cpu.write_word(addr, memval & !(1 << self.b));
if d < 0 {
info!("{:#06x}: RES {}, (IY-{:#04X})", cpu.get_pc() - 2, self.b, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: RES {}, (IY+{:#04X})", cpu.get_pc() - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for ResBMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
cpu.write_word(hl, memval & !(1 << self.b));
info!("{:#06x}: RES {}, (HL)", cpu.get_pc() - 1, self.b);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct Ret ;
struct RetCc { cond: FlagCond }
impl Instruction for Ret {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
info!("{:#06x}: RET", cpu.get_pc());
cpu.set_pc(((high as u16) << 8 ) | low as u16);
debug!("{}", cpu.output(OSP));
}
}
impl Instruction for RetCc {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP|OF));
let cc = cpu.check_cond(self.cond);
info!("{:#06x}: RET {:?}", cpu.get_pc(), self.cond);
if cc {
let curr_sp = cpu.read_reg16(Reg16::SP);
let low = cpu.read_word(curr_sp);
let high = cpu.read_word(curr_sp + 1);
cpu.write_reg16(Reg16::SP, curr_sp + 2);
cpu.set_pc(((high as u16) << 8 ) | low as u16);
} else {
cpu.inc_pc(1);
}
debug!("{}", cpu.output(OSP));
}
}
struct RlR { r: Reg8 }
struct RlcA ;
impl Instruction for RlR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
let r = cpu.read_reg8(self.r);
let mut res = r.rotate_left(1);
if cpu.get_flag(CARRY_FLAG) { res |= 0x01; } else { res &= 0xFE; }
cpu.write_reg8(self.r, res);
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , r & 0x80 != 0 );
info!("{:#06x}: RL {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OF|OutputRegisters::from(self.r)));
}
}
impl Instruction for RlcA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let res = a.rotate_left(1);
cpu.write_reg8(Reg8::A, res);
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a & 0x80 != 0 );
info!("{:#06x}: RLCA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct RrA;
struct RrcA;
impl Instruction for RrA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let mut res = a.rotate_right(1);
if cpu.get_flag(CARRY_FLAG) { res |= 0x80; } else { res &= 0x7F; }
cpu.write_reg8(Reg8::A, res);
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a & 0x01 != 0 );
info!("{:#06x}: RRA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for RrcA {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let res = a.rotate_right(1);
cpu.write_reg8(Reg8::A, res);
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a & 0x01 != 0 );
info!("{:#06x}: RRCA", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct Rst { addr: u8 }
impl Instruction for Rst {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OSP));
let next_pc = cpu.get_pc() + 1;
let curr_sp = cpu.read_reg16(Reg16::SP);
cpu.write_word(curr_sp - 1, ((next_pc & 0xFF00) >> 8) as u8);
cpu.write_word(curr_sp - 2, (next_pc & 0x00FF) as u8);
cpu.write_reg16(Reg16::SP, curr_sp - 2);
info!("{:#06x}: RST {:#04X}", cpu.get_pc(), self.addr);
cpu.set_pc(self.addr as u16);
debug!("{}", cpu.output(OSP));
}
}
struct Scf;
impl Instruction for Scf {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OF));
cpu.set_flag ( CARRY_FLAG );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
info!("{:#06x}: SCF", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OF));
}
}
struct SetBMemIyD { b: u8 }
struct SetBMemHl { b: u8 }
impl Instruction for SetBMemIyD {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OIY));
let d = cpu.read_word(cpu.get_pc()) as i8;
let addr = ((cpu.get_iy() as i16) + d as i16) as u16;
let memval = cpu.read_word(addr);
cpu.write_word(addr, memval | (1 << self.b));
if d < 0 {
info!("{:#06x}: SET {}, (IY-{:#04X})", cpu.get_pc() - 2, self.b, (d ^ 0xFF) + 1);
} else {
info!("{:#06x}: SET {}, (IY+{:#04X})", cpu.get_pc() - 2, self.b, d);
}
cpu.inc_pc(2);
debug!("{}", cpu.output(ONONE));
}
}
impl Instruction for SetBMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL));
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
cpu.write_word(hl, memval | (1 << self.b));
info!("{:#06x}: SET {}, (HL)", cpu.get_pc() - 1, self.b);
cpu.inc_pc(1);
debug!("{}", cpu.output(ONONE));
}
}
struct SbcR { r: Reg8 }
struct SbcHlSs { r: Reg16 }
impl Instruction for SbcR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A) as i8;
let r = cpu.read_reg8(self.r) as i8;
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = a.wrapping_sub(r).wrapping_sub(c);
cpu.write_reg8(Reg8::A, res as u8);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < r & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r ^ 0x8000) & (a ^ res ^ 0x80) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a as i32 - r as i32 - c as i32 > 0xFFFF );
info!("{:#06x}: SBC A, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for SbcHlSs {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OH|OL|OF|OutputRegisters::from(self.r)));
let hl = cpu.read_reg16(Reg16::HL) as i16;
let r = cpu.read_reg16(self.r) as i16;
let c = if cpu.get_flag(CARRY_FLAG) { 1 } else { 0 };
let res = hl.wrapping_sub(r).wrapping_sub(c);
cpu.write_reg16(Reg16::HL, res as u16);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , hl & 0x0F < r & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (hl ^ r ^ 0x8000) & (hl ^ res ^ 0x80) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , hl as i32 - r as i32 - c as i32 > 0xFFFF );
info!("{:#06x}: SBC HL, {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OH|OL|OF));
}
}
struct SubN ;
struct SubR { r: Reg8 }
impl Instruction for SubN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A) as i8;
let n = cpu.read_word(cpu.get_pc() + 1) as i8;
let res = a.wrapping_sub(n);
cpu.write_reg8(Reg8::A, res as u8);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < n & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ n ^ 0x8000) & (a ^ res ^ 0x80) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < n );
info!("{:#06x}: SUB {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for SubR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A) as i8;
let r = cpu.read_reg8(self.r) as i8;
let res = a.wrapping_sub(r);
cpu.write_reg8(Reg8::A, res as u8);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.cond_flag ( HALF_CARRY_FLAG , a & 0x0F < r & 0x0F );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (a ^ r ^ 0x8000) & (a ^ res ^ 0x80) != 0 );
cpu.set_flag ( ADD_SUBTRACT_FLAG );
cpu.cond_flag ( CARRY_FLAG , a < r );
info!("{:#06x}: SUB {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
struct XorR { r: Reg8 }
struct XorN ;
struct XorMemHl ;
impl Instruction for XorR {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF|OutputRegisters::from(self.r)));
let a = cpu.read_reg8(Reg8::A);
let r = cpu.read_reg8(self.r);
let res = a ^ r;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: XOR {:?}", cpu.get_pc(), self.r);
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for XorN {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let n = cpu.read_word(cpu.get_pc() + 1);
let res = a ^ n;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: XOR {:#04X}", cpu.get_pc(), n);
cpu.inc_pc(2);
debug!("{}", cpu.output(OA|OF));
}
}
impl Instruction for XorMemHl {
fn execute(&self, cpu: &mut Cpu) {
debug!("{}", cpu.output(OA|OF));
let a = cpu.read_reg8(Reg8::A);
let hl = cpu.read_reg16(Reg16::HL);
let memval = cpu.read_word(hl);
let res = a ^ memval;
cpu.write_reg8(Reg8::A, res);
cpu.cond_flag ( SIGN_FLAG , res & 0x80 != 0 );
cpu.cond_flag ( ZERO_FLAG , res == 0 );
cpu.clear_flag ( HALF_CARRY_FLAG );
cpu.cond_flag ( PARITY_OVERFLOW_FLAG , res.count_ones() % 2 == 0 );
cpu.clear_flag ( ADD_SUBTRACT_FLAG );
cpu.clear_flag ( CARRY_FLAG );
info!("{:#06x}: XOR (HL)", cpu.get_pc());
cpu.inc_pc(1);
debug!("{}", cpu.output(OA|OF));
}
}
pub const INSTR_TABLE_CB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&RlR{r:Reg8::B}, &RlR{r:Reg8::C}, &RlR{r:Reg8::D}, &RlR{r:Reg8::E}, &RlR{r:Reg8::H}, &RlR{r:Reg8::L}, &Unsupported, &RlR{r:Reg8::A},
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:0}, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:1}, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:2}, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:3}, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:4}, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:5}, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:6}, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemHl{b:7}, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:0}, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:1}, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:2}, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:3}, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:4}, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:5}, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:6}, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemHl{b:7}, &Unsupported
];
pub const INSTR_TABLE_DD: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &LdIxNn , &LdMemNnIx , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &LdIxMemNn , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdMemIxDN , &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &PopQq{r:Reg16qq::IX}, &Unsupported, &Unsupported, &Unsupported, &PushQq{r:Reg16qq::IX}, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_ED: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &OutPortCR{r:Reg8::B}, &SbcHlSs{r:Reg16::BC}, &LdMemNnDd{r:Reg16::BC}, &Unsupported, &Unsupported, &Im{mode:0} , &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &OutPortCR{r:Reg8::C}, &AdcHlSs{r:Reg16::BC}, &LdDdMemNn{r:Reg16::BC}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &OutPortCR{r:Reg8::D}, &SbcHlSs{r:Reg16::DE}, &LdMemNnDd{r:Reg16::DE}, &Unsupported, &Unsupported, &Im{mode:1} , &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &OutPortCR{r:Reg8::E}, &AdcHlSs{r:Reg16::DE}, &LdDdMemNn{r:Reg16::DE}, &Unsupported, &Unsupported, &Im{mode:2}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &OutPortCR{r:Reg8::H}, &SbcHlSs{r:Reg16::HL}, &LdMemNnDd{r:Reg16::HL}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &OutPortCR{r:Reg8::L}, &AdcHlSs{r:Reg16::HL}, &LdDdMemNn{r:Reg16::HL}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported , &SbcHlSs{r:Reg16::SP}, &LdMemNnDd{r:Reg16::SP}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &OutPortCR{r:Reg8::A}, &AdcHlSs{r:Reg16::SP}, &LdDdMemNn{r:Reg16::SP}, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Ldir , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Lddr , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_FD: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &LdIyNn , &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &DecIyD , &LdMemIyDN, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::B}, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::C}, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::D}, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::E}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::H}, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::L}, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported , &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &LdRMemIyD{r:Reg8::A}, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &AddAMemIyD , &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &CpMemIyD , &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &PopQq{r:Reg16qq::IY}, &Unsupported, &Unsupported, &Unsupported, &PushQq{r:Reg16qq::IY}, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_DDCB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported
];
pub const INSTR_TABLE_FDCB: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */ /* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:0}, &Unsupported,
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */ /* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:1}, &Unsupported,
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */ /* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:2}, &Unsupported,
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */ /* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:3}, &Unsupported,
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */ /* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:4}, &Unsupported,
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */ /* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:5}, &Unsupported,
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */ /* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:6}, &Unsupported,
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */ /* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &BitBMemIyD{b:7}, &Unsupported,
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:0}, &Unsupported,
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:1}, &Unsupported,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:2}, &Unsupported,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:3}, &Unsupported,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:4}, &Unsupported,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:5}, &Unsupported,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:6}, &Unsupported,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &ResBMemIyD{b:7}, &Unsupported,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:0}, &Unsupported,
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:1}, &Unsupported,
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:2}, &Unsupported,
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:3}, &Unsupported,
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:4}, &Unsupported,
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:5}, &Unsupported,
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:6}, &Unsupported,
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &Unsupported, &SetBMemIyD{b:7}, &Unsupported
];
pub const INSTR_TABLE: [&'static Instruction; 256] = [
/* 0x00 */ /* 0x01 */ /* 0x02 */ /* 0x03 */ /* 0x04 */ /* 0x05 */ /* 0x06 */ /* 0x07 */
&Nop , &LdDdNn{r:Reg16::BC} , &Unsupported, &IncSs{r:Reg16::BC}, &IncR{r:Reg8::B}, &DecR{r:Reg8::B}, &LdRN{r:Reg8::B}, &RlcA ,
/* 0x08 */ /* 0x09 */ /* 0x0A */ /* 0x0B */ /* 0x0C */ /* 0x0D */ /* 0x0E */ /* 0x0F */
&ExAfAfAlt , &AddHlSs{r:Reg16::BC}, &Unsupported, &DecSs{r:Reg16::BC}, &IncR{r:Reg8::C}, &DecR{r:Reg8::C}, &LdRN{r:Reg8::C}, &RrcA ,
/* 0x10 */ /* 0x11 */ /* 0x12 */ /* 0x13 */ /* 0x14 */ /* 0x15 */ /* 0x16 */ /* 0x17 */
&Djnz , &LdDdNn{r:Reg16::DE} , &LdMemDeA , &IncSs{r:Reg16::DE}, &IncR{r:Reg8::D}, &DecR{r:Reg8::D}, &LdRN{r:Reg8::D}, &Unsupported,
/* 0x18 */ /* 0x19 */ /* 0x1A */ /* 0x1B */ /* 0x1C */ /* 0x1D */ /* 0x1E */ /* 0x1F */
&JrE , &AddHlSs{r:Reg16::DE}, &LdAMemDe , &DecSs{r:Reg16::DE}, &IncR{r:Reg8::E}, &DecR{r:Reg8::E}, &LdRN{r:Reg8::E}, &RrA ,
/* 0x20 */ /* 0x21 */ /* 0x22 */ /* 0x23 */ /* 0x24 */ /* 0x25 */ /* 0x26 */ /* 0x27 */
&JrNz , &LdDdNn{r:Reg16::HL} , &LdMemNnHl , &IncSs{r:Reg16::HL}, &IncR{r:Reg8::H}, &DecR{r:Reg8::H}, &LdRN{r:Reg8::H}, &Unsupported,
/* 0x28 */ /* 0x29 */ /* 0x2A */ /* 0x2B */ /* 0x2C */ /* 0x2D */ /* 0x2E */ /* 0x2F */
&JrZ , &AddHlSs{r:Reg16::HL}, &LdHlMemNn , &DecSs{r:Reg16::HL}, &IncR{r:Reg8::L}, &DecR{r:Reg8::L}, &LdRN{r:Reg8::L}, &Unsupported,
/* 0x30 */ /* 0x31 */ /* 0x32 */ /* 0x33 */ /* 0x34 */ /* 0x35 */ /* 0x36 */ /* 0x37 */
&JrNcE , &LdDdNn{r:Reg16::SP} , &LdMemNnA , &IncSs{r:Reg16::SP}, &IncMemHl , &Unsupported , &LdMemHlN , &Scf ,
/* 0x38 */ /* 0x39 */ /* 0x3A */ /* 0x3B */ /* 0x3C */ /* 0x3D */ /* 0x3E */ /* 0x3F */
&JrCE , &AddHlSs{r:Reg16::SP}, &LdAMemNn , &DecSs{r:Reg16::SP}, &IncR{r:Reg8::A}, &DecR{r:Reg8::A}, &LdRN{r:Reg8::A}, &Ccf ,
/* 0x40 */ /* 0x41 */ /* 0x42 */ /* 0x43 */
&LdRR{rt:Reg8::B,rs:Reg8::B} , &LdRR{rt:Reg8::B,rs:Reg8::C} , &LdRR{rt:Reg8::B,rs:Reg8::D} , &LdRR{rt:Reg8::B,rs:Reg8::E},
/* 0x44 */ /* 0x45 */ /* 0x46 */ /* 0x47 */
&LdRR{rt:Reg8::B,rs:Reg8::H} , &LdRR{rt:Reg8::B,rs:Reg8::L} , &LdRMemHl{r:Reg8::B} , &LdRR{rt:Reg8::B,rs:Reg8::A},
/* 0x48 */ /* 0x49 */ /* 0x4A */ /* 0x4B */
&LdRR{rt:Reg8::C,rs:Reg8::B} , &LdRR{rt:Reg8::C,rs:Reg8::C} , &LdRR{rt:Reg8::C,rs:Reg8::D} , &LdRR{rt:Reg8::C,rs:Reg8::E},
/* 0x4C */ /* 0x4D */ /* 0x4E */ /* 0x4F */
&LdRR{rt:Reg8::C,rs:Reg8::H} , &LdRR{rt:Reg8::C,rs:Reg8::L} , &LdRMemHl{r:Reg8::C} , &LdRR{rt:Reg8::C,rs:Reg8::A},
/* 0x50 */ /* 0x51 */ /* 0x52 */ /* 0x53 */
&LdRR{rt:Reg8::D,rs:Reg8::B} , &LdRR{rt:Reg8::D,rs:Reg8::C} , &LdRR{rt:Reg8::D,rs:Reg8::D} , &LdRR{rt:Reg8::D,rs:Reg8::E},
/* 0x54 */ /* 0x55 */ /* 0x56 */ /* 0x57 */
&LdRR{rt:Reg8::D,rs:Reg8::H} , &LdRR{rt:Reg8::D,rs:Reg8::L} , &LdRMemHl{r:Reg8::D} , &LdRR{rt:Reg8::D,rs:Reg8::A},
/* 0x58 */ /* 0x59 */ /* 0x5A */ /* 0x5B */
&LdRR{rt:Reg8::E,rs:Reg8::B} , &LdRR{rt:Reg8::E,rs:Reg8::C} , &LdRR{rt:Reg8::E,rs:Reg8::D} , &LdRR{rt:Reg8::E,rs:Reg8::E},
/* 0x5C */ /* 0x5D */ /* 0x5E */ /* 0x5F */
&LdRR{rt:Reg8::E,rs:Reg8::H} , &LdRR{rt:Reg8::E,rs:Reg8::L} , &LdRMemHl{r:Reg8::E} , &LdRR{rt:Reg8::E,rs:Reg8::A},
/* 0x60 */ /* 0x61 */ /* 0x62 */ /* 0x63 */
&LdRR{rt:Reg8::H,rs:Reg8::B} , &LdRR{rt:Reg8::H,rs:Reg8::C} , &LdRR{rt:Reg8::H,rs:Reg8::D} , &LdRR{rt:Reg8::H,rs:Reg8::E},
/* 0x64 */ /* 0x65 */ /* 0x66 */ /* 0x67 */
&LdRR{rt:Reg8::H,rs:Reg8::H} , &LdRR{rt:Reg8::H,rs:Reg8::L} , &LdRMemHl{r:Reg8::H} , &LdRR{rt:Reg8::H,rs:Reg8::A},
/* 0x68 */ /* 0x69 */ /* 0x6A */ /* 0x6B */
&LdRR{rt:Reg8::L,rs:Reg8::B} , &LdRR{rt:Reg8::L,rs:Reg8::C} , &LdRR{rt:Reg8::L,rs:Reg8::D} , &LdRR{rt:Reg8::L,rs:Reg8::E},
/* 0x6C */ /* 0x6D */ /* 0x6E */ /* 0x6F */
&LdRR{rt:Reg8::L,rs:Reg8::H} , &LdRR{rt:Reg8::L,rs:Reg8::L} , &LdRMemHl{r:Reg8::L} , &LdRR{rt:Reg8::L,rs:Reg8::A},
/* 0x70 */ /* 0x71 */ /* 0x72 */ /* 0x73 */
&LdMemHlR{r:Reg8::B} , &LdMemHlR{r:Reg8::C} , &LdMemHlR{r:Reg8::D} , &LdMemHlR{r:Reg8::E},
/* 0x74 */ /* 0x75 */ /* 0x76 */ /* 0x77 */
&LdMemHlR{r:Reg8::H} , &LdMemHlR{r:Reg8::L} , &Unsupported , &LdMemHlR{r:Reg8::A},
/* 0x78 */ /* 0x79 */ /* 0x7A */ /* 0x7B */
&LdRR{rt:Reg8::A,rs:Reg8::B} , &LdRR{rt:Reg8::A,rs:Reg8::C} , &LdRR{rt:Reg8::A,rs:Reg8::D} , &LdRR{rt:Reg8::A,rs:Reg8::E},
/* 0x7C */ /* 0x7D */ /* 0x7E */ /* 0x7F */
&LdRR{rt:Reg8::A,rs:Reg8::H} , &LdRR{rt:Reg8::A,rs:Reg8::L} , &LdRMemHl{r:Reg8::A} , &LdRR{rt:Reg8::A,rs:Reg8::A},
/* 0x80 */ /* 0x81 */ /* 0x82 */ /* 0x83 */ /* 0x84 */ /* 0x85 */ /* 0x86 */ /* 0x87 */
&AddAR{r:Reg8::B}, &AddAR{r:Reg8::C}, &AddAR{r:Reg8::D}, &AddAR{r:Reg8::E}, &AddAR{r:Reg8::H}, &AddAR{r:Reg8::L}, &Unsupported, &AddAR{r:Reg8::A},
/* 0x88 */ /* 0x89 */ /* 0x8A */ /* 0x8B */ /* 0x8C */ /* 0x8D */ /* 0x8E */ /* 0x8F */
&Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported , &Unsupported, &Unsupported ,
/* 0x90 */ /* 0x91 */ /* 0x92 */ /* 0x93 */ /* 0x94 */ /* 0x95 */ /* 0x96 */ /* 0x97 */
&SubR{r:Reg8::B} , &SubR{r:Reg8::C} , &SubR{r:Reg8::D} , &SubR{r:Reg8::E} , &SubR{r:Reg8::H} , &SubR{r:Reg8::L} , &Unsupported, &SubR{r:Reg8::A} ,
/* 0x98 */ /* 0x99 */ /* 0x9A */ /* 0x9B */ /* 0x9C */ /* 0x9D */ /* 0x9E */ /* 0x9F */
&SbcR{r:Reg8::B} , &SbcR{r:Reg8::C} , &SbcR{r:Reg8::D} , &SbcR{r:Reg8::E} , &SbcR{r:Reg8::H} , &SbcR{r:Reg8::L} , &Unsupported, &SbcR{r:Reg8::A} ,
/* 0xA0 */ /* 0xA1 */ /* 0xA2 */ /* 0xA3 */ /* 0xA4 */ /* 0xA5 */ /* 0xA6 */ /* 0xA7 */
&AndR{r:Reg8::B} , &AndR{r:Reg8::C} , &AndR{r:Reg8::D} , &AndR{r:Reg8::E} , &AndR{r:Reg8::H} , &AndR{r:Reg8::L} , &Unsupported, &AndR{r:Reg8::A} ,
/* 0xA8 */ /* 0xA9 */ /* 0xAA */ /* 0xAB */ /* 0xAC */ /* 0xAD */ /* 0xAE */ /* 0xAF */
&XorR{r:Reg8::B} , &XorR{r:Reg8::C} , &XorR{r:Reg8::D} , &XorR{r:Reg8::E} , &XorR{r:Reg8::H} , &XorR{r:Reg8::L} , &XorMemHl , &XorR{r:Reg8::A} ,
/* 0xB0 */ /* 0xB1 */ /* 0xB2 */ /* 0xB3 */ /* 0xB4 */ /* 0xB5 */ /* 0xB6 */ /* 0xB7 */
&OrR{r:Reg8::B} , &OrR{r:Reg8::C} , &OrR{r:Reg8::D} , &OrR{r:Reg8::E} , &OrR{r:Reg8::H} , &OrR{r:Reg8::L} , &OrMemHl , &OrR{r:Reg8::A} ,
/* 0xB8 */ /* 0xB9 */ /* 0xBA */ /* 0xBB */ /* 0xBC */ /* 0xBD */ /* 0xBE */ /* 0xBF */
&CpR{r:Reg8::B} , &CpR{r:Reg8::C} , &CpR{r:Reg8::D} , &CpR{r:Reg8::E} , &CpR{r:Reg8::H} , &CpR{r:Reg8::L} , &CpMemHl , &CpR{r:Reg8::A} ,
/* 0xC0 */ /* 0xC1 */ /* 0xC2 */ /* 0xC3 */ /* 0xC4 */ /* 0xC5 */ /* 0xC6 */ /* 0xC7 */
&RetCc{cond:FlagCond::NZ}, &PopQq{r:Reg16qq::BC}, &JpCcNn{cond:FlagCond::NZ}, &JpNn , &CallCcNn{cond:FlagCond::NZ}, &PushQq{r:Reg16qq::BC}, &AddAN , &Rst{addr:0x00},
/* 0xC8 */ /* 0xC9 */ /* 0xCA */ /* 0xCB */ /* 0xCC */ /* 0xCD */ /* 0xCE */ /* 0xCF */
&RetCc{cond:FlagCond::Z} , &Ret , &JpCcNn{cond:FlagCond::Z} , &Unsupported, &CallCcNn{cond:FlagCond::Z} , &CallNn , &AdcAN , &Rst{addr:0x08},
/* 0xD0 */ /* 0xD1 */ /* 0xD2 */ /* 0xD3 */ /* 0xD4 */ /* 0xD5 */ /* 0xD6 */ /* 0xD7 */
&RetCc{cond:FlagCond::NC}, &PopQq{r:Reg16qq::DE}, &JpCcNn{cond:FlagCond::NC}, &OutPortNA , &CallCcNn{cond:FlagCond::NC}, &PushQq{r:Reg16qq::DE}, &SubN , &Rst{addr:0x10},
/* 0xD8 */ /* 0xD9 */ /* 0xDA */ /* 0xDB */ /* 0xDC */ /* 0xDD */ /* 0xDE */ /* 0xDF */
&RetCc{cond:FlagCond::C} , &Exx , &JpCcNn{cond:FlagCond::C} , &InAPortN , &CallCcNn{cond:FlagCond::C} , &Unsupported , &Unsupported, &Rst{addr:0x18},
/* 0xE0 */ /* 0xE1 */ /* 0xE2 */ /* 0xE3 */ /* 0xE4 */ /* 0xE5 */ /* 0xE6 */ /* 0xE7 */
&RetCc{cond:FlagCond::PO}, &PopQq{r:Reg16qq::HL}, &JpCcNn{cond:FlagCond::PO}, &ExMemSpHl , &CallCcNn{cond:FlagCond::PO}, &PushQq{r:Reg16qq::HL}, &AndN , &Rst{addr:0x20},
/* 0xE8 */ /* 0xE9 */ /* 0xEA */ /* 0xEB */ /* 0xEC */ /* 0xED */ /* 0xEE */ /* 0xEF */
&RetCc{cond:FlagCond::PE}, &JpMemHl , &JpCcNn{cond:FlagCond::PE}, &ExDeHl , &CallCcNn{cond:FlagCond::PE}, &Unsupported , &XorN , &Rst{addr:0x28},
/* 0xF0 */ /* 0xF1 */ /* 0xF2 */ /* 0xF3 */ /* 0xF4 */ /* 0xF5 */ /* 0xF6 */ /* 0xF7 */
&RetCc{cond:FlagCond::P} , &PopQq{r:Reg16qq::AF}, &JpCcNn{cond:FlagCond::P} , &Di , &CallCcNn{cond:FlagCond::P} , &PushQq{r:Reg16qq::AF}, &OrN , &Rst{addr:0x30},
/* 0xF8 */ /* 0xF9 */ /* 0xFA */ /* 0xFB */ /* 0xFC */ /* 0xFD */ /* 0xFE */ /* 0xFF */
&RetCc{cond:FlagCond::M} , &LdSpHl , &JpCcNn{cond:FlagCond::M} , &Ei , &CallCcNn{cond:FlagCond::M} , &Unsupported , &CpN , &Rst{addr:0x38}
];
|
use rocket::{self, LoggingLevel};
use rocket_contrib::JSON;
use rocket::response::{content, Response, Responder};
use rocket::http::Status;
use rocket::config::{Environment, Config};
use adapters::json;
use entities::*;
use business::db::Repo;
use business::error::{Error, RepoError};
use infrastructure::error::AppError;
use serde_json::ser::to_string;
use business::sort::SortByDistanceTo;
use business::{usecase, filter, geo};
use business::filter::InBBox;
use business::duplicates::{self, DuplicateType};
use std::{env,result,io};
static MAX_INVISIBLE_RESULTS: usize = 5;
static DB_URL_KEY: &'static str = "OFDB_DATABASE_URL";
#[cfg(not(test))]
mod neo4j;
#[cfg(test)]
mod mockdb;
#[cfg(test)]
mod tests;
#[cfg(not(test))]
fn db() -> io::Result<neo4j::DB> { neo4j::db() }
#[cfg(test)]
fn db() -> io::Result<mockdb::DB> { mockdb::db() }
type Result<T> = result::Result<content::JSON<T>, AppError>;
fn extract_ids(s: &str) -> Vec<String> {
s.split(',')
.map(|x| x.to_owned())
.filter(|id| id != "")
.collect::<Vec<String>>()
}
#[test]
fn extract_ids_test() {
assert_eq!(extract_ids("abc"), vec!["abc"]);
assert_eq!(extract_ids("a,b,c"), vec!["a", "b", "c"]);
assert_eq!(extract_ids("").len(), 0);
assert_eq!(extract_ids("abc,,d"), vec!["abc", "d"]);
}
#[get("/entries")]
fn get_entries() -> Result<JSON<Vec<json::Entry>>> {
let entries: Vec<Entry> = db()?.conn().all()?;
let e = entries
.into_iter()
.map(json::Entry::from)
.collect::<Vec<json::Entry>>();
Ok(content::JSON(JSON(e)))
}
#[get("/entries/<id>")]
fn get_entry(id: &str) -> Result<String> {
let ids = extract_ids(id);
let entries: Vec<Entry> = db()?.conn().all()?;
let e = match ids.len() {
0 => {
to_string(&entries.into_iter()
.map(json::Entry::from)
.collect::<Vec<json::Entry>>())
}
1 => {
let e = entries.iter()
.find(|x| x.id == ids[0].clone())
.ok_or(RepoError::NotFound)?;
to_string(&json::Entry::from(e.clone()))
}
_ => {
to_string(&entries.into_iter()
.filter(|e| ids.iter().any(|id| e.id == id.clone()))
.map(json::Entry::from)
.collect::<Vec<json::Entry>>())
}
}?;
Ok(content::JSON(e))
}
#[get("/duplicates")]
fn get_duplicates() -> Result<JSON<Vec<(String, String, DuplicateType)>>> {
let entries: Vec<Entry> = db()?.conn().all()?;
let ids = duplicates::find_duplicates(&entries);
Ok(content::JSON(JSON(ids)))
}
#[post("/entries", format = "application/json", data = "<e>")]
fn post_entry(e: JSON<usecase::NewEntry>) -> Result<String> {
let id = usecase::create_new_entry(db()?.conn(), e.into_inner())?;
Ok(content::JSON(id))
}
#[put("/entries/<id>", format = "application/json", data = "<e>")]
fn put_entry(id: &str, e: JSON<usecase::UpdateEntry>) -> Result<String> {
usecase::update_entry(db()?.conn(), e.into_inner())?;
Ok(content::JSON(id.to_string()))
}
#[get("/categories")]
fn get_categories() -> Result<JSON<Vec<json::Category>>> {
let categories: Vec<Category> = db()?.conn().all()?;
Ok(content::JSON(JSON(categories
.into_iter()
.map(json::Category::from)
.collect::<Vec<json::Category>>())))
}
#[get("/categories/<id>")]
fn get_category(id: &str) -> Result<String> {
let ids = extract_ids(id);
let categories: Vec<Category> = db()?.conn().all()?;
let res = match ids.len() {
0 => {
to_string(&categories.into_iter()
.map(json::Category::from)
.collect::<Vec<json::Category>>())
}
1 => {
let id = ids[0].clone();
let e = categories.into_iter()
.find(|x| x.id == id)
.ok_or(RepoError::NotFound)?;
to_string(&json::Category::from(e))
}
_ => {
to_string(&categories.into_iter()
.filter(|e| ids.iter().any(|id| e.id == id.clone()))
.map(json::Category::from)
.collect::<Vec<json::Category>>())
}
}?;
Ok(content::JSON(res))
}
#[derive(FromForm)]
struct SearchQuery {
bbox: String,
categories: String,
text: Option<String>,
}
#[get("/search?<search>")]
fn get_search(search: SearchQuery) -> Result<JSON<json::SearchResult>> {
let entries: Vec<Entry> = db()?.conn().all()?;
let cat_ids = extract_ids(&search.categories);
let bbox = geo::extract_bbox(&search.bbox).map_err(Error::Parameter)
.map_err(AppError::Business)?;
let bbox_center = geo::center(&bbox[0], &bbox[1]);
let entries: Vec<_> = entries.into_iter()
.filter(|x| filter::entries_by_category_ids(&cat_ids)(&x))
.collect();
let mut entries = match search.text {
Some(txt) => {
entries.into_iter().filter(|x| filter::entries_by_search_text(&txt)(&x)).collect()
}
None => entries,
};
entries.sort_by_distance_to(&bbox_center);
let visible_results: Vec<_> =
entries.iter().filter(|x| x.in_bbox(&bbox)).map(|x| x.id.clone()).collect();
let invisible_results = entries.iter()
.filter(|e| !visible_results.iter().any(|v| *v == e.id))
.take(MAX_INVISIBLE_RESULTS)
.map(|x| x.id.clone())
.collect::<Vec<_>>();
Ok(content::JSON(JSON(json::SearchResult {
visible: visible_results,
invisible: invisible_results,
})))
}
#[get("/count/entries")]
fn get_count_entries() -> Result<String> {
let entries: Vec<Entry> = db()?.conn().all()?;
Ok(content::JSON(entries.len().to_string()))
}
#[get("/server/version")]
fn get_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
pub fn run(db_url: &str, port: u16, enable_cors: bool) {
env::set_var(DB_URL_KEY, db_url);
if enable_cors {
panic!("This feature is currently not available until\
\nhttps://github.com/SergioBenitez/Rocket/pull/141\nis merged :(");
}
let cfg = Config::build(Environment::Production)
.log_level(LoggingLevel::Normal)
.address("127.0.0.1")
.port(port)
.finalize()
.unwrap();
rocket::custom(cfg,true)
.mount("/",
routes![get_entries,
get_entry,
post_entry,
put_entry,
get_categories,
get_category,
get_search,
get_duplicates,
get_count_entries,
get_version])
.launch();
}
impl<'r> Responder<'r> for AppError {
fn respond(self) -> result::Result<Response<'r>, Status> {
Err(match self {
AppError::Business(ref err) => {
match *err {
Error::Parameter(_) => Status::BadRequest,
Error::Repo(ref err) => {
match *err {
RepoError::NotFound => Status::NotFound,
_ => Status::InternalServerError,
}
}
}
}
AppError::Adapter(_) => Status::BadRequest,
_ => Status::InternalServerError,
})
}
}
fix(web): always response with proper JSON
use rocket::{self, LoggingLevel};
use rocket_contrib::JSON;
use rocket::response::{Response, content, Responder};
use rocket::http::Status;
use rocket::config::{Environment, Config};
use adapters::json;
use entities::*;
use business::db::Repo;
use business::error::{Error, RepoError};
use infrastructure::error::AppError;
use serde_json::ser::to_string;
use business::sort::SortByDistanceTo;
use business::{usecase, filter, geo};
use business::filter::InBBox;
use business::duplicates::{self, DuplicateType};
use std::{env,result,io};
static MAX_INVISIBLE_RESULTS: usize = 5;
static DB_URL_KEY: &'static str = "OFDB_DATABASE_URL";
#[cfg(not(test))]
mod neo4j;
#[cfg(test)]
mod mockdb;
#[cfg(test)]
mod tests;
#[cfg(not(test))]
fn db() -> io::Result<neo4j::DB> { neo4j::db() }
#[cfg(test)]
fn db() -> io::Result<mockdb::DB> { mockdb::db() }
type Result<T> = result::Result<JSON<T>, AppError>;
fn extract_ids(s: &str) -> Vec<String> {
s.split(',')
.map(|x| x.to_owned())
.filter(|id| id != "")
.collect::<Vec<String>>()
}
#[test]
fn extract_ids_test() {
assert_eq!(extract_ids("abc"), vec!["abc"]);
assert_eq!(extract_ids("a,b,c"), vec!["a", "b", "c"]);
assert_eq!(extract_ids("").len(), 0);
assert_eq!(extract_ids("abc,,d"), vec!["abc", "d"]);
}
#[get("/entries")]
fn get_entries() -> Result<Vec<json::Entry>> {
let entries: Vec<Entry> = db()?.conn().all()?;
let e = entries
.into_iter()
.map(json::Entry::from)
.collect::<Vec<json::Entry>>();
Ok(JSON(e))
}
#[get("/entries/<id>")]
fn get_entry(id: &str) -> result::Result<content::JSON<String>,AppError> {
let ids = extract_ids(id);
let entries: Vec<Entry> = db()?.conn().all()?;
let e = match ids.len() {
0 => {
to_string(&entries.into_iter()
.map(json::Entry::from)
.collect::<Vec<json::Entry>>())
}
1 => {
let e = entries.iter()
.find(|x| x.id == ids[0].clone())
.ok_or(RepoError::NotFound)?;
to_string(&json::Entry::from(e.clone()))
}
_ => {
to_string(&entries.into_iter()
.filter(|e| ids.iter().any(|id| e.id == id.clone()))
.map(json::Entry::from)
.collect::<Vec<json::Entry>>())
}
}?;
Ok(content::JSON(e))
}
#[get("/duplicates")]
fn get_duplicates() -> Result<Vec<(String, String, DuplicateType)>> {
let entries: Vec<Entry> = db()?.conn().all()?;
let ids = duplicates::find_duplicates(&entries);
Ok(JSON(ids))
}
#[post("/entries", format = "application/json", data = "<e>")]
fn post_entry(e: JSON<usecase::NewEntry>) -> Result<String> {
let id = usecase::create_new_entry(db()?.conn(), e.into_inner())?;
Ok(JSON(id))
}
#[put("/entries/<id>", format = "application/json", data = "<e>")]
fn put_entry(id: &str, e: JSON<usecase::UpdateEntry>) -> Result<String> {
usecase::update_entry(db()?.conn(), e.into_inner())?;
Ok(JSON(id.to_string()))
}
#[get("/categories")]
fn get_categories() -> Result<Vec<json::Category>> {
let categories: Vec<Category> = db()?.conn().all()?;
Ok(JSON(categories
.into_iter()
.map(json::Category::from)
.collect::<Vec<json::Category>>()))
}
#[get("/categories/<id>")]
fn get_category(id: &str) -> Result<String> {
let ids = extract_ids(id);
let categories: Vec<Category> = db()?.conn().all()?;
let res = match ids.len() {
0 => {
to_string(&categories.into_iter()
.map(json::Category::from)
.collect::<Vec<json::Category>>())
}
1 => {
let id = ids[0].clone();
let e = categories.into_iter()
.find(|x| x.id == id)
.ok_or(RepoError::NotFound)?;
to_string(&json::Category::from(e))
}
_ => {
to_string(&categories.into_iter()
.filter(|e| ids.iter().any(|id| e.id == id.clone()))
.map(json::Category::from)
.collect::<Vec<json::Category>>())
}
}?;
Ok(JSON(res))
}
#[derive(FromForm)]
struct SearchQuery {
bbox: String,
categories: String,
text: Option<String>,
}
#[get("/search?<search>")]
fn get_search(search: SearchQuery) -> Result<json::SearchResult> {
let entries: Vec<Entry> = db()?.conn().all()?;
let cat_ids = extract_ids(&search.categories);
let bbox = geo::extract_bbox(&search.bbox).map_err(Error::Parameter)
.map_err(AppError::Business)?;
let bbox_center = geo::center(&bbox[0], &bbox[1]);
let entries: Vec<_> = entries.into_iter()
.filter(|x| filter::entries_by_category_ids(&cat_ids)(&x))
.collect();
let mut entries = match search.text {
Some(txt) => {
entries.into_iter().filter(|x| filter::entries_by_search_text(&txt)(&x)).collect()
}
None => entries,
};
entries.sort_by_distance_to(&bbox_center);
let visible_results: Vec<_> =
entries.iter().filter(|x| x.in_bbox(&bbox)).map(|x| x.id.clone()).collect();
let invisible_results = entries.iter()
.filter(|e| !visible_results.iter().any(|v| *v == e.id))
.take(MAX_INVISIBLE_RESULTS)
.map(|x| x.id.clone())
.collect::<Vec<_>>();
Ok(JSON(json::SearchResult {
visible: visible_results,
invisible: invisible_results,
}))
}
#[get("/count/entries")]
fn get_count_entries() -> Result<String> {
let entries: Vec<Entry> = db()?.conn().all()?;
Ok(JSON(entries.len().to_string()))
}
#[get("/server/version")]
fn get_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
pub fn run(db_url: &str, port: u16, enable_cors: bool) {
env::set_var(DB_URL_KEY, db_url);
if enable_cors {
panic!("This feature is currently not available until\
\nhttps://github.com/SergioBenitez/Rocket/pull/141\nis merged :(");
}
let cfg = Config::build(Environment::Production)
.log_level(LoggingLevel::Normal)
.address("127.0.0.1")
.port(port)
.finalize()
.unwrap();
rocket::custom(cfg,true)
.mount("/",
routes![get_entries,
get_entry,
post_entry,
put_entry,
get_categories,
get_category,
get_search,
get_duplicates,
get_count_entries,
get_version])
.launch();
}
impl<'r> Responder<'r> for AppError {
fn respond(self) -> result::Result<Response<'r>, Status> {
Err(match self {
AppError::Business(ref err) => {
match *err {
Error::Parameter(_) => Status::BadRequest,
Error::Repo(ref err) => {
match *err {
RepoError::NotFound => Status::NotFound,
_ => Status::InternalServerError,
}
}
}
}
AppError::Adapter(_) => Status::BadRequest,
_ => Status::InternalServerError,
})
}
}
|
use rustc::hir::def_id::DefId;
use rustc::middle::const_val::ConstVal;
use rustc::mir::repr as mir;
use rustc::traits::{self, Reveal};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::layout::Layout;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty, TyCtxt, BareFnTy};
use std::iter;
use std::rc::Rc;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::{ast, attr};
use error::{EvalError, EvalResult};
use memory::Pointer;
use super::{EvalContext, IntegerExt, StackPopCleanup};
impl<'a, 'tcx> EvalContext<'a, 'tcx> {
pub(super) fn goto_block(&mut self, target: mir::BasicBlock) {
self.frame_mut().block = target;
self.frame_mut().stmt = 0;
}
pub(super) fn eval_terminator(
&mut self,
terminator: &mir::Terminator<'tcx>,
) -> EvalResult<'tcx, ()> {
use rustc::mir::repr::TerminatorKind::*;
match terminator.kind {
Return => self.pop_stack_frame()?,
Goto { target } => self.goto_block(target),
If { ref cond, targets: (then_target, else_target) } => {
let cond_val = self.eval_operand_to_primval(cond)?
.expect_bool("TerminatorKind::If condition constant was not a bool");
self.goto_block(if cond_val { then_target } else { else_target });
}
SwitchInt { ref discr, ref values, ref targets, .. } => {
let discr_ptr = self.eval_lvalue(discr)?.to_ptr();
let discr_ty = self.lvalue_ty(discr);
let discr_size = self
.type_layout(discr_ty)
.size(&self.tcx.data_layout)
.bytes() as usize;
let discr_val = self.memory.read_uint(discr_ptr, discr_size)?;
if let ty::TyChar = discr_ty.sty {
if ::std::char::from_u32(discr_val as u32).is_none() {
return Err(EvalError::InvalidChar(discr_val as u64));
}
}
// Branch to the `otherwise` case by default, if no match is found.
let mut target_block = targets[targets.len() - 1];
for (index, const_val) in values.iter().enumerate() {
let val = match const_val {
&ConstVal::Integral(i) => i.to_u64_unchecked(),
_ => bug!("TerminatorKind::SwitchInt branch constant was not an integer"),
};
if discr_val == val {
target_block = targets[index];
break;
}
}
self.goto_block(target_block);
}
Switch { ref discr, ref targets, adt_def } => {
let adt_ptr = self.eval_lvalue(discr)?.to_ptr();
let adt_ty = self.lvalue_ty(discr);
let discr_val = self.read_discriminant_value(adt_ptr, adt_ty)?;
let matching = adt_def.variants.iter()
.position(|v| discr_val == v.disr_val.to_u64_unchecked());
match matching {
Some(i) => self.goto_block(targets[i]),
None => return Err(EvalError::InvalidDiscriminant),
}
}
Call { ref func, ref args, ref destination, .. } => {
let destination = match *destination {
Some((ref lv, target)) => Some((self.eval_lvalue(lv)?.to_ptr(), target)),
None => None,
};
let func_ty = self.operand_ty(func);
match func_ty.sty {
ty::TyFnPtr(bare_fn_ty) => {
let fn_ptr = self.eval_operand_to_primval(func)?
.expect_fn_ptr("TyFnPtr callee did not evaluate to PrimVal::FnPtr");
let (def_id, substs, fn_ty) = self.memory.get_fn(fn_ptr.alloc_id)?;
if fn_ty != bare_fn_ty {
return Err(EvalError::FunctionPointerTyMismatch(fn_ty, bare_fn_ty));
}
self.eval_fn_call(def_id, substs, bare_fn_ty, destination, args,
terminator.source_info.span)?
},
ty::TyFnDef(def_id, substs, fn_ty) => {
self.eval_fn_call(def_id, substs, fn_ty, destination, args,
terminator.source_info.span)?
}
_ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
}
}
Drop { ref location, target, .. } => {
let ptr = self.eval_lvalue(location)?.to_ptr();
let ty = self.lvalue_ty(location);
self.drop(ptr, ty)?;
self.goto_block(target);
}
Assert { ref cond, expected, ref msg, target, .. } => {
let cond_val = self.eval_operand_to_primval(cond)?
.expect_bool("TerminatorKind::Assert condition constant was not a bool");
if expected == cond_val {
self.goto_block(target);
} else {
return match *msg {
mir::AssertMessage::BoundsCheck { ref len, ref index } => {
let span = terminator.source_info.span;
let len = self.eval_operand_to_primval(len).expect("can't eval len")
.expect_uint("BoundsCheck len wasn't a uint");
let index = self.eval_operand_to_primval(index)
.expect("can't eval index")
.expect_uint("BoundsCheck index wasn't a uint");
Err(EvalError::ArrayIndexOutOfBounds(span, len, index))
},
mir::AssertMessage::Math(ref err) =>
Err(EvalError::Math(terminator.source_info.span, err.clone())),
}
}
},
DropAndReplace { .. } => unimplemented!(),
Resume => unimplemented!(),
Unreachable => unimplemented!(),
}
Ok(())
}
fn eval_fn_call(
&mut self,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
fn_ty: &'tcx BareFnTy,
destination: Option<(Pointer, mir::BasicBlock)>,
args: &[mir::Operand<'tcx>],
span: Span,
) -> EvalResult<'tcx, ()> {
use syntax::abi::Abi;
match fn_ty.abi {
Abi::RustIntrinsic => {
let ty = fn_ty.sig.0.output;
let layout = self.type_layout(ty);
let (ret, target) = destination.unwrap();
self.call_intrinsic(def_id, substs, args, ret, layout)?;
self.goto_block(target);
Ok(())
}
Abi::C => {
let ty = fn_ty.sig.0.output;
let size = self.type_size(ty);
let (ret, target) = destination.unwrap();
self.call_c_abi(def_id, args, ret, size)?;
self.goto_block(target);
Ok(())
}
Abi::Rust | Abi::RustCall => {
// TODO(solson): Adjust the first argument when calling a Fn or
// FnMut closure via FnOnce::call_once.
let mut arg_srcs = Vec::new();
for arg in args {
let src = self.eval_operand_to_ptr(arg)?;
let src_ty = self.operand_ty(arg);
arg_srcs.push((src, src_ty));
}
// Only trait methods can have a Self parameter.
let (resolved_def_id, resolved_substs) =
if let Some(trait_id) = self.tcx.trait_of_item(def_id) {
self.trait_method(trait_id, def_id, substs, &mut arg_srcs)?
} else {
(def_id, substs)
};
if fn_ty.abi == Abi::RustCall {
if let Some((last, last_ty)) = arg_srcs.pop() {
let last_layout = self.type_layout(last_ty);
match (&last_ty.sty, last_layout) {
(&ty::TyTuple(fields),
&Layout::Univariant { ref variant, .. }) => {
let offsets = iter::once(0)
.chain(variant.offset_after_field.iter()
.map(|s| s.bytes()));
for (offset, ty) in offsets.zip(fields) {
let src = last.offset(offset as isize);
arg_srcs.push((src, ty));
}
}
ty => bug!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
}
}
}
let mir = self.load_mir(resolved_def_id);
let (return_ptr, return_to_block) = match destination {
Some((ptr, block)) => (Some(ptr), StackPopCleanup::Goto(block)),
None => (None, StackPopCleanup::None),
};
self.push_stack_frame(resolved_def_id, span, mir, resolved_substs, return_ptr, return_to_block)?;
for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
let dest = self.frame().locals[i];
self.move_(src, dest, src_ty)?;
}
Ok(())
}
abi => Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
}
}
fn read_discriminant_value(&self, adt_ptr: Pointer, adt_ty: Ty<'tcx>) -> EvalResult<'tcx, u64> {
use rustc::ty::layout::Layout::*;
let adt_layout = self.type_layout(adt_ty);
let discr_val = match *adt_layout {
General { discr, .. } | CEnum { discr, .. } => {
let discr_size = discr.size().bytes();
self.memory.read_uint(adt_ptr, discr_size as usize)?
}
RawNullablePointer { nndiscr, .. } => {
self.read_nonnull_discriminant_value(adt_ptr, nndiscr)?
}
StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
let offset = self.nonnull_offset(adt_ty, nndiscr, discrfield)?;
let nonnull = adt_ptr.offset(offset.bytes() as isize);
self.read_nonnull_discriminant_value(nonnull, nndiscr)?
}
// The discriminant_value intrinsic returns 0 for non-sum types.
Array { .. } | FatPointer { .. } | Scalar { .. } | Univariant { .. } |
Vector { .. } | UntaggedUnion { .. } => 0,
};
Ok(discr_val)
}
fn read_nonnull_discriminant_value(&self, ptr: Pointer, nndiscr: u64) -> EvalResult<'tcx, u64> {
let not_null = match self.memory.read_usize(ptr) {
Ok(0) => false,
Ok(_) | Err(EvalError::ReadPointerAsBytes) => true,
Err(e) => return Err(e),
};
assert!(nndiscr == 0 || nndiscr == 1);
Ok(if not_null { nndiscr } else { 1 - nndiscr })
}
fn call_intrinsic(
&mut self,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
args: &[mir::Operand<'tcx>],
dest: Pointer,
dest_layout: &'tcx Layout,
) -> EvalResult<'tcx, ()> {
// TODO(solson): We can probably remove this _to_ptr easily.
let args_res: EvalResult<Vec<Pointer>> = args.iter()
.map(|arg| self.eval_operand_to_ptr(arg))
.collect();
let args_ptrs = args_res?;
let pointer_size = self.memory.pointer_size();
match &self.tcx.item_name(def_id).as_str()[..] {
"add_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Add, &args[0], &args[1], dest, dest_layout)?,
"sub_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Sub, &args[0], &args[1], dest, dest_layout)?,
"mul_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Mul, &args[0], &args[1], dest, dest_layout)?,
"assume" => {
if !self.memory.read_bool(args_ptrs[0])? {
return Err(EvalError::AssumptionNotHeld);
}
}
"copy_nonoverlapping" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let elem_align = self.type_align(elem_ty);
let src = self.memory.read_ptr(args_ptrs[0])?;
let dest = self.memory.read_ptr(args_ptrs[1])?;
let count = self.memory.read_isize(args_ptrs[2])?;
self.memory.copy(src, dest, count as usize * elem_size, elem_align)?;
}
"ctpop" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let num = self.memory.read_uint(args_ptrs[0], elem_size)?.count_ones();
self.memory.write_uint(dest, num.into(), elem_size)?;
}
"ctlz" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let num = self.memory.read_uint(args_ptrs[0], elem_size)?.leading_zeros();
self.memory.write_uint(dest, num.into(), elem_size)?;
}
"discriminant_value" => {
let ty = substs.type_at(0);
let adt_ptr = self.memory.read_ptr(args_ptrs[0])?;
let discr_val = self.read_discriminant_value(adt_ptr, ty)?;
self.memory.write_uint(dest, discr_val, 8)?;
}
"forget" => {}
"init" => self.memory.write_repeat(dest, 0, dest_layout.size(&self.tcx.data_layout).bytes() as usize)?,
"min_align_of" => {
let elem_ty = substs.type_at(0);
let elem_align = self.type_align(elem_ty);
self.memory.write_uint(dest, elem_align as u64, pointer_size)?;
}
"move_val_init" => {
let ty = substs.type_at(0);
let ptr = self.memory.read_ptr(args_ptrs[0])?;
self.move_(args_ptrs[1], ptr, ty)?;
}
"offset" => {
let pointee_ty = substs.type_at(0);
let pointee_size = self.type_size(pointee_ty) as isize;
let ptr_arg = args_ptrs[0];
let offset = self.memory.read_isize(args_ptrs[1])?;
match self.memory.read_ptr(ptr_arg) {
Ok(ptr) => {
let result_ptr = ptr.offset(offset as isize * pointee_size);
self.memory.write_ptr(dest, result_ptr)?;
}
Err(EvalError::ReadBytesAsPointer) => {
let addr = self.memory.read_isize(ptr_arg)?;
let result_addr = addr + offset * pointee_size as i64;
self.memory.write_isize(dest, result_addr)?;
}
Err(e) => return Err(e),
}
}
"overflowing_sub" => {
self.intrinsic_overflowing(mir::BinOp::Sub, &args[0], &args[1], dest)?;
}
"overflowing_mul" => {
self.intrinsic_overflowing(mir::BinOp::Mul, &args[0], &args[1], dest)?;
}
"overflowing_add" => {
self.intrinsic_overflowing(mir::BinOp::Add, &args[0], &args[1], dest)?;
}
"size_of" => {
let ty = substs.type_at(0);
let size = self.type_size(ty) as u64;
self.memory.write_uint(dest, size, pointer_size)?;
}
"size_of_val" => {
let ty = substs.type_at(0);
if self.type_is_sized(ty) {
let size = self.type_size(ty) as u64;
self.memory.write_uint(dest, size, pointer_size)?;
} else {
match ty.sty {
ty::TySlice(_) | ty::TyStr => {
let elem_ty = ty.sequence_element_type(self.tcx);
let elem_size = self.type_size(elem_ty) as u64;
let ptr_size = self.memory.pointer_size() as isize;
let n = self.memory.read_usize(args_ptrs[0].offset(ptr_size))?;
self.memory.write_uint(dest, n * elem_size, pointer_size)?;
}
_ => return Err(EvalError::Unimplemented(format!("unimplemented: size_of_val::<{:?}>", ty))),
}
}
}
"transmute" => {
let ty = substs.type_at(0);
self.move_(args_ptrs[0], dest, ty)?;
}
"uninit" => self.memory.mark_definedness(dest, dest_layout.size(&self.tcx.data_layout).bytes() as usize, false)?,
name => return Err(EvalError::Unimplemented(format!("unimplemented intrinsic: {}", name))),
}
// Since we pushed no stack frame, the main loop will act
// as if the call just completed and it's returning to the
// current frame.
Ok(())
}
fn call_c_abi(
&mut self,
def_id: DefId,
args: &[mir::Operand<'tcx>],
dest: Pointer,
dest_size: usize,
) -> EvalResult<'tcx, ()> {
let name = self.tcx.item_name(def_id);
let attrs = self.tcx.get_attrs(def_id);
let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
Some(ln) => ln.clone(),
None => name.as_str(),
};
// TODO(solson): We can probably remove this _to_ptr easily.
let args_res: EvalResult<Vec<Pointer>> = args.iter()
.map(|arg| self.eval_operand_to_ptr(arg))
.collect();
let args = args_res?;
if link_name.starts_with("pthread_") {
warn!("ignoring C ABI call: {}", link_name);
return Ok(());
}
match &link_name[..] {
"__rust_allocate" => {
let size = self.memory.read_usize(args[0])?;
let align = self.memory.read_usize(args[1])?;
let ptr = self.memory.allocate(size as usize, align as usize)?;
self.memory.write_ptr(dest, ptr)?;
}
"__rust_reallocate" => {
let ptr = self.memory.read_ptr(args[0])?;
let size = self.memory.read_usize(args[2])?;
let align = self.memory.read_usize(args[3])?;
let new_ptr = self.memory.reallocate(ptr, size as usize, align as usize)?;
self.memory.write_ptr(dest, new_ptr)?;
}
"memcmp" => {
let left = self.memory.read_ptr(args[0])?;
let right = self.memory.read_ptr(args[1])?;
let n = self.memory.read_usize(args[2])? as usize;
let result = {
let left_bytes = self.memory.read_bytes(left, n)?;
let right_bytes = self.memory.read_bytes(right, n)?;
use std::cmp::Ordering::*;
match left_bytes.cmp(right_bytes) {
Less => -1,
Equal => 0,
Greater => 1,
}
};
self.memory.write_int(dest, result, dest_size)?;
}
_ => {
return Err(EvalError::Unimplemented(format!("can't call C ABI function: {}", link_name)));
}
}
// Since we pushed no stack frame, the main loop will act
// as if the call just completed and it's returning to the
// current frame.
Ok(())
}
pub(super) fn fulfill_obligation(&self, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> {
// Do the initial selection for the obligation. This yields the shallow result we are
// looking for -- that is, what specific impl.
self.tcx.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
let mut selcx = traits::SelectionContext::new(&infcx);
let obligation = traits::Obligation::new(
traits::ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
trait_ref.to_poly_trait_predicate(),
);
let selection = selcx.select(&obligation).unwrap().unwrap();
// Currently, we use a fulfillment context to completely resolve all nested obligations.
// This is because they can inform the inference of the impl's type parameters.
let mut fulfill_cx = traits::FulfillmentContext::new();
let vtable = selection.map(|predicate| {
fulfill_cx.register_predicate_obligation(&infcx, predicate);
});
infcx.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &vtable)
})
}
/// Trait method, which has to be resolved to an impl method.
fn trait_method(
&self,
trait_id: DefId,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
args: &mut Vec<(Pointer, Ty<'tcx>)>,
) -> EvalResult<'tcx, (DefId, &'tcx Substs<'tcx>)> {
let trait_ref = ty::TraitRef::from_method(self.tcx, trait_id, substs);
let trait_ref = self.tcx.normalize_associated_type(&ty::Binder(trait_ref));
match self.fulfill_obligation(trait_ref) {
traits::VtableImpl(vtable_impl) => {
let impl_did = vtable_impl.impl_def_id;
let mname = self.tcx.item_name(def_id);
// Create a concatenated set of substitutions which includes those from the impl
// and those from the method:
let mth = get_impl_method(self.tcx, substs, impl_did, vtable_impl.substs, mname);
Ok((mth.method.def_id, mth.substs))
}
traits::VtableClosure(vtable_closure) =>
Ok((vtable_closure.closure_def_id, vtable_closure.substs.func_substs)),
traits::VtableFnPointer(vtable_fn_ptr) => {
if let ty::TyFnDef(did, ref substs, _) = vtable_fn_ptr.fn_ty.sty {
args.remove(0);
Ok((did, substs))
} else {
bug!("VtableFnPointer did not contain a concrete function: {:?}", vtable_fn_ptr)
}
}
traits::VtableObject(ref data) => {
let idx = self.tcx.get_vtable_index_of_object_method(data, def_id);
if let Some(&mut(first_arg, ref mut first_ty)) = args.get_mut(0) {
let (_, vtable) = self.get_fat_ptr(first_arg);
let vtable = self.memory.read_ptr(vtable)?;
let idx = idx + 3;
let offset = idx * self.memory.pointer_size();
let fn_ptr = self.memory.read_ptr(vtable.offset(offset as isize))?;
let (def_id, substs, ty) = self.memory.get_fn(fn_ptr.alloc_id)?;
// FIXME: skip_binder is wrong for HKL
*first_ty = ty.sig.skip_binder().inputs[0];
Ok((def_id, substs))
} else {
Err(EvalError::VtableForArgumentlessMethod)
}
},
vtable => bug!("resolved vtable bad vtable {:?} in trans", vtable),
}
}
pub(super) fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
self.tcx.type_needs_drop_given_env(ty, &self.tcx.empty_parameter_environment())
}
fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<'tcx, ()> {
if !self.type_needs_drop(ty) {
debug!("no need to drop {:?}", ty);
return Ok(());
}
trace!("-need to drop {:?}", ty);
// TODO(solson): Call user-defined Drop::drop impls.
match ty.sty {
ty::TyBox(_contents_ty) => {
let contents_ptr = self.memory.read_ptr(ptr)?;
// self.drop(contents_ptr, contents_ty)?;
trace!("-deallocating box");
self.memory.deallocate(contents_ptr)?;
}
// TODO(solson): Implement drop for other relevant types (e.g. aggregates).
_ => {}
}
Ok(())
}
}
#[derive(Debug)]
pub(super) struct ImplMethod<'tcx> {
pub(super) method: Rc<ty::Method<'tcx>>,
pub(super) substs: &'tcx Substs<'tcx>,
pub(super) is_provided: bool,
}
/// Locates the applicable definition of a method, given its name.
pub(super) fn get_impl_method<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
substs: &'tcx Substs<'tcx>,
impl_def_id: DefId,
impl_substs: &'tcx Substs<'tcx>,
name: ast::Name,
) -> ImplMethod<'tcx> {
assert!(!substs.needs_infer());
let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
let trait_def = tcx.lookup_trait_def(trait_def_id);
match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
Some(node_item) => {
let substs = tcx.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
let substs = substs.rebase_onto(tcx, trait_def_id, impl_substs);
let substs = traits::translate_substs(&infcx, impl_def_id,
substs, node_item.node);
tcx.lift(&substs).unwrap_or_else(|| {
bug!("trans::meth::get_impl_method: translate_substs \
returned {:?} which contains inference types/regions",
substs);
})
});
ImplMethod {
method: node_item.item,
substs: substs,
is_provided: node_item.node.is_from_trait(),
}
}
None => {
bug!("method {:?} not found in {:?}", name, impl_def_id)
}
}
}
prep for eddyb's find_method
use rustc::hir::def_id::DefId;
use rustc::middle::const_val::ConstVal;
use rustc::mir::repr as mir;
use rustc::traits::{self, Reveal};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::layout::Layout;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty, TyCtxt, BareFnTy};
use std::iter;
use std::rc::Rc;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::{ast, attr};
use error::{EvalError, EvalResult};
use memory::Pointer;
use super::{EvalContext, IntegerExt, StackPopCleanup};
impl<'a, 'tcx> EvalContext<'a, 'tcx> {
pub(super) fn goto_block(&mut self, target: mir::BasicBlock) {
self.frame_mut().block = target;
self.frame_mut().stmt = 0;
}
pub(super) fn eval_terminator(
&mut self,
terminator: &mir::Terminator<'tcx>,
) -> EvalResult<'tcx, ()> {
use rustc::mir::repr::TerminatorKind::*;
match terminator.kind {
Return => self.pop_stack_frame()?,
Goto { target } => self.goto_block(target),
If { ref cond, targets: (then_target, else_target) } => {
let cond_val = self.eval_operand_to_primval(cond)?
.expect_bool("TerminatorKind::If condition constant was not a bool");
self.goto_block(if cond_val { then_target } else { else_target });
}
SwitchInt { ref discr, ref values, ref targets, .. } => {
let discr_ptr = self.eval_lvalue(discr)?.to_ptr();
let discr_ty = self.lvalue_ty(discr);
let discr_size = self
.type_layout(discr_ty)
.size(&self.tcx.data_layout)
.bytes() as usize;
let discr_val = self.memory.read_uint(discr_ptr, discr_size)?;
if let ty::TyChar = discr_ty.sty {
if ::std::char::from_u32(discr_val as u32).is_none() {
return Err(EvalError::InvalidChar(discr_val as u64));
}
}
// Branch to the `otherwise` case by default, if no match is found.
let mut target_block = targets[targets.len() - 1];
for (index, const_val) in values.iter().enumerate() {
let val = match const_val {
&ConstVal::Integral(i) => i.to_u64_unchecked(),
_ => bug!("TerminatorKind::SwitchInt branch constant was not an integer"),
};
if discr_val == val {
target_block = targets[index];
break;
}
}
self.goto_block(target_block);
}
Switch { ref discr, ref targets, adt_def } => {
let adt_ptr = self.eval_lvalue(discr)?.to_ptr();
let adt_ty = self.lvalue_ty(discr);
let discr_val = self.read_discriminant_value(adt_ptr, adt_ty)?;
let matching = adt_def.variants.iter()
.position(|v| discr_val == v.disr_val.to_u64_unchecked());
match matching {
Some(i) => self.goto_block(targets[i]),
None => return Err(EvalError::InvalidDiscriminant),
}
}
Call { ref func, ref args, ref destination, .. } => {
let destination = match *destination {
Some((ref lv, target)) => Some((self.eval_lvalue(lv)?.to_ptr(), target)),
None => None,
};
let func_ty = self.operand_ty(func);
match func_ty.sty {
ty::TyFnPtr(bare_fn_ty) => {
let fn_ptr = self.eval_operand_to_primval(func)?
.expect_fn_ptr("TyFnPtr callee did not evaluate to PrimVal::FnPtr");
let (def_id, substs, fn_ty) = self.memory.get_fn(fn_ptr.alloc_id)?;
if fn_ty != bare_fn_ty {
return Err(EvalError::FunctionPointerTyMismatch(fn_ty, bare_fn_ty));
}
self.eval_fn_call(def_id, substs, bare_fn_ty, destination, args,
terminator.source_info.span)?
},
ty::TyFnDef(def_id, substs, fn_ty) => {
self.eval_fn_call(def_id, substs, fn_ty, destination, args,
terminator.source_info.span)?
}
_ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
}
}
Drop { ref location, target, .. } => {
let ptr = self.eval_lvalue(location)?.to_ptr();
let ty = self.lvalue_ty(location);
self.drop(ptr, ty)?;
self.goto_block(target);
}
Assert { ref cond, expected, ref msg, target, .. } => {
let cond_val = self.eval_operand_to_primval(cond)?
.expect_bool("TerminatorKind::Assert condition constant was not a bool");
if expected == cond_val {
self.goto_block(target);
} else {
return match *msg {
mir::AssertMessage::BoundsCheck { ref len, ref index } => {
let span = terminator.source_info.span;
let len = self.eval_operand_to_primval(len).expect("can't eval len")
.expect_uint("BoundsCheck len wasn't a uint");
let index = self.eval_operand_to_primval(index)
.expect("can't eval index")
.expect_uint("BoundsCheck index wasn't a uint");
Err(EvalError::ArrayIndexOutOfBounds(span, len, index))
},
mir::AssertMessage::Math(ref err) =>
Err(EvalError::Math(terminator.source_info.span, err.clone())),
}
}
},
DropAndReplace { .. } => unimplemented!(),
Resume => unimplemented!(),
Unreachable => unimplemented!(),
}
Ok(())
}
fn eval_fn_call(
&mut self,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
fn_ty: &'tcx BareFnTy,
destination: Option<(Pointer, mir::BasicBlock)>,
args: &[mir::Operand<'tcx>],
span: Span,
) -> EvalResult<'tcx, ()> {
use syntax::abi::Abi;
match fn_ty.abi {
Abi::RustIntrinsic => {
let ty = fn_ty.sig.0.output;
let layout = self.type_layout(ty);
let (ret, target) = destination.unwrap();
self.call_intrinsic(def_id, substs, args, ret, layout)?;
self.goto_block(target);
Ok(())
}
Abi::C => {
let ty = fn_ty.sig.0.output;
let size = self.type_size(ty);
let (ret, target) = destination.unwrap();
self.call_c_abi(def_id, args, ret, size)?;
self.goto_block(target);
Ok(())
}
Abi::Rust | Abi::RustCall => {
// TODO(solson): Adjust the first argument when calling a Fn or
// FnMut closure via FnOnce::call_once.
let mut arg_srcs = Vec::new();
for arg in args {
let src = self.eval_operand_to_ptr(arg)?;
let src_ty = self.operand_ty(arg);
arg_srcs.push((src, src_ty));
}
// Only trait methods can have a Self parameter.
let (resolved_def_id, resolved_substs) =
if let Some(trait_id) = self.tcx.trait_of_item(def_id) {
self.trait_method(trait_id, def_id, substs, &mut arg_srcs)?
} else {
(def_id, substs)
};
if fn_ty.abi == Abi::RustCall {
if let Some((last, last_ty)) = arg_srcs.pop() {
let last_layout = self.type_layout(last_ty);
match (&last_ty.sty, last_layout) {
(&ty::TyTuple(fields),
&Layout::Univariant { ref variant, .. }) => {
let offsets = iter::once(0)
.chain(variant.offset_after_field.iter()
.map(|s| s.bytes()));
for (offset, ty) in offsets.zip(fields) {
let src = last.offset(offset as isize);
arg_srcs.push((src, ty));
}
}
ty => bug!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
}
}
}
let mir = self.load_mir(resolved_def_id);
let (return_ptr, return_to_block) = match destination {
Some((ptr, block)) => (Some(ptr), StackPopCleanup::Goto(block)),
None => (None, StackPopCleanup::None),
};
self.push_stack_frame(resolved_def_id, span, mir, resolved_substs, return_ptr, return_to_block)?;
for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
let dest = self.frame().locals[i];
self.move_(src, dest, src_ty)?;
}
Ok(())
}
abi => Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
}
}
fn read_discriminant_value(&self, adt_ptr: Pointer, adt_ty: Ty<'tcx>) -> EvalResult<'tcx, u64> {
use rustc::ty::layout::Layout::*;
let adt_layout = self.type_layout(adt_ty);
let discr_val = match *adt_layout {
General { discr, .. } | CEnum { discr, .. } => {
let discr_size = discr.size().bytes();
self.memory.read_uint(adt_ptr, discr_size as usize)?
}
RawNullablePointer { nndiscr, .. } => {
self.read_nonnull_discriminant_value(adt_ptr, nndiscr)?
}
StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
let offset = self.nonnull_offset(adt_ty, nndiscr, discrfield)?;
let nonnull = adt_ptr.offset(offset.bytes() as isize);
self.read_nonnull_discriminant_value(nonnull, nndiscr)?
}
// The discriminant_value intrinsic returns 0 for non-sum types.
Array { .. } | FatPointer { .. } | Scalar { .. } | Univariant { .. } |
Vector { .. } | UntaggedUnion { .. } => 0,
};
Ok(discr_val)
}
fn read_nonnull_discriminant_value(&self, ptr: Pointer, nndiscr: u64) -> EvalResult<'tcx, u64> {
let not_null = match self.memory.read_usize(ptr) {
Ok(0) => false,
Ok(_) | Err(EvalError::ReadPointerAsBytes) => true,
Err(e) => return Err(e),
};
assert!(nndiscr == 0 || nndiscr == 1);
Ok(if not_null { nndiscr } else { 1 - nndiscr })
}
fn call_intrinsic(
&mut self,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
args: &[mir::Operand<'tcx>],
dest: Pointer,
dest_layout: &'tcx Layout,
) -> EvalResult<'tcx, ()> {
// TODO(solson): We can probably remove this _to_ptr easily.
let args_res: EvalResult<Vec<Pointer>> = args.iter()
.map(|arg| self.eval_operand_to_ptr(arg))
.collect();
let args_ptrs = args_res?;
let pointer_size = self.memory.pointer_size();
match &self.tcx.item_name(def_id).as_str()[..] {
"add_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Add, &args[0], &args[1], dest, dest_layout)?,
"sub_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Sub, &args[0], &args[1], dest, dest_layout)?,
"mul_with_overflow" => self.intrinsic_with_overflow(mir::BinOp::Mul, &args[0], &args[1], dest, dest_layout)?,
"assume" => {
if !self.memory.read_bool(args_ptrs[0])? {
return Err(EvalError::AssumptionNotHeld);
}
}
"copy_nonoverlapping" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let elem_align = self.type_align(elem_ty);
let src = self.memory.read_ptr(args_ptrs[0])?;
let dest = self.memory.read_ptr(args_ptrs[1])?;
let count = self.memory.read_isize(args_ptrs[2])?;
self.memory.copy(src, dest, count as usize * elem_size, elem_align)?;
}
"ctpop" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let num = self.memory.read_uint(args_ptrs[0], elem_size)?.count_ones();
self.memory.write_uint(dest, num.into(), elem_size)?;
}
"ctlz" => {
let elem_ty = substs.type_at(0);
let elem_size = self.type_size(elem_ty);
let num = self.memory.read_uint(args_ptrs[0], elem_size)?.leading_zeros();
self.memory.write_uint(dest, num.into(), elem_size)?;
}
"discriminant_value" => {
let ty = substs.type_at(0);
let adt_ptr = self.memory.read_ptr(args_ptrs[0])?;
let discr_val = self.read_discriminant_value(adt_ptr, ty)?;
self.memory.write_uint(dest, discr_val, 8)?;
}
"forget" => {}
"init" => self.memory.write_repeat(dest, 0, dest_layout.size(&self.tcx.data_layout).bytes() as usize)?,
"min_align_of" => {
let elem_ty = substs.type_at(0);
let elem_align = self.type_align(elem_ty);
self.memory.write_uint(dest, elem_align as u64, pointer_size)?;
}
"move_val_init" => {
let ty = substs.type_at(0);
let ptr = self.memory.read_ptr(args_ptrs[0])?;
self.move_(args_ptrs[1], ptr, ty)?;
}
"offset" => {
let pointee_ty = substs.type_at(0);
let pointee_size = self.type_size(pointee_ty) as isize;
let ptr_arg = args_ptrs[0];
let offset = self.memory.read_isize(args_ptrs[1])?;
match self.memory.read_ptr(ptr_arg) {
Ok(ptr) => {
let result_ptr = ptr.offset(offset as isize * pointee_size);
self.memory.write_ptr(dest, result_ptr)?;
}
Err(EvalError::ReadBytesAsPointer) => {
let addr = self.memory.read_isize(ptr_arg)?;
let result_addr = addr + offset * pointee_size as i64;
self.memory.write_isize(dest, result_addr)?;
}
Err(e) => return Err(e),
}
}
"overflowing_sub" => {
self.intrinsic_overflowing(mir::BinOp::Sub, &args[0], &args[1], dest)?;
}
"overflowing_mul" => {
self.intrinsic_overflowing(mir::BinOp::Mul, &args[0], &args[1], dest)?;
}
"overflowing_add" => {
self.intrinsic_overflowing(mir::BinOp::Add, &args[0], &args[1], dest)?;
}
"size_of" => {
let ty = substs.type_at(0);
let size = self.type_size(ty) as u64;
self.memory.write_uint(dest, size, pointer_size)?;
}
"size_of_val" => {
let ty = substs.type_at(0);
if self.type_is_sized(ty) {
let size = self.type_size(ty) as u64;
self.memory.write_uint(dest, size, pointer_size)?;
} else {
match ty.sty {
ty::TySlice(_) | ty::TyStr => {
let elem_ty = ty.sequence_element_type(self.tcx);
let elem_size = self.type_size(elem_ty) as u64;
let ptr_size = self.memory.pointer_size() as isize;
let n = self.memory.read_usize(args_ptrs[0].offset(ptr_size))?;
self.memory.write_uint(dest, n * elem_size, pointer_size)?;
}
_ => return Err(EvalError::Unimplemented(format!("unimplemented: size_of_val::<{:?}>", ty))),
}
}
}
"transmute" => {
let ty = substs.type_at(0);
self.move_(args_ptrs[0], dest, ty)?;
}
"uninit" => self.memory.mark_definedness(dest, dest_layout.size(&self.tcx.data_layout).bytes() as usize, false)?,
name => return Err(EvalError::Unimplemented(format!("unimplemented intrinsic: {}", name))),
}
// Since we pushed no stack frame, the main loop will act
// as if the call just completed and it's returning to the
// current frame.
Ok(())
}
fn call_c_abi(
&mut self,
def_id: DefId,
args: &[mir::Operand<'tcx>],
dest: Pointer,
dest_size: usize,
) -> EvalResult<'tcx, ()> {
let name = self.tcx.item_name(def_id);
let attrs = self.tcx.get_attrs(def_id);
let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
Some(ln) => ln.clone(),
None => name.as_str(),
};
// TODO(solson): We can probably remove this _to_ptr easily.
let args_res: EvalResult<Vec<Pointer>> = args.iter()
.map(|arg| self.eval_operand_to_ptr(arg))
.collect();
let args = args_res?;
if link_name.starts_with("pthread_") {
warn!("ignoring C ABI call: {}", link_name);
return Ok(());
}
match &link_name[..] {
"__rust_allocate" => {
let size = self.memory.read_usize(args[0])?;
let align = self.memory.read_usize(args[1])?;
let ptr = self.memory.allocate(size as usize, align as usize)?;
self.memory.write_ptr(dest, ptr)?;
}
"__rust_reallocate" => {
let ptr = self.memory.read_ptr(args[0])?;
let size = self.memory.read_usize(args[2])?;
let align = self.memory.read_usize(args[3])?;
let new_ptr = self.memory.reallocate(ptr, size as usize, align as usize)?;
self.memory.write_ptr(dest, new_ptr)?;
}
"memcmp" => {
let left = self.memory.read_ptr(args[0])?;
let right = self.memory.read_ptr(args[1])?;
let n = self.memory.read_usize(args[2])? as usize;
let result = {
let left_bytes = self.memory.read_bytes(left, n)?;
let right_bytes = self.memory.read_bytes(right, n)?;
use std::cmp::Ordering::*;
match left_bytes.cmp(right_bytes) {
Less => -1,
Equal => 0,
Greater => 1,
}
};
self.memory.write_int(dest, result, dest_size)?;
}
_ => {
return Err(EvalError::Unimplemented(format!("can't call C ABI function: {}", link_name)));
}
}
// Since we pushed no stack frame, the main loop will act
// as if the call just completed and it's returning to the
// current frame.
Ok(())
}
pub(super) fn fulfill_obligation(&self, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> {
// Do the initial selection for the obligation. This yields the shallow result we are
// looking for -- that is, what specific impl.
self.tcx.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
let mut selcx = traits::SelectionContext::new(&infcx);
let obligation = traits::Obligation::new(
traits::ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
trait_ref.to_poly_trait_predicate(),
);
let selection = selcx.select(&obligation).unwrap().unwrap();
// Currently, we use a fulfillment context to completely resolve all nested obligations.
// This is because they can inform the inference of the impl's type parameters.
let mut fulfill_cx = traits::FulfillmentContext::new();
let vtable = selection.map(|predicate| {
fulfill_cx.register_predicate_obligation(&infcx, predicate);
});
infcx.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &vtable)
})
}
/// Trait method, which has to be resolved to an impl method.
fn trait_method(
&self,
trait_id: DefId,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
args: &mut Vec<(Pointer, Ty<'tcx>)>,
) -> EvalResult<'tcx, (DefId, &'tcx Substs<'tcx>)> {
let trait_ref = ty::TraitRef::from_method(self.tcx, trait_id, substs);
let trait_ref = self.tcx.normalize_associated_type(&ty::Binder(trait_ref));
match self.fulfill_obligation(trait_ref) {
traits::VtableImpl(vtable_impl) => {
let impl_did = vtable_impl.impl_def_id;
let mname = self.tcx.item_name(def_id);
// Create a concatenated set of substitutions which includes those from the impl
// and those from the method:
let (did, substs) = find_method(self.tcx, substs, impl_did, vtable_impl.substs, mname);
Ok((did, substs))
}
traits::VtableClosure(vtable_closure) =>
Ok((vtable_closure.closure_def_id, vtable_closure.substs.func_substs)),
traits::VtableFnPointer(vtable_fn_ptr) => {
if let ty::TyFnDef(did, ref substs, _) = vtable_fn_ptr.fn_ty.sty {
args.remove(0);
Ok((did, substs))
} else {
bug!("VtableFnPointer did not contain a concrete function: {:?}", vtable_fn_ptr)
}
}
traits::VtableObject(ref data) => {
let idx = self.tcx.get_vtable_index_of_object_method(data, def_id);
if let Some(&mut(first_arg, ref mut first_ty)) = args.get_mut(0) {
let (_, vtable) = self.get_fat_ptr(first_arg);
let vtable = self.memory.read_ptr(vtable)?;
let idx = idx + 3;
let offset = idx * self.memory.pointer_size();
let fn_ptr = self.memory.read_ptr(vtable.offset(offset as isize))?;
let (def_id, substs, ty) = self.memory.get_fn(fn_ptr.alloc_id)?;
// FIXME: skip_binder is wrong for HKL
*first_ty = ty.sig.skip_binder().inputs[0];
Ok((def_id, substs))
} else {
Err(EvalError::VtableForArgumentlessMethod)
}
},
vtable => bug!("resolved vtable bad vtable {:?} in trans", vtable),
}
}
pub(super) fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
self.tcx.type_needs_drop_given_env(ty, &self.tcx.empty_parameter_environment())
}
fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<'tcx, ()> {
if !self.type_needs_drop(ty) {
debug!("no need to drop {:?}", ty);
return Ok(());
}
trace!("-need to drop {:?}", ty);
// TODO(solson): Call user-defined Drop::drop impls.
match ty.sty {
ty::TyBox(_contents_ty) => {
let contents_ptr = self.memory.read_ptr(ptr)?;
// self.drop(contents_ptr, contents_ty)?;
trace!("-deallocating box");
self.memory.deallocate(contents_ptr)?;
}
// TODO(solson): Implement drop for other relevant types (e.g. aggregates).
_ => {}
}
Ok(())
}
}
#[derive(Debug)]
pub(super) struct ImplMethod<'tcx> {
pub(super) method: Rc<ty::Method<'tcx>>,
pub(super) substs: &'tcx Substs<'tcx>,
pub(super) is_provided: bool,
}
/// Locates the applicable definition of a method, given its name.
pub(super) fn get_impl_method<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
substs: &'tcx Substs<'tcx>,
impl_def_id: DefId,
impl_substs: &'tcx Substs<'tcx>,
name: ast::Name,
) -> ImplMethod<'tcx> {
assert!(!substs.needs_infer());
let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
let trait_def = tcx.lookup_trait_def(trait_def_id);
match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
Some(node_item) => {
let substs = tcx.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
let substs = substs.rebase_onto(tcx, trait_def_id, impl_substs);
let substs = traits::translate_substs(&infcx, impl_def_id,
substs, node_item.node);
tcx.lift(&substs).unwrap_or_else(|| {
bug!("trans::meth::get_impl_method: translate_substs \
returned {:?} which contains inference types/regions",
substs);
})
});
ImplMethod {
method: node_item.item,
substs: substs,
is_provided: node_item.node.is_from_trait(),
}
}
None => {
bug!("method {:?} not found in {:?}", name, impl_def_id)
}
}
}
/// Locates the applicable definition of a method, given its name.
pub fn find_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
substs: &'tcx Substs<'tcx>,
impl_def_id: DefId,
impl_substs: &'tcx Substs<'tcx>,
name: ast::Name)
-> (DefId, &'tcx Substs<'tcx>)
{
assert!(!substs.needs_infer());
let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
let trait_def = tcx.lookup_trait_def(trait_def_id);
match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
Some(node_item) => {
let substs = tcx.infer_ctxt(None, None, Reveal::All).enter(|infcx| {
let substs = substs.rebase_onto(tcx, trait_def_id, impl_substs);
let substs = traits::translate_substs(&infcx, impl_def_id, substs, node_item.node);
tcx.lift(&substs).unwrap_or_else(|| {
bug!("find_method: translate_substs \
returned {:?} which contains inference types/regions",
substs);
})
});
(node_item.item.def_id, substs)
}
None => {
bug!("method {:?} not found in {:?}", name, impl_def_id)
}
}
}
|
use std::collections::HashMap;
use std::boxed::Box;
use std::io::{Read, Write};
use mio::{self, Token, EventLoop, EventSet, PollOpt, Sender};
use mio::tcp::{TcpListener, TcpStream};
use protobuf::RepeatedField;
use kvproto::kvrpcpb::{CmdGetResponse, CmdScanResponse, CmdPrewriteResponse, CmdCommitResponse,
CmdCleanupResponse, CmdRollbackThenGetResponse, CmdCommitThenGetResponse,
Request, Response, MessageType, Item, ResultType, ResultType_Type,
LockInfo, Operator};
use storage::{Storage, Key, Value, KvPair, KvContext, Mutation, MaybeLocked, MaybeComitted,
MaybeRolledback, Callback};
use storage::Result as StorageResult;
use storage::Error as StorageError;
use storage::EngineError;
use super::conn::Conn;
use super::{Result, ServerError};
// Token(1) instead of Token(0)
// See here: https://github.com/hjr3/mob/blob/multi-echo-blog-post/src/main.rs#L115
pub const SERVER_TOKEN: Token = Token(1);
const FIRST_CUSTOM_TOKEN: Token = Token(1024);
pub struct Server {
pub listener: TcpListener,
pub conns: HashMap<Token, Conn>,
pub token_counter: usize,
store: Storage,
}
impl Server {
pub fn new(listener: TcpListener, conns: HashMap<Token, Conn>, store: Storage) -> Server {
Server {
listener: listener,
conns: conns,
token_counter: FIRST_CUSTOM_TOKEN.as_usize(),
store: store,
}
}
pub fn handle_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_get_req() {
format_err!("Msg doesn't contain a CmdGetRequest");
}
let mut cmd_get_req = msg.take_cmd_get_req();
let mut key_address = cmd_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_get_done, sender, token, msg_id);
self.store
.async_get(ctx, Key::new(key), cmd_get_req.get_version(), cb)
.map_err(ServerError::Storage)
}
pub fn handle_scan(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_scan_req() {
format_err!("Msg doesn't contain a CmdScanRequest");
}
let mut cmd_scan_req = msg.take_cmd_scan_req();
let sender = event_loop.channel();
let mut start_key_addresss = cmd_scan_req.take_key_address();
let start_key = start_key_addresss.take_key();
let ctx = KvContext::new(start_key_addresss.get_region_id(),
start_key_addresss.take_peer());
debug!("start_key [{:?}]", start_key);
let cb = Server::make_cb::<Vec<StorageResult<KvPair>>>(Server::cmd_scan_done,
sender,
token,
msg_id);
self.store
.async_scan(ctx,
Key::new(start_key),
cmd_scan_req.get_limit() as usize,
cmd_scan_req.get_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_prewrite(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_prewrite_req() {
format_err!("Msg doesn't contain a CmdPrewriteRequest");
}
let mut cmd_prewrite_req = msg.take_cmd_prewrite_req();
let sender = event_loop.channel();
let mutations = cmd_prewrite_req.take_mutations()
.into_iter()
.map(|mut x| {
match x.get_op() {
Operator::OpPut => {
Mutation::Put((Key::new(x.take_key()),
x.take_value()))
}
Operator::OpDel => {
Mutation::Delete(Key::new(x.take_key()))
}
Operator::OpLock => {
Mutation::Lock(Key::new(x.take_key()))
}
}
})
.collect();
let ctx = {
let mut key_address = cmd_prewrite_req.take_key_address();
KvContext::new(key_address.get_region_id(), key_address.take_peer())
};
let cb = Server::make_cb::<Vec<StorageResult<()>>>(Server::cmd_prewrite_done,
sender,
token,
msg_id);
self.store
.async_prewrite(ctx,
mutations,
cmd_prewrite_req.get_primary_lock().to_vec(),
cmd_prewrite_req.get_start_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_commit(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_commit_req() {
format_err!("Msg doesn't contain a CmdCommitRequest");
}
let mut cmd_commit_req = msg.take_cmd_commit_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<()>(Server::cmd_commit_done, sender, token, msg_id);
let ctx = {
let mut first = cmd_commit_req.get_keys_address()[0].clone();
KvContext::new(first.get_region_id(), first.take_peer())
};
let keys = cmd_commit_req.take_keys_address()
.into_iter()
.map(|mut x| Key::new(x.take_key()))
.collect();
self.store
.async_commit(ctx,
keys,
cmd_commit_req.get_start_version(),
cmd_commit_req.get_commit_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_cleanup(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_cleanup_req() {
format_err!("Msg doesn't contain a CmdCleanupRequest");
}
let mut cmd_cleanup_req = msg.take_cmd_cleanup_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<()>(Server::cmd_cleanup_done, sender, token, msg_id);
let mut key_address = cmd_cleanup_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_cleanup(ctx, Key::new(key), cmd_cleanup_req.get_start_version(), cb)
.map_err(ServerError::Storage)
}
pub fn handle_commit_then_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_commit_get_req() {
format_err!("Msg doesn't contain a CmdCommitThenGetRequest");
}
let mut cmd_commit_get_req = msg.take_cmd_commit_get_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_commit_get_done,
sender,
token,
msg_id);
let mut key_address = cmd_commit_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_commit_then_get(ctx,
Key::new(key),
cmd_commit_get_req.get_lock_version(),
cmd_commit_get_req.get_commit_version(),
cmd_commit_get_req.get_get_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_rollback_then_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_rb_get_req() {
format_err!("Msg doesn't contain a CmdRollbackThenGetRequest");
}
let mut cmd_rollback_get_req = msg.take_cmd_rb_get_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_rollback_get_done,
sender,
token,
msg_id);
let mut key_address = cmd_rollback_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_rollback_then_get(ctx,
Key::new(key),
cmd_rollback_get_req.get_lock_version(),
cb)
.map_err(ServerError::Storage)
}
fn cmd_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_get_resp: CmdGetResponse = CmdGetResponse::new();
let mut res_type: ResultType = ResultType::new();
match r {
Ok(opt) => {
res_type.set_field_type(ResultType_Type::Ok);
match opt {
Some(val) => cmd_get_resp.set_value(val),
None => cmd_get_resp.set_value(Vec::new()),
}
}
Err(ref e) => {
if let StorageError::Engine(EngineError::Request(ref err)) = *e {
if err.has_not_leader() {
res_type.set_field_type(ResultType_Type::NotLeader);
res_type.set_leader_info(err.get_not_leader().to_owned());
} else {
error!("{:?}", err);
res_type.set_field_type(ResultType_Type::Other);
res_type.set_msg(format!("engine error: {:?}", err));
}
} else if r.is_locked() {
if let Some((_, primary, ts)) = r.get_lock() {
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
} else {
let err_str = "key is locked but primary info not found".to_owned();
error!("{}", err_str);
res_type.set_field_type(ResultType_Type::Other);
res_type.set_msg(err_str);
}
} else {
let err_str = format!("storage error: {:?}", e);
error!("{}", err_str);
res_type.set_field_type(ResultType_Type::Retryable);
res_type.set_msg(err_str);
}
}
}
cmd_get_resp.set_res_type(res_type);
resp.set_field_type(MessageType::CmdGet);
resp.set_cmd_get_resp(cmd_get_resp);
resp
}
fn cmd_scan_done(kvs: StorageResult<Vec<StorageResult<KvPair>>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_scan_resp: CmdScanResponse = CmdScanResponse::new();
cmd_scan_resp.set_ok(kvs.is_ok());
match kvs {
Ok(kvs) => {
// convert storage::KvPair to kvrpcpb::Item
let mut new_kvs: Vec<Item> = Vec::new();
for result in kvs {
let mut new_kv: Item = Item::new();
let mut res_type: ResultType = ResultType::new();
match result {
Ok((ref key, ref value)) => {
res_type.set_field_type(ResultType_Type::Ok);
new_kv.set_key(key.clone());
new_kv.set_value(value.clone());
}
Err(..) => {
if result.is_locked() {
if let Some((key, primary, ts)) = result.get_lock() {
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
new_kv.set_key(key);
}
} else {
res_type.set_field_type(ResultType_Type::Retryable);
}
}
}
new_kv.set_res_type(res_type);
new_kvs.push(new_kv);
}
cmd_scan_resp.set_results(RepeatedField::from_vec(new_kvs));
}
Err(e) => {
error!("storage error: {:?}", e);
}
}
resp.set_field_type(MessageType::CmdScan);
resp.set_cmd_scan_resp(cmd_scan_resp);
resp
}
fn cmd_prewrite_done(results: StorageResult<Vec<StorageResult<()>>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_prewrite_resp: CmdPrewriteResponse = CmdPrewriteResponse::new();
cmd_prewrite_resp.set_ok(results.is_ok());
let mut items: Vec<Item> = Vec::new();
match results {
Ok(results) => {
for result in results {
let mut item = Item::new();
let mut res_type: ResultType = ResultType::new();
if result.is_ok() {
res_type.set_field_type(ResultType_Type::Ok);
} else if let Some((key, primary, ts)) = result.get_lock() {
// Actually items only contain locked item, so `ok` is always false.
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
item.set_key(key);
} else {
res_type.set_field_type(ResultType_Type::Retryable);
}
item.set_res_type(res_type);
items.push(item);
}
}
Err(e) => {
error!("storage error: {:?}", e);
}
}
cmd_prewrite_resp.set_results(RepeatedField::from_vec(items));
resp.set_field_type(MessageType::CmdPrewrite);
resp.set_cmd_prewrite_resp(cmd_prewrite_resp);
resp
}
fn cmd_commit_done(r: StorageResult<()>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_commit_resp: CmdCommitResponse = CmdCommitResponse::new();
cmd_commit_resp.set_ok(r.is_ok());
resp.set_field_type(MessageType::CmdCommit);
resp.set_cmd_commit_resp(cmd_commit_resp);
resp
}
fn cmd_cleanup_done(r: StorageResult<()>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_cleanup_resp: CmdCleanupResponse = CmdCleanupResponse::new();
let mut res_type: ResultType = ResultType::new();
if r.is_ok() {
res_type.set_field_type(ResultType_Type::Ok);
} else if r.is_committed() {
res_type.set_field_type(ResultType_Type::Committed);
if let Some(commit_ts) = r.get_commit() {
cmd_cleanup_resp.set_commit_version(commit_ts);
} else {
warn!("commit_ts not found when is_committed.");
}
} else if r.is_rolledback() {
res_type.set_field_type(ResultType_Type::Rolledback);
} else {
warn!("Cleanup other error {:?}", r.err());
res_type.set_field_type(ResultType_Type::Retryable);
}
cmd_cleanup_resp.set_res_type(res_type);
resp.set_field_type(MessageType::CmdCleanup);
resp.set_cmd_cleanup_resp(cmd_cleanup_resp);
resp
}
fn cmd_commit_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_commit_get_resp: CmdCommitThenGetResponse = CmdCommitThenGetResponse::new();
cmd_commit_get_resp.set_ok(r.is_ok());
if let Ok(Some(val)) = r {
cmd_commit_get_resp.set_value(val);
}
resp.set_field_type(MessageType::CmdCommitThenGet);
resp.set_cmd_commit_get_resp(cmd_commit_get_resp);
resp
}
fn cmd_rollback_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_rollback_get_resp: CmdRollbackThenGetResponse =
CmdRollbackThenGetResponse::new();
cmd_rollback_get_resp.set_ok(r.is_ok());
if let Err(ref e) = r {
error!("rb & get error: {}", e);
}
if let Ok(Some(val)) = r {
cmd_rollback_get_resp.set_value(val);
}
resp.set_field_type(MessageType::CmdRollbackThenGet);
resp.set_cmd_rb_get_resp(cmd_rollback_get_resp);
resp
}
fn make_cb<T: 'static>(f: fn(StorageResult<T>) -> Response,
sender: Sender<QueueMessage>,
token: Token,
msg_id: u64)
-> Callback<T> {
Box::new(move |r: StorageResult<T>| {
let resp: Response = f(r);
let queue_msg: QueueMessage = QueueMessage::Response(token, msg_id, resp);
if let Err(e) = sender.send(queue_msg) {
error!("{:?}", e);
}
})
}
fn add_new_conn(&mut self,
event_loop: &mut EventLoop<Server>,
sock: TcpStream)
-> Result<(Token)> {
let new_token = Token(self.token_counter);
let _ = sock.set_nodelay(true).map_err(|e| error!("set nodelay failed {:?}", e));
self.conns.insert(new_token, Conn::new(sock, new_token));
self.token_counter += 1;
event_loop.register(&self.conns[&new_token].sock,
new_token,
EventSet::readable() | EventSet::hup(),
PollOpt::edge())
.unwrap();
Ok(new_token)
}
fn remove_conn(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let conn = self.conns.remove(&token);
match conn {
Some(conn) => {
let _ = event_loop.deregister(&conn.sock);
}
None => {
warn!("missing connection for token {}", token.as_usize());
}
}
}
fn handle_server_readable(&mut self, event_loop: &mut EventLoop<Server>) {
loop {
let sock = match self.listener.accept() {
// Some(sock, addr)
Ok(Some((sock, _))) => sock,
Ok(None) => {
debug!("no connection, accept later.");
return;
}
Err(e) => {
error!("accept error: {}", e);
return;
}
};
let _ = self.add_new_conn(event_loop, sock);
}
}
fn handle_conn_readable(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
if let Err(e) = conn.read(event_loop) {
error!("read failed with {:?}", e);
}
}
fn handle_writable(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
if let Err(e) = conn.write(event_loop) {
error!("write failed with {:?}", e);
}
}
fn handle_request(&mut self,
event_loop: &mut EventLoop<Server>,
token: Token,
msg_id: u64,
req: Request) {
debug!("notify Request token[{}] msg_id[{}] type[{:?}]",
token.0,
msg_id,
req.get_field_type());
if let Err(e) = match req.get_field_type() {
MessageType::CmdGet => self.handle_get(req, msg_id, token, event_loop),
MessageType::CmdScan => self.handle_scan(req, msg_id, token, event_loop),
MessageType::CmdPrewrite => self.handle_prewrite(req, msg_id, token, event_loop),
MessageType::CmdCommit => self.handle_commit(req, msg_id, token, event_loop),
MessageType::CmdCleanup => self.handle_cleanup(req, msg_id, token, event_loop),
MessageType::CmdCommitThenGet => {
self.handle_commit_then_get(req, msg_id, token, event_loop)
}
MessageType::CmdRollbackThenGet => {
self.handle_rollback_then_get(req, msg_id, token, event_loop)
}
} {
error!("Some error occur err[{:?}]", e);
}
}
fn handle_response(&mut self,
event_loop: &mut EventLoop<Server>,
token: Token,
msg_id: u64,
resp: Response) {
debug!("notify Response token[{}] msg_id[{}] type[{:?}]",
token.0,
msg_id,
resp.get_field_type());
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
let _ = conn.append_write_buf(event_loop, msg_id, resp);
}
}
#[allow(dead_code)]
pub enum QueueMessage {
// Request(token, msg_id, kvrpc_request)
Request(Token, u64, Request),
// Request(token, msg_id, kvrpc_response)
Response(Token, u64, Response),
Quit,
}
impl mio::Handler for Server {
type Timeout = ();
type Message = QueueMessage;
fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) {
if events.is_hup() || events.is_error() {
self.remove_conn(event_loop, token);
return;
}
if events.is_readable() {
match token {
SERVER_TOKEN => {
self.handle_server_readable(event_loop);
}
token => {
self.handle_conn_readable(event_loop, token);
}
}
}
if events.is_writable() {
self.handle_writable(event_loop, token);
}
}
fn notify(&mut self, event_loop: &mut EventLoop<Server>, msg: QueueMessage) {
match msg {
QueueMessage::Request(token, msg_id, req) => {
self.handle_request(event_loop, token, msg_id, req);
}
QueueMessage::Response(token, msg_id, resp) => {
self.handle_response(event_loop, token, msg_id, resp);
}
QueueMessage::Quit => event_loop.shutdown(),
}
}
}
#[cfg(test)]
mod tests {
use std::thread;
use mio::EventLoop;
use kvproto::kvrpcpb::*;
use kvproto::errorpb::NotLeaderError;
use storage::{self, Value, Storage, Dsn, txn, mvcc, engine};
use storage::Error::Other;
use storage::KvPair as StorageKV;
use storage::Result as StorageResult;
use super::*;
#[test]
fn test_quit() {
use std::collections::HashMap;
use mio::tcp::TcpListener;
let mut event_loop = EventLoop::new().unwrap();
let sender = event_loop.channel();
let h = thread::spawn(move || {
let l: TcpListener = TcpListener::bind(&"127.0.0.1:64321".parse().unwrap()).unwrap();
let store: Storage = Storage::new(Dsn::Memory).unwrap();
let mut srv: Server = Server::new(l, HashMap::new(), store);
event_loop.run(&mut srv).unwrap();
});
// Without this thread will be hang.
let _ = sender.send(QueueMessage::Quit);
h.join().unwrap();
}
#[test]
fn test_get_done_none() {
let actual_resp: Response = Server::cmd_get_done(Ok(None));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
exp_cmd_resp.set_res_type(make_res_type(ResultType_Type::Ok));
exp_cmd_resp.set_value(Vec::new());
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_get_done_some() {
let storage_val: Vec<_> = vec![0u8; 8];
let actual_resp: Response = Server::cmd_get_done(Ok(Some(storage_val)));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
exp_cmd_resp.set_res_type(make_res_type(ResultType_Type::Ok));
exp_cmd_resp.set_value(vec![0u8; 8]);
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
// #[should_panic]
fn test_get_done_error() {
let actual_resp: Response = Server::cmd_get_done(Err(Other(Box::new("error"))));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
let mut res_type = make_res_type(ResultType_Type::Retryable);
res_type.set_msg("storage error: Other(Any)".to_owned());
exp_cmd_resp.set_res_type(res_type);
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_scan_done_empty() {
let actual_resp: Response = Server::cmd_scan_done(Ok(Vec::new()));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdScanResponse = CmdScanResponse::new();
exp_cmd_resp.set_ok(true);
exp_resp.set_field_type(MessageType::CmdScan);
exp_resp.set_cmd_scan_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_scan_done_some() {
let k0 = vec![0u8, 0u8];
let v0: Value = vec![255u8, 255u8];
let k1 = vec![0u8, 1u8];
let v1: Value = vec![255u8, 254u8];
let kvs: Vec<StorageResult<StorageKV>> = vec![Ok((k0.clone(), v0.clone())),
Ok((k1.clone(), v1.clone()))];
let actual_resp: Response = Server::cmd_scan_done(Ok(kvs));
assert_eq!(MessageType::CmdScan, actual_resp.get_field_type());
let actual_cmd_resp: &CmdScanResponse = actual_resp.get_cmd_scan_resp();
assert_eq!(true, actual_cmd_resp.get_ok());
let actual_kvs = actual_cmd_resp.get_results();
assert_eq!(2, actual_kvs.len());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[0].get_res_type());
assert_eq!(k0, actual_kvs[0].get_key());
assert_eq!(v0, actual_kvs[0].get_value());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[1].get_res_type());
assert_eq!(k1, actual_kvs[1].get_key());
assert_eq!(v1, actual_kvs[1].get_value());
}
#[test]
fn test_scan_done_lock() {
use kvproto::kvrpcpb::LockInfo;
let k0 = vec![0u8, 0u8];
let v0: Value = vec![255u8, 255u8];
let k1 = vec![0u8, 1u8];
let k1_primary = k0.clone();
let k1_ts: u64 = 10000;
let kvs: Vec<StorageResult<StorageKV>> = vec![Ok((k0.clone(), v0.clone())),
make_lock_error(k1.clone(),
k1_primary.clone(),
k1_ts)];
let actual_resp: Response = Server::cmd_scan_done(Ok(kvs));
assert_eq!(MessageType::CmdScan, actual_resp.get_field_type());
let actual_cmd_resp: &CmdScanResponse = actual_resp.get_cmd_scan_resp();
assert_eq!(true, actual_cmd_resp.get_ok());
let actual_kvs = actual_cmd_resp.get_results();
assert_eq!(2, actual_kvs.len());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[0].get_res_type());
assert_eq!(k0, actual_kvs[0].get_key());
assert_eq!(v0, actual_kvs[0].get_value());
let mut exp_res_type1 = make_res_type(ResultType_Type::Locked);
let mut lock_info1 = LockInfo::new();
lock_info1.set_primary_lock(k1_primary.clone());
lock_info1.set_lock_version(k1_ts);
exp_res_type1.set_lock_info(lock_info1);
assert_eq!(exp_res_type1, *actual_kvs[1].get_res_type());
assert_eq!(k1, actual_kvs[1].get_key());
assert_eq!(k1_primary.clone(),
actual_kvs[1].get_res_type().get_lock_info().get_primary_lock());
assert_eq!(k1_ts,
actual_kvs[1].get_res_type().get_lock_info().get_lock_version());
}
#[test]
fn test_prewrite_done_ok() {
let actual_resp: Response = Server::cmd_prewrite_done(Ok(Vec::new()));
assert_eq!(MessageType::CmdPrewrite, actual_resp.get_field_type());
assert_eq!(true, actual_resp.get_cmd_prewrite_resp().get_ok());
}
#[test]
fn test_prewrite_done_err() {
let err = Other(Box::new("prewrite error"));
let actual_resp: Response = Server::cmd_prewrite_done(Err(err));
assert_eq!(MessageType::CmdPrewrite, actual_resp.get_field_type());
assert_eq!(false, actual_resp.get_cmd_prewrite_resp().get_ok());
}
#[test]
fn test_commit_done_ok() {
let actual_resp: Response = Server::cmd_commit_done(Ok(()));
assert_eq!(MessageType::CmdCommit, actual_resp.get_field_type());
assert_eq!(true, actual_resp.get_cmd_commit_resp().get_ok());
}
#[test]
fn test_commit_done_err() {
let err = Other(Box::new("commit error"));
let actual_resp: Response = Server::cmd_commit_done(Err(err));
assert_eq!(MessageType::CmdCommit, actual_resp.get_field_type());
assert_eq!(false, actual_resp.get_cmd_commit_resp().get_ok());
}
#[test]
fn test_cleanup_done_ok() {
let actual_resp: Response = Server::cmd_cleanup_done(Ok(()));
assert_eq!(MessageType::CmdCleanup, actual_resp.get_field_type());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_resp.get_cmd_cleanup_resp().get_res_type());
}
#[test]
fn test_cleanup_done_err() {
let err = Other(Box::new("cleanup error"));
let actual_resp: Response = Server::cmd_cleanup_done(Err(err));
assert_eq!(MessageType::CmdCleanup, actual_resp.get_field_type());
assert_eq!(make_res_type(ResultType_Type::Retryable),
*actual_resp.get_cmd_cleanup_resp().get_res_type());
}
#[test]
fn test_not_leader() {
use kvproto::errorpb::NotLeaderError;
let mut leader_info = NotLeaderError::new();
leader_info.set_region_id(1);
let storage_res: StorageResult<Option<Value>> =
make_not_leader_error(leader_info.to_owned());
let actual_resp: Response = Server::cmd_get_done(storage_res);
assert_eq!(MessageType::CmdGet, actual_resp.get_field_type());
let mut exp_res_type = make_res_type(ResultType_Type::NotLeader);
exp_res_type.set_leader_info(leader_info.to_owned());
assert_eq!(exp_res_type, *actual_resp.get_cmd_get_resp().get_res_type());
}
fn make_lock_error<T>(key: Vec<u8>, primary: Vec<u8>, ts: u64) -> StorageResult<T> {
Err(mvcc::Error::KeyIsLocked {
key: key,
primary: primary,
ts: ts,
})
.map_err(txn::Error::from)
.map_err(storage::Error::from)
}
fn make_not_leader_error<T>(leader_info: NotLeaderError) -> StorageResult<T> {
use kvproto::errorpb::Error;
let mut err = Error::new();
err.set_not_leader(leader_info);
Err(engine::Error::Request(err)).map_err(storage::Error::from)
}
fn make_res_type(tp: ResultType_Type) -> ResultType {
let mut res_type = ResultType::new();
res_type.set_field_type(tp);
res_type
}
}
server: Use Hex instead of Dec
use std::collections::HashMap;
use std::boxed::Box;
use std::io::{Read, Write};
use mio::{self, Token, EventLoop, EventSet, PollOpt, Sender};
use mio::tcp::{TcpListener, TcpStream};
use protobuf::RepeatedField;
use kvproto::kvrpcpb::{CmdGetResponse, CmdScanResponse, CmdPrewriteResponse, CmdCommitResponse,
CmdCleanupResponse, CmdRollbackThenGetResponse, CmdCommitThenGetResponse,
Request, Response, MessageType, Item, ResultType, ResultType_Type,
LockInfo, Operator};
use storage::{Storage, Key, Value, KvPair, KvContext, Mutation, MaybeLocked, MaybeComitted,
MaybeRolledback, Callback};
use storage::Result as StorageResult;
use storage::Error as StorageError;
use storage::EngineError;
use super::conn::Conn;
use super::{Result, ServerError};
// Token(1) instead of Token(0)
// See here: https://github.com/hjr3/mob/blob/multi-echo-blog-post/src/main.rs#L115
pub const SERVER_TOKEN: Token = Token(1);
const FIRST_CUSTOM_TOKEN: Token = Token(1024);
pub struct Server {
pub listener: TcpListener,
pub conns: HashMap<Token, Conn>,
pub token_counter: usize,
store: Storage,
}
impl Server {
pub fn new(listener: TcpListener, conns: HashMap<Token, Conn>, store: Storage) -> Server {
Server {
listener: listener,
conns: conns,
token_counter: FIRST_CUSTOM_TOKEN.as_usize(),
store: store,
}
}
pub fn handle_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_get_req() {
format_err!("Msg doesn't contain a CmdGetRequest");
}
let mut cmd_get_req = msg.take_cmd_get_req();
let mut key_address = cmd_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_get_done, sender, token, msg_id);
self.store
.async_get(ctx, Key::new(key), cmd_get_req.get_version(), cb)
.map_err(ServerError::Storage)
}
pub fn handle_scan(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_scan_req() {
format_err!("Msg doesn't contain a CmdScanRequest");
}
let mut cmd_scan_req = msg.take_cmd_scan_req();
let sender = event_loop.channel();
let mut start_key_addresss = cmd_scan_req.take_key_address();
let start_key = start_key_addresss.take_key();
let ctx = KvContext::new(start_key_addresss.get_region_id(),
start_key_addresss.take_peer());
debug!("start_key [{:?}]", start_key);
let cb = Server::make_cb::<Vec<StorageResult<KvPair>>>(Server::cmd_scan_done,
sender,
token,
msg_id);
self.store
.async_scan(ctx,
Key::new(start_key),
cmd_scan_req.get_limit() as usize,
cmd_scan_req.get_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_prewrite(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_prewrite_req() {
format_err!("Msg doesn't contain a CmdPrewriteRequest");
}
let mut cmd_prewrite_req = msg.take_cmd_prewrite_req();
let sender = event_loop.channel();
let mutations = cmd_prewrite_req.take_mutations()
.into_iter()
.map(|mut x| {
match x.get_op() {
Operator::OpPut => {
Mutation::Put((Key::new(x.take_key()),
x.take_value()))
}
Operator::OpDel => {
Mutation::Delete(Key::new(x.take_key()))
}
Operator::OpLock => {
Mutation::Lock(Key::new(x.take_key()))
}
}
})
.collect();
let ctx = {
let mut key_address = cmd_prewrite_req.take_key_address();
KvContext::new(key_address.get_region_id(), key_address.take_peer())
};
let cb = Server::make_cb::<Vec<StorageResult<()>>>(Server::cmd_prewrite_done,
sender,
token,
msg_id);
self.store
.async_prewrite(ctx,
mutations,
cmd_prewrite_req.get_primary_lock().to_vec(),
cmd_prewrite_req.get_start_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_commit(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_commit_req() {
format_err!("Msg doesn't contain a CmdCommitRequest");
}
let mut cmd_commit_req = msg.take_cmd_commit_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<()>(Server::cmd_commit_done, sender, token, msg_id);
let ctx = {
let mut first = cmd_commit_req.get_keys_address()[0].clone();
KvContext::new(first.get_region_id(), first.take_peer())
};
let keys = cmd_commit_req.take_keys_address()
.into_iter()
.map(|mut x| Key::new(x.take_key()))
.collect();
self.store
.async_commit(ctx,
keys,
cmd_commit_req.get_start_version(),
cmd_commit_req.get_commit_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_cleanup(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_cleanup_req() {
format_err!("Msg doesn't contain a CmdCleanupRequest");
}
let mut cmd_cleanup_req = msg.take_cmd_cleanup_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<()>(Server::cmd_cleanup_done, sender, token, msg_id);
let mut key_address = cmd_cleanup_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_cleanup(ctx, Key::new(key), cmd_cleanup_req.get_start_version(), cb)
.map_err(ServerError::Storage)
}
pub fn handle_commit_then_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_commit_get_req() {
format_err!("Msg doesn't contain a CmdCommitThenGetRequest");
}
let mut cmd_commit_get_req = msg.take_cmd_commit_get_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_commit_get_done,
sender,
token,
msg_id);
let mut key_address = cmd_commit_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_commit_then_get(ctx,
Key::new(key),
cmd_commit_get_req.get_lock_version(),
cmd_commit_get_req.get_commit_version(),
cmd_commit_get_req.get_get_version(),
cb)
.map_err(ServerError::Storage)
}
pub fn handle_rollback_then_get(&mut self,
mut msg: Request,
msg_id: u64,
token: Token,
event_loop: &mut EventLoop<Server>)
-> Result<()> {
if !msg.has_cmd_rb_get_req() {
format_err!("Msg doesn't contain a CmdRollbackThenGetRequest");
}
let mut cmd_rollback_get_req = msg.take_cmd_rb_get_req();
let sender = event_loop.channel();
let cb = Server::make_cb::<Option<Value>>(Server::cmd_rollback_get_done,
sender,
token,
msg_id);
let mut key_address = cmd_rollback_get_req.take_key_address();
let key = key_address.take_key();
let ctx = KvContext::new(key_address.get_region_id(), key_address.take_peer());
self.store
.async_rollback_then_get(ctx,
Key::new(key),
cmd_rollback_get_req.get_lock_version(),
cb)
.map_err(ServerError::Storage)
}
fn cmd_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_get_resp: CmdGetResponse = CmdGetResponse::new();
let mut res_type: ResultType = ResultType::new();
match r {
Ok(opt) => {
res_type.set_field_type(ResultType_Type::Ok);
match opt {
Some(val) => cmd_get_resp.set_value(val),
None => cmd_get_resp.set_value(Vec::new()),
}
}
Err(ref e) => {
if let StorageError::Engine(EngineError::Request(ref err)) = *e {
if err.has_not_leader() {
res_type.set_field_type(ResultType_Type::NotLeader);
res_type.set_leader_info(err.get_not_leader().to_owned());
} else {
error!("{:?}", err);
res_type.set_field_type(ResultType_Type::Other);
res_type.set_msg(format!("engine error: {:?}", err));
}
} else if r.is_locked() {
if let Some((_, primary, ts)) = r.get_lock() {
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
} else {
let err_str = "key is locked but primary info not found".to_owned();
error!("{}", err_str);
res_type.set_field_type(ResultType_Type::Other);
res_type.set_msg(err_str);
}
} else {
let err_str = format!("storage error: {:?}", e);
error!("{}", err_str);
res_type.set_field_type(ResultType_Type::Retryable);
res_type.set_msg(err_str);
}
}
}
cmd_get_resp.set_res_type(res_type);
resp.set_field_type(MessageType::CmdGet);
resp.set_cmd_get_resp(cmd_get_resp);
resp
}
fn cmd_scan_done(kvs: StorageResult<Vec<StorageResult<KvPair>>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_scan_resp: CmdScanResponse = CmdScanResponse::new();
cmd_scan_resp.set_ok(kvs.is_ok());
match kvs {
Ok(kvs) => {
// convert storage::KvPair to kvrpcpb::Item
let mut new_kvs: Vec<Item> = Vec::new();
for result in kvs {
let mut new_kv: Item = Item::new();
let mut res_type: ResultType = ResultType::new();
match result {
Ok((ref key, ref value)) => {
res_type.set_field_type(ResultType_Type::Ok);
new_kv.set_key(key.clone());
new_kv.set_value(value.clone());
}
Err(..) => {
if result.is_locked() {
if let Some((key, primary, ts)) = result.get_lock() {
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
new_kv.set_key(key);
}
} else {
res_type.set_field_type(ResultType_Type::Retryable);
}
}
}
new_kv.set_res_type(res_type);
new_kvs.push(new_kv);
}
cmd_scan_resp.set_results(RepeatedField::from_vec(new_kvs));
}
Err(e) => {
error!("storage error: {:?}", e);
}
}
resp.set_field_type(MessageType::CmdScan);
resp.set_cmd_scan_resp(cmd_scan_resp);
resp
}
fn cmd_prewrite_done(results: StorageResult<Vec<StorageResult<()>>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_prewrite_resp: CmdPrewriteResponse = CmdPrewriteResponse::new();
cmd_prewrite_resp.set_ok(results.is_ok());
let mut items: Vec<Item> = Vec::new();
match results {
Ok(results) => {
for result in results {
let mut item = Item::new();
let mut res_type: ResultType = ResultType::new();
if result.is_ok() {
res_type.set_field_type(ResultType_Type::Ok);
} else if let Some((key, primary, ts)) = result.get_lock() {
// Actually items only contain locked item, so `ok` is always false.
res_type.set_field_type(ResultType_Type::Locked);
let mut lock_info = LockInfo::new();
lock_info.set_primary_lock(primary);
lock_info.set_lock_version(ts);
res_type.set_lock_info(lock_info);
item.set_key(key);
} else {
res_type.set_field_type(ResultType_Type::Retryable);
}
item.set_res_type(res_type);
items.push(item);
}
}
Err(e) => {
error!("storage error: {:?}", e);
}
}
cmd_prewrite_resp.set_results(RepeatedField::from_vec(items));
resp.set_field_type(MessageType::CmdPrewrite);
resp.set_cmd_prewrite_resp(cmd_prewrite_resp);
resp
}
fn cmd_commit_done(r: StorageResult<()>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_commit_resp: CmdCommitResponse = CmdCommitResponse::new();
cmd_commit_resp.set_ok(r.is_ok());
resp.set_field_type(MessageType::CmdCommit);
resp.set_cmd_commit_resp(cmd_commit_resp);
resp
}
fn cmd_cleanup_done(r: StorageResult<()>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_cleanup_resp: CmdCleanupResponse = CmdCleanupResponse::new();
let mut res_type: ResultType = ResultType::new();
if r.is_ok() {
res_type.set_field_type(ResultType_Type::Ok);
} else if r.is_committed() {
res_type.set_field_type(ResultType_Type::Committed);
if let Some(commit_ts) = r.get_commit() {
cmd_cleanup_resp.set_commit_version(commit_ts);
} else {
warn!("commit_ts not found when is_committed.");
}
} else if r.is_rolledback() {
res_type.set_field_type(ResultType_Type::Rolledback);
} else {
warn!("Cleanup other error {:?}", r.err());
res_type.set_field_type(ResultType_Type::Retryable);
}
cmd_cleanup_resp.set_res_type(res_type);
resp.set_field_type(MessageType::CmdCleanup);
resp.set_cmd_cleanup_resp(cmd_cleanup_resp);
resp
}
fn cmd_commit_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_commit_get_resp: CmdCommitThenGetResponse = CmdCommitThenGetResponse::new();
cmd_commit_get_resp.set_ok(r.is_ok());
if let Ok(Some(val)) = r {
cmd_commit_get_resp.set_value(val);
}
resp.set_field_type(MessageType::CmdCommitThenGet);
resp.set_cmd_commit_get_resp(cmd_commit_get_resp);
resp
}
fn cmd_rollback_get_done(r: StorageResult<Option<Value>>) -> Response {
let mut resp: Response = Response::new();
let mut cmd_rollback_get_resp: CmdRollbackThenGetResponse =
CmdRollbackThenGetResponse::new();
cmd_rollback_get_resp.set_ok(r.is_ok());
if let Err(ref e) = r {
error!("rb & get error: {}", e);
}
if let Ok(Some(val)) = r {
cmd_rollback_get_resp.set_value(val);
}
resp.set_field_type(MessageType::CmdRollbackThenGet);
resp.set_cmd_rb_get_resp(cmd_rollback_get_resp);
resp
}
fn make_cb<T: 'static>(f: fn(StorageResult<T>) -> Response,
sender: Sender<QueueMessage>,
token: Token,
msg_id: u64)
-> Callback<T> {
Box::new(move |r: StorageResult<T>| {
let resp: Response = f(r);
let queue_msg: QueueMessage = QueueMessage::Response(token, msg_id, resp);
if let Err(e) = sender.send(queue_msg) {
error!("{:?}", e);
}
})
}
fn add_new_conn(&mut self,
event_loop: &mut EventLoop<Server>,
sock: TcpStream)
-> Result<(Token)> {
let new_token = Token(self.token_counter);
let _ = sock.set_nodelay(true).map_err(|e| error!("set nodelay failed {:?}", e));
self.conns.insert(new_token, Conn::new(sock, new_token));
self.token_counter += 1;
event_loop.register(&self.conns[&new_token].sock,
new_token,
EventSet::readable() | EventSet::hup(),
PollOpt::edge())
.unwrap();
Ok(new_token)
}
fn remove_conn(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let conn = self.conns.remove(&token);
match conn {
Some(conn) => {
let _ = event_loop.deregister(&conn.sock);
}
None => {
warn!("missing connection for token {}", token.as_usize());
}
}
}
fn handle_server_readable(&mut self, event_loop: &mut EventLoop<Server>) {
loop {
let sock = match self.listener.accept() {
// Some(sock, addr)
Ok(Some((sock, _))) => sock,
Ok(None) => {
debug!("no connection, accept later.");
return;
}
Err(e) => {
error!("accept error: {}", e);
return;
}
};
let _ = self.add_new_conn(event_loop, sock);
}
}
fn handle_conn_readable(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
if let Err(e) = conn.read(event_loop) {
error!("read failed with {:?}", e);
}
}
fn handle_writable(&mut self, event_loop: &mut EventLoop<Server>, token: Token) {
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
if let Err(e) = conn.write(event_loop) {
error!("write failed with {:?}", e);
}
}
fn handle_request(&mut self,
event_loop: &mut EventLoop<Server>,
token: Token,
msg_id: u64,
req: Request) {
debug!("notify Request token[{}] msg_id[{}] type[{:?}]",
token.0,
msg_id,
req.get_field_type());
if let Err(e) = match req.get_field_type() {
MessageType::CmdGet => self.handle_get(req, msg_id, token, event_loop),
MessageType::CmdScan => self.handle_scan(req, msg_id, token, event_loop),
MessageType::CmdPrewrite => self.handle_prewrite(req, msg_id, token, event_loop),
MessageType::CmdCommit => self.handle_commit(req, msg_id, token, event_loop),
MessageType::CmdCleanup => self.handle_cleanup(req, msg_id, token, event_loop),
MessageType::CmdCommitThenGet => {
self.handle_commit_then_get(req, msg_id, token, event_loop)
}
MessageType::CmdRollbackThenGet => {
self.handle_rollback_then_get(req, msg_id, token, event_loop)
}
} {
error!("Some error occur err[{:?}]", e);
}
}
fn handle_response(&mut self,
event_loop: &mut EventLoop<Server>,
token: Token,
msg_id: u64,
resp: Response) {
debug!("notify Response token[{}] msg_id[{}] type[{:?}]",
token.0,
msg_id,
resp.get_field_type());
let mut conn: &mut Conn = match self.conns.get_mut(&token) {
Some(c) => c,
None => {
error!("Get connection failed token[{}]", token.0);
return;
}
};
let _ = conn.append_write_buf(event_loop, msg_id, resp);
}
}
#[allow(dead_code)]
pub enum QueueMessage {
// Request(token, msg_id, kvrpc_request)
Request(Token, u64, Request),
// Request(token, msg_id, kvrpc_response)
Response(Token, u64, Response),
Quit,
}
impl mio::Handler for Server {
type Timeout = ();
type Message = QueueMessage;
fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) {
if events.is_hup() || events.is_error() {
self.remove_conn(event_loop, token);
return;
}
if events.is_readable() {
match token {
SERVER_TOKEN => {
self.handle_server_readable(event_loop);
}
token => {
self.handle_conn_readable(event_loop, token);
}
}
}
if events.is_writable() {
self.handle_writable(event_loop, token);
}
}
fn notify(&mut self, event_loop: &mut EventLoop<Server>, msg: QueueMessage) {
match msg {
QueueMessage::Request(token, msg_id, req) => {
self.handle_request(event_loop, token, msg_id, req);
}
QueueMessage::Response(token, msg_id, resp) => {
self.handle_response(event_loop, token, msg_id, resp);
}
QueueMessage::Quit => event_loop.shutdown(),
}
}
}
#[cfg(test)]
mod tests {
use std::thread;
use mio::EventLoop;
use kvproto::kvrpcpb::*;
use kvproto::errorpb::NotLeaderError;
use storage::{self, Value, Storage, Dsn, txn, mvcc, engine};
use storage::Error::Other;
use storage::KvPair as StorageKV;
use storage::Result as StorageResult;
use super::*;
#[test]
fn test_quit() {
use std::collections::HashMap;
use mio::tcp::TcpListener;
let mut event_loop = EventLoop::new().unwrap();
let sender = event_loop.channel();
let h = thread::spawn(move || {
let l: TcpListener = TcpListener::bind(&"127.0.0.1:64321".parse().unwrap()).unwrap();
let store: Storage = Storage::new(Dsn::Memory).unwrap();
let mut srv: Server = Server::new(l, HashMap::new(), store);
event_loop.run(&mut srv).unwrap();
});
// Without this thread will be hang.
let _ = sender.send(QueueMessage::Quit);
h.join().unwrap();
}
#[test]
fn test_get_done_none() {
let actual_resp: Response = Server::cmd_get_done(Ok(None));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
exp_cmd_resp.set_res_type(make_res_type(ResultType_Type::Ok));
exp_cmd_resp.set_value(Vec::new());
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_get_done_some() {
let storage_val: Vec<_> = vec![0x0; 0x8];
let actual_resp: Response = Server::cmd_get_done(Ok(Some(storage_val)));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
exp_cmd_resp.set_res_type(make_res_type(ResultType_Type::Ok));
exp_cmd_resp.set_value(vec![0x0; 0x8]);
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
// #[should_panic]
fn test_get_done_error() {
let actual_resp: Response = Server::cmd_get_done(Err(Other(Box::new("error"))));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdGetResponse = CmdGetResponse::new();
let mut res_type = make_res_type(ResultType_Type::Retryable);
res_type.set_msg("storage error: Other(Any)".to_owned());
exp_cmd_resp.set_res_type(res_type);
exp_resp.set_field_type(MessageType::CmdGet);
exp_resp.set_cmd_get_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_scan_done_empty() {
let actual_resp: Response = Server::cmd_scan_done(Ok(Vec::new()));
let mut exp_resp: Response = Response::new();
let mut exp_cmd_resp: CmdScanResponse = CmdScanResponse::new();
exp_cmd_resp.set_ok(true);
exp_resp.set_field_type(MessageType::CmdScan);
exp_resp.set_cmd_scan_resp(exp_cmd_resp);
assert_eq!(exp_resp, actual_resp);
}
#[test]
fn test_scan_done_some() {
let k0 = vec![0x0, 0x0];
let v0: Value = vec![0xff, 0xff];
let k1 = vec![0x0, 0x1];
let v1: Value = vec![0xff, 0xfe];
let kvs: Vec<StorageResult<StorageKV>> = vec![Ok((k0.clone(), v0.clone())),
Ok((k1.clone(), v1.clone()))];
let actual_resp: Response = Server::cmd_scan_done(Ok(kvs));
assert_eq!(MessageType::CmdScan, actual_resp.get_field_type());
let actual_cmd_resp: &CmdScanResponse = actual_resp.get_cmd_scan_resp();
assert_eq!(true, actual_cmd_resp.get_ok());
let actual_kvs = actual_cmd_resp.get_results();
assert_eq!(2, actual_kvs.len());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[0].get_res_type());
assert_eq!(k0, actual_kvs[0].get_key());
assert_eq!(v0, actual_kvs[0].get_value());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[1].get_res_type());
assert_eq!(k1, actual_kvs[1].get_key());
assert_eq!(v1, actual_kvs[1].get_value());
}
#[test]
fn test_scan_done_lock() {
use kvproto::kvrpcpb::LockInfo;
let k0 = vec![0x0, 0x0];
let v0: Value = vec![0xff, 0xff];
let k1 = vec![0x0, 0x1];
let k1_primary = k0.clone();
let k1_ts: u64 = 10000;
let kvs: Vec<StorageResult<StorageKV>> = vec![Ok((k0.clone(), v0.clone())),
make_lock_error(k1.clone(),
k1_primary.clone(),
k1_ts)];
let actual_resp: Response = Server::cmd_scan_done(Ok(kvs));
assert_eq!(MessageType::CmdScan, actual_resp.get_field_type());
let actual_cmd_resp: &CmdScanResponse = actual_resp.get_cmd_scan_resp();
assert_eq!(true, actual_cmd_resp.get_ok());
let actual_kvs = actual_cmd_resp.get_results();
assert_eq!(2, actual_kvs.len());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_kvs[0].get_res_type());
assert_eq!(k0, actual_kvs[0].get_key());
assert_eq!(v0, actual_kvs[0].get_value());
let mut exp_res_type1 = make_res_type(ResultType_Type::Locked);
let mut lock_info1 = LockInfo::new();
lock_info1.set_primary_lock(k1_primary.clone());
lock_info1.set_lock_version(k1_ts);
exp_res_type1.set_lock_info(lock_info1);
assert_eq!(exp_res_type1, *actual_kvs[1].get_res_type());
assert_eq!(k1, actual_kvs[1].get_key());
assert_eq!(k1_primary.clone(),
actual_kvs[1].get_res_type().get_lock_info().get_primary_lock());
assert_eq!(k1_ts,
actual_kvs[1].get_res_type().get_lock_info().get_lock_version());
}
#[test]
fn test_prewrite_done_ok() {
let actual_resp: Response = Server::cmd_prewrite_done(Ok(Vec::new()));
assert_eq!(MessageType::CmdPrewrite, actual_resp.get_field_type());
assert_eq!(true, actual_resp.get_cmd_prewrite_resp().get_ok());
}
#[test]
fn test_prewrite_done_err() {
let err = Other(Box::new("prewrite error"));
let actual_resp: Response = Server::cmd_prewrite_done(Err(err));
assert_eq!(MessageType::CmdPrewrite, actual_resp.get_field_type());
assert_eq!(false, actual_resp.get_cmd_prewrite_resp().get_ok());
}
#[test]
fn test_commit_done_ok() {
let actual_resp: Response = Server::cmd_commit_done(Ok(()));
assert_eq!(MessageType::CmdCommit, actual_resp.get_field_type());
assert_eq!(true, actual_resp.get_cmd_commit_resp().get_ok());
}
#[test]
fn test_commit_done_err() {
let err = Other(Box::new("commit error"));
let actual_resp: Response = Server::cmd_commit_done(Err(err));
assert_eq!(MessageType::CmdCommit, actual_resp.get_field_type());
assert_eq!(false, actual_resp.get_cmd_commit_resp().get_ok());
}
#[test]
fn test_cleanup_done_ok() {
let actual_resp: Response = Server::cmd_cleanup_done(Ok(()));
assert_eq!(MessageType::CmdCleanup, actual_resp.get_field_type());
assert_eq!(make_res_type(ResultType_Type::Ok),
*actual_resp.get_cmd_cleanup_resp().get_res_type());
}
#[test]
fn test_cleanup_done_err() {
let err = Other(Box::new("cleanup error"));
let actual_resp: Response = Server::cmd_cleanup_done(Err(err));
assert_eq!(MessageType::CmdCleanup, actual_resp.get_field_type());
assert_eq!(make_res_type(ResultType_Type::Retryable),
*actual_resp.get_cmd_cleanup_resp().get_res_type());
}
#[test]
fn test_not_leader() {
use kvproto::errorpb::NotLeaderError;
let mut leader_info = NotLeaderError::new();
leader_info.set_region_id(1);
let storage_res: StorageResult<Option<Value>> =
make_not_leader_error(leader_info.to_owned());
let actual_resp: Response = Server::cmd_get_done(storage_res);
assert_eq!(MessageType::CmdGet, actual_resp.get_field_type());
let mut exp_res_type = make_res_type(ResultType_Type::NotLeader);
exp_res_type.set_leader_info(leader_info.to_owned());
assert_eq!(exp_res_type, *actual_resp.get_cmd_get_resp().get_res_type());
}
fn make_lock_error<T>(key: Vec<u8>, primary: Vec<u8>, ts: u64) -> StorageResult<T> {
Err(mvcc::Error::KeyIsLocked {
key: key,
primary: primary,
ts: ts,
})
.map_err(txn::Error::from)
.map_err(storage::Error::from)
}
fn make_not_leader_error<T>(leader_info: NotLeaderError) -> StorageResult<T> {
use kvproto::errorpb::Error;
let mut err = Error::new();
err.set_not_leader(leader_info);
Err(engine::Error::Request(err)).map_err(storage::Error::from)
}
fn make_res_type(tp: ResultType_Type) -> ResultType {
let mut res_type = ResultType::new();
res_type.set_field_type(tp);
res_type
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.